code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
using System;
using System.IO;
using System.Net;
namespace Dongle.System.IO.Ftp
{
public class FtpFileInfo
{
private readonly string _fileName;
private readonly NetworkCredential _networkCredential;
public FtpFileInfo(string fileName, NetworkCredential networkCredential)
{
_fileName = fileName;
_networkCredential = networkCredential;
}
public string FullName
{
get
{
return _fileName;
}
}
public string Name
{
get
{
return _fileName.LastIndexOf("/") > 0 ? _fileName.Substring(_fileName.LastIndexOf("/") + 1) : _fileName;
}
}
public FileInfo CopyTo(string destFilename)
{
var request = (FtpWebRequest)WebRequest.Create(new Uri(_fileName));
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = _networkCredential;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (var response = (FtpWebResponse)request.GetResponse())
{
if (response != null)
{
using (var reader = response.GetResponseStream())
{
if (reader != null)
{
using (var memoryStream = new MemoryStream())
{
var buffer = new byte[1024];
while (true)
{
var bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
memoryStream.Write(buffer, 0, bytesRead);
}
var downloadedData = memoryStream.ToArray();
using (var newFile = new FileStream(destFilename, FileMode.Create))
{
newFile.Write(downloadedData, 0, downloadedData.Length);
}
}
}
}
}
}
return new FileInfo(destFilename);
}
public FileInfo MoveTo(string destFilename)
{
var fileInfo = CopyTo(destFilename);
Delete();
return fileInfo;
}
public void Delete()
{
var request = (FtpWebRequest)WebRequest.Create(new Uri(_fileName));
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = _networkCredential;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
var response = (FtpWebResponse)request.GetResponse();
if (response != null)
{
response.Close();
}
}
}
} | webbers/dongle.net | src/Dongle/System/IO/Ftp/FtpFileInfo.cs | C# | mit | 3,281 |
// Chapter 19, exercise 03: template class Pair to hold pair of values of any
// type; use to implement symbol table like the one used in calculator (§7.8)
#include "../lib_files/std_lib_facilities.h"
// -----------------------------------------------------------------------------
template<class T, class U> struct Pair {
Pair(T vt, U vu) : val1(vt), val2(vu) { }
T val1;
U val2;
};
// -----------------------------------------------------------------------------
class Symbol_table {
vector< Pair<string,double> > var_table;
public:
double get(string s); // return the value of the Variable named s
void set(string s, double d); // set the Variable named s to d
bool is_declared(string var); // is var already in var_table?
double declare(string var, double val); // add (var,val) to var_table
void print(); // print table
};
// -----------------------------------------------------------------------------
double Symbol_table::get(string s)
{
for (int i = 0; i<var_table.size(); ++i)
if (var_table[i].val1==s) return var_table[i].val2;
error("Variable not found: ",s);
}
// -----------------------------------------------------------------------------
void Symbol_table::set(string s, double d)
{
for (int i = 0; i<var_table.size(); ++i)
if (var_table[i].val1==s) {
var_table[i].val2 = d;
return;
}
error("Variable not found: ",s);
}
// -----------------------------------------------------------------------------
bool Symbol_table::is_declared(string s)
{
for (int i = 0; i<var_table.size(); ++i)
if (var_table[i].val1==s) return true;
return false;
}
// -----------------------------------------------------------------------------
double Symbol_table::declare(string s, double d)
{
if (is_declared(s)) error("Variable exists already: ",s);
var_table.push_back(Pair<string,double>(s,d));
return d;
}
// -----------------------------------------------------------------------------
void Symbol_table::print()
{
for (int i = 0; i<var_table.size(); ++i)
cout << var_table[i].val1 << ": " << var_table[i].val2 << "\n";
}
// -----------------------------------------------------------------------------
int main()
try {
Symbol_table st;
st.declare("Pi",3.14);
st.declare("e",2.72);
st.print();
cout << "Pi is " << st.get("Pi") << "\n";
if (st.is_declared("Pi"))
cout << "Pi is declared\n";
else
cout << "Pi is not declared\n";
if (st.is_declared("nd"))
cout << "nd is declared\n";
else
cout << "nd is not declared\n";
st.set("Pi",4.14);
cout << "Pi is now " << st.get("Pi") << "\n";
// provoke errors
// cout << st.get("nd") << "\n";
// st.set("nd",99);
// st.declare("Pi",99);
}
catch (exception& e) {
cerr << "Exception: " << e.what() << "\n";
}
catch (...) {
cerr << "Exception\n";
}
| bewuethr/stroustrup_ppp | chapter19/chapter19_ex03.cpp | C++ | mit | 3,000 |
const Helpers = require('../../../../common/databaseHelpers.js');
const Assert = require('chai').assert;
module.exports = function() {
it('return default query part with no parameter', function() {
Assert.equal(Helpers.getOrderByQuery(), ' ORDER BY id ASC');
});
it('return correct query part with single ascending parameter', function() {
const parameter = 'username';
Assert.equal(Helpers.getOrderByQuery(parameter), ' ORDER BY username ASC');
});
it('return correct query part with single descending parameter', function() {
const parameter = '-email';
Assert.equal(Helpers.getOrderByQuery(parameter), ' ORDER BY email DESC');
});
it('return correct query part with multiple ascending parameters', function() {
const parameter = 'id,email,user,password';
Assert.equal(Helpers.getOrderByQuery(parameter), ' ORDER BY id ASC, email ASC, user ASC, password ASC');
});
it('return correct query part with multiple descending parameters', function() {
const parameter = '-order,-user,-login';
Assert.equal(Helpers.getOrderByQuery(parameter), ' ORDER BY order DESC, user DESC, login DESC');
});
it('return correct query part with multiple mixed parameters', function() {
const parameter = 'user,-price,-size,date';
Assert.equal(Helpers.getOrderByQuery(parameter), ' ORDER BY user ASC, price DESC, size DESC, date ASC');
});
};
| waiterio/api | test/unit/common/databaseHelpers/testGetOrderByQuery.js | JavaScript | mit | 1,362 |
<?php
namespace App\Controllers\Api\Admin;
use Slim\Http\Request;
use Slim\Http\Response;
use App\Models\Node;
use App\Models\TrafficLog;
use App\Controllers\BaseController;
class NodeController extends BaseController
{
public function index(Request $req, Response $res, $args)
{
$pageNum = 1;
if (isset($req->getQueryParams()['page'])) {
$pageNum = $req->getQueryParams()['page'];
}
$traffic = Node::paginate(15, [
'*',
], 'page', $pageNum);
$traffic->setPath('/api/admin/nodes');
//return $this->echoJsonWithData($res,$traffic);
return $this->echoJson($res, $traffic);
}
private function saveModel(Response $response, Node $node, $arr)
{
foreach ($arr as $k => $v) {
$node->$k = $v;
}
$node->save();
return $this->echoJsonWithData($response, $node);
}
public function store(Request $req, Response $res, $args)
{
$input = file_get_contents("php://input");
$arr = json_decode($input, true);
return $this->saveModel($res, new Node(), $arr);
}
public function update(Request $req, Response $res, $args)
{
$input = file_get_contents("php://input");
$arr = json_decode($input, true);
return $this->saveModel($res, Node::find($args['id']), $arr);
}
public function delete(Request $req, Response $res, $args)
{
$node = Node::find($args['id']);
$node->delete();
return $this->echoJsonWithData($res, []);
}
public function trafficLogs(Request $req, Response $res, $args)
{
$pageNum = 1;
if (isset($req->getQueryParams()['page'])) {
$pageNum = $req->getQueryParams()['page'];
}
$traffic = TrafficLog::where('user_traffic_log.node_id', $args['id'])
->join('ss_node', 'user_traffic_log.node_id', '=', 'ss_node.id')
->orderBy('user_traffic_log.id', 'desc')
->paginate(15, [
'user_traffic_log.*',
'ss_node.name as name'
], 'page', $pageNum);
$traffic->setPath('/api/admin/trafficLogs');
//return $this->echoJsonWithData($res,$traffic);
return $this->echoJson($res, $traffic);
}
} | ma321c/SS-panel_V4 | app/Controllers/Api/Admin/NodeController.php | PHP | mit | 2,300 |
class RevisionsController < ApplicationController
before_filter :load_article
def new
@revision = @article.revisions.new
@revision.body = @article.current_revision.body
end
def create
@revision = @article.revisions.create(revision_params)
if @revision.persisted?
redirect_to article_path(@article), notice: "Article edited!"
else
render "new"
end
end
private
def load_article
@article = Article.find(params[:article_id])
end
def revision_params
params[:article_revision].permit(:body, :edit_summary)
end
end | locriani/magmawiki | app/controllers/revisions_controller.rb | Ruby | mit | 574 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v1/enums/asset_type.proto
package enums
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// Enum describing possible types of asset.
type AssetTypeEnum_AssetType int32
const (
// Not specified.
AssetTypeEnum_UNSPECIFIED AssetTypeEnum_AssetType = 0
// Used for return value only. Represents value unknown in this version.
AssetTypeEnum_UNKNOWN AssetTypeEnum_AssetType = 1
// YouTube video asset.
AssetTypeEnum_YOUTUBE_VIDEO AssetTypeEnum_AssetType = 2
// Media bundle asset.
AssetTypeEnum_MEDIA_BUNDLE AssetTypeEnum_AssetType = 3
// Image asset.
AssetTypeEnum_IMAGE AssetTypeEnum_AssetType = 4
// Text asset.
AssetTypeEnum_TEXT AssetTypeEnum_AssetType = 5
)
var AssetTypeEnum_AssetType_name = map[int32]string{
0: "UNSPECIFIED",
1: "UNKNOWN",
2: "YOUTUBE_VIDEO",
3: "MEDIA_BUNDLE",
4: "IMAGE",
5: "TEXT",
}
var AssetTypeEnum_AssetType_value = map[string]int32{
"UNSPECIFIED": 0,
"UNKNOWN": 1,
"YOUTUBE_VIDEO": 2,
"MEDIA_BUNDLE": 3,
"IMAGE": 4,
"TEXT": 5,
}
func (x AssetTypeEnum_AssetType) String() string {
return proto.EnumName(AssetTypeEnum_AssetType_name, int32(x))
}
func (AssetTypeEnum_AssetType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_491e1f3963d1cbfd, []int{0, 0}
}
// Container for enum describing the types of asset.
type AssetTypeEnum struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *AssetTypeEnum) Reset() { *m = AssetTypeEnum{} }
func (m *AssetTypeEnum) String() string { return proto.CompactTextString(m) }
func (*AssetTypeEnum) ProtoMessage() {}
func (*AssetTypeEnum) Descriptor() ([]byte, []int) {
return fileDescriptor_491e1f3963d1cbfd, []int{0}
}
func (m *AssetTypeEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_AssetTypeEnum.Unmarshal(m, b)
}
func (m *AssetTypeEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AssetTypeEnum.Marshal(b, m, deterministic)
}
func (m *AssetTypeEnum) XXX_Merge(src proto.Message) {
xxx_messageInfo_AssetTypeEnum.Merge(m, src)
}
func (m *AssetTypeEnum) XXX_Size() int {
return xxx_messageInfo_AssetTypeEnum.Size(m)
}
func (m *AssetTypeEnum) XXX_DiscardUnknown() {
xxx_messageInfo_AssetTypeEnum.DiscardUnknown(m)
}
var xxx_messageInfo_AssetTypeEnum proto.InternalMessageInfo
func init() {
proto.RegisterEnum("google.ads.googleads.v1.enums.AssetTypeEnum_AssetType", AssetTypeEnum_AssetType_name, AssetTypeEnum_AssetType_value)
proto.RegisterType((*AssetTypeEnum)(nil), "google.ads.googleads.v1.enums.AssetTypeEnum")
}
func init() {
proto.RegisterFile("google/ads/googleads/v1/enums/asset_type.proto", fileDescriptor_491e1f3963d1cbfd)
}
var fileDescriptor_491e1f3963d1cbfd = []byte{
// 326 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0x4f, 0x4e, 0xf3, 0x30,
0x14, 0xc4, 0xbf, 0xa6, 0xed, 0x07, 0x75, 0x29, 0x18, 0x2f, 0x11, 0x5d, 0xb4, 0x07, 0x70, 0x14,
0xb1, 0x33, 0x2b, 0x87, 0x98, 0x2a, 0x82, 0xa6, 0x95, 0x48, 0xc2, 0x1f, 0x45, 0xaa, 0x42, 0x13,
0x45, 0x95, 0x5a, 0x3b, 0xaa, 0xdd, 0x4a, 0xbd, 0x0e, 0x4b, 0x8e, 0xc2, 0x35, 0xd8, 0x71, 0x0a,
0x14, 0x9b, 0x64, 0x07, 0x1b, 0x6b, 0xf4, 0xde, 0xef, 0x8d, 0xc6, 0x03, 0x70, 0x21, 0x44, 0xb1,
0xce, 0xed, 0x34, 0x93, 0xb6, 0x91, 0x95, 0xda, 0x3b, 0x76, 0xce, 0x77, 0x1b, 0x69, 0xa7, 0x52,
0xe6, 0x6a, 0xa1, 0x0e, 0x65, 0x8e, 0xcb, 0xad, 0x50, 0x02, 0x0d, 0x0d, 0x84, 0xd3, 0x4c, 0xe2,
0x86, 0xc7, 0x7b, 0x07, 0x6b, 0xfe, 0xe2, 0xb2, 0xb6, 0x2b, 0x57, 0x76, 0xca, 0xb9, 0x50, 0xa9,
0x5a, 0x09, 0x2e, 0xcd, 0xf1, 0x58, 0x81, 0x01, 0xad, 0x0c, 0xc3, 0x43, 0x99, 0x33, 0xbe, 0xdb,
0x8c, 0x97, 0xa0, 0xd7, 0x0c, 0xd0, 0x19, 0xe8, 0x47, 0xc1, 0xc3, 0x9c, 0xdd, 0xf8, 0xb7, 0x3e,
0xf3, 0xe0, 0x3f, 0xd4, 0x07, 0x47, 0x51, 0x70, 0x17, 0xcc, 0x1e, 0x03, 0xd8, 0x42, 0xe7, 0x60,
0xf0, 0x3c, 0x8b, 0xc2, 0xc8, 0x65, 0x8b, 0xd8, 0xf7, 0xd8, 0x0c, 0x5a, 0x08, 0x82, 0x93, 0x29,
0xf3, 0x7c, 0xba, 0x70, 0xa3, 0xc0, 0xbb, 0x67, 0xb0, 0x8d, 0x7a, 0xa0, 0xeb, 0x4f, 0xe9, 0x84,
0xc1, 0x0e, 0x3a, 0x06, 0x9d, 0x90, 0x3d, 0x85, 0xb0, 0xeb, 0x7e, 0xb6, 0xc0, 0x68, 0x29, 0x36,
0xf8, 0xcf, 0xe4, 0xee, 0x69, 0x13, 0x64, 0x5e, 0x65, 0x9d, 0xb7, 0x5e, 0xdc, 0x9f, 0x83, 0x42,
0xac, 0x53, 0x5e, 0x60, 0xb1, 0x2d, 0xec, 0x22, 0xe7, 0xfa, 0x27, 0x75, 0x55, 0xe5, 0x4a, 0xfe,
0xd2, 0xdc, 0xb5, 0x7e, 0xdf, 0xac, 0xf6, 0x84, 0xd2, 0x77, 0x6b, 0x38, 0x31, 0x56, 0x34, 0x93,
0xd8, 0xc8, 0x4a, 0xc5, 0x0e, 0xae, 0x5a, 0x90, 0x1f, 0xf5, 0x3e, 0xa1, 0x99, 0x4c, 0x9a, 0x7d,
0x12, 0x3b, 0x89, 0xde, 0x7f, 0x59, 0x23, 0x33, 0x24, 0x84, 0x66, 0x92, 0x90, 0x86, 0x20, 0x24,
0x76, 0x08, 0xd1, 0xcc, 0xeb, 0x7f, 0x1d, 0xec, 0xea, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x60, 0xe7,
0xfb, 0x60, 0xd1, 0x01, 0x00, 0x00,
}
| pushbullet/engineer | vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/enums/asset_type.pb.go | GO | mit | 5,428 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("05. Calculate Sequence with Queue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05. Calculate Sequence with Queue")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2ac1ddc3-dcaa-426c-9a73-9ebf325f293d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| PhilipYordanov/Software-University-CSharp-Fundamentals-track | CSharpAdvance/Stacks and Queues/05. Calculate Sequence with Queue/Properties/AssemblyInfo.cs | C# | mit | 1,437 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using ApprovalTests.Reporters;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
[UseReporter(typeof(VisualStudioReporter))]
public class PureDotNetAssemblyTests
{
Assembly assembly;
string beforeAssemblyPath;
string afterAssemblyPath;
ModuleDefinition moduleDefinition;
public PureDotNetAssemblyTests()
{
beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcessWithoutUnmanaged\bin\Debug\AssemblyToProcessWithoutUnmanaged.dll");
var directoryName = Path.GetDirectoryName(@"..\..\..\Debug\");
#if (!DEBUG)
beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
directoryName = directoryName.Replace("Debug", "Release");
#endif
afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "InMemory.dll");
File.Copy(beforeAssemblyPath, afterAssemblyPath, true);
File.Copy(beforeAssemblyPath.Replace(".dll", ".pdb"), afterAssemblyPath.Replace(".dll", ".pdb"), true);
var readerParams = new ReaderParameters { ReadSymbols = true };
moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath, readerParams);
var references = new List<string>
{
beforeAssemblyPath.Replace("AssemblyToProcessWithoutUnmanaged", "AssemblyToReference"),
};
var assemblyToReferenceDirectory = Path.GetDirectoryName(beforeAssemblyPath.Replace("AssemblyToProcessWithoutUnmanaged", "AssemblyToReference"));
var assemblyToReferenceResources = Directory.GetFiles(assemblyToReferenceDirectory, "*.resources.dll", SearchOption.AllDirectories);
references.AddRange(assemblyToReferenceResources);
// This should use ILTemplate instead of ILTemplateWithUnmanagedHandler.
using (var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AssemblyResolver = new MockAssemblyResolver(),
Config = XElement.Parse("<Costura />"),
ReferenceCopyLocalPaths = references,
AssemblyFilePath = beforeAssemblyPath
})
{
weavingTask.Execute();
var writerParams = new WriterParameters { WriteSymbols = true };
moduleDefinition.Write(afterAssemblyPath, writerParams);
}
var isolatedPath = Path.Combine(Path.GetTempPath(), "CosturaPureDotNetIsolatedMemory.dll");
File.Copy(afterAssemblyPath, isolatedPath, true);
File.Copy(afterAssemblyPath.Replace(".dll", ".pdb"), isolatedPath.Replace(".dll", ".pdb"), true);
assembly = Assembly.LoadFile(isolatedPath);
}
[Test]
public void Simple()
{
var instance2 = assembly.GetInstance("ClassToTest");
Assert.AreEqual("Hello", instance2.Foo());
}
[Test]
public void ThrowException()
{
try
{
var instance = assembly.GetInstance("ClassToTest");
instance.ThrowException();
}
catch (Exception exception)
{
Debug.WriteLine(exception.StackTrace);
Assert.IsTrue(exception.StackTrace.Contains("ClassToReference.cs:line"));
}
}
[Test]
public void EnsureOnly1RefToMscorLib()
{
Assert.AreEqual(1, moduleDefinition.AssemblyReferences.Count(x => x.Name == "mscorlib"));
}
[Test]
public void EnsureNoReferenceToTemplate()
{
Assert.AreEqual(0, moduleDefinition.AssemblyReferences.Count(x => x.Name == "Template"));
}
[Test]
public void EnsureCompilerGeneratedAttribute()
{
Assert.IsTrue(moduleDefinition.GetType("Costura.AssemblyLoader").Resolve().CustomAttributes.Any(attr => attr.AttributeType.Name == "CompilerGeneratedAttribute"));
}
#if DEBUG
[Test]
public void TemplateHasCorrectSymbols()
{
Approvals.Verify(Decompiler.Decompile(afterAssemblyPath, "Costura.AssemblyLoader"));
}
#endif
[Test]
public void PeVerify()
{
Verifier.Verify(beforeAssemblyPath, afterAssemblyPath);
}
[Test]
public void TypeReferencedWithPartialAssemblyNameIsLoadedFromExistingAssemblyInstance()
{
var instance = assembly.GetInstance("ClassToTest");
var assemblyLoadedByCompileTimeReference = instance.GetReferencedAssembly();
var typeLoadedWithPartialAssemblyName = Type.GetType("ClassToReference, AssemblyToReference");
Assume.That(typeLoadedWithPartialAssemblyName, Is.Not.Null);
Assert.AreSame(assemblyLoadedByCompileTimeReference, typeLoadedWithPartialAssemblyName.Assembly);
}
} | distantcam/Costura | Tests/PureDotNetAssemblyTests.cs | C# | mit | 4,751 |
// -----------------------------------------------------------
// visualizer.js - main code for visualizing hands
// Created by Raquel Vélez
//
// 30 Dec 2011 - Reviewing code for submission. For future
// development: fix bugs, implement inverse kinematic model
// for single-point drag of each finger (more human-like
// and intuitive than adjusting each individual joint)
//
// 12 Oct 2010 - Compiled all the individual files (math.js,
// setupHand.js, setupHandFunctions.js, visualizerFunctions.js)
// into one to facilitate moving to the server. It's not
// perfect, but it's cool!
// -----------------------------------------------------------
// -----------------------------------------------------------
// set the angles of each joint and global rotation (for testing)
// -----------------------------------------------------------
function setAngles()
{
var thumb = [0 * Math.PI/180, -30 * Math.PI/180, 10 * Math.PI/180, 10 * Math.PI/180];
var index = [0 * Math.PI/180, 0 * Math.PI/180, 10 * Math.PI/180, 10 * Math.PI/180];
var middle = [0 * Math.PI/180, 0 * Math.PI/180, 10 * Math.PI/180, 10 * Math.PI/180];
var ring = [0 * Math.PI/180, 0 * Math.PI/180, 10 * Math.PI/180, 10 * Math.PI/180];
var pinky = [0 * Math.PI/180, 0 * Math.PI/180, 10 * Math.PI/180, 10 * Math.PI/180];
var global = [0,0,Math.PI/2];
return thumb.concat(index, middle, ring, pinky, global);
}
// -----------------------------------------------------------
// get angles from the hand (and the orientation), and whether the hand is left or right))
// -----------------------------------------------------------
function getAnglesDeg(fingers, globalRotationAngles)
{
var angles = new Array();
for (var f = 0; f < fingers.length; ++f)
{
for (var j = 0; j < fingers[f].jointAngles.length; ++j)
{
angles.push(Math.round(fingers[f].jointAngles[j] * 180 / Math.PI));
}
}
for (var g = 0; g < globalRotationAngles.length; ++g)
{
angles.push(Math.round(globalRotationAngles[g] * 180 / Math.PI));
}
angles.push(fingers[0].isLeft);
return angles;
}
// -----------------------------------------------------------
// get angles from the hand
// -----------------------------------------------------------
function getAnglesRad(fingers, globalRotationAngles)
{
var angles = new Array();
for (var f = 0; f < fingers.length; ++f)
{
for (var j = 0; j < fingers[f].jointAngles.length; ++j)
{
angles.push(fingers[f].jointAngles[j]);
}
}
for (var g = 0; g < globalRotationAngles.length; ++g)
{
angles.push(globalRotationAngles[g]);
}
return angles;
}
// -----------------------------------------------------------
// create a gesture
// -----------------------------------------------------------
function startMove()
{
// initialize the canvas and context writer
var canvas = document.getElementById("canvas_new_gesture");
var ctx = canvas.getContext("2d");
// set up the guide coordinates
var origin_guide = new Vector(380,380,0);
guide_coords = createCoords(origin_guide, 15);
// pre-define global yaw, pitch, roll, with rotations for isometric view
var startGlobalZrotAng = 0;//Math.PI/15;
var startGlobalYrotAng = -Math.PI/10;
var startGlobalXrotAng = Math.PI/3;
var globalRotationAngles = new Array(startGlobalZrotAng, startGlobalYrotAng, startGlobalXrotAng);
// set up the hand
var origin_palm = new Vector(185,185,0);
var isLeft = false;
var spacing = 30;
var shrinkFactor = 1;
var fingers = Hand(origin_palm, spacing, shrinkFactor, isLeft);
applyRotToAllFingers(fingers, origin_palm, globalRotationAngles);
// pre-rotate into isometric view
var visGuideCoords = rotateCoords(guide_coords, globalRotationAngles);
//var visPalm = rotatePalm(palm, origin_palm, globalRotationAngles);
var visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
// draw the guide coordinates and the fingers into view
redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
// draw the origin of the entire hand
// ctx.fillStyle = "rgb(200,200,100)";
// ctx.fillRect(origin_palm.v[0]-3, origin_palm.v[1]-3, 6, 6);
var reset = false;
var moveHand_lr = false;
var moveHand_ud = false;
var movePoint = false;
var selectedPointIndex = null;
var selectedFinger = null;
var mouseCoords = null;
// document.getElementById('new_gesture_left_hand_button').onclick = function(event)
// {
// document.getElementById('new_gesture_left_hand_button').className='new_gesture_hand_button_selected';
// document.getElementById('new_gesture_right_hand_button').className='new_gesture_hand_button';
// globalRotationAngles = [globalRotationAngles[0], -globalRotationAngles[1], globalRotationAngles[2]];
// fingers = switchHands(fingers, globalRotationAngles, origin_palm, spacing, shrinkFactor, 1); // 1 is left
// visGuideCoords = rotateHand([0,0], guide_coords, fingers, origin_palm, globalRotationAngles, moveHand_lr, moveHand_ud);
// visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
// redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
// }
//
// document.getElementById('new_gesture_right_hand_button').onclick = function(event)
// {
// document.getElementById('new_gesture_left_hand_button').className='new_gesture_hand_button';
// document.getElementById('new_gesture_right_hand_button').className='new_gesture_hand_button_selected';
// globalRotationAngles = [globalRotationAngles[0], -globalRotationAngles[1], globalRotationAngles[2]];
// fingers = switchHands(fingers, globalRotationAngles, origin_palm, spacing, shrinkFactor, 0); // 0 is right
// visGuideCoords = rotateHand([0,0], guide_coords, fingers, origin_palm, globalRotationAngles, moveHand_lr, moveHand_ud);
// visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
// redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
// }
//
// document.getElementById('new_gesture_reset_button').onclick = function(event)
// {
// for (var f=0; f<fingers.length; ++f) {
// fingers[f].reset();
// }
// applyRotToAllFingers(fingers, origin_palm, globalRotationAngles);
//
// globalRotationAngles = [startGlobalZrotAng, startGlobalYrotAng, startGlobalXrotAng];
// visGuideCoords = rotateHand([0,0], guide_coords, fingers, origin_palm, globalRotationAngles, moveHand_lr, moveHand_ud);
//
// visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
// redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
// }
// when the mouse is clicked
document.onmousedown = function(event)
{
mouseCoords = getMouseCoords(event);
if (mouseCoords == null)
{
alert("Nothing!")
}
else
{
// if there's a click on the guide coords, reset to starting angles
if (mouseCoords[0] > 370 && mouseCoords[1] < 400 &&
mouseCoords[1] > 370 && mouseCoords[1] < 400)
{
reset = true;
}
// if dragging around in one of the guide boxes, move the hand
else if (mouseCoords[0] > 0 && mouseCoords[0] < 370 &&
mouseCoords[1] > 370 && mouseCoords[1] < 400)
{
moveHand_lr = true;
}
else if (mouseCoords[0] > 370 && mouseCoords[0] < 400 &&
mouseCoords[1] > 0 && mouseCoords[1] < 370)
{
moveHand_ud = true;
}
else
{
// if dragging one of the points, move the point around
// the appropriate joint
for (var fingNum = 0; fingNum < fingers.length; ++fingNum)
{
for (var ip = 0; ip < fingers[fingNum].visPoints.length; ++ip)
{
var radiusAroundPoints = 10;
if (fingers[fingNum].visPoints[ip].withinRadiusAroundPoint(radiusAroundPoints, mouseCoords))
{
// set current point for dragging
movePoint = true;
selectedPointIndex = ip;
selectedFinger = fingers[fingNum];
} // if
} // for ip
} // for fingerNumber
} // else
}
}
// when the mouse is being dragged around
document.onmousemove = function(event)
{
var newMouseCoords = getMouseCoords(event);
if (newMouseCoords == null)
{
alert("Nothing!")
}
else
{
// determine the direction of the mouse movement
if (mouseCoords != null)
var diff = [ newMouseCoords[0] - mouseCoords[0], newMouseCoords[1] - mouseCoords[1] ];
// move a selected point and the corresponding joints along the finger
if (movePoint)
{
moveFinger(ctx, mouseCoords, newMouseCoords, selectedFinger, selectedPointIndex, origin_palm, globalRotationAngles, visGuideCoords);
visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
}
// move the entire hand
else if (moveHand_lr || moveHand_ud)
{
visGuideCoords = rotateHand(diff, guide_coords, fingers, origin_palm, globalRotationAngles, moveHand_lr, moveHand_ud);
// visPalm = rotatePalm(palm, origin_palm, globalRotationAngles);
visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
}
// reset for next mouse movement
mouseCoords = newMouseCoords;
// redraw everything
// ctx.fillStyle = "rgb(200,200,100)";
// ctx.fillRect(origin_palm.v[0]-3, origin_palm.v[1]-3, 6, 6);
// debugText(ctx, visGuideCoords[1].v[0] - visGuideCoords[2].v[0]);
}
}
// after dragging
document.onmouseup = function(event)
{
mouseCoords = getMouseCoords(event);
if (mouseCoords == null)
{
alert("Nothing!")
}
else
{
if (reset)
{
globalRotationAngles = [startGlobalZrotAng, startGlobalYrotAng, startGlobalXrotAng];
visGuideCoords = rotateHand([0,0], guide_coords, fingers, origin_palm, globalRotationAngles, moveHand_lr, moveHand_ud);
visPalm = createPalm(fingers, origin_palm, globalRotationAngles);
redrawAllMove(ctx, origin_palm, visGuideCoords, fingers, visPalm, globalRotationAngles);
reset = false;
}
moveHand_lr = false;
moveHand_ud = false;
movePoint = false;
selectedPointIndex = null;
selectedFinger = null;
// document.getElementById('input_new_gesture_angles').value = getAnglesDeg(fingers, globalRotationAngles);
}
}
}
// -----------------------------------------------------------
// visualize the hand only
// -----------------------------------------------------------
function startVis(handArray)
{
for(iterator=0; iterator<handArray.length; iterator++) {
// initialize the canvas and context writer
var canvas = document.getElementById("hand_"+handArray[iterator][0]);
var ctx = canvas.getContext("2d");
var thumb = [handArray[iterator][2] * Math.PI/180, handArray[iterator][3] * Math.PI/180, handArray[iterator][4] * Math.PI/180, handArray[iterator][5] * Math.PI/180];
var index = [handArray[iterator][6] * Math.PI/180, handArray[iterator][7] * Math.PI/180, handArray[iterator][8] * Math.PI/180, handArray[iterator][9] * Math.PI/180];
var middle = [handArray[iterator][10] * Math.PI/180, handArray[iterator][11] * Math.PI/180, handArray[iterator][12] * Math.PI/180, handArray[iterator][13] * Math.PI/180];
var ring = [handArray[iterator][14] * Math.PI/180, handArray[iterator][15] * Math.PI/180, handArray[iterator][16] * Math.PI/180, handArray[iterator][17] * Math.PI/180];
var pinky = [handArray[iterator][18] * Math.PI/180, handArray[iterator][19] * Math.PI/180, handArray[iterator][20] * Math.PI/180, handArray[iterator][21] * Math.PI/180];
var global = [handArray[iterator][22] * Math.PI/180, handArray[iterator][23] * Math.PI/180, handArray[iterator][24] * Math.PI/180];
var handedness = handArray[iterator][25];
var shrinkFactor = 180.0/400.0;
// set up the hand
var origin_palm = new Vector(90, 90, 0);
// draw the fancy circle around everything
ctx.fillStyle = "rgb(255,255,255)";
ctx.beginPath();
ctx.arc(origin_palm.v[0], origin_palm.v[1], 90, 0, Math.PI * 2, 0);
ctx.fill();
var fingers = Hand(origin_palm, 30, shrinkFactor, handedness);
var angles = thumb.concat(index, middle, ring, pinky, global);
applyAngles(angles, fingers, origin_palm, handedness);
// how do i get the angles out again?????
applyRotToAllFingers(fingers, origin_palm, angles.slice(-3));
var visPalm = createPalm(fingers, origin_palm, angles.slice(-3));
redrawAllVis(ctx, origin_palm, fingers, visPalm, angles.slice(-3), shrinkFactor);
}
}
// -----------------------------------------------------------
// apply an array of angles to the hand
// -----------------------------------------------------------
function applyAngles(angles, fingers, isLeft)
{
for (var f = 0; f < fingers.length; ++f)
{
fingers[f].jointAngles = angles.slice(f * 4, (f + 1) * 4);
fingers[f].recalc();
}
}
// -----------------------------------------------------------
// one place to describe the hand and do all the dirty work
// -----------------------------------------------------------
function Hand(origin_palm, spacing, shrinkFactor, isLeftHand)
{
if (isLeftHand)
{
// define the origin of each finger
var origin_thumb = new Vector(origin_palm.v[0] - spacing * shrinkFactor, origin_palm.v[1], -125 * shrinkFactor);
var origin_index = new Vector(origin_palm.v[0] - spacing * shrinkFactor, origin_palm.v[1], 0);
var origin_middle = new Vector(origin_palm.v[0], origin_palm.v[1], 0);
var origin_ring = new Vector(origin_palm.v[0] + spacing * shrinkFactor, origin_palm.v[1], -10 * shrinkFactor);
var origin_pinky = new Vector(origin_palm.v[0] + 2 * spacing * shrinkFactor, origin_palm.v[1], -20 * shrinkFactor);
}
else
{
// define the origin of each finger
var origin_thumb = new Vector(origin_palm.v[0] + spacing * shrinkFactor, origin_palm.v[1], -125 * shrinkFactor);
var origin_index = new Vector(origin_palm.v[0] + spacing * shrinkFactor, origin_palm.v[1], 0);
var origin_middle = new Vector(origin_palm.v[0], origin_palm.v[1], 0);
var origin_ring = new Vector(origin_palm.v[0] - spacing * shrinkFactor, origin_palm.v[1], -10 * shrinkFactor);
var origin_pinky = new Vector(origin_palm.v[0] - 2 * spacing * shrinkFactor, origin_palm.v[1], -20 * shrinkFactor);
}
var numPoints = 6;
var numPhalanges = 4;
// define the segment lengths for each finger
var thumbHeights = new Array(0, 80 * shrinkFactor, 53 * shrinkFactor, 46 * shrinkFactor);
var indexHeights = new Array(0, 73 * shrinkFactor, 46 * shrinkFactor, 37 * shrinkFactor);
var middleHeights = new Array(0, 78 * shrinkFactor, 52 * shrinkFactor, 37 * shrinkFactor);
var ringHeights = new Array(0, 75 * shrinkFactor, 51 * shrinkFactor, 37 * shrinkFactor);
var pinkyHeights = new Array(0, 60 * shrinkFactor, 37 * shrinkFactor, 35 * shrinkFactor);
// create each finger
var thumb = new Finger(origin_thumb, numPoints, numPhalanges, thumbHeights, 'thumb', isLeftHand);
var indexFinger = new Finger(origin_index, numPoints, numPhalanges, indexHeights, 'index', isLeftHand);
var middleFinger = new Finger(origin_middle, numPoints, numPhalanges, middleHeights, 'middle', isLeftHand);
var ringFinger = new Finger(origin_ring, numPoints, numPhalanges, ringHeights, 'ring', isLeftHand);
var pinkyFinger = new Finger(origin_pinky, numPoints, numPhalanges, pinkyHeights, 'pinky', isLeftHand);
return [thumb, indexFinger, middleFinger, ringFinger, pinkyFinger];
}
// -----------------------------------------------------------
// switch between left and right hand orientations
// -----------------------------------------------------------
function switchHands(fingers, globalRotationAngles, origin_palm, spacing, shrinkFactor, handedness)
{
if (handedness == fingers[0].isLeft) {
return fingers;
}
else {
// now, grab all the angles from the current hand
var angles = getAnglesRad(fingers, globalRotationAngles);
// now, create a new hand
var newFingers = Hand(origin_palm, spacing, shrinkFactor, handedness);
applyAngles(angles, newFingers, handedness);
applyRotToAllFingers(newFingers, origin_palm, globalRotationAngles);
return newFingers;
}
}
// -----------------------------------------------------------
// collect z-coords of visualized points
// -----------------------------------------------------------
function buildFingerZ(fingers, palmAvg, thumbAvg)
{
// array for z coords
var fingerZ = new Array(fingers.length);
// array for matching coords
var matchTable = new Array();
for (var g = 0; g < fingers.length; ++g)
{
fingerZ[g] = new Array(fingers[g].numPhalanges);
for (var ph = 0; ph < fingers[g].numPhalanges; ++ph)
{
fingerZ[g][ph] = fingers[g].visPoints[ph].v[2] + fingers[g].visPoints[ph+1].v[2];
fingerZ[g][ph] /= 2;
var unmatched = true;
for (var i = 0; i < matchTable.length; ++i)
{
if (matchTable[i][0] == fingerZ[g][ph])
{
matchTable[i][1].push([g, ph]);
unmatched = false;
}
}
if (unmatched)
{
matchArray = new Array();
matchArray.push([g, ph]);
matchTable.push([fingerZ[g][ph], matchArray]);
}
}
}
var palmUnmatched = true;
for (var i = 0; i < matchTable.length; ++i)
{
if (matchTable[i][0] == palmAvg)
{
matchTable[i][1].push([0, 'p']);
palmUnmatched = false;
}
}
if (palmUnmatched)
{
matchArray = new Array();
matchArray.push([0, 'p']);
matchTable.push([palmAvg, matchArray]);
}
var thumbUnmatched = true;
for (var i = 0; i < matchTable.length; ++i)
{
if (matchTable[i][0] == thumbAvg)
{
matchTable[i][1].push([0, 't']);
thumbUnmatched = false;
}
}
if (thumbUnmatched)
{
matchArray = new Array();
matchArray.push([0, 't']);
matchTable.push([thumbAvg, matchArray]);
}
return [fingerZ, matchTable];
}
// -----------------------------------------------------------
// calculate the average z coord of the palm's vis points
// -----------------------------------------------------------
function calcPalmAvgZ(visPalm)
{
var palmAvg = 0;
for (var i = 3; i < visPalm.length; ++i)
{
palmAvg += visPalm[i].v[2];
}
palmAvg /= visPalm.length;
return palmAvg;
}
// -----------------------------------------------------------
// calculate the average z coord of the palm-thumb's vis points
// -----------------------------------------------------------
function calcThumbAvgZ(visPalm)
{
var palmAvg = 0;
for (var i = 0; i <= 3; ++i)
{
palmAvg += visPalm[i].v[2];
}
palmAvg /= visPalm.length;
return palmAvg;
}
// -----------------------------------------------------------
// determine drawing order
// -----------------------------------------------------------
function getDrawingOrder(fingerArrays)
{
var fingerZ = fingerArrays[0];
var matchTable = fingerArrays[1];
var drawingOrder = new Array();
var minZ = 100000; // some ridiculously large number
var prevMinZ = -100000; // some ridiculously low number
while (drawingOrder.length < fingerZ.length * fingerZ[0].length + 2)
{
for (var i = 0; i < matchTable.length; ++i)
{
var inQuestion = parseFloat(matchTable[i][0]);
if (inQuestion < minZ && inQuestion > prevMinZ)
{
// alert('i: ' + i + ' minZ: ' + minZ + ' inQ: ' + inQuestion + ' prev: ' + prevMinZ);
minZ = inQuestion;
loc = i;
} // if
} // for i
for (var m = 0; m < matchTable[loc][1].length; ++m)
{
drawingOrder.push(matchTable[loc][1][m]);
} // for m
prevMinZ = minZ;
minZ = 100000;
} // while
return drawingOrder;
}
// -----------------------------------------------------------
// clears the board and draws everything fresh for startMove()
// -----------------------------------------------------------
function redrawAllMove(ctx, origin_palm, guide_coords, fingers, visPalm, globalRotationAngles)
{
// clear the board
ctx.clearRect(0,0,400,400);
// calculate the average z coord of the palm's vis points
var palmAvg = calcPalmAvgZ(visPalm);
var thumbAvg = calcThumbAvgZ(visPalm);
// figure out what to draw in what order
var fingerArrays = buildFingerZ(fingers, palmAvg, thumbAvg);
// now compile them into one array in the order in which they should be drawn
var drawingOrder = getDrawingOrder(fingerArrays, palmAvg, thumbAvg);
for (d = 0; d < drawingOrder.length; ++d)
{
var drawNow = drawingOrder[d];
if (drawNow[1] == 'p')
{
drawPalm(ctx, visPalm, 1);
}
else if (drawNow[1] == 't')
{
drawThumb(ctx, visPalm, 1);
}
else
{
var fingNum = drawNow[0];
var phalNum = drawNow[1];
if (phalNum != 0)
{
drawPhalanx(ctx, fingers[fingNum], phalNum, 1);
drawFingerPoint(ctx, fingers[fingNum], phalNum);
}
}
}
// drawFingerPoints(ctx, fingers);
drawCoords(ctx, guide_coords);
}
// -----------------------------------------------------------
// clears the board and draws everything fresh for startVis()
// -----------------------------------------------------------
function redrawAllVis(ctx, origin_palm, fingers, visPalm, globalRotationAngles, shrinkFactor)
{
// clear the board
// ctx.clearRect(0,0,400,400);
// calculate the average z coord of the palm's vis points
var palmAvg = calcPalmAvgZ(visPalm);
var thumbAvg = calcThumbAvgZ(visPalm);
// figure out what to draw in what order
var fingerArrays = buildFingerZ(fingers, palmAvg, thumbAvg);
// now compile them into one array in the order in which they should be drawn
var drawingOrder = getDrawingOrder(fingerArrays, palmAvg, thumbAvg);
for (d = 0; d < drawingOrder.length; ++d)
{
var drawNow = drawingOrder[d];
if (drawNow[1] == 'p')
{
drawPalm(ctx, visPalm, shrinkFactor);
}
else if (drawNow[1] == 't')
{
drawThumb(ctx, visPalm, shrinkFactor);
}
else
{
var fingNum = drawNow[0];
var phalNum = drawNow[1];
if (phalNum != 0)
{
drawPhalanx(ctx, fingers[fingNum], phalNum, shrinkFactor);
}
}
}
}
// -----------------------------------------------------------
// create palm
// -----------------------------------------------------------
function createPalm(fingers, origin, globalRotationAngles)
{
var thumb = fingers[0].points3D;
var index = fingers[1].points3D;
var pinky = fingers[4].points3D;
var atIndex = new Vector(index[0].v[0], index[0].v[1], index[0].v[2]);
var atPinky = new Vector(pinky[0].v[0], pinky[0].v[1], pinky[0].v[2]);
var atHeel = new Vector(pinky[0].v[0], thumb[0].v[1],
Math.min(thumb[0].v[2], thumb[0].v[2]));
var atThenar = new Vector(thumb[0].v[0], thumb[0].v[1], thumb[0].v[2]);
var atSquishy = new Vector(index[0].v[0], index[0].v[1],
(index[0].v[2] + thumb[0].v[2])/2);
var atThumb = thumb[2];
var palm = [atSquishy, atThumb, atThenar, atSquishy, atIndex, atPinky, atHeel, atThenar];
var visPalm = new Array(palm.length);
for (var i = 0; i < palm.length; ++i)
{
var vp = RotVectorAboutOrigin(palm[i], origin, globalRotationAngles, true);
// alert(palm[i].v);
visPalm[i] = new Vector(vp[0], vp[1], vp[2]);
}
return visPalm;
}
// -----------------------------------------------------------
// draws the palm
// -----------------------------------------------------------
function drawPalm(ctx, palm, shrinkFactor)
{
ctx.lineWidth = 34 * shrinkFactor;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = "rgba(0,0,0,0.3)";
ctx.beginPath();
ctx.moveTo(palm[3].v[0], palm[3].v[1]);
for (var i = 3; i < palm.length; ++i)
{
ctx.lineTo(palm[i].v[0], palm[i].v[1]);
}
ctx.stroke();
// ctx.fill();
ctx.lineWidth = 31 * shrinkFactor;
ctx.strokeStyle = "rgb(255,203,162)";
ctx.fillStyle = "rgb(255,203,162)";
ctx.beginPath();
ctx.moveTo(palm[palm.length-1].v[0], palm[palm.length-1].v[1]);
for (i = 3; i < palm.length; ++i)
{
ctx.lineTo(palm[i].v[0], palm[i].v[1]);
}
ctx.stroke();
ctx.fill();
}
// -----------------------------------------------------------
// draws the flappy part between the thumb and palm
// -----------------------------------------------------------
function drawThumb(ctx, palm, shrinkFactor)
{
ctx.lineWidth = 34 * shrinkFactor;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = "rgba(0,0,0,0.3)";
ctx.beginPath();
ctx.moveTo(palm[0].v[0], palm[0].v[1]);
for (var i = 0; i < 3; ++i)
{
ctx.lineTo(palm[i].v[0], palm[i].v[1]);
}
ctx.stroke();
ctx.lineWidth = 31 * shrinkFactor;
ctx.strokeStyle = "rgb(255,203,162)";
ctx.fillStyle = "rgb(255,203,162)";
ctx.beginPath();
ctx.moveTo(palm[palm.length-1].v[0], palm[palm.length-1].v[1]);
for (var i = 0; i <= 3; ++i)
{
ctx.lineTo(palm[i].v[0], palm[i].v[1]);
}
ctx.stroke();
ctx.fill();
}
// -----------------------------------------------------------
// draw each individual phalanx
// -----------------------------------------------------------
function drawPhalanx(ctx, finger, phalanxNumber, shrinkFactor)
{
if (phalanxNumber == 1)
{
var startPoint = finger.visPoints[0];
}
else
{
var startPoint = finger.visPoints[phalanxNumber];
}
var endPoint = finger.visPoints[phalanxNumber+1];
if (finger.fingerType == 'thumb')
{
ctx.lineWidth = shrinkFactor * (34 - 1.5 * phalanxNumber);
}
else
{
ctx.lineWidth = shrinkFactor * (27 - 1.5 * phalanxNumber);
}
// draw outside of phalanx
ctx.strokeStyle = "rgba(0,0,0,0.3)";
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(startPoint.v[0], startPoint.v[1]-2);
ctx.lineTo(endPoint.v[0]+1, endPoint.v[1]+1);
ctx.stroke();
if (finger.fingerType == 'thumb')
{
ctx.lineWidth = shrinkFactor * (31 - 1.5 * phalanxNumber);
}
else
{
ctx.lineWidth = shrinkFactor * (24 - 1.5 * phalanxNumber);
}
// draw inside of finger
ctx.strokeStyle = "rgb(255,203,162)";
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(startPoint.v[0], startPoint.v[1]);
ctx.lineTo(endPoint.v[0]+1, endPoint.v[1]+1);
ctx.stroke();
// draw the point at the bottom of the phalanx
if (shrinkFactor == 1)
{
drawFingerPoint(ctx, finger, phalanxNumber-1);
}
}
// -----------------------------------------------------------
// draw the finger points for all fingers
// -----------------------------------------------------------
function drawFingerPoint(ctx, finger, phalanxNum)
{
var colors = ["rgb(200, 200, 0)", "rgb(0,0,200)", "rgb(0,200,0)", "rgb(200,0,0)"];
var fingerPoint = finger.visPoints[phalanxNum+1];
ctx.fillStyle = colors[phalanxNum];
ctx.beginPath();
ctx.arc(fingerPoint.v[0], fingerPoint.v[1], 4, 0, Math.PI * 2, 0);
ctx.fill();
}
// -----------------------------------------------------------
// move the finger joints in a reasonable way
// -----------------------------------------------------------
function moveFinger(ctx, startMouse, endMouse, selectedFinger, selectedPointIndex, origin_palm, globalRotAngles, visGuideCoords)
{
// determine the rotation angle based on the mouse movement
var visPoint = selectedFinger.visPoints[selectedPointIndex].v;
var visJoint = selectedFinger.visPoints[selectedPointIndex-1].v;
//var v1 = [ visPoint[0] - visJoint[0], visPoint[1] - visJoint[1] ];
var v1 = [ startMouse[0] - visJoint[0], startMouse[1] - visJoint[1], startMouse[2] - visJoint[2], 1 ];
var v2 = [ endMouse[0] - visJoint[0], endMouse[1] - visJoint[1], endMouse[2] - visJoint[2], 1 ];
var vis1 = RotVectorAboutOrigin(v1, origin_palm, globalRotAngles);
// alert(vis1);
var newV1 = new Vector(vis1[0] + selectedFinger.points3D[selectedPointIndex-1].v[0], vis1[1] + selectedFinger.points3D[selectedPointIndex-1].v[1], vis1[2] + selectedFinger.points3D[selectedPointIndex-1].v[2]);
// alert(newV1.v);
var vis2 = RotVectorAboutOrigin(v2, origin_palm, globalRotAngles);
// alert(vis2);
var newV2 = new Vector(vis2[0] + selectedFinger.points3D[selectedPointIndex-1].v[0], vis2[1] + selectedFinger.points3D[selectedPointIndex-1].v[1], vis2[2] + selectedFinger.points3D[selectedPointIndex-1].v[2]);
// alert(newV2.v);
v1 = newV1.v;
v2 = newV2.v;
var v1dotv2 = v1[0] * v2[0] + v1[1] * v2[1];
var v1crossv2 = v1[0] * v2[1] - v1[1] * v2[0];
var magv1 = Math.sqrt( v1[0] * v1[0] + v1[1] * v1[1] );
var magv2 = Math.sqrt( v2[0] * v2[0] + v2[1] * v2[1] );
var mouseRotAng = Math.acos( v1dotv2 / (magv1 * magv2) );
var diffX = [visGuideCoords[1].v[0] - visGuideCoords[0].v[0], visGuideCoords[1].v[1] - visGuideCoords[0].v[1], visGuideCoords[1].v[2] - visGuideCoords[0].v[2]];
var diffY = [visGuideCoords[2].v[0] - visGuideCoords[0].v[0], visGuideCoords[2].v[1] - visGuideCoords[0].v[1], visGuideCoords[2].v[2] - visGuideCoords[0].v[2]];
var diffZ = [visGuideCoords[3].v[0] - visGuideCoords[0].v[0], visGuideCoords[3].v[1] - visGuideCoords[0].v[1], visGuideCoords[3].v[2] - visGuideCoords[0].v[2]];
var xCrossY = diffX[0] * diffY[1] - diffX[1] * diffY[0];
var yCrossZ = diffY[0] * diffZ[1] - diffY[1] * diffZ[0];
var zCrossX = diffZ[0] * diffX[1] - diffZ[1] * diffX[0];
var compareToVisGuideCoords;
if (selectedFinger.fingerType == 'thumb')
{
if (selectedPointIndex == 1) {
if (selectedFinger.isLeft) { compareToVisGuideCoords = yCrossZ; }
else { compareToVisGuideCoords = -yCrossZ; }
}
else {
if (selectedFinger.isLeft) { compareToVisGuideCoords = -xCrossY; }
else { compareToVisGuideCoords = xCrossY; }
}
}
else
{
if (selectedPointIndex == 1) {
if (selectedFinger.isLeft) { compareToVisGuideCoords = -yCrossZ * zCrossX; }
else { compareToVisGuideCoords = yCrossZ * zCrossX; }
}
else {
compareToVisGuideCoords = yCrossZ;
}
}
// determine the rotation angle
var rotAngle = 2 * Math.PI/180;// mouseRotAng; //Math.PI/30;
var zRotAng = 0;
// rotate around z axis
if (mouseRotAng)
{
if (v1crossv2 > 0)
{
// if (compareToVisGuideCoords > 0) { zRotAng = -rotAngle; }
{ zRotAng = rotAngle; }
}
else if (v1crossv2 < 0)
{
// if (compareToVisGuideCoords > 0) { zRotAng = rotAngle; }
{ zRotAng = -rotAngle; }
}
}
// apply new joint angles to finger
selectedFinger.jointAngles[selectedPointIndex-1] += zRotAng;
ctx.lineWidth = 1;
ctx.strokeStyle = "rgb(0,0,0)";
ctx.font = "10pt Arial";
ctx.clearRect(400,0,400,400);
ctx.strokeText('finger: ' + selectedFinger.fingerType, 410, 10);
ctx.strokeText('joint0: ' + (selectedFinger.jointAngles[0] * 180/Math.PI), 410, 40);
ctx.strokeText('joint1: ' + (selectedFinger.jointAngles[1] * 180/Math.PI), 410, 70);
ctx.strokeText('joint2: ' + (selectedFinger.jointAngles[2] * 180/Math.PI), 410, 100);
ctx.strokeText('joint3: ' + (selectedFinger.jointAngles[3] * 180/Math.PI), 410, 130);
// var D = new Array(3);
// for (var k = 0; k < D.length; ++k)
// {
// D[k] = [visGuideCoords[k+1].v[0] - visGuideCoords[0].v[0],
// visGuideCoords[k+1].v[1] - visGuideCoords[0].v[1],
// visGuideCoords[k+1].v[2] - visGuideCoords[0].v[2]];
// }
// var v1crossv2 = v1[0] * v2[1] - v1[1] * v2[0];
ctx.strokeText('rot: ' + zRotAng, 410, 170);
ctx.strokeText('FingPos3d: ' + selectedFinger.points3D[selectedPointIndex].v, 410, 200);
ctx.strokeText('FingPosVis: ' + selectedFinger.visPoints[selectedPointIndex].v, 410, 230);
// ctx.strokeText('diffX: ' + diffX, 410, 200);
// ctx.strokeText('diffY: ' + diffY, 410, 230);
// ctx.strokeText('diffZ: ' + diffZ, 410, 260);
ctx.strokeText('v1: ' + v1, 410, 290);
ctx.strokeText('v2: ' + v2, 410, 320);
// ctx.strokeText('diffX x diffY: ' + (D[0][0] * D[1][1] - D[0][1] * D[1][0]), 410, 300);
// ctx.strokeText('diffY x diffZ: ' + (D[1][0] * D[2][1] - D[1][1] * D[2][0]), 410, 330);
// ctx.strokeText('diffZ x diffX: ' + (D[2][0] * D[0][1] - D[2][1] * D[0][0]), 410, 360);
// recalculate 3D position of finger
selectedFinger.recalc();
// interpret 3D points to visual points:
// go through each finger point
for (var p = 0; p < selectedFinger.points3D.length; ++p)
{
// update the viewer coordinates of each point
var vip = RotVectorAboutOrigin(selectedFinger.points3D[p], origin_palm, globalRotAngles, true);
selectedFinger.visPoints[p] = new Vector(vip[0], vip[1], vip[2]);
}
// for the 1st point, we want it located approx 1/3 of the way up the finger
var pt0 = selectedFinger.visPoints[1].v;
var pt1 = selectedFinger.visPoints[2].v;
vip = [pt1[0] - pt0[0], pt1[1] - pt0[1], pt1[2] - pt0[2]];
selectedFinger.visPoints[1] = new Vector(pt0[0] + vip[0] / 3, pt0[1] + vip[1] / 3, pt0[2] + vip[2] / 3);
}
// -----------------------------------------------------------
// rotate the hand and the guide around the palm's origin
// -----------------------------------------------------------
function rotateHand(diff, guide_coords, fingers, origin_palm, globalRotAng, moveHand_lr, moveHand_ud)
{
var rotAngle = Math.PI/30;
if (moveHand_lr)
{
if ( diff[0] < -1 )
{
globalRotAng[1] -= rotAngle;
}
if ( diff[0] > 1 )
{
globalRotAng[1] += rotAngle;
}
}
if (moveHand_ud)
{
if ( diff[1] > 1 )
{
globalRotAng[2] -= rotAngle;
}
if ( diff[1] < -1 )
{
globalRotAng[2] += rotAngle;
}
}
// calculate the visualized coordinates
var visGuideCoords = rotateCoords(guide_coords, globalRotAng);
applyRotToAllFingers(fingers, origin_palm, globalRotAng);
return visGuideCoords;
}
// -----------------------------------------------------------
// apply a given rotation to all the fingers in the hand
// -----------------------------------------------------------
function applyRotToAllFingers(fingers, origin_palm, rotAngles)
{
// go through each finger
for (var f = 0; f < fingers.length; ++f)
{
var thisFinger = fingers[f];
// go through each finger point
for (var p = 0; p < thisFinger.points3D.length; ++p)
{
// update the viewer coordinates of each point
var vip = RotVectorAboutOrigin(thisFinger.points3D[p], origin_palm, rotAngles, true);
thisFinger.visPoints[p] = new Vector(vip[0], vip[1], vip[2]);
}
// for the 1st point, we want it located approx 1/3 of the way up the finger
var pt0 = thisFinger.visPoints[1].v;
var pt1 = thisFinger.visPoints[2].v;
vip = [pt1[0] - pt0[0], pt1[1] - pt0[1], pt1[2] - pt0[2]];
thisFinger.visPoints[1] = new Vector(pt0[0] + vip[0] / 3, pt0[1] + vip[1] / 3, pt0[2] + vip[2] / 3);
}
}
// -----------------------------------------------------------
// apply inverse rotation to a point
// -----------------------------------------------------------
function applyInverseRotation(origin_palm, globalRotAngles, pt)
{
var invRotAng = [-globalRotAngles[0], -globalRotAngles[1], -globalRotAngles[2] ];
var inv = RotVectorAboutOrigin(pt, origin_palm, invRotAng);
return inv;
}
// -----------------------------------------------------------
// angle limits, as posed by Winnie Tsang's Master thesis, "Helping
// Hand: An Atomically Accurate Inverse Dynamics Solution for
// Unconstrained Hand Motion," 2005
// -----------------------------------------------------------
function calcMinAndMaxJointAngles(fingerType, isLeft)
{
var minAngles = new Array(4);
var maxAngles = new Array(4);
if (fingerType == 'thumb')
{
minAngles[0] = -10 * Math.PI/180;
maxAngles[0] = 70 * Math.PI/180;
minAngles[1] = -40 * Math.PI/180;
maxAngles[1] = 15 * Math.PI/180;
minAngles[2] = 0;
maxAngles[2] = 50 * Math.PI/180;
minAngles[3] = 0;
maxAngles[3] = 80 * Math.PI/180;
}
else
{
if (fingerType == 'index')
{
minAngles[0] = -20 * Math.PI/180;
maxAngles[0] = 20 * Math.PI/180;
}
else if (fingerType == 'middle')
{
minAngles[0] = -10 * Math.PI/180;
maxAngles[0] = 10 * Math.PI/180;
}
else if (fingerType == 'ring')
{
minAngles[0] = -5 * Math.PI/180;
maxAngles[0] = 15 * Math.PI/180;
}
else
{
minAngles[0] = -5 * Math.PI/180;
maxAngles[0] = 20 * Math.PI/180;
}
minAngles[1] = -10 * Math.PI/180;
maxAngles[1] = 90 * Math.PI/180;
minAngles[2] = 0;
maxAngles[2] = 100 * Math.PI/180;
minAngles[3] = -10 * Math.PI/180;
maxAngles[3] = 90 * Math.PI/180;
}
return [minAngles, maxAngles];
}
// -----------------------------------------------------------
// Finger class - might make things a bit easier? - later!!
// -----------------------------------------------------------
function Finger(origin, numPoints, numPhalanges, heights, fingerType, isLeft)
{
// VARIABLES
this.origin = origin;
this.numPoints = numPoints;
this.numPhalanges = numPhalanges;
this.heights = heights;
this.fingerType = fingerType;
this.isLeft = isLeft;
// initialize the joint angles
this.jointAngles = new Array(numPhalanges);
for (var jointNum = 0; jointNum < this.jointAngles.length; ++jointNum)
{
this.jointAngles[jointNum] = 0;
}
// initialize the manipulator
if (this.fingerType == 'thumb')
{
this.jointAngles[0] = 15 * Math.PI/180;
this.jointAngles[1] = -20 * Math.PI/180;
// different manipulator!
this.manipulator = new ThumbManipulator(origin, numPhalanges, heights, isLeft);
}
else
{
this.manipulator = new Manipulator(origin, numPhalanges, heights, isLeft);
}
// define the 3-dimensional locations of each point along the finger
this.points3D = this.manipulator.recalcManipulator(this.jointAngles);
// define the 2-dimensional locations viewed by the user
this.visPoints = new Array(this.points3D.length);
// FUNCTIONS
this.recalc = function()
{
var jointLimits = calcMinAndMaxJointAngles(this.fingerType, this.isLeft);
for (var j = 0; j < this.jointAngles.length; ++j)
{
if (this.jointAngles[j] < jointLimits[0][j])
{
this.jointAngles[j] = jointLimits[0][j];
}
else if (this.jointAngles[j] > jointLimits[1][j])
{
this.jointAngles[j] = jointLimits[1][j];
}
}
// send the joint angles to the manipulator
this.points3D = this.manipulator.recalcManipulator(this.jointAngles);
// also send the joint angles to the phalanges
// this.phalanges = calcPhalanges(this.numPoints, this.numPhalanges, this.points3D, this.jointAngles);
}
this.reset = function()
{
// set joint angles back to initial values
for (var jointNum = 0; jointNum < this.jointAngles.length; ++jointNum)
{
this.jointAngles[jointNum] = 0;
}
if (this.fingerType == 'thumb')
{
this.jointAngles[0] = 15 * Math.PI/180;
this.jointAngles[1] = -20 * Math.PI/180;
}
// recalculate the manipulator
this.recalc();
}
}
// -----------------------------------------------------------
// create a coordinate system based on an origin and armlength
// -----------------------------------------------------------
function createCoords(origin, lengthOfArm)
{
var x = new Vector(origin.v[0] + lengthOfArm, origin.v[1], origin.v[2]);
var y = new Vector(origin.v[0], origin.v[1] + lengthOfArm, origin.v[2]);
var z = new Vector(origin.v[0], origin.v[1], origin.v[2] + lengthOfArm);
return new Array(origin, x, y, z);
}
// -----------------------------------------------------------
// rotate coordinate system
// -----------------------------------------------------------
function rotateCoords(guide_coords, globalRotationAngles)
{
var visGuideCoords = new Array(guide_coords.length);
for (var i = 1; i < guide_coords.length; ++i)
{
var vgc = RotVectorAboutOrigin(guide_coords[i], guide_coords[0], globalRotationAngles, true);
visGuideCoords[i] = new Vector(vgc[0], vgc[1], vgc[2]);
}
visGuideCoords[0] = new Vector(guide_coords[0].v[0], guide_coords[0].v[1], guide_coords[0].v[2])
return visGuideCoords;
}
// -----------------------------------------------------------
// draws the coordinate orientation guide in the lower
// left-hand corner of the canvas
// -----------------------------------------------------------
function drawCoords(ctx, points)
{
// designate the colors for each point/ray
var colors = new Array("rgb(0,0,0)",
"rgb(200,0,0)",
"rgb(0,0,200)",
"rgb(0,200,0)");
// draw each ray from the origin
var o = points[0].v; // origin
for (var i = 1; i < points.length; ++i)
{
var v = points[i].v; // vector
ctx.fillStyle = colors[0];
ctx.fillRect (o[0],o[1],4,4);
ctx.lineWidth = 2;
ctx.strokeStyle = colors[i];
ctx.fillStyle = colors[i];
ctx.beginPath();
ctx.moveTo(o[0]+2, o[1]+2);
ctx.lineTo(v[0]+2, v[1]+2);
ctx.stroke();
ctx.fillStyle = colors[i];
ctx.fillRect (v[0],v[1],4,4);
}
// draw the box around the guide
// ctx.strokeStyle = colors[0];
// ctx.strokeRect(370,370,30,30);
//
// draw the left-right box
// ctx.strokeRect(0,370,370,30);
//
// draw the up-down box
// ctx.strokeRect(370,0,30,370);
ctx.beginPath();
// draw the left-right arrows
ctx.strokeStyle = "rgb(128,128,128)";
ctx.moveTo(10,385);
ctx.lineTo(20,390);
ctx.moveTo(10,385);
ctx.lineTo(20,380);
ctx.moveTo(10,385);
ctx.lineTo(360,385);
ctx.moveTo(360,385);
ctx.lineTo(350,390);
ctx.moveTo(360,385);
ctx.lineTo(350,380);
// draw the up-down box and arrows
ctx.moveTo(385,10);
ctx.lineTo(390,20);
ctx.moveTo(385,10);
ctx.lineTo(380,20);
ctx.moveTo(385,10);
ctx.lineTo(385,360);
ctx.moveTo(385,360);
ctx.lineTo(390,350);
ctx.moveTo(385,360);
ctx.lineTo(380,350);
ctx.stroke();
}
// -----------------------------------------------------------
// grab mouse coordinates from the window
// -----------------------------------------------------------
function getMouseCoords(event)
{
if (event == null)
{
alert("mouse event resulted in null");
event = window.event;
return null;
}
// NOTE: This is specific to Safari; will need to be changed
// for FF & IE
if (event.offsetX || event.offsetY)
{
var coords = new Vector(event.offsetX, event.offsetY, 0);
return coords.v;
}
return null;
}
// -----------------------------------------------------------
// math.js - math code
// -----------------------------------------------------------
// -----------------------------------------------------------
// Vector class
// -----------------------------------------------------------
function Vector(x, y, z)
{
this.v = new Array(x,y,z,1);
// check to see if the vector is within a given distance to
// a point
this.withinRadiusAroundPoint = function(r, p)
{
var dx = this.v[0] - p[0];
var dy = this.v[1] - p[1];
return (dx * dx + dy * dy) < (r * r);
}
// rotate the vector about an origin
this.rotateAboutOrigin = function(o, rotAngles)
{
var rv = RotVectorAboutOrigin(this.v, o, rotAngles);
for (var i = 0; i < rv.length; ++i)
{
this.v[i] = rv[i];
}
}
// move the vector to another point
this.moveTo = function(p)
{
this.v[0] = p.v[0];
this.v[1] = p.v[1];
this.v[2] = p.v[2];
}
// calculate the distance from another vector
this.distanceFrom = function(b)
{
var sumOfSquares = 0;
for (var i = 0; i < this.v.length; ++i)
{
sumOfSquares += (this.v[i] - b.v[i]) * (this.v[i] - b.v[i]);
}
return Math.sqrt(sumOfSquares);
}
}
// -----------------------------------------------------------
// multiply two matrices together
// -----------------------------------------------------------
function MultiplyMatrices(A,B)
{
var size = A.size;
var m = new SqMat(size);
for (var i = 0; i < size; ++i)
{
for (var j = 0; j < size; ++j)
{
var val = 0;
for (var k = 0; k < size; ++k)
{
val += A.get(i,k) * B.get(k,j);
}
m.set(i, j, val);
}
}
return m;
}
// -----------------------------------------------------------
// Square Matrix class
// -----------------------------------------------------------
function SqMat(size)
{
// initialize the matrix
this.size = size;
this.A = new Array(size);
for (var i = 0; i < size; ++i)
{
this.A[i] = new Array(size);
}
// set values
this.set = function(i,j,val)
{
this.A[i][j] = val;
}
// get values
this.get = function(i,j)
{
return this.A[i][j];
}
// get position info
this.getPos = function()
{
var pos = new Vector(0, 0, 0);
for (var i = 0; i < size-1; ++i)
{
pos.v[i] = this.A[i][size-1];
}
return pos;
}
// mutliply the matrix by another matrix
this.multiplyByMatrix = function(B)
{
var m = MultiplyMatrices(this, B);
this.A = m.A;
}
// multiply the matrix by a vector
this.multiplyByVector = function(v)
{
var vec = new Array(size);
for (var i = 0; i < size; ++i)
{
vec[i] = 0;
for (var k = 0; k < size; ++k)
{
vec[i] += this.A[i][k] * v[k];
}
}
return vec;
}
// determine the transpose of the matrix
this.transpose = function()
{
var T = new Array(size);
for(var i = 0; i < size; ++i)
{
T[i] = new Array(size);
for (var j = 0; j < size; ++j)
{
T[i][j] = this.A[j][i];
}
}
return T;
}
}
// -----------------------------------------------------------
// rotation matrix around the X axis
// -----------------------------------------------------------
function RotX(theta)
{
var R = new SqMat(4);
R.set(0, 0, 1);
R.set(0, 1, 0);
R.set(0, 2, 0);
R.set(0, 3, 0);
R.set(1, 0, 0);
R.set(1, 1, Math.cos(theta));
R.set(1, 2, -Math.sin(theta));
R.set(1, 3, 0);
R.set(2, 0, 0);
R.set(2, 1, Math.sin(theta));
R.set(2, 2, Math.cos(theta));
R.set(2, 3, 0);
R.set(3, 0, 0);
R.set(3, 1, 0);
R.set(3, 2, 0);
R.set(3, 3, 1);
return R;
}
// -----------------------------------------------------------
// rotation matrix around the Y axis
// -----------------------------------------------------------
function RotY(theta)
{
var R = new SqMat(4);
R.set(0, 0, Math.cos(theta));
R.set(0, 1, 0);
R.set(0, 2, Math.sin(theta));
R.set(0, 3, 0);
R.set(1, 0, 0);
R.set(1, 1, 1);
R.set(1, 2, 0);
R.set(1, 3, 0);
R.set(2, 0, -Math.sin(theta));
R.set(2, 1, 0);
R.set(2, 2, Math.cos(theta));
R.set(2, 3, 0);
R.set(3, 0, 0);
R.set(3, 1, 0);
R.set(3, 2, 0);
R.set(3, 3, 1);
return R;
}
// -----------------------------------------------------------
// rotation matrix around the Z axis
// -----------------------------------------------------------
function RotZ(theta)
{
var R = new SqMat(4);
R.set(0, 0, Math.cos(theta));
R.set(0, 1, -Math.sin(theta));
R.set(0, 2, 0);
R.set(0, 3, 0);
R.set(1, 0, Math.sin(theta));
R.set(1, 1, Math.cos(theta));
R.set(1, 2, 0);
R.set(1, 3, 0);
R.set(2, 0, 0);
R.set(2, 1, 0);
R.set(2, 2, 1);
R.set(2, 3, 0);
R.set(3, 0, 0);
R.set(3, 1, 0);
R.set(3, 2, 0);
R.set(3, 3, 1);
return R;
}
// -----------------------------------------------------------
// rotate ZYX
// -----------------------------------------------------------
function Rot(zRotAng, yRotAng, xRotAng)
{
return MultiplyMatrices( MultiplyMatrices(RotZ(zRotAng), RotY(yRotAng)), RotX(xRotAng) );
// return MultiplyMatrices( MultiplyMatrices(RotX(xRotAng), RotY(yRotAng)), RotZ(zRotAng) );
}
// -----------------------------------------------------------
// translation matrix
// -----------------------------------------------------------
function Trans(x,y,z)
{
var R = new SqMat(4);
R.set(0, 0, 1);
R.set(0, 1, 0);
R.set(0, 2, 0);
R.set(0, 3, x);
R.set(1, 0, 0);
R.set(1, 1, 1);
R.set(1, 2, 0);
R.set(1, 3, y);
R.set(2, 0, 0);
R.set(2, 1, 0);
R.set(2, 2, 1);
R.set(2, 3, z);
R.set(3, 0, 0);
R.set(3, 1, 0);
R.set(3, 2, 0);
R.set(3, 3, 1);
return R;
}
// -----------------------------------------------------------
// rotate a vector about a defined origin by angles
// zRotAng (yaw), yRotAng (pitch), xRotAng (roll)
// -----------------------------------------------------------
function RotVectorAboutOrigin(vector, origin, rotAngles, on)
{
var T = Trans(-origin.v[0], -origin.v[1], -origin.v[2]);
var R = MultiplyMatrices( MultiplyMatrices(RotZ(rotAngles[0]), RotY(rotAngles[1])), RotX(rotAngles[2]) );
var Trev = Trans(origin.v[0], origin.v[1], origin.v[2]);
var TRTrev = MultiplyMatrices( Trev, MultiplyMatrices(R, T) );
if (on)
{
return TRTrev.multiplyByVector(vector.v);
}
return TRTrev.multiplyByVector(vector);
}
// -----------------------------------------------------------
// define a manipulator system
// -----------------------------------------------------------
function Manipulator(origin, numJoints, heights, isLeft)
{
// set up the manipulator
this.origin = origin;
this.tipPos;
// recalculate the position of the end effector (fingertip)
this.recalcManipulator = function(jointAngles)
{
// prepare to return the positions of each joint
var pointPositions = new Array(jointAngles+1);
// start at the origin
var T = Trans(this.origin.v[0], this.origin.v[1], this.origin.v[2]);
// orient joint coordinates
T.multiplyByMatrix(RotY(-Math.PI/2));
// apply side-to-side rotation to base
T.multiplyByMatrix(RotX(-Math.PI/2));
if (isLeft)
{
T.multiplyByMatrix(RotZ(jointAngles[0]));
}
else
{
T.multiplyByMatrix(RotZ(-jointAngles[0]));
}
pointPositions[0] = T.getPos();
// rotate for front-to-back rotations for other joints
T.multiplyByMatrix(RotX(Math.PI/2));
pointPositions[1] = T.getPos();
var A;
for (var j = 1; j < jointAngles.length; ++j)
{
A = MultiplyMatrices(RotZ(jointAngles[j]), Trans(heights[j],0,0));
T.multiplyByMatrix(A);
pointPositions[j+1] = T.getPos();
}
// finish with the final positions
this.tipPos = T.getPos();
return pointPositions;
}
this.getPos = function()
{
return this.tipPos;
}
}
// -----------------------------------------------------------
// define a manipulator system specific to thumbs
// -----------------------------------------------------------
function ThumbManipulator(origin, numJoints, heights, isLeft)
{
// set up the manipulator
this.origin = origin;
this.tipPos;
this.isLeft = isLeft;
// recalculate the position of the end effector (fingertip)
this.recalcManipulator = function(jointAngles)
{
var pointPositions = new Array(jointAngles+1);
// start at the origin
var T = Trans(this.origin.v[0], this.origin.v[1], this.origin.v[2]);
// then rotate the origin so that each joint rotates around the z axis
T.multiplyByMatrix(RotY(-Math.PI/2));
T.multiplyByMatrix(RotZ(jointAngles[0]));
pointPositions[0] = T.getPos();
T.multiplyByMatrix(RotX(-Math.PI/2));
// apply the joint angle rotations to each joint
var A;
// var dVals = [0, 10, 15, 10];
var dVals = [0, 0, 0, 0];
pointPositions[1] = T.getPos();
for (var j = 1; j < jointAngles.length; ++j)
{
if (isLeft)
{
A = MultiplyMatrices(RotZ(jointAngles[j]), Trans(0,0,dVals[j-1]));
}
else
{
A = MultiplyMatrices(RotZ(-jointAngles[j]), Trans(0,0,dVals[j-1]));
}
A.multiplyByMatrix(Trans(heights[j],0,0));
T.multiplyByMatrix(A);
pointPositions[j+1] = T.getPos();
}
// finish with the final positions
this.tipPos = T.getPos();
return pointPositions;
}
this.getPos = function()
{
return this.tipPos;
}
}
| rwaldron/vektor | example/public/js/visualizer.js | JavaScript | mit | 52,295 |
(function () {
'use strict';
angular
.module('app')
.factory('config', config);
function config() {
return {
baseApiUrl: "http://localhost:3000/api"
// baseApiUrl: "https://nuflow.herokuapp.com/api"
};
}
})();
| Alberto19/nuflow-web | public/config/config.js | JavaScript | mit | 298 |
namespace WebBlocks.Types.DataContracts
{
public interface ISortable
{
int SortOrder { get; }
}
}
| dyatlov-a/WebBlocks | src/WebBlocks.Types/DataContracts/ISortable.cs | C# | mit | 121 |
#ifndef CALC_CPP
#define CALC_CPP
#include "../include/calc.hpp"
std::unordered_map<std::string, double> Calculator::constants;
int Calculator::get_prim(char*& expr) {
skip_spaces(expr);
bool is_negative = false;
switch (*expr) {
case '+': {
expr++;
break;
}
case '-': {
is_negative = true;
expr++;
break;
}
default:
break;
}
if (*expr == '(') {
expr++;
opened_brackets_cnt++;
int prim = get_expr(expr);
if (*expr != ')') {
std::stringstream err;
err << "Mismached brackets: an extra \"(\"" << endl;
throw std::runtime_error(err.str());
}
expr++;
opened_brackets_cnt--;
return is_negative ? (-prim) : (prim);
}
int prim = 0;
if (is_digit(*expr)) {
do {
prim = 10 * prim + (*expr - '0');
if (value > NumericTraits<int>::max || value < NumericTraits<int>::min) {
cout << "error" << endl;
exit(0);
}
expr++;
} while (is_digit(*expr));
} else if (is_letter(*expr)) {
string s;
do {
s += *expr;
expr++;
} while (is_letter(*expr));
if (constants.find(s) != constants.end()) {
prim = constants[s];
} else {
std::stringstream err;
err << "Constant: \"" << s << "\" is not found" << endl;
throw std::runtime_error(err.str());
}
}
return is_negative ? (-prim) : (prim);
}
int Calculator::get_term(char*& expr) {
int term_1 = get_prim(expr);
while (1) {
skip_spaces(expr);
char op = *expr;
switch (op) {
case '*': {
expr++;
term_1 *= get_prim(expr);
break;
}
case '/': {
expr++;
int term_2 = get_prim(expr);
if (term_2 == 0) {
std::stringstream err;
err << "Division by zero: \"" << term_1 << " / " << term_2 << "\"" << endl;
throw std::runtime_error(err.str());
}
term_1 /= term_2;
break;
}
default:
return term_1;
}
}
}
int Calculator::get_expr(char*& expr) {
int term_1 = get_term(expr);
while (1) {
skip_spaces(expr);
char op = *expr;
switch (op) {
case '+': {
expr++;
term_1 += get_term(expr);
break;
}
case '-': {
expr++;
term_1 -= get_term(expr);
break;
}
default:
return term_1;
}
}
}
int Calculator::eval(char* expr) {
if (*expr == '\0') {
std::stringstream err;
err << "Error: input expression is empty" << endl;
throw std::runtime_error(err.str());
}
opened_brackets_cnt = 0;
int result = get_expr(expr);
if (opened_brackets_cnt != 0 || *expr == ')') {
std::stringstream err;
err << "Mismached brackets: an extra \"" << *expr << "\"" << endl;
throw std::runtime_error(err.str());
}
if (*expr != '\0') {
std::stringstream err;
err << "Invalid character: \"" << *expr << "\"" << endl;
throw std::runtime_error(err.str());
}
return result;
};
#endif
| mtrempoltsev/msu_cpp_autumn_2017 | homework/Kulagin/03/src/calc.cpp | C++ | mit | 2,738 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients', '0010_auto_20151024_2343'),
]
operations = [
migrations.AddField(
model_name='client',
name='napis_id',
field=models.CharField(blank=True, max_length=11, null=True),
),
]
| deafhhs/adapt | clients/migrations/0011_client_napis_id.py | Python | mit | 425 |
package com.zebdar.tom;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
public class DropdownListView extends ListView implements OnScrollListener {
private static final String TAG = "listview";
private final static int RELEASE_To_REFRESH = 0;
private final static int PULL_To_REFRESH = 1;
private final static int REFRESHING = 2;
private final static int DONE = 3;
private final static int LOADING = 4;
// 实际的padding的距离与界面上偏移距离的比例
private final static int RATIO = 3;
private LayoutInflater inflater;
private FrameLayout fl;
private LinearLayout headView;
// private View line;
private ProgressBar progressBar;
// private RotateAnimation animation;
// private RotateAnimation reverseAnimation;
// 用于保证startY的值在一个完整的touch事件中只被记录一次
private boolean isRecored;
private int headContentWidth;
private int headContentHeight;
private int startY;
private int firstItemIndex;
private int state;
private boolean isBack;
private OnRefreshListenerHeader refreshListenerHeader;
private boolean isRefreshableHeader;
public DropdownListView(Context context) {
super(context);
init(context);
}
public DropdownListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
setCacheColorHint(context.getResources().getColor(R.color.transparent));
inflater = LayoutInflater.from(context);
fl = (FrameLayout)inflater.inflate(R.layout.dropdown_lv_head, null);
headView = (LinearLayout) fl.findViewById(R.id.drop_down_head);
progressBar = (ProgressBar) fl.findViewById(R.id.loading);
measureView(headView);
headContentHeight = headView.getMeasuredHeight();
headContentWidth = headView.getMeasuredWidth();
headView.setPadding(0, -1 * headContentHeight, 0, 0);
headView.invalidate();
Log.v("size", "width:" + headContentWidth + " height:"
+ headContentHeight);
addHeaderView(fl, null, false);
// addHeaderView(headView, null, false);
setOnScrollListener(this);
state = DONE;
isRefreshableHeader = false;
}
public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,
int arg3) {
firstItemIndex = firstVisiableItem;
}
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// 判断滚动到底部
}
}
public boolean onTouchEvent(MotionEvent event) {
if (isRefreshableHeader) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstItemIndex == 0 && !isRecored) {
isRecored = true;
startY = (int) event.getY();
Log.v(TAG, "在down时候记录当前位置‘");
}
break;
case MotionEvent.ACTION_UP:
if (state != REFRESHING && state != LOADING) {
if (state == DONE) {
// 什么都不做
}
if (state == PULL_To_REFRESH) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由下拉刷新状态,到done状态");
}
if (state == RELEASE_To_REFRESH) {
state = REFRESHING;
changeHeaderViewByState();
// recoverLine();
onRefresh();
Log.v(TAG, "由松开刷新状态,到done状态");
}
}
isRecored = false;
isBack = false;
break;
case MotionEvent.ACTION_MOVE:
int tempY = (int) event.getY();
if (!isRecored && firstItemIndex == 0) {
Log.v(TAG, "在move时候记录下位置");
isRecored = true;
startY = tempY;
}
if (state != REFRESHING && isRecored && state != LOADING) {
// 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动
// 可以松手去刷新了
if (state == RELEASE_To_REFRESH) {
setSelection(0);
// 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步
if (((tempY - startY) / RATIO < headContentHeight)
&& (tempY - startY) > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");
}
// 一下子推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到done状态");
}
// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步
else {
// 不用进行特别的操作,只用更新paddingTop的值就行了
}
}
// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
if (state == PULL_To_REFRESH) {
setSelection(0);
// 下拉到可以进入RELEASE_TO_REFRESH的状态
if ((tempY - startY) / RATIO >= headContentHeight) {
state = RELEASE_To_REFRESH;
isBack = true;
changeHeaderViewByState();
Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");
}
// 上推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由DOne或者下拉刷新状态转变到done状态");
}
}
// done状态下
if (state == DONE) {
if (tempY - startY > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
}
}
// 更新headView的size
if (state == PULL_To_REFRESH) {
headView.setPadding(0, -1 * headContentHeight
+ (tempY - startY) / RATIO, 0, 0);
}
// 更新headView的paddingTop
if (state == RELEASE_To_REFRESH) {
headView.setPadding(0, (tempY - startY) / RATIO
- headContentHeight, 0, 0);
}
}
break;
}
}
return super.onTouchEvent(event);
}
// 当状态改变时候,调用该方法,以更新界面
private void changeHeaderViewByState() {
switch (state) {
case RELEASE_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,松开刷新");
break;
case PULL_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
// 是由RELEASE_To_REFRESH状态转变来的
if (isBack) {
isBack = false;
} else {
}
Log.v(TAG, "当前状态,下拉刷新");
break;
case REFRESHING:
headView.setPadding(0, 0, 0, 0);
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,正在刷新...");
break;
case DONE:
headView.setPadding(0, -1 * headContentHeight, 0, 0);
progressBar.setVisibility(View.GONE);
Log.v(TAG, "当前状态,done");
break;
}
}
public void setOnRefreshListenerHead(
OnRefreshListenerHeader refreshListenerHeader) {
this.refreshListenerHeader = refreshListenerHeader;
isRefreshableHeader = true;
}
public interface OnRefreshListenerHeader {
public void onRefresh();
}
public interface OnRefreshListenerFooter {
public void onRefresh();
}
public void onRefreshCompleteHeader() {
state = DONE;
changeHeaderViewByState();
}
private void onRefresh() {
if (refreshListenerHeader != null) {
refreshListenerHeader.onRefresh();
}
}
// 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及height
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
}
| cowthan/Ayo2022 | Ayo/app-talker/src/main/java/com/zebdar/tom/DropdownListView.java | Java | mit | 8,410 |
from django import forms
from django_filters.widgets import RangeWidget
class DropDownFilterWidget(forms.widgets.ChoiceWidget):
template_name = 'foirequest/widgets/dropdown_filter.html'
def __init__(self, *args, **kwargs):
self.get_url = kwargs.pop('get_url', None)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None, renderer=None):
value = super(DropDownFilterWidget, self).render(name, value, attrs=attrs, renderer=renderer)
return value
def get_context(self, name, value, attrs):
self.default_label = self.attrs.get('label', '')
self.selected_label = self.default_label
context = super(DropDownFilterWidget, self).get_context(
name, value, attrs
)
context['selected_label'] = self.selected_label
context['default_label'] = self.default_label
return context
def create_option(self, name, value, label, selected, index,
subindex=None, attrs=None):
option = super(DropDownFilterWidget, self).create_option(name, value,
label, selected, index, subindex=subindex, attrs=attrs)
if selected and value:
self.selected_label = label
# Data is set on widget directly before rendering
data = self.data.copy()
data[name] = value
option['url'] = self.get_url(data)
return option
class AttachmentFileWidget(forms.ClearableFileInput):
template_name = 'foirequest/widgets/attachment_file.html'
class DateRangeWidget(RangeWidget):
template_name = 'foirequest/widgets/daterange.html'
def __init__(self):
widgets = [
forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
forms.DateInput(attrs={'class': 'form-control', 'type': 'date'})
]
super(RangeWidget, self).__init__(widgets)
| stefanw/froide | froide/foirequest/widgets.py | Python | mit | 1,895 |
package com.gulj.app.admin.config;
import com.gulj.entity.common.bo.JoinAnnotationBeanNameGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value = "classpath:config/mybatis.properties")
@ComponentScan(basePackages = {"com.gulj.app.admin.biz.service"}, nameGenerator = JoinAnnotationBeanNameGenerator.class)
@MapperScan(basePackages = "com.gulj.app.admin.biz.mapper")
public class AdminBizConfig {
/* private final static Logger logger = LoggerFactory.getLogger(AdminBizConfig.class);
@Autowired
private DataSourceProperties dataSourceProperties;
@Bean
public String getStr() {
logger.info("++++加载的数据源信息 url:{}", dataSourceProperties.getUrl());
return "ok";
}*/
}
| gulijian/joingu | gulj-app-admin-biz/src/main/java/com/gulj/app/admin/config/AdminBizConfig.java | Java | mit | 952 |
<?php
namespace Kernel\Snmp;
use Kernel\Interfaces\OltInterface;
/**
* @ This class work with only zte olt
* @author Xeleniumz Fx
* @version 1.1
* @date 2/3/2017
* */
class Olt implements OltInterface
{
private $olt_name = '1.3.6.1.2.1.1.5.0';
private $snmp_get_octet = '1.3.6.1.2.1.2.2.1.1';
private $gpon_name ='1.3.6.1.2.1.2.2.1.2';
private $gpon_status = '1.3.6.1.2.1.2.2.1.8';
private $gpon_uptime = '1.3.6.1.2.1.1.3.0';
private $community = 'public';
public function __construct()
{
$this->olt_name = '1.3.6.1.2.1.1.5.0';
$this->snmp_get_octet = '1.3.6.1.2.1.2.2.1.1';
$this->gpon_name ='1.3.6.1.2.1.2.2.1.2';
$this->gpon_status = '1.3.6.1.2.1.2.2.1.8';
$this->gpon_uptime = '1.3.6.1.2.1.1.3.0';
$this->community = 'public';
}
public function getOltName($ip) :string
{
$name = snmpwalk($ip, $this->community, $this->olt_name);
return $name;
}
public function getOltId($ip) :int
{
$id = snmpwalk($ip, $this->community, $this->snmp_get_octet);
return $id;
}
public function getOltSolt($ip,$id) :array
{
$data = $this->gpon_name.'.'.$id;
$rs = snmpwalk($ip,$this->community,$data);
return $rs;
}
public function getOltStatus($ip,$id,$check=FALSE) :string
{
if($check == TRUE){
$data = $this->gpon_status.'.'.$id;
$rs = snmpwalk($ip,$this->community,$data);
$rs = explode(' ', $rs[0]);
return $rs[1];
}else{
$data = $this->gpon_status.'.'.$id;
$rs = snmpwalk($ip,$this->community,$data);
$rs = explode(' ', $rs[0]);
$res = ($rs[1] == '1') ? 'ONLINE':'OFFLINE';
return $res;
}
}
public function checkGpon($val) :string
{
$v = explode('"', $val);
$g = explode('_', $v[1]);
$rs['chk'] = ($g[0] == 'gpon') ? TRUE:FALSE;
$rs['gpon'] = $v[1];
return $rs;
}
public function getUptime($ip) :string
{
$uptime = snmpwalk($ip,$this->community,$this->gpon_uptime);
return $uptime;
}
}
| xeleniumz/zte-libraries-php | Kernel/Snmp/Olt.php | PHP | mit | 1,896 |
from ..operations import Operations
from .migration import MigrationContext
from .. import util
class EnvironmentContext(util.ModuleClsProxy):
"""A configurational facade made available in an ``env.py`` script.
The :class:`.EnvironmentContext` acts as a *facade* to the more
nuts-and-bolts objects of :class:`.MigrationContext` as well as certain
aspects of :class:`.Config`,
within the context of the ``env.py`` script that is invoked by
most Alembic commands.
:class:`.EnvironmentContext` is normally instantiated
when a command in :mod:`alembic.command` is run. It then makes
itself available in the ``alembic.context`` module for the scope
of the command. From within an ``env.py`` script, the current
:class:`.EnvironmentContext` is available by importing this module.
:class:`.EnvironmentContext` also supports programmatic usage.
At this level, it acts as a Python context manager, that is, is
intended to be used using the
``with:`` statement. A typical use of :class:`.EnvironmentContext`::
from alembic.config import Config
from alembic.script import ScriptDirectory
config = Config()
config.set_main_option("script_location", "myapp:migrations")
script = ScriptDirectory.from_config(config)
def my_function(rev, context):
'''do something with revision "rev", which
will be the current database revision,
and "context", which is the MigrationContext
that the env.py will create'''
with EnvironmentContext(
config,
script,
fn = my_function,
as_sql = False,
starting_rev = 'base',
destination_rev = 'head',
tag = "sometag"
):
script.run_env()
The above script will invoke the ``env.py`` script
within the migration environment. If and when ``env.py``
calls :meth:`.MigrationContext.run_migrations`, the
``my_function()`` function above will be called
by the :class:`.MigrationContext`, given the context
itself as well as the current revision in the database.
.. note::
For most API usages other than full blown
invocation of migration scripts, the :class:`.MigrationContext`
and :class:`.ScriptDirectory` objects can be created and
used directly. The :class:`.EnvironmentContext` object
is *only* needed when you need to actually invoke the
``env.py`` module present in the migration environment.
"""
_migration_context = None
config = None
"""An instance of :class:`.Config` representing the
configuration file contents as well as other variables
set programmatically within it."""
script = None
"""An instance of :class:`.ScriptDirectory` which provides
programmatic access to version files within the ``versions/``
directory.
"""
def __init__(self, config, script, **kw):
"""Construct a new :class:`.EnvironmentContext`.
:param config: a :class:`.Config` instance.
:param script: a :class:`.ScriptDirectory` instance.
:param \**kw: keyword options that will be ultimately
passed along to the :class:`.MigrationContext` when
:meth:`.EnvironmentContext.configure` is called.
"""
self.config = config
self.script = script
self.context_opts = kw
def __enter__(self):
"""Establish a context which provides a
:class:`.EnvironmentContext` object to
env.py scripts.
The :class:`.EnvironmentContext` will
be made available as ``from alembic import context``.
"""
self._install_proxy()
return self
def __exit__(self, *arg, **kw):
self._remove_proxy()
def is_offline_mode(self):
"""Return True if the current migrations environment
is running in "offline mode".
This is ``True`` or ``False`` depending
on the the ``--sql`` flag passed.
This function does not require that the :class:`.MigrationContext`
has been configured.
"""
return self.context_opts.get('as_sql', False)
def is_transactional_ddl(self):
"""Return True if the context is configured to expect a
transactional DDL capable backend.
This defaults to the type of database in use, and
can be overridden by the ``transactional_ddl`` argument
to :meth:`.configure`
This function requires that a :class:`.MigrationContext`
has first been made available via :meth:`.configure`.
"""
return self.get_context().impl.transactional_ddl
def requires_connection(self):
return not self.is_offline_mode()
def get_head_revision(self):
"""Return the hex identifier of the 'head' script revision.
If the script directory has multiple heads, this
method raises a :class:`.CommandError`;
:meth:`.EnvironmentContext.get_head_revisions` should be preferred.
This function does not require that the :class:`.MigrationContext`
has been configured.
.. seealso:: :meth:`.EnvironmentContext.get_head_revisions`
"""
return self.script.as_revision_number("head")
def get_head_revisions(self):
"""Return the hex identifier of the 'heads' script revision(s).
This returns a tuple containing the version number of all
heads in the script directory.
This function does not require that the :class:`.MigrationContext`
has been configured.
.. versionadded:: 0.7.0
"""
return self.script.as_revision_number("heads")
def get_starting_revision_argument(self):
"""Return the 'starting revision' argument,
if the revision was passed using ``start:end``.
This is only meaningful in "offline" mode.
Returns ``None`` if no value is available
or was configured.
This function does not require that the :class:`.MigrationContext`
has been configured.
"""
if self._migration_context is not None:
return self.script.as_revision_number(
self.get_context()._start_from_rev)
elif 'starting_rev' in self.context_opts:
return self.script.as_revision_number(
self.context_opts['starting_rev'])
else:
# this should raise only in the case that a command
# is being run where the "starting rev" is never applicable;
# this is to catch scripts which rely upon this in
# non-sql mode or similar
raise util.CommandError(
"No starting revision argument is available.")
def get_revision_argument(self):
"""Get the 'destination' revision argument.
This is typically the argument passed to the
``upgrade`` or ``downgrade`` command.
If it was specified as ``head``, the actual
version number is returned; if specified
as ``base``, ``None`` is returned.
This function does not require that the :class:`.MigrationContext`
has been configured.
"""
return self.script.as_revision_number(
self.context_opts['destination_rev'])
def get_tag_argument(self):
"""Return the value passed for the ``--tag`` argument, if any.
The ``--tag`` argument is not used directly by Alembic,
but is available for custom ``env.py`` configurations that
wish to use it; particularly for offline generation scripts
that wish to generate tagged filenames.
This function does not require that the :class:`.MigrationContext`
has been configured.
.. seealso::
:meth:`.EnvironmentContext.get_x_argument` - a newer and more
open ended system of extending ``env.py`` scripts via the command
line.
"""
return self.context_opts.get('tag', None)
def get_x_argument(self, as_dictionary=False):
"""Return the value(s) passed for the ``-x`` argument, if any.
The ``-x`` argument is an open ended flag that allows any user-defined
value or values to be passed on the command line, then available
here for consumption by a custom ``env.py`` script.
The return value is a list, returned directly from the ``argparse``
structure. If ``as_dictionary=True`` is passed, the ``x`` arguments
are parsed using ``key=value`` format into a dictionary that is
then returned.
For example, to support passing a database URL on the command line,
the standard ``env.py`` script can be modified like this::
cmd_line_url = context.get_x_argument(
as_dictionary=True).get('dbname')
if cmd_line_url:
engine = create_engine(cmd_line_url)
else:
engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
This then takes effect by running the ``alembic`` script as::
alembic -x dbname=postgresql://user:pass@host/dbname upgrade head
This function does not require that the :class:`.MigrationContext`
has been configured.
.. versionadded:: 0.6.0
.. seealso::
:meth:`.EnvironmentContext.get_tag_argument`
:attr:`.Config.cmd_opts`
"""
if self.config.cmd_opts is not None:
value = self.config.cmd_opts.x or []
else:
value = []
if as_dictionary:
value = dict(
arg.split('=', 1) for arg in value
)
return value
def configure(self,
connection=None,
url=None,
dialect_name=None,
transactional_ddl=None,
transaction_per_migration=False,
output_buffer=None,
starting_rev=None,
tag=None,
template_args=None,
render_as_batch=False,
target_metadata=None,
include_symbol=None,
include_object=None,
include_schemas=False,
process_revision_directives=None,
compare_type=False,
compare_server_default=False,
render_item=None,
literal_binds=False,
upgrade_token="upgrades",
downgrade_token="downgrades",
alembic_module_prefix="op.",
sqlalchemy_module_prefix="sa.",
user_module_prefix=None,
**kw
):
"""Configure a :class:`.MigrationContext` within this
:class:`.EnvironmentContext` which will provide database
connectivity and other configuration to a series of
migration scripts.
Many methods on :class:`.EnvironmentContext` require that
this method has been called in order to function, as they
ultimately need to have database access or at least access
to the dialect in use. Those which do are documented as such.
The important thing needed by :meth:`.configure` is a
means to determine what kind of database dialect is in use.
An actual connection to that database is needed only if
the :class:`.MigrationContext` is to be used in
"online" mode.
If the :meth:`.is_offline_mode` function returns ``True``,
then no connection is needed here. Otherwise, the
``connection`` parameter should be present as an
instance of :class:`sqlalchemy.engine.Connection`.
This function is typically called from the ``env.py``
script within a migration environment. It can be called
multiple times for an invocation. The most recent
:class:`~sqlalchemy.engine.Connection`
for which it was called is the one that will be operated upon
by the next call to :meth:`.run_migrations`.
General parameters:
:param connection: a :class:`~sqlalchemy.engine.Connection`
to use
for SQL execution in "online" mode. When present, is also
used to determine the type of dialect in use.
:param url: a string database url, or a
:class:`sqlalchemy.engine.url.URL` object.
The type of dialect to be used will be derived from this if
``connection`` is not passed.
:param dialect_name: string name of a dialect, such as
"postgresql", "mssql", etc.
The type of dialect to be used will be derived from this if
``connection`` and ``url`` are not passed.
:param transactional_ddl: Force the usage of "transactional"
DDL on or off;
this otherwise defaults to whether or not the dialect in
use supports it.
:param transaction_per_migration: if True, nest each migration script
in a transaction rather than the full series of migrations to
run.
.. versionadded:: 0.6.5
:param output_buffer: a file-like object that will be used
for textual output
when the ``--sql`` option is used to generate SQL scripts.
Defaults to
``sys.stdout`` if not passed here and also not present on
the :class:`.Config`
object. The value here overrides that of the :class:`.Config`
object.
:param output_encoding: when using ``--sql`` to generate SQL
scripts, apply this encoding to the string output.
:param literal_binds: when using ``--sql`` to generate SQL
scripts, pass through the ``literal_binds`` flag to the compiler
so that any literal values that would ordinarily be bound
parameters are converted to plain strings.
.. warning:: Dialects can typically only handle simple datatypes
like strings and numbers for auto-literal generation. Datatypes
like dates, intervals, and others may still require manual
formatting, typically using :meth:`.Operations.inline_literal`.
.. note:: the ``literal_binds`` flag is ignored on SQLAlchemy
versions prior to 0.8 where this feature is not supported.
.. versionadded:: 0.7.6
.. seealso::
:meth:`.Operations.inline_literal`
:param starting_rev: Override the "starting revision" argument
when using ``--sql`` mode.
:param tag: a string tag for usage by custom ``env.py`` scripts.
Set via the ``--tag`` option, can be overridden here.
:param template_args: dictionary of template arguments which
will be added to the template argument environment when
running the "revision" command. Note that the script environment
is only run within the "revision" command if the --autogenerate
option is used, or if the option "revision_environment=true"
is present in the alembic.ini file.
:param version_table: The name of the Alembic version table.
The default is ``'alembic_version'``.
:param version_table_schema: Optional schema to place version
table within.
Parameters specific to the autogenerate feature, when
``alembic revision`` is run with the ``--autogenerate`` feature:
:param target_metadata: a :class:`sqlalchemy.schema.MetaData`
object that
will be consulted during autogeneration. The tables present
will be compared against
what is locally available on the target
:class:`~sqlalchemy.engine.Connection`
to produce candidate upgrade/downgrade operations.
:param compare_type: Indicates type comparison behavior during
an autogenerate
operation. Defaults to ``False`` which disables type
comparison. Set to
``True`` to turn on default type comparison, which has varied
accuracy depending on backend. See :ref:`compare_types`
for an example as well as information on other type
comparison options.
.. seealso::
:ref:`compare_types`
:paramref:`.EnvironmentContext.configure.compare_server_default`
:param compare_server_default: Indicates server default comparison
behavior during
an autogenerate operation. Defaults to ``False`` which disables
server default
comparison. Set to ``True`` to turn on server default comparison,
which has
varied accuracy depending on backend.
To customize server default comparison behavior, a callable may
be specified
which can filter server default comparisons during an
autogenerate operation.
defaults during an autogenerate operation. The format of this
callable is::
def my_compare_server_default(context, inspected_column,
metadata_column, inspected_default, metadata_default,
rendered_metadata_default):
# return True if the defaults are different,
# False if not, or None to allow the default implementation
# to compare these defaults
return None
context.configure(
# ...
compare_server_default = my_compare_server_default
)
``inspected_column`` is a dictionary structure as returned by
:meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas
``metadata_column`` is a :class:`sqlalchemy.schema.Column` from
the local model environment.
A return value of ``None`` indicates to allow default server default
comparison
to proceed. Note that some backends such as Postgresql actually
execute
the two defaults on the database side to compare for equivalence.
.. seealso::
:paramref:`.EnvironmentContext.configure.compare_type`
:param include_object: A callable function which is given
the chance to return ``True`` or ``False`` for any object,
indicating if the given object should be considered in the
autogenerate sweep.
The function accepts the following positional arguments:
* ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such
as a :class:`~sqlalchemy.schema.Table`,
:class:`~sqlalchemy.schema.Column`,
:class:`~sqlalchemy.schema.Index`
:class:`~sqlalchemy.schema.UniqueConstraint`,
or :class:`~sqlalchemy.schema.ForeignKeyConstraint` object
* ``name``: the name of the object. This is typically available
via ``object.name``.
* ``type``: a string describing the type of object; currently
``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``,
or ``"foreign_key_constraint"``
.. versionadded:: 0.7.0 Support for indexes and unique constraints
within the
:paramref:`~.EnvironmentContext.configure.include_object` hook.
.. versionadded:: 0.7.1 Support for foreign keys within the
:paramref:`~.EnvironmentContext.configure.include_object` hook.
* ``reflected``: ``True`` if the given object was produced based on
table reflection, ``False`` if it's from a local :class:`.MetaData`
object.
* ``compare_to``: the object being compared against, if available,
else ``None``.
E.g.::
def include_object(object, name, type_, reflected, compare_to):
if (type_ == "column" and
not reflected and
object.info.get("skip_autogenerate", False)):
return False
else:
return True
context.configure(
# ...
include_object = include_object
)
:paramref:`.EnvironmentContext.configure.include_object` can also
be used to filter on specific schemas to include or omit, when
the :paramref:`.EnvironmentContext.configure.include_schemas`
flag is set to ``True``. The :attr:`.Table.schema` attribute
on each :class:`.Table` object reflected will indicate the name of the
schema from which the :class:`.Table` originates.
.. versionadded:: 0.6.0
.. seealso::
:paramref:`.EnvironmentContext.configure.include_schemas`
:param include_symbol: A callable function which, given a table name
and schema name (may be ``None``), returns ``True`` or ``False``,
indicating if the given table should be considered in the
autogenerate sweep.
.. deprecated:: 0.6.0
:paramref:`.EnvironmentContext.configure.include_symbol`
is superceded by the more generic
:paramref:`.EnvironmentContext.configure.include_object`
parameter.
E.g.::
def include_symbol(tablename, schema):
return tablename not in ("skip_table_one", "skip_table_two")
context.configure(
# ...
include_symbol = include_symbol
)
.. seealso::
:paramref:`.EnvironmentContext.configure.include_schemas`
:paramref:`.EnvironmentContext.configure.include_object`
:param render_as_batch: if True, commands which alter elements
within a table will be placed under a ``with batch_alter_table():``
directive, so that batch migrations will take place.
.. versionadded:: 0.7.0
.. seealso::
:ref:`batch_migrations`
:param include_schemas: If True, autogenerate will scan across
all schemas located by the SQLAlchemy
:meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names`
method, and include all differences in tables found across all
those schemas. When using this option, you may want to also
use the :paramref:`.EnvironmentContext.configure.include_object`
option to specify a callable which
can filter the tables/schemas that get included.
.. seealso::
:paramref:`.EnvironmentContext.configure.include_object`
:param render_item: Callable that can be used to override how
any schema item, i.e. column, constraint, type,
etc., is rendered for autogenerate. The callable receives a
string describing the type of object, the object, and
the autogen context. If it returns False, the
default rendering method will be used. If it returns None,
the item will not be rendered in the context of a Table
construct, that is, can be used to skip columns or constraints
within op.create_table()::
def my_render_column(type_, col, autogen_context):
if type_ == "column" and isinstance(col, MySpecialCol):
return repr(col)
else:
return False
context.configure(
# ...
render_item = my_render_column
)
Available values for the type string include: ``"column"``,
``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``,
``"type"``, ``"server_default"``.
.. seealso::
:ref:`autogen_render_types`
:param upgrade_token: When autogenerate completes, the text of the
candidate upgrade operations will be present in this template
variable when ``script.py.mako`` is rendered. Defaults to
``upgrades``.
:param downgrade_token: When autogenerate completes, the text of the
candidate downgrade operations will be present in this
template variable when ``script.py.mako`` is rendered. Defaults to
``downgrades``.
:param alembic_module_prefix: When autogenerate refers to Alembic
:mod:`alembic.operations` constructs, this prefix will be used
(i.e. ``op.create_table``) Defaults to "``op.``".
Can be ``None`` to indicate no prefix.
:param sqlalchemy_module_prefix: When autogenerate refers to
SQLAlchemy
:class:`~sqlalchemy.schema.Column` or type classes, this prefix
will be used
(i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``".
Can be ``None`` to indicate no prefix.
Note that when dialect-specific types are rendered, autogenerate
will render them using the dialect module name, i.e. ``mssql.BIT()``,
``postgresql.UUID()``.
:param user_module_prefix: When autogenerate refers to a SQLAlchemy
type (e.g. :class:`.TypeEngine`) where the module name is not
under the ``sqlalchemy`` namespace, this prefix will be used
within autogenerate. If left at its default of
``None``, the ``__module__`` attribute of the type is used to
render the import module. It's a good practice to set this
and to have all custom types be available from a fixed module space,
in order to future-proof migration files against reorganizations
in modules.
.. versionchanged:: 0.7.0
:paramref:`.EnvironmentContext.configure.user_module_prefix`
no longer defaults to the value of
:paramref:`.EnvironmentContext.configure.sqlalchemy_module_prefix`
when left at ``None``; the ``__module__`` attribute is now used.
.. versionadded:: 0.6.3 added
:paramref:`.EnvironmentContext.configure.user_module_prefix`
.. seealso::
:ref:`autogen_module_prefix`
:param process_revision_directives: a callable function that will
be passed a structure representing the end result of an autogenerate
or plain "revision" operation, which can be manipulated to affect
how the ``alembic revision`` command ultimately outputs new
revision scripts. The structure of the callable is::
def process_revision_directives(context, revision, directives):
pass
The ``directives`` parameter is a Python list containing
a single :class:`.MigrationScript` directive, which represents
the revision file to be generated. This list as well as its
contents may be freely modified to produce any set of commands.
The section :ref:`customizing_revision` shows an example of
doing this. The ``context`` parameter is the
:class:`.MigrationContext` in use,
and ``revision`` is a tuple of revision identifiers representing the
current revision of the database.
The callable is invoked at all times when the ``--autogenerate``
option is passed to ``alembic revision``. If ``--autogenerate``
is not passed, the callable is invoked only if the
``revision_environment`` variable is set to True in the Alembic
configuration, in which case the given ``directives`` collection
will contain empty :class:`.UpgradeOps` and :class:`.DowngradeOps`
collections for ``.upgrade_ops`` and ``.downgrade_ops``. The
``--autogenerate`` option itself can be inferred by inspecting
``context.config.cmd_opts.autogenerate``.
The callable function may optionally be an instance of
a :class:`.Rewriter` object. This is a helper object that
assists in the production of autogenerate-stream rewriter functions.
.. versionadded:: 0.8.0
.. seealso::
:ref:`customizing_revision`
:ref:`autogen_rewriter`
Parameters specific to individual backends:
:param mssql_batch_separator: The "batch separator" which will
be placed between each statement when generating offline SQL Server
migrations. Defaults to ``GO``. Note this is in addition to the
customary semicolon ``;`` at the end of each statement; SQL Server
considers the "batch separator" to denote the end of an
individual statement execution, and cannot group certain
dependent operations in one step.
:param oracle_batch_separator: The "batch separator" which will
be placed between each statement when generating offline
Oracle migrations. Defaults to ``/``. Oracle doesn't add a
semicolon between statements like most other backends.
"""
opts = self.context_opts
if transactional_ddl is not None:
opts["transactional_ddl"] = transactional_ddl
if output_buffer is not None:
opts["output_buffer"] = output_buffer
elif self.config.output_buffer is not None:
opts["output_buffer"] = self.config.output_buffer
if starting_rev:
opts['starting_rev'] = starting_rev
if tag:
opts['tag'] = tag
if template_args and 'template_args' in opts:
opts['template_args'].update(template_args)
opts["transaction_per_migration"] = transaction_per_migration
opts['target_metadata'] = target_metadata
opts['include_symbol'] = include_symbol
opts['include_object'] = include_object
opts['include_schemas'] = include_schemas
opts['render_as_batch'] = render_as_batch
opts['upgrade_token'] = upgrade_token
opts['downgrade_token'] = downgrade_token
opts['sqlalchemy_module_prefix'] = sqlalchemy_module_prefix
opts['alembic_module_prefix'] = alembic_module_prefix
opts['user_module_prefix'] = user_module_prefix
opts['literal_binds'] = literal_binds
opts['process_revision_directives'] = process_revision_directives
if render_item is not None:
opts['render_item'] = render_item
if compare_type is not None:
opts['compare_type'] = compare_type
if compare_server_default is not None:
opts['compare_server_default'] = compare_server_default
opts['script'] = self.script
opts.update(kw)
self._migration_context = MigrationContext.configure(
connection=connection,
url=url,
dialect_name=dialect_name,
environment_context=self,
opts=opts
)
def run_migrations(self, **kw):
"""Run migrations as determined by the current command line
configuration
as well as versioning information present (or not) in the current
database connection (if one is present).
The function accepts optional ``**kw`` arguments. If these are
passed, they are sent directly to the ``upgrade()`` and
``downgrade()``
functions within each target revision file. By modifying the
``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()``
functions accept arguments, parameters can be passed here so that
contextual information, usually information to identify a particular
database in use, can be passed from a custom ``env.py`` script
to the migration functions.
This function requires that a :class:`.MigrationContext` has
first been made available via :meth:`.configure`.
"""
with Operations.context(self._migration_context):
self.get_context().run_migrations(**kw)
def execute(self, sql, execution_options=None):
"""Execute the given SQL using the current change context.
The behavior of :meth:`.execute` is the same
as that of :meth:`.Operations.execute`. Please see that
function's documentation for full detail including
caveats and limitations.
This function requires that a :class:`.MigrationContext` has
first been made available via :meth:`.configure`.
"""
self.get_context().execute(sql,
execution_options=execution_options)
def static_output(self, text):
"""Emit text directly to the "offline" SQL stream.
Typically this is for emitting comments that
start with --. The statement is not treated
as a SQL execution, no ; or batch separator
is added, etc.
"""
self.get_context().impl.static_output(text)
def begin_transaction(self):
"""Return a context manager that will
enclose an operation within a "transaction",
as defined by the environment's offline
and transactional DDL settings.
e.g.::
with context.begin_transaction():
context.run_migrations()
:meth:`.begin_transaction` is intended to
"do the right thing" regardless of
calling context:
* If :meth:`.is_transactional_ddl` is ``False``,
returns a "do nothing" context manager
which otherwise produces no transactional
state or directives.
* If :meth:`.is_offline_mode` is ``True``,
returns a context manager that will
invoke the :meth:`.DefaultImpl.emit_begin`
and :meth:`.DefaultImpl.emit_commit`
methods, which will produce the string
directives ``BEGIN`` and ``COMMIT`` on
the output stream, as rendered by the
target backend (e.g. SQL Server would
emit ``BEGIN TRANSACTION``).
* Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin`
on the current online connection, which
returns a :class:`sqlalchemy.engine.Transaction`
object. This object demarcates a real
transaction and is itself a context manager,
which will roll back if an exception
is raised.
Note that a custom ``env.py`` script which
has more specific transactional needs can of course
manipulate the :class:`~sqlalchemy.engine.Connection`
directly to produce transactional state in "online"
mode.
"""
return self.get_context().begin_transaction()
def get_context(self):
"""Return the current :class:`.MigrationContext` object.
If :meth:`.EnvironmentContext.configure` has not been
called yet, raises an exception.
"""
if self._migration_context is None:
raise Exception("No context has been configured yet.")
return self._migration_context
def get_bind(self):
"""Return the current 'bind'.
In "online" mode, this is the
:class:`sqlalchemy.engine.Connection` currently being used
to emit SQL to the database.
This function requires that a :class:`.MigrationContext`
has first been made available via :meth:`.configure`.
"""
return self.get_context().bind
def get_impl(self):
return self.get_context().impl
| graingert/alembic | alembic/runtime/environment.py | Python | mit | 35,396 |
<?php
echo "This feature is under construction";
?> | mjcurry/LinkStor | directory.php | PHP | mit | 53 |
using Leak.Common;
namespace Leak.Listener
{
public class PeerListenerHandshake
{
private readonly Handshake handshake;
public PeerListenerHandshake(Handshake handshake)
{
this.handshake = handshake;
}
public bool HasExtensions
{
get { return handshake.Options.HasFlag(HandshakeOptions.Extended); }
}
}
} | amacal/leak | sources/Leak.Listener/PeerListenerHandshake.cs | C# | mit | 402 |
RSpec.describe CharactersController do
include ActiveJob::TestHelper
describe "GET index" do
let(:user) { create(:user) }
it "requires login without an id" do
get :index
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "requires valid id" do
get :index, params: { user_id: -1 }
expect(response).to redirect_to(users_url)
expect(flash[:error]).to eq("User could not be found.")
end
it "succeeds with an id" do
get :index, params: { user_id: user.id }
expect(response.status).to eq(200)
end
it "succeeds when logged in" do
login
get :index
expect(response.status).to eq(200)
end
it "succeeds with an id when logged in" do
login
get :index, params: { user_id: user.id }
expect(response.status).to eq(200)
end
it "succeeds with character group" do
group = create(:character_group, user: user)
create_list(:character, 3, character_group: group, user: user)
get :index, params: { user_id: user.id, group_id: group.id }
expect(response.status).to eq(200)
end
context "with render_views" do
render_views
it "successfully renders the page in template group" do
character = create(:character)
create(:template_character, user: character.user) # character2
get :index, params: { user_id: character.user_id, character_split: 'template' }
expect(response.status).to eq(200)
end
it "successfully renders the page with no group" do
character = create(:character)
create(:template_character, user: character.user) # character2
get :index, params: { user_id: character.user_id, character_split: 'none' }
expect(response.status).to eq(200)
end
it "skips retired characters when specified" do
character = create(:character, name: 'ExistingCharacter')
create(:character, user: character.user, retired: true, name: 'RetiredCharacter')
get :index, params: { user_id: character.user_id, retired: 'false' }
expect(response.body).to include('ExistingCharacter')
expect(response.body).not_to include('RetiredCharacter')
end
end
end
describe "GET new" do
it "requires login" do
get :new
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "succeeds when logged in" do
login
get :new
expect(response.status).to eq(200)
end
it "sets correct variables with template_id" do
template = create(:template)
login_as(template.user)
get :new, params: { template_id: template.id }
expect(response.status).to eq(200)
expect(assigns(:character).template).to eq(template)
end
context "with views" do
render_views
it "sets correct variables" do
user = create(:user)
templates = Array.new(2) { create(:template, user: user) }
create(:template)
login_as(user)
get :new
expect(assigns(:page_title)).to eq("New Character")
expect(assigns(:templates).map(&:name)).to match_array(templates.map(&:name))
expect(controller.gon.character_id).to eq('')
expect(controller.gon.user_id).to eq(user.id)
expect(controller.gon.gallery_groups).to eq([])
expect(assigns(:aliases)).to be_blank
end
end
end
describe "POST create" do
it "requires login" do
post :create
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "fails with missing params" do
login
post :create
expect(response.status).to eq(200)
expect(flash[:error][:message]).to eq("Your character could not be saved.")
end
it "fails with invalid params" do
login
post :create, params: { character: {} }
expect(response.status).to eq(200)
expect(flash[:error][:message]).to eq("Your character could not be saved.")
end
it "succeeds when valid" do
expect(Character.count).to eq(0)
test_name = 'Test character'
user = create(:user)
template = create(:template, user: user)
gallery = create(:gallery, user: user)
setting = create(:setting, user: user, name: 'A World')
login_as(user)
post :create, params: {
character: {
name: test_name,
nickname: 'TempName',
screenname: 'just-a-test',
setting_ids: [setting.id],
template_id: template.id,
pb: 'Facecast',
description: 'Desc',
ungrouped_gallery_ids: [gallery.id],
},
}
expect(response).to redirect_to(assigns(:character))
expect(flash[:success]).to eq("Character saved successfully.")
expect(Character.count).to eq(1)
character = assigns(:character).reload
expect(character.name).to eq(test_name)
expect(character.user_id).to eq(user.id)
expect(character.nickname).to eq('TempName')
expect(character.screenname).to eq('just-a-test')
expect(character.settings.pluck(:name)).to eq(['A World'])
expect(character.template).to eq(template)
expect(character.pb).to eq('Facecast')
expect(character.description).to eq('Desc')
expect(character.galleries).to match_array([gallery])
end
it "creates new templates when specified" do
expect(Template.count).to eq(0)
login
post :create, params: {
new_template: '1',
character: {
template_attributes: {
name: 'TemplateTest',
},
name: 'Test',
},
}
expect(Template.count).to eq(1)
expect(Template.first.name).to eq('TemplateTest')
expect(assigns(:character).template_id).to eq(Template.first.id)
end
context "with views" do
render_views
it "sets correct variables when invalid" do
user = create(:user)
gallery = create(:gallery, user: user)
group = create(:gallery_group)
group_gallery = create(:gallery, user: user, gallery_groups: [group])
templates = Array.new(2) { create(:template, user: user) }
create(:template)
login_as(user)
post :create, params: {
character: {
ungrouped_gallery_ids: [gallery.id, group_gallery.id],
gallery_group_ids: [group.id],
},
}
expect(response).to render_template(:new)
expect(controller.gon.character_id).to eq('')
expect(assigns(:templates).map(&:name)).to match_array(templates.map(&:name))
expect(assigns(:character).ungrouped_gallery_ids).to match_array([gallery.id, group_gallery.id])
expect(assigns(:character).gallery_group_ids).to eq([group.id])
end
end
end
describe "GET show" do
it "requires valid character logged out" do
get :show, params: { id: -1 }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("Character could not be found.")
end
it "requires valid character logged in" do
user_id = login
get :show, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("Character could not be found.")
end
it "should succeed when logged out" do
character = create(:character)
get :show, params: { id: character.id }
expect(response.status).to eq(200)
end
it "should succeed when logged in" do
character = create(:character)
login
get :show, params: { id: character.id }
expect(response.status).to eq(200)
end
it "should set correct variables" do
character = create(:character)
Array.new(26) { create(:post, character: character, user: character.user) }
get :show, params: { id: character.id }
expect(response.status).to eq(200)
expect(assigns(:page_title)).to eq(character.name)
expect(assigns(:posts).size).to eq(25)
expect(assigns(:posts)).to match_array(Post.where(character_id: character.id).ordered.limit(25))
end
it "should only show visible posts" do
character = create(:character)
create(:post, character: character, user: character.user, privacy: :private)
get :show, params: { id: character.id }
expect(assigns(:posts)).to be_blank
end
it "orders recent posts" do
character = create(:character)
post3 = create(:post)
post1 = create(:post, user: character.user, character: character)
post4 = create(:post, user: character.user, character: character)
post2 = create(:post)
create(:reply, post: post4)
create(:reply, post: post3, user: character.user, character: character)
create(:reply, post: post2, user: character.user, character: character)
create(:reply, post: post1)
get :show, params: { id: character.id }
expect(assigns(:posts)).to eq([post1, post2, post3, post4])
end
it "calculates OpenGraph meta for basic character" do
user = create(:user, username: 'John Doe')
character = create(:character,
user: user,
name: "Alice",
screenname: "player_one",
description: "Alice is a character",
)
get :show, params: { id: character.id }
meta_og = assigns(:meta_og)
expect(meta_og.keys).to match_array([:url, :title, :description])
expect(meta_og[:url]).to eq(character_url(character))
expect(meta_og[:title]).to eq('John Doe » Alice | player_one')
expect(meta_og[:description]).to eq("Alice is a character")
end
it "calculates OpenGraph meta for expanded character" do
user = create(:user, username: 'John Doe')
character = create(:character,
user: user,
template: create(:template, name: "A"),
name: "Alice",
nickname: "Lis",
screenname: "player_one",
settings: [
create(:setting, name: 'Infosec'),
create(:setting, name: 'Wander'),
],
description: "Alice is a character",
with_default_icon: true,
)
create(:alias, character: character, name: "Alicia")
create(:post, character: character, user: user)
create(:reply, character: character, user: user)
get :show, params: { id: character.id }
meta_og = assigns(:meta_og)
expect(meta_og.keys).to match_array([:url, :title, :description, :image])
expect(meta_og[:url]).to eq(character_url(character))
expect(meta_og[:title]).to eq('John Doe » A » Alice | player_one')
expect(meta_og[:description]).to eq("Nicknames: Lis, Alicia. Settings: Infosec, Wander\nAlice is a character\n2 posts")
expect(meta_og[:image].keys).to match_array([:src, :width, :height])
expect(meta_og[:image][:src]).to eq(character.default_icon.url)
expect(meta_og[:image][:height]).to eq('75')
expect(meta_og[:image][:width]).to eq('75')
end
end
describe "GET edit" do
it "requires login" do
get :edit, params: { id: -1 }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "requires valid character id" do
user_id = login
get :edit, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("Character could not be found.")
end
it "requires character with permissions" do
user_id = login
get :edit, params: { id: create(:character).id }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("You do not have permission to edit that character.")
end
it "succeeds when logged in" do
character = create(:character)
login_as(character.user)
get :edit, params: { id: character.id }
expect(response.status).to eq(200)
end
context "with views" do
render_views
it "sets correct variables" do
user = create(:user)
group = create(:gallery_group)
gallery = create(:gallery, user: user, gallery_groups: [group])
character = create(:character, user: user, gallery_groups: [group])
calias = create(:alias, character: character)
templates = Array.new(2) { create(:template, user: user) }
create(:template)
login_as(user)
get :edit, params: { id: character.id }
expect(assigns(:page_title)).to eq("Edit Character: #{character.name}")
expect(controller.gon.character_id).to eq(character.id)
expect(controller.gon.user_id).to eq(user.id)
expect(controller.gon.gallery_groups.pluck(:id)).to eq([group.id])
expect(controller.gon.gallery_groups.pluck(:gallery_ids)).to eq([[gallery.id]])
expect(assigns(:character).gallery_groups).to match_array([group])
expect(assigns(:templates).map(&:name)).to match_array(templates.map(&:name))
expect(assigns(:aliases)).to match_array([calias])
end
it "works for moderator with untemplated character" do
user = create(:mod_user)
login_as(user)
character = create(:character)
template = create(:template, user: character.user)
get :edit, params: { id: character.id }
expect(assigns(:page_title)).to eq("Edit Character: #{character.name}")
expect(controller.gon.character_id).to eq(character.id)
expect(controller.gon.user_id).to eq(character.user.id)
expect(assigns(:templates)).to match_array([template])
end
it "works for moderator with templated character" do
user = create(:mod_user)
login_as(user)
character = create(:template_character)
template = create(:template, user: character.user)
get :edit, params: { id: character.id }
expect(assigns(:page_title)).to eq("Edit Character: #{character.name}")
expect(controller.gon.character_id).to eq(character.id)
expect(controller.gon.user_id).to eq(character.user.id)
expect(assigns(:templates)).to match_array([character.template, template])
end
end
end
describe "PUT update" do
it "requires login" do
put :update, params: { id: -1 }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "requires valid character id" do
user_id = login
put :update, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("Character could not be found.")
end
it "requires character with permissions" do
user_id = login
put :update, params: { id: create(:character).id }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("You do not have permission to edit that character.")
end
it "fails with invalid params" do
character = create(:character)
login_as(character.user)
put :update, params: { id: character.id, character: { name: '' } }
expect(response.status).to eq(200)
expect(flash[:error][:message]).to eq("Your character could not be saved.")
end
it "fails with invalid template params" do
character = create(:character)
login_as(character.user)
new_name = character.name + 'aaa'
put :update, params: {
id: character.id,
new_template: '1',
character: {
template_attributes: { name: '' },
name: new_name,
},
}
expect(response.status).to eq(200)
expect(flash[:error][:message]).to eq("Your character could not be saved.")
expect(character.reload.name).not_to eq(new_name)
end
it "requires notes from moderators" do
character = create(:character, name: 'a')
login_as(create(:mod_user))
put :update, params: { id: character.id, character: { name: 'b' } }
expect(response).to render_template(:edit)
expect(flash[:error]).to eq('You must provide a reason for your moderator edit.')
end
it "stores note from moderators" do
Character.auditing_enabled = true
character = create(:character, name: 'a')
admin = create(:admin_user)
login_as(admin)
put :update, params: { id: character.id, character: { name: 'b', audit_comment: 'note' } }
expect(flash[:success]).to eq("Character saved successfully.")
expect(character.reload.name).to eq('b')
expect(character.audits.last.comment).to eq('note')
Character.auditing_enabled = false
end
it "succeeds when valid" do
character = create(:character)
user = character.user
login_as(user)
new_name = character.name + 'aaa'
template = create(:template, user: user)
gallery = create(:gallery, user: user)
setting = create(:setting, name: 'Another World')
put :update, params: {
id: character.id,
character: {
name: new_name,
nickname: 'TemplateName',
screenname: 'a-new-test',
setting_ids: [setting.id],
template_id: template.id,
pb: 'Actor',
description: 'Description',
ungrouped_gallery_ids: [gallery.id],
},
}
expect(response).to redirect_to(assigns(:character))
expect(flash[:success]).to eq("Character saved successfully.")
character.reload
expect(character.name).to eq(new_name)
expect(character.nickname).to eq('TemplateName')
expect(character.screenname).to eq('a-new-test')
expect(character.settings.pluck(:name)).to eq(['Another World'])
expect(character.template).to eq(template)
expect(character.pb).to eq('Actor')
expect(character.description).to eq('Description')
expect(character.galleries).to match_array([gallery])
end
it "does not persist values when invalid" do
character = create(:character)
user = character.user
login_as(user)
old_name = character.name
template = create(:template, user: user)
gallery = create(:gallery, user: user)
setting = create(:setting, name: 'Another World')
put :update, params: {
id: character.id,
character: {
name: '',
nickname: 'TemplateName',
screenname: 'a-new-test',
setting_ids: [setting.id],
template_id: template.id,
pb: 'Actor',
description: 'Description',
ungrouped_gallery_ids: [gallery.id],
},
}
expect(response.status).to eq(200)
expect(flash[:error][:message]).to eq("Your character could not be saved.")
character.reload
expect(character.name).to eq(old_name)
expect(character.nickname).to be_nil
expect(character.screenname).to be_nil
expect(character.settings).to be_blank
expect(character.template).to be_blank
expect(character.pb).to be_nil
expect(character.description).to be_nil
expect(character.galleries).to be_blank
end
it "adds galleries by groups" do
user = create(:user)
group = create(:gallery_group)
gallery = create(:gallery, gallery_groups: [group], user: user)
character = create(:character, user: user)
login_as(user)
put :update, params: { id: character.id, character: { gallery_group_ids: [group.id] } }
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to match_array([group])
expect(character.galleries).to match_array([gallery])
expect(character.ungrouped_gallery_ids).to be_blank
expect(character.characters_galleries.first).to be_added_by_group
end
it "creates new templates when specified" do
expect(Template.count).to eq(0)
character = create(:character)
login_as(character.user)
put :update, params: { id: character.id, new_template: '1', character: { template_attributes: { name: 'Test' } } }
expect(Template.count).to eq(1)
expect(Template.first.name).to eq('Test')
expect(character.reload.template_id).to eq(Template.first.id)
end
it "removes gallery only if not shared between groups" do
user = create(:user)
group1 = create(:gallery_group) # gallery1
group2 = create(:gallery_group) # -> gallery1
group3 = create(:gallery_group) # gallery2 ->
group4 = create(:gallery_group) # gallery2
gallery1 = create(:gallery, gallery_groups: [group1, group2], user: user)
gallery2 = create(:gallery, gallery_groups: [group3, group4], user: user)
character = create(:character, gallery_groups: [group1, group3, group4], user: user)
login_as(user)
put :update, params: { id: character.id, character: { gallery_group_ids: [group2.id, group4.id] } }
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to match_array([group2, group4])
expect(character.galleries).to match_array([gallery1, gallery2])
expect(character.ungrouped_gallery_ids).to be_blank
expect(character.characters_galleries.map(&:added_by_group)).to eq([true, true])
end
it "does not remove gallery if tethered by group" do
user = create(:user)
group = create(:gallery_group)
gallery = create(:gallery, gallery_groups: [group], user: user)
character = create(:character, gallery_groups: [group], user: user)
character.ungrouped_gallery_ids = [gallery.id]
character.save!
expect(character.characters_galleries.first).not_to be_added_by_group
login_as(user)
put :update, params: {
id: character.id,
character: {
ungrouped_gallery_ids: [''],
gallery_group_ids: [group.id],
},
}
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to match_array([group])
expect(character.galleries).to match_array([gallery])
expect(character.ungrouped_gallery_ids).to be_blank
expect(character.characters_galleries.first).to be_added_by_group
end
it "works when adding both group and gallery" do
user = create(:user)
group = create(:gallery_group)
gallery = create(:gallery, gallery_groups: [group], user: user)
character = create(:character, user: user)
login_as(user)
put :update, params: {
id: character.id,
character: {
gallery_group_ids: [group.id],
ungrouped_gallery_ids: [gallery.id],
},
}
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to match_array([group])
expect(character.galleries).to match_array([gallery])
expect(character.ungrouped_gallery_ids).to eq([gallery.id])
expect(character.characters_galleries.first).not_to be_added_by_group
end
it "does not add another user's galleries" do
group = create(:gallery_group)
create(:gallery, gallery_groups: [group]) # gallery
character = create(:character)
login_as(character.user)
put :update, params: { id: character.id, character: { gallery_group_ids: [group.id] } }
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to match_array([group])
expect(character.galleries).to be_blank
end
it "removes untethered galleries when group goes" do
user = create(:user)
group = create(:gallery_group)
create(:gallery, gallery_groups: [group], user: user) # gallery
character = create(:character, gallery_groups: [group], user: user)
login_as(user)
put :update, params: { id: character.id, character: { gallery_group_ids: [''] } }
expect(flash[:success]).to eq('Character saved successfully.')
character.reload
expect(character.gallery_groups).to eq([])
expect(character.galleries).to eq([])
end
context "with views" do
render_views
it "sets correct variables when invalid" do
user = create(:user)
group = create(:gallery_group)
gallery = create(:gallery, user: user, gallery_groups: [group])
character = create(:character, user: user, gallery_groups: [group])
templates = Array.new(2) { create(:template, user: user) }
create(:template)
login_as(user)
put :update, params: { id: character.id, character: { name: '', gallery_group_ids: [group.id] } }
expect(response).to render_template(:edit)
expect(controller.gon.character_id).to eq(character.id)
expect(controller.gon.user_id).to eq(user.id)
expect(controller.gon.gallery_groups.pluck(:id)).to eq([group.id])
expect(controller.gon.gallery_groups.pluck(:gallery_ids)).to eq([[gallery.id]])
expect(assigns(:character).gallery_groups).to match_array([group])
expect(assigns(:templates).map(&:name)).to match_array(templates.map(&:name))
end
end
it "reorders galleries as necessary" do
character = create(:character)
g1 = create(:gallery, user: character.user)
g2 = create(:gallery, user: character.user)
character.galleries << g1
character.galleries << g2
g1_cg = CharactersGallery.where(gallery_id: g1.id).first
g2_cg = CharactersGallery.where(gallery_id: g2.id).first
expect(g1_cg.section_order).to eq(0)
expect(g2_cg.section_order).to eq(1)
login_as(character.user)
put :update, params: { id: character.id, character: { ungrouped_gallery_ids: [g2.id.to_s] } }
expect(character.reload.galleries.pluck(:id)).to eq([g2.id])
expect(g2_cg.reload.section_order).to eq(0)
end
it "orders settings by default" do
char = create(:character)
login_as(char.user)
setting1 = create(:setting)
setting3 = create(:setting)
setting2 = create(:setting)
put :update, params: {
id: char.id,
character: { setting_ids: [setting1, setting2, setting3].map(&:id) },
}
expect(flash[:success]).to eq('Character saved successfully.')
expect(char.settings).to eq([setting1, setting2, setting3])
end
it "orders gallery groups by default" do
user = create(:user)
login_as(user)
char = create(:character, user: user)
group4 = create(:gallery_group, user: user)
group1 = create(:gallery_group, user: user)
group3 = create(:gallery_group, user: user)
group2 = create(:gallery_group, user: user)
put :update, params: {
id: char.id,
character: { gallery_group_ids: [group1, group2, group3, group4].map(&:id) },
}
expect(flash[:success]).to eq('Character saved successfully.')
expect(char.gallery_groups).to eq([group1, group2, group3, group4])
end
end
describe "GET facecasts" do
it "does not require login" do
get :facecasts
expect(response.status).to eq(200)
expect(assigns(:page_title)).to eq("Facecasts")
end
it "sets correct variables for facecast name sort" do
chars = Array.new(3) { create(:character, pb: SecureRandom.urlsafe_base64) }
get :facecasts
pbs = assigns(:pbs).map(&:pb)
expect(pbs).to match_array(chars.map(&:pb))
end
it "sets correct variables for character name sort: character only" do
chars = Array.new(3) { create(:character, pb: SecureRandom.urlsafe_base64) }
get :facecasts, params: { sort: 'name' }
names = assigns(:pbs).map(&:item_name)
expect(names).to match_array(chars.map(&:name))
end
it "sets correct variables for character name sort: template only" do
chars = Array.new(3) { create(:template_character, pb: SecureRandom.urlsafe_base64) }
get :facecasts, params: { sort: 'name' }
names = assigns(:pbs).map(&:item_name)
expect(names).to match_array(chars.map(&:template).map(&:name))
end
it "sets correct variables for character name sort: character and template mixed" do
chars = Array.new(3) { create(:template_character, pb: SecureRandom.urlsafe_base64) }
chars += Array.new(3) { create(:character, pb: SecureRandom.urlsafe_base64) }
get :facecasts, params: { sort: 'name' }
names = assigns(:pbs).map(&:item_name)
expect(names).to match_array(chars.map { |c| (c.template || c).name })
end
it "sets correct variables for writer sort" do
chars = Array.new(3) { create(:template_character, pb: SecureRandom.urlsafe_base64) }
chars += Array.new(3) { create(:character, pb: SecureRandom.urlsafe_base64) }
get :facecasts, params: { sort: 'writer' }
user_ids = assigns(:pbs).map(&:user_id)
expect(user_ids).to match_array(chars.map(&:user).map(&:id))
end
end
describe "DELETE destroy" do
it "requires login" do
delete :destroy, params: { id: -1 }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq("You must be logged in to view that page.")
end
it "requires valid character" do
user_id = login
delete :destroy, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq("Character could not be found.")
end
it "requires permission" do
user = create(:user)
login_as(user)
character = create(:character)
expect(character.user_id).not_to eq(user.id)
delete :destroy, params: { id: character.id }
expect(response).to redirect_to(user_characters_url(user.id))
expect(flash[:error]).to eq("You do not have permission to edit that character.")
end
it "succeeds" do
character = create(:character)
login_as(character.user)
delete :destroy, params: { id: character.id }
expect(response).to redirect_to(user_characters_url(character.user_id))
expect(flash[:success]).to eq("Character deleted successfully.")
expect(Character.find_by_id(character.id)).to be_nil
end
it "handles destroy failure" do
character = create(:character)
post = create(:post, user: character.user, character: character)
login_as(character.user)
expect_any_instance_of(Character).to receive(:destroy!).and_raise(ActiveRecord::RecordNotDestroyed, 'fake error')
delete :destroy, params: { id: character.id }
expect(response).to redirect_to(character_url(character))
expect(flash[:error]).to eq({ message: "Character could not be deleted.", array: [] })
expect(post.reload.character).to eq(character)
end
end
describe "GET replace" do
it "requires login" do
character = create(:character)
get :replace, params: { id: character.id }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq('You must be logged in to view that page.')
end
it "requires valid character" do
user_id = login
get :replace, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('Character could not be found.')
end
it "requires own character" do
character = create(:character)
user_id = login
get :replace, params: { id: character.id }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('You do not have permission to edit that character.')
end
it "sets correct variables" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
other_char.default_icon = create(:icon, user: user)
other_char.save!
calias = create(:alias, character: other_char)
char_post = create(:post, user: user, character: character)
create(:reply, user: user, post: char_post, character: character) # reply
create(:post) # other post
char_reply2 = create(:reply, user: user, character: character) # other reply
login_as(user)
get :replace, params: { id: character.id }
expect(response).to have_http_status(200)
expect(assigns(:page_title)).to eq('Replace Character: ' + character.name)
expect(controller.gon.gallery[other_char.id][:url]).to eq(other_char.default_icon.url)
expect(controller.gon.gallery[other_char.id][:aliases]).to eq([calias.as_json])
expect(assigns(:posts)).to match_array([char_post, char_reply2.post])
end
context "with template" do
it "sets alts correctly" do
user = create(:user)
template = create(:template, user: user)
character = create(:character, user: user, template: template)
alts = Array.new(5) { create(:character, user: user, template: template) }
create(:character, user: user) # other character
login_as(user)
get :replace, params: { id: character.id }
expect(response).to have_http_status(200)
expect(assigns(:page_title)).to eq('Replace Character: ' + character.name)
expect(assigns(:alts)).to match_array(alts)
expect(assigns(:alt_dropdown).length).to eq(alts.length)
end
it "includes character if no others in template" do
user = create(:user)
template = create(:template, user: user)
character = create(:character, user: user, template: template)
create(:character, user: user) # other character
login_as(user)
get :replace, params: { id: character.id }
expect(response).to have_http_status(200)
expect(assigns(:alts)).to match_array([character])
end
end
context "without template" do
it "sets alts correctly" do
user = create(:user)
character = create(:character, user: user)
alts = Array.new(5) { create(:character, user: user) }
template = create(:template, user: user)
create(:character, user: user, template: template) # other character
login_as(user)
get :replace, params: { id: character.id }
expect(response).to have_http_status(200)
expect(assigns(:page_title)).to eq('Replace Character: ' + character.name)
expect(assigns(:alts)).to match_array(alts)
expect(assigns(:alt_dropdown).length).to eq(alts.length)
end
it "includes character if no others in template" do
user = create(:user)
template = create(:template, user: user)
character = create(:character, user: user)
create(:character, user: user, template: template) # other character
login_as(user)
get :replace, params: { id: character.id }
expect(response).to have_http_status(200)
expect(assigns(:alts)).to match_array([character])
end
end
end
describe "POST do_replace" do
it "requires login" do
character = create(:character)
post :do_replace, params: { id: character.id }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq('You must be logged in to view that page.')
end
it "requires valid character" do
user_id = login
post :do_replace, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('Character could not be found.')
end
it "requires own character" do
character = create(:character)
user_id = login
post :do_replace, params: { id: character.id }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('You do not have permission to edit that character.')
end
it "requires valid other character" do
character = create(:character)
login_as(character.user)
post :do_replace, params: { id: character.id, icon_dropdown: -1 }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('Character could not be found.')
end
it "requires other character to be yours if present" do
character = create(:character)
other_char = create(:character)
login_as(character.user)
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('That is not your character.')
end
it "requires valid new alias if parameter provided" do
character = create(:character)
login_as(character.user)
post :do_replace, params: { id: character.id, alias_dropdown: -1 }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('Invalid new alias.')
end
it "requires matching new alias if parameter provided" do
character = create(:character)
other_char = create(:character, user: character.user)
calias = create(:alias)
login_as(character.user)
post :do_replace, params: { id: character.id, alias_dropdown: calias.id, icon_dropdown: other_char.id }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('Invalid new alias.')
end
it "requires valid old alias if parameter provided" do
character = create(:character)
login_as(character.user)
post :do_replace, params: { id: character.id, orig_alias: -1 }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('Invalid old alias.')
end
it "requires matching old alias if parameter provided" do
character = create(:character)
calias = create(:alias)
login_as(character.user)
post :do_replace, params: { id: character.id, orig_alias: calias.id }
expect(response).to redirect_to(replace_character_path(character))
expect(flash[:error]).to eq('Invalid old alias.')
end
context "with audits enabled" do
before(:each) { Reply.auditing_enabled = true }
after(:each) { Reply.auditing_enabled = false }
it "succeeds with valid other character" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
char_post = create(:post, user: user, character: character)
reply = create(:reply, user: user, character: character)
reply_post_char = reply.post.character_id
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id }
end
expect(response).to redirect_to(character_path(character))
expect(flash[:success]).to eq('All uses of this character will be replaced.')
expect(char_post.reload.character_id).to eq(other_char.id)
expect(reply.reload.character_id).to eq(other_char.id)
expect(reply.post.reload.character_id).to eq(reply_post_char) # check it doesn't replace all replies in a post
audit = reply.audits.where(action: 'update').first
expect(audit).not_to be(nil)
expect(audit.user).to eq(user)
end
end
it "succeeds with no other character" do
user = create(:user)
character = create(:character, user: user)
char_post = create(:post, user: user, character: character)
reply = create(:reply, user: user, character: character)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id }
end
expect(response).to redirect_to(character_path(character))
expect(flash[:success]).to eq('All uses of this character will be replaced.')
expect(char_post.reload.character_id).to be_nil
expect(reply.reload.character_id).to be_nil
end
it "succeeds with alias" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
calias = create(:alias, character: other_char)
char_post = create(:post, user: user, character: character)
reply = create(:reply, user: user, character: character)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id, alias_dropdown: calias.id }
end
expect(char_post.reload.character_id).to eq(other_char.id)
expect(reply.reload.character_id).to eq(other_char.id)
expect(char_post.reload.character_alias_id).to eq(calias.id)
expect(reply.reload.character_alias_id).to eq(calias.id)
end
it "filters to selected posts if given" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
char_post = create(:post, user: user, character: character)
char_reply = create(:reply, user: user, character: character)
other_post = create(:post, user: user, character: character)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: {
id: character.id,
icon_dropdown: other_char.id,
post_ids: [char_post.id, char_reply.post.id],
}
end
expect(response).to redirect_to(character_path(character))
expect(flash[:success]).to eq('All uses of this character in the specified posts will be replaced.')
expect(char_post.reload.character_id).to eq(other_char.id)
expect(char_reply.reload.character_id).to eq(other_char.id)
expect(other_post.reload.character_id).to eq(character.id)
end
it "filters to alias if given" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
calias = create(:alias, character: character)
char_post = create(:post, user: user, character: character)
char_reply = create(:reply, user: user, character: character, character_alias_id: calias.id)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id, orig_alias: calias.id }
end
expect(char_post.reload.character_id).to eq(character.id)
expect(char_reply.reload.character_id).to eq(other_char.id)
end
it "filters to nil if given" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
calias = create(:alias, character: character)
char_post = create(:post, user: user, character: character)
char_reply = create(:reply, user: user, character: character, character_alias_id: calias.id)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id, orig_alias: '' }
end
expect(char_post.reload.character_id).to eq(other_char.id)
expect(char_reply.reload.character_id).to eq(character.id)
end
it "does not filter if all given" do
user = create(:user)
character = create(:character, user: user)
other_char = create(:character, user: user)
calias = create(:alias, character: character)
char_post = create(:post, user: user, character: character)
char_reply = create(:reply, user: user, character: character, character_alias_id: calias.id)
login_as(user)
perform_enqueued_jobs(only: UpdateModelJob) do
post :do_replace, params: { id: character.id, icon_dropdown: other_char.id, orig_alias: 'all' }
end
expect(char_post.reload.character_id).to eq(other_char.id)
expect(char_reply.reload.character_id).to eq(other_char.id)
end
end
describe "GET search" do
it 'works logged in' do
login
get :search
expect(response).to have_http_status(200)
expect(assigns(:users)).to be_empty
expect(assigns(:templates)).to be_empty
end
it 'works logged out' do
get :search
expect(response).to have_http_status(200)
expect(assigns(:users)).to be_empty
end
it 'searches author' do
author = create(:user)
found = create(:character, user: author)
create(:character) # notfound
get :search, params: { commit: true, author_id: author.id }
expect(response).to have_http_status(200)
expect(assigns(:users)).to match_array([author])
expect(assigns(:search_results)).to match_array([found])
end
it "doesn't search missing author" do
character = create(:template_character)
get :search, params: { commit: true, author_id: 9999 }
expect(response).to have_http_status(200)
expect(flash[:error]).to eq('The specified author could not be found.')
expect(assigns(:users)).to be_empty
expect(assigns(:search_results)).to match_array([character])
end
it "sets templates by author" do
author = create(:user)
template2 = create(:template, user: author, name: 'b')
template = create(:template, user: author, name: 'a')
template3 = create(:template, user: author, name: 'c')
create(:template)
get :search, params: { commit: true, author_id: author.id }
expect(assigns(:templates)).to eq([template, template2, template3])
end
it "doesn't search missing template" do
character = create(:template_character)
get :search, params: { commit: true, template_id: 9999 }
expect(response).to have_http_status(200)
expect(flash[:error]).to eq('The specified template could not be found.')
expect(assigns(:templates)).to be_empty
expect(assigns(:search_results)).to match_array([character])
end
it "doesn't search author/template mismatch" do
character = create(:template_character)
character2 = create(:character)
get :search, params: { commit: true, template_id: character.template_id, author_id: character2.user_id }
expect(response).to have_http_status(200)
expect(flash[:error]).to eq('The specified author and template do not match; template filter will be ignored.')
expect(assigns(:templates)).to be_empty
expect(assigns(:search_results)).to match_array([character2])
end
it 'searches template' do
author = create(:user)
template = create(:template, user: author)
found = create(:character, user: author, template: template)
create(:character, user: author, template: create(:template, user: author)) # notfound
get :search, params: { commit: true, template_id: template.id }
expect(response).to have_http_status(200)
expect(assigns(:templates)).to match_array([template])
expect(assigns(:search_results)).to match_array([found])
end
context "with search" do
let!(:name) { create(:character, name: 'a', screenname: 'b', nickname: 'c') }
let!(:nickname) { create(:character, name: 'b', screenname: 'c', nickname: 'a') }
let!(:screenname) { create(:character, name: 'c', screenname: 'a', nickname: 'b') }
it "searches names correctly" do
get :search, params: { commit: true, name: 'a', search_name: true }
expect(assigns(:search_results)).to match_array([name])
end
it "searches screenname correctly" do
get :search, params: { commit: true, name: 'a', search_screenname: true }
expect(assigns(:search_results)).to match_array([screenname])
end
it "searches nickname correctly" do
get :search, params: { commit: true, name: 'a', search_nickname: true }
expect(assigns(:search_results)).to match_array([nickname])
end
it "searches name + screenname correctly" do
get :search, params: { commit: true, name: 'a', search_name: true, search_screenname: true }
expect(assigns(:search_results)).to match_array([name, screenname])
end
it "searches name + nickname correctly" do
get :search, params: { commit: true, name: 'a', search_name: true, search_nickname: true }
expect(assigns(:search_results)).to match_array([name, nickname])
end
it "searches nickname + screenname correctly" do
get :search, params: { commit: true, name: 'a', search_nickname: true, search_screenname: true }
expect(assigns(:search_results)).to match_array([nickname, screenname])
end
it "searches all correctly" do
get :search, params: {
commit: true,
name: 'a',
search_name: true,
search_screenname: true,
search_nickname: true,
}
expect(assigns(:search_results)).to match_array([name, screenname, nickname])
end
it "orders results correctly" do
template = create(:template)
user = template.user
char4 = create(:character, user: user, template: template, name: 'd')
char2 = create(:character, user: user, name: 'b')
char1 = create(:character, user: user, template: template, name: 'a')
char5 = create(:character, user: user, name: 'e')
char3 = create(:character, user: user, name: 'c')
get :search, params: { commit: true, author_id: user.id }
expect(assigns(:search_results)).to eq([char1, char2, char3, char4, char5])
end
it "paginates correctly" do
user = create(:user)
26.times do |i|
create(:character, user: user, name: "character#{i}")
end
get :search, params: { commit: true, author_id: user.id }
expect(assigns(:search_results).length).to eq(25)
end
end
end
describe "POST duplicate" do
it "requires login" do
post :duplicate, params: { id: -1 }
expect(response).to redirect_to(root_url)
expect(flash[:error]).to eq('You must be logged in to view that page.')
end
it "requires valid character id" do
user_id = login
post :duplicate, params: { id: -1 }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('Character could not be found.')
end
it "requires character with permissions" do
user_id = login
post :duplicate, params: { id: create(:character).id }
expect(response).to redirect_to(user_characters_url(user_id))
expect(flash[:error]).to eq('You do not have permission to edit that character.')
end
it "succeeds" do
user = create(:user)
template = create(:template, user: user)
icon = create(:icon, user: user)
gallery = create(:gallery, icons: [icon], user: user)
group = create(:gallery_group)
gallery2 = create(:gallery, gallery_groups: [group], user: user)
gallery3 = create(:gallery, gallery_groups: [group], user: user)
character = create(:character, template: template, galleries: [gallery, gallery2], gallery_groups: [group], default_icon: icon, user: user)
calias = create(:alias, character: character)
char_post = create(:post, character: character, user: user)
char_reply = create(:reply, character: character, user: user)
character.settings << create(:setting)
character.reload
expect(character.galleries).to match_array([gallery, gallery2, gallery3])
expect(character.ungrouped_gallery_ids).to match_array([gallery.id, gallery2.id])
expect(character.gallery_groups).to match_array([group])
login_as(user)
expect do
post :duplicate, params: { id: character.id }
end.to not_change {
[Template.count, Gallery.count, Icon.count, Reply.count, Post.count, Tag.count]
}.and change { Character.count }.by(1).and change { CharactersGallery.count }.by(3).and change { CharacterTag.count }.by(2)
dupe = Character.last
character.reload
expect(response).to redirect_to(edit_character_url(dupe))
expect(flash[:success]).to eq('Character duplicated successfully. You are now editing the new character.')
expect(dupe).not_to eq(character)
# check all attrs but id, created_at and updated_at are same
dup_attrs = dupe.attributes.clone
char_attrs = character.attributes.clone
['id', 'created_at', 'updated_at'].each do |val|
dup_attrs.delete(val)
char_attrs.delete(val)
end
expect(dup_attrs).to eq(char_attrs)
# check character associations aren't changed
expect(character.template).to eq(template)
expect(character.galleries).to match_array([gallery, gallery2, gallery3])
expect(character.ungrouped_gallery_ids).to match_array([gallery.id, gallery2.id])
expect(character.gallery_groups).to match_array([group])
expect(character.default_icon).to eq(icon)
expect(character.user).to eq(user)
expect(character.aliases.map(&:name)).to eq([calias.name])
# check duplicate has appropriate associations
expect(dupe.template).to eq(template)
expect(dupe.galleries).to match_array([gallery, gallery2, gallery3])
expect(dupe.ungrouped_gallery_ids).to match_array([gallery.id, gallery2.id])
expect(dupe.gallery_groups).to match_array([group])
expect(dupe.default_icon).to eq(icon)
expect(dupe.user).to eq(user)
expect(dupe.aliases.map(&:name)).to eq([calias.name])
# check old posts and replies have old attributes
char_post.reload
char_reply.reload
expect(char_post.character).to eq(character)
expect(char_reply.character).to eq(character)
end
it "handles unexpected failure" do
character = create(:character)
login_as(character.user)
character.update_columns(default_icon_id: create(:icon).id) # rubocop:disable Rails/SkipsModelValidations
expect(character).not_to be_valid
expect { post :duplicate, params: { id: character.id } }.to not_change { Character.count }
expect(response).to redirect_to(character_path(character))
expect(flash[:error][:message]).to eq('Character could not be duplicated.')
expect(flash[:error][:array]).to eq(['Default icon must be yours'])
end
end
describe "#character_split" do
context "when logged out" do
it "works by default" do
expect(controller.send(:character_split)).to eq('template')
end
it "can be overridden with a parameter" do
controller.params[:character_split] = 'none'
expect(session[:character_split]).to be_nil
expect(controller.send(:character_split)).to eq('none')
expect(session[:character_split]).to eq('none')
end
it "uses session variable if it exists" do
session[:character_split] = 'none'
expect(controller.send(:character_split)).to eq('none')
end
end
context "when logged in" do
it "works by default" do
login
expect(controller.send(:character_split)).to eq('template')
end
it "uses account default if different" do
user = create(:user, default_character_split: 'none')
login_as(user)
expect(controller.send(:character_split)).to eq('none')
end
it "is not overridden by session" do
# also does not modify user default
user = create(:user, default_character_split: 'none')
login_as(user)
session[:character_split] = 'template'
expect(controller.send(:character_split)).to eq('none')
expect(user.reload.default_character_split).to eq('none')
end
it "can be overridden by params" do
# also does not modify user default
user = create(:user, default_character_split: 'none')
login_as(user)
controller.params[:character_split] = 'template'
expect(controller.send(:character_split)).to eq('template')
expect(user.reload.default_character_split).to eq('none')
end
end
end
describe "#editor_setup" do
it "orders characters correctly" do
user = create(:user)
login_as(user)
template4 = create(:template, user: user, name: "d")
template2 = create(:template, user: user, name: "b")
template1 = create(:template, user: user, name: "a")
template3 = create(:template, user: user, name: "c")
controller.send(:editor_setup)
expect(assigns(:templates)).to eq([template1, template2, template3, template4])
end
skip "has more tests"
end
end
| Marri/glowfic | spec/controllers/characters_controller_spec.rb | Ruby | mit | 56,627 |
<?php get_template_part('templates/page', 'header'); ?>
<?php if (!have_posts()) : ?>
<div data-alert class="alert-box warning">
<?php _e('Sorry, no results were found.', 'roots'); ?>
</div>
<?php get_search_form(); ?>
<?php endif; ?>
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', get_post_format()); ?>
<?php endwhile; ?>
<?php if ($wp_query->max_num_pages > 1) : ?>
<nav class="post-nav clearfix">
<ul class="pagination">
<li class="left"><?php next_posts_link(__('← Older posts', 'roots')); ?></li>
<li class="right"><?php previous_posts_link(__('Newer posts →', 'roots')); ?></li>
</ul>
</nav>
<?php endif; ?>
| atanasiuswau/furai | index.php | PHP | mit | 706 |
Package.describe({
summary: "Stanford Javascript Crypto Library with public key cryptography support"
});
Package.on_use(function (api, where) {
api.export('sjcl', 'client');
api.add_files('sjcl.js', 'client', {
bare: true
});
});
| lencinhaus/ubersafe | app/packages/sjcl/package.js | JavaScript | mit | 254 |
<?php
namespace Crocos\SecurityBundle\Security\AuthLogic;
/**
* AuthLogicInterface.
*
* @author Katsuhiro Ogawa <ogawa@crocos.co.jp>
*/
interface AuthLogicInterface
{
/**
* Set authentication domain.
*/
public function setDomain($domain);
/**
* Log in.
*
* @param user $user
*/
public function login($user);
/**
* Log out.
*/
public function logout();
/**
* Check is authenticated.
*
* @return bool
*/
public function isAuthenticated();
/**
* Get user.
*
* @return mixed
*/
public function getUser();
}
| crocos/CrocosSecurityBundle | Security/AuthLogic/AuthLogicInterface.php | PHP | mit | 632 |
module WeMeet
class ActivityCategory
attr_accessor :name
def initialize(name)
@name = name.capitalize
end
def similar_to?(other)
return (@name.downcase.include? other.downcase or other.downcase.include? @name.downcase)
end
def ==(other)
return @name.downcase == other.name.downcase
end
end
end
| dcaba/wemeet | lib/we_meet/activity_category.rb | Ruby | mit | 322 |
module Tod
module TasksRepository
class InMemory
def initialize
@tasks = {}
@id = 0
end
def persist(task)
@id += 1
task.id = @id
tasks[@id] = task
task
end
def count
tasks.length
end
private
attr_reader :tasks
end
end
end
| bezelga/tod | lib/tod/tasks_repository/in_memory.rb | Ruby | mit | 342 |
<?php
/* TwigBundle:Exception:trace.txt.twig */
class __TwigTemplate_9059c36d2d4ecdaa941ebef449cf6897e5465f46e03b305a1a47f53905e11533 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
if ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function")) {
// line 2
echo " at ";
echo twig_escape_filter($this->env, (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "class") . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "type")) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function")), "html", null, true);
echo "(";
echo twig_escape_filter($this->env, $this->env->getExtension('code')->formatArgsAsText($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "args")), "html", null, true);
echo ")
";
} else {
// line 4
echo " at n/a
";
}
// line 6
if (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "file", array(), "any", true, true) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "line", array(), "any", true, true))) {
// line 7
echo " in ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file"), "html", null, true);
echo " line ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line"), "html", null, true);
echo "
";
}
}
public function getTemplateName()
{
return "TwigBundle:Exception:trace.txt.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 29 => 4, 42 => 14, 38 => 13, 35 => 7, 26 => 5, 87 => 20, 80 => 19, 55 => 13, 46 => 7, 44 => 10, 36 => 7, 31 => 5, 25 => 3, 21 => 2, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 9, 27 => 4, 24 => 4, 22 => 2, 201 => 92, 199 => 91, 196 => 90, 187 => 84, 183 => 82, 173 => 74, 171 => 73, 168 => 72, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 133 => 55, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 112 => 42, 105 => 40, 101 => 24, 91 => 31, 86 => 28, 69 => 25, 66 => 15, 62 => 23, 51 => 15, 49 => 19, 39 => 6, 32 => 12, 19 => 1, 57 => 16, 54 => 21, 43 => 8, 40 => 7, 33 => 6, 30 => 3,);
}
}
| Oukhay/smjetsetmag | app/cache/dev/twig/90/59/c36d2d4ecdaa941ebef449cf6897e5465f46e03b305a1a47f53905e11533.php | PHP | mit | 3,171 |
var expect = require('chai').expect;
var _ = require('lodash');
var ReadlineStub = require('../../helpers/readline');
var fixtures = require('../../helpers/fixtures');
var Expand = require('../../../lib/prompts/expand');
describe('`expand` prompt', function () {
beforeEach(function () {
this.fixture = _.clone(fixtures.expand);
this.rl = new ReadlineStub();
this.expand = new Expand(this.fixture, this.rl);
});
it('should throw if `key` is missing', function () {
var mkPrompt = function () {
this.fixture.choices = ['a', 'a'];
return new Expand(this.fixture, this.rl);
}.bind(this);
expect(mkPrompt).to.throw(/Format error/);
});
it('should throw if `key` is duplicate', function () {
var mkPrompt = function () {
this.fixture.choices = [
{key: 'a', name: 'foo'},
{key: 'a', name: 'foo'}
];
return new Expand(this.fixture, this.rl);
}.bind(this);
expect(mkPrompt).to.throw(/Duplicate\ key\ error/);
});
it('should throw if `key` is `h`', function () {
var mkPrompt = function () {
this.fixture.choices = [
{key: 'h', name: 'foo'}
];
return new Expand(this.fixture, this.rl);
}.bind(this);
expect(mkPrompt).to.throw(/Reserved\ key\ error/);
});
it('should take the first choice by default', function (done) {
this.expand.run().then(function (answer) {
expect(answer).to.equal('acab');
done();
});
this.rl.emit('line');
});
it('should use the `default` argument value', function (done) {
this.fixture.default = 1;
this.expand = new Expand(this.fixture, this.rl);
this.expand.run().then(function (answer) {
expect(answer).to.equal('bar');
done();
});
this.rl.emit('line');
});
it('should return the user input', function (done) {
this.expand.run().then(function (answer) {
expect(answer).to.equal('bar');
done();
});
this.rl.emit('line', 'b');
});
it('should strip the user input', function (done) {
this.expand.run().then(function (answer) {
expect(answer).to.equal('bar');
done();
});
this.rl.emit('line', ' b ');
});
it('should have help option', function (done) {
this.expand.run().then(function (answer) {
expect(this.rl.output.__raw__).to.match(/a\)\ acab/);
expect(this.rl.output.__raw__).to.match(/b\)\ bar/);
expect(answer).to.equal('chile');
done();
}.bind(this));
this.rl.emit('line', 'h');
this.rl.emit('line', 'c');
});
it('should not allow invalid command', function () {
var self = this;
var promise = this.expand.run();
this.rl.emit('line', 'blah');
setTimeout(function () {
self.rl.emit('line', 'a');
}, 10);
return promise;
});
it('should display and capitalize the default choice `key`', function () {
this.fixture.default = 1;
this.expand = new Expand(this.fixture, this.rl);
this.expand.run();
expect(this.rl.output.__raw__).to.contain('(aBch)');
});
it('should \'autocomplete\' the user input', function (done) {
this.expand = new Expand(this.fixture, this.rl);
this.expand.run();
this.rl.line = 'a';
this.rl.emit('keypress');
setTimeout(function () {
expect(this.rl.output.__raw__).to.contain('acab');
done();
}.bind(this), 10);
});
});
| senshuu/Inquirer.js | test/specs/prompts/expand.js | JavaScript | mit | 3,372 |
var engine = require("../../engine").engine;
var task;
var factories = require("../spec_helper").component_factories;
describe("error scenarios", function(){
beforeEach(function(){
waits(500);
runs(function(){
this.identifier = "error" + Math.floor(Math.random() * 100000);
this.intake = factories.create_ipc_intake(this.identifier);
this.exhaust = factories.create_ipc_exhaust(this.identifier);
this.cylinder = (factories.create_ipc_cylinders(1,this.identifier))["1"];
this.client = (factories.create_ipc_clients(1,this.identifier))["1"];
});
});
afterEach(function(){
this.intake.close();
this.exhaust.close();
this.cylinder.close();
this.client.close();
});
it("throws a TimeoutError", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("(function(locals){ return { sleep: function() { var now = new Date().getTime(); while(new Date().getTime() < now + 10000) { /* sleep */ } } } })");
task.setLocals({});
task.setCode("sleep();");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
var error = callback.mostRecentCall.args[0]
expect(error).toContain("TimeoutError");
});
});
it("catches syntax errors with task's code", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("(function(locals){ return { add: function(a,b){ return a+b; } } })");
task.setLocals({});
task.setCode("add(1,2");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
var response = callback.mostRecentCall.args[1]
expect(response.getEvaluation()).toContain("SyntaxError");
expect(response.isError()).toBe(true);
});
});
it("throws a ReferenceError", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("(function(locals){ return { add: function(a,b){ return a+b; } } })");
task.setLocals({});
task.setCode("subtract(1,1)");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
var response = callback.mostRecentCall.args[1]
expect(response.getEvaluation()).toContain("ReferenceError");
expect(response.isError()).toBe(true);
});
});
describe("Context Validation", function(){
it("catches syntax errors in task's context", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("foo;");
task.setLocals({});
task.setCode("subtract(1,1)");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
expect(callback.mostRecentCall.args[0]).toContain("SandboxError");
});
});
it("catches task context's that are not functions", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("({'foo':'bar'})");
task.setLocals({});
task.setCode("subtract(1,1)");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
expect(callback.mostRecentCall.args[0]).toContain("SandboxError");
});
});
it("catches task context's that do not return object literals", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("(function(){ return 1; })");
task.setLocals({});
task.setCode("subtract(1,1)");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
expect(callback.mostRecentCall.args[0]).toContain("SandboxError");
});
});
it("catches task contexts that reference non-existant locals", function(){
var callback = jasmine.createSpy();
task = this.client.createTask();
task.setContext("(function(locals){ var foo = locals.foo.bar; return { getFoo:function(){ return foo; } } })");
task.setLocals({bar:"hello"});
task.setCode("getFoo()");
task.on('eval', callback);
task.run();
waitsFor(function(){
return callback.callCount > 0;
});
runs(function(){
expect(callback.mostRecentCall.args[0]).toContain("SandboxError");
});
});
});
});
| rehanift/engine.js | spec/end-to-end/errors_spec.js | JavaScript | mit | 4,732 |
/* Copyright 1986, 1989, 1990 by Abacus Research and
* Development, Inc. All rights reserved.
*/
#if !defined (OMIT_RCSID_STRINGS)
char ROMlib_rcsid_qRegular[] =
"$Id: qRegular.c 63 2004-12-24 18:19:43Z ctm $";
#endif
/* Forward declarations in QuickDraw.h (DO NOT DELETE THIS LINE) */
#include "rsys/common.h"
#include "QuickDraw.h"
#include "CQuickDraw.h"
#include "DialogMgr.h"
#include "rsys/quick.h"
#include "rsys/cquick.h"
#include "rsys/ctl.h"
#include "rsys/wind.h"
using namespace Executor;
P1(PUBLIC pascal trap, void, FrameRect, Rect *, r)
{
CALLRECT(frame, r);
}
P1(PUBLIC pascal trap, void, PaintRect, Rect *, r)
{
CALLRECT(paint, r);
}
P1(PUBLIC pascal trap, void, EraseRect, Rect *, r)
{
CALLRECT(erase, r);
}
P1(PUBLIC pascal trap, void, InvertRect, Rect *, r)
{
CALLRECT(invert, r);
}
P2(PUBLIC pascal trap, void, FillRect, Rect *, r, Pattern, pat)
{
if (!EmptyRgn (PORT_VIS_REGION (thePort)))
{
ROMlib_fill_pat (pat);
CALLRECT(fill, r);
}
}
P1(PUBLIC pascal trap, void, FrameOval, Rect *, r)
{
CALLOVAL(frame, r);
}
P1(PUBLIC pascal trap, void, PaintOval, Rect *, r)
{
CALLOVAL(paint, r);
}
P1(PUBLIC pascal trap, void, EraseOval, Rect *, r)
{
CALLOVAL(erase, r);
}
P1(PUBLIC pascal trap, void, InvertOval, Rect *, r)
{
CALLOVAL(invert, r);
}
P2(PUBLIC pascal trap, void, FillOval, Rect *, r, Pattern, pat)
{
ROMlib_fill_pat (pat);
CALLOVAL(fill, r);
}
PRIVATE boolean_t
rect_matches_control_item (WindowPtr w, Rect *rp)
{
boolean_t retval;
ControlHandle c;
retval = FALSE;
for (c = WINDOW_CONTROL_LIST (w); !retval && c ; c = CTL_NEXT_CONTROL (c))
{
Rect r;
r = CTL_RECT (c);
retval = ((CW (r.top) - CW (rp->top) == CW (rp->bottom) - CW (r.bottom)) &&
(CW (r.left) - CW (rp->left) == CW (rp->right) - CW (r.right)));
}
return retval;
}
P3(PUBLIC pascal trap, void, FrameRoundRect, Rect *, r, INTEGER, ow,
INTEGER, oh)
{
boolean_t do_rect;
do_rect = FALSE;
if (ROMlib_cdef0_is_rectangular)
{
AuxWinHandle aux;
aux = MR (*lookup_aux_win (thePort));
if (aux && rect_matches_control_item (HxP(aux, awOwner), r))
do_rect = TRUE;
}
if (do_rect)
FrameRect (r);
else
CALLRRECT(frame, r, ow, oh);
}
P3(PUBLIC pascal trap, void, PaintRoundRect, Rect *, r, INTEGER, ow,
INTEGER, oh)
{
CALLRRECT(paint, r, ow, oh);
}
P3(PUBLIC pascal trap, void, EraseRoundRect, Rect *, r, INTEGER, ow,
INTEGER, oh)
{
CALLRRECT(erase, r, ow, oh);
}
P3(PUBLIC pascal trap, void, InvertRoundRect, Rect *, r, INTEGER, ow,
INTEGER, oh)
{
CALLRRECT(invert, r, ow, oh);
}
P4(PUBLIC pascal trap, void, FillRoundRect, Rect *, r, INTEGER, ow,
INTEGER, oh, Pattern, pat)
{
ROMlib_fill_pat (pat);
CALLRRECT(fill, r, ow, oh);
}
P3(PUBLIC pascal trap, void, FrameArc, Rect *, r, INTEGER, start,
INTEGER, angle)
{
CALLARC(frame, r, start, angle);
}
P3(PUBLIC pascal trap, void, PaintArc, Rect *, r, INTEGER, start,
INTEGER, angle)
{
CALLARC(paint, r, start, angle);
}
P3(PUBLIC pascal trap, void, EraseArc, Rect *, r, INTEGER, start,
INTEGER, angle)
{
CALLARC(erase, r, start, angle);
}
P3(PUBLIC pascal trap, void, InvertArc, Rect *, r, INTEGER, start,
INTEGER, angle)
{
CALLARC(invert, r, start, angle);
}
P4(PUBLIC pascal trap, void, FillArc, Rect *, r, INTEGER, start,
INTEGER, angle, Pattern, pat)
{
ROMlib_fill_pat (pat);
CALLARC (fill, r, start, angle);
}
P1(PUBLIC pascal trap, void, FrameRgn, RgnHandle, rh)
{
CALLRGN(frame, rh);
}
P1(PUBLIC pascal trap, void, PaintRgn, RgnHandle, rh)
{
CALLRGN(paint, rh);
}
P1(PUBLIC pascal trap, void, EraseRgn, RgnHandle, rh)
{
CALLRGN(erase, rh);
}
P1(PUBLIC pascal trap, void, InvertRgn, RgnHandle, rh)
{
CALLRGN(invert, rh);
}
P2(PUBLIC pascal trap, void, FillRgn, RgnHandle, rh, Pattern, pat)
{
ROMlib_fill_pat (pat);
CALLRGN(fill, rh);
}
P1(PUBLIC pascal trap, void, FramePoly, PolyHandle, poly)
{
CALLPOLY(frame, poly);
}
P1(PUBLIC pascal trap, void, PaintPoly, PolyHandle, poly)
{
CALLPOLY(paint, poly);
}
P1(PUBLIC pascal trap, void, ErasePoly, PolyHandle, poly)
{
CALLPOLY(erase, poly);
}
P1(PUBLIC pascal trap, void, InvertPoly, PolyHandle, poly)
{
CALLPOLY(invert, poly);
}
P2(PUBLIC pascal trap, void, FillPoly, PolyHandle, poly, Pattern, pat)
{
ROMlib_fill_pat (pat);
CALLPOLY (fill, poly);
}
| MaddTheSane/executor | src/qRegular.cpp | C++ | mit | 4,494 |
using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace LentilToolbox
{
//-------------------派生文本框类----------------------
//修改后不会影响dB和dd的参数
public class TextBoxInt: TextBox
{
public TextBoxInt()
{
}
private int value = 0;
public void Check()
{
if ((Regex.IsMatch(Text, @"^\d+$")) && (Text != "0"))
{
value = Convert.ToInt32(Text);
}
else
{
MessageBox.Show(Name + "一般是正整数值,请填写一个正整数");
}
}
public int consult()
{
Check();
return value;
}
}
public class TextBoxDouble : TextBox
{
public TextBoxDouble()
{
}
private double value = 0;
public void Check()
{
if (Regex.IsMatch(Text, @"^\d+(\.\d+)?$"))
{
value = Convert.ToDouble(Text);
}
else
{
MessageBox.Show(Name + "一般是正实数值,请填写一个正实数");
}
}
public double consult()
{
Check();
return value;
}
}
//修改后会影响dB和dd的参数
public class TextBoxIntFactor : TextBoxInt
{
private ftrwin ParentWin;
public TextBoxIntFactor(ftrwin oftrwin)
{
ParentWin = oftrwin;
this.Leave += new System.EventHandler(IntTextFactorChanged);
}
private void IntTextFactorChanged(object sender, EventArgs e)
{
ParentWin.refreshdBAnddd();
//MessageBox.Show("Faxtor Changed");
}
}
public class TextBoxDoubleFactor : TextBoxDouble
{
private ftrwin ParentWin;
public TextBoxDoubleFactor(ftrwin oftrwin)
{
ParentWin = oftrwin;
this.Leave += new System.EventHandler(DoubleTextFactorChanged);
}
private void DoubleTextFactorChanged(object sender, EventArgs e)
{
ParentWin.refreshdBAnddd();
//MessageBox.Show("Faxtor Changed");
}
}
}
| Lentil1016/LTB | v1.1/LentilToolbox/TextBox.cs | C# | mit | 2,271 |
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactInputSelection
*/
"use strict";
var ReactDOMSelection = require("./ReactDOMSelection");
var getActiveElement = require("./getActiveElement");
var nodeContains = require("./nodeContains");
function isInDocument(node) {
return nodeContains(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
return elem && (
(elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.nodeName === 'TEXTAREA' ||
elem.contentEditable === 'true'
);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange:
ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
ReactInputSelection.getSelection(focusedElem) :
null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem &&
isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(
priorFocusedElem,
priorSelectionRange
);
}
priorFocusedElem.focus();
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName === 'INPUT') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || {start: 0, end: 0};
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName === 'INPUT') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
| M3kH/tire-bouchon | node_modules/grunt-react/node_modules/react-tools/build/modules/ReactInputSelection.js | JavaScript | mit | 4,502 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
import frappe
def get_parent_doc(doc):
"""Returns document of `reference_doctype`, `reference_doctype`"""
if not hasattr(doc, "parent_doc"):
if doc.reference_doctype and doc.reference_name:
doc.parent_doc = frappe.get_doc(doc.reference_doctype, doc.reference_name)
else:
doc.parent_doc = None
return doc.parent_doc
def set_timeline_doc(doc):
"""Set timeline_doctype and timeline_name"""
parent_doc = get_parent_doc(doc)
if (doc.timeline_doctype and doc.timeline_name) or not parent_doc:
return
timeline_field = parent_doc.meta.timeline_field
if not timeline_field:
return
doctype = parent_doc.meta.get_link_doctype(timeline_field)
name = parent_doc.get(timeline_field)
if doctype and name:
doc.timeline_doctype = doctype
doc.timeline_name = name
else:
return
def find(list_of_dict, match_function):
'''Returns a dict in a list of dicts on matching the conditions
provided in match function
Usage:
list_of_dict = [{'name': 'Suraj'}, {'name': 'Aditya'}]
required_dict = find(list_of_dict, lambda d: d['name'] == 'Aditya')
'''
for entry in list_of_dict:
if match_function(entry):
return entry
return None
def find_all(list_of_dict, match_function):
'''Returns all matching dicts in a list of dicts.
Uses matching function to filter out the dicts
Usage:
colored_shapes = [
{'color': 'red', 'shape': 'square'},
{'color': 'red', 'shape': 'circle'},
{'color': 'blue', 'shape': 'triangle'}
]
red_shapes = find_all(colored_shapes, lambda d: d['color'] == 'red')
'''
found = []
for entry in list_of_dict:
if match_function(entry):
found.append(entry)
return found
def ljust_list(_list, length, fill_word=None):
"""
Similar to ljust but for list.
Usage:
$ ljust_list([1, 2, 3], 5)
> [1, 2, 3, None, None]
"""
# make a copy to avoid mutation of passed list
_list = list(_list)
fill_length = length - len(_list)
if fill_length > 0:
_list.extend([fill_word] * fill_length)
return _list
| mhbu50/frappe | frappe/core/utils.py | Python | mit | 2,081 |
/*
Problem 1. Say Hello
Write a method that asks the user for his name and prints “Hello, <name>”
Write a program to test this method.
Example:
input output
Peter Hello, Peter!
*/
using System;
class SayHello
{
static void PrintHello(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
static void Main()
{
Console.Write("Please, enter your first name: ");
string name = Console.ReadLine();
PrintHello(name);
}
}
| AdrianApostolov/TelerikAcademy | Homeworks/C#2/MethodsHomework/01.SayHello/SayHello.cs | C# | mit | 497 |
// Copied from the lunr.js test suite
var stemmingFixture = { "läufer": "lauf" };
test('should stem words correctly', function () {
Object.keys(stemmingFixture).forEach(function (testWord) {
var expected = stemmingFixture[testWord];
equal(lunr.de.stemmer(testWord), expected);
});
});
test('should be registered with lunr.Pipeline', function () {
equal(lunr.de.stemmer.label, 'stemmer-de');
deepEqual(lunr.Pipeline.registeredFunctions['stemmer-de'], lunr.de.stemmer);
}); | severinh/lunr.de.js | test/stemmer_test.js | JavaScript | mit | 492 |
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { getComponentTestId } from 'utils/test-utils';
import { head } from 'ramda';
import Modal from 'react-modal';
import * as nodeValidation from 'validations/node';
import * as eventUtils from 'utils/event';
import EditNodeCptModal from './component';
const renderComponent = (props) => {
Modal.setAppElement(document.body);
return {
...render(<EditNodeCptModal {...props} />),
element: document.body.lastChild,
};
};
describe('EditNodeCptModal Component', () => {
let component;
describe('When node has no parents', () => {
const props = {
node: {
id: 'Node 1',
states: [
'True',
'False',
],
parents: [],
cpt: {
True: 0.5,
False: 0.5,
},
},
hasParents: false,
onSave: jest.fn(),
onCancel: jest.fn(),
onAlert: jest.fn(),
};
beforeEach(() => {
component = renderComponent(props);
});
it('matches snapshot', () => {
expect(component.element).toMatchSnapshot();
});
describe('When key pressed in cpt input', () => {
beforeEach(() => {
props.onSave.mockClear();
});
describe('and is "enter" key', () => {
const { isEnterKey } = eventUtils;
beforeEach(() => {
const { getAllByTestId } = component;
const inputCptTrueState = head(getAllByTestId(getComponentTestId('InputCpt', 'True')));
eventUtils.isEnterKey = () => true;
fireEvent.keyUp(inputCptTrueState);
});
afterAll(() => {
eventUtils.isEnterKey = isEnterKey;
});
it('calls onSave fucntion', () => {
expect(props.onSave).toHaveBeenCalledWith(props.node.id, props.node.cpt);
});
});
describe('and is not "enter" key', () => {
const { isEnterKey } = eventUtils;
beforeEach(() => {
const { getAllByTestId } = component;
const inputCptTrueState = head(getAllByTestId(getComponentTestId('InputCpt', 'True')));
eventUtils.isEnterKey = () => false;
fireEvent.keyUp(inputCptTrueState);
});
afterAll(() => {
eventUtils.isEnterKey = isEnterKey;
});
it('does not call onSave fucntion', () => {
expect(props.onSave).not.toHaveBeenCalled();
});
});
});
describe('When saving', () => {
beforeEach(() => {
props.onSave.mockClear();
props.onAlert.mockClear();
});
describe('and cpt is valid', () => {
beforeEach(() => {
const { getByText } = component;
const saveButton = getByText('Salvar');
fireEvent.click(saveButton);
});
it('calls onSave function with cpt', () => {
expect(props.onSave).toHaveBeenCalledWith(props.node.id, props.node.cpt);
});
});
describe('and cpt is invalid', () => {
const { isNodeCptValid } = nodeValidation;
beforeEach(() => {
const { getByText } = component;
const saveButton = getByText('Salvar');
nodeValidation.isNodeCptValid = () => false;
fireEvent.click(saveButton);
});
afterAll(() => {
nodeValidation.isNodeCptValid = isNodeCptValid;
});
it('calls onAlert function with message', () => {
expect(props.onAlert).toHaveBeenCalledWith('A soma das probabilidades para cada uma das linhas deve ser igual a 1');
});
});
});
});
describe('When node has parents', () => {
const props = {
node: {
id: 'Node 3',
states: [
'True',
'False',
],
parents: [
'Node 2',
'Node 1',
],
cpt: [
{
when: {
'Node 2': 'True',
'Node 1': 'True',
},
then: {
True: 0.5,
False: 0.5,
},
},
{
when: {
'Node 2': 'False',
'Node 1': 'True',
},
then: {
True: 0.5,
False: 0.5,
},
},
{
when: {
'Node 2': 'True',
'Node 1': 'False',
},
then: {
True: 0.5,
False: 0.5,
},
},
{
when: {
'Node 2': 'False',
'Node 1': 'False',
},
then: {
True: 0.5,
False: 0.5,
},
},
],
},
hasParents: true,
onSave: jest.fn(),
onCancel: jest.fn(),
onAlert: jest.fn(),
};
beforeEach(() => {
component = renderComponent(props);
});
it('matches snapshot', () => {
expect(component.element).toMatchSnapshot();
});
describe('When key pressed in cpt input', () => {
beforeEach(() => {
props.onSave.mockClear();
});
describe('and is "enter" key', () => {
const { isEnterKey } = eventUtils;
beforeEach(() => {
const { getAllByTestId } = component;
const inputCptTrueState = head(getAllByTestId(getComponentTestId('InputCpt', 'True')));
eventUtils.isEnterKey = () => true;
fireEvent.keyUp(inputCptTrueState);
});
afterAll(() => {
eventUtils.isEnterKey = isEnterKey;
});
it('calls onSave fucntion', () => {
expect(props.onSave).toHaveBeenCalledWith(props.node.id, props.node.cpt);
});
});
describe('and is not "enter" key', () => {
const { isEnterKey } = eventUtils;
beforeEach(() => {
const { getAllByTestId } = component;
const inputCptTrueState = head(getAllByTestId(getComponentTestId('InputCpt', 'True')));
eventUtils.isEnterKey = () => false;
fireEvent.keyUp(inputCptTrueState);
});
afterAll(() => {
eventUtils.isEnterKey = isEnterKey;
});
it('does not call onSave fucntion', () => {
expect(props.onSave).not.toHaveBeenCalled();
});
});
});
describe('When saving', () => {
beforeEach(() => {
props.onSave.mockClear();
props.onAlert.mockClear();
});
describe('and cpt is valid', () => {
beforeEach(() => {
const { getByText } = component;
const saveButton = getByText('Salvar');
fireEvent.click(saveButton);
});
it('calls onSave function with cpt', () => {
expect(props.onSave).toHaveBeenCalledWith(props.node.id, props.node.cpt);
});
});
describe('and cpt is invalid', () => {
const { isNodeCptValid } = nodeValidation;
beforeEach(() => {
const { getByText } = component;
const saveButton = getByText('Salvar');
nodeValidation.isNodeCptValid = () => false;
fireEvent.click(saveButton);
});
afterAll(() => {
nodeValidation.isNodeCptValid = isNodeCptValid;
});
it('calls onAlert function with message', () => {
expect(props.onAlert).toHaveBeenCalledWith('A soma das probabilidades para cada uma das linhas deve ser igual a 1');
});
});
});
});
});
| fhelwanger/bayesjs-editor | src/components/EditNodeCptModal/index.test.js | JavaScript | mit | 7,502 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About TheoremCoin</source>
<translation>Om TheoremCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>TheoremCoin</b> version</source>
<translation><b>TheoremCoin</b> versjon</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2015 The TheoremCoin developers</source>
<translation>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2015 The TheoremCoin developers</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressebok</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Lag en ny adresse</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adressen til systemets utklippstavle</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Ny Adresse</translation>
</message>
<message>
<location line="-43"/>
<source>These are your TheoremCoin 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>Dette er adressene for å motta betalinger. Du ønsker kanskje å gi ulike adresser til hver avsender så du lettere kan holde øye med hvem som betaler deg.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Kopier Adresse</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Vis &QR Kode</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a TheoremCoin address</source>
<translation>Signer en melding for å bevise din egen TheoremCoin adresse.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signer &Melding</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Slett den valgte adressen fra listen.</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified TheoremCoin address</source>
<translation>Verifiser en melding får å forsikre deg om at den er signert med en spesifikk TheoremCoin adresse</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiser en melding</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Slett</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Kopier &Merkelapp</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Rediger</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Eksporter Adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Feil under eksportering</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog for Adgangsfrase</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Angi adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Ny adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Gjenta ny adgangsfrase</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Krypter lommebok</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekrypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Endre adgangsfrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Bekreft kryptering av lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Advarsel: Viss du krypterer lommeboken og mister passordet vil du <b>MISTE ALLE MYNTENE DINE</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Er du sikker på at du vil kryptere lommeboken?</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>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Advarsel: Caps Lock er på !</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Lommebok kryptert</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>TheoremCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av lommebok feilet</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>De angitte adgangsfrasene er ulike.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Opplåsing av lommebok feilet</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av lommebok feilet</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Adgangsfrase for lommebok endret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>Signer &melding...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Vis generell oversikt over lommeboken</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaksjoner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Vis transaksjonshistorikk</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Endre listen med lagrede adresser og merkelapper</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen med adresser for å motta betalinger</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Avslutt</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avslutt applikasjonen</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about TheoremCoin</source>
<translation>Vis info om TheoremCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vis informasjon om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Innstillinger...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Krypter Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>Lag &Sikkerhetskopi av Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Endre Adgangsfrase...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Eksporter...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a TheoremCoin address</source>
<translation>Send coins til en TheoremCoin adresse</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for TheoremCoin</source>
<translation>Endre innstillingene til TheoremCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter dataene i nåværende fane til en fil</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Krypter eller dekrypter lommeboken</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Sikkerhetskopiér lommebok til annet sted</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Feilsøkingsvindu</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Åpne konsoll for feilsøk og diagnostikk</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifiser melding...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>TheoremCoin</source>
<translation>TheoremCoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+193"/>
<source>&About TheoremCoin</source>
<translation>&Om TheoremCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Gjem / vis</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Lås Lommeboken</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Lås lommeboken</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Innstillinger</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hjelp</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Verktøylinje for faner</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>TheoremCoin client</source>
<translation>TheoremCoin klient</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to TheoremCoin network</source>
<translation><numerusform>%n aktiv tilkobling til TheoremCoin nettverket</numerusform><numerusform>%n aktive tilkoblinger til TheoremCoin nettverket</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>&Lås opp lommeboken</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Ajour</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Kommer ajour...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Sendt transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Innkommende transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløp: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid TheoremCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>ulåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>låst</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Sikkerhetskopier Lommeboken</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lommebokdata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sikkerhetskopiering feilet</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n sekund</numerusform><numerusform>%n sekunder</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minutt</numerusform><numerusform>%n minutter</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n time</numerusform><numerusform>%n timer</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dager</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<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="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<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="+324"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. TheoremCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Nettverksvarsel</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Mengde:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioritet:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lav Utdata:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>nei</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Etter Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Endring:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Fjern alt valgt</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Tre modus</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Liste modus</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Bekreftelser</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioritet</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopier mengde</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopier gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopier etter gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopier prioritet</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopier veksel</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>høyest</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>høy</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>medium-høy</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>medium</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>lav-medium</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>lav</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>lavest</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ja</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Denne merkelappen blir rød, viss endringen er mindre enn %1
Dette betyr at det trengs en avgift på minimum %2.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>endring fra %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(endring)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Rediger adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Merkelapp</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Merkelappen assosiert med denne adressen</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</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 type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny utsendingsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Rediger mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Rediger utsendingsadresse</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den oppgitte adressen "%1" er allerede i adresseboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid TheoremCoin address.</source>
<translation>Den angitte adressen "%1" er ikke en gyldig TheoremCoin adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse opp lommeboken.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generering av ny nøkkel feilet.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>TheoremCoin-Qt</source>
<translation>TheoremCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versjon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start Minimert</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Innstillinger</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hoved</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betal transaksjons&gebyr</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start TheoremCoin after logging in to the system.</source>
<translation>Start TheoremCoin automatisk ved hver innlogging.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start TheoremCoin on system login</source>
<translation>&Start Theoremcoin ved innlogging</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Nettverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the TheoremCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Sett opp port vha. &UPnP</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyens port (f.eks. 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the TheoremCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Vindu</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systemkurv istedenfor oppgavelinjen</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>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukking</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visning</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Språk for brukergrensesnitt</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting TheoremCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enhet for visning av beløper:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Velg standard delt enhet for visning i grensesnittet og for sending av theoremcoins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Skal mynt kontroll funksjoner vises eller ikke.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Bruk</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>standardverdi</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Advarsel</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting TheoremCoin.</source>
<translation>Denne innstillingen vil tre i kraft etter TheoremCoin er blitt startet på nytt.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Angitt proxyadresse er ugyldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the TheoremCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Ubekreftet:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Disponibelt:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Umoden:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Minet saldo har ikke modnet enda</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Totalt:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Siste transaksjoner</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>ute av synk</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start theoremcoin: 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 type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Merkelapp:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Melding:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Lagre som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnavn</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"/>
<source>N/A</source>
<translation>-</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Klientversjon</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasjon</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Bruker OpenSSL versjon</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Oppstartstidspunkt</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nettverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antall tilkoblinger</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokkjeden</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nåværende antall blokker</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Tidspunkt for siste blokk</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Åpne</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the TheoremCoin-Qt help message to get a list with possible TheoremCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Vis</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoll</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Byggedato</translation>
</message>
<message>
<location line="-104"/>
<source>TheoremCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>TheoremCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Loggfil for feilsøk</translation>
</message>
<message>
<location line="+7"/>
<source>Open the TheoremCoin 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>Tøm konsoll</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the TheoremCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Bruk opp og ned pil for å navigere historikken, og <b>Ctrl-L</b> for å tømme skjermen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> for en oversikt over kommandoer.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Theoremcoins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Mynt Kontroll Funksjoner</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Inndata...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automatisk valgte</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Utilstrekkelige midler!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Mengde:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Prioritet:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lav Utdata:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>nei</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Etter Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere enn én mottaker</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Legg til Mottaker</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Bekreft sending</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a TheoremCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopier mengde</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopier gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekreft sending av bitcoins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på du ønsker å sende %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>og</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresse for mottaker er ugyldig.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløpen som skal betales må være over 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Beløpet overstiger saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid TheoremCoin address</source>
<translation>ADVARSEL: Ugyldig TheoremCoin adresse</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Beløp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</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>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Merkelapp:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Velg adresse fra adresseboken</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>Lim inn adresse fra utklippstavlen</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>Fjern denne mottakeren</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a TheoremCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signer / Verifiser en melding</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Signér Melding</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Velg en adresse fra adresseboken</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</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>Skriv inn meldingen du vil signere her</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopier valgt signatur til utklippstavle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this TheoremCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tilbakestill alle felter for meldingssignering</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte "man-in-the-middle" angrep.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified TheoremCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tilbakestill alle felter for meldingsverifikasjon</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a TheoremCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikk "Signer Melding" for å generere signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter TheoremCoin signature</source>
<translation>Skriv inn TheoremCoin signatur</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Angitt adresse er ugyldig.</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>Vennligst sjekk adressen og prøv igjen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Angitt adresse refererer ikke til en nøkkel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Opplåsing av lommebok ble avbrutt.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signering av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Melding signert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunne ikke dekodes.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Vennligst sjekk signaturen og prøv igjen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen passer ikke til meldingen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikasjon av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Melding verifisert.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/frakoblet</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekreftet</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekreftelser</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kilde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generert</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Fra</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Til</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>merkelapp</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ikke akseptert</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksjonsgebyr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobeløp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Melding</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksjons-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informasjon for feilsøk</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksjon</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Inndata</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sann</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>usann</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har ikke blitt kringkastet uten problemer enda.</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>ukjent</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaksjonsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Her vises en detaljert beskrivelse av transaksjonen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekreftet (%1 bekreftelser)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Åpen for %n blokk til</numerusform><numerusform>Åpen for %n blokker til</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Ubekreftet</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Bekrefter (%1 av %2 anbefalte bekreftelser)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generert men ikke akseptert</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottatt fra</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling til deg selv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>-</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for da transaksjonen ble mottat.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transaksjon.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Mottaksadresse for transaksjonen</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløp fjernet eller lagt til saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denne uken</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denne måneden</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Forrige måned</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dette året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervall...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Til deg selv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andre</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Skriv inn adresse eller merkelapp for søk</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimumsbeløp</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Rediger merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Vis transaksjonsdetaljer</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+208"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+173"/>
<source>TheoremCoin version</source>
<translation>TheoremCoin versjon</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or theoremcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>List opp kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Vis hjelpetekst for en kommando</translation>
</message>
<message>
<location line="-147"/>
<source>Options:</source>
<translation>Innstillinger:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: theoremcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: theoremcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Angi lommebok fil (inne i data mappe)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Angi mappe for datafiler</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=theoremcoinrpc
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 "TheoremCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 63211 or testnet: 53211)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Hold maks <n> koblinger åpne til andre noder (standardverdi: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Angi din egen offentlige adresse</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation>
</message>
<message>
<location line="-36"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation>
</message>
<message>
<location line="+63"/>
<source>Listen for JSON-RPC connections on <port> (default: 63212 or testnet: 53212)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Bruk testnettverket</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation>
</message>
<message>
<location line="+94"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation>
</message>
<message>
<location line="-104"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong TheoremCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+132"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Advarsel: Feil ved lesing av wallet.dat! Alle taster lest riktig, men transaksjon dataene eller adresse innlegg er kanskje manglende eller feil.</translation>
</message>
<message>
<location line="-17"/>
<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>Advarsel: wallet.dat korrupt, data reddet! Original wallet.dat lagret som wallet.{timestamp}.bak i %s; hvis din saldo eller dine transaksjoner ikke er korrekte bør du gjenopprette fra en backup.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Forsøk å berge private nøkler fra en korrupt wallet.dat</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Valg for opprettelse av blokker:</translation>
</message>
<message>
<location line="-68"/>
<source>Connect only to the specified node(s)</source>
<translation>Koble kun til angitt(e) node(r)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation>
</message>
<message>
<location line="+102"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation>
</message>
<message>
<location line="-92"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maks mottaksbuffer per forbindelse, <n>*1000 bytes (standardverdi: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maks sendebuffer per forbindelse, <n>*1000 bytes (standardverdi: 1000)</translation>
</message>
<message>
<location line="-17"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Koble kun til noder i nettverket <nett> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+31"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL valg: (se Bitcoin Wiki for instruksjoner for oppsett av SSL)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation>
</message>
<message>
<location line="+116"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation>
</message>
<message>
<location line="-26"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Username for JSON-RPC connections</source>
<translation>Brukernavn for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Verifiserer databasens integritet...</translation>
</message>
<message>
<location line="+43"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation>
</message>
<message>
<location line="-53"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat korrupt, bergning feilet</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>Passord for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-48"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node på <ip> (standardverdi: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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>Upgrade wallet to latest format</source>
<translation>Oppgradér lommebok til nyeste format</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Angi størrelse på nøkkel-lager til <n> (standardverdi: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servers sertifikat (standardverdi: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servers private nøkkel (standardverdi: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. TheoremCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<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="+3"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-174"/>
<source>This help message</source>
<translation>Denne hjelpemeldingen</translation>
</message>
<message>
<location line="+105"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Lommeboken %s holder til utenfor data mappen %s.</translation>
</message>
<message>
<location line="+36"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation>
</message>
<message>
<location line="-131"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation>
</message>
<message>
<location line="+127"/>
<source>Loading addresses...</source>
<translation>Laster adresser...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of TheoremCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart TheoremCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Feil ved lasting av wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ugyldig -proxy adresse: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ukjent nettverk angitt i -onlynet '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kunne ikke slå opp -bind adresse: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kunne ikke slå opp -externalip adresse: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ugyldig beløp for -paytxfee=<beløp>: '%s'</translation>
</message>
<message>
<location line="+59"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ugyldig beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Utilstrekkelige midler</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Laster blokkindeks...</translation>
</message>
<message>
<location line="-111"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Legg til node for tilkobling og hold forbindelsen åpen</translation>
</message>
<message>
<location line="+126"/>
<source>Unable to bind to %s on this computer. TheoremCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-102"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebyr per KB som skal legges til transaksjoner du sender</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. TheoremCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Loading wallet...</source>
<translation>Laster lommebok...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Kan ikke nedgradere lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Kan ikke skrive standardadresse</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Leser gjennom...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Ferdig med lasting</translation>
</message>
<message>
<location line="-161"/>
<source>To use the %s option</source>
<translation>For å bruke %s opsjonen</translation>
</message>
<message>
<location line="+188"/>
<source>Error</source>
<translation>Feil</translation>
</message>
<message>
<location line="-18"/>
<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>Du må sette rpcpassword=<passord> i konfigurasjonsfilen:
%s
Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation>
</message>
</context>
</TS> | TheoremCrypto/TheoremCoin | src/qt/locale/bitcoin_nb.ts | TypeScript | mit | 120,368 |
<?php
namespace minipipo1\BlogBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class CommentType extends AbstractType
{
/**
* @var \minipipo1\UserBundle\Entity\User $current_user
*/
private $current_user;
public function __construct(\minipipo1\UserBundle\Entity\User $current_user = NULL) {
$this->current_user = $current_user;
}
public function buildForm(FormBuilder $builder, array $options)
{
$cu = $this->current_user;
$builder
->add('content', 'textarea', array('required' => false)) // Le required à false est juste là pour empêcher que Symfony mette l'attribut required car il cause un bug à cause de TinyMCE
->add('auteur', 'entity', array(
'empty_value' => "Choisissez l'auteur",
'required' => true,
'class' => 'minipipo1UserBundle:Membre',
'query_builder' => function(\minipipo1\UserBundle\Entity\MembreRepository $er) use ($options, $cu) {
if ($options["data"]->getId())
$user = $options["data"]->getAuteur()->getUser();
else
$user = $cu;
return $er->createQueryBuilder('m')
->where('m.user = :user')
->setParameter('user', $user);
},
))
;
}
public function getName()
{
return 'minipipo1_blogbundle_commenttype';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'minipipo1\BlogBundle\Entity\Comment',
);
}
}
| ilancoulon/familyWeb | src/minipipo1/BlogBundle/Form/CommentType.php | PHP | mit | 1,893 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Lidgren.Network;
using ClientServerExtension;
using System.ComponentModel;
namespace Troma
{
public class GameClient
{
#region Constants
private const string APP_NAME = "TROMA";
private const int PORT = 11420;
public const int MAX_CLIENT = 10;
private const int DT = 30; // ms
#endregion
#region Fields
private NetClient Client;
private NetPeerConfiguration Config;
private NetIncomingMessage IncMsg;
private NetOutgoingMessage OutMsg;
public int ID;
public STATE State;
public INPUT Input;
public bool Alive;
public int Score;
public Map Terrain;
public int MaxScore;
public event EventHandler ScoreChanged;
public event EventHandler EndedGame;
public List<OtherPlayer> Players;
public Tuple<int, string, int>[] Scoring;
private System.Timers.Timer timerUpdate;
private BackgroundWorker backgroundUpdater;
public bool Connected
{
get
{
return (Client.ConnectionStatus == NetConnectionStatus.Connected);
}
}
#endregion
public GameClient()
{
Initialize();
SetupClient();
}
#region Initialization
private void Initialize()
{
Players = new List<OtherPlayer>();
Players.Capacity = MAX_CLIENT;
Score = 0;
timerUpdate = new System.Timers.Timer(35); // 35ms
timerUpdate.Elapsed += new System.Timers.ElapsedEventHandler(UpdateElapsed);
backgroundUpdater = new BackgroundWorker();
backgroundUpdater.DoWork += HandleMsg;
}
private void SetupClient()
{
Config = new NetPeerConfiguration(APP_NAME);
Config.EnableUPnP = true;
Config.EnableMessageType(NetIncomingMessageType.Data);
Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
#if DEBUG
Config.EnableMessageType(NetIncomingMessageType.WarningMessage);
Config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
Config.EnableMessageType(NetIncomingMessageType.ErrorMessage);
Config.EnableMessageType(NetIncomingMessageType.Error);
Config.EnableMessageType(NetIncomingMessageType.DebugMessage);
#endif
Client = new NetClient(Config);
Client.Start();
Client.UPnP.ForwardPort(Client.Port, "Troma client");
#if DEBUG
Console.WriteLine("Client start.");
#endif
}
private void Connect(string host)
{
OutMsg = Client.CreateMessage();
OutMsg.Write((byte)PacketTypes.LOGIN);
OutMsg.Write(Settings.Name);
Client.Connect(host, PORT, OutMsg);
#if DEBUG
Console.WriteLine("Send connection request to server.");
#endif
}
private void WaitInitialData()
{
DateTime expired = DateTime.Now + new TimeSpan(0, 0, 0, 10, 0);
bool canStart = false;
#if DEBUG
Console.WriteLine("Waiting initial data...");
#endif
while (!canStart && expired > DateTime.Now)
{
if ((IncMsg = Client.ReadMessage()) != null)
{
switch (IncMsg.MessageType)
{
case NetIncomingMessageType.Data:
#region Connection Approved
switch (IncMsg.ReadPacketType())
{
case PacketTypes.LOGIN:
ID = IncMsg.ReadInt32();
Terrain = (Map)IncMsg.ReadByte();
Terrain = Map.Cracovie;
MaxScore = IncMsg.ReadInt32();
canStart = true;
#if DEBUG
Console.WriteLine("Confirm initial data!");
#endif
break;
default:
break;
}
break;
#endregion
#if DEBUG
case NetIncomingMessageType.VerboseDebugMessage:
break;
case NetIncomingMessageType.DebugMessage:
break;
case NetIncomingMessageType.WarningMessage:
break;
case NetIncomingMessageType.ErrorMessage:
break;
case NetIncomingMessageType.Error:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Corrupted message!!!");
break;
#endif
default:
break;
}
#if DEBUG
Console.ResetColor();
#endif
Client.Recycle(IncMsg); // generate less garbage
}
System.Threading.Thread.Sleep(1);
}
}
#endregion
public void Join(string host)
{
Connect(host);
WaitInitialData();
}
public void Shutdown()
{
Client.Shutdown("End");
}
public void Start()
{
timerUpdate.Start();
backgroundUpdater.RunWorkerAsync();
}
private void HandleMsg(object sender, DoWorkEventArgs e)
{
OtherPlayer p;
int id;
string name;
while (true)
{
if ((IncMsg = Client.ReadMessage()) != null)
{
switch (IncMsg.MessageType)
{
case NetIncomingMessageType.Data:
#region Process Data
switch (IncMsg.ReadPacketType())
{
case PacketTypes.QUIT:
p = FindPlayer(IncMsg.ReadInt32(), Players);
if (p == null)
break;
Players.Remove(p);
break;
case PacketTypes.KILL:
Alive = false;
break;
case PacketTypes.SPAWN:
Alive = true;
State = IncMsg.ReadPlayerState();
break;
case PacketTypes.SHOOT:
p = FindPlayer(IncMsg.ReadInt32(), Players);
if (p == null)
break;
//p.Shoot();
break;
case PacketTypes.SCORE:
Score = IncMsg.ReadInt32();
ScoreChanged(null, null);
break;
case PacketTypes.END:
int size = IncMsg.ReadInt32();
Scoring = new Tuple<int, string, int>[size];
for (int i = 0; i < size; i++)
{
Scoring[i] = new Tuple<int, string, int>(
IncMsg.ReadInt32(),
IncMsg.ReadString(),
IncMsg.ReadInt32());
}
EndedGame(null, null);
break;
case PacketTypes.STATE:
id = IncMsg.ReadInt32();
name = IncMsg.ReadString();
p = FindPlayer(id, Players);
if (p == null)
{
p = new OtherPlayer(name, id);
Players.Add(p);
}
p.State = IncMsg.ReadPlayerState();
break;
case PacketTypes.INPUT:
p = FindPlayer(IncMsg.ReadInt32(), Players);
if (p == null)
break;
p.Input = IncMsg.ReadPlayerInput();
break;
default:
break;
}
break;
#endregion
default:
break;
}
Client.Recycle(IncMsg); // generate less garbage
}
System.Threading.Thread.Sleep(1);
}
}
private void UpdateElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
SendState(State);
SendInput(Input);
}
private void SendState(STATE s)
{
OutMsg = Client.CreateMessage();
OutMsg.Write((byte)PacketTypes.STATE);
OutMsg.WritePlayerState(s);
Client.SendMessage(OutMsg, NetDeliveryMethod.UnreliableSequenced, 2);
}
private void SendInput(INPUT i)
{
OutMsg = Client.CreateMessage();
OutMsg.Write((byte)PacketTypes.INPUT);
OutMsg.WritePlayerInput(i);
Client.SendMessage(OutMsg, NetDeliveryMethod.UnreliableSequenced, 2);
}
public void SendShoot()
{
OutMsg = Client.CreateMessage();
OutMsg.Write((byte)PacketTypes.SHOOT);
Client.SendMessage(OutMsg, NetDeliveryMethod.Unreliable, 0);
}
public void SetData(STATE s, INPUT i)
{
State = s;
Input = i;
}
#region Help Methods
public OtherPlayer FindPlayer(int id, List<OtherPlayer> list)
{
foreach (OtherPlayer player in list)
{
if (player.ID == id)
return player;
}
return null;
}
#endregion
}
}
| dethi/troma | src/Game/Troma/Troma/Game/GameClient.cs | C# | mit | 11,170 |
<?php
abstract class Controller {
public $view;
public $input;
private $_uri;
private $_errors;
private $_success;
private $_renderView;
private $_name;
const VALIDATION_NUMBER = 1;
const VALIDATION_ALPHANUM = 2;
public function __construct() {
$this->view = new stdClass();
$this->input = new stdClass();
$this->_errors = array();
$this->_success = array();
}
public function getControllerName() {
return $this->_name;
}
public function getUser() {
global $USER;
return $USER;
}
public function setUser($user) {
global $USER;
$USER = $user;
}
public function setName($s) {
$this->_name = $s;
}
public function setRenderView($str) {
$this->_renderView = $str;
}
public function getRenderViewForDisplay() {
return str_replace('indexIndex','index',$this->_renderView);
}
public function getRenderview() {
return $this->_renderView;
}
public function callAction($action,$arg=null) {
$this->{$action}($arg);
$this->render();
}
public function addParam($name,$value) {
$this->input->{$name} = $value;
}
public function setUri($s) {$this->_uri = $s;}
public function getUri() {return $this->_uri;}
public function formUnserialize($salt,$name) {
if (md5($_POST[$name].$salt) == $_POST[$name.'Hash']) {
return unserialize(gzinflate(base64_decode($_POST[$name])));
} else {
return null;
}
}
public function formSerialize($data,$salt,$name) {
$ser = base64_encode(gzdeflate(serialize($data)));
$hash = md5($ser.$salt);
return '<input type="hidden" name="'.$name.'" value="'.$ser.'"/><input type="hidden" name="'.$name.'Hash" value="'.$hash.'"/>';
}
public function formEscape($text) {
return htmlspecialchars($text);
}
public function hasErrorMessages() {
return $this->_errors;
}
public function addErrorMsg($msg) {
array_push($this->_errors,$msg);
}
public function addSuccessMsg($msg) {
array_push($this->_success,$msg);
}
public function renderMessages() {
$result = '';
if ($this->_errors) {
$result .= Bootstrap_Alert::error(implode('<br/>',$this->_errors));
}
if ($this->_success) {
$result .= Bootstrap_Alert::success(implode('<br/>',$this->_success));
}
return $result;
}
public function args($id,$validate = null) {
if (isset($this->input->{'arg'.$id})) {
if ($validate != null) {
$str = $this->input->{'arg'.$id};
switch ($validate) {
case Controller::VALIDATION_NUMBER : return ctype_digit($str)?$str:null;
case Controller::VALIDATION_ALPHANUM : return ctype_alnum($str)?$str:null;
default : return null;
}
} else {
return trim($this->input->{'arg'.$id});
}
} else {
return null;
}
}
public function forwardAction($action) {
$array = get_object_vars($this->input);
foreach ($array as $idx => $value) {
if (strpos($idx,'arg') === 0) {
continue;
}
unset($this->input->$idx);
}
$array = get_object_vars($this->view);
foreach ($array as $idx => $value) {unset($this->input->$idx);}
//echo '<pre>';print_r($this);exit;
if (strstr($this->_renderView,'/')) {
$parts = explode("/",$this->_renderView);
$this->_renderView = $parts[0].'/'.strtolower($this->_name).ucfirst($action);
} else {
$this->_renderView = $action;
}
$this->callAction($action.'Action');
exit;
}
public function get($name,$trim = true) {
if (isset($_GET[$name])) {
if (is_array($_GET[$name])) {
return $_GET[$name];
} else {
if ($trim) {
return trim($_GET[$name]);
} else {
return $_GET[$name];
}
}
} else {
return null;
}
}
public function isPost() {
return $_SERVER['REQUEST_METHOD']=='POST';
}
public function post($name,$trim = true) {
if (isset($_POST[$name])) {
if (is_array($_POST[$name])) {
return $_POST[$name];
} else {
if ($trim) {
return trim($_POST[$name]);
} else {
return $_POST[$name];
}
}
}
}
} | bryhardt/grcpool | classes/core/Controller.php | PHP | mit | 3,916 |
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react/addons'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
| tonikarttunen/tonikarttunen-com | src/decorators/withViewport.js | JavaScript | mit | 1,757 |
module Nodectl
VERSION = "0.2.5.dev"
end
| sybis/nodectl | lib/nodectl/version.rb | Ruby | mit | 43 |
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
void c_to_f(void);
void f_to_c(void);
int main(void)
{
int choice;
char again;
do
{
system("CLS");
cout<<setw(10)<<" "<< "What conversion would you like to make?\n";// menu
cout<<setw(20)<<" "<< "1. Celsius to Fahrenhei\n\n";
// make a choice which functions to use.
cout<<setw(20)<<" "<< "2. Fahrenheit to Celsius\n\n";
cin>>choice;
switch(choice)
// go to chosen function
{
case 1:
{
c_to_f();
break;
}
case 2:
{
f_to_c();
break;
}
default:
{
cout<<setw(10)<<" "<< "Enter 1 ot 2 "<< endl;
// validate and correct input of function choice.
}
}
cout<<setw(10)<<" "<< "Do you wish to do another conversion? y for yes, n for no "; // return loop on y for yes.
cin>> again;
}while (again=='Y'||again=='y');
return 0;
}
void c_to_f(void)
{
system("CLS"); //clean screen for function data.
int temp,fahrenheit;
cout<< "\n\n\n ";
cout<<setw(10)<<" "<< "Enter the temperature in whole degress Celsius: \a";
cin>>temp;
fahrenheit=((temp*9)/5)+32;
cout<<endl<<setw(10)<<" "<<temp<<" degrees celsius is " <<fahrenheit<<"\a\n\n\n ";
}
void f_to_c(void)
{
system("CLS"); // clear screen for function data.
int temp, celsius;
cout<< "\n\n\n ";
cout<<setw(10)<<" "<< "Enter the temperature in whole degrees fahrenheit: \a";
cin>>temp;
celsius=((temp-32)*5)/9;
cout<<endl<<setw(10)<<" "<<temp<<" degrees fahrenheit is "<<celsius<<" degrees celsius \a\n\n\n";
}
| wshca/Modelling_ClimateChange_Forest_CPP | converter.cpp | C++ | mit | 1,540 |
import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';
class F7AccordionContent extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const props = this.props;
const {
className,
id,
style
} = props;
const classes = Utils.classNames(className, 'accordion-item-content', Mixins.colorClasses(props));
return React.createElement('div', {
id: id,
style: style,
className: classes
}, this.slots['default']);
}
get slots() {
return __reactComponentSlots(this.props);
}
}
__reactComponentSetProps(F7AccordionContent, Object.assign({
id: [String, Number]
}, Mixins.colorProps));
F7AccordionContent.displayName = 'f7-accordion-content';
export default F7AccordionContent; | AdrianV/Framework7 | packages/react/components/accordion-content.js | JavaScript | mit | 1,003 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-08-16 21:29
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('quotes', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='quote',
name='mentions',
field=models.ManyToManyField(blank=True, editable=False, related_name='mentioned_in', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='quote',
name='author',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='author_of', to=settings.AUTH_USER_MODEL),
),
]
| nivbend/memoir | quotes/migrations/0002_mentions.py | Python | mit | 885 |
<?php
namespace Biz\File\Service\Impl;
use Biz\BaseService;
use Biz\File\Dao\UploadFileDao;
use Biz\File\Service\FileImplementor;
use AppBundle\Common\FileToolkit;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Biz\User\Service\UserService;
class LocalFileImplementorImpl extends BaseService implements FileImplementor
{
public function getFile($file)
{
$file['fullpath'] = $this->getFileFullPath($file);
$file['webpath'] = '';
return $file;
}
public function getFullFile($file)
{
return $this->getFile($file);
}
public function addFile($targetType, $targetId, array $fileInfo = array(), UploadedFile $originalFile = null)
{
$errors = FileToolkit::validateFileExtension($originalFile);
if ($errors) {
@unlink($originalFile->getRealPath());
throw $this->createServiceException('该文件格式,不允许上传。');
}
$uploadFile = array();
$uploadFile['filename'] = $originalFile->getClientOriginalName();
$uploadFile['ext'] = FileToolkit::getFileExtension($originalFile);
$uploadFile['fileSize'] = $originalFile->getSize();
$filename = FileToolkit::generateFilename($uploadFile['ext']);
$uploadFile['hashId'] = "{$uploadFile['targetType']}/{$uploadFile['targetId']}/{$filename}";
$uploadFile['convertHash'] = "ch-{$uploadFile['hashId']}";
$uploadFile['convertStatus'] = 'none';
$uploadFile['type'] = FileToolkit::getFileTypeByExtension($uploadFile['ext']);
$uploadFile['isPublic'] = empty($fileInfo['isPublic']) ? 0 : 1;
$uploadFile['canDownload'] = empty($uploadFile['canDownload']) ? 0 : 1;
$uploadFile['updatedUserId'] = $uploadFile['createdUserId'] = $this->getCurrentUser()->id;
$uploadFile['updatedTime'] = $uploadFile['createdTime'] = time();
$targetPath = $this->getFilePath($targetType, $targetId);
$originalFile->move($targetPath, $filename);
return $uploadFile;
}
public function saveConvertResult($file, array $result = array())
{
}
public function convertFile($file, $status, $result = null, $callback = null)
{
throw $this->createServiceException('本地文件暂不支持转换');
}
public function updateFile($file, $fields)
{
}
public function makeUploadParams($params)
{
$uploadParams = array();
$uploadParams['storage'] = 'local';
$uploadParams['url'] = $params['defaultUploadUrl'];
$uploadParams['postParams'] = array();
$uploadParams['postParams']['token'] = $this->getUserService()->makeToken('fileupload', $params['user'], strtotime('+ 2 hours'));
return $uploadParams;
}
public function reconvert($globalId, $options)
{
}
public function getUploadAuth($params)
{
}
public function reconvertFile($file, $convertCallback, $pipeline = null)
{
}
//LocalFileImplementorImpl2
public function findFiles($file, $conditions)
{
}
public function prepareUpload($params)
{
$file = array();
$file['filename'] = empty($params['fileName']) ? '' : $params['fileName'];
$pos = strrpos($file['filename'], '.');
$file['ext'] = empty($pos) ? '' : substr($file['filename'], $pos + 1);
$file['fileSize'] = empty($params['fileSize']) ? 0 : $params['fileSize'];
$file['status'] = 'uploading';
$file['targetId'] = $params['targetId'];
$file['targetType'] = $params['targetType'];
$file['storage'] = 'local';
$file['type'] = FileToolkit::getFileTypeByExtension($file['ext']);
$file['updatedUserId'] = empty($params['userId']) ? 0 : $params['userId'];
$file['updatedTime'] = time();
$file['createdUserId'] = $file['updatedUserId'];
$file['createdTime'] = $file['updatedTime'];
$filename = FileToolkit::generateFilename($file['ext']);
$file['hashId'] = "{$file['targetType']}/{$file['targetId']}/{$filename}";
$file['convertHash'] = "ch-{$file['hashId']}";
$file['convertStatus'] = 'none';
return $file;
}
public function moveFile($targetType, $targetId, UploadedFile $originalFile = null, $data = array())
{
$errors = FileToolkit::validateFileExtension($originalFile);
if ($errors) {
@unlink($originalFile->getRealPath());
throw $this->createServiceException('该文件格式,不允许上传。');
}
$targetPath = $this->getFilePath($targetType, $targetId);
$filename = str_replace("{$targetType}/{$targetId}/", '', $data['hashId']);
$originalFile->move($targetPath, $filename);
}
public function reconvertOldFile($file, $convertCallback, $pipeline = null)
{
return null;
}
public function finishedUpload($file, $params)
{
return array_merge(array('success' => true, 'convertStatus' => 'success'), $params);
}
public function resumeUpload($hash, $params)
{
}
public function getDownloadFile($file, $ssl = false)
{
return $file;
}
public function deleteFile($file)
{
$filename = $this->getFileFullPath($file);
@unlink($filename);
return array('success' => true);
}
public function search($conditions)
{
$start = $conditions['start'];
$limit = $conditions['limit'];
unset($conditions['start']);
unset($conditions['limit']);
return $this->getUploadFileDao()->search($conditions, array('createdTime' => 'DESC'), $start, $limit);
}
public function getFileByGlobalId($globalId)
{
}
public function initUpload($params)
{
$uploadParams = array();
$uploadParams['uploadMode'] = 'local';
$uploadParams['url'] = $this->getUploadUrl($params);
$uploadParams['postParams'] = array();
$uploadParams['postParams']['token'] = $this->getUserService()->makeToken(
'fileupload',
$params['userId'],
strtotime('+ 2 hours'),
$params
);
return $uploadParams;
}
protected function getUploadUrl($params)
{
global $kernel;
$url = $kernel->getContainer()->get('router')->generate('uploadfile_upload', $params, true);
return $url;
}
protected function getFileFullPath($file)
{
$baseDirectory = $this->biz['topxia.disk.local_directory'];
return $baseDirectory.DIRECTORY_SEPARATOR.$file['hashId'];
}
protected function getFileWebPath($file)
{
if (!$file['isPublic']) {
return '';
}
return $this->biz['topxia.upload.public_url_path'].DIRECTORY_SEPARATOR.$file['hashId'];
}
protected function getFilePath($targetType, $targetId)
{
$baseDirectory = $this->biz['topxia.disk.local_directory'];
return $baseDirectory.DIRECTORY_SEPARATOR.$targetType.DIRECTORY_SEPARATOR.$targetId;
}
/**
* only support for cloud file.
*
* @param $globalId
*
* @return array
*/
public function download($globalId)
{
return array();
}
/**
* only support for cloud file.
*
* @param $globalId
*
* @return array
*/
public function getDefaultHumbnails($globalId)
{
return array();
}
/**
* only support for cloud file.
*
* @param $globalId
* @param $options
*
* @return array
*/
public function getThumbnail($globalId, $options)
{
return array();
}
/**
* only support for cloud file.
*
* @param $options
*
* @return array
*/
public function getStatistics($options)
{
return array();
}
/**
* @param $globalId
* @param bool $ssl
*
* @deprecated only support for cloud file use CloudFileImplementorImpl
*
* @return array
*/
public function player($globalId, $ssl = false)
{
return array();
}
/**
* @return UserService
*/
protected function getUserService()
{
return $this->biz->service('User:UserService');
}
/**
* @return UploadFileDao
*/
protected function getUploadFileDao()
{
return $this->createDao('File:UploadFileDao');
}
}
| richtermark/SMEAGOnline | src/Biz/File/Service/Impl/LocalFileImplementorImpl.php | PHP | mit | 8,475 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
File name: myWirelessRouter.py
Author: xu42 <https://github.com/xu42>
Date created: 04/04/2016
Python Version: 3.5
监测某台无线设备是否接入路由器, 同时猜解当前任务
适用于 Mercury MW310R 型号的无线路由器
'''
import http.client
import base64
import re
import time
# 配置参数
# url: 路由器后台登陆地址
# port: 路由器后台登陆地址端口
# timeout: 超时
# password: 路由器后台登陆密码
# mac_address: 需要监测的设备的MAC地址
# payload: ajax请求时发送的数据, 请忽视
config = {
'url': '123.123.123.123',
'port': '80',
'timeout': 20,
'password': '123456',
'mac_address': '11:11:11:11:11:11',
'payload': '[LAN_WLAN_ASSOC_DEV#0,0,0,0,0,0#0,0,0,0,0,0]0,4\r\nAssociatedDeviceMACAddress\r\nX_TP_TotalPacketsSent\r\nX_TP_TotalPacketsReceived\r\nX_TP_HostName\r\n'
}
# 构造请求头部
def __setHeaders():
headers = {
'cookie': 'Authorization=Basic ' + base64.b64encode(config['password'].encode('utf-8')).decode('utf-8'),
'referer': config['url']
}
return headers
# 发起请求
def __initRequest():
conn = http.client.HTTPConnection(config['url'], config['port'], config['timeout'])
conn.request('POST', "/cgi?5", config['payload'], __setHeaders())
res = conn.getresponse()
if res.status != 200:
print(res.status, res.reason)
exit()
data = res.read()
conn.close()
return data.decode('utf-8')
# 解析当前接入设备和接收发送数据包量
def __getAssociatedDevice():
a = re.findall(r"=(.+?)\s", __initRequest())
# device_list = zip(a[::3], a[1::3], a[2::3])
return a
# 判断某一设备是否在线
def __isOnline(MACAddress):
device_list = __getAssociatedDevice()
try:
device_list.index(MACAddress)
return True
except ValueError:
return False
# 猜解当前在做什么
def __doWhat(MACAddress = config['mac_address']):
if __isOnline(MACAddress):
print("已连入WIFI...")
print("正在猜解当前在做...")
device_list_1 = __getAssociatedDevice()
time.sleep(10)
device_list_2 = __getAssociatedDevice()
index_1 = device_list_1.index(MACAddress)
index_2 = device_list_2.index(MACAddress)
less = int(device_list_2[index_2 + 2]) - int(device_list_1[index_1 + 2])
if less < 5:
print("10s内接收数据包:", less, ",可能连着WIFI什么也没做...")
elif less < 30:
print("10s内接收数据包:", less, ",可能聊着QQ...")
else:
print("10s内接收数据包:", less, ",可能刷微博|看视频...")
else:
print("没有连入WIFI...")
def main():
__doWhat()
if __name__ == '__main__':
main()
| xu42/Python | myWirelessRouter/myWirelessRouter.py | Python | mit | 2,628 |
<?php
namespace Orchestra\Foundation\Http\Controllers;
use Illuminate\Http\Request;
use Orchestra\Contracts\Foundation\Listener\Account\UserCreator;
use Orchestra\Contracts\Foundation\Listener\Account\UserRemover;
use Orchestra\Contracts\Foundation\Listener\Account\UserUpdater;
use Orchestra\Contracts\Foundation\Listener\Account\UserViewer;
use Orchestra\Foundation\Processors\User as Processor;
class UsersController extends AdminController implements UserCreator, UserRemover, UserUpdater, UserViewer
{
/**
* Setup controller middleware.
*
* @return void
*/
protected function onCreate()
{
$this->middleware([
'orchestra.auth',
'orchestra.can:manage-users',
]);
$this->middleware('orchestra.csrf', ['only' => 'delete']);
}
/**
* List all the users.
*
* GET (:orchestra)/users
*
* @param \Illuminate\Http\Request $request
* @param \Orchestra\Foundation\Processors\User $processor
*
* @return mixed
*/
public function index(Request $request, Processor $processor)
{
return $processor->view($this, $request->all());
}
/**
* Create a new user.
*
* GET (:orchestra)/users/create
*
* @param \Orchestra\Foundation\Processors\User $processor
*
* @return mixed
*/
public function create(Processor $processor)
{
return $processor->create($this);
}
/**
* Edit the user.
*
* GET (:orchestra)/users/$user/edit
*
* @param \Orchestra\Foundation\Processors\User $processor
* @param int|string $user
*
* @return mixed
*/
public function edit(Processor $processor, $user)
{
return $processor->edit($this, $user);
}
/**
* Create the user.
*
* POST (:orchestra)/users
*
* @param \Illuminate\Http\Request $request
* @param \Orchestra\Foundation\Processors\User $processor
*
* @return mixed
*/
public function store(Request $request, Processor $processor)
{
return $processor->store($this, $request->all());
}
/**
* Update the user.
*
* PUT (:orchestra)/users/$user
*
* @param \Illuminate\Http\Request $request
* @param \Orchestra\Foundation\Processors\User $processor
* @param int|string $user
*
* @return mixed
*/
public function update(Request $request, Processor $processor, $user)
{
return $processor->update($this, $user, $request->all());
}
/**
* Request to delete a user.
*
* GET (:orchestra)/$user/delete
*
* @param \Orchestra\Foundation\Processors\User $processor
* @param int|string $user
*
* @return mixed
*/
public function delete(Processor $processor, $user)
{
return $this->destroy($processor, $user);
}
/**
* Request to delete a user.
*
* DELETE (:orchestra)/$user
*
* @param \Orchestra\Foundation\Processors\User $processor
* @param int|string $user
*
* @return mixed
*/
public function destroy(Processor $processor, $user)
{
return $processor->destroy($this, $user);
}
/**
* Response when list users page succeed.
*
* @param array $data
*
* @return mixed
*/
public function showUsers(array $data)
{
\set_meta('title', \trans('orchestra/foundation::title.users.list'));
return \view('orchestra/foundation::users.index', $data);
}
/**
* Response when create user page succeed.
*
* @param array $data
*
* @return mixed
*/
public function showUserCreator(array $data)
{
\set_meta('title', \trans('orchestra/foundation::title.users.create'));
return \view('orchestra/foundation::users.edit', $data);
}
/**
* Response when edit user page succeed.
*
* @param array $data
*
* @return mixed
*/
public function showUserChanger(array $data)
{
\set_meta('title', \trans('orchestra/foundation::title.users.update'));
return \view('orchestra/foundation::users.edit', $data);
}
/**
* Response when storing user failed on validation.
*
* @param \Illuminate\Contracts\Support\MessageBag|array $errors
*
* @return mixed
*/
public function createUserFailedValidation($errors)
{
return $this->redirectWithErrors(handles('orchestra::users/create'), $errors);
}
/**
* Response when storing user failed.
*
* @param array $errors
*
* @return mixed
*/
public function createUserFailed(array $errors)
{
$message = \trans('orchestra/foundation::response.db-failed', $errors);
return $this->redirectWithMessage(\handles('orchestra::users'), $message, 'error');
}
/**
* Response when storing user succeed.
*
* @return mixed
*/
public function userCreated()
{
$message = \trans('orchestra/foundation::response.users.create');
return $this->redirectWithMessage(\handles('orchestra::users'), $message);
}
/**
* Response when update user failed on validation.
*
* @param \Illuminate\Contracts\Support\MessageBag|array $errors
* @param string|int $id
*
* @return mixed
*/
public function updateUserFailedValidation($errors, $id)
{
return $this->redirectWithErrors(\handles("orchestra::users/{$id}/edit"), $errors);
}
/**
* Response when updating user failed.
*
* @param array $errors
*
* @return mixed
*/
public function updateUserFailed(array $errors)
{
$message = \trans('orchestra/foundation::response.db-failed', $errors);
return $this->redirectWithMessage(\handles('orchestra::users'), $message, 'error');
}
/**
* Response when updating user succeed.
*
* @return mixed
*/
public function userUpdated()
{
$message = \trans('orchestra/foundation::response.users.update');
return $this->redirectWithMessage(\handles('orchestra::users'), $message);
}
/**
* Response when destroying user failed.
*
* @param array $errors
*
* @return mixed
*/
public function userDeletionFailed(array $errors)
{
$message = \trans('orchestra/foundation::response.db-failed', $errors);
return $this->redirectWithMessage(\handles('orchestra::users'), $message, 'error');
}
/**
* Response when destroying user succeed.
*
* @return mixed
*/
public function userDeleted()
{
$message = \trans('orchestra/foundation::response.users.delete');
return $this->redirectWithMessage(\handles('orchestra::users'), $message);
}
/**
* Response when user tried to self delete.
*
* @return mixed
*/
public function selfDeletionFailed()
{
return $this->suspend(404);
}
/**
* Response when user verification failed.
*
* @return mixed
*/
public function abortWhenUserMismatched()
{
return $this->suspend(500);
}
}
| orchestral/foundation | src/Http/Controllers/UsersController.php | PHP | mit | 7,310 |
require 'cgi'
require 'net/http'
require 'uri'
require 'yaml'
module HtmlMockup
class W3CValidator
ValidationUri = "http://validator.w3.org/check"
class RequestError < StandardError; end
attr_reader :valid,:response,:errors,:warnings,:status
class << self
def validation_uri
@uri ||= URI.parse(ValidationUri)
end
end
def initialize(html)
@html = html
end
def validate!
@status = @warnings = @errors = @response = @valid = nil
options = {"output" => "json"}
query,headers = build_post_query(options)
response = self.request(:post,self.class.validation_uri.path,query,headers)
@status,@warnings,@errors = response["x-w3c-validator-status"],response["x-w3c-validator-warnings"].to_i,response["x-w3c-validator-errors"].to_i
if @status == "Valid" && @warnings == 0 && @errors == 0
return @valid = true
else
begin
@response = YAML.load(response.body)
rescue
end
return (@valid = (@errros == 0))
end
end
protected
def build_post_query(options)
boundary = "validate-this-content-please"
headers = {"Content-type" => "multipart/form-data, boundary=" + boundary + " "}
parts = []
options.each do |k,v|
parts << post_param(k,v)
end
parts << file_param("uploaded_file","index.html",@html,"text/html")
q = parts.map{|p| "--#{boundary}\r\n#{p}"}.join("") + "--#{boundary}--"
[q,headers]
end
def post_param(k,v)
"Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"\r\n\r\n#{v}\r\n"
end
def file_param(k,filename,content,mime_type)
out = []
out << "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"; filename=\"#{filename}\""
out << "Content-Transfer-Encoding: binary"
out << "Content-Type: #{mime_type}"
out.join("\r\n") + "\r\n\r\n" + content + "\r\n"
end
# Makes request to remote service.
def request(method, path, *arguments)
perform_request(method, path, arguments, 3)
end
def perform_request(method, path, arguments, tries=3)
result = nil
result = http.send(method, path, *arguments)
handle_response(result)
rescue RequestError => e
if tries > 0
perform_request(method, path, arguments, tries-1)
else
raise
end
rescue Timeout::Error => e
raise
end
# Handles response and error codes from remote service.
def handle_response(response)
case response.code.to_i
when 301,302
raise "Redirect"
when 200...400
response
when 400
raise "Bad Request"
when 401
raise "Unauthorized Access"
when 403
raise "Forbidden Access"
when 404
raise "Rescoure not found"
when 405
raise "Method not allowed"
when 409
raise RequestError.new("Rescource conflict")
when 422
raise RequestError.new("Resource invalid")
when 401...500
raise "Client error"
when 500...600
raise RequestError.new("Server error")
else
raise "Unknown response: #{response.code.to_i}"
end
end
def http
site = self.class.validation_uri
http = Net::HTTP.new(site.host, site.port)
# http.use_ssl = site.is_a?(URI::HTTPS)
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl
http
end
end
end | DigitPaint/html_mockup | lib/html_mockup/w3c_validator.rb | Ruby | mit | 3,595 |
from django.urls import path
from . import views
urlpatterns = [
path('overview/', views.overview, name='overview'),
]
| mrts/foodbank-campaign | src/locations/urls.py | Python | mit | 125 |
<?php
namespace App\Http\Controllers\Asset;
use App\Http\Controllers\Controller as BaseController;
use App\Http\Requests\Asset\ManualRequest;
use App\Http\Requests\AttachmentUpdateRequest;
use App\Repositories\Asset\ManualRepository;
use App\Repositories\Asset\Repository as AssetRepository;
class ManualController extends BaseController
{
/**
* @var AssetRepository
*/
protected $asset;
/**
* Constructor.
*
* @param AssetRepository $asset
* @param ManualRepository $manual
*/
public function __construct(AssetRepository $asset, ManualRepository $manual)
{
$this->asset = $asset;
$this->manual = $manual;
}
/**
* Displays all of the specified asset manuals.
*
* @param int|string $id
*
* @return \Illuminate\View\View
*/
public function index($id)
{
$asset = $this->asset->find($id);
return view('assets.manuals.index', compact('asset'));
}
/**
* Displays the asset manual upload form.
*
* @param int|string $id
*
* @return \Illuminate\View\View
*/
public function create($id)
{
$asset = $this->asset->find($id);
return view('assets.manuals.create', compact('asset'));
}
/**
* Uploads manuals and attaches them to the specified asset.
*
* @param ManualRequest $request
* @param int|string $id
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(ManualRequest $request, $id)
{
$asset = $this->asset->find($id);
$attachments = $this->manual->upload($request, $asset, $asset->manuals());
if ($attachments) {
$message = 'Successfully uploaded files.';
return redirect()->route('maintenance.assets.manuals.index', [$asset->id])->withSuccess($message);
} else {
$message = 'There was an issue uploading the files you selected. Please try again.';
return redirect()->route('maintenance.assets.manuals.create', [$id])->withErrors($message);
}
}
/**
* Displays the asset manual.
*
* @param int|string $id
* @param int|string $manualId
*
* @return \Illuminate\View\View
*/
public function show($id, $manualId)
{
$asset = $this->asset->find($id);
$manual = $asset->manuals()->find($manualId);
if ($manual) {
return view('assets.manuals.show', compact('asset', 'manual'));
}
abort(404);
}
/**
* Displays the form for editing an uploaded manual.
*
* @param int|string $id
* @param int|string $manualId
*
* @return \Illuminate\View\View
*/
public function edit($id, $manualId)
{
$asset = $this->asset->find($id);
$manual = $asset->manuals()->find($manualId);
if ($manual) {
return view('assets.manuals.edit', compact('asset', 'manual'));
}
abort(404);
}
/**
* Updates the specified asset manual upload.
*
* @param AttachmentUpdateRequest $request
* @param int|string $id
* @param int|string $manualId
*
* @return \Illuminate\Http\RedirectResponse
*/
public function update(AttachmentUpdateRequest $request, $id, $manualId)
{
$asset = $this->asset->find($id);
$manual = $this->manual->update($request, $asset->manuals(), $manualId);
if ($manual) {
$message = 'Successfully updated manual.';
return redirect()->route('maintenance.assets.manuals.show', [$asset->id, $manual->id])->withSuccess($message);
} else {
$message = 'There was an issue updating this manual. Please try again.';
return redirect()->route('maintenance.assets.manuals.show', [$id, $manualId])->withErrors($message);
}
}
/**
* Processes deleting an attachment record and the file itself.
*
* @param int|string $id
* @param int|string $manualId
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id, $manualId)
{
$asset = $this->asset->find($id);
$manual = $asset->manuals()->find($manualId);
if ($manual && $manual->delete()) {
$message = 'Successfully deleted manual.';
return redirect()->route('maintenance.assets.manuals.index', [$asset->id])->withSuccess($message);
} else {
$message = 'There was an issue deleting this manual. Please try again.';
return redirect()->route('maintenance.assets.manuals.show', [$asset->id, $manual->id])->withErrors($message);
}
}
/**
* Prompts the user to download the specified uploaded file.
*
* @param int|string $id
* @param int|string $manualId
*
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function download($id, $manualId)
{
$asset = $this->asset->find($id);
$manual = $asset->manuals()->find($manualId);
if ($manual) {
return response()->download($manual->download_path);
}
abort(404);
}
}
| stevebauman/maintenance | app/Http/Controllers/Asset/ManualController.php | PHP | mit | 5,254 |
using System;
using System.Web.Http;
using System.Web.Http.Tracing;
namespace WebConfigTransformations
{
// TODO: To enable tracing in your application, please add the following line of code
// to your startup code (WebApiConfig.cs or Global.asax.cs in an MVC 4 project):
// TraceConfig.Register(config);
// For more information, refer to: http://www.asp.net/web-api
/// <summary>
/// This static class contains helper methods related to the registration
/// of <see cref="ITraceWriter"/> instances.
/// </summary>
public static class TraceConfig
{
/// <summary>
/// Registers the <see cref="ITraceWriter"/> implementation to use
/// for this application.
/// </summary>
/// <param name="configuration">The <see cref="HttpConfiguration"/> in which
/// to register the trace writer.</param>
public static void Register(HttpConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
SystemDiagnosticsTraceWriter traceWriter =
new SystemDiagnosticsTraceWriter()
{
MinimumLevel = TraceLevel.Info,
IsVerbose = false
};
configuration.Services.Replace(typeof(ITraceWriter), traceWriter);
}
}
}
| MicrosoftLearning/20487-DevelopingWindowsAzureAndWebServices | Allfiles/20487C/Mod08/DemoFiles/WebConfigTransformations/end/WebConfigTransformations/App_Start/TraceConfig.cs | C# | mit | 1,429 |
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("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>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SMALLCHANGE</b>!\nAre you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
tr("TopCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your smallchange from being stolen by malware infecting your computer."));
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when accepable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on."));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on."));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return false;
}
| topcoin/topcoin | src/qt/askpassphrasedialog.cpp | C++ | mit | 8,937 |
import React, { createElement, forwardRef, useRef, useState } from 'react';
import { decorate, observable } from 'mobx';
import { observer, useObserver } from 'mobx-react';
import 'mobx-react-lite/batchingForReactDom';
class Todo {
constructor() {
this.id = Math.random();
this.title = 'initial';
this.finished = false;
}
}
decorate(Todo, {
title: observable,
finished: observable
});
const Forward = observer(
// eslint-disable-next-line react/display-name
forwardRef(({ todo }, ref) => {
return (
<p ref={ref}>
Forward: "{todo.title}" {'' + todo.finished}
</p>
);
})
);
const todo = new Todo();
const TodoView = observer(({ todo }) => {
return (
<p>
Todo View: "{todo.title}" {'' + todo.finished}
</p>
);
});
const HookView = ({ todo }) => {
return useObserver(() => {
return (
<p>
Todo View: "{todo.title}" {'' + todo.finished}
</p>
);
});
};
export function MobXDemo() {
const ref = useRef(null);
let [v, set] = useState(0);
const success = ref.current && ref.current.nodeName === 'P';
return (
<div>
<input
type="text"
placeholder="type here..."
onInput={e => {
todo.title = e.target.value;
set(v + 1);
}}
/>
<p>
<b style={`color: ${success ? 'green' : 'red'}`}>
{success ? 'SUCCESS' : 'FAIL'}
</b>
</p>
<TodoView todo={todo} />
<Forward todo={todo} ref={ref} />
<HookView todo={todo} />
</div>
);
}
| developit/preact | demo/mobx.js | JavaScript | mit | 1,434 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePersonsReferencesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('persons_references_1_1', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('id_history');
$table->foreign('id_history', 'persons_references_1_1_1_fk_historys')->references('id')->on('historys');
$table->unsignedInteger('id_elderly');
$table->foreign('id_elderly', 'persons_references_1_1_2_fk_elderlies')->references('id')->on('elderlies');
$table->string('name_1_1', '50')->nullable(true);
$table->date('date_of_birth_1_1')->nullable(true);
$table->string('link_1_1', '30')->nullable(true);
$table->string('address_1_1', '50')->nullable(true);
$table->string('telephone_1_1', '15')->nullable(true);
$table->string('cell_phone_1_1', '15')->nullable(true);
$table->boolean('does_this_person_live_with_you_1_1')->nullable(true);
$table->date('date_of_this_information_1_1')->nullable(true);
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('persons_references_1_1');
}
}
| Vabrins/CadernetaDoIdoso | database/migrations/2017_08_23_025525_create_persons_references_table.php | PHP | mit | 1,549 |
// Test logging in
casper.test.comment('Test logging in');
casper.start('http://localhost:3000/', function() {
this.clickLabel('Login', 'a');
this.then(function() {
this.test.assertExists('form', 'login form exists');
this.test.assertUrlMatch('http://localhost:3000/auth/login');
this.fill('form', {
'username' : 'testuserone',
'password' : 'password'
}, true);
this.then(function() {
this.test.assertExists('div .alert', 'alert exists');
this.test.assertSelectorHasText('div .alert', 'Logged in');
this.test.assertSelectorHasText('a', 'Logout');
this.test.assertSelectorDoesntHaveText('a', 'Login');
this.test.assertSelectorHasText('a', 'My Profile');
});
});
});
casper.run(function() {
this.clickLabel('Logout', 'a');
this.test.done(7);
});
| ShaneKilkelly/YesodExample | casper/loginTest.js | JavaScript | mit | 916 |
<?php
function shorten($url, $qr=NULL){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://goo.gl/api/shorten');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'security_token=null&url='.urlencode($url));
$results = curl_exec($ch);
$headerInfo = curl_getinfo($ch);
curl_close($ch);
if ($headerInfo['http_code'] === 201){ // HTTP Code 201 = Created
$results = json_decode($results);
if(isset($results->short_url)){
$qr = !is_null($qr)?'.qr':'';
return $results->short_url.$qr;
}
return FALSE;
}
return FALSE;
}
trigger_error("cURL required to shorten URLs.", E_USER_WARNING); // Show the user a neat error.
return FALSE;
}
// Example: Just the Short URL
echo shorten('http://www.google.com/');
// Example: Give the Short Code URL and image it.
$qrURL = shorten('http://www.google.com/', TRUE);
echo '<img src="'.$qrURL.'" />';
?>
| voidabhi/reddy | ShortUrl.php | PHP | mit | 942 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jam;
using MySql.Data.MySqlClient;
using System.Web.UI.HtmlControls;
public partial class Track : JamPage
{
public Track()
{
m_Code = 22;
}
private string TrackID
{
get
{
return (string)ViewState["TrackID"];
}
set
{
ViewState["TrackID"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TrackID = (string)HttpContext.Current.Items["song_id"];
FillForm();
ctrUserComment.SubjectID = TrackID;
ctrUserComment.SubjKind = "music";
ctrRating.SubjectID = TrackID;
ctrRating.SubjKind = "music";
SetPageTitleDescr(new string[] {
lbTitle.Text,
lbTitle.Text },
new string[] {
String.Format("Music. Title: {0}, Author: {1}", lbTitle.Text, hlAuthor.Text) + (!String.IsNullOrEmpty(hlBand.Text) ? (", Band: " + hlBand.Text) : ""),
String.Format("Музыка. Название: {0}, Автор: {1}", lbTitle.Text, hlAuthor.Text) + (!String.IsNullOrEmpty(hlBand.Text) ? (", Группа: " + hlBand.Text) : "") });
}
}
private void AddPlayer(string sSongTitle, string sImgId)
{
HtmlGenericControl hcPlayer = new HtmlGenericControl();
hcPlayer.InnerHtml = String.Format(@"
<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='400' height='15' id='xspf_player' align='middle'>
<param name='allowScriptAccess' value='sameDomain' />
<param name='movie' value='{0}' />
<param name='quality' value='high' />
<param name='bgcolor' value='#e6e6e6' />
<embed src='{0}' quality='high' bgcolor='#e6e6e6' width='400' height='15' name='xspf_player' align='middle' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />
</object>
", this.ResolveUrl("~/Player/xspf_player.swf") + "?song_title=" + Uri.EscapeUriString(sSongTitle) + "&song_url=" + this.ResolveUrl("~/GetMusic.aspx?id=" + TrackID) + "&autoload=true" + (!String.IsNullOrEmpty(sImgId) ? "&song_image=" + this.ResolveUrl("~/GetImage.aspx?id=" + sImgId) : ""));
phPlayer.Controls.Add(hcPlayer);
}
private void FillForm()
{
if (!String.IsNullOrEmpty(TrackID))
{
MySqlConnection con = Utils.GetSqlConnection();
if (con != null)
{
try
{
MySqlCommand cmd = new MySqlCommand(@"select
music.Title, music.FileName, music.Description, music.Style, music.Language, music.ImgId, userinfo.SiteName as AuthorName, bands.Name as BandName
from music left outer join bands on (music.BandId=bands.Id and bands.Deleted=0), userinfo, usertoband where music.Id=?TrackId and music.Deleted=0 and music.Author=userinfo.Id and userinfo.Deleted=0", con);
cmd.Parameters.Add("?TrackId", MySqlDbType.UInt64).Value = UInt64.Parse(TrackID);
if (UserInfo != null)
{
cmd.CommandText += @" and (music.Author=?UserId or music.Visibility IS NULL or music.Visibility=0 or music.Visibility=1 or
(music.Visibility=3 and music.BandId=usertoband.BandId and usertoband.UserId=?UserId and usertoband.Deleted=0))";
cmd.Parameters.Add("?UserId", MySqlDbType.UInt64).Value = UserInfo.UIntId;
}
else
{
cmd.CommandText += " and (music.Visibility IS NULL or music.Visibility=0)";
}
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr != null)
{
string sImgId = null;
if (rdr.Read())
{
lbTitle.Text = rdr.GetString("Title");
lbDescr.Text = rdr.IsDBNull ( rdr.GetOrdinal ( "Description" ) ) ? "" : rdr.GetString ( "Description" );
lbStyle.Text = rdr.IsDBNull ( rdr.GetOrdinal ( "Description" ) ) ? "" : rdr.GetString ( "Style" );
//lbAuthor.Text = rdr.GetString("AuthorName");
hlAuthor.Text = rdr.GetString("AuthorName");
hlAuthor.NavigateUrl = Jam.JamRouteUrl.PickUp ( "folk", this.LangEnum, new System.Collections.Generic.Dictionary<string, string> ( ) { { "name", hlAuthor.Text } } );
//lbBand.Text = rdr.IsDBNull(rdr.GetOrdinal("BandName")) ? "" : rdr.GetString("BandName");
hlBand.Text = rdr.IsDBNull(rdr.GetOrdinal("BandName")) ? "" : rdr.GetString("BandName");
if (!String.IsNullOrEmpty(hlBand.Text))
{
trBand.Visible = true;
hlBand.NavigateUrl = Jam.JamRouteUrl.PickUp ( "band", this.LangEnum, new System.Collections.Generic.Dictionary<string, string> ( ) { { "name", hlBand.Text } } );
}
else
{
trBand.Visible = false;
}
lbLang.Text = rdr.IsDBNull(rdr.GetOrdinal("Language")) ? "" : rdr.GetString("Language");
trLang.Visible = !String.IsNullOrEmpty(lbLang.Text);
sImgId = rdr.IsDBNull(rdr.GetOrdinal("ImgId")) ? null : rdr.GetString("ImgId");
}
rdr.Close();
AddPlayer(lbTitle.Text, sImgId);
}
}
catch (Exception ex)
{
JamLog.log(JamLog.enEntryType.error, "Track", "FillForm: " + ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
| hardsky/music-head | web/Track.aspx.cs | C# | mit | 6,295 |
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Propel filter form generator.
*
* This class generates a Propel filter forms.
*
* @package symfony
* @subpackage generator
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfPropelFormFilterGenerator.class.php 24392 2009-11-25 18:35:39Z FabianLange $
*/
class sfPropelFormFilterGenerator extends sfPropelFormGenerator
{
/**
* Initializes the current sfGenerator instance.
*
* @param sfGeneratorManager $generatorManager A sfGeneratorManager instance
*/
public function initialize(sfGeneratorManager $generatorManager)
{
parent::initialize($generatorManager);
$this->setGeneratorClass('sfPropelFormFilter');
}
/**
* Generates classes and templates in cache.
*
* @param array $params The parameters
*
* @return string The data to put in configuration cache
*/
public function generate($params = array())
{
$this->params = $params;
if (!isset($this->params['connection']))
{
throw new sfParseException('You must specify a "connection" parameter.');
}
if (!isset($this->params['model_dir_name']))
{
$this->params['model_dir_name'] = 'model';
}
if (!isset($this->params['filter_dir_name']))
{
$this->params['filter_dir_name'] = 'filter';
}
$this->loadBuilders();
// create the project base class for all forms
$file = sfConfig::get('sf_lib_dir').'/filter/BaseFormFilterPropel.class.php';
if (!file_exists($file))
{
if (!is_dir($directory = dirname($file)))
{
mkdir($directory, 0777, true);
}
file_put_contents($file, $this->evalTemplate('sfPropelFormFilterBaseTemplate.php'));
}
// create a form class for every Propel class
foreach ($this->dbMap->getTables() as $tableName => $table)
{
$behaviors = $table->getBehaviors();
if (isset($behaviors['symfony']['filter']) && 'false' === $behaviors['symfony']['filter'])
{
continue;
}
$this->table = $table;
// find the package to store filter forms in the same directory as the model classes
$packages = explode('.', constant(constant($table->getClassname().'::PEER').'::CLASS_DEFAULT'));
array_pop($packages);
if (false === $pos = array_search($this->params['model_dir_name'], $packages))
{
throw new InvalidArgumentException(sprintf('Unable to find the model dir name (%s) in the package %s.', $this->params['model_dir_name'], constant(constant($table->getClassname().'::PEER').'::CLASS_DEFAULT')));
}
$packages[$pos] = $this->params['filter_dir_name'];
$baseDir = sfConfig::get('sf_root_dir').'/'.implode(DIRECTORY_SEPARATOR, $packages);
if (!is_dir($baseDir.'/base'))
{
mkdir($baseDir.'/base', 0777, true);
}
file_put_contents($baseDir.'/base/Base'.$table->getClassname().'FormFilter.class.php', $this->evalTemplate('sfPropelFormFilterGeneratedTemplate.php'));
if (!file_exists($classFile = $baseDir.'/'.$table->getClassname().'FormFilter.class.php'))
{
file_put_contents($classFile, $this->evalTemplate('sfPropelFormFilterTemplate.php'));
}
}
}
/**
* Returns a sfWidgetForm class name for a given column.
*
* @param ColumnMap $column A ColumnMap object
*
* @return string The name of a subclass of sfWidgetForm
*/
public function getWidgetClassForColumn(ColumnMap $column)
{
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
case PropelColumnTypes::ENUM:
$name = 'Choice';
break;
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIME:
case PropelColumnTypes::TIMESTAMP:
$name = 'FilterDate';
break;
default:
$name = 'FilterInput';
}
if ($column->isForeignKey())
{
$name = 'PropelChoice';
}
return sprintf('sfWidgetForm%s', $name);
}
/**
* Returns a PHP string representing options to pass to a widget for a given column.
*
* @param ColumnMap $column A ColumnMap object
*
* @return string The options to pass to the widget as a PHP string
*/
public function getWidgetOptionsForColumn(ColumnMap $column)
{
$options = array();
$withEmpty = $column->isNotNull() && !$column->isForeignKey() ? array("'with_empty' => false") : array();
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
$options[] = "'choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no')";
break;
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIME:
case PropelColumnTypes::TIMESTAMP:
$options[] = "'from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate()";
$options = array_merge($options, $withEmpty);
break;
case PropelColumnTypes::ENUM:
$valueSet = $column->getValueSet();
$choices = array_merge(array(''=>'all'), $valueSet);
$options[] = sprintf("'choices' => %s", preg_replace('/\s+/', '', var_export($choices, true)));
break;
default:
$options = array_merge($options, $withEmpty);
}
if ($column->isForeignKey())
{
$options[] = sprintf('\'model\' => \'%s\', \'add_empty\' => true', $this->getForeignTable($column)->getClassname());
$refColumn = $this->getForeignTable($column)->getColumn($column->getRelatedColumnName());
if (!$refColumn->isPrimaryKey())
{
$options[] = sprintf('\'key_method\' => \'get%s\'', $refColumn->getPhpName());
}
}
return count($options) ? sprintf('array(%s)', implode(', ', $options)) : '';
}
/**
* Returns a sfValidator class name for a given column.
*
* @param ColumnMap $column A ColumnMap object
*
* @return string The name of a subclass of sfValidator
*/
public function getValidatorClassForColumn(ColumnMap $column)
{
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
case PropelColumnTypes::ENUM:
$name = 'Choice';
break;
case PropelColumnTypes::DOUBLE:
case PropelColumnTypes::FLOAT:
case PropelColumnTypes::NUMERIC:
case PropelColumnTypes::DECIMAL:
case PropelColumnTypes::REAL:
$name = 'Number';
break;
case PropelColumnTypes::INTEGER:
case PropelColumnTypes::SMALLINT:
case PropelColumnTypes::TINYINT:
case PropelColumnTypes::BIGINT:
$name = 'Integer';
break;
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIME:
case PropelColumnTypes::TIMESTAMP:
$name = 'DateRange';
break;
default:
$name = 'Pass';
}
if ($column->isPrimaryKey() || $column->isForeignKey())
{
$name = 'PropelChoice';
}
return sprintf('sfValidator%s', $name);
}
/**
* Returns a PHP string representing options to pass to a validator for a given column.
*
* @param ColumnMap $column A ColumnMap object
*
* @return string The options to pass to the validator as a PHP string
*/
public function getValidatorOptionsForColumn(ColumnMap $column)
{
$options = array('\'required\' => false');
if ($column->isForeignKey())
{
$options[] = sprintf('\'model\' => \'%s\', \'column\' => \'%s\'', $this->getForeignTable($column)->getClassname(), $this->translateColumnName($column, true));
}
else if ($column->isPrimaryKey())
{
$options[] = sprintf('\'model\' => \'%s\', \'column\' => \'%s\'', $column->getTable()->getClassname(), $this->translateColumnName($column));
}
else
{
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
$options[] = "'choices' => array('', 1, 0)";
break;
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIME:
case PropelColumnTypes::TIMESTAMP:
$options[] = "'from_date' => new sfValidatorDate(array('required' => false)), 'to_date' => new sfValidatorDate(array('required' => false))";
break;
case PropelColumnTypes::ENUM:
$valueSet = $column->getValueSet();
$options[] = sprintf("'choices' => %s", preg_replace('/\s+/', '', var_export(array_keys($valueSet), true)));
break;
}
}
return count($options) ? sprintf('array(%s)', implode(', ', $options)) : '';
}
public function getValidatorForColumn($column)
{
$format = 'new %s(%s)';
if (in_array($class = $this->getValidatorClassForColumn($column), array('sfValidatorInteger', 'sfValidatorNumber')))
{
$format = 'new sfValidatorSchemaFilter(\'text\', new %s(%s))';
}
return sprintf($format, $class, $this->getValidatorOptionsForColumn($column));
}
public function getType(ColumnMap $column)
{
if ($column->isForeignKey())
{
return 'ForeignKey';
}
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
return 'Boolean';
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIME:
case PropelColumnTypes::TIMESTAMP:
return 'Date';
case PropelColumnTypes::DOUBLE:
case PropelColumnTypes::FLOAT:
case PropelColumnTypes::NUMERIC:
case PropelColumnTypes::DECIMAL:
case PropelColumnTypes::REAL:
case PropelColumnTypes::INTEGER:
case PropelColumnTypes::SMALLINT:
case PropelColumnTypes::TINYINT:
case PropelColumnTypes::BIGINT:
return 'Number';
default:
return 'Text';
}
}
}
| jenkins-khan/Jenkins-Khan | plugins/sfPropelORMPlugin/lib/generator/sfPropelFormFilterGenerator.class.php | PHP | mit | 10,039 |
// Initialize your app
var myApp = new Framework7({
cache: false,
});
// Export selectors engine
var $$ = Dom7;
// Add views
var leftView = myApp.addView('.view-left', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
,ignoreCache : true
});
var mainView = myApp.addView('.view-main', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
,ignoreCache : true
});
myApp.pageData = {'sliders' : {'clockIn' : {'value' : 0 , outputHour : 0, outputMins: 0}, 'clockOut' : {'value' : 0, outputHour : 0, outputMins: 0} }}
myApp.onPageInit('ClockIn special', function (page) {
myApp.options = {};
myApp.options.StartHour = 5;
//Clear div
// $$('.ajaxResult1');.html('..');
$$('.inputStartHour').val(myApp.options.StartHour);
myApp.CalculateHoursWorked = function(){
//Figure out hours worked by blocks.
var CheckInTime = $$('.inputCheckInTime').val();
var CheckOutTime = $$('.inputCheckOutTime').val();
var CheckInArray = CheckInTime.split(':');
var CheckOutArray = CheckOutTime.split(':');
var InMinutes = (parseFloat(CheckInArray[0],2) * 60 )+ parseFloat(CheckInArray[1]);
var OutMinutes = (parseFloat(CheckOutArray[0],2) * 60 )+ parseFloat(CheckOutArray[1]);
hoursWorked = hoursTohhmm((OutMinutes - InMinutes) /60);
$$('.hourWorked').html(hoursWorked +' hours. ' );
$$('.clockHoursWorked').val(hoursWorked +' hours. ');
}
myApp.SliderToTime = function (sliderValue) {
//Start at 5am and create increments for each minute to midnight
var startTime = 60 * myApp.options.StartHour;
var maxTime = 60 * 24;
var totalMins = maxTime - startTime;
var outputValue = (totalMins / 100) * sliderValue;
var inMins = (outputValue / 60 ) + 5 ;
var outputHour = Math.floor(inMins);
var theMins = (inMins - outputHour) * 100;;
var outputMins = 0;
//Set out intervals of 15 mins.
if (theMins < 25){
outputMins = '00';
}else if (theMins < 50){
outputMins = '15';
} else if (theMins < 75) {
outputMins = '30';
}else if (theMins < 100) {
outputMins = '45';
} else {
outputMins = '45';
}
return myApp.Time24To12({ 'outputMins' : outputMins, 'outputHour' : outputHour , 'ampm' : '', 'pmHour': outputHour});
}
myApp.TimeToSlider = function(Hour, Min ){
//5am start.
var startTime = 60 * myApp.options.StartHour;
var maxTime = 60 * 24;
var totalMins = maxTime - startTime;
var TotalMinutesSelected = ((Hour - myApp.options.StartHour) * 60 )+ Min;
var perc = TotalMinutesSelected / totalMins;
return TimeToSlider;
}
myApp.Time24To12 = function(TimeArray) {
if (TimeArray.outputHour > 12){
TimeArray.ampm = 'PM';
TimeArray.pmHour = TimeArray.outputHour - 12;
} else {
TimeArray.ampm = 'AM';
}
return TimeArray;
}
$$('.clockInSliderPosition').on('input change', function(){
Output = myApp.SliderToTime(this.value);
$$('.clockinSelectOutput').html( Output.pmHour + ':' + Output.outputMins + ' ' + Output.ampm);
$$('.inputCheckInTime').val(Output.outputHour + ':' + Output.outputMins);
myApp.pageData.sliders.clockIn.outputHour = Output.outputHour;
myApp.pageData.sliders.clockIn.outputMins = Output.outputMins;
myApp.pageData.sliders.clockIn.value = this.value;
myApp.CalculateHoursWorked();
});
myApp.CalculateSliderHours = function(){
Output = myApp.SliderToTime(this.value);
$$('.clockOutSelectOutput').html( Output.pmHour + ':' + Output.outputMins+ ' ' + Output.ampm);
$$('.inputCheckOutTime').val(Output.outputHour + ':' + Output.outputMins);
myApp.pageData.sliders.clockOut.outputHour = Output.outputHour;
myApp.pageData.sliders.clockOut.outputMins = Output.outputMins;
myApp.pageData.sliders.clockOut.value = this.value;
myApp.CalculateHoursWorked();
}
$$('.clockOutSliderPosition').on('input change', myApp.CalculateSliderHours );
//Form Submit variables
$$('form.ajax-submit').on('submitError', function (e) {
alert('An error has occured while recording your ClockIn Details. Please record on paper and contact Toby.');
});
$$('.btnsavedone').on('click' , function(){
// alert('ha');
myApp.BtnSaveDoneClicked = true;
$$('.debugout').html($$('.debugout').html() + ';' );
})
$$('form.ajax-submit').on('submitted', function (e) {
var ajaxResultDiv = $$('.ajaxResult1');
$$('.debugout').html($$('.debugout').html() + 'x' );
if (myApp.BtnSaveDoneClicked == true){
// Initialize View
var mainView = myApp.addView('.view-main')
$$('.debugout').html($$('.debugout').html() + 'y' );
// Load page from about.html file to main View:
//var empid = $$('input:[name=employeeID]').val();
//mainView.router.loadPage('done.php?id=' + empid);
//alert($$('.input_employeeid').val() + ' ' + 'done.php?id=' + $$('#employeeID').val() );
var empid = $$( e.currentTarget ).find('input.employeeID')
mainView.router.loadPage('done.php?id=' + $$(empid).val());
}
myApp.BtnSaveDoneClicked = false;
// var data = e.detail.data; // Ajax response from action file
// do something with response data
//alert( e.detail.stringify());
// ajaxResultDiv.html(data);
})
});
function hoursTohhmm(hours){
var sign = hours < 0 ? "-" : "";
var h = Math.floor(Math.abs(hours))
var m = Math.floor((Math.abs(hours) * 60) % 60);
return sign + (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m;
}
| tobya/wageminder | clockin/js/my-app.js | JavaScript | mit | 5,892 |
<?php
namespace Tests\QueryBuilder\PostgreSQL;
use Furry\Database;
trait Table
{
/**
* @dataProvider tableNameProvider
*
* @param $tableName
* @param $expected
*/
public function testTable($tableName, $expected)
{
/** @var Database $db */
$db = $this->db;
$query = $db->table($tableName);
$class = new \ReflectionClass('\Furry\Database\Query');
$property = $class->getProperty("table");
$property->setAccessible(true);
$tableName = $property->getValue($query);
$this->assertEquals($expected, $tableName);
}
/**
* escaped table names
* @return array
*/
public function tableNameProvider()
{
return [
['testTable', '"testTable"'],
['testTable as t', '"testTable" AS "t"']
];
}
}
| gpawru/furry-framework-database | Tests/QueryBuilder/PostgreSQL/Table.php | PHP | mit | 861 |
# frozen_string_literal: true
require "test_helper"
describe Committee::Drivers::OpenAPI2::ParameterSchemaBuilder do
before do
end
it "reflects a basic type into a schema" do
data = {
"parameters" => [
{
"name" => "limit",
"type" => "integer",
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal ["limit"], schema.properties.keys
assert_equal [], schema.required
assert_equal ["integer"], schema.properties["limit"].type
assert_nil schema.properties["limit"].enum
assert_nil schema.properties["limit"].format
assert_nil schema.properties["limit"].pattern
assert_nil schema.properties["limit"].min_length
assert_nil schema.properties["limit"].max_length
assert_nil schema.properties["limit"].min_items
assert_nil schema.properties["limit"].max_items
assert_nil schema.properties["limit"].unique_items
assert_nil schema.properties["limit"].min
assert_nil schema.properties["limit"].min_exclusive
assert_nil schema.properties["limit"].max
assert_nil schema.properties["limit"].max_exclusive
assert_nil schema.properties["limit"].multiple_of
end
it "reflects a required property into a schema" do
data = {
"parameters" => [
{
"name" => "limit",
"required" => true,
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal ["limit"], schema.required
end
it "reflects an array with an items schema into a schema" do
data = {
"parameters" => [
{
"name" => "tags",
"type" => "array",
"minItems" => 1,
"maxItems" => 10,
"uniqueItems" => true,
"items" => {
"type" => "string"
}
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal ["array"], schema.properties["tags"].type
assert_equal 1, schema.properties["tags"].min_items
assert_equal 10, schema.properties["tags"].max_items
assert_equal true, schema.properties["tags"].unique_items
assert_equal({ "type" => "string" }, schema.properties["tags"].items)
end
it "reflects a enum property into a schema" do
data = {
"parameters" => [
{
"name" => "type",
"type" => "string",
"enum" => ["hoge", "fuga"]
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal ["hoge", "fuga"], schema.properties["type"].enum
end
it "reflects string properties into a schema" do
data = {
"parameters" => [
{
"name" => "password",
"type" => "string",
"format" => "password",
"pattern" => "[a-zA-Z0-9]+",
"minLength" => 6,
"maxLength" => 30
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal "password", schema.properties["password"].format
assert_equal Regexp.new("[a-zA-Z0-9]+"), schema.properties["password"].pattern
assert_equal 6, schema.properties["password"].min_length
assert_equal 30, schema.properties["password"].max_length
end
it "reflects number properties into a schema" do
data = {
"parameters" => [
{
"name" => "limit",
"type" => "integer",
"minimum" => 20,
"exclusiveMinimum" => true,
"maximum" => 100,
"exclusiveMaximum" => false,
"multipleOf" => 10
}
]
}
schema, schema_data = call(data)
assert_nil schema_data
assert_equal 20, schema.properties["limit"].min
assert_equal true, schema.properties["limit"].min_exclusive
assert_equal 100, schema.properties["limit"].max
assert_equal false, schema.properties["limit"].max_exclusive
assert_equal 10, schema.properties["limit"].multiple_of
end
it "returns schema data for a body parameter" do
data = {
"parameters" => [
{
"name" => "payload",
"in" => "body",
"schema" => {
"$ref" => "#/definitions/foo",
}
}
]
}
schema, schema_data = call(data)
assert_nil schema
assert_equal({ "$ref" => "#/definitions/foo" }, schema_data)
end
it "requires that certain fields are present" do
data = {
"parameters" => [
{
}
]
}
e = assert_raises ArgumentError do
call(data)
end
assert_equal "Committee: no name section in link data.", e.message
end
it "requires that body parameters not be mixed with form parameters" do
data = {
"parameters" => [
{
"name" => "payload",
"in" => "body",
},
{
"name" => "limit",
"in" => "form",
},
]
}
e = assert_raises ArgumentError do
call(data)
end
assert_equal "Committee: can't mix body parameter with form parameters.",
e.message
end
def call(data)
Committee::Drivers::OpenAPI2::ParameterSchemaBuilder.new(data).call
end
end
| interagent/committee | test/drivers/open_api_2/parameter_schema_builder_test.rb | Ruby | mit | 5,146 |
from schedulerEdge import SchedulerEdge
import time
if __name__ == '__main__':
#scheduler = BackgroundScheduler()
#scheduler.add_job(tick, 'cron', second = '5,10',minute = '40' , id = "12")
#scheduler.start()
#while True:
# time.sleep(1)
test_sched = SchedulerEdge()
#test_sched.add_job(3)
test_sched.add_job('{ "modo": "cron", "info": {"second": "5", "minute": "*/1", "hour": "*", "day": "*", "week": "*", "month": "*", "year": "*" }}')
#test_sched.add_job('interval-12')
#test_sched.add_job('interval-45')
#time.sleep(2)
#test_sched.remove_job('interval-45')
| hubertokf/lupsEdgeServer | projects/old_files/moduleOfRules/testesched.py | Python | mit | 613 |
define(["app/helpers"], function(helpers) {
return ["$http", function($http) {
// This is a constructor function for the singleton SnippetLoader service. It will be called exactly once by the AngularJS Dependecy Injector.
this.loadContentTemplate = function(contentType) {
return new Promise(function(resolve, reject) {
console.log("Loading content template of type:", contentType);
if (!contentType)
contentType = "_undefined";
$http.get("snippets/content_templates/" + contentType + ".json").then(function(r) {
var template = r.data;
console.log("Received content template:", template);
resolve(template);
}).catch(function (e) {
console.error("Error requesting content template:", e);
reject(e);
})
});
};
this.loadPageTemplate = function(type) {
return this.loadContentTemplate(type).then(function(t) {
t.id = helpers.generateGuid();
return t;
}).catch(function(e) {
console.error("Unable to load page template", e);
});
}
this.loadQuestionTemplate = function(type) {
return this.loadContentTemplate(type).then(function(t) {
t.id = helpers.generateGuid();
return t;
}).catch(function(e) {
console.error("Unable to load question template", e);
});
}
}];
}); | ucam-cl-dtg/scooter | app/js/app/services/SnippetLoader.js | JavaScript | mit | 1,288 |
import os.path
import sqlite3
from config import CONFIG
def init_db():
"""初始化数据库"""
f = os.path.exists(CONFIG['DB_FILE'])
if f:
print("数据库文件存在...")
with open(CONFIG['SQL_SCRIPT_FILE'], 'r', encoding='utf8') as f:
file_content = f.read()
con = sqlite3.connect(CONFIG['DB_FILE'])
cur = con.cursor()
cur.executescript(file_content)
con.commit()
con.close()
return "初始化数据库完成!"
print(init_db()) | zzir/white | init_db.py | Python | mit | 493 |
using UnityEngine;
using System.Collections;
public class SpeedSynchro : MonoBehaviour {
private VelocityFPC vfpc;
private RelativisticObject obj;
// Use this for initialization
void Start () {
vfpc = this.GetComponent<VelocityFPC>();
obj = this.GetComponent<RelativisticObject>();
}
// Update is called once per frame
void Update () {
obj.viw = vfpc.vitesse;
}
}
| stonneau/Celerity | Sources/Assets/OpenRelativity/SpeedSynchro.cs | C# | mit | 385 |
class CreateSubscribers < ActiveRecord::Migration
def self.up
create_table :subscribers do |t|
t.string :name
t.string :email
t.timestamps
end
end
def self.down
drop_table :subscribers
end
end
| beef/Subscribers | generators/subscribers_migration/templates/migration.rb | Ruby | mit | 237 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, $, _parseRuleList: true */
// JSLint Note: _parseRuleList() is cyclical dependency, not a global function.
// It was added to this list to prevent JSLint warning about being used before being defined.
/**
* Set of utilities for simple parsing of CSS text.
*/
define(function (require, exports, module) {
"use strict";
var CodeMirror = require("thirdparty/CodeMirror2/lib/codemirror"),
Async = require("utils/Async"),
DocumentManager = require("document/DocumentManager"),
EditorManager = require("editor/EditorManager"),
HTMLUtils = require("language/HTMLUtils"),
ProjectManager = require("project/ProjectManager"),
TokenUtils = require("utils/TokenUtils"),
_ = require("thirdparty/lodash");
// Constants
var SELECTOR = "selector",
PROP_NAME = "prop.name",
PROP_VALUE = "prop.value",
IMPORT_URL = "import.url";
var RESERVED_FLOW_NAMES = ["content", "element"],
INVALID_FLOW_NAMES = ["none", "inherit", "default", "auto", "initial"],
IGNORED_FLOW_NAMES = RESERVED_FLOW_NAMES.concat(INVALID_FLOW_NAMES);
/**
* @private
* Checks if the current cursor position is inside the property name context
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property name
*/
function _isInPropName(ctx) {
var state,
lastToken;
if (!ctx || !ctx.token || !ctx.token.state || ctx.token.type === "comment") {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context) {
return false;
}
lastToken = state.context.type;
return (lastToken === "{" || lastToken === "rule" || lastToken === "block");
}
/**
* @private
* Checks if the current cursor position is inside the property value context
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property value
*/
function _isInPropValue(ctx) {
function isInsideParens(context) {
if (context.type !== "parens" || !context.prev) {
return false;
}
if (context.prev.type === "prop") {
return true;
}
return isInsideParens(context.prev);
}
var state;
if (!ctx || !ctx.token || !ctx.token.state || ctx.token.type === "comment") {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context || !state.context.prev) {
return false;
}
return ((state.context.type === "prop" &&
(state.context.prev.type === "rule" || state.context.prev.type === "block")) ||
isInsideParens(state.context));
}
/**
* @private
* Checks if the current cursor position is inside an at-rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property value
*/
function _isInAtRule(ctx) {
var state;
if (!ctx || !ctx.token || !ctx.token.state) {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context) {
return false;
}
return (state.context.type === "at");
}
/**
* @private
* Creates a context info object
* @param {string=} context A constant string
* @param {number=} offset The offset of the token for a given cursor position
* @param {string=} name Property name of the context
* @param {number=} index The index of the property value for a given cursor position
* @param {Array.<string>=} values An array of property values
* @param {boolean=} isNewItem If this is true, then the value in index refers to the index at which a new item
* is going to be inserted and should not be used for accessing an existing value in values array.
* @param {{start: {line: number, ch: number},
* end: {line: number, ch: number}}=} range A range object with a start position and an end position
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean,
* range: {start: {line: number, ch: number},
* end: {line: number, ch: number}}}} A CSS context info object.
*/
function createInfo(context, offset, name, index, values, isNewItem, range) {
var ruleInfo = { context: context || "",
offset: offset || 0,
name: name || "",
index: -1,
values: [],
isNewItem: (isNewItem === true),
range: range };
if (context === PROP_VALUE || context === SELECTOR || context === IMPORT_URL) {
ruleInfo.index = index;
ruleInfo.values = values;
}
return ruleInfo;
}
/**
* @private
* Scan backwards to check for any prefix if the current context is property name.
* If the current context is in a prefix (either 'meta' or '-'), then scan forwards
* to collect the entire property name. Return the name of the property in the CSS
* context info object if there is one that seems to be valid. Return an empty context
* info when we find an invalid one.
*
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} ctx context
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean,
* range: {start: {line: number, ch: number},
* end: {line: number, ch: number}}}} A CSS context info object.
*/
function _getPropNameInfo(ctx) {
var propName = "",
offset = TokenUtils.offsetInToken(ctx),
tokenString = ctx.token.string,
excludedCharacters = [";", "{", "}"];
if (ctx.token.type === "property" || ctx.token.type === "property error" ||
ctx.token.type === "tag") {
propName = tokenString;
if (TokenUtils.movePrevToken(ctx) && /\S/.test(ctx.token.string) &&
excludedCharacters.indexOf(ctx.token.string) === -1) {
propName = ctx.token.string + tokenString;
offset += ctx.token.string.length;
}
} else if (ctx.token.type === "meta" || tokenString === "-") {
propName = tokenString;
if (TokenUtils.moveNextToken(ctx) &&
(ctx.token.type === "property" || ctx.token.type === "property error" ||
ctx.token.type === "tag")) {
propName += ctx.token.string;
}
} else if (/\S/.test(tokenString) && excludedCharacters.indexOf(tokenString) === -1) {
// We're not inside the property name context.
return createInfo();
} else {
var testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = ctx.editor.getTokenAt(testPos, true);
if (testToken.type === "property" || testToken.type === "property error" ||
testToken.type === "tag") {
propName = testToken.string;
offset = 0;
}
}
// If we're in the property name context but not in an existing property name,
// then reset offset to zero.
if (propName === "") {
offset = 0;
}
return createInfo(PROP_NAME, offset, propName);
}
/**
* @private
* Scans backwards from the current context and returns the name of the property if there is
* a valid one.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {string} the property name of the current rule.
*/
function _getPropNameStartingFromPropValue(ctx) {
var ctxClone = $.extend({}, ctx),
propName = "";
do {
// If we're no longer in the property value before seeing a colon, then we don't
// have a valid property name. Just return an empty string.
if (ctxClone.token.string !== ":" && !_isInPropValue(ctxClone)) {
return "";
}
} while (ctxClone.token.string !== ":" && TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxClone));
if (ctxClone.token.string === ":" && TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxClone) &&
(ctxClone.token.type === "property" || ctxClone.token.type === "property error")) {
propName = ctxClone.token.string;
if (TokenUtils.movePrevToken(ctxClone) && ctxClone.token.type === "meta") {
propName = ctxClone.token.string + propName;
}
}
return propName;
}
/**
* @private
* Gets all of the space/comma seperated tokens before the the current cursor position.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {?Array.<string>} An array of all the space/comma seperated tokens before the
* current cursor position
*/
function _getPrecedingPropValues(ctx) {
var lastValue = "",
curValue,
propValues = [];
while (ctx.token.string !== ":" && TokenUtils.movePrevToken(ctx)) {
if (ctx.token.string === ":" || !_isInPropValue(ctx)) {
break;
}
curValue = ctx.token.string;
if (lastValue !== "") {
curValue += lastValue;
}
if ((ctx.token.string.length > 0 && !ctx.token.string.match(/\S/)) ||
ctx.token.string === ",") {
lastValue = curValue;
} else {
lastValue = "";
if (propValues.length === 0 || curValue.match(/,\s*$/)) {
// stack is empty, or current value ends with a comma
// (and optional whitespace), so push it on the stack
propValues.push(curValue);
} else {
// current value does not end with a comma (and optional ws) so prepend
// to last stack item (e.g. "rgba(50" get broken into 2 tokens)
propValues[propValues.length - 1] = curValue + propValues[propValues.length - 1];
}
}
}
if (propValues.length > 0) {
propValues.reverse();
}
return propValues;
}
/**
* @private
* Gets all of the space/comma seperated tokens after the the current cursor position.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {string} currentValue The token string at the current cursor position
* @return {?Array.<string>} An array of all the space/comma seperated tokens after the
* current cursor position
*/
function _getSucceedingPropValues(ctx, currentValue) {
var lastValue = currentValue,
curValue,
propValues = [];
while (ctx.token.string !== ";" && ctx.token.string !== "}" && TokenUtils.moveNextToken(ctx)) {
if (ctx.token.string === ";" || ctx.token.string === "}") {
break;
}
if (!_isInPropValue(ctx)) {
lastValue = "";
break;
}
if (lastValue === "") {
lastValue = ctx.token.string.trim();
} else if (lastValue.length > 0) {
if (ctx.token.string.length > 0 && !ctx.token.string.match(/\S/)) {
lastValue += ctx.token.string;
propValues.push(lastValue);
lastValue = "";
} else if (ctx.token.string === ",") {
lastValue += ctx.token.string;
} else if (lastValue && lastValue.match(/,$/)) {
propValues.push(lastValue);
if (ctx.token.string.length > 0) {
lastValue = ctx.token.string;
} else {
lastValue = "";
}
} else {
// e.g. "rgba(50" gets broken into 2 tokens
lastValue += ctx.token.string;
}
}
}
if (lastValue.length > 0) {
propValues.push(lastValue);
}
return propValues;
}
/**
* @private
* Return a range object with a start position and an end position after
* skipping any whitespaces and all separators used before and after a
* valid property value.
*
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} startCtx context
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} endCtx context
* @return {{start: {line: number, ch: number},
* end: {line: number, ch: number}}} A range object.
*/
function _getRangeForPropValue(startCtx, endCtx) {
var range = { "start": {},
"end": {} };
// Skip the ":" and any leading whitespace
while (TokenUtils.moveNextToken(startCtx)) {
if (/\S/.test(startCtx.token.string)) {
break;
}
}
// Skip the trailing whitespace and property separators.
while (endCtx.token.string === ";" || endCtx.token.string === "}" ||
!/\S/.test(endCtx.token.string)) {
TokenUtils.movePrevToken(endCtx);
}
range.start = _.clone(startCtx.pos);
range.start.ch = startCtx.token.start;
range.end = _.clone(endCtx.pos);
range.end.ch = endCtx.token.end;
return range;
}
/**
* @private
* Returns a context info object for the current CSS style rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {!Editor} editor
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean,
* range: {start: {line: number, ch: number},
* end: {line: number, ch: number}}}} A CSS context info object.
*/
function _getRuleInfoStartingFromPropValue(ctx, editor) {
var propNamePos = $.extend({}, ctx.pos),
backwardPos = $.extend({}, ctx.pos),
forwardPos = $.extend({}, ctx.pos),
propNameCtx = TokenUtils.getInitialContext(editor._codeMirror, propNamePos),
backwardCtx,
forwardCtx,
lastValue = "",
propValues = [],
index = -1,
offset = TokenUtils.offsetInToken(ctx),
canAddNewOne = false,
testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = editor._codeMirror.getTokenAt(testPos, true),
propName,
range;
// Get property name first. If we don't have a valid property name, then
// return a default rule info.
propName = _getPropNameStartingFromPropValue(propNameCtx);
if (!propName) {
return createInfo();
}
// Scan backward to collect all preceding property values
backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, backwardPos);
propValues = _getPrecedingPropValues(backwardCtx);
lastValue = "";
if (ctx.token.string === ":") {
index = 0;
canAddNewOne = true;
} else {
index = propValues.length - 1;
if (ctx.token.string === ",") {
propValues[index] += ctx.token.string;
index++;
canAddNewOne = true;
} else {
index = (index < 0) ? 0 : index + 1;
if (ctx.token.string.match(/\S/)) {
lastValue = ctx.token.string;
} else {
// Last token is all whitespace
canAddNewOne = true;
if (index > 0) {
// Append all spaces before the cursor to the previous value in values array
propValues[index - 1] += ctx.token.string.substr(0, offset);
}
}
}
}
if (canAddNewOne) {
offset = 0;
// If pos is at EOL, then there's implied whitespace (newline).
if (editor.document.getLine(ctx.pos.line).length > ctx.pos.ch &&
(testToken.string.length === 0 || testToken.string.match(/\S/))) {
canAddNewOne = false;
}
}
// Scan forward to collect all succeeding property values and append to all propValues.
forwardCtx = TokenUtils.getInitialContext(editor._codeMirror, forwardPos);
propValues = propValues.concat(_getSucceedingPropValues(forwardCtx, lastValue));
if (propValues.length) {
range = _getRangeForPropValue(backwardCtx, forwardCtx);
} else {
// No property value, so just return the cursor pos as range
range = { "start": _.clone(ctx.pos),
"end": _.clone(ctx.pos) };
}
// If current index is more than the propValues size, then the cursor is
// at the end of the existing property values and is ready for adding another one.
if (index === propValues.length) {
canAddNewOne = true;
}
return createInfo(PROP_VALUE, offset, propName, index, propValues, canAddNewOne, range);
}
/**
* @private
* Returns a context info object for the current CSS import rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {!Editor} editor
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean,
* range: {start: {line: number, ch: number},
* end: {line: number, ch: number}}}} A CSS context info object.
*/
function _getImportUrlInfo(ctx, editor) {
var propNamePos = $.extend({}, ctx.pos),
backwardPos = $.extend({}, ctx.pos),
forwardPos = $.extend({}, ctx.pos),
backwardCtx,
forwardCtx,
index = 0,
propValues = [],
offset = TokenUtils.offsetInToken(ctx),
testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = editor._codeMirror.getTokenAt(testPos, true);
// Currently only support url. May be null if starting to type
if (ctx.token.type && ctx.token.type !== "string") {
return createInfo();
}
// Move backward to @import and collect data as we go. We return propValues
// array, but we can only have 1 value, so put all data in first item
backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, backwardPos);
propValues[0] = backwardCtx.token.string;
while (TokenUtils.movePrevToken(backwardCtx)) {
if (backwardCtx.token.type === "def" && backwardCtx.token.string === "@import") {
break;
}
if (backwardCtx.token.type && backwardCtx.token.type !== "tag" && backwardCtx.token.string !== "url") {
// Previous token may be white-space
// Otherwise, previous token may only be "url("
break;
}
propValues[0] = backwardCtx.token.string + propValues[0];
offset += backwardCtx.token.string.length;
}
if (backwardCtx.token.type !== "def" || backwardCtx.token.string !== "@import") {
// Not in url
return createInfo();
}
// Get value after cursor up until closing paren or newline
forwardCtx = TokenUtils.getInitialContext(editor._codeMirror, forwardPos);
do {
if (!TokenUtils.moveNextToken(forwardCtx)) {
if (forwardCtx.token.string === "(") {
break;
} else {
return createInfo();
}
}
propValues[0] += forwardCtx.token.string;
} while (forwardCtx.token.string !== ")" && forwardCtx.token.string !== "");
return createInfo(IMPORT_URL, offset, "", index, propValues, false);
}
/**
* Returns a context info object for the given cursor position
* @param {!Editor} editor
* @param {{ch: number, line: number}} constPos A CM pos (likely from editor.getCursorPos())
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean,
* range: {start: {line: number, ch: number},
* end: {line: number, ch: number}}}} A CSS context info object.
*/
function getInfoAtPos(editor, constPos) {
// We're going to be changing pos a lot, but we don't want to mess up
// the pos the caller passed in so we use extend to make a safe copy of it.
var pos = $.extend({}, constPos),
ctx = TokenUtils.getInitialContext(editor._codeMirror, pos),
offset = TokenUtils.offsetInToken(ctx),
propName = "",
mode = editor.getModeForSelection();
// Check if this is inside a style block or in a css/less document.
if (mode !== "css" && mode !== "text/x-scss" && mode !== "text/x-less") {
return createInfo();
}
if (_isInPropName(ctx)) {
return _getPropNameInfo(ctx, editor);
}
if (_isInPropValue(ctx)) {
return _getRuleInfoStartingFromPropValue(ctx, editor);
}
if (_isInAtRule(ctx)) {
return _getImportUrlInfo(ctx, editor);
}
return createInfo();
}
/**
* Extracts all CSS selectors from the given text
* Returns an array of selectors. Each selector is an object with the following properties:
selector: the text of the selector (note: comma separated selector groups like
"h1, h2" are broken into separate selectors)
ruleStartLine: line in the text where the rule (including preceding comment) appears
ruleStartChar: column in the line where the rule (including preceding comment) starts
selectorStartLine: line in the text where the selector appears
selectorStartChar: column in the line where the selector starts
selectorEndLine: line where the selector ends
selectorEndChar: column where the selector ends
selectorGroupStartLine: line where the comma-separated selector group (e.g. .foo, .bar, .baz)
starts that this selector (e.g. .baz) is part of. Particularly relevant for
groups that are on multiple lines.
selectorGroupStartChar: column in line where the selector group starts.
selectorGroup: the entire selector group containing this selector, or undefined if there
is only one selector in the rule.
declListStartLine: line where the declaration list for the rule starts
declListStartChar: column in line where the declaration list for the rule starts
declListEndLine: line where the declaration list for the rule ends
declListEndChar: column in the line where the declaration list for the rule ends
* @param text {!string} CSS text to extract from
* @return {Array.<Object>} Array with objects specifying selectors.
*/
function extractAllSelectors(text) {
var selectors = [];
var mode = CodeMirror.getMode({indentUnit: 2}, "css");
var state, lines, lineCount;
var token, style, stream, line;
var currentSelector = "";
var ruleStartChar = -1, ruleStartLine = -1;
var selectorStartChar = -1, selectorStartLine = -1;
var selectorGroupStartLine = -1, selectorGroupStartChar = -1;
var declListStartLine = -1, declListStartChar = -1;
var escapePattern = new RegExp("\\\\[^\\\\]+", "g");
var validationPattern = new RegExp("\\\\([a-f0-9]{6}|[a-f0-9]{4}(\\s|\\\\|$)|[a-f0-9]{2}(\\s|\\\\|$)|.)", "i");
// implement _firstToken()/_nextToken() methods to
// provide a single stream of tokens
function _hasStream() {
while (stream.eol()) {
line++;
if (line >= lineCount) {
return false;
}
if (currentSelector.match(/\S/)) {
// If we are in a current selector and starting a newline,
// make sure there is whitespace in the selector
currentSelector += " ";
}
stream = new CodeMirror.StringStream(lines[line]);
}
return true;
}
function _firstToken() {
state = CodeMirror.startState(mode);
lines = CodeMirror.splitLines(text);
lineCount = lines.length;
if (lineCount === 0) {
return false;
}
line = 0;
stream = new CodeMirror.StringStream(lines[line]);
if (!_hasStream()) {
return false;
}
style = mode.token(stream, state);
token = stream.current();
return true;
}
function _nextToken() {
// advance the stream past this token
stream.start = stream.pos;
if (!_hasStream()) {
return false;
}
style = mode.token(stream, state);
token = stream.current();
return true;
}
function _firstTokenSkippingWhitespace() {
if (!_firstToken()) {
return false;
}
while (!token.match(/\S/)) {
if (!_nextToken()) {
return false;
}
}
return true;
}
function _nextTokenSkippingWhitespace() {
if (!_nextToken()) {
return false;
}
while (!token.match(/\S/)) {
if (!_nextToken()) {
return false;
}
}
return true;
}
function _isStartComment() {
return (token.match(/^\/\*/));
}
function _parseComment() {
while (!token.match(/\*\/$/)) {
if (!_nextToken()) {
break;
}
}
}
function _nextTokenSkippingComments() {
if (!_nextToken()) {
return false;
}
while (_isStartComment()) {
_parseComment();
if (!_nextToken()) {
return false;
}
}
return true;
}
function _skipToClosingBracket() {
var unmatchedBraces = 0;
while (true) {
if (token === "{") {
unmatchedBraces++;
} else if (token === "}") {
unmatchedBraces--;
if (unmatchedBraces === 0) {
return;
}
}
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
}
function _parseSelector(start) {
currentSelector = "";
selectorStartChar = start;
selectorStartLine = line;
// Everything until the next ',' or '{' is part of the current selector
while (token !== "," && token !== "{") {
currentSelector += token;
if (!_nextTokenSkippingComments()) {
return false; // eof
}
}
// Unicode character replacement as defined in http://www.w3.org/TR/CSS21/syndata.html#characters
if (/\\/.test(currentSelector)) {
// Double replace in case of pattern overlapping (regex improvement?)
currentSelector = currentSelector.replace(escapePattern, function (escapedToken) {
return escapedToken.replace(validationPattern, function (unicodeChar) {
unicodeChar = unicodeChar.substr(1);
if (unicodeChar.length === 1) {
return unicodeChar;
} else {
if (parseInt(unicodeChar, 16) < 0x10FFFF) {
return String.fromCharCode(parseInt(unicodeChar, 16));
} else { return String.fromCharCode(0xFFFD); }
}
});
});
}
currentSelector = currentSelector.trim();
var startChar = (selectorGroupStartLine === -1) ? selectorStartChar : selectorStartChar + 1;
var selectorStart = (stream.string.indexOf(currentSelector, selectorStartChar) !== -1) ? stream.string.indexOf(currentSelector, selectorStartChar - currentSelector.length) : startChar;
if (currentSelector !== "") {
selectors.push({selector: currentSelector,
ruleStartLine: ruleStartLine,
ruleStartChar: ruleStartChar,
selectorStartLine: selectorStartLine,
selectorStartChar: selectorStart,
declListEndLine: -1,
selectorEndLine: line,
selectorEndChar: selectorStart + currentSelector.length,
selectorGroupStartLine: selectorGroupStartLine,
selectorGroupStartChar: selectorGroupStartChar
});
currentSelector = "";
}
selectorStartChar = -1;
return true;
}
function _parseSelectorList() {
selectorGroupStartLine = (stream.string.indexOf(",") !== -1) ? line : -1;
selectorGroupStartChar = stream.start;
if (!_parseSelector(stream.start)) {
return false;
}
while (token === ",") {
if (!_nextTokenSkippingComments()) {
return false; // eof
}
if (!_parseSelector(stream.start)) {
return false;
}
}
return true;
}
function _parseDeclarationList() {
var j;
declListStartLine = Math.min(line, lineCount - 1);
declListStartChar = stream.start;
// Extract the entire selector group we just saw.
var selectorGroup, sgLine;
if (selectorGroupStartLine !== -1) {
selectorGroup = "";
for (sgLine = selectorGroupStartLine; sgLine <= declListStartLine; sgLine++) {
var startChar = 0, endChar = lines[sgLine].length;
if (sgLine === selectorGroupStartLine) {
startChar = selectorGroupStartChar;
} else {
selectorGroup += " "; // replace the newline with a single space
}
if (sgLine === declListStartLine) {
endChar = declListStartChar;
}
selectorGroup += lines[sgLine].substring(startChar, endChar);
}
selectorGroup = selectorGroup.trim();
}
// Since we're now in a declaration list, that means we also finished
// parsing the whole selector group. Therefore, reset selectorGroupStartLine
// so that next time we parse a selector we know it's a new group
selectorGroupStartLine = -1;
selectorGroupStartChar = -1;
ruleStartLine = -1;
ruleStartChar = -1;
// Skip everything until the next '}'
while (token !== "}") {
if (!_nextTokenSkippingComments()) {
break;
}
}
// assign this declaration list position and selector group to every selector on the stack
// that doesn't have a declaration list start and end line
for (j = selectors.length - 1; j >= 0; j--) {
if (selectors[j].declListEndLine !== -1) {
break;
} else {
selectors[j].declListStartLine = declListStartLine;
selectors[j].declListStartChar = declListStartChar;
selectors[j].declListEndLine = line;
selectors[j].declListEndChar = stream.pos - 1; // stream.pos actually points to the char after the }
if (selectorGroup) {
selectors[j].selectorGroup = selectorGroup;
}
}
}
}
function includeCommentInNextRule() {
if (ruleStartChar !== -1) {
return false; // already included
}
if (stream.start > 0 && lines[line].substr(0, stream.start).indexOf("}") !== -1) {
return false; // on same line as '}', so it's for previous rule
}
return true;
}
function _isStartAtRule() {
return (token.match(/^@/));
}
function _parseAtRule() {
// reset these fields to ignore comments preceding @rules
ruleStartLine = -1;
ruleStartChar = -1;
selectorStartLine = -1;
selectorStartChar = -1;
selectorGroupStartLine = -1;
selectorGroupStartChar = -1;
if (token.match(/@media/i)) {
// @media rule holds a rule list
// Skip everything until the opening '{'
while (token !== "{") {
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
// skip past '{', to next non-ws token
if (!_nextTokenSkippingWhitespace()) {
return; // eof
}
// Parse rules until we see '}'
_parseRuleList("}");
} else if (token.match(/@(charset|import|namespace)/i)) {
// This code handles @rules in this format:
// @rule ... ;
// Skip everything until the next ';'
while (token !== ";") {
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
} else {
// This code handle @rules that use this format:
// @rule ... { ... }
// such as @page, @keyframes (also -webkit-keyframes, etc.), and @font-face.
// Skip everything including nested braces until the next matching '}'
_skipToClosingBracket();
}
}
// parse a style rule
function _parseRule() {
if (!_parseSelectorList()) {
return false;
}
_parseDeclarationList();
}
function _parseRuleList(escapeToken) {
while ((!escapeToken) || token !== escapeToken) {
if (_isStartAtRule()) {
// @rule
_parseAtRule();
} else if (_isStartComment()) {
// comment - make this part of style rule
if (includeCommentInNextRule()) {
ruleStartChar = stream.start;
ruleStartLine = line;
}
_parseComment();
} else {
// Otherwise, it's style rule
if (ruleStartChar === -1) {
ruleStartChar = stream.start;
ruleStartLine = line;
}
_parseRule();
}
if (!_nextTokenSkippingWhitespace()) {
break;
}
}
}
// Do parsing
if (_firstTokenSkippingWhitespace()) {
// Style sheet is a rule list
_parseRuleList();
}
return selectors;
}
/*
* This code can be used to create an "independent" HTML document that can be passed to jQuery
* calls. Allows using jQuery's CSS selector engine without actually putting anything in the browser's DOM
*
var _htmlDoctype = document.implementation.createDocumentType('html',
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);
var _htmlDocument = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', _htmlDoctype);
function checkIfSelectorSelectsHTML(selector, theHTML) {
$('html', _htmlDocument).html(theHTML);
return ($(selector, _htmlDocument).length > 0);
}
*/
/**
* Finds all instances of the specified selector in "text".
* Returns an Array of Objects with start and end properties.
*
* For Sprint 4, we only support simple selectors. This function will need to change
* dramatically to support full selectors.
*
* FUTURE: (JRB) It would be nice to eventually use the browser/jquery to do the selector evaluation.
* One way to do this would be to take the user's HTML, add a special attribute to every tag with a UID,
* and then construct a DOM (using the commented out code above). Then, give this DOM and the selector to
* jquery and ask what matches. If the node that the user's cursor is in comes back from jquery, then
* we know the selector applies.
*
* @param text {!string} CSS text to search
* @param selector {!string} selector to search for
* @return {Array.<{selectorGroupStartLine:number, declListEndLine:number, selector:string}>}
* Array of objects containing the start and end line numbers (0-based, inclusive range) for each
* matched selector.
*/
function _findAllMatchingSelectorsInText(text, selector) {
var allSelectors = extractAllSelectors(text);
var result = [];
var i;
// For sprint 4 we only match the rightmost simple selector, and ignore
// attribute selectors and pseudo selectors
var classOrIdSelector = selector[0] === "." || selector[0] === "#";
var prefix = "";
// Escape initial "." in selector, if present.
if (selector[0] === ".") {
selector = "\\" + selector;
}
if (!classOrIdSelector) {
// Tag selectors must have nothing, whitespace, or a combinator before it.
selector = "(^|[\\s>+~])" + selector;
}
var re = new RegExp(selector + "(\\[[^\\]]*\\]|:{1,2}[\\w-()]+|\\.[\\w-]+|#[\\w-]+)*\\s*$", classOrIdSelector ? "" : "i");
allSelectors.forEach(function (entry) {
if (entry.selector.search(re) !== -1) {
result.push(entry);
} else if (!classOrIdSelector) {
// Special case for tag selectors - match "*" as the rightmost character
if (/\*\s*$/.test(entry.selector)) {
result.push(entry);
}
}
});
return result;
}
/**
* Converts the results of _findAllMatchingSelectorsInText() into a simpler bag of data and
* appends those new objects to the given 'resultSelectors' Array.
* @param {Array.<{document:Document, lineStart:number, lineEnd:number}>} resultSelectors
* @param {Array.<{selectorGroupStartLine:number, declListEndLine:number, selector:string}>} selectorsToAdd
* @param {!Document} sourceDoc
* @param {!number} lineOffset Amount to offset all line number info by. Used if the first line
* of the parsed CSS text is not the first line of the sourceDoc.
*/
function _addSelectorsToResults(resultSelectors, selectorsToAdd, sourceDoc, lineOffset) {
selectorsToAdd.forEach(function (selectorInfo) {
resultSelectors.push({
name: selectorInfo.selector,
document: sourceDoc,
lineStart: selectorInfo.ruleStartLine + lineOffset,
lineEnd: selectorInfo.declListEndLine + lineOffset,
selectorGroup: selectorInfo.selectorGroup
});
});
}
/** Finds matching selectors in CSS files; adds them to 'resultSelectors' */
function _findMatchingRulesInCSSFiles(selector, resultSelectors) {
var result = new $.Deferred();
// Load one CSS file and search its contents
function _loadFileAndScan(fullPath, selector) {
var oneFileResult = new $.Deferred();
DocumentManager.getDocumentForPath(fullPath)
.done(function (doc) {
// Find all matching rules for the given CSS file's content, and add them to the
// overall search result
var oneCSSFileMatches = _findAllMatchingSelectorsInText(doc.getText(), selector);
_addSelectorsToResults(resultSelectors, oneCSSFileMatches, doc, 0);
oneFileResult.resolve();
})
.fail(function (error) {
oneFileResult.reject(error);
});
return oneFileResult.promise();
}
ProjectManager.getAllFiles(ProjectManager.getLanguageFilter("css"))
.done(function (cssFiles) {
// Load index of all CSS files; then process each CSS file in turn (see above)
Async.doInParallel(cssFiles, function (fileInfo, number) {
return _loadFileAndScan(fileInfo.fullPath, selector);
})
.then(result.resolve, result.reject);
});
return result.promise();
}
/** Finds matching selectors in the <style> block of a single HTML file; adds them to 'resultSelectors' */
function _findMatchingRulesInStyleBlocks(htmlDocument, selector, resultSelectors) {
// HTMLUtils requires a real CodeMirror instance; make sure we can give it the right Editor
var htmlEditor = EditorManager.getCurrentFullEditor();
if (htmlEditor.document !== htmlDocument) {
console.error("Cannot search for <style> blocks in HTML file other than current editor");
return;
}
// Find all <style> blocks in the HTML file
var styleBlocks = HTMLUtils.findStyleBlocks(htmlEditor);
styleBlocks.forEach(function (styleBlockInfo) {
// Search this one <style> block's content, appending results to 'resultSelectors'
var oneStyleBlockMatches = _findAllMatchingSelectorsInText(styleBlockInfo.text, selector);
_addSelectorsToResults(resultSelectors, oneStyleBlockMatches, htmlDocument, styleBlockInfo.start.line);
});
}
/**
* Return all rules matching the specified selector.
* For Sprint 4, we only look at the rightmost simple selector. For example, searching for ".foo" will
* match these rules:
* .foo {}
* div .foo {}
* div.foo {}
* div .foo[bar="42"] {}
* div .foo:hovered {}
* div .foo::first-child
* but will *not* match these rules:
* .foobar {}
* .foo .bar {}
* div .foo .bar {}
* .foo.bar {}
*
* @param {!string} selector The selector to match. This can be a tag selector, class selector or id selector
* @param {?Document} htmlDocument An HTML file for context (so we can search <style> blocks)
* @return {$.Promise} that will be resolved with an Array of objects containing the
* source document, start line, and end line (0-based, inclusive range) for each matching declaration list.
* Does not addRef() the documents returned in the array.
*/
function findMatchingRules(selector, htmlDocument) {
var result = new $.Deferred(),
resultSelectors = [];
// Synchronously search for matches in <style> blocks
if (htmlDocument) {
_findMatchingRulesInStyleBlocks(htmlDocument, selector, resultSelectors);
}
// Asynchronously search for matches in all the project's CSS files
// (results are appended together in same 'resultSelectors' array)
_findMatchingRulesInCSSFiles(selector, resultSelectors)
.done(function () {
result.resolve(resultSelectors);
})
.fail(function (error) {
result.reject(error);
});
return result.promise();
}
/**
* Returns the selector(s) of the rule at the specified document pos, or "" if the position is
* is not within a style rule.
*
* @param {!Editor} editor Editor to search
* @param {!{line: number, ch: number}} pos Position to search
* @return {string} Selector(s) for the rule at the specified position, or "" if the position
* is not within a style rule. If the rule has multiple selectors, a comma-separated
* selector string is returned.
*/
function findSelectorAtDocumentPos(editor, pos) {
var cm = editor._codeMirror;
var ctx = TokenUtils.getInitialContext(cm, $.extend({}, pos));
var selector = "", inSelector = false, foundChars = false;
function _stripAtRules(selector) {
selector = selector.trim();
if (selector.indexOf("@") === 0) {
return "";
}
return selector;
}
// Parse a selector. Assumes ctx is pointing at the opening
// { that is after the selector name.
function _parseSelector(ctx) {
var selector = "";
// Skip over {
TokenUtils.movePrevToken(ctx);
while (true) {
if (ctx.token.type !== "comment") {
// Stop once we've reached a {, }, or ;
if (/[\{\}\;]/.test(ctx.token.string)) {
break;
}
// Stop once we've reached a <style ...> tag
if (ctx.token.string === "style" && ctx.token.type === "tag") {
// Remove everything up to end-of-tag from selector
var eotIndex = selector.indexOf(">");
if (eotIndex !== -1) {
selector = selector.substring(eotIndex + 1);
}
break;
}
selector = ctx.token.string + selector;
}
if (!TokenUtils.movePrevToken(ctx)) {
break;
}
}
return selector;
}
// scan backwards to see if the cursor is in a rule
while (true) {
if (ctx.token.type !== "comment") {
if (ctx.token.string === "}") {
break;
} else if (ctx.token.string === "{") {
selector = _parseSelector(ctx);
break;
} else {
if (/\S/.test(ctx.token.string)) {
foundChars = true;
}
}
}
if (!TokenUtils.movePrevToken(ctx)) {
break;
}
}
selector = _stripAtRules(selector);
// Reset the context to original scan position
ctx = TokenUtils.getInitialContext(cm, $.extend({}, pos));
// special case - we aren't in a selector and haven't found any chars,
// look at the next immediate token to see if it is non-whitespace
if (!selector && !foundChars) {
if (TokenUtils.moveNextToken(ctx) && ctx.token.type !== "comment" && /\S/.test(ctx.token.string)) {
foundChars = true;
ctx = TokenUtils.getInitialContext(cm, $.extend({}, pos));
}
}
// At this point if we haven't found a selector, but have seen chars when
// scanning, assume we are in the middle of a selector.
if (!selector && foundChars) {
// scan forward to see if the cursor is in a selector
while (true) {
if (ctx.token.type !== "comment") {
if (ctx.token.string === "{") {
selector = _parseSelector(ctx);
break;
} else if (ctx.token.string === "}" || ctx.token.string === ";") {
break;
}
}
if (!TokenUtils.moveNextToken(ctx)) {
break;
}
}
}
return _stripAtRules(selector);
}
/**
* removes CSS comments from the content
* @param {!string} content to reduce
* @return {string} reduced content
*/
function _removeComments(content) {
return content.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\//g, "");
}
/**
* removes strings from the content
* @param {!string} content to reduce
* @return {string} reduced content
*/
function _removeStrings(content) {
return content.replace(/[^\\]\"(.*)[^\\]\"|[^\\]\'(.*)[^\\]\'+/g, "");
}
/**
* Reduces the style sheet by removing comments and strings
* so that the content can be parsed using a regular expression
* @param {!string} content to reduce
* @return {string} reduced content
*/
function reduceStyleSheetForRegExParsing(content) {
return _removeStrings(_removeComments(content));
}
/**
* Extracts all named flow instances
* @param {!string} text to extract from
* @return {Array.<string>} array of unique flow names found in the content (empty if none)
*/
function extractAllNamedFlows(text) {
var namedFlowRegEx = /(?:flow\-(into|from)\:\s*)([\w\-]+)(?:\s*;)/gi,
result = [],
names = {},
thisMatch;
// Reduce the content so that matches
// inside strings and comments are ignored
text = reduceStyleSheetForRegExParsing(text);
// Find the first match
thisMatch = namedFlowRegEx.exec(text);
// Iterate over the matches and add them to result
while (thisMatch) {
var thisName = thisMatch[2];
if (IGNORED_FLOW_NAMES.indexOf(thisName) === -1 && !names.hasOwnProperty(thisName)) {
names[thisName] = result.push(thisName);
}
thisMatch = namedFlowRegEx.exec(text);
}
return result;
}
/**
* Adds a new rule to the end of the given document, and returns the range of the added rule
* and the position of the cursor on the indented blank line within it. Note that the range will
* not include all the inserted text (we insert extra newlines before and after the rule).
* @param {Document} doc The document to insert the rule into.
* @param {string} selector The selector to use for the given rule.
* @param {boolean} useTabChar Whether to indent with a tab.
* @param {number} indentUnit If useTabChar is false, how many spaces to indent with.
* @return {{range: {from: {line: number, ch: number}, to: {line: number, ch: number}}, pos: {line: number, ch: number}}}
* The range of the inserted rule and the location where the cursor should be placed.
*/
function addRuleToDocument(doc, selector, useTabChar, indentUnit) {
var newRule = "\n" + selector + " {\n",
blankLineOffset;
if (useTabChar) {
newRule += "\t";
blankLineOffset = 1;
} else {
var i;
for (i = 0; i < indentUnit; i++) {
newRule += " ";
}
blankLineOffset = indentUnit;
}
newRule += "\n}\n";
var docLines = doc.getText().split("\n"),
lastDocLine = docLines.length - 1,
lastDocChar = docLines[docLines.length - 1].length;
doc.replaceRange(newRule, {line: lastDocLine, ch: lastDocChar});
return {
range: {
from: {line: lastDocLine + 1, ch: 0},
to: {line: lastDocLine + 3, ch: 1}
},
pos: {line: lastDocLine + 2, ch: blankLineOffset}
};
}
/**
*
* In the given rule array (as returned by `findMatchingRules()`), if multiple rules in a row
* refer to the same rule (because there were multiple matching selectors), eliminate the redundant
* rules. Also, always use the selector group if available instead of the original matching selector.
*/
function consolidateRules(rules) {
var newRules = [], lastRule;
rules.forEach(function (rule) {
if (rule.selectorGroup) {
rule.name = rule.selectorGroup;
}
// Push the entry unless it refers to the same rule as the previous entry.
if (!(lastRule &&
rule.document === lastRule.document &&
rule.lineStart === lastRule.lineStart &&
rule.lineEnd === lastRule.lineEnd &&
rule.selectorGroup === lastRule.selectorGroup)) {
newRules.push(rule);
}
lastRule = rule;
});
return newRules;
}
/**
* Given a TextRange, extracts the selector(s) for the rule in the range and returns it.
* Assumes the range only contains one rule; if there's more than one, it will return the
* selector(s) for the first rule.
* @param {TextRange} range The range to extract the selector(s) from.
* @return {string} The selector(s) for the rule in the range.
*/
function getRangeSelectors(range) {
// There's currently no immediate way to access a given line in a Document, because it's just
// stored as a string. Eventually, we should have Documents cache the lines in the document
// as well, or make them use CodeMirror documents which do the same thing.
var i, startIndex = 0, endIndex, text = range.document.getText();
for (i = 0; i < range.startLine; i++) {
startIndex = text.indexOf("\n", startIndex) + 1;
}
endIndex = startIndex;
// Go one line past the end line. We'll extract text up to but not including the last newline.
for (i = range.startLine + 1; i <= range.endLine + 1; i++) {
endIndex = text.indexOf("\n", endIndex) + 1;
}
var allSelectors = extractAllSelectors(text.substring(startIndex, endIndex));
// There should only be one rule in the range, and if there are multiple selectors for
// the first rule, they'll all be recorded in the "selectorGroup" for the first selector,
// so we only need to look at the first one.
return (allSelectors.length ? allSelectors[0].selectorGroup || allSelectors[0].selector : "");
}
exports._findAllMatchingSelectorsInText = _findAllMatchingSelectorsInText; // For testing only
exports.findMatchingRules = findMatchingRules;
exports.extractAllSelectors = extractAllSelectors;
exports.extractAllNamedFlows = extractAllNamedFlows;
exports.findSelectorAtDocumentPos = findSelectorAtDocumentPos;
exports.reduceStyleSheetForRegExParsing = reduceStyleSheetForRegExParsing;
exports.addRuleToDocument = addRuleToDocument;
exports.consolidateRules = consolidateRules;
exports.getRangeSelectors = getRangeSelectors;
exports.SELECTOR = SELECTOR;
exports.PROP_NAME = PROP_NAME;
exports.PROP_VALUE = PROP_VALUE;
exports.IMPORT_URL = IMPORT_URL;
exports.getInfoAtPos = getInfoAtPos;
// The createInfo is really only for the unit tests so they can make the same
// structure to compare results with.
exports.createInfo = createInfo;
});
| alicoding/nimble | src/language/CSSUtils.js | JavaScript | mit | 60,267 |
(function(){
"use strict";
angular.module('app.controllers').controller('HomeCtrl', function(){
//
});
})();
| apps-libX/myapp | angular/app/app/home/home.js | JavaScript | mit | 131 |
// ***********************************************************************
// Assembly : ACBr.Net.NFSe
// Author : RFTD
// Created : 05-19-2016
//
// Last Modified By : RFTD
// Last Modified On : 05-19-2016
// ***********************************************************************
// <copyright file="TipoRPS.cs" company="ACBr.Net">
// The MIT License (MIT)
// Copyright (c) 2016 Grupo ACBr.Net
//
// 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.
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace ACBr.Net.NFSe.Nota
{
public enum TipoRps
{
RPS = 0,
NFConjugada = 1,
Cupom = 2
}
} | rafd75/ACBr.Net.NFSe | src/ACBr.Net.NFSe.Shared/Nota/TipoRps.cs | C# | mit | 1,736 |
#include "worker.h"
#include "sharedbuffer.h"
#include "nan.h"
#include "util.h"
using namespace v8;
static Persistent<ObjectTemplate> worker_template;
static Persistent<String> id_symbol;
NAN_METHOD(Eval) {
NanScope();
NanReturnUndefined();
}
Worker::Worker() {
m_error = 0;
}
Worker::~Worker() {
}
//static
Worker* Worker::Start(const v8::Arguments &args) {
if (worker_template.IsEmpty()) {
Local<String> localSymbol = NanNew<String>("id");
NanAssignPersistent(id_symbol, localSymbol);
Local<ObjectTemplate> tpl = ObjectTemplate::New();
tpl->SetInternalFieldCount(1);
tpl->Set(localSymbol, NanNew<Integer>(0));
tpl->Set(NanNew<String>("eval"), NanNew<FunctionTemplate>(Eval));
NanAssignPersistent(worker_template, tpl);
}
if (args.Length() < 3 || !args[2]->IsFunction()) {
NanThrowTypeError("Usage: createWorker(script, sharedBufferObj, callback)");
return NULL;
}
Worker *worker = new Worker();
worker->m_script = new String::Utf8Value(args[0]);
if (args[1]->IsNumber()) {
NanAssignPersistent(worker->m_sharedBufferId, args[1]->ToInt32());
}
NanAssignPersistent(worker->m_callback, args[2]->ToObject());
Local<Object> jsObj = NanNew(worker_template)->NewInstance();
jsObj->Set(NanNew<String>("id"), NanNew<Integer>(11));
NanSetInternalFieldPointer(jsObj, 0, worker);
NanAssignPersistent(worker->m_jsobject, jsObj);
worker->m_work.data = worker;
/*int ret = */uv_queue_work(uv_default_loop(), &(worker->m_work), WorkerProc, PostWorkerProc);
return worker;
}
//static
void Worker::WorkerProc(uv_work_t *req) {
// sub thread
Worker *worker = (Worker*)(req->data);
worker->m_isolate = Isolate::New();
NanSetIsolateData(worker->m_isolate, worker);
if (!Locker::IsActive()) {
worker->ReleaseIsolate();
return;
}
{ // wrap Lock within scope is very important
Locker myLocker(worker->m_isolate);
worker->m_isolate->Enter();
NanScope();
Persistent<Context> ctx = Context::New();
ctx->Enter();
Local<Object> ctx_global = ctx->Global();
Handle<Object> consoleObj = NanNew<Object>();
consoleObj->Set(NanNew<String>("log"), NanNew<FunctionTemplate>(console_log)->GetFunction());
consoleObj->Set(NanNew<String>("error"), NanNew<FunctionTemplate>(console_error)->GetFunction());
ctx_global->Set(NanNew<String>("console"), consoleObj, (PropertyAttribute)(ReadOnly | DontDelete));
if (!worker->m_sharedBufferId.IsEmpty()) {
SharedBuffer *buf = SharedBuffer::getSharedBuffer((int)worker->m_sharedBufferId->Value());
if (buf) {
Local<ObjectTemplate> sharedBufTpl = ObjectTemplate::New();
Local<Object> jsObj = sharedBufTpl->NewInstance();
SharedBuffer::bindProperties(jsObj, buf);
NanAssignPersistent(worker->m_sharedBufferObject, jsObj);
ctx_global->Set(NanNew<String>("sharedBuffer"), jsObj);
} else {
ctx_global->Set(NanNew<String>("sharedBuffer"), Null());
}
} else {
ctx_global->Set(NanNew<String>("sharedBuffer"), Null());
}
TryCatch tryCatch;
String::Utf8Value *result;
Local<String> source = NanNew<String>(**worker->m_script, worker->m_script->length());
Local<Script> script = NanCompileScript(source);
Local<Value> retValue = NanRunScript(script);
if (!tryCatch.HasCaught()) {
result = new String::Utf8Value(retValue->ToString());
} else {
worker->m_error = 1;
Local<Value> err = tryCatch.Exception();
result = new String::Utf8Value(err->ToString());
printf("WorkerProc failed to run script: %s\n", **result);
}
worker->m_result = result;
ctx.Dispose();
}
worker->ReleaseIsolate();
}
//static
void Worker::PostWorkerProc(uv_work_t *req, int result) {
Worker *worker = (Worker*)(req->data);
NanScope();
Local<Value> argv[2];
if (worker->m_error) {
argv[0] = String::New("error");
argv[1] = Local<Value>::New(Null());
} else {
argv[0] = Local<Value>::New(Null());
argv[1] = String::New("Succeed");
}
worker->m_callback->CallAsFunction(Object::New(), 2, argv);
}
void Worker::ReleaseIsolate() {
m_isolate->Exit();
m_isolate->Dispose();
m_isolate = NULL;
}
| yejingfu/multithread | src/worker.cc | C++ | mit | 4,222 |
// stdafx.cpp : source file that includes just the standard includes
// Pookie.DayTime.Client.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| jleo2255/c_challenges | Pookie.DayTime.Client/Pookie.DayTime.Client/stdafx.cpp | C++ | mit | 300 |
/* -----------------------------------------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
1. INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
of the MPEG specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
individually for the purpose of encoding or decoding bit streams in products that are compliant with
the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
software may already be covered under those patent licenses when it is used for those licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
applications information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification, are permitted without
payment of copyright license fees provided that you satisfy the following conditions:
You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation and/or other materials
provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived from this library without
prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
and the date of any change. For modified versions of the FDK AAC Codec, the term
"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
respect to this software.
You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
or business interruption, however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence), arising in any way out of the use of this software, even if
advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------------------------------------- */
/***************************** MPEG-4 AAC Decoder **************************
Author(s): Josef Hoepfl
Description: long/short-block decoding
******************************************************************************/
#include "block.h"
#include "aac_rom.h"
#include "FDK_bitstream.h"
#include "FDK_tools_rom.h"
#include "aacdec_hcr.h"
#include "rvlc.h"
#if defined(__arm__)
#include "arm/block_arm.cpp"
#endif
/*!
\brief Read escape sequence of codeword
The function reads the escape sequence from the bitstream,
if the absolute value of the quantized coefficient has the
value 16.
\return quantized coefficient
*/
LONG CBlock_GetEscape(HANDLE_FDK_BITSTREAM bs, /*!< pointer to bitstream */
const LONG q) /*!< quantized coefficient */
{
LONG i, off, neg ;
if (q < 0)
{
if (q != -16) return q;
neg = 1;
}
else
{
if (q != +16) return q;
neg = 0;
}
for (i=4; ; i++)
{
if (FDKreadBits(bs,1) == 0)
break;
}
if (i > 16)
{
if (i - 16 > CACHE_BITS) { /* cannot read more than "CACHE_BITS" bits at once in the function FDKreadBits() */
return (MAX_QUANTIZED_VALUE + 1); /* returning invalid value that will be captured later */
}
off = FDKreadBits(bs,i-16) << 16;
off |= FDKreadBits(bs,16);
}
else
{
off = FDKreadBits(bs,i);
}
i = off + (1 << i);
if (neg) i = -i;
return i;
}
AAC_DECODER_ERROR CBlock_ReadScaleFactorData(
CAacDecoderChannelInfo *pAacDecoderChannelInfo,
HANDLE_FDK_BITSTREAM bs,
UINT flags
)
{
int temp;
int band;
int group;
int position = 0; /* accu for intensity delta coding */
int factor = pAacDecoderChannelInfo->pDynData->RawDataInfo.GlobalGain; /* accu for scale factor delta coding */
UCHAR *pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
SHORT *pScaleFactor = pAacDecoderChannelInfo->pDynData->aScaleFactor;
const CodeBookDescription *hcb =&AACcodeBookDescriptionTable[BOOKSCL];
int ScaleFactorBandsTransmitted = GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
for (group=0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)
{
for (band=0; band < ScaleFactorBandsTransmitted; band++)
{
switch (pCodeBook[group*16+band]) {
case ZERO_HCB: /* zero book */
pScaleFactor[group*16+band] = 0;
break;
default: /* decode scale factor */
{
temp = CBlock_DecodeHuffmanWord(bs,hcb);
factor += temp - 60; /* MIDFAC 1.5 dB */
}
pScaleFactor[group*16+band] = factor - 100;
break;
case INTENSITY_HCB: /* intensity steering */
case INTENSITY_HCB2:
temp = CBlock_DecodeHuffmanWord(bs,hcb);
position += temp - 60;
pScaleFactor[group*16+band] = position - 100;
break;
case NOISE_HCB: /* PNS */
if (flags & (AC_MPS_RES|AC_USAC|AC_RSVD50)) {
return AAC_DEC_PARSE_ERROR;
}
CPns_Read( &pAacDecoderChannelInfo->data.aac.PnsData, bs, hcb, pAacDecoderChannelInfo->pDynData->aScaleFactor, pAacDecoderChannelInfo->pDynData->RawDataInfo.GlobalGain, band, group);
break;
}
}
}
return AAC_DEC_OK;
}
void CBlock_ScaleSpectralData(CAacDecoderChannelInfo *pAacDecoderChannelInfo, SamplingRateInfo *pSamplingRateInfo)
{
int band;
int window;
const SHORT * RESTRICT pSfbScale = pAacDecoderChannelInfo->pDynData->aSfbScale;
SHORT * RESTRICT pSpecScale = pAacDecoderChannelInfo->specScale;
int groupwin,group;
const SHORT * RESTRICT BandOffsets = GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
SPECTRAL_PTR RESTRICT pSpectralCoefficient = pAacDecoderChannelInfo->pSpectralCoefficient;
FDKmemclear(pSpecScale, 8*sizeof(SHORT));
int max_band = GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
for (window=0, group=0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)
{
for (groupwin=0; groupwin < GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo,group); groupwin++, window++)
{
int SpecScale_window = pSpecScale[window];
FIXP_DBL *pSpectrum = SPEC(pSpectralCoefficient, window, pAacDecoderChannelInfo->granuleLength);
/* find scaling for current window */
for (band=0; band < max_band; band++)
{
SpecScale_window = fMax(SpecScale_window, (int)pSfbScale[window*16+band]);
}
if (pAacDecoderChannelInfo->pDynData->TnsData.Active) {
SpecScale_window += TNS_SCALE;
}
/* store scaling of current window */
pSpecScale[window] = SpecScale_window;
#ifdef FUNCTION_CBlock_ScaleSpectralData_func1
CBlock_ScaleSpectralData_func1(pSpectrum, max_band, BandOffsets, SpecScale_window, pSfbScale, window);
#else /* FUNCTION_CBlock_ScaleSpectralData_func1 */
for (band=0; band < max_band; band++)
{
int scale = SpecScale_window - pSfbScale[window*16+band];
if (scale)
{
/* following relation can be used for optimizations: (BandOffsets[i]%4) == 0 for all i */
int max_index = BandOffsets[band+1];
for (int index = BandOffsets[band]; index < max_index; index++)
{
pSpectrum[index] >>= scale;
}
}
}
#endif /* FUNCTION_CBlock_ScaleSpectralData_func1 */
}
}
}
AAC_DECODER_ERROR CBlock_ReadSectionData(HANDLE_FDK_BITSTREAM bs,
CAacDecoderChannelInfo *pAacDecoderChannelInfo,
const SamplingRateInfo *pSamplingRateInfo,
const UINT flags)
{
int top, band;
int sect_len, sect_len_incr;
int group;
UCHAR sect_cb;
UCHAR *pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
/* HCR input (long) */
SHORT *pNumLinesInSec = pAacDecoderChannelInfo->pDynData->specificTo.aac.aNumLineInSec4Hcr;
int numLinesInSecIdx = 0;
UCHAR *pHcrCodeBook = pAacDecoderChannelInfo->pDynData->specificTo.aac.aCodeBooks4Hcr;
const SHORT *BandOffsets = GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
pAacDecoderChannelInfo->pDynData->specificTo.aac.numberSection = 0;
AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
FDKmemclear(pCodeBook, sizeof(UCHAR)*(8*16));
const int nbits = (IsLongBlock(&pAacDecoderChannelInfo->icsInfo) == 1) ? 5 : 3;
int sect_esc_val = (1 << nbits) - 1 ;
UCHAR ScaleFactorBandsTransmitted = GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
for (group=0; group<GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)
{
for (band=0; band < ScaleFactorBandsTransmitted; )
{
sect_len = 0;
if ( flags & AC_ER_VCB11 ) {
sect_cb = (UCHAR) FDKreadBits(bs,5);
}
else
sect_cb = (UCHAR) FDKreadBits(bs,4);
if ( ((flags & AC_ER_VCB11) == 0) || ( sect_cb < 11 ) || ((sect_cb > 11) && (sect_cb < 16)) ) {
sect_len_incr = FDKreadBits(bs, nbits);
while (sect_len_incr == sect_esc_val)
{
sect_len += sect_esc_val;
sect_len_incr = FDKreadBits(bs, nbits);
}
}
else {
sect_len_incr = 1;
}
sect_len += sect_len_incr;
top = band + sect_len;
if (flags & AC_ER_HCR) {
/* HCR input (long) -- collecting sideinfo (for HCR-_long_ only) */
pNumLinesInSec[numLinesInSecIdx] = BandOffsets[top] - BandOffsets[band];
numLinesInSecIdx++;
if (numLinesInSecIdx >= MAX_SFB_HCR) {
return AAC_DEC_PARSE_ERROR;
}
if (sect_cb == BOOKSCL)
{
return AAC_DEC_INVALID_CODE_BOOK;
} else {
*pHcrCodeBook++ = sect_cb;
}
pAacDecoderChannelInfo->pDynData->specificTo.aac.numberSection++;
}
/* Check spectral line limits */
if (IsLongBlock( &(pAacDecoderChannelInfo->icsInfo) ))
{
if (top > 64) {
return AAC_DEC_DECODE_FRAME_ERROR;
}
} else { /* short block */
if (top + group*16 > (8 * 16)) {
return AAC_DEC_DECODE_FRAME_ERROR;
}
}
/* Check if decoded codebook index is feasible */
if ( (sect_cb == BOOKSCL)
|| ( (sect_cb == INTENSITY_HCB || sect_cb == INTENSITY_HCB2) && pAacDecoderChannelInfo->pDynData->RawDataInfo.CommonWindow == 0)
)
{
return AAC_DEC_INVALID_CODE_BOOK;
}
/* Store codebook index */
for (; band < top; band++)
{
pCodeBook[group*16+band] = sect_cb;
}
}
}
return ErrorStatus;
}
/* mso: provides a faster way to i-quantize a whole band in one go */
/**
* \brief inverse quantize one sfb. Each value of the sfb is processed according to the
* formula: spectrum[i] = Sign(spectrum[i]) * Matissa(spectrum[i])^(4/3) * 2^(lsb/4).
* \param spectrum pointer to first line of the sfb to be inverse quantized.
* \param noLines number of lines belonging to the sfb.
* \param lsb last 2 bits of the scale factor of the sfb.
* \param scale max allowed shift scale for the sfb.
*/
static
void InverseQuantizeBand( FIXP_DBL * RESTRICT spectrum,
INT noLines,
INT lsb,
INT scale )
{
const FIXP_DBL * RESTRICT InverseQuantTabler=(FIXP_DBL *)InverseQuantTable;
const FIXP_DBL * RESTRICT MantissaTabler=(FIXP_DBL *)MantissaTable[lsb];
const SCHAR* RESTRICT ExponentTabler=(SCHAR*)ExponentTable[lsb];
FIXP_DBL *ptr = spectrum;
FIXP_DBL signedValue;
FDK_ASSERT(noLines>2);
for (INT i=noLines; i--; )
{
if ((signedValue = *ptr++) != FL2FXCONST_DBL(0))
{
FIXP_DBL value = fAbs(signedValue);
UINT freeBits = CntLeadingZeros(value);
UINT exponent = 32 - freeBits;
UINT x = (UINT) (LONG)value << (INT) freeBits;
x <<= 1; /* shift out sign bit to avoid masking later on */
UINT tableIndex = x >> 24;
x = (x >> 20) & 0x0F;
UINT r0=(UINT)(LONG)InverseQuantTabler[tableIndex+0];
UINT r1=(UINT)(LONG)InverseQuantTabler[tableIndex+1];
UINT temp= (r1 - r0)*x + (r0 << 4);
value = fMultDiv2((FIXP_DBL)temp, MantissaTabler[exponent]);
/* + 1 compensates fMultDiv2() */
scaleValueInPlace(&value, scale + ExponentTabler[exponent] + 1);
signedValue = (signedValue < (FIXP_DBL)0) ? -value : value;
ptr[-1] = signedValue;
}
}
}
AAC_DECODER_ERROR CBlock_InverseQuantizeSpectralData(CAacDecoderChannelInfo *pAacDecoderChannelInfo, SamplingRateInfo *pSamplingRateInfo)
{
int window, group, groupwin, band;
int ScaleFactorBandsTransmitted = GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
UCHAR *RESTRICT pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
SHORT *RESTRICT pSfbScale = pAacDecoderChannelInfo->pDynData->aSfbScale;
SHORT *RESTRICT pScaleFactor = pAacDecoderChannelInfo->pDynData->aScaleFactor;
const SHORT *RESTRICT BandOffsets = GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
FDKmemclear(pAacDecoderChannelInfo->pDynData->aSfbScale, (8*16)*sizeof(SHORT));
for (window=0, group=0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)
{
for (groupwin=0; groupwin < GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo,group); groupwin++, window++)
{
/* inverse quantization */
for (band=0; band < ScaleFactorBandsTransmitted; band++)
{
FIXP_DBL *pSpectralCoefficient = SPEC(pAacDecoderChannelInfo->pSpectralCoefficient, window, pAacDecoderChannelInfo->granuleLength) + BandOffsets[band];
int noLines = BandOffsets[band+1] - BandOffsets[band];
int bnds = group*16+band;
int i;
if ((pCodeBook[bnds] == ZERO_HCB)
|| (pCodeBook[bnds] == INTENSITY_HCB)
|| (pCodeBook[bnds] == INTENSITY_HCB2)
)
continue;
if (pCodeBook[bnds] == NOISE_HCB)
{
/* Leave headroom for PNS values. + 1 because ceil(log2(2^(0.25*3))) = 1,
worst case of additional headroom required because of the scalefactor. */
pSfbScale[window*16+band] = (pScaleFactor [bnds] >> 2) + 1 ;
continue;
}
/* Find max spectral line value of the current sfb */
FIXP_DBL locMax = (FIXP_DBL)0;
for (i = noLines; i-- ; ) {
/* Expensive memory access */
locMax = fMax(fixp_abs(pSpectralCoefficient[i]), locMax);
}
/* Cheap robustness improvement - Do not remove!!! */
if (fixp_abs(locMax) > (FIXP_DBL)MAX_QUANTIZED_VALUE) {
return AAC_DEC_DECODE_FRAME_ERROR;
}
/*
The inverse quantized spectral lines are defined by:
pSpectralCoefficient[i] = Sign(pSpectralCoefficient[i]) * 2^(0.25*pScaleFactor[bnds]) * pSpectralCoefficient[i]^(4/3)
This is equivalent to:
pSpectralCoefficient[i] = Sign(pSpectralCoefficient[i]) * (2^(pScaleFactor[bnds] % 4) * pSpectralCoefficient[i]^(4/3))
pSpectralCoefficient_e[i] += pScaleFactor[bnds]/4
*/
{
int msb = pScaleFactor [bnds] >> 2 ;
int lsb = pScaleFactor [bnds] & 0x03 ;
int scale = GetScaleFromValue(locMax, lsb);
pSfbScale[window*16+band] = msb - scale;
InverseQuantizeBand(pSpectralCoefficient, noLines, lsb, scale);
}
}
}
}
return AAC_DEC_OK;
}
AAC_DECODER_ERROR CBlock_ReadSpectralData(HANDLE_FDK_BITSTREAM bs,
CAacDecoderChannelInfo *pAacDecoderChannelInfo,
const SamplingRateInfo *pSamplingRateInfo,
const UINT flags)
{
int i,index;
int window,group,groupwin,groupoffset,band;
UCHAR *RESTRICT pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
const SHORT *RESTRICT BandOffsets = GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
SPECTRAL_PTR pSpectralCoefficient = pAacDecoderChannelInfo->pSpectralCoefficient;
FIXP_DBL locMax;
int ScaleFactorBandsTransmitted = GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
FDK_ASSERT(BandOffsets != NULL);
FDKmemclear(pSpectralCoefficient, sizeof(SPECTRUM));
if ( (flags & AC_ER_HCR) == 0 )
{
groupoffset = 0;
/* plain huffman decoder short */
for (group=0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)
{
for (band=0; band < ScaleFactorBandsTransmitted; band++)
{
int bnds = group*16+band;
UCHAR currentCB = pCodeBook[bnds];
/* patch to run plain-huffman-decoder with vcb11 input codebooks (LAV-checking might be possible below using the virtual cb and a LAV-table) */
if ((currentCB >= 16) && (currentCB <= 31)) {
pCodeBook[bnds] = currentCB = 11;
}
if ( !((currentCB == ZERO_HCB)
|| (currentCB == NOISE_HCB)
|| (currentCB == INTENSITY_HCB)
|| (currentCB == INTENSITY_HCB2)) )
{
const CodeBookDescription *hcb = &AACcodeBookDescriptionTable[currentCB];
int step = hcb->Dimension;
int offset = hcb->Offset;
int bits = hcb->numBits;
int mask = (1<<bits)-1;
for (groupwin=0; groupwin < GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo,group); groupwin++)
{
window = groupoffset + groupwin;
FIXP_DBL *mdctSpectrum = SPEC(pSpectralCoefficient, window, pAacDecoderChannelInfo->granuleLength);
locMax = (FIXP_DBL)0 ;
for (index=BandOffsets[band]; index < BandOffsets[band+1]; index+=step)
{
int idx = CBlock_DecodeHuffmanWord(bs,hcb);
for (i=0; i<step; i++) {
FIXP_DBL tmp;
tmp = (FIXP_DBL)((idx & mask)-offset);
idx >>= bits;
if (offset == 0) {
if (tmp != FIXP_DBL(0))
tmp = (FDKreadBits(bs,1))? -tmp : tmp;
}
mdctSpectrum[index+i] = tmp;
}
if (currentCB == ESCBOOK)
{
mdctSpectrum[index+0] = (FIXP_DBL)CBlock_GetEscape(bs, (LONG)mdctSpectrum[index+0]);
mdctSpectrum[index+1] = (FIXP_DBL)CBlock_GetEscape(bs, (LONG)mdctSpectrum[index+1]);
}
}
}
}
}
groupoffset += GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo,group);
}
/* plain huffman decoding (short) finished */
}
/* HCR - Huffman Codeword Reordering short */
else /* if ( flags & AC_ER_HCR ) */
{
H_HCR_INFO hHcr = &pAacDecoderChannelInfo->pComData->overlay.aac.erHcrInfo;
int hcrStatus = 0;
/* advanced Huffman decoding starts here (HCR decoding :) */
if ( pAacDecoderChannelInfo->pDynData->specificTo.aac.lenOfReorderedSpectralData != 0 ) {
/* HCR initialization short */
hcrStatus = HcrInit(hHcr, pAacDecoderChannelInfo, pSamplingRateInfo, bs);
if (hcrStatus != 0) {
return AAC_DEC_DECODE_FRAME_ERROR;
}
/* HCR decoding short */
hcrStatus = HcrDecoder(hHcr, pAacDecoderChannelInfo, pSamplingRateInfo, bs);
if (hcrStatus != 0) {
#if HCR_ERROR_CONCEALMENT
HcrMuteErroneousLines(hHcr);
#else
return AAC_DEC_DECODE_FRAME_ERROR;
#endif /* HCR_ERROR_CONCEALMENT */
}
FDKpushFor (bs, pAacDecoderChannelInfo->pDynData->specificTo.aac.lenOfReorderedSpectralData);
}
}
/* HCR - Huffman Codeword Reordering short finished */
if ( IsLongBlock(&pAacDecoderChannelInfo->icsInfo) && !(flags & (AC_ELD|AC_SCALABLE)) )
{
/* apply pulse data */
CPulseData_Apply(&pAacDecoderChannelInfo->pDynData->specificTo.aac.PulseData,
GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo),
SPEC_LONG(pSpectralCoefficient));
}
return AAC_DEC_OK;
}
void ApplyTools ( CAacDecoderChannelInfo *pAacDecoderChannelInfo[],
const SamplingRateInfo *pSamplingRateInfo,
const UINT flags,
const int channel )
{
if ( !(flags & (AC_USAC|AC_RSVD50|AC_MPS_RES)) ) {
CPns_Apply(
&pAacDecoderChannelInfo[channel]->data.aac.PnsData,
&pAacDecoderChannelInfo[channel]->icsInfo,
pAacDecoderChannelInfo[channel]->pSpectralCoefficient,
pAacDecoderChannelInfo[channel]->specScale,
pAacDecoderChannelInfo[channel]->pDynData->aScaleFactor,
pSamplingRateInfo,
pAacDecoderChannelInfo[channel]->granuleLength,
channel
);
}
CTns_Apply (
&pAacDecoderChannelInfo[channel]->pDynData->TnsData,
&pAacDecoderChannelInfo[channel]->icsInfo,
pAacDecoderChannelInfo[channel]->pSpectralCoefficient,
pSamplingRateInfo,
pAacDecoderChannelInfo[channel]->granuleLength
);
}
static
int getWindow2Nr(int length, int shape)
{
int nr = 0;
if (shape == 2) {
/* Low Overlap, 3/4 zeroed */
nr = (length * 3)>>2;
}
return nr;
}
void CBlock_FrequencyToTime(CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
CAacDecoderChannelInfo *pAacDecoderChannelInfo,
INT_PCM outSamples[],
const SHORT frameLen,
const int stride,
const int frameOk,
FIXP_DBL *pWorkBuffer1 )
{
int fr, fl, tl, nSamples, nSpec;
/* Determine left slope length (fl), right slope length (fr) and transform length (tl).
USAC: The slope length may mismatch with the previous frame in case of LPD / FD
transitions. The adjustment is handled by the imdct implementation.
*/
tl = frameLen;
nSpec = 1;
switch( pAacDecoderChannelInfo->icsInfo.WindowSequence ) {
default:
case OnlyLongSequence:
fl = frameLen;
fr = frameLen - getWindow2Nr(frameLen, GetWindowShape(&pAacDecoderChannelInfo->icsInfo));
break;
case LongStopSequence:
fl = frameLen >> 3;
fr = frameLen;
break;
case LongStartSequence: /* or StopStartSequence */
fl = frameLen;
fr = frameLen >> 3;
break;
case EightShortSequence:
fl = fr = frameLen >> 3;
tl >>= 3;
nSpec = 8;
break;
}
{
int i;
{
FIXP_DBL *tmp = pAacDecoderChannelInfo->pComData->workBufferCore1->mdctOutTemp;
nSamples = imdct_block(
&pAacDecoderStaticChannelInfo->IMdct,
tmp,
SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
pAacDecoderChannelInfo->specScale,
nSpec,
frameLen,
tl,
FDKgetWindowSlope(fl, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
fl,
FDKgetWindowSlope(fr, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
fr,
(FIXP_DBL)0 );
for (i=0; i<frameLen; i++) {
outSamples[i*stride] = IMDCT_SCALE(tmp[i]);
}
}
}
FDK_ASSERT(nSamples == frameLen);
}
#include "ldfiltbank.h"
void CBlock_FrequencyToTimeLowDelay( CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
CAacDecoderChannelInfo *pAacDecoderChannelInfo,
INT_PCM outSamples[],
const short frameLen,
const char stride )
{
InvMdctTransformLowDelay_fdk (
SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
pAacDecoderChannelInfo->specScale[0],
outSamples,
pAacDecoderStaticChannelInfo->pOverlapBuffer,
stride,
frameLen
);
}
| alesaccoia/asutilities | thirdparty/fdk-aac/libAACdec/src/block.cpp | C++ | mit | 26,810 |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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.
#
__revision__ = "test/scons-time/mem/stage.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Verify the mem --stage option.
"""
import TestSCons_time
test = TestSCons_time.TestSCons_time()
test.fake_logfile('foo-000-0.log', 0)
test.fake_logfile('foo-000-1.log', 0)
test.fake_logfile('foo-000-2.log', 0)
test.fake_logfile('foo-001-0.log', 1)
test.fake_logfile('foo-001-1.log', 1)
test.fake_logfile('foo-001-2.log', 1)
expect = """\
set key bottom left
plot '-' title "Startup" with lines lt 1, \\
'-' title "Full build" with lines lt 2, \\
'-' title "Up-to-date build" with lines lt 3
# Startup
0 %(index)s000.000
1 %(index)s001.000
e
# Full build
0 %(index)s000.000
1 %(index)s001.000
e
# Up-to-date build
0 %(index)s000.000
1 %(index)s001.000
e
"""
pre_read = expect % {'index' : 1}
post_read = expect % {'index' : 2}
pre_build = expect % {'index' : 3}
post_build = expect % {'index' : 4}
test.run(arguments = 'mem --fmt gnuplot --stage pre-read', stdout=pre_read)
test.run(arguments = 'mem --fmt gnuplot --stage=post-read', stdout=post_read)
test.run(arguments = 'mem --fmt gnuplot --stage=pre-build', stdout=pre_build)
test.run(arguments = 'mem --fmt gnuplot --stage post-build', stdout=post_build)
expect = """\
scons-time: mem: Unrecognized stage "unknown".
"""
test.run(arguments = 'mem --fmt gnuplot --stage unknown',
status = 1,
stderr = expect)
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| EmanueleCannizzaro/scons | test/scons-time/mem/stage.py | Python | mit | 2,679 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("2.NotDevisableBy3And7")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2.NotDevisableBy3And7")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c16e57d6-a31c-4fe2-b9dd-ed34c911610e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Ico093/TelerikAcademy | C#1/Homework/6.Loops/6.Loops/2.NotDevisableBy3And7/Properties/AssemblyInfo.cs | C# | mit | 1,418 |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Diagnostics.Runtime.Utilities;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.Diagnostics.Runtime.Interop;
namespace Microsoft.Diagnostics.Runtime.Tests
{
public static class Helpers
{
public static ClrMethod GetMethod(this ClrType type, string name)
{
return GetMethods(type, name).Single();
}
public static IEnumerable<ClrMethod> GetMethods(this ClrType type, string name)
{
return type.Methods.Where(m => m.Name == name);
}
public static HashSet<T> Unique<T>(this IEnumerable<T> self)
{
HashSet<T> set = new HashSet<T>();
foreach (T t in self)
set.Add(t);
return set;
}
public static ClrAppDomain GetDomainByName(this ClrRuntime runtime, string domainName)
{
return runtime.AppDomains.Where(ad => ad.Name == domainName).Single();
}
public static ClrModule GetModule(this ClrRuntime runtime, string filename)
{
return (from module in runtime.Modules
let file = Path.GetFileName(module.FileName)
where file.Equals(filename, StringComparison.OrdinalIgnoreCase)
select module).Single();
}
public static ClrThread GetMainThread(this ClrRuntime runtime)
{
ClrThread thread = runtime.Threads.Where(t => !t.IsFinalizer).Single();
return thread;
}
public static ClrStackFrame GetFrame(this ClrThread thread, string functionName)
{
return thread.StackTrace.Where(sf => sf.Method != null ? sf.Method.Name == functionName : false).Single();
}
public static string TestWorkingDirectory { get { return _userSetWorkingPath ?? _workingPath.Value; } set { Debug.Assert(!_workingPath.IsValueCreated); _userSetWorkingPath = value; } }
#region Working Path Helpers
static string _userSetWorkingPath = null;
static Lazy<string> _workingPath = new Lazy<string>(() => CreateWorkingPath(), true);
private static string CreateWorkingPath()
{
Random r = new Random();
string path;
do
{
path = Path.Combine(Environment.CurrentDirectory, TempRoot + r.Next().ToString());
} while (Directory.Exists(path));
Directory.CreateDirectory(path);
return path;
}
internal static readonly string TempRoot = "clrmd_removeme_";
#endregion
}
[TestClass]
public class GlobalCleanup
{
[AssemblyCleanup]
public static void AssemblyCleanup()
{
GC.Collect();
GC.WaitForPendingFinalizers();
foreach (string directory in Directory.GetDirectories(Environment.CurrentDirectory))
if (directory.Contains(Helpers.TempRoot))
Directory.Delete(directory, true);
}
}
} | JeffCyr/clrmd | src/Microsoft.Diagnostics.Runtime.Tests/Helpers.cs | C# | mit | 3,242 |
(function() {
packages = {
// Lazily construct the package hierarchy from class names.
root: function(classes) {
var map = {};
function find(name, data) {
var node = map[name], i;
if (!node) {
node = map[name] = data || {name: name, children: []};
if (name.length) {
node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
node.parent.children.push(node);
//node.key = name.substring(i + 1);
node.key = data.rpiId;
}
}
return node;
}
classes.forEach(function(d) {
find(d.name, d);
});
return map[""];
},
// Return a list of imports for the given array of nodes.
imports: function(nodes) {
var map = {},
imports = [];
// Compute a map from name to node.
nodes.forEach(function(d) {
map[d.name] = d;
});
// For each import, construct a link from the source to target node.
nodes.forEach(function(d) {
if (d.imports) d.imports.forEach(function(i) {
imports.push({source: map[d.name], target: map[i.name], goals: i.goals});
});
});
return imports;
}
};
})(); | gxm/soccer-visuals | web/js-lib/packages.js | JavaScript | mit | 1,109 |
require 'spec_helper'
describe Neoid::Relationship do
let(:user) { User.create!(name: "Elad Ossadon", slug: "elado") }
let(:movie) { Movie.create!(name: "Memento", slug: "memento-1999", year: 1999) }
it "should call neo_save after relationship model creation" do
Like.any_instance.should_receive(:neo_save)
user.like! movie
end
it "should create a neo_relationship for like" do
like = user.like! movie
like = user.likes.last
like.neo_find_by_id.should_not be_nil
like.neo_relationship.should_not be_nil
like.neo_relationship.start_node.should == user.neo_node
like.neo_relationship.end_node.should == movie.neo_node
like.neo_relationship.rel_type.should == 'likes'
end
it "should delete a relationship on deleting a record" do
user.like! movie
like = user.likes.last
relationship_neo_id = like.neo_relationship.neo_id
Neography::Relationship.load(relationship_neo_id).should_not be_nil
user.unlike! movie
expect { Neography::Relationship.load(relationship_neo_id) }.to raise_error(Neography::RelationshipNotFoundException)
end
it "should update neo4j on manual set of a collection" do
movies = [
Movie.create(name: "Memento"),
Movie.create(name: "The Prestige"),
Movie.create(name: "The Dark Knight"),
Movie.create(name: "Spiderman")
]
user.neo_node.outgoing(:likes).length.should == 0
expect {
user.movies = movies
}.to change{ user.neo_node.outgoing(:likes).length }.to(movies.length)
expect { expect {
user.movies -= movies[0..1]
}.to change{ user.movies.count }.by(-2)
}.to change{ user.neo_node.outgoing(:likes).length }.by(-2)
expect {
user.movies = []
}.to change{ user.neo_node.outgoing(:likes).length }.to(0)
expect {
user.movie_ids = movies[0...2].collect(&:id)
}.to change{ user.neo_node.outgoing(:likes).length }.to(2)
end
it "should update a relationship after relationship model update" do
like = user.like! movie
like.neo_relationship.rate.should be_nil
like.rate = 10
like.save!
like.neo_relationship.rate.should == 10
end
context "polymorphic relationship" do
let(:user) { User.create(name: "Elad Ossadon", slug: "elado") }
it "should create relationships with polymorphic items" do
followed = [
User.create(name: "Some One", slug: "someone"),
Movie.create(name: "The Prestige"),
Movie.create(name: "The Dark Knight")
]
expect {
followed.each do |item|
user.user_follows.create!(item: item)
end
}.to change{ user.neo_node.outgoing(:follows).length }.to(followed.length)
expect {
user.user_follows = user.user_follows[0...1]
}.to change{ user.neo_node.outgoing(:follows).length }.to(1)
expect {
user.user_follows = []
}.to change{ user.neo_node.outgoing(:follows).length }.to(0)
end
end
end
| glsignal/neoid | spec/neoid/relationship_spec.rb | Ruby | mit | 2,983 |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _EventRowMixin = require('./EventRowMixin');
var _EventRowMixin2 = _interopRequireDefault(_EventRowMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var EventRow = function (_React$Component) {
_inherits(EventRow, _React$Component);
function EventRow() {
_classCallCheck(this, EventRow);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
EventRow.prototype.render = function render() {
var _this2 = this;
var segments = this.props.segments;
var lastEnd = 1;
return _react2.default.createElement(
'div',
{ className: 'rbc-row' },
segments.reduce(function (row, _ref, li) {
var event = _ref.event,
left = _ref.left,
right = _ref.right,
span = _ref.span;
var key = '_lvl_' + li;
var gap = left - lastEnd;
var content = _EventRowMixin2.default.renderEvent(_this2.props, event);
if (gap) row.push(_EventRowMixin2.default.renderSpan(_this2.props, gap, key + '_gap'));
row.push(_EventRowMixin2.default.renderSpan(_this2.props, span, key, content));
lastEnd = right + 1;
return row;
}, [])
);
};
return EventRow;
}(_react2.default.Component);
EventRow.propTypes = _extends({
segments: _propTypes2.default.array
}, _EventRowMixin2.default.propTypes);
EventRow.defaultProps = _extends({}, _EventRowMixin2.default.defaultProps);
exports.default = EventRow; | aggiedefenders/aggiedefenders.github.io | node_modules/react-big-calendar/lib/EventRow.js | JavaScript | mit | 2,891 |
module.exports = function brify (text) {
return text.replace(/\n/g, '<br/>');
}; | intesso/brify | index.js | JavaScript | mit | 82 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z" /></g>
, 'Keyboard');
| cherniavskii/material-ui | packages/material-ui-icons/src/Keyboard.js | JavaScript | mit | 387 |
import sys
import os
import os.path
from jinja2 import Template
from configparser import ConfigParser
import io
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: <program> <deploy_cfg_template_file> <file_with_properties>")
print("Properties from <file_with_properties> will be applied to <deploy_cfg_template_file>")
print("template which will be overwritten with .orig copy saved in the same folder first.")
sys.exit(1)
file = open(sys.argv[1], 'r')
text = file.read()
t = Template(text)
config = ConfigParser()
if os.path.isfile(sys.argv[2]):
config.read(sys.argv[2])
elif "KBASE_ENDPOINT" in os.environ:
kbase_endpoint = os.environ.get("KBASE_ENDPOINT")
props = "[global]\n" + \
"kbase_endpoint = " + kbase_endpoint + "\n" + \
"job_service_url = " + kbase_endpoint + "/userandjobstate\n" + \
"workspace_url = " + kbase_endpoint + "/ws\n" + \
"shock_url = " + kbase_endpoint + "/shock-api\n" + \
"handle_url = " + kbase_endpoint + "/handle_service\n" + \
"srv_wiz_url = " + kbase_endpoint + "/service_wizard\n" + \
"njsw_url = " + kbase_endpoint + "/njs_wrapper\n"
if "AUTH_SERVICE_URL" in os.environ:
props += "auth_service_url = " + os.environ.get("AUTH_SERVICE_URL") + "\n"
elif "auth2services" in kbase_endpoint:
props += "auth_service_url = " + kbase_endpoint + "/auth/api/legacy/KBase/Sessions/Login\n"
props += "auth_service_url_allow_insecure = " + \
os.environ.get("AUTH_SERVICE_URL_ALLOW_INSECURE", "false") + "\n"
config.readfp(io.StringIO(props))
else:
raise ValueError('Neither ' + sys.argv[2] + ' file nor KBASE_ENDPOINT env-variable found')
props = dict(config.items("global"))
output = t.render(props)
with open(sys.argv[1] + ".orig", 'w') as f:
f.write(text)
with open(sys.argv[1], 'w') as f:
f.write(output)
| briehl/narrative-test | scripts/prepare_deploy_cfg.py | Python | mit | 2,057 |
#include "variant/pwm_platform.hpp"
#include "hal.h"
static const PWMConfig MOTOR_PWM_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
PWMPlatform::PWMPlatform() {
pwmStart(&PWMD1, &MOTOR_PWM_CONFIG);
palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}
void PWMPlatform::set(std::uint8_t ch, float dc) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD1, dc * 10000.0f);
pwmEnableChannel(&PWMD1, ch, width);
}
| OSURoboticsClub/aerial_control | variants/platforms/stm32f4discovery/pwm_platform.cpp | C++ | mit | 844 |
require 'yaml'
$messages = YAML.load_file(File.dirname(__FILE__) + '/messages.yml')
$language = 'en'
public
##
# Translate the given key with the default language
# @param [Symbol|String] key the key
# @return the translated text
def translate(key)
$messages[$language][key.to_s]
end
##
# Set the language to be used
# @param [String] language the language
def set_language(language)
$language = language
end
| thomsmits/markdown-tools | mdc/lib/messages.rb | Ruby | mit | 417 |
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20170318145737 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE page ADD title_en VARCHAR(255) NOT NULL, ADD content_en LONGTEXT NOT NULL, ADD raw TINYINT(1) NOT NULL');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE page DROP title_en, DROP content_en, DROP raw');
}
}
| spopovic14/cedeum_final | app/DoctrineMigrations/Version20170318145737.php | PHP | mit | 1,122 |
var MongoClient = require('mongodb').MongoClient;
/**
* Count the number of talks in the database
*
* @param {string} dburl Database url string.
* @param {function} callback Callback function to execute with results.
*/
function count(dburl, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
return db.collection('talks').count();
});
}
/**
* Generic method for getting Talks.
*
* By default pageNumber is set to 1 if its not specified.
* Also returns 25 elements if quantity is not specified.
*
* @param {string} dburl Database url string.
* @param {object} conds Search and filter conditions.
* @param {object} sort Sorting conditions.
* @param {number} quantity Number of results to fetch.
* @param {number} pageNumber Page number to fetch.
* @param {function} callback Callback function to execute with results.
*/
function searchTalks(dburl, conds, sort, quantity, pageNumber, callback) {
'use strict';
pageNumber = pageNumber || 1;
quantity = quantity || 25;
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks
.find(conds)
.sort(sort)
.skip(pageNumber > 0 ? ((pageNumber - 1) * quantity) : 0)
.limit(quantity)
.toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
}
/**
* Get a Random Talk.
*
* Get a random talk from the collection.
*
* @param {string} dburl Database url string.
* @param {function} callback Callback function to execute with the results.
*/
exports.getRandom = function(dburl, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.count(function(err, count) {
var rand = Math.floor(Math.random() * count) + 1;
talks
.find()
.limit(-1)
.skip(rand)
.limit(1)
.toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
});
};
/**
* Search Talks.
*
* Performs a query search on talks full-text index on elastic-search.
*
* @param {string} index Elastic search connection string.
* @param {string} q Query string to search.
* @param {function} callback Callback function to execute with the results.
*/
exports.search = function(q, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
var results = {};
db.close();
return callback(null, results);
});
};
/**
* Get all the Talks from the database.
*
* @param {string} dburl Database url string.
* @param {function} callback Callback function to execute with results.
*/
exports.all = function(dburl, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks
.find({})
.toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Get the latest Talks.
*
* Latest talks are sorted by its creation date in descendant order.
*
* @param {string} dburl Database url string.
* @param {number} quantity Number of results to get.
* @param {number} pageNumber Page number to get results.
* @param {function} callback Callback function to execute with results.
*/
exports.latest = function(dburl, quantity, pageNumber, callback) {
'use strict';
var conds = {};
var sort = {
created: -1
};
quantity = quantity || 25;
pageNumber = pageNumber || 1;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
/**
* Get the most popular Talks.
*
* Popular talks are sorted in descendant order first by its number of
* votes and then by its number of views.
*
* @param {string} dburl Database url string.
* @param {number} quantity Number of results to get.
* @param {number} pageNumber Page number to get results.
* @param {function} callback Callback function to execute with results.
*/
exports.popular = function(dburl, quantity, pageNumber, callback) {
'use strict';
var conds = {};
var sort = {
voteCount: -1,
viewCount: -1
};
quantity = quantity || 25;
pageNumber = pageNumber || 1;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
/**
* Create a new talk.
*
* Creates a new talk storing it into the database.
*
* @param {string} dburl Database url string.
* @param {number} obj Number of results to get.
* @param {function} callback Callback function to execute with results.
*/
exports.createTalk = function(dburl, obj, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.insert(obj, function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Delete a talk by its id.
*
* Remove a database from the database.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {function} callback Callback function to execute with results.
*/
exports.deleteTalk = function(dburl, id, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.remove({
id: id
}, function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Get a talk by id.
*
* Get a Talk from the database by its unique id.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {function} callback Callbacak function to execute with results.
*/
exports.get = function(dburl, id, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.findOne({
id: id
}, function(err, doc) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, doc);
});
});
};
/**
* Upvote a Talk.
*
* Updates a talk increasing its vote count by 1.
* It checks if the user did not upvoted the talk already and also adds user
* id on a list of upvoters for this talk in case its not present.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {number} userid User's unique id.
* @param {function} callback Callback function to execute with the results.
*/
exports.upvote = function(dburl, id, userid, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.update({
'id': id,
'votes': {
'$ne': userid
}
}, {
'$inc': {
'voteCount': 1
},
'$push': {
'votes': userid
}
}, function(err, talk) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, talk);
});
});
};
/**
* Favorite a Talk.
*
* Updates a talk with increasing its favorites count by 1.
* It checks if the user did not favorited the talk already and also adds user
* id on a list of favoriters for this talk in case its not present.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {number} userid User's unique id.
* @param {function} callback Callback function to execute with the results.
*/
exports.favorite = function(dburl, id, userid, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.update({
'id': id,
'favorites': {
'$ne': userid
}
}, {
'$inc': {
'favoriteCount': 1
},
'$push': {
'favorites': userid
}
}, function(err, talk) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, talk);
});
});
};
/**
* Unfavorite a Talk.
*
* Updates a talk with decreasing its favorites count by 1.
* It checks if the user did favorited the talk already and also removes user
* id on a list of favoriters for this talk.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {number} userid User's unique id.
* @param {function} callback Callback function to execute with the results.
*/
exports.unfavorite = function(dburl, id, userid, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.update({
'id': id,
'favorites': {
'$in': [userid]
}
}, {
'$inc': {
'favoriteCount': -1
},
'$pull': {
'favorites': userid
}
}, function(err, talk) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, talk);
});
});
};
/**
* Rank a Talk.
*
* Updates a talk with its raking score field.
*
* @param {string} dburl Database url string.
* @param {number} id Talk unique id.
* @param {float} score Ranking score.
* @param {function} callback Callback function to execute with the results.
*/
exports.rank = function(dburl, id, score, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.update({
'id': id
}, {
'$set': {
'ranking': score
}
}, function(err) {
if (err) {
return callback(err);
}
db.close();
return callback(null);
});
});
};
/**
* Play a Talk.
*
* Get a Talk by its slug name and updates views counter field by 1.
*
* @param {string} dburl Database url string
* @param {string} slug Talk slug field.
* @param {function} callback Callback function to execute with results.
*/
exports.play = function(dburl, slug, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.findOne({
'slug': slug
}, function(err, talk) {
if (err) {
return callback(err, null);
}
talks.update({
'slug': slug
}, {
'$inc': {
'viewCount': 1
},
'$set': {
updated: Date.now()
}
}, function(err) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, talk);
});
});
});
};
/**
* Get a list of talks tagged as.
*
* Results are sorted by creation date in descending order.
* By default 25 results are returned.
*
* @param {string} dburl Database url string.
* @param {string} tag Tag string.
* @param {number} quantity Number of results to fetch.
* @param {number} pageNumber Number of the page to fetch.
* @param {function} callback Callback function to execute with results.
*/
exports.getByTag = function(dburl, tag, quantity, pageNumber, callback) {
'use strict';
var conds = {
tags: tag
};
var sort = {
created: -1
};
quantity = quantity || 25;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
/**
* Get a Talk by slug.
*
* Get a Talk by its generated slug field.
* http://en.wikipedia.org/wiki/Semantic_URL#Slug
*
* @param {string} dburl Database url string.
* @param {string} slug Slug string.
* @param {function} callback Callback function to execute with results.
*/
exports.getBySlug = function(dburl, slug, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.find({
'slug': slug
}).toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Get a Talk by code.
*
* Get a Talk by its field code .
*
* @param {string} dburl Database url string.
* @param {string} code Code string.
* @param {function} callback Callback function to execute with results.
*/
exports.getByCode = function(dburl, code, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks.find({
'code': code
}).toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Get related Talks to another Talk.
*
* Related Talks are tagged with at least one of the tags of the
* original one.
* Results are sorted by creation date in descendant order.
* Also the original Talk is descarted so a Talk can't be related to
* itself.
*
* @param {string} dburl Database url string.
* @param {number} id Original Talk id.
* @param {Array} tags List of tag strings.
* @param {number} quantity Number of results to fetch.
* @param {function} callback Callback function to execute with results.
*/
exports.related = function(dburl, id, tags, quantity, callback) {
'use strict';
MongoClient.connect(dburl, function(err, db) {
if (err) {
return callback(err, null);
}
var talks = db.collection('talks');
talks
.find({
'tags': {
'$in': tags
},
'id': {
'$ne': id
}
})
.sort({
'created': -1
})
.limit(quantity)
.toArray(function(err, docs) {
if (err) {
return callback(err, null);
}
db.close();
return callback(null, docs);
});
});
};
/**
* Get a list of Talks published by an User.
*
* Given an userid, get a list of talks published by him.
* Returns the list sorted by creation date, being first element the
* most recent one.
*
* @param {string} dburl Database url string.
* @param {number} userid User unique id.
* @param {number} quantity Number of results to fetch.
* @param {number} pageNumber Number of the page to fetch.
* @param {function} callback Callback function to execute with results.
*/
exports.getByAuthorId = function(dburl, id, quantity, pageNumber, callback) {
'use strict';
var conds = {
'author.id': id
};
var sort = {
created: -1
};
quantity = quantity || 25;
pageNumber = pageNumber || 1;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
/**
* Get a list of Talks upvoted by an User.
*
* Given an userid, get a list fo the Tlks that the User has upvoted.
* Returns the list sorted by creation date, being first element the
* most recent one.
*
* @param {string} dburl Database url string.
* @param {number} userid User unique id.
* @param {function} callback Callback function to execute with results.
*/
exports.getUpvotedByAuthorId = function(
dburl,
userid,
quantity,
pageNumber,
callback) {
'use strict';
var conds = {
'votes': {
'$in': [userid]
}
};
var sort = {
created: -1
};
quantity = quantity || 25;
pageNumber = pageNumber || 1;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
/**
* Get a list of Talks favorited by an User.
*
* Given an userid, get a list of the Talks that the User has favorited.
* Returns the list sorted by creation date, being first element the
* most recent one.
*
* @param {string} dburl Database url connection string.
* @param {number} userid User unique id.
* @param {function} callback Callback function to execute with results.
*/
exports.getFavoritedByAuthorId = function(
dburl,
userid,
quantity,
pageNumber,
callback) {
'use strict';
var conds = {
'favorites': {
'$in': [userid]
}
};
var sort = {
created: -1
};
quantity = quantity || 25;
pageNumber = pageNumber || 1;
return searchTalks(dburl, conds, sort, quantity, pageNumber, callback);
};
| tlksio/libtlks | lib/talk.js | JavaScript | mit | 19,184 |
# frozen_string_literal: true
class ConvertExternalServiceReceiverData < ActiveRecord::Migration[4.2]
def up
ExternalServiceReceiver.find_each do |receiver|
show_url = receiver.response_data
new_data = { show_url: show_url, edit_url: "#{show_url}/take" }
receiver.update_attribute :response_data, new_data.to_json
end
end
def down
ExternalServiceReceiver.find_each do |receiver|
json = receiver.response_data
parsed = JSON.parse json
receiver.update_attribute :response_data, parsed[:show_url]
end
end
end
| tablexi/nucore-open | db/migrate/20140320184445_convert_external_service_receiver_data.rb | Ruby | mit | 570 |
#include "unitinventoryhandler.h"
/*!
* @author kovlev
*/
bool UnitInventoryHandler::matches(UnitType unitType, ItemType itemType) {
switch (unitType) {
case UnitType::FIGHTER:
return (itemType == ItemType::MELEE ||
itemType == ItemType::SHIELD ||
itemType == ItemType::ARMOR ||
itemType == ItemType::JEWELLERY);
break;
case UnitType::ARCHER:
return (itemType == ItemType::BOW ||
itemType == ItemType::ARROW ||
itemType == ItemType::ARMOR ||
itemType == ItemType::JEWELLERY);
break;
case UnitType::MAGE:
return (itemType == ItemType::STAFF ||
itemType == ItemType::MAGICSHIELD ||
itemType == ItemType::CLOAK ||
itemType == ItemType::JEWELLERY);
break;
case UnitType::OTHER:
return false;
break;
}
return false;
}
bool UnitInventoryHandler::hasType(Unit* unit, ItemType itemType) {
for (int i = 0; i < unit->getUnitInventorySize(); i++) {
if (unit->getItem(i) != NULL) {
if (unit->getItem(i)->getItemType() == itemType) {
return true;
}
}
}
return false;
}
| kovleventer/FoD | src/player/unitinventoryhandler.cpp | C++ | mit | 1,049 |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Linq;
using osu.Framework.Caching;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Objects.Drawables;
using OpenTK;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Timing
{
/// <summary>
/// A container that scrolls relative to the current time. Will autosize to the total duration of all contained hit objects along the scrolling axes.
/// </summary>
public abstract class ScrollingContainer : Container<DrawableHitObject>
{
/// <summary>
/// Gets or sets the range of time that is visible by the length of the scrolling axes.
/// </summary>
public readonly BindableDouble VisibleTimeRange = new BindableDouble { Default = 1000 };
/// <summary>
/// The axes through which this <see cref="ScrollingContainer"/> scrolls. This is set by the <see cref="SpeedAdjustmentContainer"/>.
/// </summary>
internal Axes ScrollingAxes;
public override bool RemoveWhenNotAlive => false;
/// <summary>
/// The control point that defines the speed adjustments for this container. This is set by the <see cref="SpeedAdjustmentContainer"/>.
/// </summary>
internal MultiplierControlPoint ControlPoint;
private Cached<double> durationBacking;
/// <summary>
/// Creates a new <see cref="ScrollingContainer"/>.
/// </summary>
protected ScrollingContainer()
{
RelativeSizeAxes = Axes.Both;
RelativePositionAxes = Axes.Both;
}
protected override int Compare(Drawable x, Drawable y)
{
var hX = (DrawableHitObject)x;
var hY = (DrawableHitObject)y;
int result = hY.HitObject.StartTime.CompareTo(hX.HitObject.StartTime);
if (result != 0)
return result;
return base.Compare(y, x);
}
public override void Add(DrawableHitObject drawable)
{
durationBacking.Invalidate();
base.Add(drawable);
}
public override bool Remove(DrawableHitObject drawable)
{
durationBacking.Invalidate();
return base.Remove(drawable);
}
// Todo: This may underestimate the size of the hit object in some cases, but won't be too much of a problem for now
private double computeDuration() => Math.Max(0, Children.Select(c => (c.HitObject as IHasEndTime)?.EndTime ?? c.HitObject.StartTime).DefaultIfEmpty().Max() - ControlPoint.StartTime) + 1000;
/// <summary>
/// An approximate total duration of this scrolling container.
/// </summary>
public double Duration => durationBacking.IsValid ? durationBacking : (durationBacking.Value = computeDuration());
protected override void Update()
{
base.Update();
RelativeChildOffset = new Vector2((ScrollingAxes & Axes.X) > 0 ? (float)ControlPoint.StartTime : 0, (ScrollingAxes & Axes.Y) > 0 ? (float)ControlPoint.StartTime : 0);
// We want our size and position-space along the scrolling axes to span our duration to completely enclose all the hit objects
Size = new Vector2((ScrollingAxes & Axes.X) > 0 ? (float)Duration : Size.X, (ScrollingAxes & Axes.Y) > 0 ? (float)Duration : Size.Y);
// And we need to make sure the hit object's position-space doesn't change due to our resizing
RelativeChildSize = Size;
}
}
}
| Damnae/osu | osu.Game/Rulesets/Timing/ScrollingContainer.cs | C# | mit | 3,838 |
# frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Here we check if the elements of a multi-line array literal are
# aligned.
class AlignArray < Cop
include AutocorrectAlignment
MSG = 'Align the elements of an array literal if they span more ' \
'than one line.'.freeze
def on_array(node)
check_alignment(node.children)
end
end
end
end
end
| mclark/rubocop | lib/rubocop/cop/layout/align_array.rb | Ruby | mit | 456 |
/*
* Copyright (c) 2002-2010 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.graphdb;
/**
* Defines a common API for handling properties on both {@link Node nodes} and
* {@link Relationship relationships}.
* <p>
* Properties are key-value pairs. The keys are always strings. Valid property
* value types are all the Java primitives (<code>int</code>, <code>byte</code>,
* <code>float</code>, etc), <code>java.lang.String</code>s and arrays of
* primitives and Strings.
* <p>
* <b>Please note</b> that Neo4j does NOT accept arbitrary objects as property
* values. {@link #setProperty(String, Object) setProperty()} takes a
* <code>java.lang.Object</code> only to avoid an explosion of overloaded
* <code>setProperty()</code> methods.
*/
public interface PropertyContainer
{
/**
* Returns <code>true</code> if this property container has a property
* accessible through the given key, <code>false</code> otherwise. If key is
* <code>null</code>, this method returns <code>false</code>.
*
* @param key the property key
* @return <code>true</code> if this property container has a property
* accessible through the given key, <code>false</code> otherwise
*/
public boolean hasProperty( String key );
/**
* Returns the property value associated with the given key. The value is of
* one of the valid property types, i.e. a Java primitive, a {@link String
* String} or an array of any of the valid types.
* <p>
* If there's no property associated with <code>key</code> an unchecked
* exception is raised. The idiomatic way to avoid an exception for an
* unknown key and instead get <code>null</code> back is to use a default
* value: {@link #getProperty(String, Object) Object valueOrNull =
* nodeOrRel.getProperty( key, null )}
*
* @param key the property key
* @return the property value associated with the given key
* @throws NotFoundException if there's no property associated with
* <code>key</code>
*/
public Object getProperty( String key );
/**
* Returns the property value associated with the given key, or a default
* value. The value is of one of the valid property types, i.e. a Java
* primitive, a {@link String String} or an array of any of the valid types.
*
* @param key the property key
* @param defaultValue the default value that will be returned if no
* property value was associated with the given key
* @return the property value associated with the given key
*/
public Object getProperty( String key, Object defaultValue );
/**
* Sets the property value for the given key to <code>value</code>. The
* property value must be one of the valid property types, i.e:
* <ul>
* <li><code>boolean</code> or <code>boolean[]</code></li>
* <li><code>byte</code> or <code>byte[]</code></li>
* <li><code>short</code> or <code>short[]</code></li>
* <li><code>int</code> or <code>int[]</code></li>
* <li><code>long</code> or <code>long[]</code></li>
* <li><code>float</code> or <code>float[]</code></li>
* <li><code>double</code> or <code>double[]</code></li>
* <li><code>char</code> or <code>char[]</code></li>
* <li><code>java.lang.String</code> or <code>String[]</code></li>
* </ul>
* <p>
* This means that <code>null</code> is not an accepted property value.
*
* @param key the key with which the new property value will be associated
* @param value the new property value, of one of the valid property types
* @throws IllegalArgumentException if <code>value</code> is of an
* unsupported type (including <code>null</code>)
*/
public void setProperty( String key, Object value );
/**
* Removes the property associated with the given key and returns the old
* value. If there's no property associated with the key, <code>null</code>
* will be returned.
*
* @param key the property key
* @return the property value that used to be associated with the given key
*/
public Object removeProperty( String key );
/**
* Returns all existing property keys, or an empty iterable if this property
* container has no properties.
*
* @return all property keys on this property container
*/
// TODO: figure out concurrency semantics
public Iterable<String> getPropertyKeys();
/**
* Returns all currently valid property values, or an empty iterable if this
* node has no properties. All values are of a supported property type, i.e.
* a Java primitive, a {@link String String} or an array of any of the
* supported types.
* <p>
* <b>Note:</b> This method is deprecated and <i>will</i> be removed in
* future releases. Use a combination of {@link #getPropertyKeys()} and
* {@link #getProperty(String)} to achieve the same result.
*
* @return all property values
* @deprecated in favor of using {@link #getPropertyKeys()} in combination
* with {@link #getProperty(String)}.
*/
// TODO: figure out concurrency semantics
@Deprecated
public Iterable<Object> getPropertyValues();
} | alexmsmartins/GraphDHT | neo4j/kernel-1.0/src/main/java/org/neo4j/graphdb/PropertyContainer.java | Java | mit | 6,071 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem 8. Catalan Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem 8. Catalan Numbers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5385409b-b530-4a64-8c05-76362a41cb6e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| fr0wsTyl/TelerikAcademy-2015 | Telerik - C# 1/HOMEWORK - loops/Problem 8. Catalan Numbers/Properties/AssemblyInfo.cs | C# | mit | 1,428 |
# -*- coding: utf-8 -*-
"""Objects representing WikidataQuery query syntax and API."""
#
# (C) Pywikibot team, 2013
#
# Distributed under the terms of the MIT license.
from __future__ import unicode_literals
import json
import sys
if sys.version_info[0] > 2:
from urllib.parse import quote
basestring = (str, )
else:
from urllib2 import quote
import pickle
import os
import hashlib
import time
import tempfile
import pywikibot
from pywikibot.comms import http
from pywikibot.page import ItemPage, PropertyPage, Claim
from pywikibot import config
def listify(x):
"""
If given a non-list, encapsulate in a single-element list.
@rtype: list
"""
return x if isinstance(x, list) else [x]
class QuerySet():
"""
A QuerySet represents a set of queries or other query sets.
Queries may be joined by operators (AND and OR).
A QuerySet stores this information as a list of Query(Sets) and
a joiner operator to join them all together
"""
def __init__(self, q):
"""
Initialise a query set from a Query or another QuerySet.
@type q: Query or QuerySet
"""
self.qs = [q]
def addJoiner(self, args, joiner):
"""
Add to this QuerySet using the given joiner.
If the given joiner is not the same as we used before in
this QuerySet, nest the current one in parens before joining.
This makes the implicit grouping of the API explicit.
@return: a new query set representing the joining of this one and
the arguments
"""
if len(self.qs) > 1 and joiner != self.joiner:
left = QuerySet(self)
else:
left = self
left.joiner = joiner
for a in listify(args):
left.qs.append(a)
return left
def AND(self, args):
"""
Add the given args (Queries or QuerySets) to the Query set as a logical conjuction (AND).
@type args: Query or QuerySet
"""
return self.addJoiner(args, "AND")
def OR(self, args):
"""
Add the given args (Queries or QuerySets) to the Query set as a logical disjunction (OR).
@type args: Query or QuerySet
"""
return self.addJoiner(args, "OR")
def __str__(self):
"""
Output as an API-ready string.
@rtype: str
"""
def bracketIfQuerySet(q):
if isinstance(q, QuerySet) and q.joiner != self.joiner:
return "(%s)" % q
else:
return str(q)
s = bracketIfQuerySet(self.qs[0])
for q in self.qs[1:]:
s += " %s %s" % (self.joiner, bracketIfQuerySet(q))
return s
def __repr__(self):
return u"QuerySet(%s)" % self
class Query():
"""
A query is a single query for the WikidataQuery API.
For example:
claim[100:60] or link[enwiki]
Construction of a Query can throw a TypeError if you feed it bad
parameters. Exactly what these need to be depends on the Query
"""
def AND(self, ands):
"""
Produce a query set ANDing this query and all the given query/sets.
@type ands: Query or list of Query
"""
return QuerySet(self).addJoiner(ands, "AND")
def OR(self, ors):
"""
Produce a query set ORing this query and all the given query/sets.
@type ors: Query or list of Query
"""
return QuerySet(self).addJoiner(ors, "OR")
def formatItem(self, item):
"""
Default item formatting is string.
This will work for queries, querysets, ints and strings
"""
return str(item)
def formatList(self, l):
"""
Format and comma-join a list.
@type l: list
"""
return ",".join([self.formatItem(x) for x in l])
@staticmethod
def isOrContainsOnlyTypes(items, types):
"""
Either this item is one of the given types, or it is a list of only those types.
@rtype: bool
"""
if isinstance(items, list):
for x in items:
found = False
for typ in listify(types):
if isinstance(x, typ):
found = True
break
if not found:
return False
else:
for typ in listify(types):
found = False
if isinstance(items, typ):
found = True
break
if not found:
return False
return True
def validate(self):
"""
Validate the query parameters.
Default validate result is a pass - subclasses need to implement
this if they want to check their parameters.
@return: True
@rtype: bool
"""
return True
def validateOrRaise(self, msg=None):
if not self.validate():
raise TypeError(msg)
def convertWDType(self, item):
"""
Convert Wikibase items like ItemPage or PropertyPage into integer IDs.
The resulting IDs may be used in query strings.
@param item: A single item. One of ItemPages, PropertyPages, int
or anything that can be fed to int()
@return: the int ID of the item
"""
if isinstance(item, ItemPage) or isinstance(item, PropertyPage):
return item.getID(numeric=True)
else:
return int(item)
def convertWDTypes(self, items):
return [self.convertWDType(x) for x in listify(items)]
def __str__(self):
"""
Generate a query string to be passed to the WDQ API.
Sub-classes must override this method.
@raise NotImplementedError: Always raised by this abstract method
"""
raise NotImplementedError
def __repr__(self):
return u"Query(%s)" % self
class HasClaim(Query):
"""
This is a Query of the form "claim[prop:val]".
It is subclassed by
the other similar forms like noclaim and string
"""
queryType = "claim"
def __init__(self, prop, items=[]):
"""Constructor."""
self.prop = self.convertWDType(prop)
if isinstance(items, Query):
self.items = items
elif isinstance(self, StringClaim):
self.items = listify(items)
else:
self.items = self.convertWDTypes(items)
self.validateOrRaise()
def formatItems(self):
res = ''
if self.items:
res += ":" + ",".join([self.formatItem(x) for x in self.items])
return res
def validate(self):
return self.isOrContainsOnlyTypes(self.items, [int, Query])
def __str__(self):
if isinstance(self.items, list):
return "%s[%s%s]" % (self.queryType, self.prop, self.formatItems())
elif isinstance(self.items, Query):
return "%s[%s:(%s)]" % (self.queryType, self.prop, self.items)
class NoClaim(HasClaim):
"""Query of the form noclaim[PROPERTY]."""
queryType = "noclaim"
class StringClaim(HasClaim):
"""Query of the form string[PROPERTY:"STRING",...]."""
queryType = "string"
def formatItem(self, x):
"""Add quotes around string."""
return '"%s"' % x
def validate(self):
return self.isOrContainsOnlyTypes(self.items, basestring)
class Tree(Query):
"""Query of the form tree[ITEM,...][PROPERTY,...]<PROPERTY,...>."""
queryType = "tree"
def __init__(self, item, forward=[], reverse=[]):
"""
Constructor.
@param item: The root item
@param forward: List of forward properties, can be empty
@param reverse: List of reverse properties, can be empty
"""
# check sensible things coming in, as we lose info once we do
# type conversion
if not self.isOrContainsOnlyTypes(item, [int, ItemPage]):
raise TypeError("The item paramter must contain or be integer IDs "
"or page.ItemPages")
elif (not self.isOrContainsOnlyTypes(forward, [int, PropertyPage]) or
not self.isOrContainsOnlyTypes(reverse, [int, PropertyPage])):
raise TypeError("The forward and reverse parameters must contain "
"or be integer IDs or page.PropertyPages")
self.item = self.convertWDTypes(item)
self.forward = self.convertWDTypes(forward)
self.reverse = self.convertWDTypes(reverse)
self.validateOrRaise()
def validate(self):
return (self.isOrContainsOnlyTypes(self.item, int) and
self.isOrContainsOnlyTypes(self.forward, int) and
self.isOrContainsOnlyTypes(self.reverse, int))
def __str__(self):
return "%s[%s][%s][%s]" % (self.queryType, self.formatList(self.item),
self.formatList(self.forward),
self.formatList(self.reverse))
class Around(Query):
"""A query in the form around[PROPERTY,LATITUDE,LONGITUDE,RADIUS]."""
queryType = "around"
def __init__(self, prop, coord, rad):
"""Constructor."""
self.prop = self.convertWDType(prop)
self.lt = coord.lat
self.lg = coord.lon
self.rad = rad
def validate(self):
return isinstance(self.prop, int)
def __str__(self):
return "%s[%s,%s,%s,%s]" % (self.queryType, self.prop,
self.lt, self.lg, self.rad)
class Between(Query):
"""
A query in the form between[PROP, BEGIN, END].
You have to give prop and one of begin or end. Note that times have
to be in UTC, timezones are not supported by the API
@param prop: the property
@param begin: WbTime object representing the beginning of the period
@param end: WbTime object representing the end of the period
"""
queryType = "between"
def __init__(self, prop, begin=None, end=None):
"""Constructor."""
self.prop = self.convertWDType(prop)
self.begin = begin
self.end = end
def validate(self):
return (self.begin or self.end) and isinstance(self.prop, int)
def __str__(self):
begin = self.begin.toTimestr() if self.begin else ''
# if you don't have an end, you don't put in the comma
end = ',' + self.end.toTimestr() if self.end else ''
return "%s[%s,%s%s]" % (self.queryType, self.prop, begin, end)
class Link(Query):
"""
A query in the form link[LINK,...], which also includes nolink.
All link elements have to be strings, or validation will throw
"""
queryType = "link"
def __init__(self, link):
"""Constructor."""
self.link = listify(link)
self.validateOrRaise()
def validate(self):
return self.isOrContainsOnlyTypes(self.link, basestring)
def __str__(self):
return "%s[%s]" % (self.queryType, self.formatList(self.link))
class NoLink(Link):
"""A query in the form nolink[..]."""
queryType = "nolink"
def fromClaim(claim):
"""
Construct from a pywikibot.page Claim object.
@type claim: L{pywikibot.page.Claim}
@rtype: L{Query}
"""
if not isinstance(claim, Claim):
raise TypeError("claim must be a page.Claim")
if claim.type == 'wikibase-item':
return HasClaim(claim.getID(numeric=True), claim.getTarget().getID(numeric=True))
if claim.type == 'string':
return StringClaim(claim.getID(numeric=True), claim.getTarget())
else:
raise TypeError("Cannot construct a query from a claim of type %s"
% claim.type)
class WikidataQuery():
"""
An interface to the WikidataQuery API.
Default host is
https://wdq.wmflabs.org/, but you can substitute
a different one.
Caching defaults to a subdir of the system temp directory with a
1 hour max cache age.
Set a zero or negative maxCacheAge to disable caching
"""
def __init__(self, host="https://wdq.wmflabs.org", cacheDir=None,
cacheMaxAge=60):
"""Constructor."""
self.host = host
self.cacheMaxAge = cacheMaxAge
if cacheDir:
self.cacheDir = cacheDir
else:
self.cacheDir = os.path.join(tempfile.gettempdir(),
"wikidataquery_cache")
def getUrl(self, queryStr):
return "%s/api?%s" % (self.host, queryStr)
def getQueryString(self, q, labels=[], props=[]):
"""
Get the query string for a given query or queryset.
@return: string including labels and props
"""
qStr = "q=%s" % quote(str(q))
if labels:
qStr += "&labels=%s" % ','.join(labels)
if props:
qStr += "&props=%s" % ','.join(props)
return qStr
def getCacheFilename(self, queryStr):
"""
Encode a query into a unique and universally safe format.
@rtype: unicode
"""
encQuery = hashlib.sha1(queryStr.encode('utf8')).hexdigest() + ".wdq_cache"
return os.path.join(self.cacheDir, encQuery)
def readFromCache(self, queryStr):
"""
Load the query result from the cache, if possible.
@return: None if the data is not there or if it is too old.
"""
if self.cacheMaxAge <= 0:
return None
cacheFile = self.getCacheFilename(queryStr)
if os.path.isfile(cacheFile):
mtime = os.path.getmtime(cacheFile)
now = time.time()
if ((now - mtime) / 60) < self.cacheMaxAge:
with open(cacheFile, 'rb') as f:
try:
data = pickle.load(f)
except pickle.UnpicklingError:
pywikibot.warning(u"Couldn't read cached data from %s"
% cacheFile)
data = None
return data
return None
def saveToCache(self, q, data):
"""
Save data from a query to a cache file, if enabled.
@rtype: None
"""
if self.cacheMaxAge <= 0:
return
# we have to use our own query string, as otherwise we may
# be able to find the cache file again if there are e.g.
# whitespace differences
cacheFile = self.getCacheFilename(q)
if os.path.exists(cacheFile) and not os.path.isfile(cacheFile):
return
if not os.path.exists(self.cacheDir):
os.makedirs(self.cacheDir)
with open(cacheFile, 'wb') as f:
try:
pickle.dump(data, f, protocol=config.pickle_protocol)
except IOError:
pywikibot.warning(u"Failed to write cache file %s" % cacheFile)
def getDataFromHost(self, queryStr):
"""
Go and fetch a query from the host's API.
@rtype: dict
"""
url = self.getUrl(queryStr)
try:
resp = http.fetch(url)
except:
pywikibot.warning(u"Failed to retrieve %s" % url)
raise
try:
data = json.loads(resp.content)
except ValueError:
pywikibot.warning(u"Data received from host but no JSON could be decoded")
raise pywikibot.ServerError("Data received from host but no JSON could be decoded")
return data
def query(self, q, labels=[], props=[]):
"""
Actually run a query over the API.
@return: dict of the interpreted JSON or None on failure
"""
fullQueryString = self.getQueryString(q, labels, props)
# try to get cached data first
data = self.readFromCache(fullQueryString)
if data:
return data
# the cached data must not be OK, go and get real data from the
# host's API
data = self.getDataFromHost(fullQueryString)
# no JSON found
if not data:
return None
# cache data for next time
self.saveToCache(fullQueryString, data)
return data
| hperala/kontuwikibot | pywikibot/data/wikidataquery.py | Python | mit | 16,312 |
#include "FileStream.hpp"
#include <cstring>
namespace warped {
//////////////////////////////// Constructors ///////////////////////////////////////////}
FileStream::FileStream(const std::string& filename, std::ios_base::openmode mode) {
fstream_.open(filename, mode);
}
FileStream::FileStream (FileStream&& x) {
*this = std::move(x);
}
FileStream& FileStream::operator= (FileStream&& rhs) {
if (this == &rhs)
return *this;
*this = std::move(rhs);
return *this;
}
///////////////////////////// fstream operations //////////////////////////////////////////////
void FileStream::open(const char* filename, std::ios_base::openmode mode) {
fstream_.open(filename, mode);
}
void FileStream::open(const std::string& filename, std::ios_base::openmode mode) {
fstream_.open(filename, mode);
}
bool FileStream::is_open() const {
return fstream_.is_open();
}
void FileStream::close() {
fstream_.close();
}
std::filebuf* FileStream::rdbuf() const {
return fstream_.rdbuf();
}
//////////////////////////// Output ////////////////////////////////////////////////////////
FileStream& FileStream::operator<< (bool val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (short val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (unsigned short val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (int val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (unsigned int val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (long val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (unsigned long val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (long long val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (unsigned long long val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (float val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (double val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (long double val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (void* val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (const char * val) {
fstream_ << val;
return *this;
}
FileStream& FileStream::operator<< (std::streambuf* sb) {
fstream_ << sb;
return *this;
}
// FileStream& FileStream::operator<< (FileStream& (*pf)(FileStream&)) {
// *this << pf;
// return *this;
// }
FileStream& FileStream::operator<< (std::ios& (*pf)(std::ios&)) {
fstream_ << pf;
return *this;
}
FileStream& FileStream::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
fstream_ << pf;
return *this;
}
FileStream& FileStream::put(char c) {
fstream_.put(c);
return *this;
}
FileStream& FileStream::write(const char* s, std::streamsize n) {
fstream_.write(s, n);
return *this;
}
//////////////////////////////// Input /////////////////////////////////////////////////
FileStream& FileStream::operator>> (bool& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (short& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (unsigned short & val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (int& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (unsigned int& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (long& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (unsigned long& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (float& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (double& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (long double& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::FileStream::operator>> (void*& val) {
fstream_ >> val;
return *this;
}
FileStream& FileStream::operator>> (std::streambuf* sb) {
fstream_ >> sb;
return *this;
}
// FileStream& FileStream::operator>> (FileStream& (*pf)(FileStream)) {
// *this >> pf;
// return *this;
// }
FileStream& FileStream::operator>> (std::ios& (*pf)(std::ios&)) {
fstream_ >> pf;
return *this;
}
FileStream& FileStream::operator>> (std::ios_base& (*pf)(std::ios_base&)) {
fstream_ >> pf;
return *this;
}
std::streamsize FileStream::gcount() const {
return fstream_.gcount();
}
int FileStream::get() {
return fstream_.get();
}
FileStream& FileStream::get (char& c) {
fstream_.get(c);
return *this;
}
FileStream& FileStream::get (char* s, std::streamsize n) {
fstream_.get(s, n);
return *this;
}
FileStream& FileStream::get (char* s, std::streamsize n, char delim) {
fstream_.get(s, n, delim);
return *this;
}
FileStream& FileStream::get (std::streambuf& sb) {
fstream_.get(sb);
return *this;
}
FileStream& FileStream::get (std::streambuf& sb, char delim) {
fstream_.get(sb, delim);
return *this;
}
FileStream& FileStream::getline (char* s, std::streamsize n ) {
fstream_.getline(s, n);
return *this;
}
FileStream& FileStream::getline (char* s, std::streamsize n, char delim ) {
fstream_.getline(s, n, delim);
return *this;
}
FileStream& FileStream::ignore (std::streamsize n, int delim) {
fstream_.ignore(n, delim);
return *this;
}
int FileStream::peek() {
return fstream_.peek();
}
FileStream& FileStream::read (char* s, std::streamsize n) {
fstream_.read(s, n);
return *this;
}
std::streamsize FileStream::readsome (char* s, std::streamsize n) {
return fstream_.readsome(s, n);
}
FileStream& FileStream::putback (char c) {
fstream_.putback(c);
return *this;
}
FileStream& FileStream::unget() {
fstream_.unget();
return *this;
}
std::streampos FileStream::tellg() {
return fstream_.tellg();
}
FileStream& FileStream::seekg (std::streampos pos) {
fstream_.seekg(pos);
return *this;
}
FileStream& FileStream::seekg (std::streamoff off, std::ios_base::seekdir way) {
fstream_.seekg(off, way);
return *this;
}
int FileStream::sync() {
return fstream_.sync();
}
} // namespace warped
| wilseypa/warped2 | src/FileStream.cpp | C++ | mit | 6,479 |
<div class="alert alert-danger">
<?php echo $errorName; ?>
</div> | Mcfloy/Intranet | views/global/error.php | PHP | mit | 66 |
//= require "prism.js"
//= require "jquery/dist/jquery.min.js"
//= require "ga.js"
| nakanishy/blog.nakanishy.com | source/javascripts/all.js | JavaScript | mit | 83 |
#include "transactionview.h"
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "bitcoinunits.h"
#include "csvmodelwriter.h"
#include "transactiondescdialog.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QScrollBar>
#include <QComboBox>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QMessageBox>
#include <QPoint>
#include <QMenu>
#include <QApplication>
#include <QClipboard>
#include <QLabel>
#include <QDateTimeEdit>
TransactionView::TransactionView(QWidget *parent) :
QWidget(parent), model(0), transactionProxyModel(0),
transactionView(0)
{
// Build filter row
setContentsMargins(0,0,0,0);
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(0,0,0,0);
#ifdef Q_OS_MAC
hlayout->setSpacing(5);
hlayout->addSpacing(26);
#else
hlayout->setSpacing(0);
hlayout->addSpacing(23);
#endif
dateWidget = new QComboBox(this);
#ifdef Q_OS_MAC
dateWidget->setFixedWidth(121);
#else
dateWidget->setFixedWidth(120);
#endif
dateWidget->addItem(tr("All"), All);
dateWidget->addItem(tr("Today"), Today);
dateWidget->addItem(tr("This week"), ThisWeek);
dateWidget->addItem(tr("This month"), ThisMonth);
dateWidget->addItem(tr("Last month"), LastMonth);
dateWidget->addItem(tr("This year"), ThisYear);
dateWidget->addItem(tr("Range..."), Range);
hlayout->addWidget(dateWidget);
typeWidget = new QComboBox(this);
#ifdef Q_OS_MAC
typeWidget->setFixedWidth(121);
#else
typeWidget->setFixedWidth(120);
#endif
typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
typeWidget->addItem(tr("Forged"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
hlayout->addWidget(typeWidget);
addressWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
addressWidget->setPlaceholderText(tr("Enter address or label to search"));
#endif
hlayout->addWidget(addressWidget);
amountWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
amountWidget->setPlaceholderText(tr("Min amount"));
#endif
#ifdef Q_OS_MAC
amountWidget->setFixedWidth(97);
#else
amountWidget->setFixedWidth(100);
#endif
amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
hlayout->addWidget(amountWidget);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(0,0,0,0);
vlayout->setSpacing(0);
QTableView *view = new QTableView(this);
vlayout->addLayout(hlayout);
vlayout->addWidget(createDateRangeWidget());
vlayout->addWidget(view);
vlayout->setSpacing(0);
int width = view->verticalScrollBar()->sizeHint().width();
// Cover scroll bar width with spacing
#ifdef Q_OS_MAC
hlayout->addSpacing(width+2);
#else
hlayout->addSpacing(width);
#endif
// Always show scroll bar
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->setTabKeyNavigation(false);
view->setContextMenuPolicy(Qt::CustomContextMenu);
transactionView = view;
// Actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this);
QAction *editLabelAction = new QAction(tr("Edit label"), this);
QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTxIDAction);
contextMenu->addAction(editLabelAction);
contextMenu->addAction(showDetailsAction);
// Connect actions
connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));
connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
}
void TransactionView::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
transactionProxyModel = new TransactionFilterProxy(this);
transactionProxyModel->setSourceModel(model->getTransactionTableModel());
transactionProxyModel->setDynamicSortFilter(true);
transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
transactionProxyModel->setSortRole(Qt::EditRole);
transactionView->setModel(transactionProxyModel);
transactionView->setAlternatingRowColors(true);
transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
transactionView->setSortingEnabled(true);
transactionView->sortByColumn(TransactionTableModel::Date, Qt::DescendingOrder);
transactionView->verticalHeader()->hide();
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Status, 23);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Date, 120);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Type, 120);
transactionView->horizontalHeader()->setResizeMode(
TransactionTableModel::ToAddress, QHeaderView::Stretch);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Amount, 100);
}
}
void TransactionView::chooseDate(int idx)
{
if(!transactionProxyModel)
return;
QDate current = QDate::currentDate();
dateRangeWidget->setVisible(false);
switch(dateWidget->itemData(idx).toInt())
{
case All:
transactionProxyModel->setDateRange(
TransactionFilterProxy::MIN_DATE,
TransactionFilterProxy::MAX_DATE);
break;
case Today:
transactionProxyModel->setDateRange(
QDateTime(current),
TransactionFilterProxy::MAX_DATE);
break;
case ThisWeek: {
// Find last Monday
QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
transactionProxyModel->setDateRange(
QDateTime(startOfWeek),
TransactionFilterProxy::MAX_DATE);
} break;
case ThisMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month(), 1)),
TransactionFilterProxy::MAX_DATE);
break;
case LastMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month()-1, 1)),
QDateTime(QDate(current.year(), current.month(), 1)));
break;
case ThisYear:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), 1, 1)),
TransactionFilterProxy::MAX_DATE);
break;
case Range:
dateRangeWidget->setVisible(true);
dateRangeChanged();
break;
}
}
void TransactionView::chooseType(int idx)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setTypeFilter(
typeWidget->itemData(idx).toInt());
}
void TransactionView::changedPrefix(const QString &prefix)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setAddressPrefix(prefix);
}
void TransactionView::changedAmount(const QString &amount)
{
if(!transactionProxyModel)
return;
qint64 amount_parsed = 0;
if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
{
transactionProxyModel->setMinAmount(amount_parsed);
}
else
{
transactionProxyModel->setMinAmount(0);
}
}
void TransactionView::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Transaction Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(transactionProxyModel);
writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void TransactionView::contextualMenu(const QPoint &point)
{
QModelIndex index = transactionView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void TransactionView::copyAddress()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
}
void TransactionView::copyLabel()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
}
void TransactionView::copyAmount()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
}
void TransactionView::copyTxID()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole);
}
void TransactionView::editLabel()
{
if(!transactionView->selectionModel() ||!model)
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
AddressTableModel *addressBook = model->getAddressTableModel();
if(!addressBook)
return;
QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
if(address.isEmpty())
{
// If this transaction has no associated address, exit
return;
}
// Is address in address book? Address book can miss address when a transaction is
// sent from outside the UI.
int idx = addressBook->lookupAddress(address);
if(idx != -1)
{
// Edit sending / receiving address
QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
// Determine type of address, launch appropriate editor dialog type
QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
EditAddressDialog dlg(type==AddressTableModel::Receive
? EditAddressDialog::EditReceivingAddress
: EditAddressDialog::EditSendingAddress,
this);
dlg.setModel(addressBook);
dlg.loadRow(idx);
dlg.exec();
}
else
{
// Add sending address
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
this);
dlg.setModel(addressBook);
dlg.setAddress(address);
dlg.exec();
}
}
}
void TransactionView::showDetails()
{
if(!transactionView->selectionModel())
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
TransactionDescDialog dlg(selection.at(0));
dlg.exec();
}
}
QWidget *TransactionView::createDateRangeWidget()
{
dateRangeWidget = new QFrame();
dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
dateRangeWidget->setContentsMargins(1,1,1,1);
QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
layout->setContentsMargins(0,0,0,0);
layout->addSpacing(23);
layout->addWidget(new QLabel(tr("Range:")));
dateFrom = new QDateTimeEdit(this);
dateFrom->setDisplayFormat("dd/MM/yy");
dateFrom->setCalendarPopup(true);
dateFrom->setMinimumWidth(100);
dateFrom->setDate(QDate::currentDate().addDays(-7));
layout->addWidget(dateFrom);
layout->addWidget(new QLabel(tr("to")));
dateTo = new QDateTimeEdit(this);
dateTo->setDisplayFormat("dd/MM/yy");
dateTo->setCalendarPopup(true);
dateTo->setMinimumWidth(100);
dateTo->setDate(QDate::currentDate());
layout->addWidget(dateTo);
layout->addStretch();
// Hide by default
dateRangeWidget->setVisible(false);
// Notify on change
connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
return dateRangeWidget;
}
void TransactionView::dateRangeChanged()
{
if(!transactionProxyModel)
return;
transactionProxyModel->setDateRange(
QDateTime(dateFrom->date()),
QDateTime(dateTo->date()).addDays(1));
}
void TransactionView::focusTransaction(const QModelIndex &idx)
{
if(!transactionProxyModel)
return;
QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);
transactionView->scrollTo(targetIdx);
transactionView->setCurrentIndex(targetIdx);
transactionView->setFocus();
}
| techcoincommunity/firecoin | src/qt/transactionview.cpp | C++ | mit | 15,306 |
<?php
/**
* User: Dre
* Date: 27-1-2016
* Time: 11:55
*/
namespace CF\DataStruct\Join;
abstract class DataStructJoin {
const TYPE_OBJECT = 'object';
const TYPE_EXTENSION = 'extension';
const ORDER_ONE_TO_MANY = 'oneToMany';
const ORDER_ONE_TO_ONE = 'oneToOne';
const STRUCTURE_INNER = 'inner';
const STRUCTURE_LEFT = 'left';
const ONE = 'one';
const MANY = 'many';
/**
* @var array(<localFieldName> => <foreignFieldName>, ...)
*/
protected $foreignKey;
/**
* @var string You can assign an identifier to a join, so you can retreive it with DataStructManager::getJoinByIdentifier
*/
protected $identifier;
/**
* Geeft terug of de join uit aparte objecten bestaat (object), of dat deze in velden in de datastruct zitten(extension)
* @return string <object/extension>
*/
abstract public function getJoinType();
/**
* Geeft terug of de join een 1-1 of 1-n is
* @return DataStructJoin::ORDER...
*/
abstract public function getJoinOrder();
public function setForeignKey(array $keys) {
$this->foreignKey = $keys;
return $this;
}
/**
* Geeft de foreign keys terug
* @return array(<localFieldName> => <foreignFieldName>, ...)
*/
public function getForeignKey() {
return $this->foreignKey;
}
public function getJoinStructure() {
return DataStructJoin::STRUCTURE_INNER;
}
/**
* @return string
*/
public function getIdentifier() {
return $this->identifier;
}
/**
* @param string $identifier
* @return DataStructJoin
*/
public function setIdentifier($identifier) {
$this->identifier = $identifier;
return $this;
}
} | ConscriboOS/CF | src/DataStruct/Join/DataStructJoin.php | PHP | mit | 1,690 |
/*
Written by John MacCallum, The Center for New Music and Audio Technologies,
University of California, Berkeley. Copyright (c) 2009, The Regents of
the University of California (Regents).
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, this paragraph and the following two paragraphs appear in all copies,
modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include <osc/OscPatternMatching.h>
#include <string.h>
/**
* Switch this off to disable matching against a pattern with 2 stars
*/
//#define OSC_MATCH_ENABLE_2STARS 1
/**
* Switch this off to disable matching against a pattern with more than 2 stars which will
* be done recursively.
*/
//#define OSC_MATCH_ENABLE_NSTARS 1
static int osc_match_star(const char *pattern, const char *address);
#if (OSC_MATCH_ENABLE_NSTARS == 1)
static int osc_match_star_r(const char *pattern, const char *address);
#endif
static int osc_match_single_char(const char *pattern, const char *address);
static int osc_match_bracket(const char *pattern, const char *address);
static int osc_match_curly_brace(const char *pattern, const char *address);
int OSCPatternMatching::osc_match(const char *pattern, const char *address, int *pattern_offset, int *address_offset)
{
if(!strcmp(pattern, address))
{
*pattern_offset = (int)strlen(pattern);
*address_offset = (int)strlen(address);
return OSC_MATCH_ADDRESS_COMPLETE | OSC_MATCH_PATTERN_COMPLETE;
}
const char *pattern_start;
const char *address_start;
pattern_start = pattern;
address_start = address;
*pattern_offset = 0;
*address_offset = 0;
while(*address != '\0' && *pattern != '\0')
{
if(*pattern == '*')
{
if(!osc_match_star(pattern, address))
{
return 0;
}
while(*pattern != '/' && *pattern != '\0')
{
pattern++;
}
while(*address != '/' && *address != '\0')
{
address++;
}
}
else if(*address == '*')
{
while(*pattern != '/' && *pattern != '\0')
{
pattern++;
}
while(*address != '/' && *address != '\0')
{
address++;
}
}
else
{
int n = 0;
if(!(n = osc_match_single_char(pattern, address)))
{
return 0;
}
if(*pattern == '[')
{
while(*pattern != ']')
{
pattern++;
}
pattern++;
address++;
}
else if(*pattern == '{')
{
while(*pattern != '}')
{
pattern++;
}
pattern++;
address += n;
}
else
{
pattern++;
address++;
}
}
}
*pattern_offset = pattern - pattern_start;
*address_offset = address - address_start;
int r = 0;
if(*address == '\0')
{
r |= OSC_MATCH_ADDRESS_COMPLETE;
}
if(*pattern == '\0')
{
r |= OSC_MATCH_PATTERN_COMPLETE;
}
return r;
}
static int osc_match_star(const char *pattern, const char *address)
{
#if (OSC_MATCH_ENABLE_2STARS == 1)
const char *address_start = address;
const char *pattern_start = pattern;
#endif
int num_stars = 0;
if(*address == '\0')
{
return 0;
}
while(*address != '/' && *address != '\0')
{
address++;
}
while(*pattern != '/' && *pattern != '\0')
{
if(*pattern == '*')
{
num_stars++;
}
pattern++;
}
pattern--;
address--;
switch(num_stars)
{
case 1:
{
const char *pp = pattern, *aa = address;
while(*pp != '*')
{
if(!(osc_match_single_char(pp, aa)))
{
return 0;
}
if(*pp == ']' || *pp == '}'){
while(*pp != '[' && *pp != '{')
{
pp--;
}
}
pp--;
aa--;
}
}
break;
case 2:
#if (OSC_MATCH_ENABLE_2STARS == 1)
{
const char *pp = pattern, *aa = address;
while(*pp != '*')
{
if(!(osc_match_single_char(pp, aa)))
{
return 0;
}
if(*pp == ']' || *pp == '}')
{
while(*pp != '[' && *pp != '{')
{
pp--;
}
}
pp--;
aa--;
}
aa++; // we want to start one character forward to allow the star to match nothing
const char *star2 = pp;
const char *test = aa;
int i = 0;
while(test > address_start)
{
pp = star2 - 1;
aa = test - 1;
i++;
while(*pp != '*')
{
if(!osc_match_single_char(pp, aa))
{
break;
}
if(*pp == ']' || *pp == '}')
{
while(*pp != '[' && *pp != '{')
{
pp--;
}
}
pp--;
aa--;
}
if(pp == pattern_start)
{
return 1;
}
test--;
}
return 0;
}
break;
#else
return 0;
#endif
default:
#if (OSC_MATCH_ENABLE_NSTARS == 1)
return osc_match_star_r(pattern_start, address_start);
break;
#else
return 0;
#endif
}
return 1;
}
#if (OSC_MATCH_ENABLE_NSTARS == 1)
static int osc_match_star_r(const char *pattern, const char *address)
{
if(*address == '/' || *address == '\0')
{
if(*pattern == '/' || *pattern == '\0' || (*pattern == '*' && ((*(pattern + 1) == '/') || *(pattern + 1) == '\0')))
{
return 1;
}
else
{
return 0;
}
}
if(*pattern == '*')
{
if(osc_match_star_r(pattern + 1, address))
{
return 1;
}
else
{
return osc_match_star_r(pattern, address + 1);
}
}
else
{
if(!osc_match_single_char(pattern, address))
{
return 0;
}
if(*pattern == '[' || *pattern == '{')
{
while(*pattern != ']' && *pattern != '}')
{
pattern++;
}
}
return osc_match_star_r(pattern + 1, address + 1);
}
}
#endif
static int osc_match_single_char(const char *pattern, const char *address)
{
switch(*pattern)
{
case '[':
return osc_match_bracket(pattern, address);
case ']':
while(*pattern != '[')
{
pattern--;
}
return osc_match_bracket(pattern, address);
case '{':
return osc_match_curly_brace(pattern, address);
case '}':
while(*pattern != '{')
{
pattern--;
}
return osc_match_curly_brace(pattern, address);
case '?':
return 1;
default:
if(*pattern == *address)
{
return 1;
}
else
{
return 0;
}
}
return 0;
}
static int osc_match_bracket(const char *pattern, const char *address)
{
pattern++;
int val = 1;
if(*pattern == '!')
{
pattern++;
val = 0;
}
int matched = !val;
while(*pattern != ']' && *pattern != '\0')
{
// the character we're on now is the beginning of a range
if(*(pattern + 1) == '-')
{
if(*address >= *pattern && *address <= *(pattern + 2))
{
matched = val;
break;
}
else
{
pattern += 3;
}
}
else
{
// just test the character
if(*pattern == *address)
{
matched = val;
break;
}
pattern++;
}
}
return matched;
}
int osc_match_curly_brace(const char *pattern, const char *address)
{
pattern++;
const char *ptr = pattern;
while(*ptr != '}' && *ptr != '\0' && *ptr != '/')
{
while(*ptr != '}' && *ptr != '\0' && *ptr != '/' && *ptr != ',')
{
ptr++;
}
int n = ptr - pattern;
if(!strncmp(pattern, address, n))
{
return n;
}
else
{
ptr++;
pattern = ptr;
}
}
return 0;
}
| MugenSAS/osc-cpp-qt | osc/OscPatternMatching.cpp | C++ | mit | 7,646 |
<?php
namespace SportChecked\ContactBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('contact');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| leoestela/sportchecked | src/SportChecked/ContactBundle/DependencyInjection/Configuration.php | PHP | mit | 882 |