code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
import clearSuggestedActions from './actions/clearSuggestedActions';
import connect from './actions/connect';
import createStore, { withDevTools as createStoreWithDevTools } from './createStore';
import disconnect from './actions/disconnect';
import dismissNotification from './actions/dismissNotification';
import emitTypingIndicator from './actions/emitTypingIndicator';
import markActivity from './actions/markActivity';
import postActivity from './actions/postActivity';
import sendEvent from './actions/sendEvent';
import sendFiles from './actions/sendFiles';
import sendMessage from './actions/sendMessage';
import sendMessageBack from './actions/sendMessageBack';
import sendPostBack from './actions/sendPostBack';
import setDictateInterims from './actions/setDictateInterims';
import setDictateState from './actions/setDictateState';
import setLanguage from './actions/setLanguage';
import setNotification from './actions/setNotification';
import setSendBox from './actions/setSendBox';
import setSendTimeout from './actions/setSendTimeout';
import setSendTypingIndicator from './actions/setSendTypingIndicator';
import startDictate from './actions/startDictate';
import startSpeakingActivity from './actions/startSpeakingActivity';
import stopDictate from './actions/stopDictate';
import stopSpeakingActivity from './actions/stopSpeakingActivity';
import submitSendBox from './actions/submitSendBox';
import * as ActivityClientState from './constants/ActivityClientState';
import * as DictateState from './constants/DictateState';
const Constants = { ActivityClientState, DictateState };
const version = process.env.npm_package_version;
export {
clearSuggestedActions,
connect,
Constants,
createStore,
createStoreWithDevTools,
disconnect,
dismissNotification,
emitTypingIndicator,
markActivity,
postActivity,
sendEvent,
sendFiles,
sendMessage,
sendMessageBack,
sendPostBack,
setDictateInterims,
setDictateState,
setLanguage,
setNotification,
setSendBox,
setSendTimeout,
setSendTypingIndicator,
startDictate,
startSpeakingActivity,
stopDictate,
stopSpeakingActivity,
submitSendBox,
version
};
| Java |
var assert = require('assert');
var listXf = require('./helpers/listXf');
var R = require('..');
describe('any', function() {
var odd = function(n) {return n % 2 === 1;};
var T = function() {return true;};
var intoArray = R.into([]);
it('returns true if any element satisfies the predicate', function() {
assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 11, 12]), true);
});
it('returns false if all elements fails to satisfy the predicate', function() {
assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 12]), false);
});
it('returns true into array if any element satisfies the predicate', function() {
assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 11, 12]), [true]);
});
it('returns false if all elements fails to satisfy the predicate', function() {
assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 12]), [false]);
});
it('works with more complex objects', function() {
var people = [{first: 'Paul', last: 'Grenier'}, {first:'Mike', last: 'Hurley'}, {first: 'Will', last: 'Klein'}];
var alliterative = function(person) {return person.first.charAt(0) === person.last.charAt(0);};
assert.strictEqual(R.any(alliterative, people), false);
people.push({first: 'Scott', last: 'Sauyet'});
assert.strictEqual(R.any(alliterative, people), true);
});
it('can use a configurable function', function() {
var teens = [{name: 'Alice', age: 14}, {name: 'Betty', age: 18}, {name: 'Cindy', age: 17}];
var atLeast = function(age) {return function(person) {return person.age >= age;};};
assert.strictEqual(R.any(atLeast(16), teens), true, 'Some can legally drive');
assert.strictEqual(R.any(atLeast(21), teens), false, 'None can legally drink');
});
it('returns false for an empty list', function() {
assert.strictEqual(R.any(T, []), false);
});
it('returns false into array for an empty list', function() {
assert.deepEqual(intoArray(R.any(T), []), [false]);
});
it('dispatches when given a transformer in list position', function() {
assert.deepEqual(R.any(odd, listXf), {
any: false,
f: odd,
xf: listXf
});
});
it('is automatically curried', function() {
var count = 0;
var test = function(n) {count++; return odd(n);};
assert(R.any(test)([2, 4, 6, 7, 8, 10]) === true);
});
});
| Java |
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2>_SEGMENT_HEAP</h2>
<font face="arial"> +0x000 EnvHandle : <a href="./RTL_HP_ENV_HANDLE.html">RTL_HP_ENV_HANDLE</a><br>
+0x010 Signature : Uint4B<br>
+0x014 GlobalFlags : Uint4B<br>
+0x018 Interceptor : Uint4B<br>
+0x01c ProcessHeapListIndex : Uint2B<br>
+0x01e AllocatedFromMetadata : Pos 0, 1 Bit<br>
+0x020 CommitLimitData : <a href="./_RTL_HEAP_MEMORY_LIMIT_DATA.html">_RTL_HEAP_MEMORY_LIMIT_DATA</a><br>
+0x020 ReservedMustBeZero1 : Uint8B<br>
+0x028 UserContext : Ptr64 Void<br>
+0x030 ReservedMustBeZero2 : Uint8B<br>
+0x038 Spare : Ptr64 Void<br>
+0x040 LargeMetadataLock : Uint8B<br>
+0x048 LargeAllocMetadata : <a href="./_RTL_RB_TREE.html">_RTL_RB_TREE</a><br>
+0x058 LargeReservedPages : Uint8B<br>
+0x060 LargeCommittedPages : Uint8B<br>
+0x068 StackTraceInitVar : <a href="./_RTL_RUN_ONCE.html">_RTL_RUN_ONCE</a><br>
+0x080 MemStats : <a href="./_HEAP_RUNTIME_MEMORY_STATS.html">_HEAP_RUNTIME_MEMORY_STATS</a><br>
+0x0d8 GlobalLockCount : Uint2B<br>
+0x0dc GlobalLockOwner : Uint4B<br>
+0x0e0 ContextExtendLock : Uint8B<br>
+0x0e8 AllocatedBase : Ptr64 UChar<br>
+0x0f0 UncommittedBase : Ptr64 UChar<br>
+0x0f8 ReservedLimit : Ptr64 UChar<br>
+0x100 SegContexts : [2] <a href="./_HEAP_SEG_CONTEXT.html">_HEAP_SEG_CONTEXT</a><br>
+0x280 VsContext : <a href="./_HEAP_VS_CONTEXT.html">_HEAP_VS_CONTEXT</a><br>
+0x340 LfhContext : <a href="./_HEAP_LFH_CONTEXT.html">_HEAP_LFH_CONTEXT</a><br>
</font></body></html> | Java |
@extends('frontend.layouts.default')
@section('content')
<div class="breadcrumb-wrapper">
<div class="pattern-overlay">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-6">
<h2 class="title">Recent Events</h2>
</div>
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-6">
<div class="breadcrumbs pull-right">
<ul>
<li><a href="{!! URL::to('/') !!}">Home</a></li>
<li><a href="#">Events</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Main Content start-->
<div class="content margin-top60 margin-bottom60">
<div class="container">
<div class="row">
<!-- Blog Posts -->
<div class="posts-block col-lg-8 col-md-8 col-sm-8 col-xs-12">
@foreach($events as $event)
<!-- Blog Post 1 -->
<article class="post hentry">
<div class="post-image">
<a href="{!! asset($event->banner) !!}" data-rel="prettyPhoto">
<span class="img-hover"></span>
<span class="fullscreen"><i class="fa fa-plus"></i></span>
<img src="{!! asset($event->banner) !!}" alt="" width="800px" class="img-responsive">
</a>
</div>
<header class="post-header">
<h2><a href="{!! route('event.details',$event->event_meta_data) !!}" title="dd"> {!! $event->headline !!}</a></h2>
<div class="blog-entry-meta">
<div class="blog-entry-meta-author">
<i class="fa fa-user"></i>
<span class="blog-entry-meta-author">Department: {!! $event->dept->name !!}</span>
</div>
<div class="blog-entry-meta-tags">
<i class="fa fa-tags"></i>
<a href="#">Venue: {!! $event->venue !!}</a>,
</div>
<div class="blog-entry-meta-date">
<i class="fa fa-clock-o"></i>
<span class="blog-entry-meta-date-day">Start Date: {!! $event->start_time !!}</span>
</div>
</div>
</header>
<div class="post-content">
<p>
{!! strip_tags(str_limit($event->description, 350)) !!}
</p>
</div>
<footer class="post-footer">
<a class="btn btn-color" href="{!! route('event.details',$event->event_meta_data) !!}" class="readmore">Read More</a>
</footer>
</article>
<!-- /Blog Post 1 -->
<!-- Star-->
<div class="star">
<div class="row">
<div class="col-md-12">
<div class="star-divider">
<div class="star-divider-icon">
<i class=" fa fa-star"></i>
</div>
</div>
</div>
</div>
</div>
<!-- /Star -->
@endforeach
<!-- /Star -->
<ul class="pager">
{!! $events->render() !!}
</ul>
</div>
<!-- /Blog Posts -->
@include('frontend.includes.rightsidebarEvent')
</div>
</div>
</div>
<!-- /Main Content end-->
@stop
@section('style')
<style>
</style>
@stop
@section('script')
@stop
| Java |
Hamahatschi
===========
Hamahatschi is a simple program to turn Hamachi and its service as well as network adapter on and off.
Usage
------
Simply compile the project or start the executable. It will try to find the adapter and the service and disable/enable Hamachi, depending on what its current state is. If it can't decide on what you want (because one thing is enabled and the other is disabled), it will prompt whether you want to start or close Hamachi.
Because I'm messing around with network adapters and services, this program requires elevated rights (i.e. UAC will bother you every time you start it).
If everything went according to plan, Hamachi should shut down/start up and the program will close itself. In case there was an error, the command line stays open and prints some information. If you are encountering an error and cannot solve it on your own, submit it as an issue. When opening an issue, please include everything Hamahatschi writes.
Motivation
----------
Because Steam's P2P functionality was severely broken for me and a few friends, we had to create direct connections between each other. We chose Hamachi for that as it was somewhat well established and known to all of us.
However, I disliked having Hamachi open 24/7, especially with its (more or less useless) service and network adapter that was only used from time to time. Hamahatschi was created as an attempt to solve this by disabling the network adapter Hamachi creates (called "Hamachi") and stopping its service ("LogMeIn Tunneling Engine"), therefore rendering it quite useless. | Java |
<div layout="row" layout-align="space-between center">
<md-button href="#">Code Challenge for T-Systems</md-button>
<md-button class="acme-navbar-text">Application was created {{ vm.relativeDate }}.</md-button>
</div>
| Java |
{% extends 'layouts/base.html' %}
{% block title %}
{% endblock %}
{% block content %}
<div class="row">
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Question Details</h3>
</div>
<div class="panel-body">
<h5>Lecture: {{ question.lecture }}</h5>
<h5>Text: <blockquote><p>{{ question.text }}</p></blockquote></h5>
<h5>Correct Answer: {{ question.answer.correct_answer.text }}</h5>
<table class="table">
<thead>
<th>#</th>
<th>Answer Option</th>
</thead>
{% for option in question.answer.answer_options.all %}
<tbody>
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ option }}</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Response Summary</h3>
</div>
<div class="panel-body">
<h5>Response Ratio: X/Y </h5>
{% for stat in response_stats %}
{{ stat.0 }} {{ stat.1 }} <br>
{% endfor %}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Responses</h3>
</div>
<div class="panel-body">
<table class="table table-responsive">
<thead>
<th>#</th>
<th>Student</th>
<th>Response</th>
</thead>
<tbody>
{% for response in responses %}
{% if response.is_correct %}
<tr class="success">
{% else %}
<tr class="danger">
{% endif %}
<td>{{ forloop.counter }}</td>
<td>{{ response.student.user.first_name }}, {{ response.student.user.last_name }}</td>
<td>{{ response.answer_option.id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %} | Java |
<?php
namespace Kids\Controller;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Kids\Entity\Workshop;
use Kids\Entity\Establishment;
use Kids\Entity\PublicAge;
use Kids\Entity\WorkshopCategory;
use Kids\Entity\Address;
use Kids\Entity\Kid;
use Kids\Entity\KidHasParent;
use Kids\Entity\ParentOfKid;
use Kids\Entity\WorkshopHasKid;
use Kids\Entity\Timetable;
class WorkshopController
{
public function indexAction(Application $app, Request $request)
{
$workshop = new Workshop();
$list = $workshop->fetchAll();
$age = new PublicAge();
$ages = $age->fetchAll();
$establishment = new Establishment();
$establishments = $establishment->fetchAll();
$categorie = new WorkshopCategory();
$categories = $categorie->fetchAll();
return new Response($app['twig']->render('workshop/index.html.twig', array('workshops' => $list,
'ages' => $ages,
'lieux' => $establishments,
'categories' => $categories)));
}
public function indexAdminAction(Application $app, Request $request)
{
$workshop = new Workshop();
$list = $workshop->fetchAll(null, false);
return new Response($app['twig']->render('workshop/index_admin.html.twig', array(
'workshops' => $list)));
}
/**
* nouveau atelier
*
*/
public function newAction(Application $app, Request $request)
{
$user = $app['session']->get('user');
if (empty($user)) {
return $app->redirect('/login');
}
$age = new PublicAge();
$ages = $age->fetchAll();
$establishment = new Establishment();
$establishments = $establishment->fetchAll();
$workshop = new WorkshopCategory();
$workshops = $workshop->fetchAll();
if ($request->isMethod('post')){
// upload images
$target_dir = __DIR__.'/../../web/images/';
$filename = time() . basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $filename;
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 9999999) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$workshop = new Workshop();
if (isset($_POST['visibility']) && $_POST['visibility'] != null) {
$visibility = 1;
} else {
$visibility = 0;
}
$workshop
->setTitle($_POST['title'])
->setDescription($_POST['description'])
->setPrice($_POST['price'])
->setMaxKids($_POST['max_kids'])
->setImage($filename)
->setVisible($visibility)
->setPublicAgeId($_POST['age'])
->setEstablishmentId($_POST['establishment'])
->setWorkshopCategoryId($_POST['category']);
$workshop->save();
$timetable = new Timetable();
$date = explode('/', $_POST['debut']);
$dateFormat = $date[2] . '-' . $date[1] . '-' . $date[0];
$startAt = $dateFormat . ' ' . $_POST['hours_debut'];
$endAt = $dateFormat . ' ' . $_POST['hours_fin'];
$timetable->setStartAt($startAt)
->setEndAt($endAt)
->setWorkshopId($workshop->getId())
->save();
return $app->redirect('/admin/ateliers');
}
return new Response($app['twig']->render('workshop/new.html.twig', array(
'ages' => $ages,
'establishments' => $establishments,
'workshops_category' => $workshops,
)));
}
public function deleteAction(Application $app, Request $request)
{
$user = $app['session']->get('user');
if (empty($user)) {
return $app->redirect('/login');
}
$id = $request->get('id');
$workshopModel = new Workshop();
$workshop = $workshopModel->delete($id);
return $app->redirect('/admin/ateliers');
}
public function registerAction(Application $app, Request $request)
{
$default = ($request->get('id') != null ? $request->get('id') : null);
$workshop = new Workshop();
$list = $workshop->fetchAll();
if ($request->isMethod('post')){
$address = new Address();
$address->setAddress($_POST['adresse'])
->setComplement($_POST['complement'])
->setCity($_POST['ville'])
->setZipcode($_POST['code_postal'])
->save();
$parent = new ParentOfKid();
$parent->setFirstname($_POST['parent_prenom'])
->setLastname($_POST['parent_nom'])
->setEmail($_POST['mail'])
->setAddressId($address->getId())
->setPhone($_POST['telephone'])
->save();
$enfant = new Kid();
$birthday = explode('/', $_POST['enfant1_naissance']);
$birthdayFormat = $birthday[2] . '-' . $birthday[1] . '-' . $birthday[0];
$enfant->setFirstname($_POST['enfant1_prenom'])
->setLastname($_POST['enfant1_nom'])
->setBirthday($birthdayFormat)
->setClassroom( ($_POST['enfant1_classe'] == '' ? 'NULL' : $_POST['enfant1_classe']))
->save();
$WorkshopHasKid = new WorkshopHasKid();
$WorkshopHasKid->setWorkshopId($_POST['ateliers'])
->setKidId($enfant->getId())
->save();
$kidHasParent = new KidHasParent();
$kidHasParent->setKidId($enfant->getId())
->setParentId($parent->getId())
->save();
if ($_POST['enfant2_nom'] != ''
&& $_POST['enfant2_prenom'] != ''
&& $_POST['enfant2_naissance'] != '') {
$enfant = new Kid();
$birthday = explode('/', $_POST['enfant2_naissance']);
$birthdayFormat = $birthday[2] . '-' . $birthday[1] . '-' . $birthday[0];
$enfant->setFirstname($_POST['enfant2_prenom'])
->setLastname($_POST['enfant2_nom'])
->setBirthday($birthdayFormat)
->setClassroom( ($_POST['enfant2_classe'] == '' ? 'NULL' : $_POST['enfant2_classe']))
->save();
$WorkshopHasKid = new WorkshopHasKid();
$WorkshopHasKid->setWorkshopId($_POST['ateliers'])
->setKidId($enfant->getId())
->save();
$kidHasParent = new KidHasParent();
$kidHasParent->setKidId($enfant->getId())
->setParentId($parent->getId())
->save();
}
$app['session']->getFlashBag()->add('message', 'Votre inscription a bien été enregistrer.');
return $app->redirect('/ateliers');
}
return new Response($app['twig']->render('workshop/register.html.twig', array('workshops' => $list, 'default' => $default)));
}
public function attenteAdminAction(Application $app, Request $request)
{
$user = $app['session']->get('user');
if (empty($user)) {
return $app->redirect('/login');
}
$workshop = new WorkshopHasKid();
$list = $workshop->fetchAll();
if ($request->get('workshop') != NULL && $request->get('response') != NULL && $request->get('kid') != NULL) {
$workshop->edit($request->get('response'), $request->get('workshop'), $request->get('kid'));
return $app->redirect('/ateliers/attente');
}
return new Response($app['twig']->render('workshop/attente.html.twig', array('workshops' => $list)));
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Controllers.Bases;
namespace net.authorize.sample
{
public class GetAccountUpdaterJobSummary
{
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey)
{
Console.WriteLine("Get Account Updater job summary sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
// Set a valid month for the request
string month = "2017-07";
// Build tbe request object
var request = new getAUJobSummaryRequest();
request.month = month;
// Instantiate the controller that will call the service
var controller = new getAUJobSummaryController(request);
controller.Execute();
// Get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
{
Console.WriteLine("SUCCESS: Get Account Updater Summary for Month : " + month);
if (response.auSummary == null)
{
Console.WriteLine("No Account Updater summary for this month.");
return response;
}
// Displaying the summary of each response in the list
foreach (var result in response.auSummary)
{
Console.WriteLine(" Reason Code : " + result.auReasonCode);
Console.WriteLine(" Reason Description : " + result.reasonDescription);
Console.WriteLine(" # of Profiles updated for this reason : " + result.profileCount);
}
}
else if (response != null)
{
Console.WriteLine("ERROR : Invalid response");
Console.WriteLine("Response : " + response.messages.message[0].code + " " + response.messages.message[0].text);
}
return response;
}
}
}
| Java |
-- Copyright (C) 2014 MariaDB Ab.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; version 2 of the License.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This part creates stored procedures required by the OpenGIS standards.
# script is prepared to be run with the --bootstrap server option
SET sql_mode='';
DROP PROCEDURE IF EXISTS AddGeometryColumn;
DROP PROCEDURE IF EXISTS DropGeometryColumn;
CREATE PROCEDURE AddGeometryColumn(catalog varchar(64), t_schema varchar(64),
t_name varchar(64), geometry_column varchar(64), t_srid int)
begin
set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' ADD ', geometry_column,' GEOMETRY REF_SYSTEM_ID=', t_srid); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end ;
CREATE PROCEDURE DropGeometryColumn(catalog varchar(64), t_schema varchar(64),
t_name varchar(64), geometry_column varchar(64))
begin
set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' DROP ', geometry_column); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end ;
| Java |
// Copyright(c) 2013 GROWTH XPARTNERS, Incorporated.
//
//
package junit.tutorial.calculator;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class CalculatorTest {
@Test
public void multiplyで3と4の乗算結果が取得できる() {
Calculator calc = new Calculator();
int expected = 12;
int actual = calc.multiply(3, 4);
assertThat(actual, is(expected));
}
@Test
public void multiplyで5と7の乗算結果が取得できる() {
Calculator calc = new Calculator();
int expected = 35;
int actual = calc.multiply(5, 7);
assertThat(actual, is(expected));
}
@Test
public void divideで3と2の除算結果が取得できる() {
Calculator calc = new Calculator();
float expected = 1.5f;
float actual = calc.divide(3, 2);
assertThat(actual, is(expected));
}
@Test(expected = IllegalArgumentException.class)
public void divideで5と0のときIllegalArgumentExceptionを送出する() {
Calculator calc = new Calculator();
calc.divide(5, 0);
}
public static void main(String[] args) {
org.junit.runner.JUnitCore.main(CalculatorTest.class.getName());
}
}
| Java |
import {Vec3f} from "./Vec3f";
import {Quaternion} from "./Quaternion";
import {MathUtils} from "./MathUtils";
import {Vec4f} from "./Vec4f";
/**
* Created by r3f on 7/1/2016.
*/
export class Mat4f{
// Matrix row & column values as in i,j
m:Float32Array;
/*
* Constructor Mat4f()
* @info: Rows and columns are 0 by default
*/
constructor(m?:Float32Array)
{
this.m = m?m:new Float32Array(16);
}
identity(overwrite:boolean=false):Mat4f {
if (!overwrite) {
var mat = new Mat4f()
mat.m[0] = 1;
mat.m[1] = 0;
mat.m[2] = 0;
mat.m[3] = 0;
mat.m[4] = 0;
mat.m[5] = 1;
mat.m[6] = 0;
mat.m[7] = 0;
mat.m[8] = 0;
mat.m[9] = 0;
mat.m[10] = 1;
mat.m[11] = 0;
mat.m[12] = 0;
mat.m[13] = 0;
mat.m[14] = 0;
mat.m[15] = 1;
return mat;
}
this.m[0] = 1;
this.m[1] = 0;
this.m[2] = 0;
this.m[3] = 0;
this.m[4] = 0;
this.m[5] = 1;
this.m[6] = 0;
this.m[7] = 0;
this.m[8] = 0;
this.m[9] = 0;
this.m[10] = 1;
this.m[11] = 0;
this.m[12] = 0;
this.m[13] = 0;
this.m[14] = 0;
this.m[15] = 1;
return this;
}
transpose(overwrite:boolean=false):Mat4f {
if (!overwrite) {
var mat = new Mat4f();
var a01 = this.m[1], a02 = this.m[2], a03 = this.m[3],
a12 = this.m[6], a13 = this.m[7],
a23 = this.m[11];
mat.m[1] = mat[4];
mat.m[2] = mat[8];
mat.m[3] = mat[12];
mat.m[4] = a01;
mat.m[6] = mat[9];
mat.m[7] = mat[13];
mat.m[8] = a02;
mat.m[9] = a12;
mat.m[11] = mat[14];
mat.m[12] = a03;
mat.m[13] = a13;
mat.m[14] = a23;
return mat;
}
this.m[0] = this.m[0];
this.m[1] = this.m[4];
this.m[2] = this.m[8];
this.m[3] = this.m[12];
this.m[4] = this.m[1];
this.m[5] = this.m[5];
this.m[6] = this.m[9];
this.m[7] = this.m[13];
this.m[8] = this.m[2];
this.m[9] = this.m[6];
this.m[10] = this.m[10];
this.m[11] = this.m[14];
this.m[12] = this.m[3];
this.m[13] = this.m[7];
this.m[14] = this.m[11];
this.m[15] = this.m[15];
return this;
}
determinant():number {
// Cache the matrix values (makes for huge speed increases!)
var a00 = this.m[0], a01 = this.m[1], a02 = this.m[2], a03 = this.m[3],
a10 = this.m[4], a11 = this.m[5], a12 = this.m[6], a13 = this.m[7],
a20 = this.m[8], a21 = this.m[9], a22 = this.m[10], a23 = this.m[11],
a30 = this.m[12], a31 = this.m[13], a32 = this.m[14], a33 = this.m[15];
return (a30 * a21 * a12 * a03 - a20 * a31 * a12 * a03 - a30 * a11 * a22 * a03 + a10 * a31 * a22 * a03 +
a20 * a11 * a32 * a03 - a10 * a21 * a32 * a03 - a30 * a21 * a02 * a13 + a20 * a31 * a02 * a13 +
a30 * a01 * a22 * a13 - a00 * a31 * a22 * a13 - a20 * a01 * a32 * a13 + a00 * a21 * a32 * a13 +
a30 * a11 * a02 * a23 - a10 * a31 * a02 * a23 - a30 * a01 * a12 * a23 + a00 * a31 * a12 * a23 +
a10 * a01 * a32 * a23 - a00 * a11 * a32 * a23 - a20 * a11 * a02 * a33 + a10 * a21 * a02 * a33 +
a20 * a01 * a12 * a33 - a00 * a21 * a12 * a33 - a10 * a01 * a22 * a33 + a00 * a11 * a22 * a33);
}
inverse(overwrite:boolean=false) {
var mat = this.m;
if(overwrite){
var dest:Mat4f = this;
}else{
var dest = new Mat4f();
}
// Cache the matrix values (makes for huge speed increases!)
var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3],
a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7],
a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11],
a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
d = (b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06),
invDet;
// Calculate the determinant
if (!d) { return null; }
invDet = 1 / d;
dest.m[0] = (a11 * b11 - a12 * b10 + a13 * b09) * invDet;
dest.m[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet;
dest.m[2] = (a31 * b05 - a32 * b04 + a33 * b03) * invDet;
dest.m[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet;
dest.m[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet;
dest.m[5] = (a00 * b11 - a02 * b08 + a03 * b07) * invDet;
dest.m[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet;
dest.m[7] = (a20 * b05 - a22 * b02 + a23 * b01) * invDet;
dest.m[8] = (a10 * b10 - a11 * b08 + a13 * b06) * invDet;
dest.m[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet;
dest.m[10] = (a30 * b04 - a31 * b02 + a33 * b00) * invDet;
dest.m[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet;
dest.m[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet;
dest.m[13] = (a00 * b09 - a01 * b07 + a02 * b06) * invDet;
dest.m[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet;
dest.m[15] = (a20 * b03 - a21 * b01 + a22 * b00) * invDet;
return dest;
}
toRotationMat() {
var dest:Mat4f = new Mat4f();
dest.m[0] = this.m[0];
dest.m[1] = this.m[1];
dest.m[2] = this.m[2];
dest.m[3] = this.m[3];
dest.m[4] = this.m[4];
dest.m[5] = this.m[5];
dest.m[6] = this.m[6];
dest.m[7] = this.m[7];
dest.m[8] = this.m[8];
dest.m[9] = this.m[9];
dest.m[10] = this.m[10];
dest.m[11] = this.m[11];
dest.m[12] = 0;
dest.m[13] = 0;
dest.m[14] = 0;
dest.m[15] = 1;
return dest;
}
frustum(left, right, bottom, top, near, far, overwrite:boolean=false) {
if(overwrite){
var dest:Mat4f = this;
}else{
dest = new Mat4f();
}
var rl = (right - left),
tb = (top - bottom),
fn = (far - near);
dest.m[0] = (near * 2) / rl;
dest.m[1] = 0;
dest.m[2] = 0;
dest.m[3] = 0;
dest.m[4] = 0;
dest.m[5] = (near * 2) / tb;
dest.m[6] = 0;
dest.m[7] = 0;
dest.m[8] = (right + left) / rl;
dest.m[9] = (top + bottom) / tb;
dest.m[10] = -(far + near) / fn;
dest.m[11] = -1;
dest.m[12] = 0;
dest.m[13] = 0;
dest.m[14] = -(far * near * 2) / fn;
dest.m[15] = 0;
return dest;
}
perspective(fovy, aspect, near, far, overwrite:boolean=false) {
var top = near * Math.tan(fovy * Math.PI / 360.0),
right = top * aspect;
return this.frustum(-right, right, -top, top, near, far, overwrite);
}
lookAt(eye, center, up) {
var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2],
centerx = center[0],
centery = center[1],
centerz = center[2];
if (eyex === centerx && eyey === centery && eyez === centerz) {
return this.identity(true);
}
//vec3.direction(eye, center, z);
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
// normalize (no check needed for 0 because of early return)
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
//vec3.normalize(vec3.cross(up, z, x));
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
//vec3.normalize(vec3.cross(z, x, y));
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
this.m[0] = x0;
this.m[1] = y0;
this.m[2] = z0;
this.m[3] = 0;
this.m[4] = x1;
this.m[5] = y1;
this.m[6] = z1;
this.m[7] = 0;
this.m[8] = x2;
this.m[9] = y2;
this.m[10] = z2;
this.m[11] = 0;
this.m[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
this.m[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
this.m[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
this.m[15] = 1;
return this;
}
multiply(mat2) {
var dest = new Mat4f();
var mat = this.m;
// Cache the matrix values (makes for huge speed increases!)
var a00 = mat[ 0], a01 = mat[ 1], a02 = mat[ 2], a03 = mat[3];
var a10 = mat[ 4], a11 = mat[ 5], a12 = mat[ 6], a13 = mat[7];
var a20 = mat[ 8], a21 = mat[ 9], a22 = mat[10], a23 = mat[11];
var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
// Cache only the current line of the second matrix
var b0 = mat2.m[0], b1 = mat2.m[1], b2 = mat2.m[2], b3 = mat2.m[3];
dest.m[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
dest.m[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
dest.m[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
dest.m[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = mat2.m[4];
b1 = mat2.m[5];
b2 = mat2.m[6];
b3 = mat2.m[7];
dest.m[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
dest.m[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
dest.m[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
dest.m[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = mat2.m[8];
b1 = mat2.m[9];
b2 = mat2.m[10];
b3 = mat2.m[11];
dest.m[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
dest.m[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
dest.m[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
dest.m[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = mat2.m[12];
b1 = mat2.m[13];
b2 = mat2.m[14];
b3 = mat2.m[15];
dest.m[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
dest.m[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
dest.m[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
dest.m[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
return dest;
}
multiplyVec4(vec) {
var dest = new Vec4f();
var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
dest.x = this.m[0] * x + this.m[4] * y + this.m[8] * z + this.m[12] * w;
dest.y = this.m[1] * x + this.m[5] * y + this.m[9] * z + this.m[13] * w;
dest.z = this.m[2] * x + this.m[6] * y + this.m[10] * z + this.m[14] * w;
dest.w = this.m[3] * x + this.m[7] * y + this.m[11] * z + this.m[15] * w;
return dest;
}
} | Java |
module.exports = function (options, suite, test, expect, teardown) {
require('./integration.expressions')(options, suite, test, expect, teardown);
suite('tribe.storage.integration.' + options.type, function () {
var storage = require('tribe.storage'),
db;
test("basic store and retrieve", function () {
return open(['p1', 'p2'],
[
{ p1: 1, p2: 'test' },
{ p1: 2, p2: 'test2' }
])
.then(function (container) {
return container.retrieve({ p: 'p1', v: 1 });
})
.then(function (rows) {
expect(rows.length).to.equal(1);
expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' });
});
});
test("multiple key index store and retrieve", function () {
return open([['p1', 'p2']],
[
{ p1: 'test', p2: 1 },
{ p1: 'test', p2: 2 },
{ p1: 'test', p2: 3 },
{ p1: 'test2', p2: 2 },
])
.then(function (container) {
return container.retrieve([{ p: 'p1', v: 'test' }, { p: 'p2', o: '>=', v: 2 }]);
})
.then(function (rows) {
expect(rows.length).to.equal(2);
});
});
// this was originally done by sorting the index. this won't work with indexeddb as order is significant
// we can store some metadata about index order and apply expression components in the correct order. todo.
//test("multiple key order does not need to match expression order", function () {
// return open([['p1', 'p2']], [{ p1: 'test', p2: 1 }])
// .then(function (container) {
// return container.retrieve([{ p: 'p2', v: 1 }, { p: 'p1', v: 'test' }]);
// })
// .then(function (rows) {
// expect(rows.length).to.equal(1);
// });
//});
test("complex object store and retrieve", function () {
return open([['p1.p2', 'p3']],
[
{ p1: { p2: 'test' }, p3: 1 },
{ p1: { p2: 'test' }, p3: 1 },
{ p1: { p2: 'test2' }, p3: 1 }
])
.then(function (container) {
return container.retrieve([{ p: 'p1.p2', v: 'test' }, { p: 'p3', v: 1 }]);
})
.then(function (rows) {
expect(rows.length).to.equal(2);
});
});
test("keyPath can be queried when autoIncrement is set", function () {
return open([],
[
{ p2: 'test' },
{ p2: 'test2' }
], 'p1', true)
.then(function (container) {
return container.retrieve({ p: 'p1', v: 1 });
})
.then(function (rows) {
expect(rows.length).to.equal(1);
expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' });
});
});
test("keyPath can be queried when autoIncrement is not set", function () {
return open([],
[
{ p1: 3, p2: 'test' },
{ p1: 4, p2: 'test2' }
], 'p1', false)
.then(function (container) {
return container.retrieve({ p: 'p1', v: 3 });
})
.then(function (rows) {
expect(rows.length).to.equal(1);
expect(rows[0]).to.deep.equal({ p1: 3, p2: 'test' });
});
});
test("keyPath can be queried with indexes", function () {
return open(['p2'],
[
{ p1: 1, p2: 'test' },
{ p1: 2, p2: 'test2' }
], 'p1')
.then(function (container) {
return container.retrieve([{ p: 'p1', v: 1 }, { p: 'p2', v: 'test' }]);
})
.then(function (rows) {
expect(rows.length).to.equal(1);
expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' });
});
});
test("store operation returns entity with autoIncrement keyPath property set", function () {
return open([], [], 'id', true)
.then(function (container) {
return container.store({});
})
.then(function (updatedEntity) {
expect(updatedEntity).to.deep.equal({ id: 1 });
});
});
test("multiple store operation returns entities with autoIncrement keyPath property set", function () {
return open([], [], 'id', true)
.then(function (container) {
return container.store([{}, {}]);
})
.then(function (updatedEntity) {
expect(updatedEntity).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
});
test("stored entity has autoIncrement keyPath property set", function () {
var container;
return open([], [], 'id', true)
.then(function (db) {
container = db;
return container.store({});
})
.then(function () {
return container.retrieve({ p: 'id', v: 1 });
})
.then(function (entities) {
expect(entities.length).to.equal(1);
expect(entities[0]).to.deep.equal({ id: 1 });
});
});
test("store operation replaces entities with matching keys", function () {
var entity;
return open([], [{ p1: 1, p2: 'test' }], 'p1')
.then(function (provider) {
entity = provider;
return entity.store({ p1: 1, p2: 'test2' });
})
.then(function () {
return entity.retrieve({ p: 'p1', v: 1 });
})
.then(function (entities) {
expect(entities.length).to.equal(1);
expect(entities[0].p2).to.equal('test2');
});
});
test("single property indexes can be specified and requested as arrays or individually", function () {
var container;
return open(['p1', ['p2']], [
{ p1: 1, p2: 1 },
{ p1: 2, p2: 2 }
])
.then(function (result) {
container = result;
return container.retrieve({ p: 'p1', v: 2 });
})
.then(function (results) {
expect(results.length).to.equal(1);
})
.then(function (result) {
return container.retrieve([{ p: 'p1', v: 2 }]);
})
.then(function (results) {
expect(results.length).to.equal(1);
})
.then(function (result) {
return container.retrieve({ p: 'p2', v: 2 });
})
.then(function (results) {
expect(results.length).to.equal(1);
})
.then(function (result) {
return container.retrieve([{ p: 'p2', v: 2 }]);
})
.then(function (results) {
expect(results.length).to.equal(1);
});
});
test("retrieve sorts by index properties", function () {
var container;
return open([['p1', 'p2.value'], ['p2.value', 'p1']], [
{ p1: 4, p2: { value: 1 } },
{ p1: 3, p2: { value: 2 } },
{ p1: 1, p2: { value: 1 } },
{ p1: 2, p2: { value: 2 } }
])
.then(function (result) {
container = result;
return container.retrieve([{ p: 'p1', o: '>', v: 0 }, { p: 'p2.value', o: '>', v: 0 }]);
})
.then(function (results) {
expect(results).to.deep.equal([
{ p1: 1, p2: { value: 1 } },
{ p1: 2, p2: { value: 2 } },
{ p1: 3, p2: { value: 2 } },
{ p1: 4, p2: { value: 1 } }
]);
return container.retrieve([{ p: 'p2.value', o: '>', v: 0 }, { p: 'p1', o: '>', v: 0 }]);
})
.then(function (results) {
expect(results).to.deep.equal([
{ p1: 1, p2: { value: 1 } },
{ p1: 4, p2: { value: 1 } },
{ p1: 2, p2: { value: 2 } },
{ p1: 3, p2: { value: 2 } }
]);
});
});
test("clear deletes all entities", function () {
var container;
return open(['p1'], [{ p1: 1, p2: 1 }])
.then(function (result) {
container = result;
container.clear();
})
.then(function () {
return container.retrieve({ p: 'p1', v: 1 });
})
.then(function (messages) {
expect(messages.length).to.equal(0);
});
});
function open(indexes, entities, keyPath, autoIncrement) {
var entity;
return storage.open([{ name: 'test', indexes: indexes, keyPath: keyPath, autoIncrement: autoIncrement }], options)
.then(function (provider) {
db = provider;
entity = provider.entity('test');
return entity.store(entities);
})
.then(function () {
return entity;
});
}
teardown(function () {
db.close();
});
});
};
| Java |
from math import floor
def score_syntax_errors(program_lines):
points = {')': 3, ']': 57, '}': 1197, '>': 25137}
s = 0
scores_auto = []
for line in program_lines:
corrupted, stack = corrupted_character(line)
if corrupted:
s += points[corrupted]
else:
scores_auto.append(score_autocomplete(stack))
return s, sorted(scores_auto)[floor(len(scores_auto)/2)]
def corrupted_character(inp):
stack = []
lookup = {'(': ')', '[': ']', '{': '}', '<': '>'}
lookup_close = {v: k for k, v in lookup.items()}
def stack_converter(st):
return [lookup[element] for element in st[::-1]]
for char in inp:
if char in lookup:
stack.append(char)
elif char in lookup_close:
expected = stack.pop()
if expected != lookup_close[char]:
return char, stack_converter(stack)
else:
print(f"INVALID {char}")
return None, stack_converter(stack)
def score_autocomplete(stack):
points_autocomplete = {')': 1, ']': 2, '}': 3, '>': 4}
s_auto = 0
for char in stack:
s_auto *= 5
s_auto += points_autocomplete[char]
return s_auto
def test_corrupted_character():
assert corrupted_character('{([(<{}[<>[]}>{[]{[(<()>')[0] == '}'
assert corrupted_character('[[<[([]))<([[{}[[()]]]')[0] == ')'
assert corrupted_character('[{[{({}]{}}([{[{{{}}([]')[0] == ']'
assert corrupted_character('[<(<(<(<{}))><([]([]()')[0] == ')'
assert corrupted_character('<{([([[(<>()){}]>(<<{{')[0] == '>'
def test_score_syntax_errors():
assert score_syntax_errors(open('input/10.test').read().splitlines()) == (26397, 288957)
def test_corrupted_character_stack():
assert corrupted_character('[({(<(())[]>[[{[]{<()<>>')[1] == ['}', '}', ']', ']', ')', '}', ')', ']']
def test_scoring_autocomplete():
assert score_autocomplete('}}]])})]') == 288957
assert score_autocomplete(')}>]})') == 5566
assert score_autocomplete('}}>}>))))') == 1480781
if __name__ == '__main__':
print(score_syntax_errors(open('input/10').read().splitlines()))
| Java |
using System;
using App.Common.Extensions;
namespace App.Core.Elements
{
/// <summary>
/// Класс для описания списка заявлений по оплате по типам служб.
/// </summary>
public class Declaration
{
/// <summary>
/// Расчетный период.
/// </summary>
public string SettlementPeriod { get; set; }
/// <summary>
/// Имя.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Тип.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Ресурс.
/// </summary>
public string Resource { get; set; }
/// <summary>
/// Регион.
/// </summary>
public string Region { get; set; }
/// <summary>
/// SKU.
/// </summary>
/// <remarks>Указывает уникальный идентификатор системы для каждого ресурса Windows Azure.</remarks>
public string SKU { get; set; }
/// <summary>
/// Единица.
/// </summary>
public string Unit { get; set; }
/// <summary>
/// Израсходовано.
/// </summary>
public string Spent { get; set; }
/// <summary>
/// Включено.
/// </summary>
/// <remarks>Содержит объем ресурсов, бесплатно включаемых в текущий расчетный период.</remarks>
public string Include { get; set; }
/// <summary>
/// Подлежит оплате.
/// </summary>
/// <remarks>Содержит объем ресурсов, подлежащих оплате в текущем расчетном периоде.</remarks>
public string Payable { get; set; }
/// <summary>
/// В рамках обязательства.
/// </summary>
/// <remarks>Содержит выплаты за ресурсы, которые вычитаются из суммы обязательства, связанной с 6- или 12-месячным предложением. Обратите внимание на то, что выплаты за ресурсы вычитаются из суммы обязательства в хронологическом порядке.</remarks>
public string AsPartOfACommitment { get; set; }
/// <summary>
/// Валюта.
/// </summary>
/// <remarks>Указывает валюту, используемую в текущем расчетном периоде.</remarks>
public string Currency { get; set; }
/// <summary>
/// Превышение.
/// </summary>
/// <remarks>Содержит выплаты за ресурсы, которые превышают сумму обязательства, связанную с 6- или 12-месячным предложением.</remarks>
public string Excess { get; set; }
/// <summary>
/// Тариф по обязательствам.
/// </summary>
/// <remarks>Содержит тариф по обязательствам, который зависит от общей суммы обязательства, связанной с 6- или 12-месячным предложением.</remarks>
public string TariffCommitments { get; set; }
/// <summary>
/// Тариф.
/// </summary>
/// <remarks>Содержит тариф оплаты по мере использования для ресурса.</remarks>
public string Tariff { get; set; }
/// <summary>
/// Значение.
/// </summary>
/// <remarks>Содержит итоговую денежную сумму для израсходованного ресурса.</remarks>
public string Value { get; set; }
/// <summary>
/// Инициализация "пустого" объекта.
/// </summary>
public Declaration()
{ }
/// <summary>
/// Инициализация объекта с данными полученными из разбора строки CSV файла.
/// </summary>
/// <param name="data">Массив строк из файла.</param>
public Declaration(string[] data)
{
SettlementPeriod = data[0];
Name = data[1];
Type = data[2];
Resource = data[3];
Region = data[4];
SKU = data[5];
Unit = data[6];
Spent = data[7];
Include = data[8];
Payable = data[9];
AsPartOfACommitment = data[10];
Currency = data[11];
Excess = data[12];
TariffCommitments = data[13];
Tariff = data[14];
Value = data[15];
}
public override string ToString()
{
return String.Format("Декларация за {0} отчетный период по службе {1}.", SettlementPeriod, Name);
}
/// <summary>
/// Расчет потраченной суммы по декларации.
/// </summary>
/// <returns>Возвращает значение суммы, реально потраченной на услугу.</returns>
public double CalculateSpentValue()
{
return Convert.ToDouble(Spent.CorrectDouble())*Convert.ToDouble(Tariff.CorrectDouble());
}
}
}
| Java |
/*
* Copyright (C) 2013-2015 Uncharted Software Inc.
*
* Property of Uncharted(TM), formerly Oculus Info Inc.
* http://uncharted.software/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package influent.server.sql;
/**
* Represents a SQL FROM clause. This can be used to create complicated
* sub-selects that can still be chained together.
*
* @author cregnier
*
*/
public interface SQLFrom {
/**
* Sets the name of table to select results from.<br>
* This cannot be set if {@link #fromQuery(SQLSelect)} has also been set.
* @param name
* The name of an existing table in the database
* @return
*/
SQLFrom table(String name);
/**
* Adds an alias for the table.
* @param alias
* The name of the alias that will be used in the SQL statement.
* @return
*/
SQLFrom as(String alias);
/**
* Sets a subquery that should be used to select results from.<br>
* This cannot be set if {@link #table(String)} has also been set.
* @param fromQuery
* A subquery to select results from.
* @return
*/
SQLFrom fromQuery(SQLSelect fromQuery);
}
| Java |
# jekyll-theme-jtannerjones_com
Welcome to your new Jekyll theme! In this directory, you'll find the files you need to be able to package up your theme into a gem. Put your layouts in `_layouts`, your includes in `_includes` and your sass in `_sass`. To experiment with this code, add some sample content and run `bundle exec jekyll serve` – this directory is setup just like a Jekyll site!
TODO: Delete this and the text above, and describe your gem
## Installation
Add this line to your Jekyll site's `Gemfile`:
```ruby
gem "jekyll-theme-jtannerjones_com"
```
And add this line to your Jekyll site's `_config.yml`:
```yaml
theme: jekyll-theme-jtannerjones_com
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install jekyll-theme-jtannerjones_com
## Usage
TODO: Write usage instructions here. Describe your available layouts, includes, and/or sass.
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/hello. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## Development
To set up your environment to develop this theme, run `bundle install`.
Your theme is setup just like a normal Jekyll site! To test your theme, run `bundle exec jekyll serve` and open your browser at `http://localhost:4000`. This starts a Jekyll server using your theme. Add pages, documents, data, etc. like normal to test your theme's contents. As you make modifications to your theme and to your content, your site will regenerate and you should see the changes in the browser after a refresh, just like normal.
When your theme is released, only the files in `_layouts`, `_includes`, and `_sass` tracked with Git will be released.
## License
The theme is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
| Java |
module TinyMVC
class BaseModel
attr_reader :id
def initialize(options = {})
parameters = self.class.stored_parameters + [:id]
parameters.each do |attr|
instance_variable_set(:"@#{attr}", options[attr.to_s] || options[attr.to_sym])
end
end
def self.stored_parameters(*args)
return @stored_parameters if args.empty?
@stored_parameters = *args
@stored_parameters.freeze
attr_accessor *args
end
def self.all
raise NotImplementedError
end
def self.find(id)
raise NotImplementedError
end
def self.count
raise NotImplementedError
end
def self.create(options)
new(options).save
end
def self.delete_all
raise NotImplementedError
end
# should generate @id for new record and return self
def save
raise NotImplementedError
end
# should return self
def delete
raise NotImplementedError
end
def ==(obj)
self.class == obj.class && obj.id && self.id == obj.id
end
def new_record?
self.id.nil?
end
def attributes
parameters = self.class.stored_parameters + [:id]
parameters.reduce({}) do |hash, attr|
hash.merge(attr => instance_variable_get("@#{attr}"))
end
end
end
end
| Java |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>ReturnCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2015 The ReturnCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este é um programa experimental.
Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php.
Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Clique duas vezes para editar o endereço ou o rótulo</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Criar um novo endereço</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copie o endereço selecionado para a área de transferência</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your ReturnCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Copiar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Apagar o endereço selecionado da lista</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>E&liminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copiar &Rótulo</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgulas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de Frase-Passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Escreva a frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita a nova frase de segurança</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="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Escreva a nova frase de seguraça da sua carteira. <br/> Por favor, use uma frase de <b>10 ou mais caracteres aleatórios,</b> ou <b>oito ou mais palavras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encriptar carteira</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desencriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Alterar frase de segurança</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar encriptação da carteira</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 type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Tem a certeza que deseja encriptar a carteira?</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>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenção: A tecla Caps Lock está activa!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Carteira encriptada</translation>
</message>
<message>
<location line="-58"/>
<source>ReturnCoin 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>A encriptação da carteira falhou</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>As frases de segurança fornecidas não coincidem.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>O desbloqueio da carteira falhou</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>A desencriptação da carteira falhou</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>A frase de segurança da carteira foi alterada com êxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Assinar &mensagem...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando com a rede...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>Visã&o geral</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar visão geral da carteira</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transações</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Navegar pelo histórico de transações</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>Fec&har</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sair da aplicação</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Sobre &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar informação sobre Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opções...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>E&ncriptar Carteira...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Guardar Carteira...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Mudar &Palavra-passe...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Faça uma cópia de segurança da carteira para outra localização</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>Janela de &depuração</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir consola de diagnóstico e depuração</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verificar mensagem...</translation>
</message>
<message>
<location line="-202"/>
<source>ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+180"/>
<source>&About ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar / Ocultar</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Ficheiro</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>Con&figurações</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>A&juda</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Barra de separadores</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[rede de testes]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>ReturnCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to ReturnCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation 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 numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About ReturnCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about ReturnCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Atualizado</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transação enviada</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transação recebida</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Quantia: %2
Tipo: %3
Endereço: %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 ReturnCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>desbloqueada</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>bloqueada</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. ReturnCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Alerta da Rede</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>Quantidade:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Saída Baixa:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>não</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Depois de taxas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Troco:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(des)seleccionar todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo de árvore</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmados</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridade</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Taxa de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Taxa depois de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Prioridade de Cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>o maior</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>médio-alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>médio</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>baixo-médio</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>baixo</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>O mais baixo</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>sim</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 type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(Sem rótulo)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Alteração de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(Alteração)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Rótulo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>E&ndereço</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="+20"/>
<source>New receiving address</source>
<translation>Novo endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Novo endereço de saída</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar endereço de saída</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid ReturnCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossível desbloquear carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Falha ao gerar nova chave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>returncoin-qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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>Opções</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</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>Pagar &taxa de transação</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 ReturnCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start ReturnCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Rede</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the ReturnCoin 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>Mapear porta usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the ReturnCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP do proxy:</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>&Porta:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Porta do proxy (p.ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versão SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versão do proxy SOCKS (p.ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Janela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar para a bandeja e não para a barra de ferramentas</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>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar ao fechar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>Vis&ualização</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Linguagem da interface de utilizador:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting ReturnCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidade a usar em quantias:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show ReturnCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Mostrar en&dereços na lista de transações</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Escolha para mostrar funcionalidades de controlo "coin" ou não.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>padrão</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting ReturnCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>O endereço de proxy introduzido é inválido. </translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulário</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the ReturnCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>O seu saldo disponível para gastar</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Imaturo:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>O saldo minado ainda não maturou</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>O seu saldo total actual</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transações recentes</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<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="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>fora de sincronia</translation>
</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 type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nome do Cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versão do Cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informação</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Usando versão OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Tempo de início</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de ligações</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadeia de blocos</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Total estimado de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tempo do último bloco</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the returncoin-qt help message to get a list with possible ReturnCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Data de construção</translation>
</message>
<message>
<location line="-104"/>
<source>ReturnCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>ReturnCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Ficheiro de registo de depuração</translation>
</message>
<message>
<location line="+7"/>
<source>Open the ReturnCoin 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>Limpar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the ReturnCoin 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>Use as setas para cima e para baixo para navegar no histórico e <b>Ctrl-L</b> para limpar o ecrã.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Digite <b>help</b> para visualizar os comandos disponíveis.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Funcionalidades de Coin Controlo:</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>Selecção automática</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fundos insuficientes!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Quantidade:</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>Quantia:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Output Baixo:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Depois de taxas:</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>Enviar para múltiplos destinatários de uma vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Adicionar &Destinatário</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Limpar Tudo</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirme ação de envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a ReturnCoin address (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Taxa de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Taxa depois de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Prioridade de Cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirme envio de moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>O endereço de destino não é válido, por favor verifique.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>A quantia a pagar deverá ser maior que 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>A quantia excede o seu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</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="+251"/>
<source>WARNING: Invalid ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(Sem rótulo)</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>Qu&antia:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar A:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>Rótu&lo:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</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>Cole endereço da área de transferência</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 type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a ReturnCoin address (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</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>Assinaturas - Assinar / Verificar uma Mensagem</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>A&ssinar Mensagem</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>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</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>Cole endereço da área de transferência</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>Escreva aqui a mensagem que deseja assinar</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar a assinatura actual para a área de transferência</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Repôr todos os campos de assinatura de mensagem</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpar &Tudo</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verificar Mensagem</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>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified ReturnCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Repôr todos os campos de verificação de mensagem</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a ReturnCoin address (e.g. PXkRZYXwNDxsgvMmtE3M7rXJKDohbf54Pm)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Clique "Assinar mensagem" para gerar a assinatura</translation>
</message>
<message>
<location line="+3"/>
<source>Enter ReturnCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>O endereço introduzido é inválido. </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>Por favor verifique o endereço e tente de novo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>O endereço introduzido não refere a chave alguma.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>O desbloqueio da carteira foi cancelado.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>A chave privada para o endereço introduzido não está disponível.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Assinatura de mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensagem assinada.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>A assinatura não pôde ser descodificada.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Por favor verifique a assinatura e tente de novo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>A assinatura não condiz com o conteúdo da mensagem.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verificação da mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensagem verificada.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/desligado</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/não confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmações</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Origem</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gerado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>endereço próprio</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>rótulo</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>não aceite</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Taxa de transação</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Valor líquido</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentário</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID da Transação</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>Informação de depuração</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transação</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadeiro</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ainda não foi transmitida com sucesso</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>desconhecido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalhes da transação</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta janela mostra uma descrição detalhada da transação</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmada (%1 confirmações)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</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>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gerado mas não aceite</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Recebido com</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recebido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado para</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagamento ao próprio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/d)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e hora a que esta transação foi recebida.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Endereço de destino da transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantia retirada ou adicionada ao saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Todas</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoje</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mês</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mês passado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este ano</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Período...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recebida com</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviada para</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Para si</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Outras</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Escreva endereço ou rótulo a procurar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Quantia mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalhes da transação</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgula (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Quantia</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 type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Período:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>até</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>ReturnCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or returncoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Listar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obter ajuda para um comando</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Opções:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: ReturnCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: returncoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar pasta de dados</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 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="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manter no máximo <n> ligações a outros nós da rede (por defeito: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique o seu endereço público</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceitar comandos da consola e JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr o processo como um daemon e aceitar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utilizar a rede de testes - testnet</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong ReturnCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Opções de criação de bloco:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Apenas ligar ao(s) nó(s) especificado(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<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="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Armazenamento intermédio de recepção por ligação, <n>*1000 bytes (por defeito: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Armazenamento intermédio de envio por ligação, <n>*1000 bytes (por defeito: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Apenas ligar a nós na rede <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opções SSL: (ver a Wiki Bitcoin para instruções de configuração SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<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>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome de utilizador para ligações JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupta, recuperação falhou</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Palavra-passe para ligações JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=ReturnCoinrpc
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 "ReturnCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir ligações JSON-RPC do endereço IP especificado</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comandos para o nó a correr em <ip> (por defeito: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</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>Atualize a carteira para o formato mais recente</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Definir o tamanho da memória de chaves para <n> (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<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="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Chave privada do servidor (por defeito: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Esta mensagem de ajuda</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. ReturnCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Carregar endereços...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erro ao carregar wallet.dat: Carteira danificada</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of ReturnCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart ReturnCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erro ao carregar wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Endereço -proxy inválido: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rede desconhecida especificada em -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Versão desconhecida de proxy -socks requisitada: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Não conseguiu resolver endereço -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Não conseguiu resolver endereço -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Quantia inválida</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fundos insuficientes</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Carregar índice de blocos...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. ReturnCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Carregar carteira...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossível mudar a carteira para uma versão anterior</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossível escrever endereço por defeito</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexaminando...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Carregamento completo</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Para usar a opção %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Deverá definir rpcpassword=<password> no ficheiro de configuração:
%s
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation>
</message>
</context>
</TS> | Java |
//
// JavaInterfaceManager.h
// ChilliSource
// Created by Ian Copland on 08/08/2012.
//
// The MIT License (MIT)
//
// Copyright (c) 2012 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_ANDROID
#ifndef _CHILLISOURCE_PLATFORM_ANDROID_JAVAINTERFACE_JAVAINTERFACEMANAGER_H_
#define _CHILLISOURCE_PLATFORM_ANDROID_JAVAINTERFACE_JAVAINTERFACEMANAGER_H_
#include <CSBackend/Platform/Android/Main/JNI/ForwardDeclarations.h>
#include <CSBackend/Platform/Android/Main/JNI/Core/Java/JavaInterface.h>
#include <jni.h>
namespace CSBackend
{
namespace Android
{
//========================================================
/// Java Interface Manager
///
/// Handles all of the java interfaces and provides an
/// interface to access them.
///
/// This is deprecated in favour of JavaClass and
/// JavaVirtualMachine
//========================================================
class JavaInterfaceManager
{
public:
//--------------------------------------------------------
/// Get Singleton Ptr
///
/// @return a pointer to the singleton instance.
//--------------------------------------------------------
static JavaInterfaceManager* GetSingletonPtr();
//--------------------------------------------------------
/// Get Singleton
///
/// @return a reference to the singleton instance.
//--------------------------------------------------------
static JavaInterfaceManager& GetSingleton();
//--------------------------------------------------------
/// Initialise
///
/// Initialises the Java Interface Manager
///
/// @param The JVM.
//--------------------------------------------------------
void Initialise(JavaVM* inpJavaVM);
//--------------------------------------------------------
/// Get Java VM
///
/// @return The Java VM.
//--------------------------------------------------------
JavaVM* GetJavaVM();
//--------------------------------------------------------
/// Get JNI Environment Ptr
///
/// returns the jni enviroment pointer for the current
/// thread. The value returned from this should NOT be stored
/// as global or member data, as this will break thread safety
///
/// @return returns a pointer to the jni environment.
//--------------------------------------------------------
JNIEnv* GetJNIEnvironmentPtr();
//--------------------------------------------------------
/// Add Java Interface
///
/// Adds a new Java Interface. This should be called on
/// creation of the system that uses the java interface.
///
/// @param The java interface.
//--------------------------------------------------------
void AddJavaInterface(IJavaInterfaceSPtr inpJavaInterface);
//--------------------------------------------------------
/// Get Java Interface
///
/// Looks for a java interface that implements the given interface.
///
/// @param The type ID of the java interface you wish to implement
/// @return Java Interface that implements the given interface or nullptr if none
//--------------------------------------------------------
IJavaInterfaceSPtr GetJavaInterface(ChilliSource::InterfaceIDType inInterfaceID);
//--------------------------------------------------------
/// Get Java Interface
///
/// Looks for a java interface that implements the given interface.
///
/// @return Java Interface that implements the given interface or nullptr if none
//--------------------------------------------------------
template <typename T> std::shared_ptr<T> GetJavaInterface();
//--------------------------------------------------------
/// Get Java Interface
///
/// Looks for a java interface that implements the given interface.
///
/// @return Java Interface that implements the given interface or nullptr if none
//--------------------------------------------------------
template <typename T, typename U> std::shared_ptr<T> GetJavaInterface();
//--------------------------------------------------------
/// Get Java Interfaces
///
/// Looks for Java Interfaces that implement the given interface
/// and fills an array with them.
///
/// @param The type ID of the Java Interface you wish to implement
/// @param OUT: The array of java interfaces.
//--------------------------------------------------------
void GetJavaInterfaces(ChilliSource::InterfaceIDType inInterfaceID, std::vector<IJavaInterfaceSPtr>& outJavaInterfaces);
//--------------------------------------------------------
/// Get Java Interfaces
///
/// Looks for Java Interfaces that implement the given interface
/// and fills an array with them.
///
/// @param OUT: The array of java interfaces.
//--------------------------------------------------------
template <typename T> void GetJavaInterfaces(std::vector<std::shared_ptr<T> >& outJavaInterfaces);
//--------------------------------------------------------
/// Destructor
//--------------------------------------------------------
~JavaInterfaceManager();
private:
//--------------------------------------------------------
/// Constructor
//--------------------------------------------------------
JavaInterfaceManager();
static JavaInterfaceManager* mpJavaInterfaceManagerSingleton;
std::vector<IJavaInterfaceSPtr> mJavaInterfaces;
JavaVM* mpJavaVM;
};
//========================================================
/// Templated Definitions
//========================================================
//--------------------------------------------------------
/// Get Java Interface
//--------------------------------------------------------
template <typename T> std::shared_ptr<T> JavaInterfaceManager::GetJavaInterface()
{
IJavaInterfaceSPtr pJavaInterface = GetJavaInterface(T::InterfaceID);
if (pJavaInterface != nullptr)
{
return std::static_pointer_cast<T>(pJavaInterface);
}
return std::shared_ptr<T>();
}
//--------------------------------------------------------
/// Get Java Interface
//--------------------------------------------------------
template <typename T, typename U> std::shared_ptr<T> JavaInterfaceManager::GetJavaInterface()
{
IJavaInterfaceSPtr pJavaInterface = GetJavaInterface(U::InterfaceID);
if (pJavaInterface != nullptr)
{
return std::static_pointer_cast<T>(pJavaInterface);
}
return std::shared_ptr<T>();
}
//--------------------------------------------------------
/// Get Java Interfaces
//--------------------------------------------------------
template <typename T> void JavaInterfaceManager::GetJavaInterfaces(std::vector<std::shared_ptr<T> >& outJavaInterfaces)
{
for (size_t nJavaInterface = 0; nJavaInterface < mJavaInterfaces.size(); nJavaInterface++)
{
if (mJavaInterfaces[nJavaInterface]->IsA(T::InterfaceID))
{
outJavaInterfaces.push_back(std::static_pointer_cast<T>(mJavaInterfaces[nJavaInterface]));
}
}
}
}
}
#endif
#endif
| Java |
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Oeuvre.
*
* @ORM\Table(name="oeuvre")
* @ORM\Entity(repositoryClass="App\Repository\OeuvreRepository")
*/
class Oeuvre
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="titre", type="string", length=100)
*/
private $titre;
/**
* @var string
*
* @ORM\Column(name="soustitre", type="string", length=100, nullable=true)
*/
private $sousTitre;
/**
* @var int
*
* @ORM\Column(name="annee", type="integer", nullable=true)
*/
private $annee;
/**
* @var int
*
* @ORM\Column(name="ageminimum", type="integer", nullable=true)
*/
private $ageMinimum;
/**
* @var Audience
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\Audience",
* inversedBy="oeuvres"
* )
*/
private $audience;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\Nationalite",
* inversedBy="oeuvres"
* )
*/
private $nationalites;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\Langue",
* inversedBy="oeuvres"
* )
*/
private $langues;
/**
* @var CategorieOeuvre
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\CategorieOeuvre",
* inversedBy="oeuvres"
* )
* @ORM\JoinColumn(name="categorieoeuvre_id", referencedColumnName="id")
*/
private $categorieOeuvre;
/**
* @var Collection
*
* @ORM\OneToMany(
* targetEntity="App\Entity\OeuvreCategorieArtiste",
* mappedBy="oeuvre"
* )
*/
private $oeuvreCategorieArtistes;
/**
* @var Partie
*
* @ORM\OneToOne(
* targetEntity="App\Entity\Partie",
* mappedBy="oeuvre"
* )
*/
private $partie;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\Support",
* inversedBy="oeuvres"
* )
*/
private $supports;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\GroupePrincipal",
* inversedBy="oeuvres"
* )
* @ORM\JoinTable(
* name="oeuvre_groupeprincipal",
* joinColumns={
* @ORM\JoinColumn(
* name="oeuvre_id",
* referencedColumnName="id"
* )
* },
* inverseJoinColumns={
* @ORM\JoinColumn(
* name="groupeprincipal_id",
* referencedColumnName="id"
* )
* }
* )
*/
private $groupesPrincipaux;
/**
* Constructeur.
*
* @param string|null $titre
* @param string|null $sousTitre
* @param int|null $annee
* @param int|null $ageMinimum
*/
public function __construct(
string $titre = null,
string $sousTitre = null,
int $annee = null,
int $ageMinimum = null
) {
$this->titre = $this->checkTitre($titre);
$this->sousTitre = $this->checkTitre($sousTitre);
$this->annee = $annee;
$this->ageMinimum = $ageMinimum;
$this->nationalites = new ArrayCollection();
$this->langues = new ArrayCollection();
$this->oeuvreCategorieArtistes = new ArrayCollection();
$this->supports = new ArrayCollection();
$this->groupesPrincipaux = new ArrayCollection();
}
/**
* Get id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Set titre.
*
* @param string $titre
*/
public function setTitre(?string $titre): void
{
$this->titre = $titre;
}
/**
* Get titre.
*
* @return string|null
*/
public function getTitre(): ?string
{
return $this->titre;
}
/**
* Set sousTitre.
*
* @param string|null $sousTitre
*/
public function setSousTitre(?string $sousTitre): void
{
$this->sousTitre = $sousTitre;
}
/**
* Get sousTitre.
*
* @return string
*/
public function getSousTitre(): ?string
{
return $this->sousTitre;
}
/**
* Set annee.
*
* @param int|null $annee
*/
public function setAnnee(?int $annee): void
{
$this->annee = $annee;
}
/**
* Get annee.
*
* @return int|null
*/
public function getAnnee(): ?int
{
return $this->annee;
}
/**
* Set ageMinimum.
*
* @param int|null $ageMinimum
*/
public function setAgeMinimum(?int $ageMinimum): void
{
$this->ageMinimum = $ageMinimum;
}
/**
* Get ageMinimum.
*
* @return int
*/
public function getAgeMinimum(): ?int
{
return $this->ageMinimum;
}
/**
* @param mixed $titre
* @param int $maxSize
*
* @return null|string
*/
public function checkTitre(?string $titre, $maxSize = 100): ?string
{
if (null !== $titre) {
$titre = trim($titre);
$titre = iconv_substr($titre, 0, $maxSize);
return trim($titre);
}
return null;
}
/**
* Set audience.
*
* @param Audience $audience
*/
public function setAudience(Audience $audience = null): void
{
$this->audience = $audience;
}
/**
* Get audience.
*
* @return Audience|null
*/
public function getAudience(): ?Audience
{
return $this->audience;
}
/**
* Add nationalite.
*
* @param Nationalite $nationalite
*/
public function addNationalite(Nationalite $nationalite): void
{
if (!$this->nationalites->contains($nationalite)) {
$this->nationalites[] = $nationalite;
$nationalite->addOeuvre($this);
}
}
/**
* Remove nationalite.
*
* @param Nationalite $nationalite
*/
public function removeNationalite(Nationalite $nationalite): void
{
if ($this->nationalites->contains($nationalite)) {
$this->nationalites->removeElement($nationalite);
$nationalite->removeOeuvre($this);
}
}
/**
* Get nationalites.
*
* @return Collection
*/
public function getNationalites(): Collection
{
return $this->nationalites;
}
/**
* Add langue.
*
* @param Langue $langue
*/
public function addLangue(Langue $langue): void
{
if (!$this->langues->contains($langue)) {
$this->langues[] = $langue;
$langue->addOeuvre($this);
}
}
/**
* Remove langue.
*
* @param Langue $langue
*/
public function removeLangue(Langue $langue): void
{
if ($this->langues->contains($langue)) {
$this->langues->removeElement($langue);
$langue->removeOeuvre($this);
}
}
/**
* Get langues.
*
* @return Collection
*/
public function getLangues(): Collection
{
return $this->langues;
}
/**
* Set categorieOeuvre.
*
* @param CategorieOeuvre $categorieOeuvre
*/
public function setCategorieOeuvre(
CategorieOeuvre $categorieOeuvre = null
): void {
$this->categorieOeuvre = $categorieOeuvre;
}
/**
* Get categorieOeuvre.
*
* @return CategorieOeuvre
*/
public function getCategorieOeuvre(): ?CategorieOeuvre
{
return $this->categorieOeuvre;
}
/**
* Remove oeuvreCategorieArtiste.
*
* @param OeuvreCategorieArtiste $oeuvreCategorieArtiste
*/
public function removeOeuvreCategorieArtiste(
OeuvreCategorieArtiste $oeuvreCategorieArtiste
): void {
if ($this->oeuvreCategorieArtistes->contains($oeuvreCategorieArtiste)) {
$this->oeuvreCategorieArtistes->removeElement($oeuvreCategorieArtiste);
}
$oeuvreCategorieArtiste->setOeuvre(null);
}
/**
* Add oeuvreCategorieArtiste.
*
* @param OeuvreCategorieArtiste $oeuvreCategorieArtiste
*/
public function addOeuvreCategorieArtiste(
OeuvreCategorieArtiste $oeuvreCategorieArtiste
): void {
if (!$this->oeuvreCategorieArtistes->contains($oeuvreCategorieArtiste)) {
$this->oeuvreCategorieArtistes[] = $oeuvreCategorieArtiste;
}
$oeuvreCategorieArtiste->setOeuvre($this);
}
/**
* Get oeuvreCategorieArtistes.
*
* @return Collection
*/
public function getOeuvreCategorieArtistes(): Collection
{
return $this->oeuvreCategorieArtistes;
}
/**
* Set partie.
*
* @param Partie|null $partie
*/
public function setPartie(Partie $partie = null): void
{
$this->partie = $partie;
}
/**
* Get partie.
*
* @return Partie|null
*/
public function getPartie(): ?Partie
{
return $this->partie;
}
/**
* Add support.
*
* @param Support $support
*/
public function addSupport(Support $support): void
{
if (!$this->supports->contains($support)) {
$this->supports[] = $support;
$support->addOeuvre($this);
}
}
/**
* Remove support.
*
* @param Support $support
*/
public function removeSupport(Support $support): void
{
if ($this->supports->contains($support)) {
$this->supports->removeElement($support);
$support->removeOeuvre($this);
}
}
/**
* Get supports.
*
* @return Collection
*/
public function getSupports(): Collection
{
return $this->supports;
}
/**
* Add groupePrincipal.
*
* @param GroupePrincipal $groupePrincipal
*/
public function addGroupePrincipal(GroupePrincipal $groupePrincipal): void
{
if (!$this->groupesPrincipaux->contains($groupePrincipal)) {
$this->groupesPrincipaux[] = $groupePrincipal;
$groupePrincipal->addOeuvre($this);
}
}
/**
* Remove groupePrincipal.
*
* @param GroupePrincipal $groupePrincipal
*/
public function removeGroupePrincipal(GroupePrincipal $groupePrincipal): void
{
if ($this->groupesPrincipaux->contains($groupePrincipal)) {
$this->groupesPrincipaux->removeElement($groupePrincipal);
$groupePrincipal->removeOeuvre($this);
}
}
/**
* Get groupesPrincipaux.
*
* @return Collection
*/
public function getGroupesPrincipaux(): Collection
{
return $this->groupesPrincipaux;
}
}
| Java |
<section>
<body>
<!-- Quick setting box starts -->
<div class="quick-slide hidden-xs"></div>
<div class="out-container">
<div class="outer">
<!-- Sidebar starts -->
<!-- Sidebar ends -->
<!-- Mainbar starts -->
<div class="mainbar">
<!-- Page heading starts -->
<div class="page-head">
<div class="container">
<div class="row">
<!-- Page heading -->
<div class="col-md-3 col-sm-6 col-xs-6">
<h2><i class="fa fa-desktop"></i>LAY</h2>
</div>
</div>
</div>
<!-- Page heading ends -->
<!-- Black block starts -->
<div class="blue-block">
<div class="page-title">
<h3 class="pull-left"><i class="fa fa-group"></i>Denuncias</h3>
<div class="clearfix"></div>
</div>
</div>
<!-- Black block ends -->
<!-- Content starts -->
<div class="container">
<div class="page-content">
<!-- Content starts -->
<div class="container">
<div class="page-content page-users">
<div class="page-tabs">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade active in" id="search">
<h3>Denuncias</h3>
<?php echo form_open('regidenu/registro_exitoso', array('class'=>'form-horizontal')); ?>
<h1>Inserción exitosa</h1>
</div>
</form>
<a href="<?php echo site_url('regidenu/buscar');?>" class="btn btn-danger">Aceptar</a>
<div class="well" align="center">
<!-- Advanced search Denuncia-->
</div>
<!-- Add new Denuncia -->
<div class="tab-pane fade" id="addnew">
</div>
<!--hasta aqui -->
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Content ends -->
</div>
<!-- Mainbar ends -->
<div class="clearfix"></div>
</div>
</div>
</body>
</section>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>nlocks</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">
</head>
<body bgcolor="white">
<div class="navbar"><a name="#navbar_top"></a><table width="100%" border="0" cellspacing="0" cellpadding="2" summary="navigation bar"><tr><td><a href="overview-summary.html" target="overviewFrame">Overview</a></td><td><a href="http://www.erlang.org/"><img src="erlang.png" align="right" border="0" alt="erlang logo"></a></td></tr></table></div>
<h1>nlocks</h1>
<p>Copyright © 2016 Guilherme Andrade</p>
<p><b>Version:</b> 1.1.2</p>
<p><b>Authors:</b> Guilherme Andrade (<a href="mailto:nlocks(at)gandrade(dot)net"><tt>nlocks(at)gandrade(dot)net</tt></a>).</p>
<p><code>nlocks</code>: Native spinlocks for Erlang</p>
<hr>
<p>An experiment on Erlang native spinlocks:
* Able to guarantee exclusive access to shared resources
* Not dependent on a single process (no flooded mailbox as a bottleneck)
* Able to deal with brutally killed processes that still held unreleased locks (more below)</p>
<pre lang="erlang">
Lock = nlocks:new(),
Transaction = fun() ->
io:format("hello from ~p at ~p~n", [self(), os:timestamp()]),
timer:sleep(100)
end,
[spawn(fun () -> nlocks:transaction(Lock, Transaction) end) || _ <- lists:seq(1, 4)].
% hello from <0.66.0> at {1465,509871,454813}
% hello from <0.69.0> at {1465,509871,555028}
% hello from <0.67.0> at {1465,509871,656021}
% hello from <0.68.0> at {1465,509871,757031}
</pre>
<h3><a name="Brutal_kills_and_unreleased_locks">Brutal kills and unreleased locks</a></h3><p>
Hackish solution. Other than setting up some sort of monitor in the Erlang land, I found no practical way to deal with these other than making use of _ownership_ objects, references to which should never leave the process under which they were created; the release therefore becomes dependent on the garbage collector calling their destructor, but this also makes it more convenient for regularly terminated processes that forget to clean up.</p>
<h3><a name="Ownership_objects">Ownership objects</a></h3>
<pre lang="c++">
struct Ownership {
ERL_NIF_TERM pid;
Lock** lockResource;
};
</pre>
<p>* They're created for lock acquisition in order to deal with the above problem
* They should never leave their owning process
* On successful acquisition, they link themselves to the lock and force it to live as long as they live
* They guarantee only the lock owner can release the lock
* No explicit destruction needed</p>
<h3><a name="Lock_objects">Lock objects</a></h3>
<pre lang="c++">
struct Lock {
std::atomic<Ownership*> ownership;
};
</pre>
<p>* They keep an atomic pointer either set to null (free) or to the ownership object's address (locked)
* Can be shared between local processes through messages, ETS tables, etc.
* No explicit destruction needed</p>
<h3><a name="The_spinning">The spinning</a></h3><p>
* It uses C++ 11 <a href="http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange">compare_exchange_weak</a>
* For each attempt, a new NIF call is scheduled; this brings some overhead to the table but it's crucial to play nice with the VM
* If the timeout is other than 'infinity', for each attempt it compares the deadline against the current <a href="http://en.cppreference.com/w/cpp/chrono/steady_clock">steady_clock</a> value; this feels excessive and might hurt performance.</p>
<h3><a name="Internal_metrics">Internal metrics</a></h3>
<pre lang="erlang">
% nlocks:info()
[{allocated_locks,2},
{allocated_ownerships,6},
{acquired_locks,1},
{contention,5}, % amount of processes attempting lock acquisition
{has_lockfree_counters,true},
{has_lockfree_ownership,true}]
</pre>
<hr>
<div class="navbar"><a name="#navbar_bottom"></a><table width="100%" border="0" cellspacing="0" cellpadding="2" summary="navigation bar"><tr><td><a href="overview-summary.html" target="overviewFrame">Overview</a></td><td><a href="http://www.erlang.org/"><img src="erlang.png" align="right" border="0" alt="erlang logo"></a></td></tr></table></div>
<p><i>Generated by EDoc, May 1 2017, 02:21:31.</i></p>
</body>
</html>
| Java |
---
layout: post
microblog: true
date: 2009-11-17 03:00 +0300
guid: http://desparoz.micro.blog/2009/11/17/t5805027465.html
---
For PADI Instructors in the US this is a BIG deal. RT @DiverWire: Boy Scouts announce new Scuba Diving Merit Badge [bit.ly/15pcnA](http://bit.ly/15pcnA)
| Java |
/*
* main.c
*
* Created on: 31 May 2016
* Author: ajuaristi <a@juaristi.eus>
*/
#include <stdio.h>
#include <signal.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/videodev2.h>
#include <sys/stat.h>
#include "utils.h"
#include "appbase.h"
#include "uvc.h"
#define DEFAULT_WAIT_TIME 5
int stop;
#define SHOULD_STOP(v) (stop = v)
#define IS_STOPPED() (stop)
static char *create_debug_filename()
{
#define COUNT_LIMIT 9
static unsigned int count = 0;
char filename_template[] = "picture";
size_t size = sizeof(filename_template) + 2;
char *filename = ec_malloc(size);
snprintf(filename, size, "%s.%d", filename_template, count++);
if (count > COUNT_LIMIT)
count = 0;
return filename;
#undef COUNT_LIMIT
}
static void write_to_disk(const unsigned char *data, size_t size)
{
FILE *f;
char *filename = create_debug_filename();
f = fopen(filename, "w");
if (f) {
fwrite(data, size, 1, f);
fclose(f);
fprintf(stderr, "DEBUG: Frame written to file '%s'\n", filename);
}
free(filename);
}
static void print_usage_and_exit(const char *name)
{
if (name) {
printf("Usage: %s [OPTIONS] <app name> <username> <password>\n"
"Options:\n"
" -w secs Sleep this amount of seconds between shots\n"
" -d Display debug messages\n"
" -s Take one single shot and exit\n"
" -j Convert frames to JPEG\n"
" -S Stream as fast as possible\n",
name);
}
exit(1);
}
static void sighandler(int s)
{
char *signame;
switch (s) {
case SIGINT:
signame = "SIGINT";
break;
case SIGQUIT:
signame = "SIGQUIT";
break;
case SIGTERM:
signame = "SIGTERM";
break;
case SIGABRT:
signame = "SIGABRT";
break;
case SIGTRAP:
signame = "SIGTRAP";
break;
default:
signame = NULL;
break;
}
if (signame)
fprintf(stderr, "Received %s. Exiting.", signame);
else
fprintf(stderr, "Received %d. Exiting.", s);
/* Stop! */
SHOULD_STOP(1);
}
static void do_stream(struct appbase *ab, bool jpeg)
{
struct camera *c;
c = uvc_open();
if (!c)
fatal("Could not find any camera for capturing pictures");
c->frame = uvc_alloc_frame(320, 240, V4L2_PIX_FMT_YUYV);
if (!c->frame)
fatal("Could not allocate enough memory for frames");
if (!uvc_init(c))
fatal("Could not start camera for streaming");
while (!IS_STOPPED() && uvc_capture_frame(c)) {
if (jpeg)
frame_convert_yuyv_to_jpeg(c->frame);
if (!appbase_push_frame(ab,
c->frame->frame_data, c->frame->frame_bytes_used,
&c->frame->capture_time)) {
fprintf(stderr, "ERROR: Could not capture frame\n");
break;
}
c->frame->frame_bytes_used = 0;
}
uvc_close(c);
}
void do_capture(struct appbase *ab, unsigned int wait_time, bool oneshot, bool jpeg, bool debug)
{
struct camera *c;
struct frame *f;
while (!IS_STOPPED()) {
c = uvc_open();
if (!c)
fatal("Could not find any camera for capturing pictures");
c->frame = uvc_alloc_frame(320, 240, V4L2_PIX_FMT_YUYV);
if (!c->frame)
fatal("Could not allocate enough memory for frames");
if (!uvc_init(c))
fatal("Could not start camera for streaming");
if (uvc_capture_frame(c)) {
f = c->frame;
if (jpeg)
frame_convert_yuyv_to_jpeg(f);
if (!appbase_push_frame(ab,
f->frame_data, f->frame_bytes_used,
&f->capture_time))
fprintf(stderr, "ERROR: Could not send frame\n");
if (debug)
write_to_disk(f->frame_data, f->frame_bytes_used);
memset(f->frame_data, 0, f->frame_size);
f->frame_bytes_used = 0;
} else {
fprintf(stderr, "ERROR: Could not capture frame\n");
}
uvc_close(c);
if (oneshot)
break;
/*
* sleep(3) should not interfere with our signal handlers,
* unless we're also handling SIGALRM
*/
sleep(wait_time);
}
}
int main(int argc, char **argv)
{
int opt;
char *endptr;
long int wait_time = DEFAULT_WAIT_TIME;
bool debug = false, oneshot = false, stream = false, jpeg = false;
struct sigaction sig;
struct appbase *ab;
/* Parse command-line options */
while ((opt = getopt(argc, argv, "w:dsSj")) != -1) {
switch (opt) {
case 'w':
wait_time = strtol(optarg, &endptr, 10);
if (*endptr || wait_time < 0)
print_usage_and_exit(argv[0]);
break;
case 'd':
debug = true;
break;
case 's':
oneshot = true;
break;
case 'S':
stream = true;
break;
case 'j':
jpeg = true;
break;
default:
print_usage_and_exit(argv[0]);
break;
}
}
/* Set signal handlers and set stop condition to zero */
SHOULD_STOP(0);
memset(&sig, 0, sizeof(sig));
sig.sa_handler = sighandler;
sig.sa_flags = SA_RESETHAND;
sigemptyset(&sig.sa_mask);
sigaction(SIGINT, &sig, NULL);
sigaction(SIGQUIT, &sig, NULL);
sigaction(SIGTERM, &sig, NULL);
sigaction(SIGABRT, &sig, NULL);
sigaction(SIGTRAP, &sig, NULL);
/* Set up Appbase handle
* We need the app name, username and password to build the REST URL, and these
* should came now as parameters. We expect optind to point us to the first one.
*/
if (argc - optind < 3)
print_usage_and_exit(argv[0]);
ab = appbase_open(
argv[optind], // app name
argv[optind + 1], // username
argv[optind + 2], // password
false); // streaming off
if (!ab)
fatal("Could not log into Appbase");
if (debug) {
appbase_enable_progress(ab, true);
appbase_enable_verbose(ab, true);
}
if (stream)
do_stream(ab, jpeg);
else
do_capture(ab, wait_time, oneshot, jpeg, debug);
appbase_close(ab);
return 0;
}
| Java |
<h1><%= title %></h1>
<div class="source_info">
<p><%= title %> description.</p>
</div>
<section class="source_section">
<h2><%= title %> section</h2>
<div class="source_example">
example code
</div>
</section> | Java |
# Alarm
Cordova + Polymer
| Java |
package builtins
import (
"fmt"
"net/mail"
"net/url"
"regexp"
"strings"
u "github.com/araddon/gou"
"github.com/mssola/user_agent"
"github.com/araddon/qlbridge/expr"
"github.com/araddon/qlbridge/value"
"github.com/araddon/qlbridge/vm"
)
var _ = u.EMPTY
// email a string, parses email and makes sure it is valid
//
// email("Bob <bob@bob.com>") => bob@bob.com, true
// email("Bob <bob>") => "", false
//
type Email struct{}
// Type string
func (m *Email) Type() value.ValueType { return value.StringType }
func (m *Email) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 args for Email(field) but got %s", n)
}
return emailEval, nil
}
func emailEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := args[0]
if val == nil || val.Nil() || val.Err() {
return nil, false
}
emailStr := ""
switch v := val.(type) {
case value.StringValue:
emailStr = v.ToString()
case value.Slice:
if v.Len() > 0 {
v1 := v.SliceValue()[0]
emailStr = v1.ToString()
}
}
if emailStr == "" {
return value.EmptyStringValue, false
}
if em, err := mail.ParseAddress(emailStr); err == nil {
return value.NewStringValue(strings.ToLower(em.Address)), true
}
return value.EmptyStringValue, false
}
// emailname a string, parses email
//
// emailname("Bob <bob@bob.com>") => Bob
//
type EmailName struct{}
// Type string
func (m *EmailName) Type() value.ValueType { return value.StringType }
func (m *EmailName) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for EmailName(fieldname) but got %s", n)
}
return emailNameEval, nil
}
func emailNameEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val, ok := value.ValueToString(args[0])
if !ok || val == "" {
return value.EmptyStringValue, false
}
if em, err := mail.ParseAddress(val); err == nil {
return value.NewStringValue(em.Name), true
}
return value.EmptyStringValue, false
}
// emaildomain parses email and returns domain
//
// emaildomain("Bob <bob@bob.com>") => bob.com
//
type EmailDomain struct{}
// Type string
func (m *EmailDomain) Type() value.ValueType { return value.StringType }
func (m *EmailDomain) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for EmailDomain(fieldname) but got %s", n)
}
return emailDomainEval, nil
}
func emailDomainEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val, ok := value.ValueToString(args[0])
if !ok || val == "" {
return value.EmptyStringValue, false
}
if em, err := mail.ParseAddress(strings.ToLower(val)); err == nil {
parts := strings.SplitN(strings.ToLower(em.Address), "@", 2)
if len(parts) == 2 {
return value.NewStringValue(parts[1]), true
}
}
return value.EmptyStringValue, false
}
// Domains Extract Domains from a Value, or Values (must be urlish), doesn't do much/any validation
//
// domains("http://www.lytics.io/index.html") => []string{"lytics.io"}
//
type Domains struct{}
// Type strings
func (m *Domains) Type() value.ValueType { return value.StringsType }
func (m *Domains) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) == 0 {
return nil, fmt.Errorf("Expected 1 or more args for Domains(arg, ...) but got %s", n)
}
return domainsEval, nil
}
func domainsEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
svals := value.NewStringsValue(make([]string, 0))
for _, val := range args {
switch v := val.(type) {
case value.StringValue:
svals.Append(v.Val())
case value.StringsValue:
for _, sv := range v.Val() {
svals.Append(sv)
}
}
}
// Since its empty, we will just re-use it
if svals.Len() == 0 {
return nil, false
}
// Now convert to domains
domains := value.NewStringsValue(make([]string, 0))
for _, val := range svals.Val() {
urlstr := strings.ToLower(val)
if len(urlstr) < 4 {
continue
}
// May not have an http prefix, if not assume it
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
if urlParsed, err := url.Parse(urlstr); err == nil {
parts := strings.Split(urlParsed.Host, ".")
if len(parts) > 2 {
parts = parts[len(parts)-2:]
}
if len(parts) > 0 {
domains.Append(strings.Join(parts, "."))
}
}
}
if domains.Len() == 0 {
return nil, false
}
return domains, true
}
// Extract Domain from a Value, or Values (must be urlish), doesn't do much/any validation.
// if input is a list of strings, only first is evaluated, for plural see domains()
//
// domain("http://www.lytics.io/index.html") => "lytics.io"
//
type Domain struct{}
// Type string
func (m *Domain) Type() value.ValueType { return value.StringType }
func (m *Domain) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for Domain(field) but got %s", n)
}
return domainEval, nil
}
func domainEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
urlstr := ""
switch itemT := args[0].(type) {
case value.StringValue:
urlstr = itemT.Val()
case value.StringsValue:
for _, sv := range itemT.Val() {
urlstr = sv
break
}
}
urlstr = strings.ToLower(urlstr)
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
if urlParsed, err := url.Parse(urlstr); err == nil && len(urlParsed.Host) > 2 {
parts := strings.Split(urlParsed.Host, ".")
if len(parts) > 2 {
parts = parts[len(parts)-2:]
}
if len(parts) > 0 {
return value.NewStringValue(strings.Join(parts, ".")), true
}
}
return value.EmptyStringValue, false
}
// Extract host from a String (must be urlish), doesn't do much/any validation
// In the event the value contains more than one input url, will ONLY evaluate first
//
// host("http://www.lytics.io/index.html") => www.lytics.io
//
type Host struct{}
// Type string
func (m *Host) Type() value.ValueType { return value.StringType }
func (m *Host) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for Host(field) but got %s", n)
}
return HostEval, nil
}
func HostEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
urlstr := strings.ToLower(val)
if len(urlstr) < 8 {
return value.EmptyStringValue, false
}
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
if urlParsed, err := url.Parse(urlstr); err == nil {
//u.Infof("url.parse: %#v", urlParsed)
return value.NewStringValue(urlParsed.Host), true
}
return value.EmptyStringValue, false
}
// Extract hosts from a Strings (must be urlish), doesn't do much/any validation
//
// hosts("http://www.lytics.io", "http://www.activate.lytics.io") => www.lytics.io, www.activate.lytics.io
//
type Hosts struct{}
// Type strings
func (m *Hosts) Type() value.ValueType { return value.StringsType }
func (m *Hosts) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) == 0 {
return nil, fmt.Errorf("Expected 1 or more args for Hosts() but got %s", n)
}
return HostsEval, nil
}
func HostsEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
vals := value.NewStringsValue(make([]string, 0))
for _, item := range args {
switch itemT := item.(type) {
case value.StringValue:
val := itemT.Val()
if len(val) > 0 {
vals.Append(itemT.Val())
}
case value.Slice:
for _, sv := range itemT.SliceValue() {
val := sv.ToString()
if len(val) > 0 {
vals.Append(val)
}
}
}
}
if vals.Len() == 0 {
return vals, false
}
hosts := value.NewStringsValue(make([]string, 0))
for _, val := range vals.Val() {
urlstr := strings.ToLower(val)
if len(urlstr) < 8 {
continue
}
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
if urlParsed, err := url.Parse(urlstr); err == nil {
//u.Infof("url.parse: %#v", urlParsed)
hosts.Append(urlParsed.Host)
}
}
if hosts.Len() == 0 {
return nil, false
}
return hosts, true
}
// url decode a string
//
// urldecode("http://www.lytics.io/index.html") => http://www.lytics.io
//
// In the event the value contains more than one input url, will ONLY evaluate first
//
type UrlDecode struct{}
// Type string
func (m *UrlDecode) Type() value.ValueType { return value.StringType }
func (m *UrlDecode) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for UrlDecode(field) but got %s", n)
}
return urlDecodeEval, nil
}
func urlDecodeEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
val, err := url.QueryUnescape(val)
return value.NewStringValue(val), err == nil
}
// UrlPath Extract url path from a String (must be urlish), doesn't do much/any validation
//
// path("http://www.lytics.io/blog/index.html") => blog/index.html
//
// In the event the value contains more than one input url, will ONLY evaluate first
//
type UrlPath struct{}
// Type string
func (m *UrlPath) Type() value.ValueType { return value.StringType }
func (m *UrlPath) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for UrlPath() but got %s", n)
}
return urlPathEval, nil
}
func urlPathEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
urlstr := strings.ToLower(val)
if len(urlstr) > 6 && !strings.Contains(urlstr[:5], "/") {
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
}
if urlParsed, err := url.Parse(urlstr); err == nil {
return value.NewStringValue(urlParsed.Path), true
}
return value.EmptyStringValue, false
}
// Qs Extract qs param from a string (must be url valid)
//
// qs("http://www.lytics.io/?utm_source=google","utm_source") => "google", true
//
type Qs struct{}
// Type string
func (m *Qs) Type() value.ValueType { return value.StringType }
func (m *Qs) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 2 {
return nil, fmt.Errorf("Expected 2 args for Qs(url, param) but got %s", n)
}
return qsEval, nil
}
func qsEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
urlstr := ""
switch itemT := args[0].(type) {
case value.StringValue:
urlstr = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
urlstr = itemT.SliceValue()[0].ToString()
}
if urlstr == "" {
return value.EmptyStringValue, false
}
qsParam, ok := value.ValueToString(args[1])
if !ok || qsParam == "" {
return value.EmptyStringValue, false
}
if len(urlstr) > 6 && !strings.Contains(urlstr[:5], "/") {
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
}
if urlParsed, err := url.Parse(urlstr); err == nil {
qsval := urlParsed.Query().Get(qsParam)
if len(qsval) > 0 {
return value.NewStringValue(qsval), true
}
}
return value.EmptyStringValue, false
}
// Qs Extract qs param from a string (must be url valid)
//
// qs("http://www.lytics.io/?utm_source=google","utm_source") => "google", true
//
type QsDeprecate struct{}
// Type string
func (m *QsDeprecate) Type() value.ValueType { return value.StringType }
func (m *QsDeprecate) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 2 {
return nil, fmt.Errorf("Expected 2 args for Qs(url, param) but got %s", n)
}
return qsDeprecateEval, nil
}
func qsDeprecateEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
urlstr := strings.ToLower(val)
keyVal, ok := value.ValueToString(args[1])
if !ok || keyVal == "" {
return value.EmptyStringValue, false
}
if len(urlstr) > 6 && !strings.Contains(urlstr[:5], "/") {
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
}
if urlParsed, err := url.Parse(urlstr); err == nil {
qsval := urlParsed.Query().Get(keyVal)
if len(qsval) > 0 {
return value.NewStringValue(qsval), true
}
}
return value.EmptyStringValue, false
}
// UrlMain remove the querystring and scheme from url
//
// urlmain("http://www.lytics.io/?utm_source=google") => "www.lytics.io/", true
//
type UrlMain struct{}
// Type string
func (m *UrlMain) Type() value.ValueType { return value.StringType }
func (m *UrlMain) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 arg for UrlMain() but got %s", n)
}
return urlMainEval, nil
}
func urlMainEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
if up, err := url.Parse(val); err == nil {
return value.NewStringValue(fmt.Sprintf("%s%s", up.Host, up.Path)), true
}
return value.EmptyStringValue, false
}
// UrlMinusQs removes a specific query parameter and its value from a url
//
// urlminusqs("http://www.lytics.io/?q1=google&q2=123", "q1") => "http://www.lytics.io/?q2=123", true
//
type UrlMinusQs struct{}
// Type string
func (m *UrlMinusQs) Type() value.ValueType { return value.StringType }
func (m *UrlMinusQs) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 2 {
return nil, fmt.Errorf("Expected 2 args for UrlMinusQs(url, qsparam) but got %s", n)
}
return urlMinusQsEval, nil
}
func urlMinusQsEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
urlstr := ""
switch itemT := args[0].(type) {
case value.StringValue:
urlstr = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
urlstr = itemT.SliceValue()[0].ToString()
}
if urlstr == "" {
return value.EmptyStringValue, false
}
if len(urlstr) > 6 && !strings.Contains(urlstr[:5], "/") {
if !strings.HasPrefix(urlstr, "http") {
urlstr = "http://" + urlstr
}
}
keyVal, ok := value.ValueToString(args[1])
if !ok || keyVal == "" {
return value.EmptyStringValue, false
}
if up, err := url.Parse(urlstr); err == nil {
qsval := up.Query()
_, ok := qsval[keyVal]
if !ok {
return value.NewStringValue(fmt.Sprintf("%s://%s%s?%s", up.Scheme, up.Host, up.Path, up.RawQuery)), true
}
qsval.Del(keyVal)
up.RawQuery = qsval.Encode()
if up.RawQuery == "" {
return value.NewStringValue(fmt.Sprintf("%s://%s%s", up.Scheme, up.Host, up.Path)), true
}
return value.NewStringValue(fmt.Sprintf("%s://%s%s?%s", up.Scheme, up.Host, up.Path, up.RawQuery)), true
}
return value.EmptyStringValue, false
}
// UrlWithQueryFunc strips a url and retains only url parameters that match
// the supplied regular expressions.
//
// url.matchqs(url, re1, re2, ...) => url_withoutqs
//
type UrlWithQuery struct{}
// Type string
func (m *UrlWithQuery) Type() value.ValueType { return value.StringType }
func (*UrlWithQuery) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) == 0 {
return nil, fmt.Errorf("Expected at least 1 args for urlwithqs(url, param, param2) but got %s", n)
}
if len(n.Args) == 1 {
return UrlWithQueryEval(nil), nil
}
// Memoize these compiled reg-expressions
include := make([]*regexp.Regexp, 0)
for _, n := range n.Args[1:] {
keyItem, ok := vm.Eval(nil, n)
if !ok {
return nil, fmt.Errorf("Could not evaluate %v", n)
}
keyVal, ok := value.ValueToString(keyItem)
if !ok || keyVal == "" {
return nil, fmt.Errorf("Could not convert %q to regex", n.String())
}
keyRegexp, err := regexp.Compile(keyVal)
if err != nil {
return nil, err
}
include = append(include, keyRegexp)
}
return UrlWithQueryEval(include), nil
}
// UrlWithQueryEval pass reg-expressions to match qs args.
// Must match one regexp or else the qs param is dropped.
func UrlWithQueryEval(include []*regexp.Regexp) expr.EvaluatorFunc {
return func(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
up, err := url.Parse(val)
if err != nil {
return value.EmptyStringValue, false
}
if len(args) == 1 {
return value.NewStringValue(fmt.Sprintf("%s%s", up.Host, up.Path)), true
}
oldvals := up.Query()
newvals := make(url.Values)
for k, v := range oldvals {
// include fields specified as arguments
for _, pattern := range include {
if pattern.MatchString(k) {
newvals[k] = v
break
}
}
}
up.RawQuery = newvals.Encode()
if up.RawQuery == "" {
return value.NewStringValue(fmt.Sprintf("%s%s", up.Host, up.Path)), true
}
return value.NewStringValue(fmt.Sprintf("%s%s?%s", up.Host, up.Path, up.RawQuery)), true
}
}
// UserAgent Extract user agent features
//
// useragent(user_agent_field,"mobile") => "true", true
//
type UserAgent struct{}
// Type string
func (m *UserAgent) Type() value.ValueType { return value.StringType }
func (m *UserAgent) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 2 {
return nil, fmt.Errorf("Expected 2 args for UserAgent(user_agent_field, feature) but got %s", n)
}
return userAgentEval, nil
}
func userAgentEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return value.EmptyStringValue, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return value.EmptyStringValue, false
}
/*
fmt.Printf("%v\n", ua.Mobile()) // => false
fmt.Printf("%v\n", ua.Bot()) // => false
fmt.Printf("%v\n", ua.Mozilla()) // => "5.0"
fmt.Printf("%v\n", ua.Platform()) // => "X11"
fmt.Printf("%v\n", ua.OS()) // => "Linux x86_64"
name, version := ua.Engine()
fmt.Printf("%v\n", name) // => "AppleWebKit"
fmt.Printf("%v\n", version) // => "537.11"
name, version = ua.Browser()
fmt.Printf("%v\n", name) // => "Chrome"
fmt.Printf("%v\n", version) // => "23.0.1271.97"
// Let's see an example with a bot.
ua.Parse("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
fmt.Printf("%v\n", ua.Bot()) // => true
name, version = ua.Browser()
fmt.Printf("%v\n", name) // => Googlebot
fmt.Printf("%v\n", version) // => 2.1
*/
method, ok := value.ValueToString(args[1])
if !ok || method == "" {
return value.EmptyStringValue, false
}
ua := user_agent.New(val)
switch strings.ToLower(method) {
case "bot":
return value.NewStringValue(fmt.Sprintf("%v", ua.Bot())), true
case "mobile":
return value.NewStringValue(fmt.Sprintf("%v", ua.Mobile())), true
case "mozilla":
return value.NewStringValue(ua.Mozilla()), true
case "platform":
return value.NewStringValue(ua.Platform()), true
case "os":
return value.NewStringValue(ua.OS()), true
case "engine":
name, _ := ua.Engine()
return value.NewStringValue(name), true
case "engine_version":
_, version := ua.Engine()
return value.NewStringValue(version), true
case "browser":
name, _ := ua.Browser()
return value.NewStringValue(name), true
case "browser_version":
_, version := ua.Browser()
return value.NewStringValue(version), true
}
return value.EmptyStringValue, false
}
// UserAgentMap Extract user agent features
//
// useragent.map(user_agent_field) => {"mobile": "false","platform":"X11"}, true
//
type UserAgentMap struct{}
// Type MapString
func (m *UserAgentMap) Type() value.ValueType { return value.MapStringType }
func (m *UserAgentMap) Validate(n *expr.FuncNode) (expr.EvaluatorFunc, error) {
if len(n.Args) != 1 {
return nil, fmt.Errorf("Expected 1 args for useragentmap(user_agent) but got %s", n)
}
return userAgentMapEval, nil
}
func userAgentMapEval(ctx expr.EvalContext, args []value.Value) (value.Value, bool) {
val := ""
switch itemT := args[0].(type) {
case value.StringValue:
val = itemT.Val()
case value.Slice:
if itemT.Len() == 0 {
return nil, false
}
val = itemT.SliceValue()[0].ToString()
}
if val == "" {
return nil, false
}
/*
fmt.Printf("%v\n", ua.Mobile()) // => false
fmt.Printf("%v\n", ua.Bot()) // => false
fmt.Printf("%v\n", ua.Mozilla()) // => "5.0"
fmt.Printf("%v\n", ua.Platform()) // => "X11"
fmt.Printf("%v\n", ua.OS()) // => "Linux x86_64"
name, version := ua.Engine()
fmt.Printf("%v\n", name) // => "AppleWebKit"
fmt.Printf("%v\n", version) // => "537.11"
name, version = ua.Browser()
fmt.Printf("%v\n", name) // => "Chrome"
fmt.Printf("%v\n", version) // => "23.0.1271.97"
// Let's see an example with a bot.
ua.Parse("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
fmt.Printf("%v\n", ua.Bot()) // => true
name, version = ua.Browser()
fmt.Printf("%v\n", name) // => Googlebot
fmt.Printf("%v\n", version) // => 2.1
*/
ua := user_agent.New(val)
out := make(map[string]string)
out["bot"] = fmt.Sprintf("%v", ua.Bot())
out["mobile"] = fmt.Sprintf("%v", ua.Mobile())
out["mozilla"] = ua.Mozilla()
out["platform"] = ua.Platform()
out["os"] = ua.OS()
name, version := ua.Engine()
out["engine"] = name
out["engine_version"] = version
name, version = ua.Browser()
out["browser"] = name
out["browser_version"] = version
return value.NewMapStringValue(out), true
}
| Java |
#include <QWebView>
#include "helpdialog.h"
/**
* Constructor of Help Dialog
*/
HelpDialog::HelpDialog(QWidget *parent) : QWebPage(parent) {
view = new QWebView();
}
/**
* Shows the help dialog
*/
void HelpDialog::showHelpDialog() {
createWindow(QWebPage::WebModalDialog);
view->setPage(this);
view->setWindowIcon(QIcon(":/images/help-icon.png"));
view->setWindowTitle("Othello FPG - Help");
view->load(QUrl("qrc:/html/index.html"));
view->show();
}
| Java |
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (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) subClass.__proto__ = superClass; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
exports.alts = alts;
exports.timeout = timeout;
exports.pipelineAsync = pipelineAsync;
// Enforces order resolution on resulting channel
// This might need to be the default behavior, though that requires more thought
exports.order = order;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _channelsJs = require("./channels.js");
var Channel = _channelsJs.Channel;
var Transactor = _channelsJs.Transactor;
var AltsTransactor = (function (_Transactor) {
function AltsTransactor(offer, commitCb) {
_classCallCheck(this, AltsTransactor);
_get(Object.getPrototypeOf(AltsTransactor.prototype), "constructor", this).call(this, offer);
this.commitCb = commitCb;
}
_inherits(AltsTransactor, _Transactor);
_createClass(AltsTransactor, {
commit: {
value: function commit() {
this.commitCb();
return _get(Object.getPrototypeOf(AltsTransactor.prototype), "commit", this).call(this);
}
}
});
return AltsTransactor;
})(Transactor);
function alts(race) {
var outCh = new Channel();
var transactors = race.map(function (cmd) {
var tx = undefined;
if (Array.isArray(cmd)) {
var _cmd;
(function () {
_cmd = _slicedToArray(cmd, 2);
var ch = _cmd[0];
var val = _cmd[1];
tx = new AltsTransactor(val, function () {
transactors.forEach(function (h) {
return h.active = false;
});
});
ch.fill(val, tx).deref(function () {
outCh.fill([val, ch]).deref(function () {
return outCh.close();
});
});
})();
} else {
tx = new AltsTransactor(true, function () {
transactors.forEach(function (h) {
return h.active = false;
});
});
cmd.drain(tx).deref(function (val) {
outCh.fill([val, cmd]).deref(function () {
return outCh.close();
});
});
}
return tx;
});
return outCh;
}
function timeout(ms) {
var ch = new Channel();
setTimeout(function () {
ch.close();
}, ms);
return ch;
}
function pipelineAsync(inch, converter, outch) {
var shouldCloseDownstream = arguments[3] === undefined ? false : arguments[3];
function take(val) {
if (val !== null) {
Promise.resolve(converter(val)).then(function (converted) {
outch.put(converted).then(function (didPut) {
if (didPut) {
inch.take().then(take);
}
});
});
} else if (shouldCloseDownstream) {
outch.close();
}
}
inch.take().then(take);
}
function order(inch, sizeOrBuf) {
var outch = new Channel(sizeOrBuf);
function drain() {
inch.take().then(function (val) {
if (val === null) {
outch.close();
} else {
outch.put(val).then(drain);
}
});
}
drain();
return outch;
}
//# sourceMappingURL=utils.js.map | Java |
//estrutura com os dados lidos
struct {
float tensao;
float corrente;
float temperaturaBaterias;
float temperaturaCockpit;
float velocidade; //velocidade calculada do carro
double hodometro; //armazena a quantidade de metros percorridos
} dados;
//estrutura com as configuracoes do controlador
struct {
long intervaloLeitura; //intervalo de leitura dos sensores
float raioRoda; // raio da roda em mm
byte qtdPulsos; // pulsos por volta recebidos pelo sensor de velocidade
} cfg;
void enviar(String cod, String msg) {
Serial.println(" {\"" + cod + "\":\"" + msg + "\"}");
}
/*
* Funcao de regressao linear com com valores em ponto flutuante
*/
float converte(float x, float in_min, float in_max, float out_min,
float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
const int chipSelect = 10;
/*
Abre cartao de memoria
*/
boolean abreCartao(boolean forcar) {
static boolean cartaoOK = false;
if (!cartaoOK || forcar) {
cartaoOK = SD.begin(chipSelect);
if (!cartaoOK) {
enviar("20", "Erro ao abrir o cartao SD!");
}
}
return cartaoOK;
}
| Java |
<?php
namespace Wallabag\Bundle\CoreBundle\Entity;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
/**
* Entry
*
* @ORM\Entity
*/
class Entry
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(type="text")
* @Expose
* @Groups({"entries"})
*/
private $url;
/**
* @var string
*
* @ORM\Column(type="text")
* @Expose
* @Groups({"entries"})
*/
private $title;
/**
* @var string
*
* @ORM\Column(type="text")
* @Expose
* @Groups({"entries"})
*/
private $content;
/**
* @var User
*
* @ORM\OneToOne(targetEntity="Wallabag\Bundle\CoreBundle\Entity\User")
*/
private $user;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
* @Expose
* @Groups({"entries"})
*/
private $createdAt;
/**
* @var ArrayCollection
* @ORM\ManyToMany(targetEntity="Wallabag\Bundle\CoreBundle\Entity\Tag")
* @Expose
* @Groups({"entries"})
*/
private $tags;
/**
* @var boolean
* @ORM\Column(type="boolean")
* @Expose
* @Groups({"entries"})
*/
private $archived = false;
/**
* @var boolean
* @ORM\Column(type="boolean")
* @Expose
* @Groups({"entries"})
*/
private $deleted = false;
/**
* @var boolean
* @ORM\Column(type="boolean")
* @Expose
* @Groups({"entries"})
*/
private $starred = false;
public function __construct()
{
$this->tags = new ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* @param string $url
* @return Entry
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set title
*
* @param string $title
* @return Entry
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set content
*
* @param string $content
* @return Entry
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return self
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime $createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add tag
*
* @param \Wallabag\Bundle\CoreBundle\Entiy\Tag $tag
*/
public function addTag(\Wallabag\Bundle\CoreBundle\Entiy\Tag $tag)
{
$this->tags[] = $tag;
}
/**
* Remove tag
*
* @param \Wallabag\Bundle\CoreBundle\Entiy\Tag $tag
*/
public function removeTag(\Wallabag\Bundle\CoreBundle\Entiy\Tag $tag)
{
$this->tags->removeElement($tag);
}
public function flushTags() {
$this->tags->clear();
}
/**
* Get tags
*
* @return Tag[] $tags
*/
public function getTags()
{
return $this->tags;
}
/**
* Set archived
*
* @param boolean $archived
* @return self
*/
public function setArchived($archived)
{
$this->archived = $archived;
return $this;
}
/**
* Get archived
*
* @return boolean $archived
*/
public function getArchived()
{
return $this->archived;
}
/**
* Set deleted
*
* @param boolean $deleted
* @return self
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* @return boolean $deleted
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set starred
*
* @param boolean $starred
* @return self
*/
public function setStarred($starred)
{
$this->starred = $starred;
return $this;
}
/**
* Get starred
*
* @return boolean $starred
*/
public function getStarred()
{
return $this->starred;
}
/**
* Set user
*
* @param User $user
* @return self
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return User $user
*/
public function getUser()
{
return $this->user;
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace CommonHelperLibrary.WEB
{
/// <summary>
/// Author : Hans.Huang
/// Date : 2012-12-03
/// Class : HttpWebDealer
/// Discription : Helper class for dealer with the http website
/// </summary>
public class HttpWebDealer
{
protected static LoggerHelper Logger = LoggerHelper.Instance;
#region GetHtml
/// <summary>
/// Get Html text by URL
/// I can't tell the encoding of page,So give me the encodeing best
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">http request headers</param>
/// <param name="txtEncoding">The Encoding suggest of webpage</param>
/// <returns></returns>
public static string GetHtml(string url, WebHeaderCollection headers = null, Encoding txtEncoding = null)
{
var html = "";
if (string.IsNullOrWhiteSpace(url)) return html;
var response = GetResponseByUrl(url,headers);
html = HttpWebDealerBase.GetHtmlFromResponse(response, txtEncoding);
return html;
}
#endregion
#region GetJsonObject
/// <summary>
/// Get Dynamic Object (json)
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">http request headers</param>
/// <param name="txtEncoding">The Encoding suggest of response</param>
/// <returns></returns>
public static dynamic GetJsonObject(string url,WebHeaderCollection headers = null, Encoding txtEncoding = null)
{
var json = GetHtml(url, headers, txtEncoding);
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Deserialize<dynamic>(json);
}
#endregion
#region DownloadFile
/// <summary>
/// Get file by HttpWebRequest and save it(Just for Small files those's content length less then 65K)
/// </summary>
/// <param name="fileName">File Name to save as</param>
/// <param name="url">URL</param>
/// <param name="path">The path to save the file</param>
/// <param name="timeout">Request timeout</param>
/// <param name="headers">http request header</param>
/// <returns>Success:Ture</returns>
public static bool DownloadFile(string fileName, string url, string path, int timeout, WebHeaderCollection headers = null)
{
var response = GetResponseByUrl(url, headers, timeout);
var stream = response.GetResponseStream();
if (stream == null) return false;
using (var bReader = new BinaryReader(stream))
{
var length = Int32.Parse(response.ContentLength.ToString(CultureInfo.InvariantCulture));
var byteArr = new byte[length];
//stream.Read(byteArr, 0, length);
bReader.Read(byteArr, 0, length);
//if (File.Exists(path + fileName)) File.Delete(path + fileName);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var fs = File.Create(path +"\\"+ fileName);
fs.Write(byteArr, 0, length);
fs.Close();
}
return true;
}
/// <summary>
/// Get file by WebClient method
/// </summary>
/// <param name="fileName">File name to save</param>
/// <param name="url">file url to download</param>
/// <param name="path">file path to save</param>
/// <param name="monitor">Monitor action for download progress</param>
/// <returns></returns>
public static bool DownloadFile(string fileName, string url, string path,
DownloadProgressChangedEventHandler monitor = null)
{
if (string.IsNullOrWhiteSpace(url)) return false;
if (!path.EndsWith("\\")) path += "\\";
using (var wc = new WebClient())
{
//if (File.Exists(path +"\\"+ fileName)) File.Delete(path +"\\"+ fileName);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (monitor != null)
wc.DownloadProgressChanged += monitor;
wc.DownloadFileAsync(new Uri(url), path + fileName);
}
return true;
}
/// <summary>
/// Download largest file from url list
/// </summary>
/// <param name="fileName">File name to save</param>
/// <param name="urls">file url list to download</param>
/// <param name="path">file path to save</param>
/// <param name="monitor">Monitor action for download progress</param>
/// <returns>File Length</returns>
public static long DownloadLargestFile(string fileName, List<string> urls, string path,
DownloadProgressChangedEventHandler monitor = null)
{
if (urls == null || urls.Count == 0) return 0;
var results = new Dictionary<string, long>();
var signals = new List<EventWaitHandle>();
var locker = new object();
foreach (var url in urls)
{
var signal = new EventWaitHandle(true, EventResetMode.ManualReset);
signals.Add(signal);
var str = url;
signal.Reset();
Task.Run(() =>
{
var rsponse = GetResponseByUrl(str, null, 3000);
if (rsponse == null) return;
lock (locker)
{
results.Add(str, rsponse.ContentLength);
}
signal.Set();
});
}
signals.ForEach(s => s.WaitOne(3000));
var largest = new KeyValuePair<string, long>(string.Empty, 0);
foreach (var res in results)
{
if (res.Value > largest.Value) largest = res;
}
return DownloadFile(fileName, largest.Key, path, monitor) ? largest.Value : 0;
}
#endregion
#region GetResponseByUrl
/// <summary>
/// Get response by url
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">Request headers</param>
/// <param name="requestTimeout">Request timeout(Set to 0 for no limit)</param>
/// <returns></returns>
public static HttpWebResponse GetResponseByUrl(string url, WebHeaderCollection headers = null, int requestTimeout = 0)
{
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
if (requestTimeout > 0) request.Timeout = requestTimeout;
string postData;
HttpWebDealerBase.CorrectHeader(request, headers, out postData);
for (var i = 0; i < 3; i++)
{
try
{
HttpWebDealerBase.TryPostData(request, postData);
response = (HttpWebResponse)request.GetResponse();
return response;
}
catch (Exception e)
{
Logger.Msg("Error", url);
Logger.Exception(e);
}
Thread.Sleep(200);
}
return response;
}
#endregion
/// <summary>
/// Detects the byte order mark of a file and returns an appropriate encoding for the file.
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static Encoding GetEncoding(Stream stream)
{
// Use Default of Encoding.Default (Ansi CodePage)
var enc = Encoding.Default;
// Detect byte order mark if any - otherwise assume default
//var simple = new MemoryStream();
//stream.CopyTo(simple, 5);
var buffer = new byte[5];
stream.Read(buffer, 0, 5);
if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
enc = Encoding.UTF8;
else if (buffer[0] == 0xfe && buffer[1] == 0xff)
enc = Encoding.Unicode;
else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
enc = Encoding.UTF32;
else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
enc = Encoding.UTF7;
//simple.Close();
return enc;
}
}
}
| Java |
// Endless Online Bot v0.0.1
#ifndef UTIL_HPP_INCLUDED
#define UTIL_HPP_INCLUDED
#include <math.h>
#include <vector>
#include <string>
int path_length(int x1, int y1, int x2, int y2);
std::vector<std::string> Args(std::string str);
std::string Lowercase(std::string str);
#endif // UTIL_HPP_INCLUDED
| Java |
const mutations = {
SET_ACTIVE_TAB(state, tab){
state.activeTab = tab;
},
SET_DATA_ACTIVE_TAB(state, tab){
state.hubActiveTab = tab;
},
SET_PROXY_STATE(state, proxy){
state.proxy_switch = proxy;
},
SET_INIT_INFO(state, info){
_.extend(state, info);
}
};
export default mutations;
| Java |
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("TestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestApp")]
[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("207e9870-0b01-4db3-b656-c4f296d939af")]
// 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")]
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=Shift_JIS" />
<meta name="keywords" content="L[[h" />
<meta name="description" content="Ðî¶" />
<title>z[y[WE^Cg</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<!-- C -->
<div id="main">
<!-- wb_[ -->
<div id="header">
<h1>evl[g»ì ®ïÐÌz[y[WÅ·B</h1>
<table border="0" cellpadding="0" cellspacing="0" width="800">
<tr>
<td><div id="table-left"><h2><a href="#"><img src="img/logo.gif" alt="TCgE^Cg" border="0" /></a></h2></div></td>
<td><div id="table-right"><b>00-0000-0000</b><br /><img src="img/icon.gif" alt="icon" border="0" /> <a href="link.html">N</a>@<img src="img/icon.gif" alt="icon" border="0" /> <a href="contact.html">¨â¢í¹</a></div></td>
</tr>
</table>
</div>
<div id="header-menu">
<ul>
<li><a href="index.html">HOME</a></li>
<li><a href="service.html">T[rXj
[</a></li>
<li><a href="menu.html">¿àÉ¢Ä</a></li>
<li><a href="#">¨ql̺</a></li>
<li><a href="#">æ é¿â</a></li>
<li><a href="#">ANZXîñ</a></li>
<li><a href="sitemap.html">TCg}bv</a></li>
<li><a href="contact.html">¨â¢í¹</a></li>
</ul>
</div>
<center>
<img src="img/head_img_slim.jpg" alt="" class="photo01" border="0" />
</center>
<!-- wb_[Iíè -->
<!-- Rec -->
<!-- CRec -->
<div id="container">
<div id="contents">
<h2>T[rXEj
[ 1</h2>
<p>±¿çÉÍA¨XâïÐÌTCgÌêÍAá¦ÎAT[rXÌj
[ÈÇðLڵľ³¢BîñTCgÈÇAj
[Æ¢¤RecÍKvȢƢ¤êÍAÊÉy[Wð쬵ÄAucontents1.htmlvÈÇÌt@C¼Åy[WðìÁÄÝľ³¢B</p>
<h2>T[rXEj
[ 2</h2>
<p>©oµÌhtml^OÉ¢ÄÅ·ªAuh2vÆ¢¤^Oª©oµ^CgÌ^OÅ·B±Ìuh2vðRs[µÄgp·êÎA¢çÅà©oµÌ^Cgo[ðⷱƪūܷB</p>
<h2>T[rXEj
[ 3</h2>
<p>z[y[Wì¬\tgð²pÌÛÍA±Ì©oµªÌOãðRs[µÄAºÉ\èt¯ÅâµÄ¢Áľ³¢B</p>
</div>
<!-- CRecIíè -->
<!-- j
[ -->
<div id="menu">
<div class="menulist">
<h2>RecEj
[</h2>
<a href="index.html">HOME</a>
<a href="service.html">T[rXj
[</a>
<a href="menu.html">¿àÉ¢Ä</a>
<a href="#">æ 鲿â</a>
<a href="#">ANZXîñ</a>
<a href="link.html">N</a>
<a href="sitemap.html">TCg}bv</a>
<a href="contact.html">¨â¢í¹</a>
</div>
<div class="menu_free">
<h2>t[Xy[X</h2>
<p>á¦ÎAoi[æâAANZXîñÈÇÉpÅ«éXy[XÅ·B</p>
</div>
<div class="menulist">
<h2>¨ð§¿N</h2>
<a href="#">[}KW</a>
<a href="#">}CuO</a>
</div>
</div>
<!-- j
[Iíè -->
</div>
<!-- RecIíè -->
<!-- tb^[ -->
<div id="footer">
Copyright (C) 20XX SITE NAME All Rights Reserved.@design by <a href="http://tempnate.com/">tempnate</a>
</div>
<!-- tb^[Iíè -->
</div>
<!-- CIíè -->
</body>
</html>
| Java |
#!/usr/bin/python
#
# Config file test app (together with test.cfg file)
#
import os, sys
sys.path.append("..")
import configfile
cfg = configfile.ConfigFile("test.cfg")
cfg.setCfgValue("name1", "value1")
cfg.setCfgValue("name2", "value2")
cfg.selectSection("user")
cfg.setCfgValue("username", "janis")
cfg.setCfgValue("acceptable_names", ["john", "janis"])
cfg.load()
print cfg.cfg.options("main")
print cfg.cfg.options("user")
print cfg.getCfgValue("username")
print type(cfg.getCfgValue("username"))
print cfg.getCfgValueAsList("acceptable_names")
print cfg.getCfgValueAsList("list_in_list")
cfg.selectSection("main")
print cfg.getCfgValueAsInt("a_number")
print type(cfg.getCfgValueAsInt("a_number"))
print cfg.getCfgValueAsBool("a_bool")
print type(cfg.getCfgValueAsBool("a_bool"))
cfg.filename = "test-mod.cfg"
cfg.selectSection("main")
cfg.setCfgValue("name1", "value1mod2")
cfg.setCfgValue("a_number", 14)
cfg.selectSection("user")
cfg.setCfgValue("acceptable_names", ["john", "janis", "ivan"])
cfg.setCfgValue("list_in_list2", ["[baz]", "[foo, bar]"])
cfg.setCfgValue("list_in_list3", ["first", "[second-one, second-third]"])
cfg.save()
| Java |
# frozen_string_literal: true
require "dis/jobs/delete"
require "dis/jobs/store"
require "dis/jobs/change_type"
| Java |
<?php
namespace AppBundle\Security\Core\User;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
class FOSUBUserProvider extends BaseClass
{
/**
* {@inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
$property = $this->getProperty($response);
$username = $response->getUsername();
$previousUser = $this->userManager->findUserBy(array($property => $username));
var_dump(
$property,
$response->getProfilePicture(),
$response->getRealName(),
$response->getNickname(),
$response->getUsername(),
$previousUser
);
//on connect - get the access token and the user ID
$service = $response->getResourceOwner()->getName();
//we "disconnect" previously connected users
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username,'auth_type'=>$service))) {
$previousUser->setAccessToken($response->getAccessToken());
$this->userManager->updateUser($previousUser);
}
}
/**
* {@inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$service = $response->getResourceOwner()->getName();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username,'auth_type'=>$service));
//when the user is registrating
if (null === $user) {
$user = $this->userManager->createUser();
$user->setUid($username);
$user->setAccessToken($response->getAccessToken());
$user->setAuthType($service);
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($response->getRealName());
$user->setUsernameCanonical($username);
$user->setEmail($response->getEmail());
if($service=="facebook"){
$user->setPicture("https://graph.facebook.com/$username/picture");
}else{
$user->setPicture($response->getProfilePicture());
}
$user->setPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
//update access token
$user->setAccessToken($response->getAccessToken());
return $user;
}
} | Java |
<?php
namespace Db\User;
use Core\Query;
class GetUnconfirmedUsers extends Query
{
protected $id;
protected function build()
{
$query = '
SELECT
u.id,
u.type,
u.email,
u.email_confirmed,
u.email_confirmation_hash,
u.account_confirmed,
u.password,
u.language,
u.first_name,
u.last_name,
u.department,
IFNULL(u.portrait_file_id, cnfg.value) AS portrait_file_id,
u.created
FROM
users u
JOIN configs cnfg ON cnfg.key = \'default_portrait_id\'
WHERE
u.email_confirmed = 1
AND u.account_confirmed = 0';
return $query;
}
} | Java |
<?php
echo __DIR__;
require dirname(__DIR__) . "/HikerCommand.php";
function _manually_load_plugin() {
require dirname( __FILE__ ) . '/../hikerquotes.php';
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
require getenv( 'WP_TESTS_DIR' ) . '/includes/bootstrap.php';
| Java |
// home page
exports.index = function(req, res){
res.render('index', { title: 'B O X L A N D' });
}; | Java |
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
mean = require('meanio'),
consolidate = require('consolidate'),
mongoStore = require('connect-mongo')(express),
flash = require('connect-flash'),
helpers = require('view-helpers'),
config = require('./config'),
expressValidator = require('express-validator'),
appPath = process.cwd(),
fs = require('fs'),
assetmanager = require('assetmanager');
module.exports = function(app, passport, db) {
app.set('showStackError', true);
// Prettify HTML
app.locals.pretty = true;
// cache=memory or swig dies in NODE_ENV=production
app.locals.cache = 'memory';
// Should be placed before express.static
// To ensure that all assets and data are compressed (utilize bandwidth)
app.use(express.compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
// Levels are specified in a range of 0 to 9, where-as 0 is
// no compression and 9 is best compression, but slowest
level: 9
}));
// Only use logger for development environment
if (process.env.NODE_ENV === 'development') {
app.use(express.logger('dev'));
}
// assign the template engine to .html files
app.engine('html', consolidate[config.templateEngine]);
// set .html as the default extension
app.set('view engine', 'html');
// Set views path, template engine and default layout
app.set('views', config.root + '/server/views');
// Enable jsonp
app.enable('jsonp callback');
app.configure(function() {
// The cookieParser should be above session
app.use(express.cookieParser());
// Request body parsing middleware should be above methodOverride
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
app.use(express.methodOverride());
// Import your asset file
var assets = require('./assets.json');
assetmanager.init({
js: assets.js,
css: assets.css,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'public/public'
});
// Add assets to local variables
app.use(function(req, res, next) {
res.locals({
assets: assetmanager.assets
});
next();
});
// Express/Mongo session storage
app.use(express.session({
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// Dynamic helpers
app.use(helpers(config.app.name));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
//mean middleware from modules before routes
app.use(mean.chainware.before);
// Connect flash for flash messages
app.use(flash());
// Routes should be at the last
app.use(app.router);
// Setting the fav icon and static folder
app.use(express.favicon());
app.use('/public', express.static(config.root + '/public'));
app.get('/modules/aggregated.js', function(req, res) {
res.setHeader('content-type', 'text/javascript');
res.send(mean.aggregated.js);
});
app.get('/modules/aggregated.css', function(req, res) {
res.setHeader('content-type', 'text/css');
res.send(mean.aggregated.css);
});
mean.events.on('modulesFound', function() {
mean.modules.forEach(function(module) {
app.use('/' + module.name, express.static(config.root + '/node_modules/' + module.name + '/public'));
});
bootstrapRoutes();
//mean middlware from modules after routes
app.use(mean.chainware.after);
// Assume "not found" in the error msgs is a 404. this is somewhat
// silly, but valid, you can do whatever you like, set properties,
// use instanceof etc.
app.use(function(err, req, res, next) {
// Treat as 404
if (~err.message.indexOf('not found')) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
});
});
function bootstrapRoutes() {
var routes_path = appPath + '/server/routes';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(newPath)(app, passport);
}
// We skip the app/routes/middlewares directory as it is meant to be
// used and shared by routes as further middlewares and is not a
// route by itself
} else if (stat.isDirectory() && file !== 'middlewares') {
walk(newPath);
}
});
};
walk(routes_path);
}
}; | Java |
module Marty
module Promises
module Ruby
end
end
end
| Java |
package prometheusremotewrite
import (
"bytes"
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"strings"
"testing"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
func TestRemoteWriteSerialize(t *testing.T) {
tests := []struct {
name string
config FormatConfig
metric telegraf.Metric
expected []byte
}{
{
name: "simple",
metric: testutil.MustMetric(
"cpu",
map[string]string{
"host": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
expected: []byte(`
cpu_time_idle{host="example.org"} 42
`),
},
{
name: "prometheus input untyped",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Untyped,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input counter",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Counter,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input gauge",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Gauge,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input histogram no buckets",
metric: testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"http_request_duration_seconds_sum": 53423,
"http_request_duration_seconds_count": 144320,
},
time.Unix(0, 0),
telegraf.Histogram,
),
expected: []byte(`
http_request_duration_seconds_count 144320
http_request_duration_seconds_sum 53423
http_request_duration_seconds_bucket{le="+Inf"} 144320
`),
},
{
name: "prometheus input histogram only bucket",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"le": "0.5",
},
map[string]interface{}{
"http_request_duration_seconds_bucket": 129389.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
expected: []byte(`
http_request_duration_seconds_count 0
http_request_duration_seconds_sum 0
http_request_duration_seconds_bucket{le="+Inf"} 0
http_request_duration_seconds_bucket{le="0.5"} 129389
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := NewSerializer(FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: tt.config.StringHandling,
})
require.NoError(t, err)
data, err := s.Serialize(tt.metric)
actual, err := prompbToText(data)
require.NoError(t, err)
require.Equal(t, strings.TrimSpace(string(tt.expected)),
strings.TrimSpace(string(actual)))
})
}
}
func TestRemoteWriteSerializeBatch(t *testing.T) {
tests := []struct {
name string
config FormatConfig
metrics []telegraf.Metric
expected []byte
}{
{
name: "simple",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host": "one.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"host": "two.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host="one.example.org"} 42
cpu_time_idle{host="two.example.org"} 42
`),
},
{
name: "multiple metric families",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host": "one.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
"time_guest": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_guest{host="one.example.org"} 42
cpu_time_idle{host="one.example.org"} 42
`),
},
{
name: "histogram",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"http_request_duration_seconds_sum": 53423,
"http_request_duration_seconds_count": 144320,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.05"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 24054.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.1"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 33444.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.2"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 100392.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.5"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 129389.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "1.0"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 133988.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "+Inf"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 144320.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
},
expected: []byte(`
http_request_duration_seconds_count 144320
http_request_duration_seconds_sum 53423
http_request_duration_seconds_bucket{le="+Inf"} 144320
http_request_duration_seconds_bucket{le="0.05"} 24054
http_request_duration_seconds_bucket{le="0.1"} 33444
http_request_duration_seconds_bucket{le="0.2"} 100392
http_request_duration_seconds_bucket{le="0.5"} 129389
http_request_duration_seconds_bucket{le="1"} 133988
`),
},
{
name: "summary with quantile",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"rpc_duration_seconds_sum": 1.7560473e+07,
"rpc_duration_seconds_count": 2693,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.01"},
map[string]interface{}{
"rpc_duration_seconds": 3102.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.05"},
map[string]interface{}{
"rpc_duration_seconds": 3272.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.5"},
map[string]interface{}{
"rpc_duration_seconds": 4773.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.9"},
map[string]interface{}{
"rpc_duration_seconds": 9001.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.99"},
map[string]interface{}{
"rpc_duration_seconds": 76656.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
},
expected: []byte(`
rpc_duration_seconds_count 2693
rpc_duration_seconds_sum 17560473
rpc_duration_seconds{quantile="0.01"} 3102
rpc_duration_seconds{quantile="0.05"} 3272
rpc_duration_seconds{quantile="0.5"} 4773
rpc_duration_seconds{quantile="0.9"} 9001
rpc_duration_seconds{quantile="0.99"} 76656
`),
},
{
name: "newer sample",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 43.0,
},
time.Unix(1, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle 43
`),
},
{
name: "colons are not replaced in metric name from measurement",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu::xyzzy",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu::xyzzy_time_idle 42
`),
},
{
name: "colons are not replaced in metric name from field",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time:idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time:idle 42
`),
},
{
name: "invalid label",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host-name": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "colons are replaced in label name",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host:name": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "discard strings",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu0",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle 42
`),
},
{
name: "string as label",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu0",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{cpu="cpu0"} 42
`),
},
{
name: "string as label duplicate tag",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu0",
},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu1",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{cpu="cpu0"} 42
`),
},
{
name: "replace characters when using string as label",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"host:name": "example.org",
"time_idle": 42.0,
},
time.Unix(1574279268, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "multiple fields grouping",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu0",
},
map[string]interface{}{
"time_guest": 8106.04,
"time_system": 26271.4,
"time_user": 92904.33,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu1",
},
map[string]interface{}{
"time_guest": 8181.63,
"time_system": 25351.49,
"time_user": 96912.57,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu2",
},
map[string]interface{}{
"time_guest": 7470.04,
"time_system": 24998.43,
"time_user": 96034.08,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu3",
},
map[string]interface{}{
"time_guest": 7517.95,
"time_system": 24970.82,
"time_user": 94148,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_guest{cpu="cpu0"} 8106.04
cpu_time_system{cpu="cpu0"} 26271.4
cpu_time_user{cpu="cpu0"} 92904.33
cpu_time_guest{cpu="cpu1"} 8181.63
cpu_time_system{cpu="cpu1"} 25351.49
cpu_time_user{cpu="cpu1"} 96912.57
cpu_time_guest{cpu="cpu2"} 7470.04
cpu_time_system{cpu="cpu2"} 24998.43
cpu_time_user{cpu="cpu2"} 96034.08
cpu_time_guest{cpu="cpu3"} 7517.95
cpu_time_system{cpu="cpu3"} 24970.82
cpu_time_user{cpu="cpu3"} 94148
`),
},
{
name: "summary with no quantile",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"rpc_duration_seconds_sum": 1.7560473e+07,
"rpc_duration_seconds_count": 2693,
},
time.Unix(0, 0),
telegraf.Summary,
),
},
expected: []byte(`
rpc_duration_seconds_count 2693
rpc_duration_seconds_sum 17560473
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := NewSerializer(FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: tt.config.StringHandling,
})
require.NoError(t, err)
data, err := s.SerializeBatch(tt.metrics)
require.NoError(t, err)
actual, err := prompbToText(data)
require.NoError(t, err)
require.Equal(t,
strings.TrimSpace(string(tt.expected)),
strings.TrimSpace(string(actual)))
})
}
}
func prompbToText(data []byte) ([]byte, error) {
var buf = bytes.Buffer{}
protobuff, err := snappy.Decode(nil, data)
if err != nil {
return nil, err
}
var req prompb.WriteRequest
err = proto.Unmarshal(protobuff, &req)
if err != nil {
return nil, err
}
samples := protoToSamples(&req)
for _, sample := range samples {
buf.Write([]byte(fmt.Sprintf("%s %s\n", sample.Metric.String(), sample.Value.String())))
}
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func protoToSamples(req *prompb.WriteRequest) model.Samples {
var samples model.Samples
for _, ts := range req.Timeseries {
metric := make(model.Metric, len(ts.Labels))
for _, l := range ts.Labels {
metric[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
for _, s := range ts.Samples {
samples = append(samples, &model.Sample{
Metric: metric,
Value: model.SampleValue(s.Value),
Timestamp: model.Time(s.Timestamp),
})
}
}
return samples
}
| Java |
package org.nem.core.model;
import org.nem.core.utils.ArrayUtils;
import java.util.Comparator;
/**
* A custom comparator for comparing MultisigSignatureTransaction objects.
* <br>
* This comparator only looks at the transaction signer and other hash.
*/
public class MultisigSignatureTransactionComparator implements Comparator<MultisigSignatureTransaction> {
@Override
public int compare(final MultisigSignatureTransaction lhs, final MultisigSignatureTransaction rhs) {
final Address lhsAddress = lhs.getSigner().getAddress();
final Address rhsAddress = rhs.getSigner().getAddress();
final int addressCompareResult = lhsAddress.compareTo(rhsAddress);
if (addressCompareResult != 0) {
return addressCompareResult;
}
return ArrayUtils.compare(lhs.getOtherTransactionHash().getRaw(), rhs.getOtherTransactionHash().getRaw());
}
}
| Java |
body {
padding-top: 65px;
}
#footer {
padding: 10px;
color: #333;
}
#titulo {
color: #fff;
}
#textoSobreNosotros {
color: #333;
}
#login-buttons a, .accounts-dialog a {
color: rgb(0, 0, 0);
text-decoration: none;
text-align: center;
vertical-align: middle;
line-height: 50px;
padding: 20px;
}
#submit {
background-color: #f4511e;
color: #fff;
}
#formGraffiti {
border: 2px solid #f4511e;
border-radius: 12px;
padding-top: 20px;
padding-right: 20px;
}
#agregarGraffiti {
padding-top: 0;
}
#misGraffitis {
padding-top: 0;
padding-bottom: 5px;
}
#buscarGraffitis {
padding-top: 0;
}
#textJumbotron {
color: #fff;
}
#textJumbotronUsuario {
color: #fff;
}
.map-container {
width: 800px;
max-width: 100%;
height: 500px;
margin: 0 auto;
}
.navbar {
margin-bottom: 0;
background-color: #f4511e;
z-index: 9999;
border: 0;
font-size: 12px !important;
line-height: 1.42857143 !important;
letter-spacing: 4px;
border-radius: 0;
}
.navbar-nav li a:hover, .navbar-nav li.active a {
color: #f4511e !important;
background-color: #fff !important;
}
.navbar-default .navbar-toggle {
border-color: transparent;
color: #fff !important;
}
.container .jumbotron, .container-fluid .jumbotron {
background-color: #f4511e;
}
.jumbotron {
background-color: #f4511e;
color: #fff;
padding: 100px 25px;
}
.container-fluid {
padding: 60px 50px;
}
.jumbotron h1 {
color: #fff;
}
.bg-grey {
background-color: #f6f6f6;
}
div.jumbotron.text-center {
margin-bottom: 0;
}
ol, ul {
display: inline-block;
margin-left: auto;
margin-right: auto;
}
.react-tags {
position: relative;
padding: 6px 0 0 6px;
border: 1px solid #D1D1D1;
border-radius: 1px;
/* shared font styles */
font-size: 1em;
line-height: 1.2;
/* clicking anywhere will focus the input */
cursor: text;
}
.react-tags.is-focused {
border-color: #B1B1B1;
}
.react-tags__selected {
display: inline;
}
.react-tags__selected-tag {
display: inline-block;
box-sizing: border-box;
margin: 0 6px 6px 0;
padding: 6px 8px;
border: 1px solid #D1D1D1;
border-radius: 2px;
background: #F1F1F1;
/* match the font styles */
font-size: inherit;
line-height: inherit;
}
.react-tags__selected-tag:after {
content: '\2715';
color: #AAA;
margin-left: 8px;
}
.react-tags__selected-tag:hover,
.react-tags__selected-tag:focus {
border-color: #B1B1B1;
}
.react-tags__search {
display: inline-block;
/* match tag layout */
padding: 7px 2px;
margin-bottom: 6px;
/* prevent autoresize overflowing the container */
max-width: 100%;
}
@media screen and (min-width: 30em) {
.react-tags__search {
/* this will become the offsetParent for suggestions */
position: relative;
}
}
.react-tags__search input {
/* prevent autoresize overflowing the container */
max-width: 100%;
/* remove styles and layout from this element */
margin: 0;
padding: 0;
border: 0;
outline: none;
/* match the font styles */
font-size: inherit;
line-height: inherit;
}
.react-tags__search input::-ms-clear {
display: none;
}
.react-tags__suggestions {
position: absolute;
top: 100%;
left: 80%;
width: 100%;
}
@media screen and (min-width: 30em) {
.react-tags__suggestions {
width: 240px;
}
}
.react-tags__suggestions ul {
margin: 4px -1px;
padding: 0;
list-style: none;
background: white;
border: 1px solid #D1D1D1;
border-radius: 2px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.react-tags__suggestions li {
border-bottom: 1px solid #ddd;
padding: 6px 8px;
}
.react-tags__suggestions li mark {
text-decoration: underline;
background: none;
font-weight: 600;
}
.react-tags__suggestions li:hover {
cursor: pointer;
background: #eee;
}
.react-tags__suggestions li.is-active {
background: #b7cfe0;
}
.react-tags__suggestions li.is-disabled {
opacity: 0.5;
cursor: auto;
}
.votingGraffiti1 {
padding: 50px;
float: left;
}
.votingGraffiti2 {
padding: 50px;
float: right;
}
.nuevos {
margin: 10px;
border-radius: 25px;
border: 2px solid #d34615;
padding: 20px;
}
.revelacion {
margin: 10px;
border-radius: 25px;
border: 2px solid #d34615;
padding: 20px;
}
.creativo {
margin: 10px;
border-radius: 25px;
border: 2px solid #d34615;
padding: 20px;
}
.inspirador {
margin: 10px;
border-radius: 25px;
border: 2px solid #d34615;
padding: 20px;
}
/* CSS declarations go here */
/*! normalize.css v4.1.1 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Change the default font family in all browsers (opinionated).
* 2. Prevent adjustments of font size after orientation changes in IE and iOS.
*/
html {
font-family: sans-serif; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Remove the margin in all browsers (opinionated).
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Add the correct display in IE 9-.
* 1. Add the correct display in Edge, IE, and Firefox.
* 2. Add the correct display in IE.
*/
article,
aside,
details, /* 1 */
figcaption,
figure,
footer,
header,
main, /* 2 */
menu,
nav,
section,
summary { /* 1 */
display: block;
}
/**
* Add the correct display in IE 9-.
*/
audio,
canvas,
progress,
video {
display: inline-block;
}
/**
* Add the correct display in iOS 4-7.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Add the correct display in IE 10-.
* 1. Add the correct display in IE.
*/
template, /* 1 */
[hidden] {
display: none;
}
/* Links
========================================================================== */
/**
* 1. Remove the gray background on active links in IE 10.
* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
*/
a {
background-color: transparent; /* 1 */
-webkit-text-decoration-skip: objects; /* 2 */
}
/**
* Remove the outline on focused links when they are also active or hovered
* in all browsers (opinionated).
*/
a:active,
a:hover {
outline-width: 0;
}
/* Text-level semantics
========================================================================== */
/**
* 1. Remove the bottom border in Firefox 39-.
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Prevent the duplicate application of `bolder` by the next rule in Safari 6.
*/
b,
strong {
font-weight: inherit;
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* Add the correct font style in Android 4.3-.
*/
dfn {
font-style: italic;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Add the correct background and color in IE 9-.
*/
mark {
background-color: #ff0;
color: #000;
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10-.
*/
img {
border-style: none;
}
/**
* Hide the overflow in IE.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct margin in IE 8.
*/
figure {
margin: 1em 40px;
}
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/* Forms
========================================================================== */
/**
* 1. Change font properties to `inherit` in all browsers (opinionated).
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
select,
textarea {
font: inherit; /* 1 */
margin: 0; /* 2 */
}
/**
* Restore the font weight unset by the previous rule.
*/
optgroup {
font-weight: bold;
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
* controls in Android 4.
* 2. Correct the inability to style clickable types in iOS and Safari.
*/
button,
html [type="button"], /* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 2 */
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Change the border, margin, and padding in all browsers (opinionated).
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Remove the default vertical scrollbar in IE.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10-.
* 2. Remove the padding in IE 10-.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding and cancel buttons in Chrome and Safari on OS X.
*/
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Correct the text style of placeholders in Chrome, Edge, and Safari.
*/
::-webkit-input-placeholder {
color: inherit;
opacity: 0.54;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
header {
background: #EEE;
padding: 20px;
text-align: center;
}
h1 {
margin: 0;
}
main {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
input[type='text'] {
width: 45%;
}
button[type='submit'] {
width: 100%;
border: solid 1px #111;
background: #FFF;
margin-top: 10px;
}
.item {
margin-top: 20px;
background: #FFF;
box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
padding: 20px;
display: flex;
justify-content: space-between;
}
.item p {
font-size: 18px;
margin: 0;
}
.item div {
width: 40%;
cursor: pointer;
padding: 5px;
text-align: center;
transition: 0.3s ease all;
border-bottom: solid 10px;
}
.item .vote-one {
border-bottom-color: blue;
}
.item .vote-two {
border-bottom-color: red;
}
.item > span {
font-style: italic;
color: #CCC;
}
.item div:hover {
background: #EEE;
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cfgv: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.2 / cfgv - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cfgv
<small>
8.7.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-03-05 01:02:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-03-05 01:02:10 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.11 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.8.2 Formal proof management system.
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0 Official release 4.09.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/cfgv"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/CFGV"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: generic programming" "keyword: variable bindings" "keyword: context free grammars" "keyword: substitution" "keyword: alpha equality" "keyword: equivariance" "category: Computer Science/Lambda Calculi" ]
authors: [ "Abhishek <abhishek.anand.iitg@gmail.com> [http://www.cs.cornell.edu/~aa755/]" "Vincent Rahli <vincent.rahli@gmail.com> [http://www.cs.cornell.edu/~rahli/]" ]
bug-reports: "https://github.com/coq-contribs/cfgv/issues"
dev-repo: "git+https://github.com/coq-contribs/cfgv.git"
synopsis: "Generic Proofs about Alpha Equality and Substitution"
description: """
http://www.nuprl.org/html/CFGVLFMTP2014/
Please read the following paper"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cfgv/archive/v8.7.0.tar.gz"
checksum: "md5=59a29ea2c3114e007451171d9de147d8"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-cfgv.8.7.0 coq.8.8.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2).
The following dependencies couldn't be met:
- coq-cfgv -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cfgv.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
/*******************************************************
* File name: pando_subdevice.h
* Author: razr
* Versions: 1.0
* Description: pando iot embeded framework.
* History:
* 1.Date: Sep 11, 2015
* Author: razr
* Modification: initial code
*********************************************************/
#ifndef PANDO_FRAMEWORK_H_
#define PANDO_FRAMEWORK_H_
void pando_framework_init(void);
#endif /* PANDO_FRAMEWORK_H_ */
| Java |
---
layout: default
---
<div class="page clearfix" index>
<div class="left">
<h1>Welcome to jisonami's Notes!</h1>
<small>这里记录我在程序开发过程中的学习笔记</small>
<hr>
<ul>
{% for post in paginator.posts %}
<li>
<h2>
<a class="post-link" href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
</h2>
<div class="label">
<div class="label-card">
<i class="fa fa-calendar"></i>{{ post.date | date: "%F" }}
</div>
<div class="label-card">
{% if post.author %}<i class="fa fa-user"></i>{{ post.author }}
{% endif %}
</div>
<div class="label-card">
{% if page.meta %}<i class="fa fa-key"></i>{{ page.meta }} {% endif %}
</div>
<div class="label-card">
{% include category.html %}
</div>
<div class="label-card">
{% include tag.html %}
</div>
</div>
<div class="excerpt">
{{post.excerpt}}
</div>
<div class="read-all">
<a href="{{ post.url | prepend: site.baseurl }}"><i class="fa fa-newspaper-o"></i>Read All</a>
</div>
<hr>
</li>
{% endfor %}
</ul>
<!-- Pagination links -->
<div class="pagination">
{% if paginator.previous_page %}
<a href="/index.html" class="previous"><i class="fa fa-angle-double-left"></i></a>
<a href="{{ paginator.previous_page_path }}" class="previous"><i class="fa fa-angle-left"></i></a>
{% else %}
<span class="previous disable"><i class="fa fa-angle-double-left"></i></span>
<span class="previous disable"><i class="fa fa-angle-left"></i></span>
{% endif %}
<span class="page_number ">{{ paginator.page }}/{{ paginator.total_pages }}</span>
{% if paginator.next_page %}
<a href="{{ paginator.next_page_path }}" class="next"><i class="fa fa-angle-right"></i></a>
<a href="/page{{ paginator.total_pages }}" class="next"><i class="fa fa-angle-double-right"></i></a>
{% else %}
<span class="next disable"><i class="fa fa-angle-right"></i></span>
<span class="next disable"><i class="fa fa-angle-double-right"></i></span>
{% endif %}
</div>
</div>
<!-- <button class="anchor"><i class="fa fa-anchor"></i></button> -->
<div class="right">
<div class="wrap">
<div class="side">
<div>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
Recent Posts
</div>
<ul class="content-ul" recent>
{% for post in site.posts offset: 0 limit: 10 %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
</div>
<!-- Content -->
<div class="side ">
<div>
<i class="fa fa-th-list"></i>
Categories
</div>
<ul class="content-ul" cate>
{% for category in site.categories %}
<li>
<a href="{{ root_url }}/{{ site.category_dir }}#{{ category | first }}" class="categories-list-item" cate="{{ category | first }}">
<span class="name">
{{ category | first }}
</span>
<span class="badge">{{ category | last | size }}</span>
</a>
</li>
{% endfor %}
</ul>
</div>
<!-- 其他div框放到这里 -->
<div class="side">
<div>
<i class="fa fa-tags"></i>
Tags
</div>
<div class="tags-cloud">
{% assign first = site.tags.first %}
{% assign max = first[1].size %}
{% assign min = max %}
{% for tag in site.tags offset:1 %}
{% if tag[1].size > max %}
{% assign max = tag[1].size %}
{% elsif tag[1].size < min %}
{% assign min = tag[1].size %}
{% endif %}
{% endfor %}
{% if max == min %}
{% assign diff = 1 %}
{% else %}
{% assign diff = max | minus: min %}
{% endif %}
{% for tag in site.tags %}
{% assign temp = tag[1].size | minus: min | times: 36 | divided_by: diff %}
{% assign base = temp | divided_by: 4 %}
{% assign remain = temp | modulo: 4 %}
{% if remain == 0 %}
{% assign size = base | plus: 9 %}
{% elsif remain == 1 or remain == 2 %}
{% assign size = base | plus: 9 | append: '.5' %}
{% else %}
{% assign size = base | plus: 10 %}
{% endif %}
{% if remain == 0 or remain == 1 %}
{% assign color = 9 | minus: base %}
{% else %}
{% assign color = 8 | minus: base %}
{% endif %}
<a href="{{ root_url }}/{{ site.tag_dir }}#{{ tag[0] }}" style="font-size: {{ size }}pt; color: #{{ color }}{{ color }}{{ color }};">{{ tag[0] }}</a>
{% endfor %}
</div>
</div>
<!-- <div class="side">
<div>
<i class="fa fa-external-link"></i>
Links
</div>
<ul class="content-ul">
</ul>
</div> -->
</div>
</div>
</div>
<!-- <script src="{{ "/js/scroll.min.js " | prepend: site.baseurl }}" charset="utf-8"></script> -->
<!-- <script src="{{ "/js/pageContent.js " | prepend: site.baseurl }}" charset="utf-8"></script> -->
| Java |
<?php
namespace app\controllers;
use Yii;
use app\models\{Freight, FreightSearch};
use yii\web\{Controller, NotFoundHttpException};
/**
* FreightController implements the CRUD actions for Freight model.
*/
class FreightController extends Controller
{
/**
* Lists all Freight models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new FreightSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Freight model.
* @param string $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Freight model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Freight();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Freight model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Finds the Freight model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return Freight the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Freight::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| Java |
// ReplProbe.js (c) 2010-2013 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/monitor-min
(function(root){
// Module loading - this runs server-side only
var Monitor = root.Monitor || require('../Monitor'),
_ = Monitor._,
Probe = Monitor.Probe,
REPL = require('repl'),
Stream = require('stream'),
util = require('util'),
events = require('events'),
ChildProcess = require('child_process');
// Statics
var CONSOLE_PROMPT = '> ';
var NEW_REPL = (typeof REPL.disableColors === 'undefined');
/**
* A probe based Read-Execute-Print-Loop console for node.js processes
*
* @class ReplProbe
* @extends Probe
* @constructor
* @param initParams {Object} Probe initialization parameters
* @param initParams.uniqueInstance - Usually specified to obtain a unique REPL probe instance
* @param model {Object} Monitor data model elements
* @param model.output {String} Last (current) REPL output line
* @param model.sequence {Integer} Increasing sequence number - to enforce unique line output
*/
var ReplProbe = Monitor.ReplProbe = Probe.extend({
probeClass: 'Repl',
description: 'A socket.io based Read-Execute-Print-Loop console for node.js processes.',
defaults: {
// This assures output events are sent, even if the
// data is the same as the prior output.
sequence: 0,
output: ''
},
initialize: function(attributes, options){
var t = this;
Probe.prototype.initialize.apply(t, arguments);
// Don't send change events before connected
process.nextTick(function(){
t.stream = new ReplStream(t);
if (NEW_REPL) {
t.repl = require('repl').start({
prompt: CONSOLE_PROMPT,
input: t.stream,
output: t.stream
});
} else {
t.repl = REPL.start(CONSOLE_PROMPT, t.stream);
}
t.htmlConsole = new HtmlConsole(t);
t.shellCmd = null;
t.repl.context.console = t.htmlConsole;
});
},
/**
* Send output to the terminal
*
* This forces the change event even if the last output is the same
* as this output.
*
* @protected
* @method output
* @param str {String} String to output to the repl console
*/
_output: function(str) {
var t = this;
t.set({
output: str,
sequence: t.get('sequence') + 1
});
},
/**
* Release any resources consumed by this probe.
*
* Stop the REPL console. Consoles live 1-1 with a UI counterpart, so stop
* requests exit the underlying repl console. If the probe is re-started it
* will get a new repl stream and console.
*
* @method release
*/
release: function(){
var t = this;
t.stream = null;
t.repl = null;
},
/**
* Process an autocomplete request from the client
*
* @method autocomplete
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
autocomplete_control: function(params, callback) {
var t = this;
if (typeof(params) !== 'string' || params.length < 1) {
callback("Autocomplete paramter must be a nonzero string");
}
// Forward to the completion mechanism if it can be completed
if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) {
t.repl.complete(params, callback);
} else {
// Return a no-op autocomplete
callback(null, [[],'']);
}
},
/**
* Handle user input from the console line
*
* @method input
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
input_control: function(params, callback) {
var t = this;
if (params === '.break' && t.shellCmd) {
t.shellCmd.kill();
}
if (NEW_REPL) {
t.stream.emit('data', params + "\n");
} else {
t.stream.emit('data', params);
}
return callback(null);
},
/**
* Execute a shell command
*
* @method sh
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
sh_control: function(params, callback) {
var t = this;
return callback(null, t._runShellCmd(params));
},
/**
* Run a shell command and emit the output to the browser.
*
* @private
* @method _runShellCmd
* @param {String} command - The shell command to invoke
*/
_runShellCmd: function(command) {
var t = this;
t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) {
if (err) {
var outstr = 'exit';
if (err.code) {
outstr += ' (' + err.code + ')';
}
if (err.signal) {
outstr += ' ' + err.signal;
}
t._output(outstr);
return null;
}
if (stdout.length) {
t._output(stdout);
}
if (stderr.length) {
t._output(stderr);
}
t.shellCmd = null;
t._output(CONSOLE_PROMPT);
});
return null;
}
});
// Define an internal stream class for the probe
var ReplStream = function(probe){
var t = this;
t.probe = probe;
events.EventEmitter.call(t);
if (t.setEncoding) {
t.setEncoding('utf8');
}
};
util.inherits(ReplStream, events.EventEmitter);
// util.inherits(ReplStream, require('stream'));
ReplStream.prototype.readable = true;
ReplStream.prototype.writable = true;
['pause','resume','destroySoon','pipe', 'end']
.forEach(function(fnName){
ReplStream.prototype[fnName] = function(){
console.log("REPL Stream function unexpected: " + fnName);
};
});
['resume']
.forEach(function(fnName){
ReplStream.prototype[fnName] = function(){
// Handled
};
});
ReplStream.prototype.write = function(data) {
var t = this;
t.probe._output(data);
};
ReplStream.prototype.destroy = function(data) {
var t = this;
console.log("REPL stream destroy " + t.probe.get('id'));
t.probe.stop();
};
// Define format if it's not in util.
var formatRegExp = /%[sdj]/g;
var format = util.format || function (f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(util.inspect(arguments[i]));
}
return objects.join(' ');
}
var j = 1;
var args = arguments;
var str = String(f).replace(formatRegExp, function(x) {
switch (x) {
case '%s': return String(args[j++]);
case '%d': return Number(args[j++]);
case '%j': return JSON.stringify(args[j++]);
default:
return x;
}
});
for (var len = args.length, x = args[j]; j < len; x = args[++j]) {
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + util.inspect(x);
}
}
return str;
};
// Re-define the console so it goes to the HTML window
var HtmlConsole = function(probe){
this.probe = probe;
};
HtmlConsole.prototype.log = function(msg) {
this.probe._output(format.apply(this, arguments));
};
HtmlConsole.prototype.info = HtmlConsole.prototype.log;
HtmlConsole.prototype.warn = HtmlConsole.prototype.log;
HtmlConsole.prototype.error = HtmlConsole.prototype.log;
HtmlConsole.prototype.dir = function(object) {
this.probe._output(util.inspect(object));
};
var times = {};
HtmlConsole.prototype.time = function(label) {
times[label] = Date.now();
};
HtmlConsole.prototype.timeEnd = function(label) {
var duration = Date.now() - times[label];
this.log('%s: %dms', label, duration);
};
}(this));
| Java |
package model.dataModels;
/**
* Class ManufacturingData.
* @author Daniel
*
*/
public class ManufacturingData {
private String customerNumber;
private String materialNumber;
private String orderNumber;
private String timeStamp;
private MachineData[] machineData;
private SpectralAnalysisData analysisData;
/**
* Constructor.
*/
public ManufacturingData() {}
/**
* Creates a string representation
* of this object.
* @return
*/
@Override
public String toString() {
return customerNumber + " " + materialNumber + " "
+ orderNumber + " " + timeStamp + " "
+ machineData + " " + analysisData;
}
/*
* Getters and Setters.
*/
/**
* Adds erp data.
* @param data
*/
public void setErpData(ErpData data) {
this.customerNumber = data.getCustomerNumber();
this.materialNumber = data.getMaterialNumber();
this.orderNumber = data.getOrderNumber();
this.timeStamp = data.getTimeStamp();
}
/**
* Appends machine data to the array.
* @param data
*/
public void appendMachineData(MachineData data) {
if(this.machineData == null) {
this.machineData = new MachineData[1];
machineData[0] = data;
} else {
int length = this.machineData.length;
MachineData[] temp = new MachineData[length + 1];
for(int i = 0; i < length; i++) {
temp[i] = this.machineData[i];
}
temp[length] = data;
this.machineData = temp;
}
}
/**
* Adds spectral analysis data.
* @param analysisData
*/
public void setAnalysisData(SpectralAnalysisData analysisData) {
this.analysisData = analysisData;
}
public String getCustomerNumber() {
return customerNumber;
}
public String getMaterialNumber() {
return materialNumber;
}
public String getOrderNumber() {
return orderNumber;
}
public String getTimeStamp() {
return timeStamp;
}
public MachineData[] getMachineData() {
return machineData;
}
public SpectralAnalysisData getAnalysisData() {
return analysisData;
}
} | Java |
using System;
using System.Collections.Generic;
using Roguelike.Core.Elements.Inventory;
using Roguelike.Entities;
using RLNET;
namespace Roguelike.Systems {
public class InventorySystem {
private Player player;
public InventorySystem() {
player = Game.Player;
}
void SelectEquipment(Equipment pressedOn) {
if (pressedOn.GetType() == typeof(HeadEquipment)) {
SelectHeadEquipment((HeadEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(BodyEquipment)) {
SelectBodyEquipment((BodyEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(ArmEquipment)) {
SelectArmEquipment((ArmEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(LegEquipment)) {
SelectLegEquipment((LegEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(HandEquipment)) {
SelectHandEquipment((HandEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(FeetEquipment)) {
SelectFeetEquipment((FeetEquipment)pressedOn);
}
Game.Render();
}
void DiscardEquipment(Equipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
Game.Render();
}
void SelectHeadEquipment(HeadEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if(player.Head != null && player.Head != HeadEquipment.None()) {
player.AddEquipment(player.Head);
}
player.Head = pressedOn;
}
void SelectBodyEquipment(BodyEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Body != null && player.Body != BodyEquipment.None()) {
player.AddEquipment(player.Body);
}
player.Body = pressedOn;
}
void SelectArmEquipment(ArmEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Arms != null && player.Arms != ArmEquipment.None()) {
player.AddEquipment(player.Arms);
}
player.Arms = pressedOn;
}
void SelectLegEquipment(LegEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Legs != null && player.Legs != LegEquipment.None()) {
player.AddEquipment(player.Legs);
}
player.Legs = pressedOn;
}
void SelectHandEquipment(HandEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Hands != null && player.Hands != HandEquipment.None()) {
player.AddEquipment(player.Hands);
}
player.Hands = pressedOn;
}
void SelectFeetEquipment(FeetEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Feet != null && player.Feet != FeetEquipment.None()) {
player.AddEquipment(player.Feet);
}
player.Feet = pressedOn;
}
public Equipment EquipArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if(lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if(i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if(numberOfLines == 1) {
if(x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
SelectEquipment(player.equipmentInInventory[i]);
}
}else if(numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if(y == yPosition) {
if(x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
SelectEquipment(player.equipmentInInventory[i]);
}
} else if(y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
SelectEquipment(player.equipmentInInventory[i]);
}
}
}
}
return null;
}
public void DiscardArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if (lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if (i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if (numberOfLines == 1) {
if (x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if (y == yPosition) {
if (x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
DiscardEquipment(player.equipmentInInventory[i]);
}
}
}
}
}
public void RemoveEquipment(int x, int y) {
if (y == 3) {
if (x >= 1 && x <= 14) {
HeadEquipment toRemove = player.Head;
player.Head = HeadEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
LegEquipment toRemove = player.Legs;
player.Legs = LegEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 5) {
if (x >= 1 && x <= 14) {
BodyEquipment toRemove = player.Body;
player.Body = BodyEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
HandEquipment toRemove = player.Hands;
player.Hands = HandEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 7) {
if (x >= 1 && x <= 14) {
ArmEquipment toRemove = player.Arms;
player.Arms = ArmEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
FeetEquipment toRemove = player.Feet;
player.Feet = FeetEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
}
Game.Render();
}
public Equipment RemoveCurrentArmour(int x, int y) {
if(y == 3 || y == 4) {
ClickedOnHead(x, y);
} else if(y == 6 || y == 7) {
ClickedOnBody(x, y);
} else if (y == 9 || y == 10) {
ClickedOnArms(x, y);
} else if (y == 12 || y == 13) {
ClickedOnLegs(x, y);
} else if (y == 15 || y == 16) {
ClickedOnHands(x, y);
} else if (y == 18 || y == 19) {
ClickedOnFeet(x, y);
}
return null;
}
private void ClickedOnHead(int x, int y) {
string topLine = TopLine("Head: " + player.Head.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Head: " + player.Head.Name, topLine);
} catch {
}
if (y == 4) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
}
public void ClickedOnBody(int x, int y) {
string topLine = TopLine("Body: " + player.Body.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Body: " + player.Body.Name, topLine);
} catch {
}
if (y == 7) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
}
public void ClickedOnArms(int x, int y) {
string topLine = TopLine("Arms: " + player.Arms.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Arms: " + player.Arms.Name, topLine);
} catch {
}
if (y == 10) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
}
public void ClickedOnLegs(int x, int y) {
string topLine = TopLine("Legs: " + player.Legs.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Legs: " + player.Legs.Name, topLine);
} catch {
}
if (y == 13) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
}
public void ClickedOnHands(int x, int y) {
string topLine = TopLine("Hands: " + player.Hands.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Hands: " + player.Hands.Name, topLine);
} catch {
}
if (y == 16) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
}
}
private void ClickedOnFeet(int x, int y) {
string topLine = TopLine("Feet: " + player.Feet.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Feet: " + player.Feet.Name, topLine);
} catch {
}
if (y == 19) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
}
}
public bool DidClickOnString(int x, int y, bool secondLine,string topLine, string bottomLine = "") {
int xStartPosition = 1;
int topXEndPosition = xStartPosition + topLine.Length;
int bottomXEndPosition = xStartPosition + bottomLine.Length;
if (bottomLine != "") {
if (secondLine) {
if (x >= xStartPosition && x <= bottomXEndPosition) {
return true;
} else {
return false;
}
} else {
if (x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
} else {
if(x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
}
private void UnequipArmour(Equipment toUnequip) {
if (toUnequip.GetType() == typeof(HeadEquipment) && toUnequip != HeadEquipment.None()) {
UnSelectHeadEquipment((HeadEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(BodyEquipment) && toUnequip != BodyEquipment.None()) {
UnSelectBodyEquipment((BodyEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(ArmEquipment) && toUnequip != ArmEquipment.None()) {
UnSelectArmEquipment((ArmEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(LegEquipment) && toUnequip != LegEquipment.None()) {
UnSelectLegEquipment((LegEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(HandEquipment) && toUnequip != HandEquipment.None()) {
UnSelectHandEquipment((HandEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(FeetEquipment) && toUnequip != FeetEquipment.None()) {
UnSelectFeetEquipment((FeetEquipment)toUnequip);
}
Game.Render();
}
private void UnSelectHeadEquipment(HeadEquipment toUnequip) {
if(player.equipmentInInventory.Count < 12) {
player.Head = HeadEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectBodyEquipment(BodyEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Body = BodyEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectArmEquipment(ArmEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Arms = ArmEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectLegEquipment(LegEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Legs = LegEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectHandEquipment(HandEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Hands = HandEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectFeetEquipment(FeetEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Feet = FeetEquipment.None();
player.AddEquipment(toUnequip);
}
}
private string TopLine(string totalString, int wrapLength = 18) {
List<string> wordsInString = new List<string>();
string currentString = "";
for (int i = 0; i < totalString.Length; i++) {
char character = totalString[i];
if (character == ' ') {
wordsInString.Add(currentString);
currentString = "";
}else if(i == totalString.Length - 1) {
currentString += character;
wordsInString.Add(currentString);
currentString = "";
} else {
currentString += character;
}
}
int lengthSoFar = 0;
string topLine = "";
for (int i = 0; i < wordsInString.Count; i++) {
if (lengthSoFar + wordsInString[i].Length >= wrapLength) {
break;
}
lengthSoFar += wordsInString[i].Length;
topLine += wordsInString[i];
topLine += " ";
}
return topLine;
}
private string BottomLine(string totalString, string topLine) {
string bottom = totalString;
bottom = bottom.Substring(topLine.Length);
return bottom;
}
}
}
| Java |
<?php
class TeamsTest extends Raideer\TwitchApi\TestCase
{
public function __construct()
{
$this->setResource('Raideer\TwitchApi\Resources\Teams');
}
public function test_getName_returnsTeams()
{
$this->assertSame('teams', $this->resource->getName());
}
public function test_getTeams()
{
$this->mockRequest(
'GET',
'teams',
[
'limit' => 10,
'offset' => 0,
]
);
$this->resource->getTeams(['limit' => 10]);
}
public function test_getTeam()
{
$this->mockRequest(
'GET',
'teams/testteam'
);
$this->resource->getTeam('testteam');
}
}
| Java |
# frozen_string_literal: true
require "dry/core/equalizer"
require "rom/initializer"
require "rom/relation/loaded"
require "rom/relation/composite"
require "rom/relation/materializable"
require "rom/pipeline"
require "rom/support/memoizable"
module ROM
class Relation
# Abstract relation graph class
#
# @api public
class Graph
extend Initializer
include Memoizable
# @!attribute [r] root
# @return [Relation] The root relation
param :root
# @!attribute [r] nodes
# @return [Array<Relation>] An array with relation nodes
param :nodes
include Dry::Equalizer(:root, :nodes)
include Materializable
include Pipeline
include Pipeline::Proxy
# for compatibility with the pipeline
alias_method :left, :root
alias_method :right, :nodes
# Rebuild a graph with new nodes
#
# @param [Array<Relation>] nodes
#
# @return [Graph]
#
# @api public
def with_nodes(nodes)
self.class.new(root, nodes)
end
# Return if this is a graph relation
#
# @return [true]
#
# @api private
def graph?
true
end
# Map graph tuples via custom mappers
#
# @see Relation#map_with
#
# @return [Relation::Composite]
#
# @api public
def map_with(*names, **opts)
names.reduce(self.class.new(root.with(opts), nodes)) { |a, e| a >> mappers[e] }
end
# Map graph tuples to custom objects
#
# @see Relation#map_to
#
# @return [Graph]
#
# @api public
def map_to(klass)
self.class.new(root.map_to(klass), nodes)
end
# @see Relation#mapper
#
# @api private
def mapper
mappers[to_ast]
end
# @api private
memoize def to_ast
[:relation, [name.relation, attr_ast + nodes.map(&:to_ast), meta_ast]]
end
private
# @api private
def decorate?(other)
super || other.is_a?(Composite) || other.is_a?(Curried)
end
# @api private
def composite_class
Relation::Composite
end
end
end
end
| Java |
<?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\Auth;
use PHPUnit\Framework\TestCase;
class AuthTest extends TestCase
{
public function testAdd()
{
$obj = new Auth();
$result = $obj->setToken('sdfsdf465456');
$this->assertEquals('sdfsdf465456', $obj->getToken());
}
}
| Java |
# GKDProgress
A progress use CoreAnimation
| Java |
#ifndef ZOMBIE_HUMANPLAYER_H
#define ZOMBIE_HUMANPLAYER_H
#include "device.h"
#include "physics/moving/unit.h"
#include "player.h"
#include "physics/moving/unit.h"
#include <glm/gtx/rotate_vector.hpp>
namespace zombie {
class HumanPlayer : public Player {
public:
HumanPlayer(DevicePtr device, std::unique_ptr<Unit> unit)
: device_{std::move(device)}
, unit_{std::move(unit)} {
}
void updateInput(double time, double deltaTime) override {
unit_->setInput(device_->nextInput());
unit_->updatePhysics(time, deltaTime);
}
void draw(sdl::Graphic& graphic) override {
auto pos = unit_->getPosition();
graphic.addCircle({pos.x, pos.y}, unit_->getRadius(), sdl::color::html::DeepSkyBlue);
graphic.addCircleOutline({pos.x, pos.y}, unit_->getViewDistance(), 0.1f, sdl::color::html::Firebrick);
graphic.addLine({pos.x, pos.y}, glm::vec2{pos.x, pos.y} + glm::rotate(glm::vec2{1.f, 0.f}, unit_->getDirection()), 0.1f, sdl::color::html::Firebrick);
}
Unit* getUnit() const {
return unit_.get();
}
PhysicalObject* getPhysicalObject() override {
return unit_.get();
}
private:
DevicePtr device_;
std::unique_ptr<Unit> unit_;
};
using HumanPlayerPtr = std::unique_ptr<HumanPlayer>;
}
#endif
| Java |
// Copyright (c) 2014 The Okcash Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef COIN_STATE_H
#define COIN_STATE_H
#include <string>
#include <limits>
#include "sync.h"
enum eNodeType
{
NT_FULL = 1,
NT_THIN,
NT_UNKNOWN // end marker
};
enum eNodeState
{
NS_STARTUP = 1,
NS_GET_HEADERS,
NS_GET_FILTERED_BLOCKS,
NS_READY,
NS_UNKNOWN // end marker
};
enum eBlockFlags
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
/* nServices flags
top 32 bits of CNode::nServices are used to mark services required
*/
enum
{
NODE_NETWORK = (1 << 0),
THIN_SUPPORT = (1 << 1),
THIN_STAKE = (1 << 2), // deprecated
THIN_STEALTH = (1 << 3),
SMSG_RELAY = (1 << 4),
};
const int64_t GENESIS_BLOCK_TIME = 1416737561;
static const int64_t COIN = 100000000;
static const int64_t CENT = 1000000;
/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
static const int64_t MIN_TX_FEE = 10000;
static const int64_t MIN_TX_FEE_ANON = 1000000;
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE;
static const int64_t COIN_YEAR_REWARD = 69 * CENT; // 69% 1st Year
static const int64_t SCOIN_YEAR_REWARD = 20 * CENT; // 20% 1st halving
static const int64_t CCOIN_YEAR_REWARD = 10 * CENT; // 10% 2nd halving
static const int64_t KCOIN_YEAR_REWARD = 5 * CENT; // 5% 3rd halving
static const int64_t ICOIN_YEAR_REWARD = 2.5 * CENT; // 2.5% 4th halving
static const int64_t OCOIN_YEAR_REWARD = 22 * CENT; // 22% 5th halving
static const int64_t DCOIN_YEAR_REWARD = 11 * CENT; // 11% 6th halving
static const int64_t RCOIN_YEAR_REWARD = 6.9 * CENT; // 6.9% 7th halving
static const int64_t ECOIN_YEAR_REWARD = 3.9 * CENT; // 3.9% 8th halving
static const int64_t ACOIN_YEAR_REWARD = 3.6 * CENT; // 3.6% 9th halving
static const int64_t MCOIN_YEAR_REWARD = 3.3 * CENT; // 3.3% 10th halving
static const int64_t ZCOIN_YEAR_REWARD = 3 * CENT; // 3% 11th halving
static const int64_t XCOIN_YEAR_REWARD = 2 * CENT; // 2% 12th halving
static const int64_t BCOIN_YEAR_REWARD = 1 * CENT; // 1% 13th halving
static const int64_t GCOIN_YEAR_REWARD = 0.69 * CENT; // 0.69% 14th halving
static const int64_t FCOIN_YEAR_REWARD = 0.33 * CENT; // 0.33% 15th halving and onwards
static const int64_t MBLK_RECEIVE_TIMEOUT = 60; // seconds
extern int nNodeMode;
extern int nNodeState;
extern int nMaxThinPeers;
extern int nBloomFilterElements;
extern int nMinStakeInterval;
extern int nThinIndexWindow;
static const int nTryStakeMempoolTimeout = 5 * 60; // seconds
static const int nTryStakeMempoolMaxAsk = 16;
extern uint64_t nLocalServices;
extern uint32_t nLocalRequirements;
extern bool fTestNet;
extern bool fDebug;
extern bool fDebugNet;
extern bool fDebugSmsg;
extern bool fDebugChain;
extern bool fDebugRingSig;
extern bool fDebugPoS;
extern bool fNoSmsg;
extern bool fPrintToConsole;
extern bool fPrintToDebugLog;
//extern bool fShutdown;
extern bool fDaemon;
extern bool fServer;
extern bool fCommandLine;
extern std::string strMiscWarning;
extern bool fNoListen;
extern bool fLogTimestamps;
extern bool fReopenDebugLog;
extern bool fThinFullIndex;
extern bool fReindexing;
extern bool fHaveGUI;
extern volatile bool fIsStaking;
extern bool fMakeExtKeyInitials;
extern volatile bool fPassGuiAddresses;
extern bool fConfChange;
extern bool fEnforceCanonical;
extern unsigned int nNodeLifespan;
extern unsigned int nDerivationMethodIndex;
extern unsigned int nMinerSleep;
extern unsigned int nBlockMaxSize;
extern unsigned int nBlockPrioritySize;
extern unsigned int nBlockMinSize;
extern int64_t nMinTxFee;
extern unsigned int nStakeSplitAge;
extern int nStakeMinConfirmations;
extern int64_t nStakeSplitThreshold;
extern int64_t nStakeCombineThreshold;
extern uint32_t nExtKeyLookAhead;
extern int64_t nTimeLastMblkRecv;
#endif /* COIN_STATE_H */
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:b51623fcae1419d2bb29084e11d56fc9aafae7b0e35bd2a7fd30633a133bef40
size 24229
| Java |
module Librr::Displayer
class << self
attr_accessor :save_output, :output
def clear_output
@output = []
end
def save(text)
@output ||= []
@output << text
end
end
def show text
if Librr::Displayer.save_output
Librr::Displayer.save(text)
return
end
puts text
end
end
| Java |
var gif_bgs = [];
var gif_center = [];
var length_bgs = 0;
var length_center = 0;
var timer;
var duration = 4000;
var loaded = 0;
var next_bg;
var next_center;
var audio = document.getElementById("sound");
var muted = false;
function next(e){
clearInterval(timer);
timer = setInterval(next, duration);
$("#background").css("background-image","url("+gif_bgs[next_bg]+")");
$("#center").css("background-image","url("+gif_center[next_center]+")");
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
$("#load_bg").attr("src",gif_bgs[next_bg]);
$("#load_center").attr("src",gif_center[next_center]);
}
function toggleInfo(){
$("#info-overlay").toggleClass("show");
$("#info-btn").toggleClass("show");
}
function check(){
if (loaded > 1) {
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
next();
$("#wrapper").click(next);
}
}
function toggleSound(){
if (muted) {
muted = false;
audio.muted = muted;
$("#sound-btn").removeClass('muted');
}else{
muted = true;
audio.muted = muted;
$("#sound-btn").addClass('muted');
}
}
function init() {
$("#info-btn").click(toggleInfo);
$("#sound-btn").click(toggleSound);
$.ajax({
url: "json/bg.json",
cache: false,
dataType: "json",
success: function(d){
gif_bgs = d;
length_bgs = gif_bgs.length;
loaded++;
check();
}
});
$.ajax({
url: "json/center.json",
cache: false,
dataType: "json",
success: function(d){
gif_center = d;
length_center = gif_center.length;
loaded++;
check();
}
});
}
Meteor.startup(function(){init();});
| Java |
{% extends 'login_base.html' %}
{% block body %}
<div class="form-container">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
{{ field }}
{{ field.errors }}
{% endfor %}
<input id="submit" type="submit" value="Create new account" />
</form>
</div>
<p>Have an account already? <a href="{% url 'slrtcebook:login' %}">Login here</a></p>
{% endblock %} | Java |
<?php
class ProfilesTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$di = Xhgui_ServiceContainer::instance();
$this->profiles = $di['profiles'];
$this->_loadFixture('tests/fixtures/results.json');
}
protected function _loadFixture($file)
{
$contents = file_get_contents($file);
$data = json_decode($contents, true);
foreach ($data as $record) {
if (isset($record['meta']['request_time'])) {
$time = strtotime($record['meta']['request_time']);
$record['meta']['request_time'] = new MongoDate($time);
}
$this->profiles->insert($record);
}
}
public function testPagination()
{
$options = array(
'page' => 1,
'sort' => 'wt',
);
$result = $this->profiles->paginate($options);
$this->assertEquals(25, $result['perPage'], 'default works');
$this->assertEquals(1, $result['page']);
$this->assertEquals(
array('profile.main().wt' => -1),
$result['sort']
);
}
public function testPaginateInvalidSort()
{
$options = array(
'page' => 1,
'sort' => 'barf',
);
$result = $this->profiles->paginate($options);
$this->assertEquals(
array('meta.SERVER.REQUEST_TIME' => -1),
$result['sort']
);
}
public function testPaginateOutOfRangePage()
{
$options = array(
'page' => 9000,
'sort' => 'barf',
);
$result = $this->profiles->paginate($options);
$this->assertEquals(1, $result['page']);
}
public function testGetForUrl()
{
$options = array(
'perPage' => 1
);
$result = $this->profiles->getForUrl('/', $options);
$this->assertEquals(1, $result['page']);
$this->assertEquals(2, $result['totalPages']);
$this->assertEquals(1, $result['perPage']);
$this->assertCount(1, $result['results']);
$this->assertInstanceOf('Xhgui_Profile', $result['results'][0]);
$result = $this->profiles->getForUrl('/not-there', $options);
$this->assertCount(0, $result['results']);
}
public function testGetForUrlWithSearch()
{
$options = array(
'perPage' => 2
);
$search = array(
'date_start' => '2013-01-17',
'date_end' => '2013-01-18',
);
$result = $this->profiles->getForUrl('/', $options, $search);
$this->assertEquals(1, $result['page']);
$this->assertEquals(1, $result['totalPages']);
$this->assertEquals(2, $result['perPage']);
$this->assertCount(1, $result['results']);
$search = array(
'date_start' => '2013-01-01',
'date_end' => '2013-01-02',
);
$result = $this->profiles->getForUrl('/', $options, $search);
$this->assertCount(0, $result['results']);
}
public function testGetAvgsForUrl()
{
$result = $this->profiles->getAvgsForUrl('/');
$this->assertCount(2, $result);
$this->assertArrayHasKey('avg_wt', $result[0]);
$this->assertArrayHasKey('avg_cpu', $result[0]);
$this->assertArrayHasKey('avg_mu', $result[0]);
$this->assertArrayHasKey('avg_pmu', $result[0]);
$this->assertEquals('2013-01-18', $result[0]['date']);
$this->assertEquals('2013-01-19', $result[1]['date']);
}
public function testGetAvgsForUrlWithSearch()
{
$search = array('date_start' => '2013-01-18', 'date_end' => '2013-01-18');
$result = $this->profiles->getAvgsForUrl('/', $search);
$this->assertCount(1, $result);
$this->assertArrayHasKey('avg_wt', $result[0]);
$this->assertArrayHasKey('avg_cpu', $result[0]);
$this->assertArrayHasKey('avg_mu', $result[0]);
$this->assertArrayHasKey('avg_pmu', $result[0]);
$this->assertEquals('2013-01-18', $result[0]['date']);
}
public function testGetPercentileForUrlWithSearch()
{
$search = array('date_start' => '2013-01-18', 'date_end' => '2013-01-18');
$result = $this->profiles->getPercentileForUrl(20, '/', $search);
$this->assertCount(1, $result);
$this->assertArrayHasKey('wt', $result[0]);
$this->assertArrayHasKey('cpu', $result[0]);
$this->assertArrayHasKey('mu', $result[0]);
$this->assertArrayHasKey('pmu', $result[0]);
}
public function testGetPercentileForUrlWithLimit()
{
$search = array('limit' => 'P1D');
$result = $this->profiles->getPercentileForUrl(20, '/', $search);
$this->assertCount(0, $result);
}
public function testGetAllConditions()
{
$result = $this->profiles->getAll(array(
'conditions' => array(
'date_start' => '2013-01-20',
'date_end' => '2013-01-21',
'url' => 'tasks',
)
));
$this->assertEquals(1, $result['page']);
$this->assertEquals(25, $result['perPage']);
$this->assertEquals(1, $result['totalPages']);
$this->assertCount(2, $result['results']);
}
}
| Java |
package com.tbp.safemaps;
import the.safemaps.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MarkUnsafe extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marksafe);
//Button back = (Button)findViewById(R.id.mbuttonBack);
Button done = (Button)findViewById(R.id.done);
done.setOnClickListener(onClickListener);
// back.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
// case R.id.go:
// Intent go= new Intent(Markunsafe.this,mapdirections.class);
//startActivity(go);
//break;
}
}
};
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.action_bar:
//Toast.makeText(getBaseContext(), "back", Toast.LENGTH_SHORT).show();
Intent back= new Intent(MarkUnsafe.this,MainActivity.class);
startActivity(back);
break;
}
return true;
}
}
| Java |
#include "protagonist.h"
#include "SerializeResult.h"
#include "v8_wrapper.h"
#include "snowcrash.h"
using namespace v8;
using namespace protagonist;
Result::Result()
{
}
Result::~Result()
{
}
Nan::Persistent<Function> Result::constructor;
void Result::Init(Handle<Object> exports)
{
Nan::HandleScope scope;
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->SetClassName(Nan::New<String>("Result").ToLocalChecked());
t->InstanceTemplate()->SetInternalFieldCount(1);
constructor.Reset(t->GetFunction());
exports->Set(Nan::New<String>("Result").ToLocalChecked(), t->GetFunction());
}
NAN_METHOD(Result::New)
{
Nan::HandleScope scope;
Result* result = ::new Result();
result->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
v8::Local<v8::Object> Result::WrapResult(snowcrash::ParseResult<snowcrash::Blueprint>& parseResult,
const snowcrash::BlueprintParserOptions& options,
const drafter::ASTType& astType)
{
static const char* AstKey = "ast";
static const char* ErrorKey = "error";
static const char* SourcemapKey = "sourcemap";
sos::Object result;
try {
result = drafter::WrapResult(parseResult, options, astType);
}
catch (snowcrash::Error& error) {
parseResult.report.error = error;
}
if (astType == drafter::NormalASTType && parseResult.report.error.code != snowcrash::Error::OK) {
result.set(AstKey, sos::Null());
if ((options & snowcrash::ExportSourcemapOption) != 0) {
result.set(SourcemapKey, sos::Null());
}
}
result.unset(ErrorKey);
return v8_wrap(result)->ToObject();
}
| Java |
<select ng-model="city" ng-options="city.name for city in cities">
<option value="">Choose City</option>
</select>
Best City:{{city.name}}
<label>Select Two Fish</label>
<input type="checkbox" ng-model="isTwoFish"> <br/>
<select>
<option>One Fish</option>
<option ng-selected="isTwoFish">Two Fish</option>
</select>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Sun Jan 11 17:03:54 EET 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.github.tilastokeskus.matertis.core.command (Matertis 1.0-SNAPSHOT Test API)</title>
<meta name="date" content="2015-01-11">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../com/github/tilastokeskus/matertis/core/command/package-summary.html" target="classFrame">com.github.tilastokeskus.matertis.core.command</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="DropCommandTest.html" title="class in com.github.tilastokeskus.matertis.core.command" target="classFrame">DropCommandTest</a></li>
<li><a href="MoveCommandTest.html" title="class in com.github.tilastokeskus.matertis.core.command" target="classFrame">MoveCommandTest</a></li>
<li><a href="PauseCommandTest.html" title="class in com.github.tilastokeskus.matertis.core.command" target="classFrame">PauseCommandTest</a></li>
</ul>
</div>
</body>
</html>
| Java |
<?php
/**
* Craft by Pixel & Tonic
*
* @package Craft
* @author Pixel & Tonic, Inc.
* @copyright Copyright (c) 2014, Pixel & Tonic, Inc.
* @license http://buildwithcraft.com/license Craft License Agreement
* @link http://buildwithcraft.com
*/
// Define path constants
defined('CRAFT_BASE_PATH') || define('CRAFT_BASE_PATH', str_replace('\\', '/', realpath(dirname(__FILE__).'/../../')).'/');
defined('CRAFT_APP_PATH') || define('CRAFT_APP_PATH', CRAFT_BASE_PATH.'app/');
defined('CRAFT_CONFIG_PATH') || define('CRAFT_CONFIG_PATH', CRAFT_BASE_PATH.'config/');
defined('CRAFT_PLUGINS_PATH') || define('CRAFT_PLUGINS_PATH', CRAFT_BASE_PATH.'plugins/');
defined('CRAFT_STORAGE_PATH') || define('CRAFT_STORAGE_PATH', CRAFT_BASE_PATH.'storage/');
defined('CRAFT_TEMPLATES_PATH') || define('CRAFT_TEMPLATES_PATH', CRAFT_BASE_PATH.'templates/');
defined('CRAFT_TRANSLATIONS_PATH') || define('CRAFT_TRANSLATIONS_PATH', CRAFT_BASE_PATH.'translations/');
defined('CRAFT_ENVIRONMENT') || define('CRAFT_ENVIRONMENT', 'craft.dev');
define('YII_ENABLE_EXCEPTION_HANDLER', false);
define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['DOCUMENT_ROOT'] = '/some/path/to/craft.dev';
$_SERVER['HTTP_HOST'] = 'craft.dev';
$_SERVER['HTTPS'] = 'off';
$_SERVER['PHP_SELF'] = '/index.php';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SERVER_PORT'] = 80;
$_SERVER['SCRIPT_FILENAME'] = '/some/path/to/craft.dev/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
function craft_createFolder($path)
{
// Code borrowed from IOHelper...
if (!is_dir($path))
{
$oldumask = umask(0);
if (!mkdir($path, 0755, true))
{
exit('Tried to create a folder at '.$path.', but could not.');
}
// Because setting permission with mkdir is a crapshoot.
chmod($path, 0755);
umask($oldumask);
}
}
function craft_ensureFolderIsReadable($path, $writableToo = false)
{
$realPath = realpath($path);
// !@file_exists('/.') is a workaround for the terrible is_executable()
if ($realPath === false || !is_dir($realPath) || !@file_exists($realPath.'/.'))
{
exit (($realPath !== false ? $realPath : $path).' doesn\'t exist or isn\'t writable by PHP. Please fix that.');
}
if ($writableToo)
{
if (!is_writable($realPath))
{
exit ($realPath.' isn\'t writable by PHP. Please fix that.');
}
}
}
// Validate permissions on craft/config/ and craft/storage/
craft_ensureFolderIsReadable(CRAFT_CONFIG_PATH);
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH, true);
// Create the craft/storage/runtime/ folder if it doesn't already exist
craft_createFolder(CRAFT_STORAGE_PATH.'runtime/');
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH.'runtime/', true);
// change the following paths if necessary
$yiit = CRAFT_APP_PATH.'framework/yiit.php';
$config = CRAFT_APP_PATH.'etc/config/test.php';
require_once($yiit);
require_once CRAFT_APP_PATH.'Craft.php';
require_once CRAFT_APP_PATH.'etc/web/WebApp.php';
require_once CRAFT_APP_PATH.'tests/TestApplication.php';
new Craft\TestApplication($config);
| Java |
require "importu/backends"
class DummyBackend
def self.supported_by_definition?(definition)
false
end
def initialize(finder_fields:, **)
@finder_fields = finder_fields
@objects = []
@max_id = 0
end
def find(record)
@finder_fields.detect do |field_group|
if field_group.respond_to?(:call) # proc
raise "proc-based finder scopes not supported for dummy backend"
else
values = record.values_at(*Array(field_group))
object = @objects.detect {|o| values == o.values_at(*Array(field_group)) }
break object if object
end
end
end
def unique_id(object)
object[:id]
end
def create(record)
object = { id: @max_id += 1 }.merge(record.to_hash)
@objects << object
[:created, object]
end
def update(record, object)
new_object = object.merge(record.to_hash)
if new_object == object
[:unchanged, new_object]
else
@objects[object[:id]-1] = new_object
[:updated, new_object]
end
end
end
Importu::Backends.registry.register(:dummy, DummyBackend)
| Java |
#!/usr/bin/env python3
"""
My radio server application
For my eyes only
"""
#CREATE TABLE Radio(id integer primary key autoincrement, radio text, genre text, url text);
uuid='56ty66ba-6kld-9opb-ak29-0t7f5d294686'
# Import CherryPy global namespace
import os
import sys
import time
import socket
import cherrypy
import sqlite3 as lite
import re
import subprocess
from random import shuffle
# Globals
version = "4.2.1"
database = "database.db"
player = 'omxplayer'
header = '''<!DOCTYPE html>
<html lang="en">
<head>
<title>My Radio Web Server</title>
<meta name="generator" content="Vim">
<meta charset="UTF-8">
<link rel="icon" type="image/png" href="/static/css/icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/static/js/jquery-2.0.3.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="/static/css/sticky-footer.css" rel="stylesheet">
<style media="screen" type="text/css">
#radio-playing { display: none; }
#radio-table { display: none; }
#radio-volume { display: none; }
.jumbotron { padding: 10px 10px; }
</style>
<script type="text/javascript">
function fmodradio(rid) {
$.post('/m/', {id: rid},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function fdelradio(rid) {
var r = confirm("DELETING " + rid);
if (r != true) { return; }
$.post('/d/', {id: rid},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function fplayradio(rid) {
$.post('/p/', {id: rid},
function(data){
$("#radio-playing").html(data);
$("#radio-playing").show();
$("#radio-volume").hide();
},
"html"
);
}
function faddfav(i, g) {
$.post('/haddfav/', {id: i},
function(data){
$("#radio-playing").html(data);
$("#radio-playing").show();
$("#radio-volume").hide();
},
"html"
);
}
function fvolradio(updown) {
$.post('/v/', {vol: updown},
function(data){
$("#radio-volume").html(data);
$("#radio-volume").show();
},
"html"
);
}
function fkilradio() {
$.post('/k/',
function(data){
$("#radio-volume").html(data);
$("#radio-volume").show();
},
"html"
);
}
function fsearch(nam, gen) {
$.post('/g/', {name: nam, genre: gen},
function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function frandom(n, g) {
$.post('/g/', {name: n, genre: g, randomlist:'true'},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
// ----------------------------------------------------------
$(document).ready(function() {
$('body').on('click', '#button-modify', function(e) {
i = $("#idm").val()
n = $("#namem").val()
g = $("#genrem").val()
u = $("#urlm").val()
$.post("/f/", {id: i, name: n, genre: g, url: u})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$('#namem').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#genrem').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#urlm').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#button-search').click(function(e) {
n = $("#name").val()
g = $("#genre").val()
$.post("/g/", {name: n, genre: g})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$('#name').keyup(function(e){
if(e.keyCode == 13) {
$('#button-search').click();
}
});
$('#genre').keyup(function(e){
if(e.keyCode == 13) {
$('#button-search').click();
}
});
$("#button-insert").click(function(e) {
n = $("#namei").val()
g = $("#genrei").val()
u = $("#urli").val()
$.post("/i/", {name: n, genre: g, url: u})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$("#play-radio").click(function(e) {
i = $("#idp").val()
$.post("/p/", {id: i})
.done(function(data) {
$("#radio-playing").html(data);
$("#radio-playing").show();
});
e.preventDefault();
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class='jumbotron'>
<h2><a href="/">Radio</a>
<a href="#" onClick="fvolradio('down')"><span class="glyphicon glyphicon-volume-down"></span></a>
<a href="#" onClick="fvolradio('up')"><span class="glyphicon glyphicon-volume-up"></span></a>
<a href="#" onClick="fkilradio('up')"> <span class="glyphicon glyphicon-record"></span></a>
</h2>
<p>
<div class="form-group">
<input type="text" id="name" name="name" placeholder="radio to search">
<input type="text" id="genre" name="genre" placeholder="genre" >
<button id="button-search">Search</button>
</div>
</p>
<p>
<div class="form-group">
<input type="text" id="namei" name="name" placeholder="Radio Name">
<input type="text" id="genrei" name="genre" placeholder="genre">
<input type="text" id="urli" name="url" placeholder="http://radio.com/stream.mp3">
<button id="button-insert">Insert</button>
<p>
[
<a href="#" onClick="fsearch('', 'rai')"> rai </a>|
<a href="#" onClick="fsearch('','fav')"> fav </a> |
<a href="#" onClick="fsearch('','rmc')"> rmc </a> |
<a href="#" onClick="fsearch('','class')"> class </a> |
<a href="#" onClick="fsearch('','jazz')"> jazz </a> |
<a href="#" onClick="fsearch('','chill')"> chill </a> |
<a href="#" onClick="fsearch('','nl')"> nl </a> |
<a href="#" onClick="fsearch('','bbc')"> bbc </a> |
<a href="#" onClick="fsearch('','uk')"> uk </a> |
<a href="#" onClick="fsearch('','italy')"> italy </a>
]
</p>
</div>
<small><div id="radio-playing"> </div></small>
</br>
</div> <!-- Jumbotron END -->
<div id="radio-volume"> </div>
<div id="radio-table"> </div>
'''
footer = '''<p></div></body></html>'''
def isplayfile(pathname) :
if os.path.isfile(pathname) == False:
return False
ext = os.path.splitext(pathname)[1]
ext = ext.lower()
if (ext == '.mp2') : return True;
if (ext == '.mp3') : return True;
if (ext == '.ogg') : return True;
return False
# ------------------------ AUTHENTICATION --------------------------------
from cherrypy.lib import auth_basic
# Password is: webradio
users = {'admin':'29778a9bdb2253dd8650a13b8e685159'}
def validate_password(self, login, password):
if login in users :
if encrypt(password) == users[login] :
cherrypy.session['username'] = login
cherrypy.session['database'] = userdatabase(login)
return True
return False
def encrypt(pw):
from hashlib import md5
return md5(pw).hexdigest()
# ------------------------ CLASS --------------------------------
class Root:
@cherrypy.expose
def index(self):
html = header
(_1, _2, id) = getradio('0')
(radio, genre, url) = getradio(id)
if id != 0:
html += '''<h3><a href="#" onClick="fplayradio('%s')"> ''' % id
html += '''Play Last Radio %s <span class="glyphicon glyphicon-play"></span></a></h3>''' % radio
html += getfooter()
return html
@cherrypy.expose
def music(self, directory='/mnt/Media/Music/'):
html = header
count = 0
html += '''<table class="table table-condensed">'''
filelist = os.listdir(directory)
filelist.sort()
for f in filelist:
file = os.path.join(directory, f)
html += '''<tr>'''
if isplayfile(file):
html += '''<td ><a href="#" onClick="fplayradio('%s')">''' % file
html += '''Play %s<span class="glyphicon glyphicon-play"></span></a></td>''' % (file)
if os.path.isdir(file):
html += '''<td ><a href="/music?directory=%s">%s</a> </td>''' % (file, f)
html += '''</tr>'''
count += 1
html += '''</table>'''
html += '''</div> </div>'''
html += getfooter()
return html
@cherrypy.expose
def g(self, name="", genre="", randomlist='false'):
list = searchradio(name.decode('utf8'), genre)
count = 0
# Randomlist
if randomlist == 'true' : shuffle(list)
listhtml = '''<table class="table table-condensed">'''
for id,radio,gen,url in list:
listhtml += '''<tr>'''
listhtml += '''<td width="200px"><a href="#" onClick="fmodradio('%s')" alt="%s">%s</a></td>''' % (id, url, radio)
listhtml += '''<td width="100px">%s</td>''' % gen
listhtml += '''<td ><a href="#" onClick="fplayradio('%s')">Play <span class="glyphicon glyphicon-play"></span></a></td>''' % (id)
listhtml += '''</tr>'''
count += 1
listhtml += '''</table>'''
listhtml += '''</div> </div>'''
html = ''
html += '''<div class="row"> <div class="col-md-8"> '''
if randomlist == 'false':
html += '''<h2><a href="#" onClick="frandom(name='%s', genre='%s', randomlist='true')">%d Results for '%s' + '%s'</a></h2>''' % (name, genre, count, name, genre)
else:
html += '''<h2><a href="#" onClick="fsearch(name='%s', genre='%s')">%d Random for '%s' + '%s'</a></h2>''' % (name, genre, count, name, genre)
html += listhtml
return html
@cherrypy.expose
def i(self, name="", genre="", url=""):
html = "<h2>Insert</h2>"
if name == "" or name == None :
html += "Error no name"
return html
if insert(name, genre, url) == False:
html += "Error db "
return html
html += '''<h3>This radio has been inserted</h3>'''
html += '''<p><table class="table table-condensed">'''
html += ''' <tr> '''
html += ''' <td>radio: <strong>%s</strong></td> ''' % name
html += ''' <td>genre: <strong>%s</strong></td> ''' % genre
html += ''' <td>url: <strong><a href="%s" target="_blank">%s</a></strong></td> ''' % (url, url)
html += ''' <td width="300px"><a href="#" onClick="fplayradio('%s')"> Play ''' % url
html += '''<span class="glyphicon glyphicon-play"></span></a></td>'''
html += ''' </tr> '''
html += '''</table>'''
return html
@cherrypy.expose
def d(self, id=""):
html = "<h2>Delete</h2>"
if id == "" or id == None :
html += "Error"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
#if delete(id) == False:
if nonexist(id) == False:
html += "Delete error in id" % id
html += getfooter()
return html
html += "Item %s set as non existent" % id
return html
@cherrypy.expose
def p(self, id):
html = ""
if id == "" or id == None :
html += "Error no radio id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(radio, genre, url) = playradio(id)
if url == '':
html += "Error in parameter %s" % url
return html
cherrypy.session['playing'] = id
html += '''<h3>Now Playing: '''
html += '''<a href="%s">%s</a>''' % (url, radio)
html += '''<a href="#" onClick="fplayradio('%s')">''' % id
html += '''<span class="glyphicon glyphicon-play"></span></a>'''
html += ''' <a href="#" onClick="fmodradio('%s')"><span class="glyphicon glyphicon-pencil"></span></a></small> ''' % id
html += '''<a href="#" onClick="fdelradio('%s')"><span class="glyphicon glyphicon-trash"></span></a> ''' % id
html += '''<a href="#" onClick="faddfav('%s')"><span class="glyphicon glyphicon-star"></span></a>''' % id
html += '''</h3>'''
return html
@cherrypy.expose
def v(self, vol=""):
html = ""
if vol == "" or vol == None :
html += "Error"
v = volume(vol)
html += "<h6>%s (%s) </h6>" % (v, vol)
return html
@cherrypy.expose
def m(self, id):
html = '''<h2>Modify</h2>'''
if id == "" or id == None :
html += "Error"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(name, genre, url) = getradio(id)
html += '<h3>%s | %s | %s</h3>' % (name, genre, url)
html += '''<input type="hidden" id="idm" name="id" value="%s">''' % id
html += '''<input type="text" id="namem" name="name" value="%s">''' % name
html += '''genre: <input type="text" id="genrem" name="genre" value="%s"> ''' % genre
html += '''url: <input type="text" style="min-width: 280px" id="urlm" name="url" value="%s"> ''' % url
html += '''<button id="button-modify">Change</button>'''
html += '''<h3><a href="#" onClick="fdelradio('%s')">Delete? <span class="glyphicon glyphicon-trash"></span></a></h3>''' % id
html += '''<h3><a href="%s" target="_blank">Play in browser <span class="glyphicon glyphicon-music"></span></a>''' % url
return html
@cherrypy.expose
def f(self, id="", name="", genre="", url=""):
html = '''<h2>Modified</h2>'''
if id == "" or id == None :
html += "Error missing id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
if modify(id, name, url, genre) == False:
html += "Error in DB"
return html
(name, genre, url) = getradio(id)
html += '''<p><table class="table table-condensed">'''
html += '''<tr>'''
html += '''<td width="100px"><a href="#" onClick="fmodradio('%s')">''' % id
html += '''Mod <span class="glyphicon glyphicon-pencil"></span></a></td>'''
html += '''<td width="200px">%s</td>''' % name
html += '''<td width="200px">%s</td>''' % genre
html += '''<td><a href="%s" target="_blank">%s</a></td>''' % (url, url)
html += '''<td width="300px"><a href="#" onClick="fplayradio('%s')">'''% url
html += '''Play <span class="glyphicon glyphicon-play"></span></a></td>'''
html += '''</tr>'''
html += '''</table>'''
return html
@cherrypy.expose
def haddfav(self, id=""):
if id == "" or id == None :
html += "Error missing id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(name, genre, url) = getradio(id)
if 'Fav' in genre:
genre = genre.replace(', Fav', '')
star = False
else:
genre += ', Fav'
star = True
if addgen(id, genre) == False:
return ''
(name, genre, url) = getradio(id)
cherrypy.session['playing'] = id
html = '<h3>Now Playing: '
html += '''<a href="%s">%s</a>''' % (url, name)
html += '''<a href="#" onClick="fplayradio('%s')">''' % url
html += '''<span class="glyphicon glyphicon-play"></span></a>'''
html += ''' <a href="#" onClick="fmodradio('%s')"><span class="glyphicon glyphicon-pencil"></span></a></small> ''' % id
html += '''<a href="#" onClick="fdelradio('%s')"><span class="glyphicon glyphicon-trash"></span></a> ''' % id
html += '''<a href="#" onClick="faddfav('%s')"><span class="glyphicon glyphicon-star"></span></a>''' % id
if star:
html += '''Starred'''
html += '''</h3>'''
return html
@cherrypy.expose
def k(self):
html = "<h2>Stopping</h2>"
killall()
return html
# ------------------------ DATABASE --------------------------------
def getfooter() :
global footer, version
db = cherrypy.session['database']
try:
con = lite.connect( db )
cur = con.cursor()
sql = "select radio, genre, url from Radio where id=0"
cur.execute(sql)
(radio, genre, url) = cur.fetchone()
except:
(radio, genre, url) = ('ERROR', sql, '')
con.close()
hostname = socket.gethostname()
f = '''<footer class="footer"> <div class="container">'''
f += '''<p class="text-muted">'''
f += '''Session id: %s - Session Database %s<br>''' % (cherrypy.session.id, cherrypy.session['database'])
f += '''Host: %s - Version: %s - Updated: %s // Last: %s''' % (hostname, version, genre, url)
f += '''</p>'''
f += '''</div></footer>'''
return f + footer
def updateversiondb(cur) :
db = cherrypy.session['database']
username = cherrypy.session['username']
dt = time.strftime("%Y-%m-%d %H:%M:%S")
try:
sql = "UPDATE Radio SET radio='%s', genre='%s' WHERE id = 0" % (hostname, dt)
cur.execute(sql)
except:
return
def delete(id) :
db = cherrypy.session['database']
try:
con = lite.connect( db )
cur = con.cursor()
sql = "DELETE from Radio WHERE id = '%s'" % (id)
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def nonexist(id) :
db = cherrypy.session['database']
sql = "UPDATE Radio set exist = 0 WHERE id = '%s'" % (id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def insert(radio, genre, url) :
db = cherrypy.session['database']
sql = "INSERT INTO Radio (radio, genre, url, exist) VALUES('%s', '%s', '%s', 1)" % (radio, genre, url)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def modify(id, radio, url, genre) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET radio='%s', url='%s', genre='%s', exist=1 WHERE id = %s" % (radio, url, genre, id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def addgen(id, genre) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET genre='%s' WHERE id = %s" % (genre, id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def getradio(id) :
db = cherrypy.session['database']
if id.isdigit() :
sql = "select radio, genre, url from Radio where id=%s" % id
else:
sql = "select radio, genre, url from Radio where url=%s" % id
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
except:
rows = [('Not Found', '', '')]
rows = cur.fetchone()
if rows == None:
rows = ('Not Found', '', '')
con.close()
return rows
def searchradio(radio, genre) :
db = cherrypy.session['database']
#o = 'order by radio'
o = ''
sql = "select id, radio, genre, url from Radio where exist > 0 and radio like '%%%s%%' and genre like '%%%s%%' and id > 0 %s" % (radio, genre, o)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
except:
return [(0, sql, o, genre)]
rows = cur.fetchall()
con.close()
return rows
def updatelastradio(url) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET url='%s' WHERE id=0" % (url)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
con.commit()
con.close()
except:
return
def userdatabase(user) :
db = database
if not os.path.isfile(db):
return None
return db
def getshort(code) :
maxl = 5
newcode = code.replace('http://', '')
if len(newcode) > maxl :
newcode = newcode[0:maxl]
return str(newcode)
def setplayer(p):
global player
player = p
def playradio(urlid):
global player
(radio, genre, url) = getradio(urlid)
status = 0
killall()
if player == 'mpg123':
command = "/usr/bin/mpg123 -q %s" % url
pidplayer = subprocess.Popen(command, shell=True).pid
if player == 'mplayer':
command = "/usr/bin/mplayer -really-quiet %s" % url
pidplayer = subprocess.Popen(command, shell=True).pid
if player == 'omxplayer':
# Process is in background
p = 'omxplayer'
subprocess.Popen([p, url])
updatelastradio(urlid)
return (radio, genre, urlid)
def killall():
global player
status = 0
if player == 'omxplayer':
control = "/usr/local/bin/omxcontrol"
status = subprocess.call([control, "stop"])
status = subprocess.call(["pkill", player])
return status
def volume(vol) :
global player
if player == 'omxplayer':
return volume_omxplayer(vol)
else:
return volume_alsa(vol)
def volume_alsa(vol):
# With ALSA on CHIP
if vol == 'up':
db = subprocess.check_output(["amixer set 'Power Amplifier' 5%+"], shell=True)
#db = os.system("amixer set 'Power Amplifier' 5%+")
if vol == 'down':
db = subprocess.check_output(["amixer set 'Power Amplifier' 5%-"], shell=True)
#db = os.system("amixer set 'Power Amplifier' 5%-")
i = db.rfind(':')
return db[i+1:]
def volume_omxplayer(vol) :
import math
control = "/usr/local/bin/omxcontrol"
if vol == 'up' :
db = subprocess.check_output([control, "volumeup"])
else :
db = subprocess.check_output([control, "volumedown"])
v = subprocess.check_output([control, "volume"])
i = v.rfind(':')
db = 10.0 * math.log(float(v[i+1:]), 10)
volstring = "%-2.2f dB" % db
return volstring
# ------------------------ SYSTEM --------------------------------
def writemypid(pidfile):
pid = str(os.getpid())
with open(pidfile, 'w') as f:
f.write(pid)
f.close
# Cherrypy Management
def error_page_404(status, message, traceback, version):
html = header
html += "%s<br>" % (status)
html += "%s" % (traceback)
html += getfooter()
return html
def error_page_401(status, message, traceback, version):
html = '''<!DOCTYPE html>
<html lang="en">
<head>
<title>My Radio Web Server</title>
<meta name="generator" content="Vim">
<meta charset="UTF-8">
</head>
<body>
'''
html += "<h1>%s</h1>" % (status)
html += "%s<br>" % (message)
return html
# Secure headers!
def secureheaders():
headers = cherrypy.response.headers
headers['X-Frame-Options'] = 'DENY'
headers['X-XSS-Protection'] = '1; mode=block'
headers['Content-Security-Policy'] = "default-src='self'"
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--player', action="store", dest="player", default="mplayer")
parser.add_argument('--stage', action="store", dest="stage", default="production")
parser.add_argument('--database', action="store", dest="database", default="database.db")
parser.add_argument('--root', action="store", dest="root", default=".")
parser.add_argument('--pid', action="store", dest="pid", default="/tmp/8804.pid")
parser.add_argument('--port', action="store", dest="port", type=int, default=8804)
# get args
args = parser.parse_args()
# Where to start, what to get
root = os.path.abspath(args.root)
database = os.path.join(root, args.database)
os.chdir(root)
current_dir = os.path.dirname(os.path.abspath(__file__))
setplayer(args.player)
writemypid(args.pid)
settings = {'global': {'server.socket_host': "0.0.0.0",
'server.socket_port' : args.port,
'log.screen': True,
},
}
conf = {'/static': {'tools.staticdir.on': True,
'tools.staticdir.root': current_dir,
'tools.staticfile.filename': 'icon.png',
'tools.staticdir.dir': 'static'
},
'/': {
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
'tools.auth_basic.checkpassword': validate_password,
'tools.secureheaders.on' : True,
'tools.sessions.on': True,
},
}
cherrypy.config.update(settings)
cherrypy.config.update({'error_page.404': error_page_404})
cherrypy.config.update({'error_page.401': error_page_401})
cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60)
# To make it ZERO CPU usage
#cherrypy.engine.timeout_monitor.unsubscribe()
#cherrypy.engine.autoreload.unsubscribe()
# Cherry insert pages
serverroot = Root()
# Start the CherryPy server.
cherrypy.quickstart(serverroot, config=conf)
| Java |
{% load staticfiles i18n %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{% block title %}netmon{% endblock title %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<![endif]-->
{% block css %}
<!-- Latest compiled and minified Bootstrap 4 Alpha 4 CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" integrity="sha384-2hfp1SzUoho7/TsGGGDaFdsuuDL0LX2hnUp6VkX3CUQ2K4K+xjboZdsXyp4oUHZj" crossorigin="anonymous">
<!-- Your stuff: Third-party CSS libraries go here -->
<!-- This file stores project-specific CSS -->
<link href="{% static 'css/project.css' %}" rel="stylesheet">
{% endblock %}
</head>
<body>
<div class="m-b-1">
<nav class="navbar navbar-dark navbar-static-top bg-inverse">
<div class="container">
<a class="navbar-brand" href="/">netmon</a>
<button type="button" class="navbar-toggler hidden-sm-up pull-xs-right" data-toggle="collapse" data-target="#bs-navbar-collapse-1">
☰
</button>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-toggleable-xs" id="bs-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'home' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'about' %}">About</a>
</li>
{# Links to app.customers #}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Customers
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{% url 'customers:companies' %}">Companies</a>
<a class="dropdown-item" href="{% url 'customers:sites' %}">Sites</a>
</div>
</li>
{# Links to app.netobjects #}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
NetObjects
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{% url 'netobjects:corenetworkobjects' %}">Network Objects</a>
</div>
</li>
</ul>
<ul class="nav navbar-nav pull-xs-right">
{% if request.user.is_authenticated %}
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a class="nav-link" href="{% url 'users:detail' request.user.username %}">{% trans "My Profile" %}</a>
</li>
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a class="nav-link" href="{% url 'account_logout' %}">{% trans "Sign Out" %}</a>
</li>
{% else %}
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a id="sign-up-link" class="nav-link" href="{% url 'account_signup' %}">{% trans "Sign Up" %}</a>
</li>
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a id="log-in-link" class="nav-link" href="{% url 'account_login' %}">{% trans "Sign In" %}</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
</div>
<!-- container -->
<div class="container">
{% if messages %}
{% for message in messages %}
<div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">{{ message }}</div>
{% endfor %}
{% endif %}
{% block content %}
<p>Use this document as a way to quick start any new project.</p>
{% endblock content %}
</div>
{% block modal %}{% endblock modal %}
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
{% block javascript %}
<!-- Required by Bootstrap v4 Alpha 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="sha384-VjEeINv9OSwtWFLAtmc4JCtEJXXBub00gtSnszmspDLCtC0I4z4nqz7rEFbIZLLU" crossorigin="anonymous"></script>
<!-- Your stuff: Third-party javascript libraries go here -->
<!-- place project specific Javascript in this file -->
<script src="{% static 'js/project.js' %}"></script>
{% endblock javascript %}
</body>
</html>
| Java |
require 'spec_helper'
describe 'Git LFS File Locking API' do
include WorkhorseHelpers
let(:project) { create(:project) }
let(:maintainer) { create(:user) }
let(:developer) { create(:user) }
let(:guest) { create(:user) }
let(:path) { 'README.md' }
let(:headers) do
{
'Authorization' => authorization
}.compact
end
shared_examples 'unauthorized request' do
context 'when user is not authorized' do
let(:authorization) { authorize_user(guest) }
it 'returns a forbidden 403 response' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(403)
end
end
end
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
project.add_developer(maintainer)
project.add_developer(developer)
project.add_guest(guest)
end
describe 'Create File Lock endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks" }
let(:authorization) { authorize_user(developer) }
let(:body) { { path: path } }
include_examples 'unauthorized request'
context 'with an existent lock' do
before do
lock_file('README.md', developer)
end
it 'return an error message' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(409)
expect(json_response.keys).to match_array(%w(lock message documentation_url))
expect(json_response['message']).to match(/already locked/)
end
it 'returns the existen lock' do
post_lfs_json url, body, headers
expect(json_response['lock']['path']).to eq('README.md')
end
end
context 'without an existent lock' do
it 'creates the lock' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(201)
expect(json_response['lock'].keys).to match_array(%w(id path locked_at owner))
end
end
end
describe 'Listing File Locks endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
it 'returns the list of locked files' do
lock_file('README.md', developer)
lock_file('README', developer)
do_get url, nil, headers
expect(response).to have_gitlab_http_status(200)
expect(json_response['locks'].size).to eq(2)
expect(json_response['locks'].first.keys).to match_array(%w(id path locked_at owner))
end
end
describe 'List File Locks for verification endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks/verify" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
it 'returns the list of locked files grouped by owner' do
lock_file('README.md', maintainer)
lock_file('README', developer)
post_lfs_json url, nil, headers
expect(response).to have_gitlab_http_status(200)
expect(json_response['ours'].size).to eq(1)
expect(json_response['ours'].first['path']).to eq('README')
expect(json_response['theirs'].size).to eq(1)
expect(json_response['theirs'].first['path']).to eq('README.md')
end
end
describe 'Delete File Lock endpoint' do
let!(:lock) { lock_file('README.md', developer) }
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks/#{lock[:id]}/unlock" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
context 'with an existent lock' do
it 'deletes the lock' do
post_lfs_json url, nil, headers
expect(response).to have_gitlab_http_status(200)
end
it 'returns the deleted lock' do
post_lfs_json url, nil, headers
expect(json_response['lock'].keys).to match_array(%w(id path locked_at owner))
end
end
end
def lock_file(path, author)
result = Lfs::LockFileService.new(project, author, { path: path }).execute
result[:lock]
end
def authorize_user(user)
ActionController::HttpAuthentication::Basic.encode_credentials(user.username, user.password)
end
def post_lfs_json(url, body = nil, headers = nil)
post(url, params: body.try(:to_json), headers: (headers || {}).merge('Content-Type' => LfsRequest::CONTENT_TYPE))
end
def do_get(url, params = nil, headers = nil)
get(url, params: (params || {}), headers: (headers || {}).merge('Content-Type' => LfsRequest::CONTENT_TYPE))
end
def json_response
@json_response ||= JSON.parse(response.body)
end
end
| Java |
---
layout: default
title: Yogi Tea Sayings - Archive
---
{% for post in site.posts %}
<article class="saying">{{ post.title }}</article>
{% endfor %}
| Java |
// -------------------------------------------------------------
// WARNING: this file is used by both the client and the server.
// Do not use any browser or node-specific API!
// -------------------------------------------------------------
/* eslint hammerhead/proto-methods: 2 */
import reEscape from '../utils/regexp-escape';
import INTERNAL_ATTRS from '../processing/dom/internal-attributes';
import { isSpecialPage } from '../utils/url';
const SOURCE_MAP_RE = /#\s*sourceMappingURL\s*=\s*[^\s]+(\s|\*\/)/i;
const CSS_URL_PROPERTY_VALUE_PATTERN = /(url\s*\(\s*)(?:(')([^\s']*)(')|(")([^\s"]*)(")|([^\s\)]*))(\s*\))|(@import\s+)(?:(')([^\s']*)(')|(")([^\s"]*)("))/g;
const STYLESHEET_PROCESSING_START_COMMENT = '/*hammerhead|stylesheet|start*/';
const STYLESHEET_PROCESSING_END_COMMENT = '/*hammerhead|stylesheet|end*/';
const HOVER_PSEUDO_CLASS_RE = /\s*:\s*hover(\W)/gi;
const PSEUDO_CLASS_RE = new RegExp(`\\[${ INTERNAL_ATTRS.hoverPseudoClass }\\](\\W)`, 'ig');
const IS_STYLE_SHEET_PROCESSED_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }`, 'gi');
const STYLESHEET_PROCESSING_COMMENTS_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }\n?|` +
`\n?${ reEscape(STYLESHEET_PROCESSING_END_COMMENT) }\\s*$`, 'gi');
class StyleProcessor {
constructor () {
this.STYLESHEET_PROCESSING_START_COMMENT = STYLESHEET_PROCESSING_START_COMMENT;
this.STYLESHEET_PROCESSING_END_COMMENT = STYLESHEET_PROCESSING_END_COMMENT;
}
process (css, urlReplacer, isStylesheetTable) {
if (!css || typeof css !== 'string' || IS_STYLE_SHEET_PROCESSED_RE.test(css))
return css;
var prefix = isStylesheetTable ? STYLESHEET_PROCESSING_START_COMMENT + '\n' : '';
var postfix = isStylesheetTable ? '\n' + STYLESHEET_PROCESSING_END_COMMENT : '';
// NOTE: Replace the :hover pseudo-class.
css = css.replace(HOVER_PSEUDO_CLASS_RE, '[' + INTERNAL_ATTRS.hoverPseudoClass + ']$1');
// NOTE: Remove the ‘source map’ directive.
css = css.replace(SOURCE_MAP_RE, '$1');
// NOTE: Replace URLs in CSS rules with proxy URLs.
return prefix + this._replaceStylsheetUrls(css, urlReplacer) + postfix;
}
cleanUp (css, parseProxyUrl) {
if (typeof css !== 'string')
return css;
css = css
.replace(PSEUDO_CLASS_RE, ':hover$1')
.replace(STYLESHEET_PROCESSING_COMMENTS_RE, '');
return this._replaceStylsheetUrls(css, url => {
var parsedProxyUrl = parseProxyUrl(url);
return parsedProxyUrl ? parsedProxyUrl.destUrl : url;
});
}
_replaceStylsheetUrls (css, processor) {
return css.replace(
CSS_URL_PROPERTY_VALUE_PATTERN,
(match, prefix1, openQuote1, url1, closeQuote1, openQuote2, url2, closeQuote2, url3, postfix,
prefix2, openQuote3, url4, closeQuote3, openQuote4, url5, closeQuote4) => {
var prefix = prefix1 || prefix2;
var openQuote = openQuote1 || openQuote2 || openQuote3 || openQuote4 || '';
var url = url1 || url2 || url3 || url4 || url5;
var closeQuote = closeQuote1 || closeQuote2 || closeQuote3 || closeQuote4 || '';
postfix = postfix || '';
var processedUrl = isSpecialPage(url) ? url : processor(url);
return url ? prefix + openQuote + processedUrl + closeQuote + postfix : match;
}
);
}
}
export default new StyleProcessor();
| Java |
import announcements from './announcements'
import delegates from './delegates'
import fees from './fees'
import ledger from './ledger'
import market from './market'
import peer from './peer'
import wallets from './wallets'
export {
announcements,
delegates,
fees,
ledger,
market,
peer,
wallets
}
| Java |
/**
* @flow
* @module ProductPropertyInput
* @extends React.PureComponent
*
* @author Oleg Nosov <olegnosov1@gmail.com>
* @license MIT
*
* @description
* React form for product property(options select only).
*
*/
import React, { PureComponent } from "react";
import { isObject } from "../../../helpers";
import type {
GetLocalization,
InputEvent,
ProductPropertyOption,
Prices,
} from "../../../types";
/**
* @typedef {Object.<string, number>} OptionIndex
*/
export type OptionIndex = {
[propertyName: string]: number,
};
/**
* @typedef {Object} OptionObject
*/
export type OptionObject = {|
onSelect?: (option: OptionObject) => void,
additionalCost?: Prices,
value: ProductPropertyOption,
|};
/** @ */
export type PropertyOption = ProductPropertyOption | OptionObject;
/** @ */
export type PropertyOptions = Array<PropertyOption>;
/** @ */
export type OnChange = (obj: { value: OptionIndex }) => void;
export type Props = {|
name: string,
options: PropertyOptions,
selectedOptionIndex: number,
currency: string,
onChange: OnChange,
getLocalization: GetLocalization,
|};
const defaultProps = {
selectedOptionIndex: 0,
};
export default class ProductPropertyInput extends PureComponent<Props, void> {
props: Props;
static defaultProps = defaultProps;
static displayName = "ProductPropertyInput";
/*
* If option value is an object, we need to extract primitive value
*/
static getOptionValue = (value: PropertyOption): ProductPropertyOption =>
isObject(value) ? ProductPropertyInput.getOptionValue(value.value) : value;
/*
* Generate select input options based on options values
*/
static generateOptionsSelectionList = (
options: PropertyOptions,
getLocalization: GetLocalization,
currency: string,
localizationScope: Object = {},
): Array<React$Element<*>> =>
options
.map(ProductPropertyInput.getOptionValue)
.map((optionValue, index) => (
<option key={optionValue} value={optionValue}>
{typeof optionValue === "string"
? getLocalization(optionValue, {
...localizationScope,
...(isObject(options[index])
? {
cost:
(isObject(options[index].additionalCost) &&
options[index].additionalCost[currency]) ||
0,
}
: {}),
})
: optionValue}
</option>
));
handleSelectInputValueChange = ({ currentTarget }: InputEvent) => {
const { value: optionValue } = currentTarget;
const { name, options, onChange } = this.props;
const { getOptionValue } = ProductPropertyInput;
const selectedOptionIndex = options
.map(getOptionValue)
.indexOf(optionValue);
const selectedOption = options[selectedOptionIndex];
if (
isObject(selectedOption) &&
typeof selectedOption.onSelect === "function"
)
selectedOption.onSelect(selectedOption);
onChange({
value: { [name]: selectedOptionIndex },
});
};
render() {
const {
name,
options,
selectedOptionIndex,
currency,
getLocalization,
} = this.props;
const { handleSelectInputValueChange } = this;
const {
generateOptionsSelectionList,
getOptionValue,
} = ProductPropertyInput;
const localizationScope = {
name,
currency,
get localizedName() {
return getLocalization(name, localizationScope);
},
get localizedCurrency() {
return getLocalization(currency, localizationScope);
},
};
return (
<div className="form-group row">
<label
htmlFor={name}
className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col-form-label"
>
{getLocalization("propertyLabel", localizationScope)}
</label>
<div className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<select
onChange={handleSelectInputValueChange}
className="form-control"
value={getOptionValue(options[selectedOptionIndex | 0])}
>
{generateOptionsSelectionList(
options,
getLocalization,
currency,
localizationScope,
)}
</select>
</div>
</div>
);
}
}
| Java |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Message Communications -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492303162911&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=30125&V_SEARCH.docsStart=1&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Message Communications
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>Message Communications</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http://www.messagecommunications.ca"
target="_blank" title="Website URL">http://www.messagecommunications.ca</a></p>
<p><a href="mailto:hello@messagecommunications.ca" title="hello@messagecommunications.ca">hello@messagecommunications.ca</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
601-283 Bannatyne Ave<br/>
WINNIPEG,
Manitoba<br/>
R3B 3B2
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
601-283 Bannatyne Ave<br/>
WINNIPEG,
Manitoba<br/>
R3B 3B2
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(204) 880-4509
</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(866) 739-5719</p>
</div>
<div class="col-md-3 mrgn-tp-md">
<h2 class="wb-inv">Logo</h2>
<img class="img-responsive text-left" src="https://www.ic.gc.ca/app/ccc/srch/media?estblmntNo=234567111997&graphFileName=MC_rgb+site.jpg&applicationCode=AP&lang=eng" alt="Logo" />
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Provides communication planning, copywriting and public relations services to non-profit and corporate sector.<br>
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Deborah
Zanke
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
President
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(204) 880-4509
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(866) 739-5719
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
deborah@messagecommunications.ca
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541820 - Public Relations Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Communications/Public Relations<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Provides communication planning, copywriting and public relations services to non-profit and corporate sector.<br>
<br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Deborah
Zanke
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
President
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(204) 880-4509
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(866) 739-5719
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
deborah@messagecommunications.ca
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541820 - Public Relations Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Communications/Public Relations<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Provides communication planning, copywriting and public relations services to non-profit and corporate sector.<br>
<br>
</div>
</div>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2015-07-07
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| Java |
let BASE_DIR = '/masn01-archive/';
const TAG_OPTIONS = ['meteor', 'cloud', 'bug', 'misc'];
let CURR_DIR = null;
let CURR_FILES = null;
let INIT_CMAP = null;
let CURR_IDX = 0;
let PREV_IDX = null;
$(async function() {
let cameras = JSON.parse(await $.get('cameras.php'));
cameras.forEach((camera) => {
$('#masn-switch').append(`<option value='${camera}/'>${camera}</option>`);
});
BASE_DIR = $('#masn-switch').val();
JS9.ResizeDisplay(750, 750);
TAG_OPTIONS.forEach(tag => $('#tag-select').append(`<option value='${tag}'>${tag}</option>`));
$('#datepicker').prop('disabled', true);
let result = await $.get(BASE_DIR);
let years = getDirectories(result, /\d{4}/);
console.log(years);
new Pikaday({
field: document.getElementById('datepicker'),
format: 'YYYY-MM-DD',
minDate: moment(`${years[0]}-01-01`, 'YYYY-MM-DD').toDate(),
maxDate: moment(`${years[years.length-1]}-12-31`, 'YYYY-MM-DD').toDate(),
defaultDate: moment(`2018-11-20`).toDate(),
onSelect: renderDate,
onDraw: async function(evt) {
let { year, month } = evt.calendars[0];
let { tabs, days } = await $.get(`stats.php?y=${year}&m=${String(month + 1).padStart(2, '0')}`);
let renderedDays = $('.pika-lendar tbody td').filter('[data-day]');
renderedDays.each((_, elem) => {
let dateStr = moment({
day: $(elem).data('day'),
month: month,
year: year
}).format('YYYY-MM-DD');
if (days.indexOf(dateStr) !== -1) {
let dateTab = tabs[days.indexOf(dateStr)];
$(elem).attr('data-tab', dateTab);
if (0 <= dateTab && dateTab < POOR_LIM) $(elem).addClass('day-poor');
else if (POOR_LIM <= dateTab && dateTab < MEDIUM_LIM) $(elem).addClass('day-medium');
else if (MEDIUM_LIM <= dateTab && dateTab < GOOD_LIM) $(elem).addClass('day-good');
}
});
}
});
$('#datepicker').prop('disabled', false);
$('#fileprev').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX - 1 < 0 ? CURR_FILES.length - 1 : CURR_IDX - 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#filenext').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX + 1 >= CURR_FILES.length - 1 ? 0 : CURR_IDX + 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#action-tag').click(function() {
let selectedRegions = JS9.GetRegions('selected');
if (selectedRegions.length === 1) {
$('#tag-select')[0].selectedIndex = 0;
$('#tag-modal').show();
} else if (selectedRegions.length > 1) {
alert('Please select only one region.');
} else {
alert('Please select a region.');
}
});
$('#tag-select').change(function(evt) {
let tag = $(this).val();
if (tag.trim() != '') {
JS9.ChangeRegions('selected', { text: tag, data: { tag: tag } });
saveCurrentRegions();
}
$('#tag-modal').hide();
});
$('#action-reset').click(function() {
if (INIT_CMAP == null) return;
JS9.SetColormap(INIT_CMAP.colormap, INIT_CMAP.contrast, INIT_CMAP.bias);
});
$('#action-save').click(function() {
saveCurrentRegions();
alert('All changes saved.');
});
$('#action-info').click(function() {
$('#info-modal').show();
});
$('.modal-close').click(function() {
$('.modal').hide();
});
$(window).keydown(function(evt) {
if (evt.which === 8 && JS9.GetImageData(true)) saveCurrentRegions();
if (evt.which === 27) $('.modal').hide();
});
});
function createSlider() {
let handle = $('#fits-handle');
handle.text(1);
$('#slider').slider({
value: 1,
min: 1,
max: CURR_FILES.length,
change: function(evt, ui) {
handle.text(ui.value);
CURR_IDX = ui.value - 1;
renderCurrentFile();
},
slide: function(evt, ui) {
handle.text(ui.value);
}
});
}
function getDirectories(html, regex) {
let parser = new DOMParser();
let root = parser.parseFromString(html, 'text/html');
let links = [].slice.call(root.getElementsByTagName('a'));
let hrefs = links.map(link => {
let directory = link.href.endsWith('/');
let dest = (directory ? link.href.slice(0, -1) : link.href).split('/').pop();
return dest.match(regex) ? dest : null;
}).filter(e => e != null);
return hrefs;
}
function renderCurrentFile() {
if (PREV_IDX == CURR_IDX) return;
if (CURR_FILES == null) return;
PREV_IDX = CURR_IDX;
let currentFile = CURR_FILES[CURR_IDX];
let currPath = `${CURR_DIR}/${currentFile}`;
JS9.CloseImage();
PREV_ZOOM = null;
PREV_PAN = null;
$('.JS9PluginContainer').each((idx, elem) => {
if($(elem).find('.tag-toggle, #tag-overlay').length === 0) {
$(elem).append(`<div class='tag-toggle'></div>`);
}
});
JS9.globalOpts.menuBar = ['scale'];
JS9.globalOpts.toolBar = ['box', 'circle', 'ellipse', 'zoom+', 'zoom-', 'zoomtofit'];
JS9.SetToolbar('init');
JS9.Load(currPath, {
zoom: 'ToFit',
onload: async function() {
let fileData = JSON.parse(await $.get({
url: 'regions.php',
cache: false
}, {
action: 'list',
path: currentFile
}));
if (Object.keys(fileData).length > 0) {
fileData.params = JSON.parse(fileData.params);
fileData.params.map(region => {
if (region.data.tag) region.text = region.data.tag;
return region;
});
JS9.AddRegions(fileData.params);
}
JS9.SetZoom('ToFit');
if (JS9.GetFlip() === 'none') JS9.SetFlip('x');
CENTER_PAN = JS9.GetPan();
INIT_CMAP = JS9.GetColormap();
console.log(CENTER_PAN);
$('#viewer-container').show();
$('#actions').show();
$('#filename').text(`${currentFile} (${CURR_IDX + 1}/${CURR_FILES.length})`);
$('#filetime').show();
updateSkymap(currentFile);
}
});
}
async function renderDate(date) {
$('#filename').text('Loading...');
let dateStr = moment(date).format('YYYY-MM-DD');
let yearDir = dateStr.substring(0, 4);
let monthDir = dateStr.substring(0, 7);
let parentDir = `${BASE_DIR}${yearDir}/${monthDir}/${dateStr}`
let list;
try {
list = await $.get(parentDir);
} catch (error) {
list = null;
}
let entries = getDirectories(list, /\.fits?/);
console.log(entries);
PREV_IDX = null;
CURR_IDX = 0;
CURR_DIR = parentDir;
CURR_FILES = entries;
if (list) {
$('#skytab').show().attr('src', `${parentDir}/sky.tab.thumb.png`);
createSlider();
renderCurrentFile();
} else {
$('#skytab').hide();
$('#filename').text('No data.');
$('#filetime').hide();
$('#viewer-container').hide();
$('#actions').hide();
}
}
function saveCurrentRegions() {
let regions = JS9.GetRegions('all');
let tags = JS9.GetRegions('all').map(region => region.data ? region.data.tag : null).filter(tag => tag != null);
$.get({
url: 'regions.php',
cache: false
}, {
action: 'update',
path: CURR_FILES[CURR_IDX],
tags: tags.join(','),
params: JSON.stringify(regions)
}).then(response => {
if (response.trim() !== '') {
alert(`Error saving regions: ${response}`);
}
});
}
| Java |
import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class GlobalSearch extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch
| Java |
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("PollSystem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PollSystem")]
[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("ee67169c-26f5-4dbd-8229-9f8ada329a77")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
<!-- HTML header for doxygen 1.8.10-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>SideCar: SideCar::Parameter::Defs::DynamicRangedTypeTraits< T > Struct Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="DoxygenStyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">SideCar
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceSideCar.html">SideCar</a></li><li class="navelem"><a class="el" href="namespaceSideCar_1_1Parameter.html">Parameter</a></li><li class="navelem"><a class="el" href="namespaceSideCar_1_1Parameter_1_1Defs.html">Defs</a></li><li class="navelem"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits.html">DynamicRangedTypeTraits</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">SideCar::Parameter::Defs::DynamicRangedTypeTraits< T > Struct Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Complete type and class method definitions for a parameter value with dynamically defined value ranges.
<a href="structSideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits.html#details">More...</a></p>
<p><code>#include <<a class="el" href="Parameter_8h_source.html">/Users/howes/src/sidecar/Parameter/Parameter.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for SideCar::Parameter::Defs::DynamicRangedTypeTraits< T >:</div>
<div class="dyncontent">
<div class="center"><img src="structSideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits__inherit__graph.png" border="0" usemap="#SideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits_3_01T_01_4_inherit__map" alt="Inheritance graph"/></div>
<map name="SideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits_3_01T_01_4_inherit__map" id="SideCar_1_1Parameter_1_1Defs_1_1DynamicRangedTypeTraits_3_01T_01_4_inherit__map">
<area shape="rect" id="node2" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html" title="SideCar::Parameter\l::Defs::BasicDynamicRanged\lTypeDef\< T \>" alt="" coords="35,199,228,267"/>
<area shape="rect" id="node3" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html" title="SideCar::Parameter\l::Defs::BasicTypeDef\< T \>" alt="" coords="44,102,220,151"/>
<area shape="rect" id="node5" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html" title="Helper class that initializes an XML-RPC value object with a name and type. " alt="" coords="119,5,256,54"/>
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td colspan="2" onclick="javascript:toggleInherit('pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef')"><img src="closed.png" alt="-"/> Public Types inherited from <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html">SideCar::Parameter::Defs::BasicDynamicRangedTypeDef< T ></a></td></tr>
<tr class="memitem:a95ccf0377a3a21163ee27943afaa708e inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a95ccf0377a3a21163ee27943afaa708e"></a>
using </td><td class="memItemRight" valign="bottom"><b>Super</b> = <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html">BasicTypeDef</a>< T ></td></tr>
<tr class="separator:a95ccf0377a3a21163ee27943afaa708e inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3f613529db0949b79d2e079805770df3 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3f613529db0949b79d2e079805770df3"></a>
using </td><td class="memItemRight" valign="bottom"><b>ValueType</b> = typename T::ValueType</td></tr>
<tr class="separator:a3f613529db0949b79d2e079805770df3 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aaf189c0f613360a7035b72d9948c2339 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aaf189c0f613360a7035b72d9948c2339"></a>
using </td><td class="memItemRight" valign="bottom"><b>XMLType</b> = typename T::XMLType</td></tr>
<tr class="separator:aaf189c0f613360a7035b72d9948c2339 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5195f7974c63e086ec3d450f65ede335 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5195f7974c63e086ec3d450f65ede335"></a>
using </td><td class="memItemRight" valign="bottom"><b>ConstReferenceType</b> = const typename T::ValueType &</td></tr>
<tr class="separator:a5195f7974c63e086ec3d450f65ede335 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td colspan="2" onclick="javascript:toggleInherit('pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef')"><img src="closed.png" alt="-"/> Public Types inherited from <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html">SideCar::Parameter::Defs::BasicTypeDef< T ></a></td></tr>
<tr class="memitem:a1a84d368faf2e57fa930ea1dd613f961 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1a84d368faf2e57fa930ea1dd613f961"></a>
using </td><td class="memItemRight" valign="bottom"><b>ValueType</b> = typename T::ValueType</td></tr>
<tr class="separator:a1a84d368faf2e57fa930ea1dd613f961 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5620f996abc0d415910acfecac60a812 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5620f996abc0d415910acfecac60a812"></a>
using </td><td class="memItemRight" valign="bottom"><b>XMLType</b> = typename T::XMLType</td></tr>
<tr class="separator:a5620f996abc0d415910acfecac60a812 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a57a10640ac22043c5457c45b2621ddfc inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a57a10640ac22043c5457c45b2621ddfc"></a>
using </td><td class="memItemRight" valign="bottom"><b>ReferenceType</b> = typename T::ValueType &</td></tr>
<tr class="separator:a57a10640ac22043c5457c45b2621ddfc inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a884452be4ca790b3e9daa510b3189255 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a884452be4ca790b3e9daa510b3189255"></a>
using </td><td class="memItemRight" valign="bottom"><b>ConstReferenceType</b> = const typename T::ValueType &</td></tr>
<tr class="separator:a884452be4ca790b3e9daa510b3189255 inherit pub_types_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html">SideCar::Parameter::Defs::BasicDynamicRangedTypeDef< T ></a></td></tr>
<tr class="memitem:a0739c380f6dc2305036cf19e58b7380f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#a0739c380f6dc2305036cf19e58b7380f">IsValid</a> (ConstReferenceType value) const</td></tr>
<tr class="memdesc:a0739c380f6dc2305036cf19e58b7380f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Determine if a given value is valid for this type. <a href="#a0739c380f6dc2305036cf19e58b7380f">More...</a><br /></td></tr>
<tr class="separator:a0739c380f6dc2305036cf19e58b7380f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ace87cbab03bcc5f7a987782bdfa6a02f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#ace87cbab03bcc5f7a987782bdfa6a02f">DescribeXML</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &xml, const std::string &name, const std::string &label, bool isAdvanced, XMLType value, XMLType original) const</td></tr>
<tr class="memdesc:ace87cbab03bcc5f7a987782bdfa6a02f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Obtain an XML description with the parameter's value, including bounds information. <a href="#ace87cbab03bcc5f7a987782bdfa6a02f">More...</a><br /></td></tr>
<tr class="separator:ace87cbab03bcc5f7a987782bdfa6a02f inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a401cb19460cf220cdf91eadf976798b0 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#a401cb19460cf220cdf91eadf976798b0">setMinValue</a> (const ValueType &value)</td></tr>
<tr class="memdesc:a401cb19460cf220cdf91eadf976798b0 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Set the parameter's minimum acceptable value. <a href="#a401cb19460cf220cdf91eadf976798b0">More...</a><br /></td></tr>
<tr class="separator:a401cb19460cf220cdf91eadf976798b0 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae936dada01919307c26550539b69a84c inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#ae936dada01919307c26550539b69a84c">setMaxValue</a> (const ValueType &value)</td></tr>
<tr class="memdesc:ae936dada01919307c26550539b69a84c inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Set the parameter's maximum acceptable value. <a href="#ae936dada01919307c26550539b69a84c">More...</a><br /></td></tr>
<tr class="separator:ae936dada01919307c26550539b69a84c inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8a0b9ccc21762188428914fff7315802 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">const ValueType & </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#a8a0b9ccc21762188428914fff7315802">getMinValue</a> () const</td></tr>
<tr class="memdesc:a8a0b9ccc21762188428914fff7315802 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Get the parameter's minimum acceptable value. <a href="#a8a0b9ccc21762188428914fff7315802">More...</a><br /></td></tr>
<tr class="separator:a8a0b9ccc21762188428914fff7315802 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a533ba881f9333abbb89837269ecda4a1 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memItemLeft" align="right" valign="top">const ValueType & </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef.html#a533ba881f9333abbb89837269ecda4a1">getMaxValue</a> () const</td></tr>
<tr class="memdesc:a533ba881f9333abbb89837269ecda4a1 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Get the parameter's maximum acceptable value. <a href="#a533ba881f9333abbb89837269ecda4a1">More...</a><br /></td></tr>
<tr class="separator:a533ba881f9333abbb89837269ecda4a1 inherit pub_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicDynamicRangedTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef')"><img src="closed.png" alt="-"/> Static Public Member Functions inherited from <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html">SideCar::Parameter::Defs::BasicTypeDef< T ></a></td></tr>
<tr class="memitem:a0e5cdbebc3a9b832a85ad82548d67c21 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a0e5cdbebc3a9b832a85ad82548d67c21">IsValid</a> (ConstReferenceType)</td></tr>
<tr class="memdesc:a0e5cdbebc3a9b832a85ad82548d67c21 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Determine if a given value is valid for this type. <a href="#a0e5cdbebc3a9b832a85ad82548d67c21">More...</a><br /></td></tr>
<tr class="separator:a0e5cdbebc3a9b832a85ad82548d67c21 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab30dce3ec33ba109fa57ecdc24aed34a inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#ab30dce3ec33ba109fa57ecdc24aed34a">Load</a> (std::istream &is, ReferenceType value)</td></tr>
<tr class="memdesc:ab30dce3ec33ba109fa57ecdc24aed34a inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Obtain a value from a C++ input stream. <a href="#ab30dce3ec33ba109fa57ecdc24aed34a">More...</a><br /></td></tr>
<tr class="separator:ab30dce3ec33ba109fa57ecdc24aed34a inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1ab5cf347fb98e965584022069ee2725 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a1ab5cf347fb98e965584022069ee2725">Load</a> (ACE_InputCDR &cdr, ReferenceType value)</td></tr>
<tr class="memdesc:a1ab5cf347fb98e965584022069ee2725 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Obtain a value from an ACE CDR input stream. <a href="#a1ab5cf347fb98e965584022069ee2725">More...</a><br /></td></tr>
<tr class="separator:a1ab5cf347fb98e965584022069ee2725 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8c2cb72ccf064f958ec0a396b595db1b inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a8c2cb72ccf064f958ec0a396b595db1b">Save</a> (std::ostream &os, const std::string &name, ConstReferenceType value)</td></tr>
<tr class="memdesc:a8c2cb72ccf064f958ec0a396b595db1b inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Write out a name and value to a C++ output stream. <a href="#a8c2cb72ccf064f958ec0a396b595db1b">More...</a><br /></td></tr>
<tr class="separator:a8c2cb72ccf064f958ec0a396b595db1b inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a49d135f2cf204948a4d802e4b8c59007 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static ACE_OutputCDR & </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a49d135f2cf204948a4d802e4b8c59007">Write</a> (ACE_OutputCDR &cdr, ConstReferenceType value)</td></tr>
<tr class="memdesc:a49d135f2cf204948a4d802e4b8c59007 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Write out a name and value to an ACE CDR output stream. <a href="#a49d135f2cf204948a4d802e4b8c59007">More...</a><br /></td></tr>
<tr class="separator:a49d135f2cf204948a4d802e4b8c59007 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a94b075480720c96b277de587f3397923 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static ValueType </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a94b075480720c96b277de587f3397923">FromXML</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &value)</td></tr>
<tr class="memdesc:a94b075480720c96b277de587f3397923 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Convert an XML-RPC value to the template's value type. <a href="#a94b075480720c96b277de587f3397923">More...</a><br /></td></tr>
<tr class="separator:a94b075480720c96b277de587f3397923 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0e1a449c097613b0c2e9f24979dc0092 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static XMLType </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a0e1a449c097613b0c2e9f24979dc0092">ToXML</a> (ConstReferenceType value)</td></tr>
<tr class="memdesc:a0e1a449c097613b0c2e9f24979dc0092 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Convert a held value into a compatible XML-RPC value. <a href="#a0e1a449c097613b0c2e9f24979dc0092">More...</a><br /></td></tr>
<tr class="separator:a0e1a449c097613b0c2e9f24979dc0092 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a81bc6b726bb8e48c696c4d6042ab8fd3 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef.html#a81bc6b726bb8e48c696c4d6042ab8fd3">DescribeXML</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &xml, const std::string &name, const std::string &label, bool isAdvanced, XMLType value, XMLType original)</td></tr>
<tr class="memdesc:a81bc6b726bb8e48c696c4d6042ab8fd3 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="mdescLeft"> </td><td class="mdescRight">Obtain an XML description with the parameter's value. <a href="#a81bc6b726bb8e48c696c4d6042ab8fd3">More...</a><br /></td></tr>
<tr class="separator:a81bc6b726bb8e48c696c4d6042ab8fd3 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1BasicTypeDef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin')"><img src="closed.png" alt="-"/> Static Public Member Functions inherited from <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html">SideCar::Parameter::Defs::XMLMixin</a></td></tr>
<tr class="memitem:a9a08abbccfa76ca26fe5ab4d452538ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memItemLeft" align="right" valign="top">static <a class="el" href="classLogger_1_1Log.html">Logger::Log</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html#a9a08abbccfa76ca26fe5ab4d452538ce">Log</a> ()</td></tr>
<tr class="memdesc:a9a08abbccfa76ca26fe5ab4d452538ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="mdescLeft"> </td><td class="mdescRight">Obtain the log device for <a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html" title="Helper class that initializes an XML-RPC value object with a name and type. ">XMLMixin</a> log messages. <a href="#a9a08abbccfa76ca26fe5ab4d452538ce">More...</a><br /></td></tr>
<tr class="separator:a9a08abbccfa76ca26fe5ab4d452538ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3d38823e6f1b4c128fc145917c532860 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html#a3d38823e6f1b4c128fc145917c532860">Init</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &xml, const std::string &name, const std::string &typeName, const std::string &label, bool isAdvanced)</td></tr>
<tr class="memdesc:a3d38823e6f1b4c128fc145917c532860 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="mdescLeft"> </td><td class="mdescRight">Initialize an XML-RPC container object with a parameter's name, type, <a class="el" href="namespaceSideCar_1_1GUI.html" title="Namespace for the GUI applications. ">GUI</a> label, and 'advanced' flag. <a href="#a3d38823e6f1b4c128fc145917c532860">More...</a><br /></td></tr>
<tr class="separator:a3d38823e6f1b4c128fc145917c532860 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1a32c77d9d411b7204a45bd3aa1ac8ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html#a1a32c77d9d411b7204a45bd3aa1ac8ce">AddEnumNames</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &xml, const char *const *names, size_t size)</td></tr>
<tr class="memdesc:a1a32c77d9d411b7204a45bd3aa1ac8ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="mdescLeft"> </td><td class="mdescRight">Add enumeration tags to an XML-RPC conainer. <a href="#a1a32c77d9d411b7204a45bd3aa1ac8ce">More...</a><br /></td></tr>
<tr class="separator:a1a32c77d9d411b7204a45bd3aa1ac8ce inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad558c1a3571b68769cb1c8e473c33233 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin.html#ad558c1a3571b68769cb1c8e473c33233">AddEnumNames</a> (<a class="el" href="classXmlRpc_1_1XmlRpcValue.html">XmlRpc::XmlRpcValue</a> &xml, const std::vector< std::string > &names)</td></tr>
<tr class="memdesc:ad558c1a3571b68769cb1c8e473c33233 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="mdescLeft"> </td><td class="mdescRight">Add enumeration tags to an XML-RPC conainer. <a href="#ad558c1a3571b68769cb1c8e473c33233">More...</a><br /></td></tr>
<tr class="separator:ad558c1a3571b68769cb1c8e473c33233 inherit pub_static_methods_structSideCar_1_1Parameter_1_1Defs_1_1XMLMixin"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><h3>template<typename T><br />
struct SideCar::Parameter::Defs::DynamicRangedTypeTraits< T ></h3>
<p>Complete type and class method definitions for a parameter value with dynamically defined value ranges. </p>
<p>Definition at line <a class="el" href="Parameter_8h_source.html#l01171">1171</a> of file <a class="el" href="Parameter_8h_source.html">Parameter.h</a>.</p>
</div><hr/>The documentation for this struct was generated from the following file:<ul>
<li>/Users/howes/src/sidecar/Parameter/<a class="el" href="Parameter_8h_source.html">Parameter.h</a></li>
</ul>
</div><!-- contents -->
<!-- HTML footer for doxygen 1.8.10-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| Java |
require 'test_helper'
class HostRedirectorTest < ActionController::TestCase
tests MyController
setup do
@old_host = get_config_host
set_config_host "localhost"
end
teardown do
set_config_host @old_host
end
test "should get index" do
request.host = "localhost"
get :index
assert_response :success
end
test "should redirect ip" do
request.host = "127.0.0.1"
get :index
assert_permanently_redirected_to "http://localhost/my"
end
test "should redirect hostname" do
request.host = "blah"
get :index
assert_permanently_redirected_to "http://localhost/my"
end
test "should redirect with port" do
request.host = "blah:3000"
get :index
assert_permanently_redirected_to "http://localhost:3000/my"
end
end
| Java |
/***********************************************************************
* Copyright (c) 2015 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
/****
* Please do not link this file directly. It is not part of the libsecp256k1
* project and does not promise any stability in its API, functionality or
* presence. Projects which use this code should instead copy this header
* and its accompanying .c file directly into their codebase.
****/
/* This file defines a function that parses DER with various errors and
* violations. This is not a part of the library itself, because the allowed
* violations are chosen arbitrarily and do not follow or establish any
* standard.
*
* In many places it matters that different implementations do not only accept
* the same set of valid signatures, but also reject the same set of signatures.
* The only means to accomplish that is by strictly obeying a standard, and not
* accepting anything else.
*
* Nonetheless, sometimes there is a need for compatibility with systems that
* use signatures which do not strictly obey DER. The snippet below shows how
* certain violations are easily supported. You may need to adapt it.
*
* Do not use this for new systems. Use well-defined DER or compact signatures
* instead if you have the choice (see secp256k1_ecdsa_signature_parse_der and
* secp256k1_ecdsa_signature_parse_compact).
*
* The supported violations are:
* - All numbers are parsed as nonnegative integers, even though X.609-0207
* section 8.3.3 specifies that integers are always encoded as two's
* complement.
* - Integers can have length 0, even though section 8.3.1 says they can't.
* - Integers with overly long padding are accepted, violation section
* 8.3.2.
* - 127-byte long length descriptors are accepted, even though section
* 8.1.3.5.c says that they are not.
* - Trailing garbage data inside or after the signature is ignored.
* - The length descriptor of the sequence is ignored.
*
* Compared to for example OpenSSL, many violations are NOT supported:
* - Using overly long tag descriptors for the sequence or integers inside,
* violating section 8.1.2.2.
* - Encoding primitive integers as constructed values, violating section
* 8.3.1.
*/
#ifndef SECP256K1_CONTRIB_LAX_DER_PARSING_H
#define SECP256K1_CONTRIB_LAX_DER_PARSING_H
/* #include secp256k1.h only when it hasn't been included yet.
This enables this file to be #included directly in other project
files (such as tests.c) without the need to set an explicit -I flag,
which would be necessary to locate secp256k1.h. */
#ifndef SECP256K1_H
#include <secp256k1.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** Parse a signature in "lax DER" format
*
* Returns: 1 when the signature could be parsed, 0 otherwise.
* Args: ctx: a secp256k1 context object
* Out: sig: a pointer to a signature object
* In: input: a pointer to the signature to be parsed
* inputlen: the length of the array pointed to be input
*
* This function will accept any valid DER encoded signature, even if the
* encoded numbers are out of range. In addition, it will accept signatures
* which violate the DER spec in various ways. Its purpose is to allow
* validation of the Syscoin blockchain, which includes non-DER signatures
* from before the network rules were updated to enforce DER. Note that
* the set of supported violations is a strict subset of what OpenSSL will
* accept.
*
* After the call, sig will always be initialized. If parsing failed or the
* encoded numbers are out of range, signature validation with it is
* guaranteed to fail for every message and public key.
*/
int ecdsa_signature_parse_der_lax(
const secp256k1_context* ctx,
secp256k1_ecdsa_signature* sig,
const unsigned char *input,
size_t inputlen
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_CONTRIB_LAX_DER_PARSING_H */
| Java |
# .NET CoreのプロジェクトをCIする方法
サンプル : https://ci.appveyor.com/project/KazuhitoMiura/dotnetcoresample/history
MSの.NET系のCI…といえばAppVeyorなのですが、.NET Coreのやつは「今まだ対応されてない」ので、 `appveyor.yml` という設定ファイルを書きます。
UIと両方できるのですが、設定ファイルに書きます。
https://github.com/Remote-Pairpro/DotNetCoreSample/blob/master/appveyor.yml
ランナーはxunitをつかってるので、いくつかのサイトでは「特殊な設定が必要」て感じなのですが、自分のプロジェクトでは `dotnet test` だけで行けました。
---
でも、AppVeiyrの売りは
「MS系の.NetのプロジェクトをCIビルド出来る、何も書かなくてもビルドコマンド探したりテスト種探したり、ある程度自動でアジャストしてくる」
ことにあると思うですが、ビルドもテストも書いてしまうなら、その利点も薄れます。
そう、 `.Net Core` なんだから「Linux系のCIサービスでもテスト実行出来る」わけです。
(CircleCIの例とか載せる)
## 参考資料
https://github.com/StevenLiekens/dotnet-core-appveyor/blob/master/appveyor.yml
https://xunit.github.io/docs/getting-started-dotnet-core.html
https://github.com/xunit/xunit/issues/1331
| Java |
---
title: 'off-canvas'
items:
1:
url: /
title: Front Page
icon: home
2:
url: /tools
title: Tools
icon: wrench
3:
url: /forms
title: Forms
icon: files-o
4:
url: /alerts
title: Alerts
icon: bell-o
--- | Java |
PowerdnsOnRails::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
end
| Java |
%"Èíòåëëåêòóàëüíûå" êðåñòèêè-íîëèêè íà Java Internet Prolog
%êîìïüþòåð óìååò èãðàòü è çà êðåñòèêè, è çà 0
% (Ñ) À.À. Òþãàøåâ 2014
%Êëåòêè ïîëÿ çàäàþòñÿ êîîðäèíàòàìè, íàïèìåð, [3,1] - ïðàâûé âåðõíèé óãîë
%ñíà÷àëà íîìåð âåðòèêàëè!
% 1 2 3
%1 | |
%---------------------
%2 | |
%---------------------
%3 | |
%âñïîìîãàòåëüíûé ïðåäèêàò - îïðåäåëÿåò ïóñòîòó ïîëÿ
free(X):-p(-,X).
%âñïîìîãàòåëüíûé ïðåäèêàò - îïðåäåëÿåò, ÷åì èãðàåò ñîïåðíèê
partner(0,x).
partner(x,0).
%âñïîìîãàòåëüíûé ïðåäèêàò - äîïîëíåíèå äî çàïîëíåíèÿ ïîëíîãî ñïèñêà êîîðäèíàò [1,2,3] íà ãåíåðàòîðå âñåõ ïåðåñòàíîâîê ýëåìåíòîâ òðîåê
%ò.å. äëÿ [1,X,2] äàåò X=3, äëÿ [1,2,X] - X=3, äëÿ [X,2,3] - 1, è òàê äàëåå
dop(X):-permutation([1,2,3],X).
%÷òî òàêîå "íà îäíîé ëèíèè"
same_line(S):-glav_diagonal(L),permutation(S,L).
same_line(S):-pob_diagonal(L),permutation(S,L).
same_line(S):-vertikal(L),permutation(S,L).
same_line(S):-horizontal(L),permutation(S,L).
%ãëàâíàÿ è ïîáî÷íàÿ äèàãîíàëè, ãîðèçîíòàëü, âåðòèêàëü
glav_diagonal([[1,1],[2,2],[3,3]]).
pob_diagonal([[3,1],[2,2],[1,3]]).
horizontal([[P,Y],[K,Y],[L,Y]]):-dop([P,K,L]),dop([Y,_,_]).
vertikal([[X,P],[X,K],[X,L]]):-dop([P,K,L]),dop([X,_,_]).
%========================================================== ÎÑÍÎÂÍÀß ËÎÃÈÊÀ ÈÃÐÛ - ïðåäèêàò hod (×åì,Êóäà) íàïðèìåð Hod(x,[3,1]).
%ïîðÿäîê ïðåäèêàòîâ hodl(D,P) èìååò çíà÷åíèå, èñïîëüçóåòñÿ îòñå÷åíèå ! ïîñëå âûáîðà õîäà äëÿ îòáðàñûâàíèÿ íèæåñòîÿùèõ
%------------------ Ïåðâûì äåëîì ïûòàåìñÿ âûèãðàòü, çàòåì íå ïðîèãðàòü
hod(D,P):-free(P),try_win(D,P),!.
%----- íå ïðîèãðàé
hod(D,P):-free(P),not_lose(D,P),!.
%----- Åñëè óæå åñòü äâà îäèíàêîâûõ íà îäíîé ëèíèè -> äåëàåì õîä, ëèáî çàâåðøàþùèé çàïîëíåíèå ëèíèè, ëèáî ìåøàþùèé, åñëè ñòîÿò çíàêè ïðîòèâíèêà
try_win(D,P):-same_line([X,Y,P]),p(D,X),p(D,Y),not(free(X)),!.
not_lose(O,P):-same_line([X,Y,P]),p(D,X),p(D,Y),partner(O,D),!.
%--------------------------------- Ñëåäóþùèé ïî ïðèîðèòåòíîñòè õîä - ïîñòàâèòü âèëêó --------------------------------------------------------
hod(D,P):-free(P),try_attack(D,P),!.
%---------------------------- âèëêà îáðàçóåòñÿ åñëè ñòàíåò ïîñëå õîäà äâà îäèíàêîâûõ çíàêà íà îäíîé ëèíèè, íå áëîêèðîâàíà àòàêà, è åùå ïî îäíîé ëèíèè - òî æå ñàìîå
try_attack(D,X):-same_line([X,P,M]),same_line([X,K,L]),p(D,P),p(D,K),free(M),free(L),P\=K,M\=L,!.
%Åñëè íè÷åãî âûøå íå ïîäîøëî
%------------- âñïîìîãàòåëüíàÿ ëîãèêà äëÿ õîäîâ íà÷àëà èãðû
ugol([3,3]). ugol([1,1]). ugol([1,3]).
%ñàìûé ñèëüíûé ïåðâûé õîä - â [3,1]
hod(_,[3,1]):-free([3,1]),!. %è êðåñòèêàìè, è íîëèêàìè è äîñòóïíîñòü ïîëÿ [3,1] ìîæíî îòäåëüíî íå ïðîâåðÿòü ;-)
hod(0,[2,2]):-free([2,2]),!.
hod(x,U):-free(U),glav_diagonal([P,L,U]),p(0,L),p(x,P),!.
hod(x,U):-free(U),pob_diagonal([P,L,U]),p(0,L),p(x,P),!.
hod(x,[2,2] ):-free([2,2] ),p(0,O),not(ugol(O)),!.
hod(x,X):-free(X),p(0,O),ugol(O),ugol(X),!.
hod(0,[2,1] ):-free([2,1] ),p(0,[2,2] ),!.
hod(0,O):-free(O),ugol(O),p(x,[2,2] ),!.
%èíà÷å - â ïåðâóþ ïîïàâøóþñÿ ñëó÷àéíóþ êëåòêó
hod(D,P):-free(P),!.
| Java |
'''
Test cases for pyclbr.py
Nick Mathewson
'''
from test.test_support import run_unittest, import_module
import sys
from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase
StaticMethodType = type(staticmethod(lambda: None))
ClassMethodType = type(classmethod(lambda c: None))
# Silence Py3k warning
import_module('commands', deprecated=True)
# This next line triggers an error on old versions of pyclbr.
from commands import getstatus
# Here we test the python class browser code.
#
# The main function in this suite, 'testModule', compares the output
# of pyclbr with the introspected members of a module. Because pyclbr
# is imperfect (as designed), testModule is called with a set of
# members to ignore.
class PyclbrTest(TestCase):
def assertListEq(self, l1, l2, ignore):
''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
missing = (set(l1) ^ set(l2)) - set(ignore)
if missing:
print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore)
self.fail("%r missing" % missing.pop())
def assertHasattr(self, obj, attr, ignore):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
if not hasattr(obj, attr): print "???", attr
self.failUnless(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
def assertHaskey(self, obj, key, ignore):
''' succeed iff key in obj or key in ignore. '''
if key in ignore: return
if key not in obj:
print >>sys.stderr, "***", key
self.assertTrue(key in obj)
def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore '''
if a not in ignore and b not in ignore:
self.assertEqual(a, b)
def checkModule(self, moduleName, module=None, ignore=()):
''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
to the actual module object, module. Any identifiers in
ignore are ignored. If no module is provided, the appropriate
module is loaded with __import__.'''
if module is None:
# Import it.
# ('<silly>' is to work around an API silliness in __import__)
module = __import__(moduleName, globals(), {}, ['<silly>'])
dict = pyclbr.readmodule_ex(moduleName)
def ismethod(oclass, obj, name):
classdict = oclass.__dict__
if isinstance(obj, FunctionType):
if not isinstance(classdict[name], StaticMethodType):
return False
else:
if not isinstance(obj, MethodType):
return False
if obj.im_self is not None:
if (not isinstance(classdict[name], ClassMethodType) or
obj.im_self is not oclass):
return False
else:
if not isinstance(classdict[name], FunctionType):
return False
objname = obj.__name__
if objname.startswith("__") and not objname.endswith("__"):
objname = "_%s%s" % (obj.im_class.__name__, objname)
return objname == name
# Make sure the toplevel functions and classes are the same.
for name, value in dict.items():
if name in ignore:
continue
self.assertHasattr(module, name, ignore)
py_item = getattr(module, name)
if isinstance(value, pyclbr.Function):
self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType)))
if py_item.__module__ != moduleName:
continue # skip functions that came from somewhere else
self.assertEquals(py_item.__module__, value.module)
else:
self.failUnless(isinstance(py_item, (ClassType, type)))
if py_item.__module__ != moduleName:
continue # skip classes that came from somewhere else
real_bases = [base.__name__ for base in py_item.__bases__]
pyclbr_bases = [ getattr(base, 'name', base)
for base in value.super ]
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
print >>sys.stderr, "class=%s" % py_item
raise
actualMethods = []
for m in py_item.__dict__.keys():
if ismethod(py_item, getattr(py_item, m), m):
actualMethods.append(m)
foundMethods = []
for m in value.methods.keys():
if m[:2] == '__' and m[-2:] != '__':
foundMethods.append('_'+name+m)
else:
foundMethods.append(m)
try:
self.assertListEq(foundMethods, actualMethods, ignore)
self.assertEquals(py_item.__module__, value.module)
self.assertEqualsOrIgnored(py_item.__name__, value.name,
ignore)
# can't check file or lineno
except:
print >>sys.stderr, "class=%s" % py_item
raise
# Now check for missing stuff.
def defined_in(item, module):
if isinstance(item, ClassType):
return item.__module__ == module.__name__
if isinstance(item, FunctionType):
return item.func_globals is module.__dict__
return False
for name in dir(module):
item = getattr(module, name)
if isinstance(item, (ClassType, FunctionType)):
if defined_in(item, module):
self.assertHaskey(dict, name, ignore)
def test_easy(self):
self.checkModule('pyclbr')
self.checkModule('doctest')
# Silence Py3k warning
rfc822 = import_module('rfc822', deprecated=True)
self.checkModule('rfc822', rfc822)
self.checkModule('difflib')
def test_decorators(self):
# XXX: See comment in pyclbr_input.py for a test that would fail
# if it were not commented out.
#
self.checkModule('test.pyclbr_input')
def test_others(self):
cm = self.checkModule
# These were once about the 10 longest modules
cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator
cm('cgi', ignore=('log',)) # set with = in module
cm('urllib', ignore=('_CFNumberToInt32',
'_CStringFromCFString',
'_CFSetup',
'getproxies_registry',
'proxy_bypass_registry',
'proxy_bypass_macosx_sysconf',
'open_https',
'getproxies_macosx_sysconf',
'getproxies_internetconfig',)) # not on all platforms
cm('pickle')
cm('aifc', ignore=('openfp',)) # set with = in module
cm('Cookie')
cm('sre_parse', ignore=('dump',)) # from sre_constants import *
cm('pdb')
cm('pydoc')
# Tests for modules inside packages
cm('email.parser')
cm('test.test_pyclbr')
def test_main():
run_unittest(PyclbrTest)
if __name__ == "__main__":
test_main()
| Java |
<<<<<<< HEAD
var xmlDoc;
var xmlloaded = false;
var _finalUrl;
/*
* input: none
* output: none
* gets zipcode from the zipcode text field
*/
function createURL() {
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
// document.getElementById("displayURL").innerHTML = _finalUrl; // debugging
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// ready states 1-4 & status 200 = okay
// 0: uninitialized
// 1: loading
// 2: loaded
// 3: interactive
// 4: complete
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
xhttp.open("GET", _finalUrl, true);
xhttp.send();
}
function myFunction(xml) {
var i, buyTickets;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("recommendations");
for (i = 0; i < x.length; i++) {
buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = window.open(buyTickets);
}
| Java |
<div class="col-md-12 remove_padding">
<div class="col-md-4 right_padding ttt_pack" id="rmpd_calculate">
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">Location</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<hr />
<div class="form-group">
<label class="form-input col-md-3">LOCATION: </label>
<div class="input-group col-md-8">
<select class="selectlocation">
<?php foreach ($locations as $location) {
?>
<option <?php if ($location_id == $location['location_id']) {
echo 'selected="selected"';
} ?> value="<?php echo $location['location_id'] ?>"><?php echo $location['location'] ?></option>
<?php
} ?>
</select>
<hr />
</div>
<div class="col-md-12">
<table class="table ">
<tr class="color_green">
<td class="add_text_tran">Expense to reach <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($expenses_price_travel);?></td>
</tr>
<tr class="color-red">
<td class="add_text_tran">Expense at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($expenses_price_des);?></td>
</tr>
<tr class="color-gre">
<td class="add_text_tran">Revenue at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($income_price);?></td>
</tr>
<tr class="<?php if (($income_price - $expenses_price_des) > 0) {
echo 'color-gre';
} else {
echo 'color-red';
}?>">
<td class="add_text_tran">Current <?php if (($income_price - $expenses_price_des) > 0) {
echo 'Profit';
} else {
echo 'losses';
}?> at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt">
<?php
$money = $income_price - $expenses_price_des;
$this->M_tour->convertmoney($money);?>
</td>
</tr>
</table>
</div>
<div class="col-md-12">
<div class="col-md-12 searchform_new searchform">
Tax in location:
<a onclick="addtaxmodal('create','location',0,'name','price');" class="btn">Add tax this location</a>
</div>
<div class="col-md-12 remove_padding">
<?php $taxs = $this->M_tour->getTax('location', $current_location['location_id']);
$total_after_tax = 0;
if ($taxs != false) {
echo '<hr />';
foreach ($taxs as $tax) {
?>
<div class="col-md-12 remove_padding">
<label class="col-md-4"><?php echo $tax['name']; ?> :</label>
<div class="col-md-2 remove_padding searchform_new">
<input class="bnt new_style_tax" readonly="true" type="text" value="<?php echo $tax['tax']; ?>" />
</div>
<div class="col-md-4">
<?php $show_tax = $money * $tax['tax'] / 100;
$total_after_tax = $total_after_tax + $show_tax;
$this->M_tour->convertmoney($show_tax); ?>
</div>
<div class="col-md-2 remove_padding">
<a href="javascript:void(0)" onclick="addtaxmodal('edit','location',<?php echo $tax['id'] ?>,'<?php echo $tax['name']; ?>','<?php echo $tax['tax']; ?>');">Edit</a>
<a onclick="return confirm('Are you sure you want to delete this item?');" href="<?php echo base_url('') ?>the_total_tour/delete_tax/<?php echo $tour['tour_id']; ?>/<?php echo $current_location['location_id']; ?>/<?php echo $tax['id'] ?>">Delete</a>
</div>
</div>
<?php
}
}
?>
</div>
<div class="col-md-12">
<table class="table ">
<tr class="<?php if (($income_price - $expenses_price_des) > 0) {
echo 'color-gre';
} else {
echo 'color-red';
}?>">
<td class="add_text_tran">Current <?php if (($income_price - $expenses_price_des) > 0) {
echo 'Profit';
} else {
echo 'losses';
}?> at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt">
<?php
$this->M_tour->convertmoney($money - $total_after_tax);?>
</td>
</tr>
</table>
</div>
</div>
</div>
<hr />
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">All location of tour</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<table class="table">
<?php
$total = 0;
foreach ($location_caculates as $location_caculate) {
$total = $total + $location_caculate['tax_location_result']; ?>
<tr class="color_green">
<td class="add_text_tran">Total at <?php echo $location_caculate['location']; ?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($location_caculate['tax_location_result']); ?></td>
</tr>
<?php
} ?>
<tr class="color-gre">
<td class="add_text_tran">Total before tax in tour <?php echo $tour['tour'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($total);?></td>
</tr>
<?php
$taxs = $this->M_tour->getTax('tour', $tour['tour_id']);
$total_money_tax = 0;
if ($taxs != false) {
foreach ($taxs as $tax) {
$total_money_tax = $total_money_tax + $total * $tax['tax'] / 100;
}
$total_money = $total - $total_money_tax;
} else {
$total_money = $total;
}
?>
</table>
</div>
<div class="col-md-12 ">
<div class="col-md-12 searchform_new searchform">
Tax in tour:
<a onclick="addtaxmodal('create','tour',0,'name','price');" class="btn">Add tax this tour</a>
</div>
<div class="col-md-12 remove_padding">
<?php $taxs = $this->M_tour->getTax('tour', $tour['tour_id']);
if ($taxs != false) {
echo '<hr />';
foreach ($taxs as $tax) {
?>
<div class="col-md-12 remove_padding">
<label class="col-md-4"><?php echo $tax['name']; ?> :</label>
<div class="col-md-2 remove_padding searchform_new">
<input class="bnt new_style_tax" readonly="true" type="text" value="<?php echo $tax['tax']; ?>" />
</div>
<div class="col-md-4">
<?php $this->M_tour->convertmoney($total_money_tax); ?>
</div>
<div class="col-md-2 remove_padding">
<a href="javascript:void(0)" onclick="addtaxmodal('edit','tour',<?php echo $tax['id'] ?>,'<?php echo $tax['name']; ?>','<?php echo $tax['tax']; ?>');">Edit</a>
<a onclick="return confirm('Are you sure you want to delete this item?');" href="<?php echo base_url('') ?>the_total_tour/delete_tax/<?php echo $tour['tour_id']; ?>/<?php echo $current_location['location_id']; ?>/<?php echo $tax['id'] ?>">Delete</a>
</div>
</div>
<?php
}
}
?>
</div>
</div>
<div class="col-md-12 remove_padding">
<table class="table">
<tr class="color-gre">
<td class="add_text_tran">Total after tax in tour <?php echo $tour['tour'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($total_money);?></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">LIST MEMBER</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<ul>
<li><a href="<?php echo base_url('the_total_tour/caculate').'/'.$check_member['tour_id'].'/'.$location_id;?>">All member</a></li>
<?php foreach ($members as $member) {
if ($member['tm_active'] == 1) {
?>
<li><a href="<?php echo base_url('the_total_tour/caculate').'/'.$check_member['tour_id'].'/'.$location_id.'/'.$member['user_id']; ?>"><?php echo $member['firstname'].' '.$member['lastname']; ?></a></li>
<?php
} else {
?>
<li><?php echo $member['name']; ?></li>
<?php
}
} ?>
<li></li>
</ul>
</div>
</div>
</div>
<div class="col-md-8 left_padding ttt_pack">
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target2">Expense at <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('expenses','at destination');" class="btn">Add Expense</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<th>Receipt</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($expenses as $expense) {
if ($expense['expense_type'] == 'at destination') {
$total = $total + $expense['expense_price'] * $expense['amount']; ?>
<tr style="color: <?php echo $expense['color_front']; ?>; <?php if ($check_member['id'] == $expense['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $expense['expense_name']; ?></td>
<td><?php echo $expense['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($expense['expense_price']); ?></td>
<td><?php echo $expense['firstname'].' '.$expense['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($expense['date'])); ?></td>
<td><img src="<?php echo base_url()."/uploads/".$expense['user_id']."/photo/banner_events/".$expense['receipt']; ?>"width="60" height="60"></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="save_id" value="<?php echo $expense['expense_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $expense['expense_name']; ?>" />
<input type="hidden" class="expense_type" value="at destination" />
<input type="hidden" class="expense_amount" value="<?php echo $expense['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $expense['date']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $expense['expense_price']; ?>" />
<input type="hidden" class="receipt" value="<?php echo $expense['receipt']; ?>" />
<input type="hidden" class="userId" value="<?php echo $expense['user_id']; ?>" />
<a class="bnt" onclick="show_edit_member($(this),'expenses')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $expense['expense_name']; ?>','expenses')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5"><span class="total-value color-red">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target3">Revenue at <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('income','none');" class="btn">Add Revenue</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($incomes as $income) {
$total = $total + $income['income_price'] * $income['amount']; ?>
<tr style="color: <?php echo $income['color_front']; ?>; <?php if ($check_member['id'] == $income['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $income['income_name']; ?></td>
<td><?php echo $income['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($income['income_price']); ?></td>
<td><?php echo $income['firstname'].' '.$income['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($income['date'])); ?></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="expense_amount" value="<?php echo $income['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $income['date']; ?>" />
<input type="hidden" class="save_id" value="<?php echo $income['income_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $income['income_name']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $income['income_price']; ?>" />
<a class="bnt" onclick="show_edit_member($(this),'income')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $income['income_name']; ?>','income')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
?>
<tr>
<td colspan="5"><span class="total-value color-gre">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target1">Expense to reach <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('expenses','travel');" class="btn">Add Expense to reach</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($expenses as $expense) {
if ($expense['expense_type'] == 'travel') {
$total = $total + $expense['expense_price'] * $expense['amount']; ?>
<tr style="color: <?php echo $expense['color_front']; ?>; <?php if ($check_member['id'] == $expense['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $expense['expense_name']; ?></td>
<td><?php echo $expense['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($expense['expense_price']); ?></td>
<td><?php echo $expense['firstname'].' '.$expense['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($expense['date'])); ?></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="expense_amount" value="<?php echo $expense['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $expense['date']; ?>" />
<input type="hidden" class="save_id" value="<?php echo $expense['expense_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $expense['expense_name']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $expense['expense_price']; ?>" />
<input type="hidden" class="expense_type" value="travel" />
<a class="bnt" onclick="show_edit_member($(this),'expenses')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $expense['expense_name']; ?>','expenses')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5"><span class="total-value">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade new_modal_style" id="edit-member-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text">Edit</h4>
<span class="liner"></span>
</div>
<form class="avatar-form" action="<?php echo base_url(); ?>members/update_price" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="price_id" class="price_id_data" value="price_id" />
<input type="hidden" name="tour_id" class="tour_id_data" value="<?php echo $tour_id;?>"/>
<input type="hidden" name="type" class="type_data" value="expenses"/>
<input type="hidden" name="expense_type" class="expense_type_edit" value="travel"/>
<input type="hidden" name="location" class="location" value="<?php echo $current_location['location_id'];?>"/>
<div class="form-group">
<label class="form-input col-md-3">Name</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Price</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_price" name="change_price" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Amount</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_amount_edit" value="1" name="change_amount" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Date</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_date_edit" value="<?php echo date('m/d/Y');?>" id="change_date" name="change_date" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Receipt</label>
<div class="input-group col-md-8">
<div class="zoom_img">
<img src="<?php echo base_url()."/uploads/"; ?>" class="receiptImg col-md-8" id="thumb">
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
</div>
</div>
</div><!-- /.modal -->
<div class="modal fade new_modal_style" id="add-caculate-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text_model">Add </h4>
<span class="liner"></span>
</div>
<?php if(count($expensePer) > 0 && $expensePer['add_expense'] == 1): ?>
<form class="avatar-form" action="<?php echo base_url(); ?>members/addcaculate" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="type" class="type_data_add" value="expenses"/>
<input type="hidden" name="expense_type" class="expense_type_add" value="travel"/>
<input type="hidden" name="tour_id" value="<?php echo $tour['tour_id']; ?>"/>
<input type="hidden" name="location" class="location_add" value="<?php echo $current_location['location_id'];?>"/>
<div class="form-group">
<label class="form-input col-md-3">Name</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name1" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Price</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_price1" name="change_price" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Amount</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_amount" value="1" name="change_amount" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Date</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_date" value="<?php echo date('m/d/Y');?>" id="change_date1" name="change_date" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Upload Receipt</label>
<div class="input-group col-md-8">
<input type="file" name="receipt" id="receiptUp">
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
<?php else: ?>
<p style="text-align:center">You don't have persmission to add expense.</p>
<?php endif; ?>
</div>
</div>
</div><!-- /.modal -->
<div class="modal fade new_modal_style" id="add-tax-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text_model">Add tax</h4>
<span class="liner"></span>
</div>
<form class="avatar-form" action="<?php echo base_url(); ?>more_ttt/addtaxcaculate" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="tour_id" value="<?php echo $tour['tour_id']; ?>"/>
<input type="hidden" name="location" class="location_add" value="<?php echo $current_location['location_id'];?>"/>
<input type="hidden" name="type" class="type_tax" value="location"/>
<input type="hidden" name="type_data" class="type_data" value="create" />
<input type="hidden" name="tax_id" class="tax_id" value="0" />
<div class="form-group">
<label class="form-input col-md-3">Name tax</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name_tax" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Tax</label>
<div class="input-group col-md-8">
<input type="number" min="0.01" step="0.01" max="2500" value="00.00" class="form-control change_price_tax" name="change_price" />
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
</div>
</div>
</div><!-- /.modal -->
<script type="text/javascript">
var value = $(".<?php echo $this->session->userdata('target'); ?>").offset().top - 100;
var domain = "<?php echo base_url(); ?>";
$(".selectlocation").change(function(){
location_id = $(this).val();
<?php
if ($this->uri->segment(5)) {
?>
location.href = "<?php echo base_url('the_total_tour/caculate/').'/'.$tour_id.'/'; ?>"+location_id+'/'+<?php echo $this->uri->segment(5); ?>;
<?php
} else {
?>
location.href = "<?php echo base_url('the_total_tour/caculate/').'/'.$tour_id.'/'; ?>"+location_id;
<?php
}
?>
});
var delete_price_url = '<?php echo base_url('members/delete_price') ?>';
var base_url = '<?php echo base_url() ?>';
var records_per_page = '<?php echo $this->security->get_csrf_hash(); ?>';
var tour_id ='<?php echo $tour_id;?>';
</script>
<script src="<?php echo base_url();?>assets/js/detail_pages/ttt/caculate.js"></script>
<link href='<?php echo base_url() ?>assets/dist/css/alertify.default.css' rel='stylesheet' />
<link href='<?php echo base_url() ?>assets/dist/css/alertify.core.css' rel='stylesheet' />
<link href='<?php echo base_url() ?>assets/css/ttt_styles.css' rel='stylesheet' />
<link href="<?php echo base_url(); ?>assets/map/css/bootstrap-colorpicker.min.css" rel="stylesheet"/>
<script src="<?php echo base_url('assets/dist/js/alertify.min.js');?>"></script>
<script src="<?php echo base_url('assets/dist/js/bootstrap-datepicker.min.js');?>"></script>
<script src="<?php echo base_url(); ?>assets/map/js/bootstrap-colorpicker.min.js"></script>
| Java |
The MIT License (MIT)
Copyright (c) 2015 copyright Juan Quemada
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.
| Java |
import { createElement } from 'react'
import omit from 'lodash/omit'
import { useSpring, animated } from '@react-spring/web'
import { useTheme, useMotionConfig } from '@nivo/core'
import { NoteSvg } from './types'
export const AnnotationNote = <Datum,>({
datum,
x,
y,
note,
}: {
datum: Datum
x: number
y: number
note: NoteSvg<Datum>
}) => {
const theme = useTheme()
const { animate, config: springConfig } = useMotionConfig()
const animatedProps = useSpring({
x,
y,
config: springConfig,
immediate: !animate,
})
if (typeof note === 'function') {
return createElement(note, { x, y, datum })
}
return (
<>
{theme.annotations.text.outlineWidth > 0 && (
<animated.text
x={animatedProps.x}
y={animatedProps.y}
style={{
...theme.annotations.text,
strokeLinejoin: 'round',
strokeWidth: theme.annotations.text.outlineWidth * 2,
stroke: theme.annotations.text.outlineColor,
}}
>
{note}
</animated.text>
)}
<animated.text
x={animatedProps.x}
y={animatedProps.y}
style={omit(theme.annotations.text, ['outlineWidth', 'outlineColor'])}
>
{note}
</animated.text>
</>
)
}
| Java |
package pl.mmorpg.prototype.client.exceptions;
public class UnknownSpellException extends GameException
{
public UnknownSpellException(String identifier)
{
super(identifier);
}
public UnknownSpellException(Class<?> type)
{
super(type.getName());
}
}
| Java |
FROM node
WORKDIR /usr/src/app
COPY package*.json client.js index.html rest-server.js UserModel.js ./
RUN npm ci
EXPOSE 3000
CMD ["npm", "start"]
| Java |
// This file was generated based on 'C:\ProgramData\Uno\Packages\Uno.Collections\0.13.2\Extensions\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#ifndef __APP_UNO_COLLECTIONS_UNION_ENUMERATOR__OUTRACKS_SIMULATOR_BYTECODE_STATEMENT_H__
#define __APP_UNO_COLLECTIONS_UNION_ENUMERATOR__OUTRACKS_SIMULATOR_BYTECODE_STATEMENT_H__
#include <app/Uno.Collections.IEnumerator.h>
#include <app/Uno.Collections.IEnumerator__Outracks_Simulator_Bytecode_Statement.h>
#include <app/Uno.IDisposable.h>
#include <app/Uno.Object.h>
#include <Uno.h>
namespace app { namespace Outracks { namespace Simulator { namespace Bytecode { struct Statement; } } } }
namespace app {
namespace Uno {
namespace Collections {
struct UnionEnumerator__Outracks_Simulator_Bytecode_Statement;
struct UnionEnumerator__Outracks_Simulator_Bytecode_Statement__uType : ::uClassType
{
::app::Uno::Collections::IEnumerator__Outracks_Simulator_Bytecode_Statement __interface_0;
::app::Uno::IDisposable __interface_1;
::app::Uno::Collections::IEnumerator __interface_2;
};
UnionEnumerator__Outracks_Simulator_Bytecode_Statement__uType* UnionEnumerator__Outracks_Simulator_Bytecode_Statement__typeof();
void UnionEnumerator__Outracks_Simulator_Bytecode_Statement___ObjInit(UnionEnumerator__Outracks_Simulator_Bytecode_Statement* __this, ::uObject* first, ::uObject* second);
void UnionEnumerator__Outracks_Simulator_Bytecode_Statement__Dispose(UnionEnumerator__Outracks_Simulator_Bytecode_Statement* __this);
::app::Outracks::Simulator::Bytecode::Statement* UnionEnumerator__Outracks_Simulator_Bytecode_Statement__get_Current(UnionEnumerator__Outracks_Simulator_Bytecode_Statement* __this);
bool UnionEnumerator__Outracks_Simulator_Bytecode_Statement__MoveNext(UnionEnumerator__Outracks_Simulator_Bytecode_Statement* __this);
UnionEnumerator__Outracks_Simulator_Bytecode_Statement* UnionEnumerator__Outracks_Simulator_Bytecode_Statement__New_1(::uStatic* __this, ::uObject* first, ::uObject* second);
void UnionEnumerator__Outracks_Simulator_Bytecode_Statement__Reset(UnionEnumerator__Outracks_Simulator_Bytecode_Statement* __this);
struct UnionEnumerator__Outracks_Simulator_Bytecode_Statement : ::uObject
{
::uStrong< ::uObject*> _current;
::uStrong< ::uObject*> _first;
::uStrong< ::uObject*> _second;
void _ObjInit(::uObject* first, ::uObject* second) { UnionEnumerator__Outracks_Simulator_Bytecode_Statement___ObjInit(this, first, second); }
void Dispose() { UnionEnumerator__Outracks_Simulator_Bytecode_Statement__Dispose(this); }
::app::Outracks::Simulator::Bytecode::Statement* Current() { return UnionEnumerator__Outracks_Simulator_Bytecode_Statement__get_Current(this); }
bool MoveNext() { return UnionEnumerator__Outracks_Simulator_Bytecode_Statement__MoveNext(this); }
void Reset() { UnionEnumerator__Outracks_Simulator_Bytecode_Statement__Reset(this); }
};
}}}
#endif
| Java |
---
layout: automation
title: Automation of Paving, Surfacing, and Tamping Equipment Operators
subtitle: Will robots and artificial intelligence take the job of Paving, Surfacing, and Tamping Equipment Operators? Get the facts.
soc:
code: 47-2071
title: Paving, Surfacing, and Tamping Equipment Operators
definition: 'Operate equipment used for applying concrete, asphalt, or other materials to road beds, parking lots, or airport runways and taxiways, or equipment used for tamping gravel, dirt, or other materials. Includes concrete and asphalt paving machine operators, form tampers, tamping machine operators, and stone spreader operators.'
employment:
current:
us: 51900
projected:
us: 58200
change:
us: 0.121
wage:
hourly:
us: 21.06
annual:
us: 43800
probability:
oxford: 0.83
rank:
oxford: 472
tags:
-
---
| Java |
import { ILogger, getLogger } from './loggers';
import { CancellationToken, ICancellationToken } from '../util/CancellationToken';
import { Step } from './Step';
import { ModuleLoader } from './ModuleLoader';
import * as _ from 'underscore';
import { Guid } from '../util/Guid';
import { InjectorLookup, Module, ModuleRepository } from './Modules';
import { IScope, Scope } from './Scope';
import validateScriptDefinition from './scriptDefinitionValidator';
import * as helpers from '../util/helpers';
import './modules/assert';
import './modules/async';
import './modules/conditional';
import './modules/http';
import './modules/json';
import './modules/loop';
import './modules/math';
import './modules/misc';
import './modules/stats';
import './modules/timer';
import './modules/wait';
const YAML = require('pumlhorse-yamljs');
class ScriptOptions {
logger: ILogger;
}
export interface IScript {
run(context: any, cancellationToken?: ICancellationToken): Promise<any>;
addFunction(name: string, func: Function): void;
addModule(moduleDescriptor: string | Object): void;
id: string;
name: string;
}
export interface IScriptDefinition {
name: string;
description?: string;
modules?: any[];
functions?: Object;
expects?: string[];
steps: any[];
cleanup?: any[];
}
export class Script implements IScript {
id: string;
name: string;
private internalScript: IScriptInternal;
private static readonly DefaultModules = ['assert', 'async', 'conditional', 'json', 'loop', 'math', 'misc', 'timer', 'wait', 'http = http'];
public static readonly StandardModules = Script.DefaultModules.concat(['stats']);
constructor(private scriptDefinition: IScriptDefinition, private scriptOptions?: ScriptOptions) {
validateScriptDefinition(this.scriptDefinition);
this.id = new Guid().value;
this.name = scriptDefinition.name;
if (this.scriptOptions == null) {
this.scriptOptions = new ScriptOptions();
}
if (this.scriptOptions.logger == null) {
this.scriptOptions.logger = getLogger();
}
this.internalScript = new InternalScript(this.id, this.scriptOptions);
}
static create(scriptText: string, scriptOptions?: ScriptOptions): Script {
const scriptDefinition = YAML.parse(scriptText);
return new Script(scriptDefinition, scriptOptions);
}
async run(context?: any, cancellationToken?: ICancellationToken): Promise<any> {
if (cancellationToken == null) cancellationToken = CancellationToken.None;
this.evaluateExpectations(context);
this.loadModules();
this.loadFunctions();
this.loadCleanupSteps();
const scope = new Scope(this.internalScript, context);
try {
await this.internalScript.runSteps(this.scriptDefinition.steps, scope, cancellationToken);
return scope;
}
finally {
await this.runCleanupTasks(scope, cancellationToken);
}
}
addFunction(name: string, func: Function): void {
this.internalScript.functions[name] = func;
}
addModule(moduleDescriptor: string | Object) {
const moduleLocator = ModuleLoader.getModuleLocator(moduleDescriptor);
const mod = ModuleRepository.lookup[moduleLocator.name];
if (mod == null) throw new Error(`Module "${moduleLocator.name}" does not exist`);
if (moduleLocator.hasNamespace) {
helpers.assignObjectByString(this.internalScript.modules, moduleLocator.namespace, mod.getFunctions());
}
else {
_.extend(this.internalScript.modules, mod.getFunctions());
}
_.extend(this.internalScript.injectors, mod.getInjectors())
}
private evaluateExpectations(context: any) {
if (this.scriptDefinition.expects == null) return;
const missingValues = _.difference(this.scriptDefinition.expects.map(m => m.toString()), _.keys(context));
if (missingValues.length > 0) {
throw new Error(missingValues.length > 1
? `Expected values "${missingValues.join(', ')}", but they were not passed`
: `Expected value "${missingValues[0]}", but it was not passed`)
}
}
private loadModules() {
const modules = Script.DefaultModules.concat(this.scriptDefinition.modules == null
? []
: this.scriptDefinition.modules)
for (let i = 0; i < modules.length; i++) {
this.addModule(modules[i]);
}
}
private loadFunctions() {
this.addFunction('debug', (msg) => this.scriptOptions.logger.debug(msg));
this.addFunction('log', (msg) => this.scriptOptions.logger.log(msg));
this.addFunction('warn', (msg) => this.scriptOptions.logger.warn(msg));
this.addFunction('error', (msg) => this.scriptOptions.logger.error(msg));
const functions = this.scriptDefinition.functions;
if (functions == null) {
return;
}
for(let name in functions) {
this.addFunction(name, this.createFunction(functions[name]));
}
}
private createFunction(val) {
if (_.isString(val)) return new Function(val)
function construct(args) {
function DeclaredFunction(): void {
return Function.apply(this, args);
}
DeclaredFunction.prototype = Function.prototype;
return new DeclaredFunction();
}
return construct(val)
}
private loadCleanupSteps() {
if (this.scriptDefinition.cleanup == null) {
return;
}
for (let i = 0; i < this.scriptDefinition.cleanup.length; i++) {
this.internalScript.cleanup.push(this.scriptDefinition.cleanup[i]);
}
}
private async runCleanupTasks(scope: Scope, cancellationToken: ICancellationToken): Promise<any> {
if (this.internalScript.cleanup == null) {
return;
}
for (let i = 0; i < this.internalScript.cleanup.length; i++) {
const task = this.internalScript.cleanup[i];
try {
await this.internalScript.runSteps([task], scope, cancellationToken);
}
catch (e) {
this.scriptOptions.logger.error(`Error in cleanup task: ${e.message}`);
}
}
}
}
export interface IScriptInternal {
modules: Module[];
functions: {[name: string]: Function};
injectors: InjectorLookup;
steps: any[];
cleanup: any[];
emit(eventName: string, eventInfo: any);
addCleanupTask(task: any, atEnd?: boolean);
getModule(moduleName: string): any;
id: string;
runSteps(steps: any[], scope: IScope, cancellationToken?: ICancellationToken): Promise<any>;
}
class InternalScript implements IScriptInternal {
id: string;
modules: Module[];
injectors: InjectorLookup;
functions: {[name: string]: Function};
steps: any[];
cleanup: any[];
private cancellationToken: ICancellationToken;
private isEnded: boolean = false;
constructor(id: string, private scriptOptions: ScriptOptions) {
this.id = id;
this.modules = [];
this.injectors = {
'$scope': (scope: IScope) => scope,
'$logger': () => this.scriptOptions.logger
};
this.functions = {
'end': () => { this.isEnded = true; }
};
this.steps = [];
this.cleanup = [];
}
emit(): void {
}
addCleanupTask(task: any, atEnd?: boolean): void {
if (atEnd) this.cleanup.push(task);
else this.cleanup.splice(0, 0, task);
}
getModule(moduleName: string): any {
return this.modules[moduleName];
}
async runSteps(steps: any[], scope: IScope, cancellationToken: ICancellationToken): Promise<any> {
if (cancellationToken != null) {
this.cancellationToken = cancellationToken;
}
if (steps == null || steps.length == 0) {
this.scriptOptions.logger.warn('Script does not contain any steps');
return;
}
_.extend(scope, this.modules, this.functions);
for (let i = 0; i < steps.length; i++) {
if (this.cancellationToken.isCancellationRequested || this.isEnded) {
return;
}
await this.runStep(steps[i], scope);
}
}
private async runStep(stepDefinition: any, scope: IScope) {
if (_.isFunction(stepDefinition)) {
// If we programatically added a function as a step, just shortcut and run it
return stepDefinition.call(scope);
}
let step: Step;
const lineNumber = stepDefinition.getLineNumber == null ? null : stepDefinition.getLineNumber();
if (_.isString(stepDefinition)) {
step = new Step(stepDefinition, null, scope, this.injectors, lineNumber);
}
else {
const functionName = _.keys(stepDefinition)[0];
step = new Step(functionName, stepDefinition[functionName], scope, this.injectors, lineNumber);
}
await step.run(this.cancellationToken);
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.