repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
cgerrior/recurly-client-net | Library/Coupon.cs | 17804 | using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
namespace Recurly
{
public class Coupon : RecurlyEntity
{
public enum CouponState : short
{
All = 0,
Redeemable,
Expired,
Inactive,
MaxedOut
}
public enum CouponDiscountType
{
Percent,
Dollars
}
public enum CouponDuration
{
Forever,
SingleUse,
Temporal
}
public enum CouponTemporalUnit
{
Day,
Week,
Month,
Year
}
public enum RedemptionResourceType
{
Account,
Subscription
}
public enum CouponType
{
Bulk,
SingleCode,
UniqueCode
}
public RecurlyList<CouponRedemption> Redemptions { get; private set; }
public string CouponCode { get; set; }
public string Name { get; set; }
public string HostedDescription { get; set; }
public string InvoiceDescription { get; set; }
public DateTime? RedeemByDate { get; set; }
public bool? SingleUse { get; set; }
public int? AppliesForMonths { get; set; }
public CouponDuration? Duration { get; set; }
public CouponTemporalUnit? TemporalUnit { get; set; }
public int? TemporalAmount { get; set; }
public int? MaxRedemptions { get; set; }
public bool? AppliesToAllPlans { get; set; }
public bool? AppliesToNonPlanCharges { get; set; }
public int? MaxRedemptionsPerAccount { get; set; }
public string UniqueCodeTemplate { get; set; }
public CouponDiscountType DiscountType { get; private set; }
public CouponState State { get; private set; }
public RedemptionResourceType RedemptionResource { get; set; }
public CouponType Type { get; set; } = CouponType.SingleCode;
/// <summary>
/// A dictionary of currencies and discounts
/// </summary>
public Dictionary<string, int> DiscountInCents { get; private set; }
public int? DiscountPercent { get; private set; }
private int? NumberOfUniqueCodes { get; set; }
private string memberUrl()
{
return UrlPrefix + CouponCode;
}
/// <summary>
/// A list of plans to limit the coupon
/// </summary>
private List<string> _plans;
public List<string> Plans
{
get { return _plans ?? (_plans = new List<string>()); }
}
public DateTime CreatedAt { get; private set; }
#region Constructors
internal Coupon()
{
}
internal Coupon(XmlTextReader xmlReader)
{
ReadXml(xmlReader);
}
/// <summary>
/// Creates a coupon, discounted by a fixed amount
/// </summary>
/// <param name="couponCode"></param>
/// <param name="name"></param>
/// <param name="discountInCents">dictionary of currencies and discounts</param>
public Coupon(string couponCode, string name, Dictionary<string, int> discountInCents)
{
CouponCode = couponCode;
Name = name;
DiscountInCents = discountInCents;
DiscountType = CouponDiscountType.Dollars;
}
/// <summary>
/// Creates a coupon, discounted by percentage
/// </summary>
/// <param name="couponCode"></param>
/// <param name="name"></param>
/// <param name="discountPercent"></param>
public Coupon(string couponCode, string name, int discountPercent)
{
CouponCode = couponCode;
Name = name;
DiscountPercent = discountPercent;
DiscountType = CouponDiscountType.Percent;
}
#endregion
internal const string UrlPrefix = "/coupons/";
/// <summary>
/// Creates this coupon.
/// </summary>
public void Create()
{
Client.Instance.PerformRequest(Client.HttpRequestMethod.Post,
UrlPrefix,
WriteXml,
ReadXml);
}
public void Update()
{
Client.Instance.PerformRequest(Client.HttpRequestMethod.Put,
UrlPrefix + Uri.EscapeUriString(CouponCode),
WriteXmlUpdate);
}
public void Restore()
{
Client.Instance.PerformRequest(Client.HttpRequestMethod.Put,
UrlPrefix + Uri.EscapeUriString(CouponCode) + "/restore",
WriteXmlUpdate);
}
/// <summary>
/// Deactivates this coupon.
/// </summary>
public void Deactivate()
{
Client.Instance.PerformRequest(Client.HttpRequestMethod.Delete,
UrlPrefix + Uri.EscapeUriString(CouponCode));
}
public RecurlyList<Coupon> GetUniqueCouponCodes()
{
var coupons = new CouponList();
var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get,
memberUrl() + "/unique_coupon_codes/",
coupons.ReadXmlList);
return statusCode == HttpStatusCode.NotFound ? null : coupons;
}
public RecurlyList<Coupon> Generate(int amount)
{
NumberOfUniqueCodes = amount;
var coupons = new CouponList();
var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Post,
memberUrl() + "/generate/",
this.WriteGenerateXml,
coupons.ReadFromLocation);
return statusCode == HttpStatusCode.NotFound ? null : coupons;
}
#region Read and Write XML documents
internal override void ReadXml(XmlTextReader reader)
{
while (reader.Read())
{
// End of coupon element, get out of here
if (reader.Name == "coupon" && reader.NodeType == XmlNodeType.EndElement)
break;
if (reader.NodeType != XmlNodeType.Element) continue;
DateTime date;
int m;
switch (reader.Name)
{
case "coupon_code":
CouponCode = reader.ReadElementContentAsString();
break;
case "name":
Name = reader.ReadElementContentAsString();
break;
case "state":
State = reader.ReadElementContentAsString().ParseAsEnum<CouponState>();
break;
case "discount_type":
DiscountType = reader.ReadElementContentAsString().ParseAsEnum<CouponDiscountType>();
break;
case "redemption_resource":
RedemptionResource = reader.ReadElementContentAsString().ParseAsEnum<RedemptionResourceType>();
break;
case "discount_percent":
DiscountPercent = reader.ReadElementContentAsInt();
break;
case "redeem_by_date":
if (DateTime.TryParse(reader.ReadElementContentAsString(), out date))
RedeemByDate = date;
break;
case "single_use":
SingleUse = reader.ReadElementContentAsBoolean();
break;
case "applies_for_months":
if (int.TryParse(reader.ReadElementContentAsString(), out m))
AppliesForMonths = m;
break;
case "duration":
Duration = reader.ReadElementContentAsString().ParseAsEnum<CouponDuration>();
break;
case "temporal_unit":
var element_content = reader.ReadElementContentAsString();
if (element_content != "")
TemporalUnit = element_content.ParseAsEnum<CouponTemporalUnit>();
break;
case "temporal_amount":
if (int.TryParse(reader.ReadElementContentAsString(), out m))
TemporalAmount = m;
break;
case "max_redemptions":
if (int.TryParse(reader.ReadElementContentAsString(), out m))
MaxRedemptions = m;
break;
case "applies_to_all_plans":
AppliesToAllPlans = reader.ReadElementContentAsBoolean();
break;
case "applies_to_non_plan_charges":
AppliesToNonPlanCharges = reader.ReadElementContentAsBoolean();
break;
case "max_redemptions_per_account":
if (int.TryParse(reader.ReadElementContentAsString(), out m))
MaxRedemptionsPerAccount = m;
break;
case "description":
HostedDescription = reader.ReadElementContentAsString();
break;
case "invoice_description":
InvoiceDescription = reader.ReadElementContentAsString();
break;
case "unique_code_template":
UniqueCodeTemplate = reader.ReadElementContentAsString();
break;
case "coupon_type":
var type_content = reader.ReadElementContentAsString();
if (type_content != "")
Type = type_content.ParseAsEnum<CouponType>();
break;
case "created_at":
if (DateTime.TryParse(reader.ReadElementContentAsString(), out date))
CreatedAt = date;
break;
case "plan_codes":
ReadXmlPlanCodes(reader);
break;
case "discount_in_cents":
ReadXmlDiscounts(reader);
break;
}
}
}
internal void ReadXmlPlanCodes(XmlTextReader reader)
{
Plans.Clear();
while (reader.Read())
{
if (reader.Name == "plan_codes" && reader.NodeType == XmlNodeType.EndElement)
break;
if (reader.NodeType != XmlNodeType.Element) continue;
switch (reader.Name)
{
case "plan_code":
Plans.Add(reader.ReadElementContentAsString());
break;
}
}
}
internal void ReadXmlDiscounts(XmlTextReader reader)
{
DiscountInCents = new Dictionary<string, int>();
while (reader.Read())
{
if (reader.Name == "discount_in_cents" && reader.NodeType == XmlNodeType.EndElement)
break;
if (reader.NodeType == XmlNodeType.Element)
{
DiscountInCents.Add(reader.Name, reader.ReadElementContentAsInt());
}
}
}
internal override void WriteXml(XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement("coupon"); // Start: coupon
xmlWriter.WriteElementString("coupon_code", CouponCode);
xmlWriter.WriteElementString("name", Name);
xmlWriter.WriteElementString("hosted_description", HostedDescription);
xmlWriter.WriteElementString("invoice_description", InvoiceDescription);
if (RedeemByDate.HasValue)
xmlWriter.WriteElementString("redeem_by_date", RedeemByDate.Value.ToString("s"));
if (SingleUse.HasValue)
xmlWriter.WriteElementString("single_use", SingleUse.Value.AsString());
if (AppliesForMonths.HasValue)
xmlWriter.WriteElementString("applies_for_months", AppliesForMonths.Value.AsString());
if (Duration != null)
xmlWriter.WriteElementString("duration", Duration.ToString().EnumNameToTransportCase());
if (TemporalUnit != null)
xmlWriter.WriteElementString("temporal_unit", TemporalUnit.ToString().EnumNameToTransportCase());
if (TemporalAmount.HasValue)
xmlWriter.WriteElementString("temporal_amount", TemporalAmount.Value.ToString());
if (AppliesToAllPlans.HasValue)
xmlWriter.WriteElementString("applies_to_all_plans", AppliesToAllPlans.Value.AsString());
if (AppliesToNonPlanCharges.HasValue)
xmlWriter.WriteElementString("applies_to_non_plan_charges", AppliesToNonPlanCharges.Value.AsString());
if(MaxRedemptions.HasValue)
xmlWriter.WriteElementString("max_redemptions", MaxRedemptions.Value.AsString());
if (MaxRedemptionsPerAccount.HasValue)
xmlWriter.WriteElementString("max_redemptions_per_account", MaxRedemptionsPerAccount.Value.AsString());
xmlWriter.WriteElementString("discount_type", DiscountType.ToString().EnumNameToTransportCase());
xmlWriter.WriteElementString("redemption_resource", RedemptionResource.ToString().EnumNameToTransportCase());
xmlWriter.WriteElementString("coupon_type", Type.ToString().EnumNameToTransportCase());
if (Type == CouponType.Bulk)
xmlWriter.WriteElementString("unique_code_template", UniqueCodeTemplate);
if (CouponDiscountType.Percent == DiscountType && DiscountPercent.HasValue)
xmlWriter.WriteElementString("discount_percent", DiscountPercent.Value.AsString());
if (CouponDiscountType.Dollars == DiscountType)
{
xmlWriter.WriteIfCollectionHasAny("discount_in_cents", DiscountInCents, pair => pair.Key,
pair => pair.Value.AsString());
}
xmlWriter.WriteIfCollectionHasAny("plan_codes", Plans, s => "plan_code", s => s);
xmlWriter.WriteEndElement(); // End: coupon
}
public void WriteGenerateXml(XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement("coupon"); // Start: coupon
xmlWriter.WriteElementString("number_of_unique_codes", NumberOfUniqueCodes.Value.AsString());
xmlWriter.WriteEndElement(); // End: coupon
}
internal void WriteXmlUpdate(XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement("coupon"); // Start: coupon
if (!Name.IsNullOrEmpty())
xmlWriter.WriteElementString("name", Name);
if (!HostedDescription.IsNullOrEmpty())
xmlWriter.WriteElementString("hosted_description", HostedDescription);
if (!InvoiceDescription.IsNullOrEmpty())
xmlWriter.WriteElementString("invoice_description", InvoiceDescription);
if (RedeemByDate.HasValue)
xmlWriter.WriteElementString("redeem_by_date", RedeemByDate.Value.ToString("s"));
if (MaxRedemptions.HasValue)
xmlWriter.WriteElementString("max_redemptions", MaxRedemptions.Value.AsString());
if (MaxRedemptionsPerAccount.HasValue)
xmlWriter.WriteElementString("max_redemptions_per_account", MaxRedemptionsPerAccount.Value.AsString());
xmlWriter.WriteEndElement(); // End: coupon
}
#endregion
#region Object Overrides
public override string ToString()
{
return "Recurly Account Coupon: " + CouponCode;
}
public override bool Equals(object obj)
{
var coupon = obj as Coupon;
return coupon != null && Equals(coupon);
}
public bool Equals(Coupon coupon)
{
return CouponCode == coupon.CouponCode;
}
public override int GetHashCode()
{
return CouponCode.GetHashCode();
}
#endregion
}
public sealed class Coupons
{
/// <summary>
/// Look up a coupon
/// </summary>
/// <param name="couponCode">Coupon code</param>
/// <returns></returns>
public static Coupon Get(string couponCode)
{
var coupon = new Coupon();
var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get,
Coupon.UrlPrefix + Uri.EscapeUriString(couponCode),
coupon.ReadXml);
return statusCode == HttpStatusCode.NotFound ? null : coupon;
}
/// <summary>
/// Lists coupons, limited to state
/// </summary>
/// <param name="state">Account state to retrieve</param>
/// <returns></returns>
public static RecurlyList<Coupon> List(Coupon.CouponState state = Coupon.CouponState.All)
{
return new CouponList(Coupon.UrlPrefix + (state != Coupon.CouponState.All ? "?state=" + state.ToString().EnumNameToTransportCase() : ""));
}
}
}
| mit |
yanisIk/Hobdy | Configuration/HobdyNeo4jConfiguration.java | 336 | @Configuration
@EnableNeo4jRepositories
@EnableTransactionManagement
public class HobdyNeo4jConfiguration extends Neo4jConfiguration{
public static final String PATH;
public HobdyNeo4jConfiguration(){
}
@Bean
public GraphDatabaseService graphDatabaseService(){
return new GraphDatabaseFactory.newEmbeddedDatabase(PATH);
}
} | mit |
teeparham/ffaker | test/test_identification_es.rb | 331 | # encoding: utf-8
require 'helper'
class TestFakerIdentificationES < Test::Unit::TestCase
include DeterministicHelper
assert_methods_are_deterministic(FFaker::IdentificationES, :gender)
def setup
@tester = FFaker::IdentificationES
end
def test_gender
assert_match(/(Hombre|Mujer)/, @tester.gender)
end
end
| mit |
cxn03651/write_xlsx | examples/outline_collapsed.rb | 5589 | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#
# Example of how to use Excel::Writer::XLSX to generate Excel outlines and
# grouping.
#
# These examples focus mainly on collapsed outlines. See also the
# outlines.pl example program for more general examples.
#
# reverse ('(c)'), March 2008, John McNamara, jmcnamara@cpan.org
# convert to ruby by Hideo NAKAMURA, nakamura.hideo@gmail.com
#
require 'write_xlsx'
# Create a new workbook and add some worksheets
workbook = WriteXLSX.new('outline.xlsx')
worksheet1 = workbook.add_worksheet('Outlined Rows')
worksheet2 = workbook.add_worksheet('Collapsed Rows 1')
worksheet3 = workbook.add_worksheet('Collapsed Rows 2')
worksheet4 = workbook.add_worksheet('Collapsed Rows 3')
worksheet5 = workbook.add_worksheet('Outline Columns')
worksheet6 = workbook.add_worksheet('Collapsed Columns')
# Add a general format
bold = workbook.add_format(:bold => 1)
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data->SubTotals menu item.
#
# The syntax is: set_row(row, height, XF, hidden, level, collapsed)
worksheet1.set_row(1, nil, nil, 0, 2)
worksheet1.set_row(2, nil, nil, 0, 2)
worksheet1.set_row(3, nil, nil, 0, 2)
worksheet1.set_row(4, nil, nil, 0, 2)
worksheet1.set_row(5, nil, nil, 0, 1)
worksheet1.set_row(6, nil, nil, 0, 2)
worksheet1.set_row(7, nil, nil, 0, 2)
worksheet1.set_row(8, nil, nil, 0, 2)
worksheet1.set_row(9, nil, nil, 0, 2)
worksheet1.set_row(10, nil, nil, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet1, bold)
###############################################################################
#
# Example 2: Create a worksheet with collapsed outlined rows.
# This is the same as the example 1 except that the all rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+' with
# the optional parameter, collapsed.
worksheet2.set_row(1, nil, nil, 1, 2)
worksheet2.set_row(2, nil, nil, 1, 2)
worksheet2.set_row(3, nil, nil, 1, 2)
worksheet2.set_row(4, nil, nil, 1, 2)
worksheet2.set_row(5, nil, nil, 1, 1)
worksheet2.set_row(6, nil, nil, 1, 2)
worksheet2.set_row(7, nil, nil, 1, 2)
worksheet2.set_row(8, nil, nil, 1, 2)
worksheet2.set_row(9, nil, nil, 1, 2)
worksheet2.set_row(10, nil, nil, 1, 1)
worksheet2.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet2, bold)
###############################################################################
#
# Example 3: Create a worksheet with collapsed outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet3.set_row(1, nil, nil, 1, 2)
worksheet3.set_row(2, nil, nil, 1, 2)
worksheet3.set_row(3, nil, nil, 1, 2)
worksheet3.set_row(4, nil, nil, 1, 2)
worksheet3.set_row(5, nil, nil, 0, 1, 1)
worksheet3.set_row(6, nil, nil, 1, 2)
worksheet3.set_row(7, nil, nil, 1, 2)
worksheet3.set_row(8, nil, nil, 1, 2)
worksheet3.set_row(9, nil, nil, 1, 2)
worksheet3.set_row(10, nil, nil, 0, 1, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet3, bold)
###############################################################################
#
# Example 4: Create a worksheet with outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet4.set_row(1, nil, nil, 1, 2)
worksheet4.set_row(2, nil, nil, 1, 2)
worksheet4.set_row(3, nil, nil, 1, 2)
worksheet4.set_row(4, nil, nil, 1, 2)
worksheet4.set_row(5, nil, nil, 1, 1, 1)
worksheet4.set_row(6, nil, nil, 1, 2)
worksheet4.set_row(7, nil, nil, 1, 2)
worksheet4.set_row(8, nil, nil, 1, 2)
worksheet4.set_row(9, nil, nil, 1, 2)
worksheet4.set_row(10, nil, nil, 1, 1, 1)
worksheet4.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet4, bold)
###############################################################################
#
# Example 5: Create a worksheet with outlined columns.
#
data = [
[ 'Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Total' ],
[ 'North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)' ],
[ 'South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)' ],
[ 'East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)' ],
[ 'West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G6)' ]
]
# Add bold format to the first row
worksheet5.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet5.set_column('A:A', 10, bold)
worksheet5.set_column('B:G', 5, nil, 0, 1)
worksheet5.set_column('H:H', 10)
# Write the data and a formula
worksheet5.write_col('A1', data)
worksheet5.write('H6', '=SUM(H2:H5)', bold)
###############################################################################
#
# Example 6: Create a worksheet with collapsed outlined columns.
# This is the same as the previous example except collapsed columns.
# Add bold format to the first row
worksheet6.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet6.set_column('A:A', 10, bold)
worksheet6.set_column('B:G', 5, nil, 1, 1)
worksheet6.set_column('H:H', 10, nil, 0, 0, 1)
# Write the data and a formula
worksheet6.write_col('A1', data)
worksheet6.write('H6', '=SUM(H2:H5)', bold)
workbook.close
| mit |
Blizzard/heroprotocol | heroprotocol/hero_cli.py | 4441 | #!/usr/bin/env python
#
# Copyright 2015-2020 Blizzard Entertainment. Subject to the MIT license.
# See the included LICENSE file for more information.
#
from __future__ import print_function
import argparse
import sys
import json
import mpyq
import pprint
from .compat import json_dumps
from .versions import build, latest
class EventLogger:
def __init__(self, args):
self.args = args
self._event_stats = {}
def log(self, output, event):
# update stats
if '_event' in event and '_bits' in event:
stat = self._event_stats.get(event['_event'], [0, 0])
stat[0] += 1 # count of events
stat[1] += event['_bits'] # count of bits
self._event_stats[event['_event']] = stat
# write structure
if self.args.json:
print(json_dumps(event, encoding='iso-8859-1'))
else:
pprint.pprint(event, stream=output, width=120)
def log_stats(self, output):
for name, stat in sorted(self._event_stats.items(), key=lambda x: x[1][1]):
print('"%s", %d, %d,' % (name, stat[0], stat[1] / 8), file=output)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('replay_file', help='.StormReplay file to load')
parser.add_argument("--gameevents", help="print game events", action="store_true")
parser.add_argument(
"--messageevents", help="print message events", action="store_true"
)
parser.add_argument(
"--trackerevents", help="print tracker events", action="store_true"
)
parser.add_argument(
"--attributeevents", help="print attributes events", action="store_true"
)
parser.add_argument("--header", help="print protocol header", action="store_true")
parser.add_argument("--details", help="print protocol details", action="store_true")
parser.add_argument(
"--initdata", help="print protocol initdata", action="store_true"
)
parser.add_argument("--stats", help="print stats", action="store_true")
parser.add_argument(
"--json",
help="protocol information is printed in json format.",
action="store_true",
)
args = parser.parse_args()
archive = mpyq.MPQArchive(args.replay_file)
logger = EventLogger(args)
# Read the protocol header, this can be read with any protocol
contents = archive.header['user_data_header']['content']
header = latest().decode_replay_header(contents)
if args.header:
logger.log(sys.stdout, header)
# The header's baseBuild determines which protocol to use
baseBuild = header['m_version']['m_baseBuild']
try:
protocol = build(baseBuild)
except:
print('Unsupported base build: %d' % baseBuild, file=sys.stderr)
sys.exit(1)
# Print protocol details
if args.details:
contents = archive.read_file('replay.details')
details = protocol.decode_replay_details(contents)
logger.log(sys.stdout, details)
# Print protocol init data
if args.initdata:
contents = archive.read_file('replay.initData')
initdata = protocol.decode_replay_initdata(contents)
logger.log(
sys.stdout,
initdata['m_syncLobbyState']['m_gameDescription']['m_cacheHandles'],
)
logger.log(sys.stdout, initdata)
# Print game events and/or game events stats
if args.gameevents:
contents = archive.read_file('replay.game.events')
for event in protocol.decode_replay_game_events(contents):
logger.log(sys.stdout, event)
# Print message events
if args.messageevents:
contents = archive.read_file('replay.message.events')
for event in protocol.decode_replay_message_events(contents):
logger.log(sys.stdout, event)
# Print tracker events
if args.trackerevents:
if hasattr(protocol, 'decode_replay_tracker_events'):
contents = archive.read_file('replay.tracker.events')
for event in protocol.decode_replay_tracker_events(contents):
logger.log(sys.stdout, event)
# Print attributes events
if args.attributeevents:
contents = archive.read_file('replay.attributes.events')
attributes = protocol.decode_replay_attributes_events(contents)
logger.log(sys.stdout, attributes)
# Print stats
if args.stats:
logger.log_stats(sys.stderr)
| mit |
mrageh/slow_factory_formatter | example/config/environments/development.rb | 1085 | Example::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
#config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
#config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
#config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
#config.active_record.migration_error = :page_load
#config.active_record.raise_in_transactional_callbacks = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| mit |
TinyPlanetStudios/Project-Crash-Land | export/windows/cpp/obj/src/_List/ListNode.cpp | 4163 | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED__List_ListNode
#include <_List/ListNode.h>
#endif
namespace _List{
void ListNode_obj::__construct( ::Dynamic item, ::_List::ListNode next){
HX_STACK_FRAME("_List.ListNode","new",0x20597943,"_List.ListNode.new","C:\\Haxe\\haxe\\std/List.hx",255,0xa8f1d5ef)
HX_STACK_THIS(this)
HX_STACK_ARG(item,"item")
HX_STACK_ARG(next,"next")
HXLINE( 256) this->item = item;
HXLINE( 257) this->next = next;
}
Dynamic ListNode_obj::__CreateEmpty() { return new ListNode_obj; }
hx::ObjectPtr< ListNode_obj > ListNode_obj::__new( ::Dynamic item, ::_List::ListNode next)
{
hx::ObjectPtr< ListNode_obj > _hx_result = new ListNode_obj();
_hx_result->__construct(item,next);
return _hx_result;
}
Dynamic ListNode_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ListNode_obj > _hx_result = new ListNode_obj();
_hx_result->__construct(inArgs[0],inArgs[1]);
return _hx_result;
}
ListNode_obj::ListNode_obj()
{
}
void ListNode_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ListNode);
HX_MARK_MEMBER_NAME(item,"item");
HX_MARK_MEMBER_NAME(next,"next");
HX_MARK_END_CLASS();
}
void ListNode_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(item,"item");
HX_VISIT_MEMBER_NAME(next,"next");
}
hx::Val ListNode_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"item") ) { return hx::Val( item); }
if (HX_FIELD_EQ(inName,"next") ) { return hx::Val( next); }
}
return super::__Field(inName,inCallProp);
}
hx::Val ListNode_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"item") ) { item=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::_List::ListNode >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ListNode_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("item","\x13","\xc5","\xbf","\x45"));
outFields->push(HX_HCSTRING("next","\xf3","\x84","\x02","\x49"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo ListNode_obj_sMemberStorageInfo[] = {
{hx::fsObject /*Dynamic*/ ,(int)offsetof(ListNode_obj,item),HX_HCSTRING("item","\x13","\xc5","\xbf","\x45")},
{hx::fsObject /*::_List::ListNode*/ ,(int)offsetof(ListNode_obj,next),HX_HCSTRING("next","\xf3","\x84","\x02","\x49")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *ListNode_obj_sStaticStorageInfo = 0;
#endif
static ::String ListNode_obj_sMemberFields[] = {
HX_HCSTRING("item","\x13","\xc5","\xbf","\x45"),
HX_HCSTRING("next","\xf3","\x84","\x02","\x49"),
::String(null()) };
static void ListNode_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ListNode_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ListNode_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ListNode_obj::__mClass,"__mClass");
};
#endif
hx::Class ListNode_obj::__mClass;
void ListNode_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("_List.ListNode","\xd1","\x1b","\xb5","\xda");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = ListNode_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(ListNode_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ListNode_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ListNode_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ListNode_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ListNode_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace _List
| mit |
spoton-marketing/laravel-navigation | src/SpotOnMarketing/Navigation/Exceptions/ContainerException.php | 121 | <?php
namespace SpotOnMarketing\Navigation\Exceptions;
use Exception;
class ContainerException extends Exception
{
}
| mit |
i-am-tom/emmeline | test/list/reduce.js | 762 | //= Emmeline: Pure and Simple Javascript.
//> Tom Harding | thedigitalnatives.co.uk
import test from 'tape'
import { reduce } from '../../list'
//- Convert to an array.
function toArray () {
return [... this]
}
test ('List.Reduce', t => {
function * reduceGen () {
yield 1
yield 2
yield 3
}
t.same
( []
:: reduce
( function () {
return 1
}
, 1
)
, 1
, 'Empty list'
)
t.same
( [1, 3, 5, 7, 9]
:: reduce
( function (that) {
return this + that
}
, 0
)
, 25
, 'General use'
)
t.same
( reduceGen ()
:: reduce
( function (that) {
return this + that
}
, 0
)
, 6
, 'Generators'
)
t.end ()
})
| mit |
fatfreecrm/ffcrm_crowd | lib/ffcrm_crowd/application_controller.rb | 2154 | ApplicationController.class_eval do
include Crowd::SingleSignOn
private
#----------------------------------------------------------------------------
def current_user_session
@current_user_session ||= Authentication.find
# Try AuthLogic first (handles HTTP Basic Auth for XML API), fall back to crowd.
if @current_user_session && @current_user_session.respond_to?(:record)
if @current_user_session.record.suspended?
@current_user_session = nil
end
end
# If @current_user_session fails with AuthLogic, try with crowd.
@current_user_session ||= crowd_token
end
#----------------------------------------------------------------------------
def current_user
unless @current_user
# Create or return current crowd user as FFCRM User model
# (User is pegged via email.)
# Try AuthLogic first (handles HTTP Basic Auth for XML API), fall back to crowd.
if current_user_session && current_user_session.respond_to?(:record)
@current_user ||= current_user_session.record
else
if crowd_authenticated?
unless user = User.find_by_username(crowd_current_user[:name])
# Update username if email is found
if user = User.find_by_email(crowd_current_user[:attributes][:mail])
user.update_attribute(:username, crowd_current_user[:name])
else
user = User.create!(:username => crowd_current_user[:name],
:email => crowd_current_user[:attributes][:mail],
:first_name => crowd_current_user[:attributes][:givenName],
:last_name => crowd_current_user[:attributes][:sn])
end
end
@current_user = user
end
end
# Set locale to user preference.
if @current_user
@current_user.set_individual_locale
@current_user.set_single_access_token
end
User.current_user = @current_user
end
@current_user
end
end
| mit |
jjballano/testProjectGrails3 | client/app/city.service.ts | 536 | import { Injectable } from '@angular/core';
import { Country } from './country'
import { City } from './city'
const COUNTRIES : Country[] = [
{id: 1, name: 'Argentina'},
{id: 2, name: 'Chile'},
{id: 3, name: 'Perú'}
]
const CITIES: City[] = [
{id: 1, name: 'Buenos Aires', country: COUNTRIES[0] },
{id: 2, name: 'Santiago de Chile', country: COUNTRIES[1] },
{id: 3, name: 'Lima', country: COUNTRIES[2] },
]
@Injectable()
export class CityService {
all(): Promise<City[]> {
return Promise.resolve(CITIES);
}
} | mit |
OHIF/Viewers | platform/core/src/measurements/measurementHandlers/handleChildMeasurementRemoved.js | 1534 | import cornerstone from 'cornerstone-core';
import { MeasurementApi } from '../classes';
import log from '../../log';
import refreshCornerstoneViewports from '../lib/refreshCornerstoneViewports';
export default function({ eventData, tool, toolGroupId, toolGroup }) {
log.info('CornerstoneToolsMeasurementRemoved');
const { measurementData } = eventData;
const measurementApi = MeasurementApi.Instance;
if (!measurementApi) {
log.warn('Measurement API is not initialized');
}
const collection = measurementApi.tools[tool.parentTool];
// Stop here if the tool data shall not be persisted (e.g. temp tools)
if (!collection) return;
const measurementIndex = collection.findIndex(
t => t._id === measurementData._id
);
const measurement =
measurementIndex > -1 ? collection[measurementIndex] : null;
// Stop here if the measurement is already gone or never existed
if (!measurement) return;
if (measurement.childToolsCount === 1) {
// Remove the measurement
collection.splice(measurementIndex, 1);
measurementApi.onMeasurementRemoved(tool.parentTool, measurement);
} else {
// Update the measurement
measurement[tool.attribute] = null;
measurement.childToolsCount = (measurement.childToolsCount || 0) - 1;
measurementApi.updateMeasurement(tool.parentTool, measurement);
}
// TODO: This is very hacky, but will work for now
refreshCornerstoneViewports();
if (MeasurementApi.isToolIncluded(tool)) {
// TODO: Notify that viewer suffered changes
}
}
| mit |
IvanBernatovic/gameshop | app/Http/Controllers/Admin/CustomerController.php | 547 | <?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
/**
* Custom models
*/
use App\User;
class CustomerController extends Controller
{
const PAGINATION_SIZE = 40;
public function index()
{
$customers = User::paginate(self::PAGINATION_SIZE);
return view('admin.customers.index', compact('customers'));
}
public function show(User $user)
{
return view('admin.customers.show', ['customer' => $user]);
}
}
| mit |
jotak/mipod | libtypes/TagsMap.ts | 1191 | /*
The MIT License (MIT)
Copyright (c) 2014 Joel Takvorian, https://github.com/jotak/mipod
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.
*/
"use strict";
interface TagsMap { [key: string]: any; }
export = TagsMap;
| mit |
brewdente/AutoWebPerf | MasterDevs.ChromeDevTools/Protocol/DOMDebugger/RemoveDOMBreakpointCommandResponse.cs | 381 | using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.DOMDebugger
{
/// <summary>
/// Removes DOM breakpoint that was set using <code>setDOMBreakpoint</code>.
/// </summary>
[CommandResponse(ProtocolName.DOMDebugger.RemoveDOMBreakpoint)]
public class RemoveDOMBreakpointCommandResponse
{
}
}
| mit |
peterellisjones/rust_move_gen | src/position/fen.rs | 10622 | use super::State;
use castling_rights::*;
use piece::*;
use side::*;
use square;
use square::Square;
pub fn from_fen(fen: &str) -> Result<([Piece; 64], State), String> {
let mut state = State {
castling_rights: ALL_RIGHTS,
ep_square: None,
stm: WHITE,
half_move_clock: 0,
full_move_number: 1,
};
let parts: Vec<&str> = fen.split(' ').collect();
if parts.is_empty() {
return Err(format!("Not enough fields for FEN: {}", fen));
}
let grid = parse_rows(parts[0])?;
if parts.len() > 1 {
state.stm = parse_stm(parts[1])?;
}
if parts.len() > 2 {
state.castling_rights = parse_castling_rights(parts[2])?;
}
if parts.len() > 3 {
state.ep_square = Square::parse(parts[3])?;
}
if parts.len() > 4 && parts[4] != "-" {
match parts[4].parse::<u8>() {
Ok(hmc) => state.half_move_clock = hmc,
Err(err) => return Err(err.to_string()),
}
}
if parts.len() > 5 && parts[5] != "-" {
match parts[5].parse::<u16>() {
Ok(fmn) => state.full_move_number = fmn,
Err(err) => return Err(err.to_string()),
}
}
Ok((grid, state))
}
pub fn to_fen(grid: &[Piece; 64], state: &State) -> String {
let mut fen = String::new();
for row in 0..8 {
let mut empties = 0;
for col in 0..8 {
let piece = grid[Square::from(7 - row, col).to_usize()];
if piece.is_none() {
empties += 1;
} else {
if empties > 0 {
fen += &empties.to_string();
empties = 0;
}
fen.push(piece.to_char());
}
}
if empties > 0 {
fen += &empties.to_string();
}
if row != 7 {
fen.push('/')
}
}
fen.push(' ');
fen.push(state.stm.to_char());
fen.push(' ');
fen += &state.castling_rights.to_string();
fen.push(' ');
fen += &(if let Some(sq) = state.ep_square {
sq.to_string()
} else {
"-".to_string()
});
fen.push(' ');
fen += &state.half_move_clock.to_string();
fen.push(' ');
fen += &state.full_move_number.to_string();
fen
}
fn parse_stm(s: &str) -> Result<Side, String> {
match s.chars().next() {
Some(c) => Side::parse(c),
None => Err("String too short".to_string()),
}
}
fn parse_castling_rights(s: &str) -> Result<CastlingRights, String> {
if s == "-" {
return Ok(NO_RIGHTS);
}
let mut rights = NO_RIGHTS;
for c in s.chars() {
rights.set(CastlingRights::parse(c)?)
}
Ok(rights)
}
fn parse_rows(fen: &str) -> Result<[Piece; 64], String> {
let mut grid = [NULL_PIECE; 64];
for (i, row) in fen.split('/').enumerate() {
if i >= 8 {
break;
}
if let Some(err) = parse_row(row, 7 - i, &mut grid) {
return Err(err);
}
}
Ok(grid)
}
fn parse_row(row_str: &str, row: usize, grid: &mut [Piece; 64]) -> Option<String> {
let mut col = 0;
for c in row_str.chars() {
if ('1'..='8').contains(&c) {
col += c as usize - '1' as usize;
} else {
if col >= 8 {
return Some(format!("Too many pieces on row {}", row + 1));
}
match Piece::parse(c) {
Ok(pc) => {
let sq = Square::from(row as square::Internal, col as square::Internal);
grid[sq.to_usize()] = pc;
}
Err(err) => {
return Some(err);
}
}
}
col += 1;
}
None
}
#[cfg(test)]
mod test {
use castle::*;
use castling_rights::*;
use position::*;
use square::*;
use unindent;
#[test]
fn parse_convert_to_fen_1() {
let result = Position::from_fen(STARTING_POSITION_FEN);
assert!(result.is_ok());
let position = result.unwrap();
let fen = position.to_fen();
assert_eq!(fen, STARTING_POSITION_FEN);
}
#[test]
fn parse_convert_to_fen_2() {
let initial_fen = "rnbqkbnr/pppppp2/6pp/8/8/PP5P/2PPPPP1/RNBQKBNR w \
QqKk - 0 1";
let result = Position::from_fen(initial_fen);
assert!(result.is_ok());
let position = result.unwrap();
let fen = position.to_fen();
assert_eq!(fen, initial_fen);
}
#[test]
fn parse_convert_to_fen_3() {
let initial_fen = "r3k2r/1b4bq/8/8/8/8/7B/R4RK1 b qk - 0 1";
let result = Position::from_fen(initial_fen);
assert!(result.is_ok());
let position = result.unwrap();
let fen = position.to_fen();
assert_eq!(fen, initial_fen);
}
#[test]
fn parse_parse_with_starting_fen() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
let expected = unindent::unindent(
"
ABCDEFGH
8|rnbqkbnr|8 side to move: white
7|pppppppp|7 castling rights: QqKk
6|........|6 en-passant: -
5|........|5 half-move clock: 0
4|........|4 full-move number: 1
3|........|3 FEN: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w QqKk - 0 1
2|PPPPPPPP|2 KEY: 0674AFC18BB45C18
1|RNBQKBNR|1
ABCDEFGH
",
);
assert_eq!(position.to_string(), expected);
}
#[test]
fn parse_with_default_state() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().castling_rights, ALL_RIGHTS);
assert_eq!(position.state().half_move_clock, 0);
assert_eq!(position.state().full_move_number, 1);
}
#[test]
fn parse_parse_with_random_fen() {
let fen = "8/8/7p/3KNN1k/2p4p/8/3P2p1/8";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
let expected = unindent::unindent(
"
ABCDEFGH
8|........|8 side to move: white
7|........|7 castling rights: QqKk
6|.......p|6 en-passant: -
5|...KNN.k|5 half-move clock: 0
4|..p....p|4 full-move number: 1
3|........|3 FEN: 8/8/7p/3KNN1k/2p4p/8/3P2p1/8 w QqKk - 0 1
2|...P..p.|2 KEY: 85FD6119056946E4
1|........|1
ABCDEFGH
",
);
assert_eq!(position.to_string(), expected);
}
#[test]
fn parse_with_stm_1() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().stm, WHITE);
}
#[test]
fn parse_with_stm_2() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().stm, BLACK);
}
#[test]
fn parse_with_ep_square_1() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - -";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert!(position.state().ep_square.is_none());
}
#[test]
fn parse_with_ep_square_2() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - c3";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().ep_square.unwrap(), C3);
}
#[test]
fn parse_with_half_move_clock_1() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - -";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().half_move_clock, 0);
}
#[test]
fn parse_with_half_move_clock_2() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 23";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().half_move_clock, 23);
}
#[test]
fn parse_with_full_move_number_1() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().full_move_number, 1);
}
#[test]
fn parse_with_full_move_number_2() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 45";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().full_move_number, 45);
}
#[test]
fn parse_with_castling_rights_1() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w -";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().castling_rights, NO_RIGHTS);
}
#[test]
fn parse_with_castling_rights_2() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b Qk";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
let mut expected_rights = WHITE_QS;
expected_rights.add(KING_SIDE, BLACK);
assert_eq!(position.state().castling_rights, expected_rights);
}
#[test]
fn parse_with_castling_rights_3() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w QkKq";
let result = Position::from_fen(fen);
assert!(result.is_ok());
let position = result.unwrap();
assert_eq!(position.state().castling_rights, ALL_RIGHTS);
}
#[test]
fn parse_with_castling_rights_4() {
let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b f";
let result = Position::from_fen(fen);
assert!(result.is_err());
assert_eq!(result.err().unwrap(), "Invalid castle: f");
}
}
| mit |
myusuf3/racks | racks/main.py | 1134 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Usage: racks <numbers>...
Examples:
racks 1 25 221 57 32 68 8
Options:
-h --help Show this screen.
-v --version Show version.
"""
from docopt import docopt
from racks import __version__
from termcolor import cprint
steps = u'▁▂▃▄▅▆▇'
def normalize_numbers(numbers):
"""
Given a list of numbers normalize the given numbers to 0 - 6
to allow each number to account for the number of different unicode
blocks we have to represent them.
"""
step_range = max(numbers) - min(numbers)
# 6 because lists start with 0 index
step = ((step_range) / float(6)) or 1
rack = u' '.join(steps[int(round((n - min(numbers)) / step))] for n in numbers)
cprint(rack, 'green')
def start():
version = ".".join(str(x) for x in __version__)
arguments = docopt(__doc__, version=version)
numbers = arguments.get('<numbers>', None)
if numbers:
try:
numbers = map(int, numbers)
normalize_numbers(numbers)
except ValueError:
cprint("Racks only accepts integers", 'red')
| mit |
asiboro/asiboro.github.io | vsdoc/toc--/topic_00000000000009F1.html.js | 351 | var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['1429',"Tlece.Recruitment.Models Namespace","topic_00000000000007B3.html"],['1452',"CardDto Class","topic_00000000000009EF.html"],['1453',"Properties","topic_00000000000009EF_props--.html"],['1454',"Brand Property","topic_00000000000009F1.html"]]; | mit |
slolam/aspnet-identity-documentdb | src/Simple.AspNetCore.Identity.DocumentDb/Models/IdentityUserClaim.cs | 1191 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Simple.AspNetCore.Identity.DocumentDb.Models
{
/// <summary>
/// Represents the claims of the identity
/// </summary>
/// <summary>
/// Represents the claims of the identity
/// </summary>
public class IdentityUserClaim
{
/// <summary>
/// Gets or sets the type of the claim.
/// </summary>
/// <value>The type of the claim.</value>
public string Type { get; set; }
/// <summary>
/// Gets or sets the claim value.
/// </summary>
/// <value>The claim value.</value>
public string Value { get; set; }
/// <summary>
/// Gets or sets the value type of the claim.
/// </summary>
public string ValueType { get; set; }
/// <summary>
/// Gets or sets the issuer of the claim.
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// Gets or sets the original issuer of the claim.
/// </summary>
public string OriginalIssuer { get; set; }
}
}
| mit |
sundarcse1216/python-crud | PythonCRUD/crud/utils/databaseutils.py | 2075 | import logging.config
import configparser
import pymysql
class DatabaseUtils:
"""
This class will maintain the database connections
"""
def __init__(self):
DatabaseUtils.log = logging.getLogger("DatabaseUtils")
self.load_properties()
@classmethod
def load_properties(cls):
"""
This method load the dbconfig.ini file and load the DB properties
:return: None
"""
try:
config = configparser.ConfigParser()
config.read('../docs/dbconfig.ini')
cls.host_name = config['DATABASE']['host']
cls.port_no = config['DATABASE']['port']
cls.user_name = config['DATABASE']['user']
cls.db_name = config['DATABASE']['db']
cls.password = config['DATABASE']['password']
DatabaseUtils.log.info("Properties loaded successfully...")
except KeyError as ex:
DatabaseUtils.log.exception("Exception occurred : %s", ex)
@classmethod
def get_data_source_connection(cls):
"""
This is create the database connection
:return: conn - database connection
"""
conn = None
try:
conn = pymysql.connect(host=cls.host_name, database=cls.db_name, user=cls.user_name,
password=cls.password)
except Exception as ex:
DatabaseUtils.log.exception("Exception occurred while connect to database : %s", ex)
return conn
@classmethod
def close_database_connection(cls, conn):
"""
This is close the database connection
:param conn: connection which we have to close
:return: None
"""
try:
if conn:
conn.close()
elif not conn:
DatabaseUtils.log.info("Connection already closed")
else:
DatabaseUtils.log.error(conn)
except Exception as ex:
DatabaseUtils.log.exception("Exception occurred while close datasource connection : %s", ex)
| mit |
Nohmapp/npm-introspect | server/server.js | 1596 | 'use strict';
const requestData = require('../server/requestData');
const less = require('./less')
const express = require('express');
const app = express();
const path = require('path');
const opn = require('opn');
module.exports.run = (args) => {
console.log('Recieving NPM scores...')
var pkgs = args._;
if (args.l || args.less == true ){
requestData.request(pkgs, args.d)
.then(function (data) {
less.buildTable(data)
}).catch(function(e){
console.log(e)
})
return;
}
else{
getNPM(pkgs, args.d)
}
app.use(express.static(path.join(__dirname, '../assets')));
app.use(express.static(path.join(__dirname, '../client')));
app.get('*', function(req, res) {
res.send('A wrong url has been requested, please check spelling')
})
listen(args.p)
}
const getNPM = function(defaultPkgs, noDevDep){
app.get('/data.json', function(req, res){
var pkgs = defaultPkgs;
if( req.query.search && req.query.search.length > 0 ){
pkgs = req.query.search.split(",")
}
requestData.request(pkgs, noDevDep)
.then(function (data) {
res.json(data)
res.setHeader('Content-Type', 'application/json');
res.send(data);
})
.catch(function (e) {
res.status(500, {
error: e
});
})
})
}
const listen = function(port){
return app.listen(port, function() {
console.log('Launching visualization on port ' + port)
opn('http://localhost:' + port + '/');
})
}
| mit |
OdimTech/Sisacon | Sisacon/Sisacon.Infra/Mapping/ProductImagesMap.cs | 361 | using Sisacon.Domain.ValueObjects;
namespace Sisacon.Infra.Mapping
{
public class ProductImagesMap : BaseMap<ProductImages>
{
public ProductImagesMap()
{
Property(x => x.Image)
.HasColumnType("varbinary")
.HasMaxLength(null)
.IsRequired();
}
}
}
| mit |
trentm/node-bunyan | test/raw-stream.test.js | 2693 | /*
* Copyright 2020 Trent Mick
*
* Test `type: 'raw'` Logger streams.
*/
var format = require('util').format;
var test = require('tap').test;
var Logger = require('../lib/bunyan');
function CapturingStream(recs) {
this.recs = recs;
}
CapturingStream.prototype.write = function (rec) {
this.recs.push(rec);
}
test('raw stream', function (t) {
var recs = [];
var log = new Logger({
name: 'raw-stream-test',
streams: [
{
stream: new CapturingStream(recs),
type: 'raw'
}
]
});
log.info('first');
log.info({two: 'deux'}, 'second');
t.equal(recs.length, 2);
t.equal(typeof (recs[0]), 'object', 'first rec is an object');
t.equal(recs[1].two, 'deux', '"two" field made it through');
t.end();
});
test('raw streams and regular streams can mix', function (t) {
var rawRecs = [];
var nonRawRecs = [];
var log = new Logger({
name: 'raw-stream-test',
streams: [
{
stream: new CapturingStream(rawRecs),
type: 'raw'
},
{
stream: new CapturingStream(nonRawRecs)
}
]
});
log.info('first');
log.info({two: 'deux'}, 'second');
t.equal(rawRecs.length, 2);
t.equal(typeof (rawRecs[0]), 'object', 'first rawRec is an object');
t.equal(rawRecs[1].two, 'deux', '"two" field made it through');
t.equal(nonRawRecs.length, 2);
t.equal(typeof (nonRawRecs[0]), 'string', 'first nonRawRec is a string');
t.end();
});
test('child adding a non-raw stream works', function (t) {
var parentRawRecs = [];
var rawRecs = [];
var nonRawRecs = [];
var logParent = new Logger({
name: 'raw-stream-test',
streams: [
{
stream: new CapturingStream(parentRawRecs),
type: 'raw'
}
]
});
var logChild = logParent.child({
child: true,
streams: [
{
stream: new CapturingStream(rawRecs),
type: 'raw'
},
{
stream: new CapturingStream(nonRawRecs)
}
]
});
logParent.info('first');
logChild.info({two: 'deux'}, 'second');
t.equal(rawRecs.length, 1,
format('rawRecs length should be 1 (is %d)', rawRecs.length));
t.equal(typeof (rawRecs[0]), 'object', 'rawRec entry is an object');
t.equal(rawRecs[0].two, 'deux', '"two" field made it through');
t.equal(nonRawRecs.length, 1);
t.equal(typeof (nonRawRecs[0]), 'string', 'first nonRawRec is a string');
t.end();
});
| mit |
Neo11/ChitChat | ChitChat/emoji.js | 3134 | var emojis = [
{ code: ["o:)","o:-)"], alt: "😇", cName: "emojiordered1463" },
{ code: [">:-o"], alt: "😠", cName: "emojiordered1488" },
{ code: [">:-)"], alt: "😈", cName: "emojiordered1464" },
{ code: [":)",":-)"], alt: "😊", cName: "emojiordered1466" },
{ code: [";)",";-)"], alt: "😉", cName: "emojiordered1465" },
{ code: [":(",":-("], alt: "😟", cName: "emojiordered1487" },
{ code: ["B)", "B-)"], alt: "😎", cName: "emojiordered1470" },
{ code: [":D",":-D"], alt: "😃", cName: "emojiordered1459" },
{ code: ["D:","D-:"], alt: "😩", cName: "emojiordered1497" },
{ code: [":d",":-d"], alt: "😋", cName: "emojiordered1467" },
{ code: [";p", ";-p",";P", ";-P"], alt: "😜", cName: "emojiordered1484" },
{ code: ["%)", "%-)"], alt: "😂", cName: "emojiordered1458" },
{ code: [":p",":-p",":P",":-P"], alt: "😛", cName: "emojiordered1483" },
{ code: [":o",":-o"], alt: "😮", cName: "emojiordered1502" },
{ code: [":s",":-s"], alt: "😖", cName: "emojiordered1478" },
{ code: [":x",":-x"], alt: "😶", cName: "emojiordered1510" },
{ code: [":|",":-|"], alt: "😐", cName: "emojiordered1472" },
{ code: [":/",":-/"], alt: "😕", cName: "emojiordered1477" },
{ code: [":[",":-["], alt: "😳", cName: "emojiordered1507" },
{ code: [":>",":->"], alt: "😏", cName: "emojiordered1471" },
{ code: [":@",":-@"], alt: "😷", cName: "emojiordered1511" },
{ code: [":*",":-*"], alt: "😘", cName: "emojiordered1480" },
{ code: [":!",":-!"], alt: "😬", cName: "emojiordered1500" },
{ code: [":3",":-3"], alt: "😺", cName: "emojiordered1514" },
{ code: ["(y)", "(Y)"], alt: "👍", cName: "emojiordered0911" },
{ code: ["(n)", "(N)"], alt: "👎", cName: "emojiordered0917" },
{ code: ["<3"], alt: "️❤️", cName: "emojiordered0192" }
];
function emoji(element) {
for(var i=0; i < emojis.length; i++) {
for(var u=0; u < emojis[i].code.length; u++) {
replaceSmiley(emojis[i].code[u],emojis[i].alt, emojis[i].cName);
}
}
}
function replaceSmiley(emoji, alt, className) {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
if(range.startOffset - emoji.length >= 0) {
var clone = range.cloneRange();
clone.setStart(range.startContainer, range.startOffset - emoji.length);
clone.setEnd(range.startContainer, range.startOffset);
var contents = clone.toString();
if(contents == emoji) {
clone.deleteContents();
var img = document.createElement("img");
img.alt = alt;
img.draggable = false;
img.className = "emoji " + className;
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
range.insertNode(img);
range.setStartAfter(img);
document.execCommand("insertHTML", false, '<span></span>');
range.collapse(false);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
| mit |
flarum/core | src/Locale/LocaleManager.php | 2836 | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Locale;
use Illuminate\Support\Arr;
use Symfony\Component\Translation\MessageCatalogueInterface;
class LocaleManager
{
/**
* @var Translator
*/
protected $translator;
protected $locales = [];
protected $js = [];
protected $css = [];
/**
* @var string
*/
protected $cacheDir;
public function __construct(Translator $translator, string $cacheDir = null)
{
$this->translator = $translator;
$this->cacheDir = $cacheDir;
}
public function getLocale(): string
{
return $this->translator->getLocale();
}
public function setLocale(string $locale)
{
$this->translator->setLocale($locale);
}
public function addLocale(string $locale, string $name)
{
$this->locales[$locale] = $name;
}
public function getLocales(): array
{
return $this->locales;
}
public function hasLocale(string $locale): bool
{
return isset($this->locales[$locale]);
}
public function addTranslations(string $locale, $file, string $module = null)
{
$prefix = $module ? $module.'::' : '';
// `messages` is the default domain, and we want to support MessageFormat
// for all translations.
$domain = 'messages'.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX;
$this->translator->addResource('prefixed_yaml', compact('file', 'prefix'), $locale, $domain);
}
public function addJsFile(string $locale, string $js)
{
$this->js[$locale][] = $js;
}
public function getJsFiles(string $locale): array
{
$files = Arr::get($this->js, $locale, []);
$parts = explode('-', $locale);
if (count($parts) > 1) {
$files = array_merge(Arr::get($this->js, $parts[0], []), $files);
}
return $files;
}
public function addCssFile(string $locale, string $css)
{
$this->css[$locale][] = $css;
}
public function getCssFiles(string $locale): array
{
$files = Arr::get($this->css, $locale, []);
$parts = explode('-', $locale);
if (count($parts) > 1) {
$files = array_merge(Arr::get($this->css, $parts[0], []), $files);
}
return $files;
}
public function getTranslator(): Translator
{
return $this->translator;
}
public function setTranslator(Translator $translator)
{
$this->translator = $translator;
}
public function clearCache()
{
if ($this->cacheDir) {
array_map('unlink', glob($this->cacheDir.'/*'));
}
}
}
| mit |
awaywego/awaywego | client/src/modules/home/home.js | 908 | import angular from 'angular';
// components used by this module
import GroupCardComponent from './group-card/group-card';
import ImageSearchComponent from '../image-search/image-search';
import GroupService from '../../services/group/group.service';
// imports for this component
import template from './home.html';
import './home.css';
class HomeController {
constructor(GroupService) {
this.GroupService = GroupService;
}
$onInit() {
this.GroupService.getAllGroups();
}
}
HomeController.$inject = ['GroupService'];
const HomeComponent = {
restrict: 'E',
bindings: {},
template: template,
controller: HomeController
};
const HomeModule = angular.module('app.home', [])
.component('home', HomeComponent)
.component('groupCard', GroupCardComponent)
.component('imageSearch', ImageSearchComponent)
.service('GroupService', GroupService);
export default HomeModule.name;
| mit |
dukescript/leaflet4j | api/src/main/java/net/java/html/leaflet/TileLayer.java | 4579 | /**
* The MIT License (MIT)
*
* Copyright (C) 2015 Andreas Grimmer <a.grimmer@gmx.at>
* Christoph Sperl <ch.sperl@gmx.at>
* Stefan Wurzinger <swurzinger@gmx.at>
*
* 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 net.java.html.leaflet;
import net.java.html.js.JavaScriptBody;
import net.java.html.leaflet.event.Event;
import net.java.html.leaflet.event.EventListener;
import net.java.html.leaflet.event.TileEvent;
import net.java.html.leaflet.event.TileListener;
/** Layer of tiles.
*
* @author Christoph Sperl
* @author Andreas Grimmer
*
*/
public class TileLayer extends ILayer {
static {
Options.initJS();
registerLayerType("L.TileLayer", new Function<Object, ILayer>() {
@Override
public ILayer apply(Object obj) {
return new TileLayer(obj);
}
});
}
TileLayer(Object jsObj) {
super(jsObj);
}
public TileLayer(String urlTemplate) {
this(urlTemplate, new TileLayerOptions());
}
public TileLayer(String urlTemplate, TileLayerOptions options) {
super(create(urlTemplate, options.getJSObj()));
}
@JavaScriptBody(args = {"urlTemplate", "options"}, body
= "return L.tileLayer(urlTemplate, options);")
private static native Object create(String urlTemplate, Object options);
// ------- Event methods --------------------------------------
/**
* Adds a tile listener to a particular tile event type of the object.
*
* @param type The tile event type. The types TILELOADSTART, TILELOAD and
* TILEUNLOAD are supported.
* @param listener The registered listener.
* @return The tile layer object.
*/
public TileLayer addTileListener(TileEvent.Type type, TileListener listener) {
EventMethodsHelper.addTileListener(getJSObj(), type, listener);
return this;
}
/**
* Adds a event listener to a particular event type of the object.
*
* @param type The event type. The types LOADING and LOAD are supported.
* @param listener The registered listener.
* @return The tile layer object.
*/
public TileLayer addEventListener(Event.Type type, EventListener listener) {
EventMethodsHelper.addEventListener(getJSObj(), type, listener);
return this;
}
/**
* Removes a tile listener to a particular tile event type of the object.
*
* @param type The tile event type. The types TILELOADSTART, TILELOAD and
* TILEUNLOAD are supported.
* @param listener The registered listener.
* @return The tile layer object.
*/
public TileLayer removeTileListener(TileEvent.Type type, TileListener listener) {
EventMethodsHelper.removeEventListener(getJSObj(), type.toString(), listener);
return this;
}
/**
* Removes a event listener to a particular event type of the object.
*
* @param type The event type. The types LOADING and LOAD are supported.
* @param listener The registered listener.
* @return The tile layer object.
*/
public TileLayer removeEventListener(Event.Type type, EventListener listener) {
EventMethodsHelper.removeEventListener(getJSObj(), type.toString(), listener);
return this;
}
/**
* Removes all listeners to all events on the object.
*
* @return The tile layer object.
*/
public TileLayer clearAllEventListeners() {
EventMethodsHelper.clearAllEventListeners(getJSObj());
return this;
}
}
| mit |
qwerty2501/NiconicoUI | NiconicoUI/Onds.Niconico.UI.WinRT/Extentions/NiconicoTextColorExtentions.cs | 650 | #if NETFX_CORE
using Windows.UI;
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Onds.Niconico.Data.Text;
namespace Onds.Niconico.UI.Extentions
{
public static class NiconicoTextColorExtentions
{
public static Color ToPlatFormColor(this NiconicoTextColor color)
{
return Color.FromArgb(0xFF, color.R, color.G, color.B);
}
public static NiconicoTextColor ToNiconicoTextColor(this Color color)
{
return new NiconicoTextColor { R = color.R, G = color.G, B = color.B };
}
}
}
| mit |
mauriciotogneri/apply | src/main/java/com/mauriciotogneri/apply/compiler/lexical/TokenList.java | 3091 | package com.mauriciotogneri.apply.compiler.lexical;
import com.mauriciotogneri.apply.compiler.lexical.tokens.delimiters.SpaceToken;
import com.mauriciotogneri.apply.compiler.types.TokenType;
import com.mauriciotogneri.apply.exceptions.lexical.InvalidCharacterException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class TokenList
{
private final CharacterList characterList;
public TokenList(CharacterList characterList)
{
this.characterList = characterList;
}
public List<Token> tokens() throws Exception
{
List<Token> tokens = new ArrayList<>();
CharacterBuffer characterBuffer = new CharacterBuffer();
for (Character character : characterList.characters())
{
characterBuffer.add(character);
characterBuffer.check(tokens);
}
if (!characterBuffer.isEmpty())
{
characterBuffer.checkRemaining(tokens);
}
return tokens;
}
private static class CharacterBuffer extends ArrayList<Character>
{
private void check(List<Token> tokens)
{
if (!matchesPattern() && (size() > 1))
{
Optional<Token> token = token(1);
if (token.isPresent())
{
addToken(tokens, token.get());
Character lastCharacter = get(size() - 1);
clear();
add(lastCharacter);
}
else
{
throw new InvalidCharacterException(get(size() - 1));
}
}
}
private boolean matchesPattern()
{
return token(0).isPresent();
}
private void addToken(List<Token> tokens, Token token)
{
if (!(token instanceof SpaceToken))
{
tokens.add(token);
}
}
private void checkRemaining(List<Token> tokens)
{
if (matchesPattern())
{
Optional<Token> token = token(0);
if (token.isPresent())
{
addToken(tokens, token.get());
}
else
{
throw new InvalidCharacterException(get(size() - 1));
}
}
else
{
throw new InvalidCharacterException(get(0));
}
}
private Optional<Token> token(int remove)
{
Lexeme lexeme = lexeme(remove);
return TokenType.ofLexeme(lexeme);
}
private Lexeme lexeme(int remove)
{
StringBuilder builder = new StringBuilder();
int limit = size() - remove;
for (int i = 0; i < limit; i++)
{
Character character = get(i);
builder.append(character.value());
}
return new Lexeme(builder.toString(), get(0));
}
}
} | mit |
BonesCoin/Bones | src/qt/locale/bitcoin_en.ts | 115019 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Bones</source>
<translation>About Bones</translation>
</message>
<message>
<location line="+39"/>
<source><b>Bones</b> version</source>
<translation><b>Bones</b> version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
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.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Bones developers</source>
<translation>The Bones developers</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Address Book</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Double-click to edit address or label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Create a new address</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copy the currently selected address to the system clipboard</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&New Address</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Bones 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>These are your Bones 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.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copy Address</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Show &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Bones address</source>
<translation>Sign a message to prove you own a Bones address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Delete the currently selected address from the list</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Bones address</source>
<translation>Verify a message to ensure it was signed with a specified Bones address</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Delete</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Bones addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>These are your Bones addresses for sending payments. Always check the amount and the receiving address before sending coins.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copy &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Edit</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Export Address Book Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(no label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrase Dialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enter passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>New passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repeat new passphrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>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>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>This operation needs your wallet passphrase to unlock the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Unlock wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>This operation needs your wallet passphrase to decrypt the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Change passphrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enter the old and new passphrase to the wallet.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirm wallet encryption</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BonesS</b>!</source>
<translation>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BonesS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Are you sure you wish to encrypt your wallet?</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>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.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warning: The Caps Lock key is on!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Wallet encrypted</translation>
</message>
<message>
<location line="-56"/>
<source>Bones will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Boness from being stolen by malware infecting your computer.</source>
<translation>Bones will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Boness from being stolen by malware infecting your computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Wallet encryption failed</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>The supplied passphrases do not match.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Wallet unlock failed</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>The passphrase entered for the wallet decryption was incorrect.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Wallet decryption failed</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Wallet passphrase was successfully changed.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Sign &message...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizing with network...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Overview</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Show general overview of wallet</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Browse transaction history</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels for sending</source>
<translation>Edit the list of stored addresses and labels for sending</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Show the list of addresses for receiving payments</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>E&xit</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quit application</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Bones</source>
<translation>Show information about Bones</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>About &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Show information about Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Encrypt Wallet...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup Wallet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Change Passphrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importing blocks from disk...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexing blocks on disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Bones address</source>
<translation>Send coins to a Bones address</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Bones</source>
<translation>Modify configuration options for Bones</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Backup wallet to another location</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Change the passphrase used for wallet encryption</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug window</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging and diagnostic console</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verify message...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Bones</source>
<translation>Bones</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Receive</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Addresses</translation>
</message>
<message>
<location line="+22"/>
<source>&About Bones</source>
<translation>&About Bones</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Show / Hide</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Show or hide the main Window</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encrypt the private keys that belong to your wallet</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Bones addresses to prove you own them</source>
<translation>Sign messages with your Bones addresses to prove you own them</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Bones addresses</source>
<translation>Verify messages to ensure they were signed with specified Bones addresses</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Settings</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tabs toolbar</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Bones client</source>
<translation>Bones client</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Bones network</source>
<translation>
<numerusform>%n active connection to Bones network</numerusform>
<numerusform>%n active connections to Bones network</numerusform>
</translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>No block source available...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Processed %1 of %2 (estimated) blocks of transaction history.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processed %1 blocks of transaction history.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation>
<numerusform>%n hour</numerusform>
<numerusform>%n hours</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation>
<numerusform>%n day</numerusform>
<numerusform>%n days</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation>
<numerusform>%n week</numerusform>
<numerusform>%n weeks</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 behind</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Last received block was generated %1 ago.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transactions after this will not yet be visible.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>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?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Up to date</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Catching up...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirm transaction fee</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sent transaction</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Incoming transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date: %1
Amount: %2
Type: %3
Address: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI handling</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Bones address or malformed URI parameters.</source>
<translation>URI can not be parsed! This can be caused by an invalid Bones address or malformed URI parameters.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>unlocked</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>locked</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Bones can no longer continue safely and will quit.</source>
<translation>A fatal error occurred. Bones can no longer continue safely and will quit.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Network Alert</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Edit Address</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>The label associated with this address book entry</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Address</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>The address associated with this address book entry. This can only be modified for sending addresses.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>New receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>New sending address</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Edit receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Edit sending address</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>The entered address "%1" is already in the address book.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Bones address.</source>
<translation>The entered address "%1" is not a valid Bones address.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Could not unlock wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>New key generation failed.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Bones-Qt</source>
<translation>Bones-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>command-line options</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI options</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Set language, for example "de_DE" (default: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimized</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Show splash screen on startup (default: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Main</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pay transaction &fee</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Bones after logging in to the system.</source>
<translation>Automatically start Bones after logging in to the system.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Bones on system login</source>
<translation>&Start Bones on system login</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Reset all client options to default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Reset Options</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Network</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Bones client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatically open the Bones client port on the router. This only works when your router supports UPnP and it is enabled.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Map port using &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Bones network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connect to the Bones network through a SOCKS proxy (e.g. when connecting through Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connect through SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP address of the proxy (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port of the proxy (e.g. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS version of the proxy (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Show only a tray icon after minimizing the window.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimize to the tray instead of the taskbar</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 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.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimize on close</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Display</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>User Interface &language:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Bones.</source>
<translation>The user interface language can be set here. This setting will take effect after restarting Bones.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit to show amounts in:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Bones addresses in the transaction list or not.</source>
<translation>Whether to show Bones addresses in the transaction list or not.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Display addresses in transaction list</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancel</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apply</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>default</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirm options reset</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Some settings may require a client restart to take effect.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Do you want to proceed?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Bones.</source>
<translation>This setting will take effect after restarting Bones.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>The supplied proxy address is invalid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bones network after a connection is established, but this process has not completed yet.</source>
<translation>The displayed information may be out of date. Your wallet automatically synchronizes with the Bones network after a connection is established, but this process has not completed yet.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unconfirmed:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immature:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Mined balance that has not yet matured</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recent transactions</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Your current balance</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>out of sync</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start Bones: click-to-pay handler</source>
<translation>Cannot start Bones: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Request Payment</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Amount:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Save As...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error encoding URI into QR Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>The entered amount is invalid, please check.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulting URI too long, try to reduce the text for label / message.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Save QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Images (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Client name</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Client version</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Using OpenSSL version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startup time</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Network</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Number of connections</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>On testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Current number of blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimated total blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Last block time</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Command-line options</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Bones-Qt help message to get a list with possible Bones command-line options.</source>
<translation>Show the Bones-Qt help message to get a list with possible Bones command-line options.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Build date</translation>
</message>
<message>
<location line="-104"/>
<source>Bones - Debug window</source>
<translation>Bones - Debug window</translation>
</message>
<message>
<location line="+25"/>
<source>Bones Core</source>
<translation>Bones Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug log file</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Bones debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open the Bones debug log file from the current data directory. This can take a few seconds for large log files.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Clear console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Bones RPC console.</source>
<translation>Welcome to the Bones RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Type <b>help</b> for an overview of available commands.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send to multiple recipients at once</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Add &Recipient</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remove all transaction fields</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirm the send action</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirm send coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Are you sure you want to send %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> and </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>The recipient address is not valid, please recheck.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>The amount to pay must be larger than 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>The amount exceeds your balance.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>The total exceeds your balance when the %1 transaction fee is included.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplicate address found, can only send to each address once per send operation.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: Transaction creation failed!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>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.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&mount:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Pay &To:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Enter a label for this address to add it to your address book</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Choose address from address book</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</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>Remove this recipient</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Bones address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>Enter a Bones address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Sign / Verify a Message</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Sign Message</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>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.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Choose an address from the address book</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</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>Enter the message you want to sign here</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copy the current signature to the system clipboard</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Bones address</source>
<translation>Sign the message to prove you own this Bones address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Reset all sign message fields</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>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.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Bones address</source>
<translation>Verify the message to ensure it was signed with the specified Bones address</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verify &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Reset all verify message fields</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Bones address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>Enter a Bones address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Sign Message" to generate signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Bones signature</source>
<translation>Enter Bones signature</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>The entered address is invalid.</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>Please check the address and try again.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>The entered address does not refer to a key.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet unlock was cancelled.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Private key for the entered address is not available.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Message signing failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Message signed.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>The signature could not be decoded.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Please check the signature and try again.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>The signature did not match the message digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Message verification failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message verified.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Bones developers</source>
<translation>The Bones developers</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unconfirmed</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, broadcast through %n node</numerusform>
<numerusform>, broadcast through %n nodes</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generated</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>From</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>To</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>own address</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>matures in %n more block</numerusform>
<numerusform>matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>not accepted</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net amount</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comment</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaction ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, has not been successfully broadcast yet</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>unknown</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaction details</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>This pane shows a detailed description of the transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Unconfirmed (%1 of %2 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmed (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation>
<numerusform>Mined balance will be available when it matures in %n more block</numerusform>
<numerusform>Mined balance will be available when it matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>This block was not received by any other nodes and will probably not be accepted!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generated but not accepted</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Received from</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Payment to yourself</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaction status. Hover over this field to show number of confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date and time that the transaction was received.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Destination address of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Amount removed from or added to balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>All</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Today</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>This week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>This month</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Last month</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>This year</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Range...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>To yourself</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Enter address or label to search</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min amount</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copy address</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copy label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copy amount</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copy transaction ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edit label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Show transaction details</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Export Transaction Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmed</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Range:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>to</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Backup Wallet</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Wallet Data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup Failed</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>There was an error trying to save the wallet data to the new location.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Backup Successful</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>The wallet data was successfully saved to the new location.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Bones version</source>
<translation>Bones version</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or Bonesd</source>
<translation>Send command to -server or Bonesd</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List commands</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Get help for a command</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Options:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: Bones.conf)</source>
<translation>Specify configuration file (default: Bones.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: Bonesd.pid)</source>
<translation>Specify pid file (default: Bonesd.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specify data directory</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Set database cache size in megabytes (default: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 55355 or testnet: 44556)</source>
<translation>Listen for connections on <port> (default: 55355 or testnet: 44556)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maintain at most <n> connections to peers (default: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Connect to a node to retrieve peer addresses, and disconnect</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Specify your own public address</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Threshold for disconnecting misbehaving peers (default: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 55255 or testnet: 44555)</source>
<translation>Listen for JSON-RPC connections on <port> (default: 55255 or testnet: 44555)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accept command line and JSON-RPC commands</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Run in the background as a daemon and accept commands</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Use the test network</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=Bonesrpc
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 "Bones Alert" admin@foo.com
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=Bonesrpc
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 "Bones Alert" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind to given address and always listen on it. Use [host]:port notation for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Bones is probably already running.</source>
<translation>Cannot obtain a lock on data directory %s. Bones is probably already running.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>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.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Execute command when a relevant alert is received (%s in cmd is replaced by message)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bones will not work properly.</source>
<translation>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bones will not work properly.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>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.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Attempt to recover private keys from a corrupt wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Block creation options:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Connect only to the specified node(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupted block database detected</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Discover own IP address (default: 1 when listening and no -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Do you want to rebuild the block database now?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error initializing block database</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error initializing wallet database environment %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error loading block database</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error opening block database</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: Disk space is low!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: Wallet locked, unable to create transaction!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: system error: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Failed to listen on any port. Use -listen=0 if you want this.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Failed to read block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Failed to read block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Failed to sync block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Failed to write block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Failed to write block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Failed to write block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Failed to write file info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Failed to write to coin database</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Failed to write transaction index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Failed to write undo data</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Find peers using DNS lookup (default: 1 unless -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generate coins (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>How many blocks to check at startup (default: 288, 0 = all)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>How thorough the block verification is (0-4, default: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Not enough file descriptors available.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Rebuild block chain index from current blk000??.dat files</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Set the number of threads to service RPC calls (default: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifying blocks...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifying wallet...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Imports blocks from external blk000??.dat file</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Invalid -tor address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Invalid amount for -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Maintain a full transaction index (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Only accept block chain matching built-in checkpoints (default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output extra debugging information. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output extra network debugging information</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation>Prepend debug output with timestamp (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Bones Wiki for SSL setup instructions)</source>
<translation>SSL options: (see the Bones Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Select the version of socks proxy to use (4-5, default: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send trace/debug info to console instead of debug.log file</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send trace/debug info to debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Set maximum block size in bytes (default: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Set minimum block size in bytes (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signing transaction failed</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specify connection timeout in milliseconds (default: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>System error: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transaction amount too small</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transaction amounts must be positive</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaction too large</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Use UPnP to map the listening port (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Use UPnP to map the listening port (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Use proxy to reach tor hidden services (default: same as -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Username for JSON-RPC connections</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warning: This version is obsolete, upgrade required!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>You need to rebuild the databases using -reindex to change -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, salvage failed</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Password for JSON-RPC connections</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Allow JSON-RPC connections from specified IP address</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send commands to node running on <ip> (default: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Upgrade wallet to latest format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Set key pool size to <n> (default: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescan the block chain for missing wallet transactions</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Use OpenSSL (https) for JSON-RPC connections</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Server certificate file (default: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private key (default: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>This help message</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Unable to bind to %s on this computer (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Connect through socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Allow DNS lookups for -addnode, -seednode and -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Loading addresses...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error loading wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Bones</source>
<translation>Error loading wallet.dat: Wallet requires newer version of Bones</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Bones to complete</source>
<translation>Wallet needed to be rewritten: restart Bones to complete</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error loading wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Invalid -proxy address: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unknown network specified in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unknown -socks proxy version requested: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Cannot resolve -bind address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Cannot resolve -externalip address: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Invalid amount</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Insufficient funds</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Loading block index...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Add a node to connect to and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Bones is probably already running.</source>
<translation>Unable to bind to %s on this computer. Bones is probably already running.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Fee per KB to add to transactions you send</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Loading wallet...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Cannot downgrade wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Cannot write default address</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescanning...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Done loading</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>To use the %s option</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</translation>
</message>
</context>
</TS>
| mit |
BrunoCamargos/billdone | src/commons/pagination.js | 401 | import config from './config';
const paginate = (page, pageLimit) => {
let skip = parseInt(page, 10);
if (isNaN(skip) || skip < 1) {
skip = 1;
}
skip -= 1;
let limit = parseInt(pageLimit, 10);
if (isNaN(limit) || limit < 1 || limit > config.app.defaultPageLimit) {
limit = config.app.defaultPageLimit;
}
return { skip: (skip *= limit), limit };
};
export default paginate;
| mit |
telminov/park-keeper | backend/project/settings.sample.py | 591 | # coding: utf-8
from project.settings_default import *
# must be agreed with park-workers
SECRET_KEY = '321'
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join('/data/', 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
WEB_SOCKET_SERVER_PORT = 8081
MONGODB = {
'NAME': 'parkkeeper',
'HOST': 'mongo3',
'PORT': 27017,
'USER': None,
'PASSWORD': None,
}
import mongoengine
#mongoengine.connect(MONGODB['NAME'], host='mongodb://%s:%s/%s' % (MONGODB['HOST'], MONGODB.get('PORT', 27017), MONGODB['NAME']))
| mit |
jangsohee/CloudUSB-Client | CloudUSB/CU/CU/Express/DVD-5/DiskImages/DISK1/program files/CloudUSB/CloudUSB/JoinView.xaml.cs | 6165 | using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Newtonsoft.Json;
namespace CloudUSB
{
/// <summary>
/// JoinView.xaml에 대한 상호 작용 논리
/// </summary>
public partial class JoinView : MetroWindow
{
MainWindow root;
public JoinView(MainWindow _root)
{
root = _root;
InitializeComponent();
}
private void joinView_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
root.Opacity = 1;
}
public bool idValidationChk(string _id)
{
bool res = true;
string id = _id;
int idLength = id.Length;
if (idLength < 5 || idLength > 20)
res = false;
for (int i = 0; i < idLength; i++)
{
char word = id[i];
if (((word > '0' && word <= '9') || (word >= 'a' && word <= 'z')) == false)
res = false;
}
return res;
}
public bool pwValidationChk(String _pw)
{
string pw = _pw;
bool res = true;
int pwLength = pw.Length;
if (pwLength < 5 || pwLength > 20)
{
res = false;
}
for (int i = 0; i < pwLength; i++)
{
char word = pw[i];
if (!((word > '0' && word <= '9') || (word >= 'a' && word <= 'z')))
res = false;
}
return res;
}
public bool checkNAME(String name)
{
bool result = true;
int length = name.Length;
if (length < 1 || length > 20)
{
result = false;
}
for (int i = 0; i < length; i++)
{
char word = name[i];
if (word == '<')
{
result = false;
}
if (word == '>')
{
result = false;
}
if (word == '\"')
{
result = false;
}
if (word == '\'')
{
result = false;
}
if (word == ' ')
{
result = false;
}
if (word == '.')
{
result = false;
}
if (word == '\\')
{
result = false;
}
}
return result;
}
private void joinBtn_Click(object sender, RoutedEventArgs e)
{
string id = joinIdBox.Text;
string pw = joinPwBox.Password;
string name = joinNameBox.Text;
if (idValidationChk(id) == false)
{
MessageBox.Show("ID는 5이상 20이하의 소문자, 숫자만 가능합니다 : " + id);
joinIdBox.Clear();
}
else if (pwValidationChk(pw) == false)
{
MessageBox.Show("PASSWORD는 5이상 20이하의 소문자, 숫자만 가능합니다 : " + pw);
joinPwBox.Clear();
}
else if (checkNAME(name) == false)
{
MessageBox.Show("NAME는 1이상 20이하의 글자만 가능합니다 : " + pw);
joinNameBox.Clear();
}
else
{
String callUrl = "http://210.118.74.120:8080/cu/api/join";
String postData = String.Format("userId={0}&password={1}&name={2}", id, pw, name);
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(callUrl);
byte[] sendData = UTF8Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = sendData.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(sendData, 0, sendData.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
string returnData = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
dynamic jsonStr = JsonConvert.DeserializeObject(returnData);
string joinResult = jsonStr["result"]; // jsonStr.result
if (joinResult.Equals("True"))
{
MessageBox.Show("가입을 축하드립니다");
root.LoginBtn.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/img/logout.png", UriKind.Absolute)));
root.isLogin = true;
this.Close();
}
else
{
root.isLogin = false;
MessageBox.Show("이미 존재하는 아이디입니다");
joinIdBox.Clear();
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}
}
| mit |
webdivane/helpers | msg/msg.php | 4230 | <?php
/** The message PHP helper
* @todo Discover bootstrap - it now can use .fade .in so the cf::appendToHeadTag can be omitted */
class msg
{
/**@var array Context "map" to dedicated Bootstrap class attribute*/
private static $contextMapToBootstrapClass = array(
"plain"=>"alert-info", "success"=>"alert-success",
"error"=>"alert-danger", "warning"=>"alert-warning"
);
/**Sets the message in the session
* @param string $msg The message content
* @param string $context For the background color of message tag; One of
* ["plain"(gray/blue),"success"(green),"error"(red), "warning"(yellow)]
* $param (null)|string $customSessionKey - Adjustment to the session key.
* For the cases where separate messages are has to appear on diferent
* positins.*/
final static function set($msg="", $context="plain", $customSessionKey=null){
self::prepare(true);
$key = (isset($customSessionKey)? $customSessionKey : helper::$config["msg"]["session key"]);
$msgs = &$_SESSION[$key];
if(!is_array($msgs)){
$msgs = array();
}
if(!in_array($context, array_keys(self::$contextMapToBootstrapClass))){
die("Incorrect msg type.");
}
$msgs[] = array("value"=>$msg, "context"=>$context);
}
/**Shows storred in the session message(s)
* $param (null)|string $customSessionKey - Adjustment to the session
* variable name. For the cases where separate messages needed (to appear on diferent positins).*/
final static function get($customSessionKey=null){
self::prepare(true);
$key = (isset($customSessionKey)? $customSessionKey : helper::$config["msg"]["session key"]);
$msgs = isset($_SESSION[$key]) ? $_SESSION[$key] : array();
foreach ($msgs as $msg){
self::Html($msg);
}
unset($_SESSION[$key]);
}
/** Just shows a message
* @param string $msg - the message contenr
* @param string $context
* @param bool $dismissable*/
final static function put($msg, $context="plain", $dismissable=true){
self::prepare(true);
self::Html(array("value"=>$msg, "context"=>$context, "dismissible"=>boolval($dismissable)));
}
private static function Html($msg){
$dismissable = (bool)(!array_key_exists("dismissible", $msg) || $msg["dismissible"]===true);
if(helper::$config["use bootstrap"]===true){
form::openP(array("class"=>"alert alert-dismissible ".self::$contextMapToBootstrapClass[$msg["context"]]));
if($dismissable){
form::openButton(array("type"=>"button", "class"=>"close", "data-dismiss"=>"alert", "aria-label"=>"Close"));
form::span("×",array("aria-hidden"=>"true"));
form::closeButton();
}
form::html($msg["value"]);
form::link("javascript:void(0);"," ",array("onclick"=>"var _this = this; setTimeout(function(){_this.parentNode.style.display = 'none';},400); this.parentNode.setAttribute('class',(this.parentNode.getAttribute('class')+' msg-fadeout'));"));
form::closeP();
} else {
form::openP(array("class"=>"app-msg ".$msg["context"]));
form::html($msg["value"]);
if($dismissable){
form::link("javascript:void(0);","close",array("class"=>"material-icons","onclick"=>"var _this = this; setTimeout(function(){_this.parentNode.style.display = 'none';},400); this.parentNode.setAttribute('class',(this.parentNode.getAttribute('class')+' msg-fadeout'));"));
}
form::closeP();
}
}
static function prepare($setOrCheck = false){
if( helper::prepare($setOrCheck, (__METHOD__)) !== true ){
return; //Stops the further execution in case the helper call doesn't return true.
}
//Starts the session if its not started yet.
if (@!session_status() || @session_status() == PHP_SESSION_NONE) {
@session_start();
}
cf::appendToHeadTag(ADD."helpers/msg/add/msg.css", "css");
}
} | mit |
cknips/b3form | lib/b3form/input/select.rb | 1168 | module B3Form
class Input::Select < Input::TopLevelElement
def render_field
if render_called_with_block
builder.modifier[:select_options] = {}
builder.modifier[:select_modifier] = {}
builder.modifier[:select_field] = field
builder.capture(&render_called_with_block)
html = builder.select(field,
builder.modifier[:select_options],
builder.modifier[:select_modifier],
input_html)
builder.modifier.delete(:select_field)
builder.modifier.delete(:select_modifier)
builder.modifier.delete(:select_options)
html
else
raise ArgumentError, "call with block to set the select options"
end
end
private
def input_html
input_options = super
add_to_options(input_options, :class, "form-control")
if options[:select_size]
add_to_options(input_options, :size, options[:select_size])
end
if options[:multiple]
add_to_options(input_options, :multiple, options[:multiple])
end
input_options
end
end
end
| mit |
modulr/modulr-laravel | resources/views/dashboard.blade.php | 3348 | @extends('layouts.app')
@section('content')
<div class="container-fluid dashboard">
<div class="row">
@permission('read-tasks')
<div class="col-md-4">
<div class="panel panel-default panel-dashboard">
<div class="panel-heading">
<h3 class="panel-title">
Tasks
<a href="/tasks" class="pull-right">View all</a>
</h3>
</div>
<div class="panel-body" style="height:400px; overflow-y:scroll;">
<tasks></tasks>
</div>
</div>
</div>
@endpermission
@permission('read-news')
<div class="col-md-4">
<div class="panel panel-default panel-dashboard">
<div class="panel-heading">
<h3 class="panel-title">
News
<a href="/news" class="pull-right">View all</a>
</h3>
</div>
<div style="height:400px; overflow-y:scroll;">
<news-list></news-list>
</div>
</div>
</div>
@endpermission
@permission('read-events')
<div class="col-md-4">
<div class="panel panel-default panel-dashboard">
<div class="panel-heading">
<h3 class="panel-title">
Events
<a href="/events" class="pull-right">View all</a>
</h3>
</div>
<div class="panel-body" style="height:400px; overflow-y:scroll;">
<events-widget></events-widget>
</div>
</div>
</div>
@endpermission
@permission('read-contacts')
<div class="col-md-5">
<div class="panel panel-default panel-dashboard">
<div class="panel-heading">
<h3 class="panel-title">
Contacts
<a href="/contacts" class="pull-right">View all</a>
</h3>
</div>
<div class="panel-body" style="height:400px; overflow-y:scroll;">
<contacts-widget></contacts-widget>
</div>
</div>
</div>
@endpermission
@permission('read-files')
<div class="col-md-7">
<div class="panel panel-default panel-dashboard">
<div class="panel-heading">
<h3 class="panel-title">
Files
<a href="/files" class="pull-right">View all</a>
</h3>
</div>
<div class="panel-body" style="height:400px; overflow-y:scroll;">
<files-widget></files-widget>
</div>
</div>
</div>
@endpermission
</div>
</div>
</div>
@endsection
| mit |
KDE/kcolorchooser | kcolorchooser.cpp | 4111 | /*
This file is part of KDE
Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
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, 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 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.
*/
#include "kcolorchooser_version.h"
#include <KAboutData>
#include <KLocalizedString>
#include <KHelpMenu>
#include <QApplication>
#include <QClipboard>
#include <QColorDialog>
#include <QCommandLineParser>
#include <QDialogButtonBox>
#include <QMenu>
#include <QMimeData>
#include <QPushButton>
#include <iostream>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#endif
QApplication app(argc, argv);
KLocalizedString::setApplicationDomain("kcolorchooser");
KAboutData aboutData(QStringLiteral("kcolorchooser"),
i18n("KColorChooser"),
QStringLiteral(KCOLORCHOOSER_VERSION_STRING),
i18n("KDE Color Chooser"),
KAboutLicense::BSDL,
i18n("(c) 2000, Waldo Bastian"));
aboutData.addAuthor(i18n("Waldo Bastian"), QString(), QStringLiteral("bastian@kde.org"));
aboutData.addAuthor(i18n("Hugo Parente Lima"),i18n("KF5 port"), QStringLiteral("hugo.pl@gmail.com"));
aboutData.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
aboutData.setupCommandLine(&parser);
QCommandLineOption print(QStringLiteral("print"), i18n("Print the selected color to stdout."));
parser.addOption(print);
QCommandLineOption color(QStringLiteral("color"), i18n("Set initially selected color."), QStringLiteral("color"));
parser.addOption(color);
parser.process(app);
aboutData.processCommandLine(&parser);
QColorDialog dlg;
dlg.setOption(QColorDialog::DontUseNativeDialog);
QDialogButtonBox *box = dlg.findChild<QDialogButtonBox*>();
if (!box) {
return 1;
}
box->addButton(QDialogButtonBox::Help);
KHelpMenu *help = new KHelpMenu(&dlg, aboutData);
QObject::connect(box, &QDialogButtonBox::helpRequested, [=] () {
QPushButton *button = box->button(QDialogButtonBox::Help);
QPoint pos = button->pos();
pos.ry() += button->height();
pos = box->mapToGlobal(pos);
help->menu()->exec(pos);
});
if (parser.isSet(color)) {
dlg.setCurrentColor(QColor(parser.value(color)));
} else {
const QMimeData *mimeData = QApplication::clipboard()->mimeData(QClipboard::Clipboard);
if (mimeData) {
QColor clipboardColor = mimeData->colorData().value<QColor>();
if (clipboardColor.isValid()) {
dlg.setCurrentColor(clipboardColor);
}
}
}
dlg.show();
app.exec();
const QColor c = dlg.currentColor();
if (parser.isSet(print) && c.isValid()) {
std::cout << c.name().toUtf8().constData() << std::endl;
}
}
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_sql/lib/2018-06-01-preview/generated/azure_mgmt_sql/models/instance_pool_update.rb | 1420 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::SQL::Mgmt::V2018_06_01_preview
module Models
#
# An update to an Instance pool.
#
class InstancePoolUpdate
include MsRestAzure
# @return [Hash{String => String}] Resource tags.
attr_accessor :tags
#
# Mapper for InstancePoolUpdate class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'InstancePoolUpdate',
type: {
name: 'Composite',
class_name: 'InstancePoolUpdate',
model_properties: {
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| mit |
IT-PM-OpenAdaptronik/Webapp | apps/calc/tess_module/tess/tess.py | 7748 | '''
Created on 10.11.2017
@author: stoll
'''
import csv
import os
from numpy import argwhere, transpose
import numpy
from apps.calc.tess_module.tess import helpers
from apps.calc.tess_module.tess import waterfalls
def tess(time,data,data2):
'''
TESS is a software project that is part of the OpenAdaptronics program, conducted at the Fraunhofer LBF.
Its preliminary title is an acronym for “Tool zur Empfehlung von Strategien zur Schwingungsberuhigung”
:param time: time data
:param data: acceleration of the instrument
:param data2: exciting acceleration
:return:
'''
analysisweightsFILENAME = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'tess_input','analysis_weights.csv')
DesiredAmpLevel = 8
MinFrequency = 3; # general minimum frequency taken into account in Hz
TFMode = 0
#analysis sensitivity parameters
sens_FindPeaks = 50; # sensitivity of finding peaks in measurement data in %
# | 0% -> peaks are virtually not found
# | 100% -> peaks are found very often
sens_SumUpPeaks = 50; # sensitivity of summing up peaks to real peaks in %
# | 0% -> peaks are virtually never summed up to a real peak
# | 100% -> peaks are very likely to be summed up to a real peak
sens_TFOrigin = 50; # sensitivity of finding that a real peak's origin is the TF (and not the excitation) in %
# | 0% -> finding that the origin of a real peak is the excitation is very likely
# | 100% -> finding that the origin of a real peak is the TF is very likely
sens_TimevariantBehavior = 50; # sensitivity of considering the vibration behavior to be timevariant
# | 0% -> behavior is virtually never considered timevariant
# | 100% -> behavior is very easily considered timevariant
sens_UnproblematicLFD = 50; # sensitivity of considering the amplitude level in the low frequency domain (LFD) of A_1 to be unproblematic
# | 0% -> the amp level in the LFD is virtually never considered unproblematic
# | 100% -> the amp level in the LFD is very easily considered unproblematic
sens_UnproblematicNFD = 50; # sensitivity of considering the amplitude level in the (peak-) neighboring frequency domain (NFD) of A_1 to be unproblematic
# | 0% -> the amp level in the NFD is virtually never considered unproblematic
# | 100% -> the amp level in the NFD is very easily considered unproblematic
sens_UnproblematicHFD = 50; # sensitivity of considering the amplitude level in the high frequency domain (HFD) of A_0 to be unproblematic
# | 0% -> the amp level in the HFD is virtually never considered unproblematic
# | 100% -> the amp level in the HFD is very easily considered unproblematic
SV = numpy.zeros(16)
# solution identifiers
SID = []
SID.append('System Verstimmen, passiv')
SID.append('System Verstimmen, schaltbar')
SID.append('System Verstimmen, semi-aktiv')
SID.append('Daempfung erhoehen, passiv')
SID.append('Daempfung erhoehen, schaltbar')
SID.append('Daempfung erhoehen, semi-aktiv')
SID.append('Aktorik in Struktur einbringen')
SID.append('Tilger, passiv')
SID.append('Tilger, schaltbar')
SID.append('Neutralisator, passiv')
SID.append('Neutralisatior, schaltbar')
SID.append('Adaptiver Tilger/Neutralisator')
SID.append('Elastische Lagerung, passiv')
SID.append('Elastische Lagerung, schaltbar')
SID.append('Elastische Lagerung, semi-aktiv')
SID.append('Elastische Lagerung, aktiv')
SID.append('Inertialmassenaktor IMA')
# CSV-Datei mit den Bewertungsgewichten/Parametern einlesen
analysisweights = []
with open(analysisweightsFILENAME) as csvfile:
rd = csv.reader(csvfile)
for row in rd:
analysisweights.append(row)
del analysisweights [0]
analysisweights = transpose([[float(j) for j in i] for i in analysisweights])
#@TODO: Daten einlesen überprüfen
t = time
a_0 = data
a_1 = data2
A_0, f, tout = waterfalls.waterfall(t, a_0, 256, overlap=.5)
A_1, f, tout = waterfalls.waterfall(t, a_1, 256, overlap=.5)
tfmat = numpy.divide(A_1,A_0)
tf = numpy.average(tfmat, 0, A_0)
iValidF = numpy.where(f >= MinFrequency)
ifmin = argwhere(f>=MinFrequency)[0];
fft_rec_max_mod = A_1[:, iValidF].flatten()
# max occuring amplitude (median of top 10 maximum amplitudes)
lst = numpy.sort(fft_rec_max_mod)
maxamp = numpy.median(lst[-10:-1])
# problematic level used as reference
problvl = (DesiredAmpLevel/100)*maxamp
# finding real peaks in measurement data and determine origin
peakloc_ind, collectivepeaks, numrealpeaks, meannumrealpeaks, realpeakloc, isrealpeakfromTF = helpers.findRealPeaks(A_1, tf, f, iValidF, sens_FindPeaks, sens_TFOrigin, sens_SumUpPeaks, maxamp, problvl)
if meannumrealpeaks > 1.1:
multiplepeaks = True
SV = SV+analysisweights[0]
else:
multiplepeaks = False
SV = SV+analysisweights[1]
pass
meanpeaksfromtf = numpy.zeros(len(tout))
for i in range(len(tout)):
meanpeaksfromtf[i] = numpy.nanmean(isrealpeakfromTF[i])
pass
if numpy.nanmean(meanpeaksfromtf) >= 0.95:
allpeaksfromtf = True
SV = SV + analysisweights[2]
else:
allpeaksfromtf = False
SV = SV + analysisweights[3]
isrealpeaktimevariant = helpers.analyseTimeVariance(A_1, f, collectivepeaks, sens_TimevariantBehavior, peakloc_ind, problvl)
meanpeakstimevariant=[]
for i in range(len(isrealpeaktimevariant)):
meanpeakstimevariant.append(numpy.nanmean(isrealpeaktimevariant[i]))
if numpy.nanmean(meanpeakstimevariant) >= 0.05:
timevariantbehavior = True
SV = SV + analysisweights[4]
else:
timevariantbehavior = False
SV = SV + analysisweights[5]
islfdunproblematic, ishfdunproblematic, isnfdunproblematic = helpers.analyseFDAmplitude(A_1, f, iValidF, realpeakloc, numrealpeaks, multiplepeaks, sens_UnproblematicLFD, sens_UnproblematicHFD, sens_UnproblematicNFD, problvl)
# Analysis of Amplitude Level
if numpy.mean(islfdunproblematic) >= .95:
lfdunproblematic = True
SV = SV + analysisweights[6]
else:
lfdunproblematic = False
SV = SV + analysisweights[7]
if ~multiplepeaks:
if numpy.mean(isnfdunproblematic)>=.95:
nfdunproblematic = True
SV = SV + analysisweights[8]
else:
nfdunproblematic = False
SV = SV + analysisweights[9]
if numpy.mean(ishfdunproblematic) >= .95:
hfdunproblematic = True
SV = SV + analysisweights[10]
else:
hfdunproblematic = False
SV = SV + analysisweights[11]
srt = numpy.argsort(SV)
lst = numpy.sort(SV)
return {'strategie1': SID[srt[-1]],
'param1': str(SV[srt[-1]]),
'strategie2': SID[srt[-2]],
'param2': str(SV[srt[-2]]),
'strategie3': SID[srt[-3]],
'param3': str(SV[srt[-3]]),
'strategie4': SID[srt[-4]],
'param4': str(SV[srt[-4]]),
'strategie5': SID[srt[-5]],
'param5': str(SV[srt[-5]])}
| mit |
Enhex/value_ptr | value_ptr.hpp | 512 | #ifndef VALUE_PTR_HPP
#define VALUE_PTR_HPP
// value_ptr automatically dereferences its pointer
// Somewhat similar to std::reference_wrapper
template<typename T>
class value_ptr
{
public:
value_ptr() {}
value_ptr(T* ptr) : ptr(ptr) {}
T* ptr = nullptr;
// assignment
T& operator=(const T x) { *ptr = x; return *ptr; };
T& operator=(const T* x) { *ptr = *x; return *ptr; };
// access
operator T& () const noexcept { return *ptr; }
T& get() const noexcept { return *ptr; }
};
#endif//VALUE_PTR_HPP | mit |
dankempster/axstrad-doctrine-extensions | Sluggable/SluggableTrait.php | 960 | <?php
/**
* This file is part of the Axstrad library.
*
* (c) Dan Kempster <dev@dankempster.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright 2014-2015 Dan Kempster <dev@dankempster.co.uk>
*/
namespace Axstrad\DoctrineExtensions\Sluggable;
/**
* Axstrad\DoctrineExtensions\Sluggable\SluggableTrait
*
* Requires the following class properties
* - $slug = null
*
* @author Dan Kempster <dev@dankempster.co.uk>
* @license MIT
* @package Axstrad/DoctrineExtensions
* @subpackage Sluggable
*/
trait SluggableTrait
{
/**
* Get slug
*
* @return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Get slug
*
* @param string $slug
* @return self
*/
public function setSlug($slug)
{
$this->slug = (string) $slug;
return $this;
}
}
| mit |
spraetor/amdis2 | src/Traits.hpp | 363 | #pragma once
// #include <iostream>
#include "AMDiS_fwd.hpp"
#include "FixVec.hpp"
#include "MatrixVector.hpp"
#include "traits/basic.hpp"
#include "traits/category.hpp"
#include "traits/meta_basic.hpp"
#include "traits/num_cols.hpp"
#include "traits/num_rows.hpp"
#include "traits/size.hpp"
#include "traits/tag.hpp"
namespace AMDiS {} // end namespace AMDiS
| mit |
bons/b-toggle | test/b-toggle-spec.js | 2279 | 'use strict';
require('angular');
require('angular-mocks');
var app = require('../lib/b-toggle');
function hasClass(element, cls)
{
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
// Patch since PhantomJS does not implement click() on HTMLElement. In some
// cases we need to execute the native click on an element. However, jQuery's
// $.fn.click() does not dispatch to the native function on <a> elements, so we
// can't use it in our implementations: $el[0].click() to correctly dispatch.
if (!HTMLElement.prototype.click)
{
HTMLElement.prototype.click = function()
{
var ev = document.createEvent('MouseEvent');
ev.initMouseEvent(
'click',
/*bubble*/true, /*cancelable*/true,
window, null,
0, 0, 0, 0, /*coordinates*/
false, false, false, false, /*modifier keys*/
0/*button=left*/, null
);
this.dispatchEvent(ev);
};
}
describe('Test Suite: bToggle', function()
{
var scope,
$compile;
function injectHTML(cls)
{
var body = document.querySelector("body");
body.innerHTML = '<div b-toggle class="' + cls +'"></div>';
$compile(body)(scope);
var toggle = body.querySelector("[b-toggle]");
return toggle;
}
beforeEach(angular.mock.module('bons.bToggle'));
beforeEach(angular.mock.inject(['$rootScope','$compile',
function ($rootScope, _$compile_)
{
scope = $rootScope.$new();
$compile = _$compile_;
}
])
);
it('should be defined', function()
{
expect(app).toBeDefined();
});
it('should add the class active if the element was clicked', function()
{
var toggleElement = injectHTML();
toggleElement.click();
expect(hasClass(toggleElement, 'active')).toBe(true);
});
it('should remove the class active is the element was clicked and had the active class', function()
{
var toggleElement = injectHTML('active');
toggleElement.click();
expect(!hasClass(toggleElement, 'active')).toBe(true);
});
it('should remove the class active is the element was clicked and had the active class', function()
{
var toggleElement = injectHTML('active');
toggleElement.click();
expect(!hasClass(toggleElement, 'active')).toBe(true);
});
});
| mit |
jesseh77/UrlFilter | src/UrlFilter/INotNullExpressionProcessor.cs | 218 | using System.Linq.Expressions;
namespace UrlFilter
{
public interface INotNullExpressionProcessor
{
Expression NotNullPropertyExpression(string segment, ParameterExpression paramExpression);
}
} | mit |
conferencesapp/rubyconferences-server | app/services/device_creator.rb | 366 | class DeviceCreator
attr_reader :device
def initialize(params)
@params = params
end
def create
@device ||= Device.find_or_create_by(
token: token,
conference_type: conference_type
)
end
private
attr_reader :params
def token
params[:token]
end
def conference_type
params[:conference_type] || "ruby"
end
end
| mit |
garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookWorksheetTablesCollectionResponse.cs | 1222 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type WorkbookWorksheetTablesCollectionResponse.
/// </summary>
[DataContract]
public class WorkbookWorksheetTablesCollectionResponse
{
/// <summary>
/// Gets or sets the <see cref="IWorkbookWorksheetTablesCollectionPage"/> value.
/// </summary>
[DataMember(Name = "value", EmitDefaultValue = false, IsRequired = false)]
public IWorkbookWorksheetTablesCollectionPage Value { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
}
}
| mit |
kaoscript/kaoscript | test/fixtures/compile/router/router.overflow.func.i_ie.js | 991 | var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
const __ks_foobar_1 = foobar;
function foobar() {
if(arguments.length === 1 && Type.isNumber(arguments[0])) {
let __ks_i = -1;
let a = arguments[++__ks_i];
if(a === void 0 || a === null) {
return __ks_foobar_1(...arguments);
}
else if(!Type.isNumber(a)) {
return __ks_foobar_1(...arguments);
}
return 1;
}
else if(arguments.length === 2 && Type.isNumber(arguments[0]) && Type.isNumber(arguments[1])) {
let __ks_i = -1;
let a = arguments[++__ks_i];
if(a === void 0 || a === null) {
return __ks_foobar_1(...arguments);
}
else if(!Type.isNumber(a)) {
return __ks_foobar_1(...arguments);
}
let b = arguments[++__ks_i];
if(b === void 0 || b === null) {
return __ks_foobar_1(...arguments);
}
else if(!Type.isNumber(b)) {
return __ks_foobar_1(...arguments);
}
return 1;
}
else {
return __ks_foobar_1(...arguments);
}
};
}; | mit |
joshsh/ripple | ripple-core/src/main/java/net/fortytwo/ripple/model/types/NumberType.java | 1578 | package net.fortytwo.ripple.model.types;
import net.fortytwo.ripple.RippleException;
import net.fortytwo.ripple.io.RipplePrintStream;
import net.fortytwo.ripple.model.ModelConnection;
import org.openrdf.model.Value;
import java.util.Collection;
/**
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class NumberType extends NumericType<Number> {
@Override
public Collection<Class> getInstanceClasses() {
return datatypeByClass.keySet();
}
@Override
public boolean isInstance(final Number instance) {
return null != findDatatype(instance);
}
@Override
public void print(final Number instance,
final RipplePrintStream p,
final ModelConnection mc) throws RippleException {
Datatype datatype = findDatatype(instance);
if (null == datatype) {
throw new IllegalArgumentException("numeric value is of unknown class: " + instance.getClass());
}
printTo(instance, datatype, p);
}
@Override
public Value toRDF(Number instance, ModelConnection mc) throws RippleException {
Datatype datatype = findDatatype(instance);
if (null == datatype) {
throw new IllegalArgumentException();
}
return toRDF(instance, datatype, mc);
}
@Override
public Datatype findDatatype(final Number instance) {
return datatypeByClass.get(instance.getClass());
}
@Override
public Number findNumber(Number instance, Datatype datatype) {
return instance;
}
}
| mit |
bigfoot90/doctrine2 | tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php | 3177 | <?php
declare(strict_types=1);
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\Collection;
use Doctrine\Tests\OrmFunctionalTestCase;
use function count;
class DDC199Test extends OrmFunctionalTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->_schemaTool->createSchema(
[
$this->_em->getClassMetadata(DDC199ParentClass::class),
$this->_em->getClassMetadata(DDC199ChildClass::class),
$this->_em->getClassMetadata(DDC199RelatedClass::class),
]
);
}
public function testPolymorphicLoading(): void
{
$child = new DDC199ChildClass();
$child->parentData = 'parentData';
$child->childData = 'childData';
$this->_em->persist($child);
$related1 = new DDC199RelatedClass();
$related1->relatedData = 'related1';
$related1->parent = $child;
$this->_em->persist($related1);
$related2 = new DDC199RelatedClass();
$related2->relatedData = 'related2';
$related2->parent = $child;
$this->_em->persist($related2);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('select e,r from Doctrine\Tests\ORM\Functional\Ticket\DDC199ParentClass e join e.relatedEntities r');
$result = $query->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf(DDC199ParentClass::class, $result[0]);
$this->assertTrue($result[0]->relatedEntities->isInitialized());
$this->assertEquals(2, $result[0]->relatedEntities->count());
$this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[0]);
$this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[1]);
}
}
/**
* @Entity @Table(name="ddc199_entities")
* @InheritanceType("SINGLE_TABLE")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"parent" = "DDC199ParentClass", "child" = "DDC199ChildClass"})
*/
class DDC199ParentClass
{
/**
* @var int
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @var string
* @Column(type="string")
*/
public $parentData;
/**
* @psalm-var Collection<int, DDC199RelatedClass>
* @OneToMany(targetEntity="DDC199RelatedClass", mappedBy="parent")
*/
public $relatedEntities;
}
/** @Entity */
class DDC199ChildClass extends DDC199ParentClass
{
/**
* @var string
* @Column
*/
public $childData;
}
/** @Entity @Table(name="ddc199_relatedclass") */
class DDC199RelatedClass
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @var string
* @Column
*/
public $relatedData;
/**
* @var DDC199ParentClass
* @ManyToOne(targetEntity="DDC199ParentClass", inversedBy="relatedEntities")
* @JoinColumn(name="parent_id", referencedColumnName="id")
*/
public $parent;
}
| mit |
juniorgasparotto/SpentBook | src_old/SpentBook.Web/App_Start/RouteConfig.cs | 583 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SpentBook.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit |
zengfenfei/ringcentral-ts | src/definitions/CompanyAnsweringRuleTimeIntervalRequest.ts | 235 | /* Generated code */
interface CompanyAnsweringRuleTimeIntervalRequest {
/**
* Time in format hh:mm
*/
from?: string;
/**
* Time in format hh:mm
*/
to?: string;
}
export default CompanyAnsweringRuleTimeIntervalRequest;
| mit |
nunows/agenda-cultural | AC_DAO/src/agendacultural/model/TipoEvento.java | 275 | package agendacultural.model;
/**
* Class que representa um Tipo de Evento
*
*/
public class TipoEvento {
private int id;
private String nome;
public TipoEvento() {
}
public TipoEvento(int id, String nome) {
super();
this.id = id;
this.nome = nome;
}
}
| mit |
GRGSIBERIA/VendingMachine | lib/vending_machine.rb | 535 | require "./lib/coin.rb"
require "./lib/stamp.rb"
require "./lib/coin_pocket.rb"
class VendingMachine
def initialize
@pocket = CoinPocket.new
end
def insert(coin_price)
begin
coin = CoinFactory.coin(coin_price)
return @pocket.insert(coin)
rescue => error_msg
puts error_msg
end
end
def buy(stamp_price)
begin
return @pocket.buy(stamp_price)
rescue => error_msg
puts error_msg
end
end
def refund
@pocket.refund
end
def check
@pocket.check
end
end | mit |
cnvs/canvas | resources/lang/en/app.php | 7009 | <?php
return [
'a_descriptive_summary' => 'A descriptive summary...',
'a_unique_slug' => 'a-unique-slug',
'add_a_caption' => 'Add a caption for your image',
'add_a_new_tag' => 'Add a new tag',
'add_a_new_topic' => 'Add this as a new topic',
'admin' => 'Admin',
'all_stats' => 'All stats',
'assets_are_not_up_to_date' => 'The assets for Canvas are not up-to-date with the installed version.',
'average_reading_time' => 'Average Reading Time',
'cancel' => 'Cancel',
'cancel_scheduling' => 'Cancel scheduling',
'canonical_link' => 'Canonical Link',
'canonical_link_placeholder' => 'Canonical URL of original source',
'caption' => 'Caption',
'choose_a_username' => 'Choose a username...',
'click_to_see_insights' => 'Click on a post below to see more detailed insights.',
'contributor' => 'Contributor',
'convert_to_draft' => 'Convert to draft',
'created' => 'Created',
'dark_mode' => 'Dark mode',
'default_layout' => 'Default layout',
'delete' => 'Delete',
'deleted_posts_are_gone_forever' => 'Are you sure you want to delete this post? This action cannot be undone.',
'deleted_tags_are_gone_forever' => 'Are you sure you want to delete this tag? This action cannot be undone.',
'deleted_topics_are_gone_forever' => 'Are you sure you want to delete this topic? This action cannot be undone.',
'deleted_users_are_gone_forever' => 'Are you sure you want to delete this user? This action cannot be undone.',
'details' => 'Details',
'done' => 'Done',
'draft' => 'Draft',
'drafts' => 'Drafts',
'drop_files_or_click_to_upload' => 'Drop files or click here to upload',
'edit_post' => 'Edit post',
'edit_profile' => 'Edit profile',
'edit_tag' => 'Edit tag',
'edit_topic' => 'Edit topic',
'edit_user' => 'Edit user',
'editor' => 'Editor',
'embed_content' => 'Embed Content',
'featured_image' => 'Featured image',
'featured_image_caption' => 'Featured Image Caption',
'from' => 'From',
'from_last_month' => 'from last month',
'general_settings' => 'General settings',
'give_your_tag_a_name' => 'Give your tag a name',
'give_your_tag_a_name_slug' => 'give-your-tag-a-name',
'give_your_topic_a_name' => 'Give your topic a name',
'give_your_topic_a_name_slug' => 'give-your-topic-a-name',
'last_thirty_days' => 'Last 30 days',
'last_updated' => 'Last updated',
'layout' => 'Layout',
'lifetime_summary' => 'Lifetime Summary',
'locale' => 'Locale',
'manage_user_roles' => 'Manage user roles and permissions.',
'meta_description' => 'Meta Description',
'meta_description_placeholder' => 'Meta description for your post',
'meta_title' => 'Meta Title',
'meta_title_placeholder' => 'Meta title for your post',
'min' => 'min',
'monthly_summary' => 'Monthly Summary',
'name' => 'Name',
'new_post' => 'New post',
'new_tag' => 'New tag',
'new_topic' => 'New topic',
'new_user' => 'New user',
'no_images_found_for' => 'No images found for',
'on' => 'on',
'other' => 'Other',
'paste_embed_code_to_include' => 'Paste any embed code to include in the post',
'paste_or_type_a_link' => 'Paste or type a link...',
'photo_by' => 'Photo by',
'popular_reading_times' => 'Popular reading times',
'post_scheduling_format' => 'Post scheduling uses a 24-hour time format and is utilizing the',
'post' => 'Post',
'posts' => 'Posts',
'publish' => 'Publish',
'publish_now' => 'Publish now',
'published' => 'Published',
'published_on' => 'Published on',
'published_posts' => 'Published Posts',
'publishing' => 'Publishing',
'read' => 'read',
'referer_unknown' => 'Post views in this category could not reliably determine a referrer. e.g. Incognito mode',
'save' => 'Save',
'save_changes' => 'Save changes',
'saved' => 'Saved!',
'saving' => 'Saving...',
'schedule_for_later' => 'Schedule for later',
'schedule_to_publish' => 'Schedule to publish',
'search_free_photos' => 'Search free high-resolution photos',
'see_all_stats' => 'See all stats',
'select_a_topic' => 'Select a topic...',
'select_some_tags' => 'Select some tags...',
'select_your_language_or_region' => 'Select your language or region.',
'search_canvas' => 'Search Canvas',
'seo_settings' => 'SEO settings',
'settings' => 'Settings',
'sign_out' => 'Sign out',
'slug' => 'Slug',
'stats' => 'Stats',
'stats_are_made_available' => 'Stats are made available when you begin publishing!',
'stats_for_your_posts' => 'Stats for your posts',
'success' => 'Success!',
'summary' => 'Summary',
'sync_with_post_description' => 'Sync with the post summary',
'sync_with_post_title' => 'Sync with the post title',
'tags' => 'Tags',
'tags_are_great_for' => 'Tags are great for describing the details of your posts.',
'tell_us_about_yourself' => 'Tell us a little bit about yourself...',
'tell_your_story' => 'Tell your story...',
'thirty_days' => '30 days',
'timezone' => 'timezone',
'title' => 'Title',
'to' => 'to',
'to_update_run' => 'To update, run:',
'toggle_dark_mode' => 'Use a dark appearance for Canvas.',
'toggle_digest' => 'Control whether to receive a weekly summary of your published content.',
'topic' => 'Topic',
'topics' => 'Topics',
'topics_are_great_for' => 'Topics are great for broadly grouping your posts.',
'total_posts' => 'Total posts',
'total_views' => 'Total Views',
'type_caption_for_image' => 'Type caption for image (optional)',
'unique_visit' => 'unique visit',
'unique_visits' => 'unique visits',
'updated' => 'Updated',
'username' => 'Username',
'users' => 'Users',
'view' => 'view',
'view_stats' => 'View stats',
'views' => 'Views',
'views_by_traffic_source' => 'Views by traffic source',
'views_info' => 'A view is counted when a visitor loads or reloads a page.',
'views_this_week' => 'Views this week',
'visitor' => 'visitor',
'visitors' => 'Visitors',
'visits_info' => 'A visitor is counted when we see a user or browser for the first time in a given 24-hour period.',
'visits' => 'Visits',
'waiting_until_more_data' => 'Waiting until your post has more views to show these insights.',
'weekly_digest' => 'Weekly digest',
'wide_image' => 'Wide image',
'write_on_the_go' => 'Write on the go with our mobile-ready app!',
'you_have_no_draft_posts' => 'You have no drafts',
'you_have_no_published_posts' => 'You have no published posts',
'you_have_no_tags' => 'You have no tags',
'you_have_no_topics' => 'You have no topics',
'your_post_will_publish_at' => 'Your post will publish at',
'your_posts_received' => 'your posts received:',
'your_profile' => 'Your profile',
'your_stats' => 'Your stats',
'your_weekly_writer_summary_for' => 'Your weekly writer summary for',
];
| mit |
gusajz/sqlite-client-server-poc | sqlite_server/server.py | 284 | import click
import logging
logging.basicConfig()
@click.command()
@click.option('--path', prompt='Sqlite database', help='Sqlite full path db.')
def server(path):
import thrift_server
thrift_server.serve(8080, path)
if __name__ == '__main__':
server()
| mit |
theoboldt/juvem | app/assets/js/lib/jquery.filedrop.js | 16824 | /*global jQuery:false, alert:false */
/*
* Default text - jQuery plugin for html5 dragging files from desktop to browser
*
* Author: Weixi Yen
*
* Email: [Firstname][Lastname]@gmail.com
*
* Copyright (c) 2010 Resopollution
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.github.com/weixiyen/jquery-filedrop
*
* Version: 0.1.0
*
* Features:
* Allows sending of extra parameters with file.
* Works with Firefox 3.6+
* Future-compliant with HTML5 spec (will work with Webkit browsers and IE9)
* Usage:
* See README at project homepage
*
*/
;(function($) {
var default_opts = {
fallback_id: '',
fallback_dropzoneClick : true,
url: '',
refresh: 1000,
paramname: 'userfile',
requestType: 'POST', // just in case you want to use another HTTP verb
allowedfileextensions:[],
allowedfiletypes:[],
maxfiles: 25, // Ignored if queuefiles is set > 0
maxfilesize: 1, // MB file size limit
queuefiles: 0, // Max files before queueing (for large volume uploads)
queuewait: 200, // Queue wait time if full
data: {},
headers: {},
drop: empty,
dragStart: empty,
dragEnter: empty,
dragOver: empty,
dragLeave: empty,
docEnter: empty,
docOver: empty,
docLeave: empty,
beforeEach: empty,
afterAll: empty,
rename: empty,
error: function(err, file, i, status) {
alert(err);
},
uploadStarted: empty,
uploadFinished: empty,
progressUpdated: empty,
globalProgressUpdated: empty,
speedUpdated: empty
},
errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge", "FileTypeNotAllowed", "NotFound", "NotReadable", "AbortError", "ReadError", "FileExtensionNotAllowed"];
$.fn.filedrop = function(options) {
var opts = $.extend({}, default_opts, options),
global_progress = [],
doc_leave_timer, stop_loop = false,
files_count = 0,
files;
if ( opts.fallback_dropzoneClick === true )
{
$('#' + opts.fallback_id).css({
display: 'none',
width: 0,
height: 0
});
}
this.on('drop', drop).on('dragstart', opts.dragStart).on('dragenter', dragEnter).on('dragover', dragOver).on('dragleave', dragLeave);
$(document).on('drop', docDrop).on('dragenter', docEnter).on('dragover', docOver).on('dragleave', docLeave);
if ( opts.fallback_dropzoneClick === true )
{
if ( this.find('#' + opts.fallback_id).length > 0 )
{
throw "Fallback element ["+opts.fallback_id+"] cannot be inside dropzone, unless option fallback_dropzoneClick is false";
}
else
{
this.on('click', function(e){
$('#' + opts.fallback_id).trigger(e);
});
}
}
$('#' + opts.fallback_id).change(function(e) {
opts.drop(e);
files = e.target.files;
files_count = files.length;
upload();
});
function drop(e) {
if( opts.drop.call(this, e) === false ) return false;
if(!e.originalEvent.dataTransfer)
return;
files = e.originalEvent.dataTransfer.files;
if (files === null || files === undefined || files.length === 0) {
opts.error(errors[0]);
return false;
}
files_count = files.length;
upload();
e.preventDefault();
return false;
}
function getBuilder(filename, filedata, mime, boundary) {
var dashdash = '--',
crlf = '\r\n',
builder = '',
paramname = opts.paramname;
if (opts.data) {
var params = $.param(opts.data).replace(/\+/g, '%20').split(/&/);
$.each(params, function() {
var pair = this.split("=", 2),
name = decodeURIComponent(pair[0]),
val = decodeURIComponent(pair[1]);
if (pair.length !== 2) {
return;
}
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="' + name + '"';
builder += crlf;
builder += crlf;
builder += val;
builder += crlf;
});
}
if (jQuery.isFunction(paramname)){
paramname = paramname(filename);
}
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="' + (paramname||"") + '"';
builder += '; filename="' + encodeURIComponent(filename) + '"';
builder += crlf;
builder += 'Content-Type: ' + mime;
builder += crlf;
builder += crlf;
builder += filedata;
builder += crlf;
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
return builder;
}
function progress(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
if (this.currentProgress !== percentage) {
this.currentProgress = percentage;
opts.progressUpdated(this.index, this.file, this.currentProgress);
global_progress[this.global_progress_index] = this.currentProgress;
globalProgress();
var elapsed = new Date().getTime();
var diffTime = elapsed - this.currentStart;
if (diffTime >= opts.refresh) {
var diffData = e.loaded - this.startData;
var speed = diffData / diffTime; // KB per second
opts.speedUpdated(this.index, this.file, speed);
this.startData = e.loaded;
this.currentStart = elapsed;
}
}
}
}
function globalProgress() {
if (global_progress.length === 0) {
return;
}
var total = 0, index;
for (index in global_progress) {
if(global_progress.hasOwnProperty(index)) {
total = total + global_progress[index];
}
}
opts.globalProgressUpdated(Math.round(total / global_progress.length));
}
// Respond to an upload
function upload() {
stop_loop = false;
if (!files) {
opts.error(errors[0]);
return false;
}
if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
for(var fileIndex = files.length;fileIndex--;) {
if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
opts.error(errors[3], files[fileIndex]);
return false;
}
}
}
if (opts.allowedfileextensions.push && opts.allowedfileextensions.length) {
for(var fileIndex = files.length;fileIndex--;) {
var allowedextension = false;
for (i=0;i<opts.allowedfileextensions.length;i++){
if (files[fileIndex].name.substr(files[fileIndex].name.length-opts.allowedfileextensions[i].length).toLowerCase()
== opts.allowedfileextensions[i].toLowerCase()
) {
allowedextension = true;
}
}
if (!allowedextension){
opts.error(errors[8], files[fileIndex]);
return false;
}
}
}
var filesDone = 0,
filesRejected = 0;
if (files_count > opts.maxfiles && opts.queuefiles === 0) {
opts.error(errors[1]);
return false;
}
// Define queues to manage upload process
var workQueue = [];
var processingQueue = [];
var doneQueue = [];
// Add everything to the workQueue
for (var i = 0; i < files_count; i++) {
workQueue.push(i);
}
// Helper function to enable pause of processing to wait
// for in process queue to complete
var pause = function(timeout) {
setTimeout(process, timeout);
};
// Process an upload, recursive
var process = function() {
var fileIndex;
if (stop_loop) {
return false;
}
// Check to see if are in queue mode
if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
return pause(opts.queuewait);
} else {
// Take first thing off work queue
fileIndex = workQueue[0];
workQueue.splice(0, 1);
// Add to processing queue
processingQueue.push(fileIndex);
}
try {
if (beforeEach(files[fileIndex]) !== false) {
if (fileIndex === files_count) {
return;
}
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = fileIndex;
if (files[fileIndex].size > max_file_size) {
opts.error(errors[2], files[fileIndex], fileIndex);
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
filesRejected++;
return true;
}
reader.onerror = function(e) {
switch(e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
opts.error(errors[4]);
return false;
case e.target.error.NOT_READABLE_ERR:
opts.error(errors[5]);
return false;
case e.target.error.ABORT_ERR:
opts.error(errors[6]);
return false;
default:
opts.error(errors[7]);
return false;
}
};
reader.onloadend = !opts.beforeSend ? send : function (e) {
opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
};
reader.readAsDataURL(files[fileIndex]);
} else {
filesRejected++;
}
} catch (err) {
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
opts.error(errors[0]);
return false;
}
// If we still have work to do,
if (workQueue.length > 0) {
process();
}
};
var send = function(e) {
var fileIndex = (e.srcElement || e.target).index;
// Sometimes the index is not attached to the
// event object. Find it by size. Hack for sure.
if (e.target.index === undefined) {
e.target.index = getIndexBySize(e.total);
}
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
file = files[e.target.index],
index = e.target.index,
start_time = new Date().getTime(),
boundary = '------multipartformboundary' + (new Date()).getTime(),
global_progress_index = global_progress.length,
builder,
newName = rename(file.name),
mime = file.type;
if (opts.withCredentials) {
xhr.withCredentials = opts.withCredentials;
}
var encodedString = e.target.result.split(',')[1];
var data = encodedString === undefined ? '' : atob(encodedString);
if (typeof newName === "string") {
builder = getBuilder(newName, data, mime, boundary);
} else {
builder = getBuilder(file.name, data, mime, boundary);
}
upload.index = index;
upload.file = file;
upload.downloadStartTime = start_time;
upload.currentStart = start_time;
upload.currentProgress = 0;
upload.global_progress_index = global_progress_index;
upload.startData = 0;
upload.addEventListener("progress", progress, false);
// Allow url to be a method
if (jQuery.isFunction(opts.url)) {
xhr.open(opts.requestType, opts.url(upload), true);
} else {
xhr.open(opts.requestType, opts.url, true);
}
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Add headers
$.each(opts.headers, function(k, v) {
xhr.setRequestHeader(k, v);
});
if(!xhr.sendAsBinary){
xhr.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
xhr.sendAsBinary(builder);
global_progress[global_progress_index] = 0;
globalProgress();
opts.uploadStarted(index, file, files_count);
xhr.onload = function() {
var serverResponse = null;
if (xhr.responseText) {
try {
serverResponse = jQuery.parseJSON(xhr.responseText);
}
catch (e) {
serverResponse = xhr.responseText;
}
}
var now = new Date().getTime(),
timeDiff = now - start_time,
result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
filesDone++;
// Remove from processing queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
// Add to donequeue
doneQueue.push(fileIndex);
// Make sure the global progress is updated
global_progress[global_progress_index] = 100;
globalProgress();
if (filesDone === (files_count - filesRejected)) {
afterAll();
}
if (result === false) {
stop_loop = true;
}
// Pass any errors to the error option
if (xhr.status < 200 || xhr.status > 299) {
opts.error(xhr.statusText, file, fileIndex, xhr.status);
}
};
};
// Initiate the processing loop
process();
}
function getIndexBySize(size) {
for (var i = 0; i < files_count; i++) {
if (files[i].size === size) {
return i;
}
}
return undefined;
}
function rename(name) {
return opts.rename(name);
}
function beforeEach(file) {
return opts.beforeEach(file);
}
function afterAll() {
return opts.afterAll();
}
function dragEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.dragEnter.call(this, e);
}
function dragOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver.call(this, e);
opts.dragOver.call(this, e);
}
function dragLeave(e) {
clearTimeout(doc_leave_timer);
opts.dragLeave.call(this, e);
e.stopPropagation();
}
function docDrop(e) {
e.preventDefault();
opts.docLeave.call(this, e);
return false;
}
function docEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docEnter.call(this, e);
return false;
}
function docOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver.call(this, e);
return false;
}
function docLeave(e) {
doc_leave_timer = setTimeout((function(_this) {
return function() {
opts.docLeave.call(_this, e);
};
})(this), 200);
}
return this;
};
function empty() {}
try {
if (XMLHttpRequest.prototype.sendAsBinary) {
return;
}
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
// Not pretty: Chrome 22 deprecated sending ArrayBuffer, moving instead
// to sending ArrayBufferView. Sadly, no proper way to detect this
// functionality has been discovered. Happily, Chrome 22 also introduced
// the base ArrayBufferView class, not present in Chrome 21.
if ('ArrayBufferView' in window)
this.send(ui8a);
else
this.send(ui8a.buffer);
};
} catch (e) {}
})(jQuery); | mit |
MrPIvanov/SoftUni | 05-Csharp OOP Basics/10-EXERCISE INHERITANCE/10-InheritanceExercises/05-MordorCruelPlan/Factories/Foods/Apple.cs | 135 | public class Apple : Food
{
private const int PointsOfHappiness = 1;
public Apple() : base(PointsOfHappiness)
{
}
} | mit |
nihey/blog | plugins/content.js | 2491 | var fs = require('fs'),
path = require('path'),
glob = require('glob').sync,
cheerio = require('cheerio');
var ContentPlugin = function(pattern, index) {
this.index = index;
this.files = glob(pattern, {nodir: true});
};
ContentPlugin.prototype.apply = function(compiler) {
this.compiler = compiler;
this.posts = [];
this.files.forEach(function(file) {
compiler.plugin('emit', this.compile.bind(this, file));
}, this);
compiler.plugin('after-emit', function(compilation, next) {
var $ = cheerio.load(global.htmls[this.index]);
this.posts = this.posts.sort((a, b) => b.date.localeCompare(a.date));
$('.main-content').html(this.posts.map(function(post) {
return [
'<div>',
' <div class="post brief">',
' <span class="title">' + post.title + '</span>',
' <div class="post-date">' + post.date + '</div>',
' <p class="post-abstract">' + post.abstrakt + '</p>',
' <a href="' + post.file + '">read</a>',
' </div>',
'</div>',
].join('');
}).join(''));
var file = path.join(compiler.outputPath, this.index);
var mainPath = path.join(compiler.outputPath, 'main.html');
fs.writeFileSync(file, $.html());
fs.writeFileSync(mainPath, $('.main-content').html());
this.posts = [];
next();
}.bind(this));
};
ContentPlugin.prototype.compile = function(file, compilation, next) {
// Make sure this script is reloaded once this file is changed
if (compilation.contextDependencies.indexOf(file) === -1) {
compilation.contextDependencies.push(file);
}
var content = fs.readFileSync(file);
// Inject a script that redirect the user to the right page if he landed
// on the raw post one
content += [
'<script>',
'if (location.hash !== "#!/' + file +'") {',
' location.replace("http://nihey.github.io/blog/#!/' + file + '")',
'}',
'</script>',
].join('');
var $ = cheerio.load(content);
this.write(compilation, file, content);
this.posts.push({
title: $('.title').html(),
date: $('.post-date').html(),
abstrakt: $('.content p:first-child').html(),
content: $('.content').html(),
file: file,
});
next();
};
ContentPlugin.prototype.write = function(compilation, filename, content) {
compilation.assets[filename] = {
source: function() {
return content;
},
size: function() {
return content.length;
},
};
};
module.exports = ContentPlugin;
| mit |
cordoval/Confoo | app/AppKernel.php | 1417 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new Sensio\Bundle\HangmanBundle\SensioHangmanBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| mit |
marcelrf/patternal | patternal.js | 1445 | var SymbolDescriptor = require("./SymbolDescriptor"),
SequenceDescriptor = require("./SequenceDescriptor"),
ParallelDescriptor = require("./ParallelDescriptor"),
RepeatDescriptor = require("./RepeatDescriptor"),
NotDescriptor = require("./NotDescriptor");
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
function DescriptorConstructor (Descriptor) {
return function () {
var args = Array.prototype.slice.call(arguments);
return construct(Descriptor, args);
};
}
function AndConstructor () {
var args = Array.prototype.slice.call(arguments),
descriptorParams = [args.length, args.length].concat(args);
return construct(ParallelDescriptor, descriptorParams);
}
function OrConstructor () {
var args = Array.prototype.slice.call(arguments),
descriptorParams = [1, args.length].concat(args);
return construct(ParallelDescriptor, descriptorParams);
}
var ANY = new SymbolDescriptor(function () { return true; });
module.exports = {
Sym: DescriptorConstructor(SymbolDescriptor),
Seq: DescriptorConstructor(SequenceDescriptor),
Par: DescriptorConstructor(ParallelDescriptor),
Rep: DescriptorConstructor(RepeatDescriptor),
Not: DescriptorConstructor(NotDescriptor),
And: AndConstructor,
Or: OrConstructor,
ANY: ANY
};
| mit |
tinywind/practice-codility.com | java/org/tinywind/codility/lesson5/PassingCars.java | 845 | package org.tinywind.codility.lesson5;
import java.util.Arrays;
/**
* https://codility.com/programmers/task/passing_cars/
* Count the number of passing cars on the road.
*
* @author tinywind
* score: 100
*/
public class PassingCars {
public static void main(String[] args) {
p(0, 1, 0, 1, 1);
}
private static void p(int... A) {
System.out.println("A(" + Arrays.toString(A) + ") : " + solution(A));
}
private static int solution(int[] A) {
int count = 0;
int lastCount = 0;
for (int i = A.length - 1; i >= 0; i--) {
if (A[i] == 1) {
lastCount++;
continue;
}
count += lastCount;
if (1000000000 < count) return -1;
}
return count;
}
}
| mit |
ruzyrain/modelweb | BRouter/src/HttpServer/ElementalHttpPostBytes.java | 10732 | package HttpServer;
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/*
*
*/
import java.io.IOException;
import java.net.Socket;
import java.util.Date;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
import internalStorageStructure.CmdBuffer;
/**
* Elemental example for executing multiple POST requests sequentially.
* Ïòhttpserver postÊý¾Ý
*/
public class ElementalHttpPostBytes implements Runnable {
private byte[] content;
private String ip;
public ElementalHttpPostBytes(){
}
public ElementalHttpPostBytes(byte[] content,String ip){
this.content = content;
this.ip = ip;
}
public void post2Server(byte[] content,String ip) throws Exception{
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost(ip, 8090);
//HttpHost host = new HttpHost("192.168.111.191", 8090);
coreContext.setTargetHost(host);
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
try {
HttpEntity[] requestBodies = {
new ByteArrayEntity(content,ContentType.create("text/plain", Consts.UTF_8))
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
try{
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
catch(Exception e)
{
//System.out.println("connect timeout exception.server is not open");
//e.printStackTrace();
}
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/test.txt");
request.setEntity(requestBodies[i]);
//System.out.println(">> Request URI: " + request.getRequestLine().getUri());
//System.out.println("***********************"+content.getBytes().length);
httpexecutor.preProcess(request, httpproc, coreContext);
String cmdString="";
HttpResponse response=null;
try {
response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
HttpEntity he=response.getEntity();
//cmdString = EntityUtils.toString(he);
byte[]cmdByte = EntityUtils.toByteArray(he);
cmdString=new String(cmdByte);
// System.out.println("<< Response: " + response.getStatusLine());
if(response.getStatusLine().getStatusCode()==200){
// oldCmdHandler(cmdString);
new DownCmdHandler().handleCmd(cmdByte,cmdString);
}
else{
System.out.println(ip);
}
//System.out.println("=============="+cmdString);
if (!connStrategy.keepAlive(response, coreContext)) {
conn.close();
} else {
//System.out.println("Connection kept alive...");
}
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
}
}
} finally {
conn.close();
}
}
public static void main(String[] args){
// ElementalHttpPostBytes elementalHttpPost = new ElementalHttpPostBytes();
// //char[]panid={0x2,0x3};
// //String string=new String(panid);
// String cmd="1122222222333333eeee";
// //elementalHttpPost.cmdHandler(cmd);
// try {
// //new ElementalHttpPost().post2Server("test content");
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("¿ªÊ¼Ê±¼äÊÇ£º" + new Date());
String originString = "192.168.10.117;a000000000000117,2015-01-30 15:45:29,9,1;1122222222333333,17,G1,-74,G2,-83,2015-01-30 15:45:28";
try{
new ElementalHttpPostBytes().post2Server(originString.getBytes(), ConstantInterface.SERVICEID);
}
catch(Exception e)
{
//System.out.println("connect timeout exception.server is not open");
//e.printStackTrace();
}
System.out.println("½áÊøÊ±¼äÊÇ£º" + new Date());
}
@Override
public void run() {
// TODO Auto-generated method stub
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost(ip, 8090);
//HttpHost host = new HttpHost("192.168.111.191", 8090);
coreContext.setTargetHost(host);
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
try {
HttpEntity[] requestBodies = {
new ByteArrayEntity(content,ContentType.create("text/plain", Consts.UTF_8))
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
try{
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
catch(Exception e)
{
//System.out.println("connect timeout exception.server is not open");
//e.printStackTrace();
}
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/test.txt");
request.setEntity(requestBodies[i]);
//System.out.println(">> Request URI: " + request.getRequestLine().getUri());
//System.out.println("***********************"+content.getBytes().length);
try {
httpexecutor.preProcess(request, httpproc, coreContext);
} catch (HttpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String cmdString="";
HttpResponse response=null;
try {
response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
HttpEntity he=response.getEntity();
//cmdString = EntityUtils.toString(he);
byte[]cmdByte = EntityUtils.toByteArray(he);
cmdString=new String(cmdByte);
// System.out.println("<< Response: " + response.getStatusLine());
if(response.getStatusLine().getStatusCode()==200){
// oldCmdHandler(cmdString);
new DownCmdHandler().handleCmd(cmdByte,cmdString);
}
else{
System.out.println(ip);
}
//System.out.println("=============="+cmdString);
if (!connStrategy.keepAlive(response, coreContext)) {
conn.close();
} else {
//System.out.println("Connection kept alive...");
}
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
}
}
} finally {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| mit |
indigophp-archive/fuel-core | lib/Fuel/Orm/SortableInterface.php | 523 | <?php
/*
* This file is part of the Indigo Core package.
*
* (c) Indigo Development Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Fuel\Orm;
/**
* Sortable Interface
*
* This interface helps the use of Sort observer
*
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
interface SortableInterface
{
/**
* Returns the maximum sort value
*
* @return integer
*/
public function getSortMax();
}
| mit |
codygman/movie-availability-api | src/api/normalize.go | 355 | package api
import (
"strings"
)
func normalizeKeyword(keyword string) (string) {
// normalizes keyword for comparison
// do your own escaping!
var replacementMap = make(map[string]string)
replacementMap["·"] = "-"
for old, replacement := range replacementMap {
keyword = strings.Replace(keyword, old, replacement, -1)
}
return keyword
}
| mit |
azarkevich/MinskTransSched | MinskTransSched/src/options/GeneralPrefs.java | 4052 | package options;
import javax.microedition.lcdui.*;
import mts.TransSched;
public class GeneralPrefs extends Form implements CommandListener
{
public void commandAction(Command cmd, Displayable d)
{
if(cmd == TransSched.cmdOK)
{
SaveSettings();
TransSched.display.setCurrent(next);
}
else if(cmd == TransSched.cmdCancel)
{
TransSched.display.setCurrent(next);
}
}
TextField tfDefWindowSize = null;
TextField tfDefWindowShift = null;
TextField tfDefWindowSizeStep = null;
TextField tfDefWindowShiftStep = null;
TextField scrollSize = null;
ChoiceGroup fullScreenMode = null;
ChoiceGroup addExitMenuCG = null;
ChoiceGroup startWithStopsList = null;
Displayable next;
public GeneralPrefs(Displayable next)
{
super("Настройки");
this.next = next;
addCommand(TransSched.cmdOK);
addCommand(TransSched.cmdCancel);
setCommandListener(this);
append(new StringItem(null, "Настройки окна расписания (мин.)"));
tfDefWindowSize = new TextField("Размер", "", 6, TextField.DECIMAL);
append(tfDefWindowSize);
tfDefWindowShift = new TextField("Сдвиг", "", 6, TextField.DECIMAL);
append(tfDefWindowShift);
tfDefWindowSizeStep = new TextField("Шаг размера", "", 6, TextField.DECIMAL);
append(tfDefWindowSizeStep);
tfDefWindowShiftStep = new TextField("Шаг сдвига", "", 6, TextField.DECIMAL);
append(tfDefWindowShiftStep);
append(new Spacer(0, 5));
scrollSize = new TextField("Скорость скролирования", "", 3, TextField.DECIMAL);
append(scrollSize);
String fullScreen[] = { "Полноэкрнанное", "Обычное" };
fullScreenMode = new ChoiceGroup("Расписание", Choice.POPUP, fullScreen, null);
append(fullScreenMode);
String startup[] = { "Расписание", "Список остановок" };
startWithStopsList = new ChoiceGroup("Старт", Choice.POPUP, startup, null);
append(startWithStopsList);
String addExitMenu[] = { "Выход", "Помощь", "О программе" };
addExitMenuCG = new ChoiceGroup("Добавлять в меню", Choice.MULTIPLE, addExitMenu, null);
append(addExitMenuCG);
LoadSettings();
}
void LoadSettings()
{
tfDefWindowSize.setString("" + Options.defWindowSize);
tfDefWindowSizeStep.setString("" + Options.defWindowSizeStep);
tfDefWindowShift.setString("" + Options.defWindowShift);
tfDefWindowShiftStep.setString("" + Options.defWindowShiftStep);
scrollSize.setString("" + Options.scrollSize);
fullScreenMode.setSelectedIndex(Options.fullScreen ? 0 : 1, true);
if(Options.showExitCommand)
addExitMenuCG.setSelectedIndex(0, true);
if(Options.showHelpCommand)
addExitMenuCG.setSelectedIndex(1, true);
if(Options.showAboutCommand)
addExitMenuCG.setSelectedIndex(2, true);
startWithStopsList.setSelectedIndex(0, !Options.showStopsListOnStartup);
startWithStopsList.setSelectedIndex(1, Options.showStopsListOnStartup);
}
void SaveSettings()
{
Options.defWindowSize = Short.parseShort(tfDefWindowSize.getString());
Options.defWindowShift = Short.parseShort(tfDefWindowShift.getString());
Options.defWindowSizeStep = Short.parseShort(tfDefWindowSizeStep.getString());
Options.defWindowShiftStep = Short.parseShort(tfDefWindowShiftStep.getString());
Options.scrollSize = Integer.parseInt(scrollSize.getString());
Options.fullScreen = (fullScreenMode.getSelectedIndex() == 0) ? true : false;
Options.showExitCommand = addExitMenuCG.isSelected(0);
Options.showHelpCommand = addExitMenuCG.isSelected(1);
Options.showAboutCommand = addExitMenuCG.isSelected(2);
Options.showStopsListOnStartup = startWithStopsList.isSelected(1);
OptionsStoreManager.SaveSettings();
for (int i = 0; i < TransSched.optionsListeners.length; i++)
{
TransSched.optionsListeners[i].OptionsUpdated();
}
}
}
| mit |
rprichard/electron | chromium_src/chrome/browser/printing/printing_message_filter.cc | 9286 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/printing/printing_message_filter.h"
#include <string>
#include "base/bind.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/printing_ui_web_contents_observer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/common/print_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
using content::BrowserThread;
namespace {
void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
// Currently hardcoded at 1.25. See PrintSettings' constructor.
params->min_shrink = settings.min_shrink();
// Currently hardcoded at 2.0. See PrintSettings' constructor.
params->max_shrink = settings.max_shrink();
// Currently hardcoded at 72dpi. See PrintSettings' constructor.
params->desired_dpi = settings.desired_dpi();
// Always use an invalid cookie.
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->title = settings.title();
params->url = settings.url();
}
} // namespace
PrintingMessageFilter::PrintingMessageFilter(int render_process_id)
: BrowserMessageFilter(PrintMsgStart),
render_process_id_(render_process_id),
queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_);
}
PrintingMessageFilter::~PrintingMessageFilter() {
}
bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilter, message)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)
#endif
IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,
OnGetDefaultPrintSettings)
IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
base::SharedMemoryHandle renderer_handle,
base::SharedMemoryHandle* browser_handle) {
// Duplicate the handle in this process right now so the memory is kept alive
// (even if it is not mapped)
base::SharedMemory shared_buf(renderer_handle, true, PeerHandle());
shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif
content::WebContents* PrintingMessageFilter::GetWebContentsForRenderView(
int render_view_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::RenderViewHost* view = content::RenderViewHost::FromID(
render_process_id_, render_view_id);
return view ? content::WebContents::FromRenderViewHost(view) : NULL;
}
struct PrintingMessageFilter::GetPrintSettingsForRenderViewParams {
printing::PrinterQuery::GetSettingsAskParam ask_user_for_settings;
int expected_page_count;
bool has_selection;
printing::MarginType margin_type;
};
void PrintingMessageFilter::GetPrintSettingsForRenderView(
int render_view_id,
GetPrintSettingsForRenderViewParams params,
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (wc) {
scoped_ptr<PrintingUIWebContentsObserver> wc_observer(
new PrintingUIWebContentsObserver(wc));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&printing::PrinterQuery::GetSettings, printer_query,
params.ask_user_for_settings, base::Passed(&wc_observer),
params.expected_page_count, params.has_selection,
params.margin_type, callback));
} else {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&PrintingMessageFilter::OnGetPrintSettingsFailed, this,
callback, printer_query));
}
}
void PrintingMessageFilter::OnGetPrintSettingsFailed(
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
printer_query->GetSettingsDone(printing::PrintSettings(),
printing::PrintingContext::FAILED);
callback.Run();
}
void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
scoped_refptr<printing::PrinterQuery> printer_query;
if (false) {
// Reply with NULL query.
OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
return;
}
printer_query = queue_->PopPrinterQuery(0);
if (!printer_query)
printer_query = queue_->CreatePrinterQuery();
// Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved.
GetPrintSettingsForRenderViewParams params;
params.ask_user_for_settings = printing::PrinterQuery::DEFAULTS;
params.expected_page_count = 0;
params.has_selection = false;
params.margin_type = printing::DEFAULT_MARGINS;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this,
reply_msg->routing_id(), params,
base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
this, printer_query, reply_msg),
printer_query));
}
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_Print_Params params;
if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);
params.document_cookie = printer_query->cookie();
}
PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If printing was enabled.
if (printer_query.get()) {
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi()) {
queue_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
}
void PrintingMessageFilter::OnScriptedPrint(
const PrintHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query =
queue_->PopPrinterQuery(params.cookie);
if (!printer_query)
printer_query = queue_->CreatePrinterQuery();
GetPrintSettingsForRenderViewParams settings_params;
settings_params.ask_user_for_settings = printing::PrinterQuery::ASK_USER;
settings_params.expected_page_count = params.expected_pages_count;
settings_params.has_selection = params.has_selection;
settings_params.margin_type = params.margin_type;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this,
reply_msg->routing_id(), settings_params,
base::Bind(&PrintingMessageFilter::OnScriptedPrintReply, this,
printer_query, reply_msg),
printer_query));
}
void PrintingMessageFilter::OnScriptedPrintReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK ||
!printer_query->settings().dpi()) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);
params.params.document_cookie = printer_query->cookie();
params.pages =
printing::PageRange::GetPages(printer_query->settings().ranges());
}
PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (params.params.dpi && params.params.document_cookie) {
queue_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
| mit |
jobinesh/jet-examples | node-jet1.2.0-mongo-app/public/js/libs/oj/v1.2.0/min-debug/ojarraydatagriddatasource.js | 28188 | /**
* Copyright (c) 2014, 2015, Oracle and/or its affiliates.
* All rights reserved.
*/
"use strict";
define(["ojs/ojcore", "jquery", "ojs/ojdatasource-common"], function($oj$$57$$) {
$oj$$57$$.$ArrayDataGridDataSource$ = function $$oj$$57$$$$ArrayDataGridDataSource$$($data$$157$$, $options$$327$$) {
if (!($data$$157$$ instanceof Array) && "function" != typeof $data$$157$$ && "function" != typeof $data$$157$$.$subscribe$) {
throw Error("_ERR_DATA_INVALID_TYPE_SUMMARY\n_ERR_DATA_INVALID_TYPE_DETAIL");
}
this.$rowHeaderKey$ = this.$_getRowHeaderFromOptions$($options$$327$$);
null != $options$$327$$ && (this.columns = $options$$327$$.columns, this.$_sortInfo$ = $options$$327$$.initialSort);
$oj$$57$$.$ArrayDataGridDataSource$.$superclass$.constructor.call(this, $data$$157$$);
};
$goog$exportPath_$$("ArrayDataGridDataSource", $oj$$57$$.$ArrayDataGridDataSource$, $oj$$57$$);
$oj$$57$$.$Object$.$createSubclass$($oj$$57$$.$ArrayDataGridDataSource$, $oj$$57$$.$DataGridDataSource$, "oj.ArrayDataGridDataSource");
$oj$$57$$.$ArrayDataGridDataSource$.prototype.Init = function $$oj$$57$$$$ArrayDataGridDataSource$$$Init$() {
null == this.columns && (this.columns = this.$_getColumnsForScaffolding$(this.$getDataArray$()));
this.$_initializeRowKeys$();
"function" == typeof this.data && this.data.subscribe(this.$_subscribe$.bind(this), null, "arrayChange");
$oj$$57$$.$ArrayDataGridDataSource$.$superclass$.Init.call(this);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.Init", {Init:$oj$$57$$.$ArrayDataGridDataSource$.prototype.Init});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getRowHeaderFromOptions$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getRowHeaderFromOptions$$($option$$38_options$$328$$) {
if (null != $option$$38_options$$328$$ && null != $option$$38_options$$328$$.rowHeader) {
if ($option$$38_options$$328$$ = $option$$38_options$$328$$.rowHeader, "object" === typeof $option$$38_options$$328$$) {
if (null != $option$$38_options$$328$$["default"] && "none" == $option$$38_options$$328$$["default"]) {
return;
}
} else {
if (null != $option$$38_options$$328$$) {
return $option$$38_options$$328$$;
}
}
}
return "m_defaultIndex";
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_initializeRowKeys$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_initializeRowKeys$$() {
var $data$$158$$;
$data$$158$$ = this.$getDataArray$();
for (this.$lastKey$ = 0;this.$lastKey$ < $data$$158$$.length;this.$lastKey$ += 1) {
$data$$158$$[this.$lastKey$].ojKey = this.$lastKey$.toString();
}
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getColumnsForScaffolding$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getColumnsForScaffolding$$($data$$159$$) {
var $propertyName$$8$$, $columns$$23$$;
if ("number" !== typeof $data$$159$$.length || 0 === $data$$159$$.length) {
return[];
}
$columns$$23$$ = [];
for ($propertyName$$8$$ in $data$$159$$[0]) {
$data$$159$$[0].hasOwnProperty($propertyName$$8$$) && (void 0 != this.$rowHeaderKey$ && $propertyName$$8$$ == this.$rowHeaderKey$ || $columns$$23$$.push($propertyName$$8$$));
}
return $columns$$23$$;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getCount$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$getCount$$($axis$$38$$) {
return "row" === $axis$$38$$ ? this.$_size$() : "column" === $axis$$38$$ ? this.columns.length : 0;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getCount", {$getCount$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getCount$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getCountPrecision$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$getCountPrecision$$() {
return "exact";
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getCountPrecision", {$getCountPrecision$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getCountPrecision$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getHeaderData$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getHeaderData$$($axis$$40$$, $index$$243$$) {
var $data$$160$$;
if ("row" === $axis$$40$$) {
if (void 0 == this.$rowHeaderKey$) {
return null;
}
if ("m_defaultIndex" == this.$rowHeaderKey$) {
return this.$_getRowKeyByIndex$($index$$243$$);
}
$data$$160$$ = this.$getDataArray$();
return $data$$160$$[$index$$243$$][this.$rowHeaderKey$];
}
if ("column" === $axis$$40$$) {
return this.columns[$index$$243$$];
}
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getHeaderMetadata$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getHeaderMetadata$$($axis$$41$$, $index$$244$$) {
var $key$$156$$;
if ("row" === $axis$$41$$) {
return{key:this.$_getRowKeyByIndex$($index$$244$$)};
}
if ("column" === $axis$$41$$) {
return $key$$156$$ = this.$_getHeaderData$($axis$$41$$, $index$$244$$), null != this.$_sortInfo$ && this.$_sortInfo$.key === $key$$156$$ ? {key:this.$_getHeaderData$($axis$$41$$, $index$$244$$), sortDirection:this.$_sortInfo$.direction} : {key:$key$$156$$};
}
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$fetchHeaders$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$fetchHeaders$$($headerRange$$5$$, $callbacks$$30$$, $callbackObjects$$16$$) {
var $axis$$42_headerSet$$1$$, $start$$51$$, $count$$52_end$$17$$, $data$$161$$;
$axis$$42_headerSet$$1$$ = $headerRange$$5$$.axis;
$start$$51$$ = $headerRange$$5$$.start;
$count$$52_end$$17$$ = $headerRange$$5$$.count;
$start$$51$$ = Math.max(0, $start$$51$$);
"column" === $axis$$42_headerSet$$1$$ ? $count$$52_end$$17$$ = Math.min(this.columns.length, $start$$51$$ + $count$$52_end$$17$$) : ($data$$161$$ = this.$getDataArray$(), $count$$52_end$$17$$ = void 0 === this.$rowHeaderKey$ ? $start$$51$$ : Math.min($data$$161$$.length, $start$$51$$ + $count$$52_end$$17$$));
$axis$$42_headerSet$$1$$ = new $oj$$57$$.$ArrayHeaderSet$($start$$51$$, $count$$52_end$$17$$, $axis$$42_headerSet$$1$$, this);
null != $callbacks$$30$$ && null != $callbacks$$30$$.success && (null == $callbackObjects$$16$$ && ($callbackObjects$$16$$ = {}), $callbacks$$30$$.success.call($callbackObjects$$16$$.success, $axis$$42_headerSet$$1$$, $headerRange$$5$$));
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.fetchHeaders", {$fetchHeaders$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$fetchHeaders$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getCellData$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getCellData$$($row$$40$$, $column$$24$$) {
var $col$$2$$ = this.columns[$column$$24$$];
return this.$getDataArray$()[$row$$40$$][$col$$2$$];
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getCellMetadata$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getCellMetadata$$($row$$41$$, $column$$25$$) {
return{keys:{row:this.$_getRowKeyByIndex$($row$$41$$), column:this.columns[$column$$25$$]}};
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$fetchCells$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$fetchCells$$($cellRanges$$6$$, $callbacks$$31$$, $callbackObjects$$17$$) {
var $cellSet$$1_i$$375$$, $cellRange$$3$$, $rowStart$$5$$, $rowEnd$$2$$, $colStart$$2$$, $colEnd$$1$$;
for ($cellSet$$1_i$$375$$ = 0;$cellSet$$1_i$$375$$ < $cellRanges$$6$$.length;$cellSet$$1_i$$375$$ += 1) {
$cellRange$$3$$ = $cellRanges$$6$$[$cellSet$$1_i$$375$$], "row" === $cellRange$$3$$.axis ? ($rowStart$$5$$ = $cellRange$$3$$.start, $rowEnd$$2$$ = Math.min(this.$_size$(), $rowStart$$5$$ + $cellRange$$3$$.count)) : "column" === $cellRange$$3$$.axis && ($colStart$$2$$ = $cellRange$$3$$.start, $colEnd$$1$$ = Math.min(this.columns.length, $colStart$$2$$ + $cellRange$$3$$.count));
}
void 0 === $rowEnd$$2$$ || void 0 === $colEnd$$1$$ ? null != $callbacks$$31$$ && null != $callbacks$$31$$.error && (null == $callbackObjects$$17$$ && ($callbackObjects$$17$$ = {}), $callbacks$$31$$.error.call($callbackObjects$$17$$.error)) : ($cellSet$$1_i$$375$$ = new $oj$$57$$.$ArrayCellSet$($rowStart$$5$$, $rowEnd$$2$$, $colStart$$2$$, $colEnd$$1$$, this), null != $callbacks$$31$$ && null != $callbacks$$31$$.success && (null == $callbackObjects$$17$$ && ($callbackObjects$$17$$ = {}), $callbacks$$31$$.success.call($callbackObjects$$17$$.success,
$cellSet$$1_i$$375$$, $cellRanges$$6$$)));
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.fetchCells", {$fetchCells$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$fetchCells$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.keys = function $$oj$$57$$$$ArrayDataGridDataSource$$$keys$($indexes$$12$$) {
var $rowIndex$$9$$ = $indexes$$12$$.row, $columnIndex$$5$$ = $indexes$$12$$.column;
return new Promise(function($resolve$$42$$) {
$resolve$$42$$({row:this.$_getRowKeyByIndex$($rowIndex$$9$$), column:this.columns[$columnIndex$$5$$]});
}.bind(this));
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.keys", {keys:$oj$$57$$.$ArrayDataGridDataSource$.prototype.keys});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$indexes$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$indexes$$($keys$$39$$) {
var $rowKey$$36$$ = $keys$$39$$.row, $columnKey$$4$$ = $keys$$39$$.column;
return new Promise(function($resolve$$43$$) {
$resolve$$43$$({row:this.$_getRowIndexByKey$($rowKey$$36$$), column:this.columns.indexOf($columnKey$$4$$)});
}.bind(this));
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.indexes", {$indexes$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$indexes$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.sort = function $$oj$$57$$$$ArrayDataGridDataSource$$$sort$($criteria$$3_direction$$11$$, $callbacks$$32$$, $callbackObjects$$18$$) {
var $sortArray$$ = [], $newColumns$$ = [], $axis$$43_i$$376$$, $headerIndex$$1_headerKey$$;
null != $callbacks$$32$$ && null == $callbackObjects$$18$$ && ($callbackObjects$$18$$ = {});
if (null == $criteria$$3_direction$$11$$) {
this.$_resetSortOrder$($callbacks$$32$$, $callbackObjects$$18$$);
} else {
if ($axis$$43_i$$376$$ = $criteria$$3_direction$$11$$.axis, $headerIndex$$1_headerKey$$ = $criteria$$3_direction$$11$$.key, $criteria$$3_direction$$11$$ = $criteria$$3_direction$$11$$.direction, "column" === $axis$$43_i$$376$$) {
void 0 == this.$origData$ && (this.$_origSortInfo$ = this.$_sortInfo$, this.$origData$ = this.data.slice()), this.$_sortInfo$ = {key:$headerIndex$$1_headerKey$$, direction:$criteria$$3_direction$$11$$}, this.$getDataArray$().sort(this.$_naturalSort$($criteria$$3_direction$$11$$, $headerIndex$$1_headerKey$$)), null != $callbacks$$32$$ && null != $callbacks$$32$$.success && $callbacks$$32$$.success.call($callbackObjects$$18$$.success);
} else {
if ("row" === $axis$$43_i$$376$$) {
$headerIndex$$1_headerKey$$ = this.$_getRowIndexByKey$($headerIndex$$1_headerKey$$);
for ($axis$$43_i$$376$$ = 0;$axis$$43_i$$376$$ < this.columns.length;$axis$$43_i$$376$$ += 1) {
$sortArray$$[$axis$$43_i$$376$$] = this.$getDataArray$()[$headerIndex$$1_headerKey$$][this.columns[$axis$$43_i$$376$$]];
}
$sortArray$$.sort(this.$_naturalSort$($criteria$$3_direction$$11$$));
for ($axis$$43_i$$376$$ = 0;$axis$$43_i$$376$$ < this.columns.length;$axis$$43_i$$376$$ += 1) {
$newColumns$$[$axis$$43_i$$376$$] = this.columns[$sortArray$$.indexOf(this.$getDataArray$()[$headerIndex$$1_headerKey$$][this.columns[$axis$$43_i$$376$$]])];
}
this.$origColumns$ = this.columns;
this.columns = $newColumns$$;
null != $callbacks$$32$$ && null != $callbacks$$32$$.success && $callbacks$$32$$.success.call($callbackObjects$$18$$.success);
} else {
null !== $callbacks$$32$$ && null != $callbacks$$32$$.error && $callbacks$$32$$.error.call($callbackObjects$$18$$.error, "Invalid axis value");
}
}
}
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.sort", {sort:$oj$$57$$.$ArrayDataGridDataSource$.prototype.sort});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_resetSortOrder$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_resetSortOrder$$($callbacks$$33$$, $callbackObjects$$19$$) {
null != this.$origData$ && (this.data = this.$origData$, this.$_sortInfo$ = this.$_origSortInfo$);
null != this.$origColumns$ && (this.columns = this.$origColumns$);
null != $callbacks$$33$$ && null != $callbacks$$33$$.success && $callbacks$$33$$.success.call($callbackObjects$$19$$.success);
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.getCapability = function $$oj$$57$$$$ArrayDataGridDataSource$$$getCapability$($feature$$8$$) {
return "sort" === $feature$$8$$ ? "column" : "move" === $feature$$8$$ ? "row" : null;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getCapability", {getCapability:$oj$$57$$.$ArrayDataGridDataSource$.prototype.getCapability});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_naturalSort$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_naturalSort$$($direction$$12$$, $key$$157$$) {
if ("ascending" === $direction$$12$$) {
return function($a$$113$$, $b$$71$$) {
var $as$$2$$, $bs$$2$$;
void 0 != $key$$157$$ && ($a$$113$$ instanceof Array ? ($a$$113$$ = $a$$113$$[parseInt($key$$157$$, 10)], $b$$71$$ = $b$$71$$[parseInt($key$$157$$, 10)]) : ($a$$113$$ = $a$$113$$[$key$$157$$], $b$$71$$ = $b$$71$$[$key$$157$$]));
$as$$2$$ = isNaN($a$$113$$);
$bs$$2$$ = isNaN($b$$71$$);
$a$$113$$ instanceof Date && ($a$$113$$ = $a$$113$$.toISOString(), $as$$2$$ = !0);
$b$$71$$ instanceof Date && ($b$$71$$ = $b$$71$$.toISOString(), $bs$$2$$ = !0);
return $as$$2$$ && $bs$$2$$ ? $a$$113$$ < $b$$71$$ ? -1 : $a$$113$$ === $b$$71$$ ? 0 : 1 : $as$$2$$ ? 1 : $bs$$2$$ ? -1 : $a$$113$$ - $b$$71$$;
};
}
if ("descending" === $direction$$12$$) {
return function($a$$114$$, $b$$72$$) {
var $as$$3$$, $bs$$3$$;
void 0 != $key$$157$$ && ($a$$114$$ instanceof Array ? ($a$$114$$ = $a$$114$$[parseInt($key$$157$$, 10)], $b$$72$$ = $b$$72$$[parseInt($key$$157$$, 10)]) : ($a$$114$$ = $a$$114$$[$key$$157$$], $b$$72$$ = $b$$72$$[$key$$157$$]));
$as$$3$$ = isNaN($a$$114$$);
$bs$$3$$ = isNaN($b$$72$$);
$a$$114$$ instanceof Date && ($a$$114$$ = $a$$114$$.toISOString(), $as$$3$$ = !0);
$b$$72$$ instanceof Date && ($b$$72$$ = $b$$72$$.toISOString(), $bs$$3$$ = !0);
return $as$$3$$ && $bs$$3$$ ? $a$$114$$ > $b$$72$$ ? -1 : $a$$114$$ === $b$$72$$ ? 0 : 1 : $as$$3$$ ? -1 : $bs$$3$$ ? 1 : $b$$72$$ - $a$$114$$;
};
}
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.move = function $$oj$$57$$$$ArrayDataGridDataSource$$$move$($moveKey$$1$$, $atKey$$1$$) {
var $event$$526_moveKeyIndex$$, $moveData$$, $atKeyIndex$$;
$event$$526_moveKeyIndex$$ = this.$_getRowIndexByKey$($moveKey$$1$$);
$moveData$$ = this.data.splice($event$$526_moveKeyIndex$$, 1)[0];
this.data instanceof Array && ($event$$526_moveKeyIndex$$ = this.$_getModelEvent$("delete", $moveKey$$1$$, null, $event$$526_moveKeyIndex$$, -1, !0), this.handleEvent("change", $event$$526_moveKeyIndex$$));
null === $atKey$$1$$ ? this.data.push($moveData$$) : ($atKeyIndex$$ = this.$_getRowIndexByKey$($atKey$$1$$), this.data.splice($atKeyIndex$$, 0, $moveData$$));
this.data instanceof Array && ($event$$526_moveKeyIndex$$ = this.$_getModelEvent$("insert", $moveKey$$1$$, null, $atKeyIndex$$, -1), this.handleEvent("change", $event$$526_moveKeyIndex$$));
null != this.$origData$ && (this.$origData$ = this.data.slice());
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.move", {move:$oj$$57$$.$ArrayDataGridDataSource$.prototype.move});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$moveOK$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$moveOK$$() {
return "valid";
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.moveOK", {$moveOK$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$moveOK$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getDataArray$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$getDataArray$$() {
return "function" === typeof this.data ? this.data() : this.data;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getRowIndexByKey$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getRowIndexByKey$$($key$$158$$) {
var $i$$377$$, $data$$163$$ = this.$getDataArray$();
for ($i$$377$$ = 0;$i$$377$$ < $data$$163$$.length;$i$$377$$++) {
if ($data$$163$$[$i$$377$$].ojKey === $key$$158$$) {
return $i$$377$$;
}
}
return-1;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getRowKeyByIndex$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getRowKeyByIndex$$($index$$245$$) {
var $data$$164$$ = this.$getDataArray$();
return $data$$164$$[$index$$245$$] ? $data$$164$$[$index$$245$$].ojKey : null;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_getModelEvent$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_getModelEvent$$($operation$$5$$, $rowKey$$37$$, $columnKey$$5$$, $rowIndex$$10$$, $columnIndex$$6$$, $silent$$26$$) {
var $event$$527$$ = {source:this};
$event$$527$$.operation = $operation$$5$$;
$event$$527$$.keys = {row:$rowKey$$37$$, column:$columnKey$$5$$};
$event$$527$$.indexes = {row:$rowIndex$$10$$, column:$columnIndex$$6$$};
$event$$527$$.silent = $silent$$26$$;
return $event$$527$$;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_subscribe$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_subscribe$$($changes$$6$$) {
var $i$$378$$, $move_rowData$$4_rowKey$$38$$, $change$$5_event$$528_rowIndex$$11$$, $added$$1$$ = !1;
$move_rowData$$4_rowKey$$38$$ = !1;
var $keys$$40$$ = [], $indexes$$13$$ = [];
for ($i$$378$$ = 0;$i$$378$$ < $changes$$6$$.length;$i$$378$$++) {
$change$$5_event$$528_rowIndex$$11$$ = $changes$$6$$[$i$$378$$];
if (void 0 !== $change$$5_event$$528_rowIndex$$11$$.moved) {
$move_rowData$$4_rowKey$$38$$ = !0;
$change$$5_event$$528_rowIndex$$11$$ = this.$_getModelEvent$("refresh", null, null);
this.handleEvent("change", $change$$5_event$$528_rowIndex$$11$$);
break;
}
"added" === $change$$5_event$$528_rowIndex$$11$$.status && ($added$$1$$ = !0);
}
if (!$move_rowData$$4_rowKey$$38$$) {
for ($i$$378$$ = 0;$i$$378$$ < $changes$$6$$.length;$i$$378$$++) {
$change$$5_event$$528_rowIndex$$11$$ = $changes$$6$$[$i$$378$$], "deleted" === $change$$5_event$$528_rowIndex$$11$$.status && ($move_rowData$$4_rowKey$$38$$ = $change$$5_event$$528_rowIndex$$11$$.value, $change$$5_event$$528_rowIndex$$11$$ = $change$$5_event$$528_rowIndex$$11$$.index, $move_rowData$$4_rowKey$$38$$ = $move_rowData$$4_rowKey$$38$$.ojKey, $keys$$40$$.push({row:$move_rowData$$4_rowKey$$38$$, column:-1}), $indexes$$13$$.push({row:$change$$5_event$$528_rowIndex$$11$$, column:-1}))
;
}
0 < $keys$$40$$.length && ($change$$5_event$$528_rowIndex$$11$$ = {source:this, operation:"delete", keys:$keys$$40$$, indexes:$indexes$$13$$, silent:$added$$1$$}, this.handleEvent("change", $change$$5_event$$528_rowIndex$$11$$));
for ($i$$378$$ = 0;$i$$378$$ < $changes$$6$$.length;$i$$378$$++) {
$change$$5_event$$528_rowIndex$$11$$ = $changes$$6$$[$i$$378$$], "added" === $change$$5_event$$528_rowIndex$$11$$.status && ($move_rowData$$4_rowKey$$38$$ = $change$$5_event$$528_rowIndex$$11$$.value, $change$$5_event$$528_rowIndex$$11$$ = $change$$5_event$$528_rowIndex$$11$$.index, null == $move_rowData$$4_rowKey$$38$$.ojKey && ($move_rowData$$4_rowKey$$38$$.ojKey = this.$lastKey$.toString(), this.$lastKey$++), $move_rowData$$4_rowKey$$38$$ = $move_rowData$$4_rowKey$$38$$.ojKey, $change$$5_event$$528_rowIndex$$11$$ =
this.$_getModelEvent$("insert", $move_rowData$$4_rowKey$$38$$, null, $change$$5_event$$528_rowIndex$$11$$, -1), this.handleEvent("change", $change$$5_event$$528_rowIndex$$11$$));
}
}
null != this.$origData$ && (this.$origData$ = this.data.slice());
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$_size$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$_size$$() {
return this.$getDataArray$().length;
};
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getRowHeaderKey$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$getRowHeaderKey$$() {
return this.$rowHeaderKey$;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getRowHeaderKey", {$getRowHeaderKey$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getRowHeaderKey$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getColumns$ = function $$oj$$57$$$$ArrayDataGridDataSource$$$$getColumns$$() {
return this.columns;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getColumns", {$getColumns$:$oj$$57$$.$ArrayDataGridDataSource$.prototype.$getColumns$});
$oj$$57$$.$ArrayDataGridDataSource$.prototype.getData = function $$oj$$57$$$$ArrayDataGridDataSource$$$getData$() {
return this.data;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayDataGridDataSource.prototype.getData", {getData:$oj$$57$$.$ArrayDataGridDataSource$.prototype.getData});
$oj$$57$$.$ArrayHeaderSet$ = function $$oj$$57$$$$ArrayHeaderSet$$($start$$52$$, $end$$18$$, $axis$$44$$, $callback$$120$$) {
this.$m_start$ = $start$$52$$;
this.$m_end$ = $end$$18$$;
this.$m_axis$ = $axis$$44$$;
this.$m_callback$ = $callback$$120$$;
};
$goog$exportPath_$$("ArrayHeaderSet", $oj$$57$$.$ArrayHeaderSet$, $oj$$57$$);
$oj$$57$$.$ArrayHeaderSet$.prototype.getData = function $$oj$$57$$$$ArrayHeaderSet$$$getData$($index$$246$$, $level$$35$$) {
if (null == this.$m_callback$) {
return null;
}
$oj$$57$$.$Assert$.assert($index$$246$$ <= this.$m_end$ && $index$$246$$ >= this.$m_start$, "index out of bounds");
$oj$$57$$.$Assert$.assert(null == $level$$35$$ || 0 == $level$$35$$, "level out of bounds");
return this.$m_callback$.$_getHeaderData$(this.$m_axis$, $index$$246$$);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getData", {getData:$oj$$57$$.$ArrayHeaderSet$.prototype.getData});
$oj$$57$$.$ArrayHeaderSet$.prototype.getMetadata = function $$oj$$57$$$$ArrayHeaderSet$$$getMetadata$($index$$247$$, $level$$36$$) {
if (null == this.$m_callback$) {
return null;
}
$oj$$57$$.$Assert$.assert($index$$247$$ <= this.$m_end$ && $index$$247$$ >= this.$m_start$, "index out of bounds");
$oj$$57$$.$Assert$.assert(null == $level$$36$$ || 0 == $level$$36$$, "level out of bounds");
return this.$m_callback$.$_getHeaderMetadata$(this.$m_axis$, $index$$247$$);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getMetadata", {getMetadata:$oj$$57$$.$ArrayHeaderSet$.prototype.getMetadata});
$oj$$57$$.$ArrayHeaderSet$.prototype.$getLevelCount$ = function $$oj$$57$$$$ArrayHeaderSet$$$$getLevelCount$$() {
return 0 < this.$getCount$() ? 1 : 0;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getLevelCount", {$getLevelCount$:$oj$$57$$.$ArrayHeaderSet$.prototype.$getLevelCount$});
$oj$$57$$.$ArrayHeaderSet$.prototype.$getExtent$ = function $$oj$$57$$$$ArrayHeaderSet$$$$getExtent$$($index$$248$$, $level$$37$$) {
$oj$$57$$.$Assert$.assert($index$$248$$ <= this.$m_end$ && $index$$248$$ >= this.$m_start$, "index out of bounds");
$oj$$57$$.$Assert$.assert(null == $level$$37$$ || 0 == $level$$37$$, "level out of bounds");
return{extent:1, more:{before:!1, after:!1}};
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getExtent", {$getExtent$:$oj$$57$$.$ArrayHeaderSet$.prototype.$getExtent$});
$oj$$57$$.$ArrayHeaderSet$.prototype.$getDepth$ = function $$oj$$57$$$$ArrayHeaderSet$$$$getDepth$$($index$$249$$, $level$$38$$) {
$oj$$57$$.$Assert$.assert($index$$249$$ <= this.$m_end$ && $index$$249$$ >= this.$m_start$, "index out of bounds");
$oj$$57$$.$Assert$.assert(null == $level$$38$$ || 0 == $level$$38$$, "level out of bounds");
return 1;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getDepth", {$getDepth$:$oj$$57$$.$ArrayHeaderSet$.prototype.$getDepth$});
$oj$$57$$.$ArrayHeaderSet$.prototype.$getCount$ = function $$oj$$57$$$$ArrayHeaderSet$$$$getCount$$() {
return null == this.$m_callback$ ? 0 : Math.max(0, this.$m_end$ - this.$m_start$);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getCount", {$getCount$:$oj$$57$$.$ArrayHeaderSet$.prototype.$getCount$});
$oj$$57$$.$ArrayHeaderSet$.prototype.$getStart$ = function $$oj$$57$$$$ArrayHeaderSet$$$$getStart$$() {
return this.$m_start$;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayHeaderSet.prototype.getStart", {$getStart$:$oj$$57$$.$ArrayHeaderSet$.prototype.$getStart$});
$oj$$57$$.$ArrayCellSet$ = function $$oj$$57$$$$ArrayCellSet$$($startRow$$2$$, $endRow$$1$$, $startColumn$$2$$, $endColumn$$1$$, $callback$$121$$) {
this.$m_startRow$ = $startRow$$2$$;
this.$m_endRow$ = $endRow$$1$$;
this.$m_startColumn$ = $startColumn$$2$$;
this.$m_endColumn$ = $endColumn$$1$$;
this.$m_callback$ = $callback$$121$$;
};
$goog$exportPath_$$("ArrayCellSet", $oj$$57$$.$ArrayCellSet$, $oj$$57$$);
$oj$$57$$.$ArrayCellSet$.prototype.getData = function $$oj$$57$$$$ArrayCellSet$$$getData$($indexes$$14$$) {
return this.$m_callback$.$_getCellData$($indexes$$14$$.row, $indexes$$14$$.column);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getData", {getData:$oj$$57$$.$ArrayCellSet$.prototype.getData});
$oj$$57$$.$ArrayCellSet$.prototype.getMetadata = function $$oj$$57$$$$ArrayCellSet$$$getMetadata$($indexes$$15$$) {
return this.$m_callback$.$_getCellMetadata$($indexes$$15$$.row, $indexes$$15$$.column);
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getMetadata", {getMetadata:$oj$$57$$.$ArrayCellSet$.prototype.getMetadata});
$oj$$57$$.$ArrayCellSet$.prototype.$getStart$ = function $$oj$$57$$$$ArrayCellSet$$$$getStart$$($axis$$45$$) {
return "row" == $axis$$45$$ ? this.$m_startRow$ : "column" == $axis$$45$$ ? this.$m_startColumn$ : -1;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getStart", {$getStart$:$oj$$57$$.$ArrayCellSet$.prototype.$getStart$});
$oj$$57$$.$ArrayCellSet$.prototype.$getCount$ = function $$oj$$57$$$$ArrayCellSet$$$$getCount$$($axis$$46$$) {
return "row" === $axis$$46$$ ? Math.max(0, this.$m_endRow$ - this.$m_startRow$) : "column" === $axis$$46$$ ? Math.max(0, this.$m_endColumn$ - this.$m_startColumn$) : 0;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getCount", {$getCount$:$oj$$57$$.$ArrayCellSet$.prototype.$getCount$});
$oj$$57$$.$ArrayCellSet$.prototype.getStartRow = function $$oj$$57$$$$ArrayCellSet$$$getStartRow$() {
return this.$m_startRow$;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getStartRow", {getStartRow:$oj$$57$$.$ArrayCellSet$.prototype.getStartRow});
$oj$$57$$.$ArrayCellSet$.prototype.getStartColumn = function $$oj$$57$$$$ArrayCellSet$$$getStartColumn$() {
return this.$m_startColumn$;
};
$oj$$57$$.$Object$.$exportPrototypeSymbol$("ArrayCellSet.prototype.getStartColumn", {getStartColumn:$oj$$57$$.$ArrayCellSet$.prototype.getStartColumn});
});
| mit |
zelda/mongodb-for-fhir-resource | app/controllers/enrollmentresponse.js | 5768 | // Copyright (c) 2011+, HL7, Inc & The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of HL7 nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
var mongoose = require('mongoose');
var _ = require('underscore');
var fs = require('fs');
var eco = require('eco');
var async = require('async');
var EnrollmentResponse = mongoose.model('EnrollmentResponse');
var ResourceHistory = mongoose.model('ResourceHistory');
var ResponseFormatHelper = require(__dirname + '/../../lib/response_format_helper');
exports.load = function(req, res, id, vid, next) {
if (req.resourceHistory) {
if(vid !== null){
req.resourceHistory.getVersion(vid, function(err, enrollmentresponse) {
req.enrollmentresponse = enrollmentresponse;
next(enrollmentresponse);
});
} else {
req.resourceHistory.findLatest(function(err, enrollmentresponse) {
req.enrollmentresponse = enrollmentresponse;
next(enrollmentresponse);
});
}
} else {
ResourceHistory.findOne(id, function(rhErr, resourceHistory) {
if (rhErr) {
next(rhErr);
}
if(resourceHistory !== null) {
req.resourceHistory = resourceHistory;
req.resourceHistory.findLatest(function(err, enrollmentresponse) {
req.enrollmentresponse = enrollmentresponse;
next(enrollmentresponse);
});
}
});
}
};
exports.show = function(req, res) {
var enrollmentresponse = req.enrollmentresponse;
var json = JSON.stringify(enrollmentresponse);
res.send(json);
};
exports.create = function(req, res) {
var enrollmentresponse = new EnrollmentResponse(req.body);
enrollmentresponse.save(function(err, savedEnrollmentResponse) {
if(err) {
res.send(500);
} else {
var resourceHistory = new ResourceHistory({resourceType: 'EnrollmentResponse'});
resourceHistory.addVersion(savedEnrollmentResponse.id);
resourceHistory.save(function(rhErr, savedResourceHistory){
if (rhErr) {
res.send(500);
} else {
res.set('Location', ("http://localhost:3000/enrollmentresponse/@" + resourceHistory.id));
res.send(201);
}
});
}
});
};
exports.update = function(req, res) {
var enrollmentresponse = req.enrollmentresponse;
enrollmentresponse = _.extend(enrollmentresponse, req.body);
enrollmentresponse.save(function(err, savedenrollmentresponse) {
if(err) {
res.send(500);
} else {
var resourceHistory = req.resourceHistory;
resourceHistory.addVersion(savedenrollmentresponse);
resourceHistory.save(function(rhErr, savedResourceHistory) {
if (rhErr) {
res.send(500);
} else {
res.send(200);
}
});
}
});
};
exports.destroy = function(req, res) {
var enrollmentresponse = req.enrollmentresponse;
enrollmentresponse.remove(function (err) {
if(err) {
res.send(500);
} else {
res.send(204);
}
});
};
exports.list = function(req, res) {
var content = {
title: "Search results for resource type EnrollmentResponse",
id: "http://localhost:3000/enrollmentresponse",
totalResults: 0,
link: {
href: "http://localhost:3000/enrollmentresponse",
rel: "self"
},
updated: new Date(Date.now()),
entry: []
};
ResourceHistory.find({resourceType:"EnrollmentResponse"}, function (rhErr, histories) {
if (rhErr) {
return next(rhErr);
}
var counter = 0;
async.forEach(histories, function(history, callback) {
counter++;
content.totalResults = counter;
history.findLatest( function(err, enrollmentresponse) {
var entrywrapper = {
title: "EnrollmentResponse " + history.vistaId + " Version " + history.versionCount(),
id: "http://localhost:3000/enrollmentresponse/@" + history.vistaId,
link: {
href: "http://localhost:3000/enrollmentresponse/@" + history.vistaId + "/history/@" + history.versionCount(),
rel: "self"
},
updated: history.lastUpdatedAt(),
published: new Date(Date.now()),
content: enrollmentresponse
};
content.entry.push(entrywrapper);
callback();
});
}, function(err) {
res.send(JSON.stringify(content));
});
});
}; | mit |
squeedee/RobotlegsUpDownPlugin | src/org/robotlegs/plugins/upDown/DownAction.java | 682 | package org.robotlegs.plugins.upDown;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.robotlegs.plugins.upDown.strategy.IUpDownStrategy;
/**
* Created by IntelliJ IDEA. User: rasheed Date: 30/03/2010 Time: 6:36:40 AM To change this template use File | Settings
* | File Templates.
*/
public class DownAction extends AbstractUpDownAction {
@Override
public void update(AnActionEvent e) {
super.update(e);
IUpDownStrategy strategy = upDownComponent().getDownStrategy(e);
strategy.update(e);
}
@Override
public void actionPerformed(AnActionEvent e) {
IUpDownStrategy strategy = upDownComponent().getDownStrategy(e);
strategy.perform(e);
}
}
| mit |
Noders/noders.github.io.dev | test/spec/controllers/header.js | 513 | 'use strict';
describe('Controller: HeaderCtrl', function () {
// load the controller's module
beforeEach(module('nodersApp'));
var HeaderCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
HeaderCtrl = $controller('HeaderCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
| mit |
Petrakisos/TelerikAcademy | CSharpPart1/06.Loops/01.NumbersFrom1ToN/NumberFrom1ToN.cs | 219 | using System;
class NumberFrom1ToN
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
Console.Write(i + " ");
}
}
}
| mit |
stackia/DNSAgent | DNSAgent/Logger.cs | 1558 | using System;
namespace DNSAgent
{
internal class Logger
{
private static readonly object OutputLock = new object();
private static string _title;
public static string Title
{
get { return _title; }
set
{
_title = value;
if (Environment.UserInteractive)
Console.Title = value;
}
}
public static void Error(string format, params object[] arg)
{
WriteLine(ConsoleColor.Red, format, arg);
}
public static void Warning(string format, params object[] arg)
{
WriteLine(ConsoleColor.Yellow, format, arg);
}
public static void Info(string format, params object[] arg)
{
WriteLine(ConsoleColor.Gray, format, arg);
}
public static void Debug(string format, params object[] arg)
{
WriteLine(ConsoleColor.Magenta, format, arg);
}
public static void Trace(string format, params object[] arg)
{
WriteLine(ConsoleColor.White, format, arg);
}
private static void WriteLine(ConsoleColor textColor, string format, params object[] arg)
{
if (!Environment.UserInteractive)
return;
lock (OutputLock)
{
Console.ForegroundColor = textColor;
Console.WriteLine(format, arg);
Console.ResetColor();
}
}
}
} | mit |
essian/rps10000 | spec/rps10000_spec.rb | 198 | require 'spec_helper'
describe Rps10000 do
it 'has a version number' do
expect(Rps10000::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| mit |
samwhelp/demo-libchewing | python/implement/module/demo-add.py | 233 | #!/usr/bin/env python3
from chewing import userphrase
def main():
phrase = '內稽'
bopomofo = 'ㄋㄟˋ ㄐㄧ'
rtn = userphrase.add(phrase, bopomofo)
print('add (', rtn, ') userphrase')
if __name__ == '__main__':
main()
| mit |
Infragistics/zero-blocks | projects/igniteui-angular/src/lib/select/select-item.component.ts | 1914 | import { IgxDropDownItemComponent } from './../drop-down/drop-down-item.component';
import { Component, DoCheck, Input } from '@angular/core';
@Component({
selector: 'igx-select-item',
template: '<span class="igx-drop-down__inner"><ng-content></ng-content></span>'
})
export class IgxSelectItemComponent extends IgxDropDownItemComponent implements DoCheck {
/** @hidden @internal */
public isHeader: boolean;
private _text: any;
/**
* An @Input property that gets/sets the item's text to be displayed in the select component's input when the item is selected.
*
* ```typescript
* //get
* let mySelectedItem = this.dropDown.selectedItem;
* let selectedItemText = mySelectedItem.text;
* ```
*
* ```html
* // set
* <igx-select-item [text]="'London'"></igx-select-item>
* ```
*/
@Input()
public get text(): string {
return this._text;
}
public set text(text: string) {
this._text = text;
}
/** @hidden @internal */
public get itemText() {
if (this._text !== undefined) {
return this._text;
}
// If text @Input is undefined, try extract a meaningful item text out of the item template
return this.elementRef.nativeElement.textContent.trim();
}
/**
* Sets/Gets if the item is the currently selected one in the select
*
* ```typescript
* let mySelectedItem = this.select.selectedItem;
* let isMyItemSelected = mySelectedItem.selected; // true
* ```
*/
public get selected() {
return !this.isHeader && !this.disabled && this.selection.is_item_selected(this.dropDown.id, this);
}
public set selected(value: any) {
if (value && !this.isHeader && !this.disabled) {
this.dropDown.selectItem(this);
}
}
public ngDoCheck(): void {
}
}
| mit |
Surnet/swagger-jsdoc | examples/app/app.spec.js | 616 | const request = require('supertest');
const { app, server } = require('./app');
const swaggerSpec = require('./swagger-spec.json');
describe('Example application written in swagger specification (v2)', () => {
it('should be healthy', async () => {
const response = await request(app).get('/');
expect(response.status).toBe(200);
});
it('should return the expected specification', async () => {
const response = await request(app).get('/api-docs.json');
expect(response.status).toBe(200);
expect(response.body).toEqual(swaggerSpec);
});
afterAll(() => {
server.close();
});
});
| mit |
Brockhurst/connect | src/app/pages/partners-page/partners-page.module.ts | 920 | import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { PartnersPageComponent } from './partners-page.component';
import { CarouselModule } from 'ngx-bootstrap';
import { PerfectScrollbarModule } from 'angular2-perfect-scrollbar';
import { PerfectScrollbarConfigInterface } from 'angular2-perfect-scrollbar';
import { ComponentsModule } from 'app/shared/components';
import { PartnersPageRoutingModule } from './partners-page-routing.module';
const PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
suppressScrollX: true
};
@NgModule({
imports: [
PerfectScrollbarModule.forRoot(PERFECT_SCROLLBAR_CONFIG),
CommonModule,
PartnersPageRoutingModule,
ComponentsModule,
CarouselModule,
FormsModule
],
declarations: [
PartnersPageComponent
]
})
export class PartnersPageModule {
}
| mit |
glenngillen/dotfiles | .vscode/extensions/hashicorp.terraform-2.11.0/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js | 329 | "use strict";
/**
* Exception details of the exception in a chain.
*/
var ExceptionDetails = (function () {
function ExceptionDetails() {
this.hasFullStack = true;
this.parsedStack = [];
}
return ExceptionDetails;
}());
module.exports = ExceptionDetails;
//# sourceMappingURL=ExceptionDetails.js.map | mit |
prasetyaningyudi/serattamu | application/controllers/Meeting.php | 18811 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Meeting extends CI_Controller {
private $data;
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
$this->load->database();
$this->load->model('menu_model'); //can replace with cookies or session
$this->data['menu'] = $this->menu_model->get_menu();
$this->data['sub_menu'] = $this->menu_model->get_sub_menu();
$this->data['title'] = 'Meeting';
ini_set('date.timezone', 'Asia/Jakarta');
}
public function index(){
//load user list
$tables = array('MEETING', 'MEETING_ROOM', 'EMPLOYEES');
$this->db->select('MEETING.ID');
$this->db->select('MEETING_TIME');
$this->db->select('DURATION');
$this->db->select('AGENDA');
$this->db->select('MEETING_ROOM_ID');
$this->db->select('PIC_ID');
$this->db->select('ROOM_NAME');
$this->db->select('EMPLOYEE_NAME');
$this->db->select('MEETING_STATUS');
$this->db->from($tables);
$this->db->where('MEETING_STATUS != ', '9');
$this->db->where('MEETING.PIC_ID=EMPLOYEES.ID');
$this->db->where('MEETING.MEETING_ROOM_ID=MEETING_ROOM.ID');
$this->db->order_by('MEETING_TIME', 'DESC');
$this->db->order_by('ROOM_NAME', 'ASC');
$query = $this->db->get();
$this->data['record'] = $query->result();
$this->data['subtitle'] = 'View';
$this->data['data_table'] = 'yes';
$this->data['role_access'] = array('1', '3');
//view
$this->load->view('section_header', $this->data);
$this->load->view('section_navbar');
$this->load->view('section_sidebar');
$this->load->view('section_breadcurm');
$this->load->view('section_content_title');
$this->load->view('meeting_index');
$this->load->view('section_footer');
}
public function participant($id= null){
if($id == null){
redirect('authentication/no_permission');
}else{
$this->db->select('ID');
$this->db->from('MEETING');
$this->db->where('MEETING.ID', $id);
$query = $this->db->get();
$this->data['record10'] = $query->result();
if($query->num_rows() == null){
redirect('meeting');
}else{
if(isset($_POST['submit'])){
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->where('EMPLOYEE_STATUS', '1');
if($_POST['pid'] == ''){
$this->db->where('EMPLOYEE_NAME', $_POST['employee']);
}else{
$this->db->where('ID', $_POST['pid']);
}
$this->db->limit(1);
$query = $this->db->get();
$this->data['record'] = $query->result();
if($query->num_rows()!=1){
$this->data['warning'] = array(
'text' => 'Ops, Employee not found, Try a new one.',
);
}else{
foreach($this->data['record'] as $item){
$employee_id = $item->ID;
}
$this->db->select('ID');
$this->db->select('EMPLOYEES_ID');
$this->db->from('MEETING_PARTICIPANTS');
$this->db->where('PARTICIPANT_STATUS !=', '9');
$this->db->where('EMPLOYEES_ID', $employee_id);
$this->db->where('MEETING_ID', $_POST['mid']);
$query = $this->db->get();
$this->data['record1'] = $query->result();
if($query->num_rows()==1){
$this->data['warning'] = array(
'text' => 'Ops, Employee has been a participant, Try a new one.',
);
}else{
//insert ke database
$this->data['saveddata'] = array(
'MEETING_ID' => $_POST['mid'],
'EMPLOYEES_ID' => $employee_id,
'USER_ID' => $_POST['user']
);
$this->db->insert('MEETING_PARTICIPANTS', $this->data['saveddata']);
redirect('meeting/participant/'.$_POST['mid']);
}
}
}else if(isset($_POST['submit_guest'])){
$this->db->select('ID');
$this->db->select('GUEST_NAME');
$this->db->from('GUEST');
$this->db->where('GUEST_STATUS', '1');
if($_POST['pid'] == ''){
$this->db->where('GUEST_NAME', $_POST['guest']);
}else{
$this->db->where('ID', $_POST['pid']);
}
$this->db->limit(1);
$query = $this->db->get();
$this->data['record'] = $query->result();
if($query->num_rows()!=1){
$this->data['warning1'] = array(
'text1' => 'Ops, Guest not found, Try a new one.',
);
}else{
foreach($this->data['record'] as $item){
$guest_id = $item->ID;
}
$this->db->select('ID');
$this->db->select('GUEST_ID');
$this->db->from('MEETING_PARTICIPANTS');
$this->db->where('PARTICIPANT_STATUS !=', '9');
$this->db->where('GUEST_ID', $guest_id);
$query = $this->db->get();
$this->data['record1'] = $query->result();
if($query->num_rows()==1){
$this->data['warning1'] = array(
'text1' => 'Ops, Guest has been a participant, Try a new one.',
);
}else{
//insert ke database
$this->data['saveddata'] = array(
'MEETING_ID' => $_POST['mid'],
'GUEST_ID' => $guest_id,
'USER_ID' => $_POST['user']
);
$this->db->insert('MEETING_PARTICIPANTS', $this->data['saveddata']);
redirect('meeting/participant/'.$_POST['mid']);
}
}
}
$this->db->select('MEETING_PARTICIPANTS.ID');
$this->db->select('PARTICIPANT_STATUS');
$this->db->select('MEETING_ID');
$this->db->select('AGENDA');
$this->db->select('GUEST_ID');
$this->db->select('EMPLOYEES_ID');
$this->db->select('GUEST_NAME');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('MEETING_PARTICIPANTS');
$this->db->join('EMPLOYEES', 'EMPLOYEES.ID = MEETING_PARTICIPANTS.EMPLOYEES_ID', 'left');
$this->db->join('GUEST', 'GUEST.ID = MEETING_PARTICIPANTS.GUEST_ID', 'left');
$this->db->join('MEETING', 'MEETING.ID = MEETING_PARTICIPANTS.MEETING_ID', 'left');
$this->db->where('PARTICIPANT_STATUS !=', '9');
$this->db->where('MEETING_ID', $id);
$this->db->order_by('MEETING_PARTICIPANTS.ID', 'ASC');
$query = $this->db->get();
$this->data['record'] = $query->result();
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->order_by('EMPLOYEE_NAME', 'ASC');
$this->db->where('EMPLOYEE_STATUS', '1');
$query = $this->db->get();
$this->data['record1'] = $query->result();
$tables = array('GUEST', 'COMPANY');
$this->db->select('GUEST.ID');
$this->db->select('GUEST_NAME');
$this->db->select('COMPANY_NAME');
$this->db->from($tables);
$this->db->order_by('GUEST_NAME', 'ASC');
$this->db->where('GUEST_STATUS', '1');
$this->db->where('GUEST.COMPANY_ID=COMPANY.ID');
$query = $this->db->get();
$this->data['record2'] = $query->result();
$this->data['meeting_id'] = $id;
$this->data['subtitle'] = 'Participant';
$this->data['data_table'] = 'yes';
$this->data['role_access'] = array('1', '3', '4');
//view
$this->load->view('section_header', $this->data);
$this->load->view('section_navbar');
$this->load->view('section_sidebar');
$this->load->view('section_breadcurm');
$this->load->view('section_content_title');
$this->load->view('meeting_participant');
$this->load->view('section_footer');
}
}
}
public function create(){
if(isset($_POST['submit'])){
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->where('EMPLOYEE_STATUS =', '1');
if($_POST['pic_id'] == ''){
$this->db->where('EMPLOYEE_NAME', $_POST['pic']);
}else{
$this->db->where('ID', $_POST['pic_id']);
}
$this->db->order_by('EMPLOYEE_NAME', 'ASC');
$query = $this->db->get();
$this->data['record'] = $query->result();
if($query->num_rows()==1){
//check room
$this->db->select('ID');
$this->db->select('MEETING_TIME');
$this->db->select('DURATION');
$this->db->select('MEETING_ROOM_ID');
$this->db->from('MEETING');
$this->db->where('DATE(MEETING_TIME)', date("Y-m-d", strtotime($_POST['date'])));
$this->db->where('MEETING_ROOM_ID', $_POST['room']);
$this->db->where('MEETING_STATUS != ', '9');
$query = $this->db->get();
$this->data['record1'] = $query->result();
if($query->num_rows()>=1){
//same date
$new_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
$new_hour = date("G", strtotime($new_date));
$new_duration = date("G", strtotime($new_date)) + ($_POST['duration'] -1);
$new_range = range($new_hour, $new_duration);
$error = false;
foreach($this->data['record1'] as $item){
$date_time = $item->MEETING_TIME;
$hour = date("G", strtotime($item->MEETING_TIME));
$duration = date("G", strtotime($item->MEETING_TIME)) + ($item->DURATION-1);
$range = range($hour, $duration);
foreach($new_range as $item){
foreach($range as $value){
if($value == $item){
$error = true;
}
}
}
}
if($error == true){
$this->data['warning'] = array(
'text' => 'Meeting with this date and time has scheduled, pick another',
);
}else{
foreach($this->data['record'] as $item){
$pic_id = $item->ID;
}
$set_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
$this->data['saveddata'] = array(
'MEETING_TIME' => $set_date,
'DURATION' => $_POST['duration'],
'AGENDA' => $_POST['agenda'],
'USER_ID' => $_POST['user'],
'MEETING_ROOM_ID' => $_POST['room'],
'PIC_ID' => $pic_id,
);
$this->db->insert('MEETING', $this->data['saveddata']);
redirect('meeting');
}
}else{
foreach($this->data['record'] as $item){
$pic_id = $item->ID;
}
$set_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
//insert ke database
$this->data['saveddata'] = array(
'MEETING_TIME' => $set_date,
'DURATION' => $_POST['duration'],
'AGENDA' => $_POST['agenda'],
'USER_ID' => $_POST['user'],
'MEETING_ROOM_ID' => $_POST['room'],
'PIC_ID' => $pic_id,
);
$this->db->insert('MEETING', $this->data['saveddata']);
redirect('meeting');
}
}else{
$this->data['warning'] = array(
'text' => 'Ops, PIC not found, Try a new one.',
);
}
}
//load data
$this->db->select('ID');
$this->db->select('ROOM_NAME');
$this->db->from('MEETING_ROOM');
$this->db->order_by('ROOM_NAME', 'ASC');
$this->db->where('ROOM_STATUS', '1');
$query = $this->db->get();
$this->data['record'] = $query->result();
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->order_by('EMPLOYEE_NAME', 'ASC');
$this->db->where('EMPLOYEE_STATUS', '1');
$query = $this->db->get();
$this->data['record1'] = $query->result();
$this->data['subtitle'] = 'Add';
$this->data['data_table'] = 'no';
$this->data['role_access'] = array('1', '3');
//view
$this->load->view('section_header', $this->data);
$this->load->view('section_navbar');
$this->load->view('section_sidebar');
$this->load->view('section_breadcurm');
$this->load->view('section_content_title');
$this->load->view('meeting_create');
$this->load->view('section_footer');
}
public function update($id=null){
if($id == null){
redirect('authentication/no_permission');
}else{
$tables = array('MEETING', 'EMPLOYEES');
$this->db->select('MEETING.ID');
$this->db->select('MEETING_TIME');
$this->db->select('DURATION');
$this->db->select('AGENDA');
$this->db->select('MEETING_ROOM_ID');
$this->db->select('PIC_ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->select('MEETING_STATUS');
$this->db->from($tables);
$this->db->where('MEETING.PIC_ID=EMPLOYEES.ID');
$this->db->where('MEETING.ID', $id);
$query = $this->db->get();
$this->data['record2'] = $query->result();
if($query->result() !== null){
if(isset($_POST['submit'])){
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->where('EMPLOYEE_STATUS =', '1');
if($_POST['pic_id'] == ''){
$this->db->where('EMPLOYEE_NAME', $_POST['pic']);
}else{
$this->db->where('ID', $_POST['pic_id']);
}
$this->db->order_by('EMPLOYEE_NAME', 'ASC');
$query = $this->db->get();
$this->data['record'] = $query->result();
if($query->num_rows()==1){
//check room
$this->db->select('ID');
$this->db->select('MEETING_TIME');
$this->db->select('DURATION');
$this->db->select('MEETING_ROOM_ID');
$this->db->from('MEETING');
$this->db->where('DATE(MEETING_TIME)', date("Y-m-d", strtotime($_POST['date'])));
$this->db->where('MEETING_ROOM_ID', $_POST['room']);
$this->db->where('MEETING.ID !=', $id);
$this->db->where('MEETING_STATUS != ', '9');
$query = $this->db->get();
$this->data['record1'] = $query->result();
if($query->num_rows()>=1){
//same date
$new_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
$new_hour = date("G", strtotime($new_date));
$new_duration = date("G", strtotime($new_date)) + $_POST['duration'];
$new_range = range($new_hour, $new_duration);
$error = false;
foreach($this->data['record1'] as $item){
$date_time = $item->MEETING_TIME;
$hour = date("G", strtotime($item->MEETING_TIME));
$duration = date("G", strtotime($item->MEETING_TIME)) + $item->DURATION;
$range = range($hour, $duration);
foreach($new_range as $item){
foreach($range as $value){
if($value == $item){
$error = true;
}
}
}
}
if($error == true){
$this->data['warning'] = array(
'text' => 'Meeting with this date and time has scheduled, pick another',
);
}else{
foreach($this->data['record'] as $item){
$pic_id = $item->ID;
}
$set_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
$this->data['saveddata'] = array(
'MEETING_TIME' => $set_date,
'DURATION' => $_POST['duration'],
'AGENDA' => $_POST['agenda'],
'USER_ID' => $_POST['user'],
'MEETING_ROOM_ID' => $_POST['room'],
'PIC_ID' => $pic_id,
);
$this->db->where('ID', $id);
$this->db->update('MEETING', $this->data['saveddata']);
redirect('meeting');
}
}else{
foreach($this->data['record'] as $item){
$pic_id = $item->ID;
}
$set_date = date("Y-m-d H:i:s", strtotime($_POST['date'] . ' ' . $_POST['time'] . ':00:00'));
//insert ke database
$this->data['saveddata'] = array(
'MEETING_TIME' => $set_date,
'DURATION' => $_POST['duration'],
'AGENDA' => $_POST['agenda'],
'USER_ID' => $_POST['user'],
'MEETING_ROOM_ID' => $_POST['room'],
'PIC_ID' => $pic_id,
);
$this->db->where('ID', $id);
$this->db->update('MEETING', $this->data['saveddata']);
redirect('meeting');
}
}else{
$this->data['warning'] = array(
'text' => 'Ops, PIC not found, Try a new one.',
);
}
}
//load data
$this->db->select('ID');
$this->db->select('ROOM_NAME');
$this->db->from('MEETING_ROOM');
$this->db->order_by('ROOM_NAME', 'ASC');
$this->db->where('ROOM_STATUS', '1');
$query = $this->db->get();
$this->data['record'] = $query->result();
$this->db->select('ID');
$this->db->select('EMPLOYEE_NAME');
$this->db->from('EMPLOYEES');
$this->db->order_by('EMPLOYEE_NAME', 'ASC');
$this->db->where('EMPLOYEE_STATUS', '1');
$query = $this->db->get();
$this->data['record1'] = $query->result();
$this->data['subtitle'] = 'Update';
$this->data['data_table'] = 'no';
$this->data['role_access'] = array('1', '3');
//view
$this->load->view('section_header', $this->data);
$this->load->view('section_navbar');
$this->load->view('section_sidebar');
$this->load->view('section_breadcurm');
$this->load->view('section_content_title');
$this->load->view('meeting_update');
$this->load->view('section_footer');
}else{
redirect('meeting');
}
}
}
public function update_status($id=null){
if($id === null){
redirect('authentication/no_permission');
}else{
//load data
$this->db->select('ID');
$this->db->select('MEETING_STATUS');
$this->db->from('MEETING');
$this->db->where('ID', $id);
$query = $this->db->get();
$result = $query->result();
if($result !== null){
foreach($result as $item){
$status = $item->MEETING_STATUS;
}
if($status == '1'){
$new_status = '0';
}else if($status == '0'){
$new_status = '1';
}
//Update Status di database
$this->db->set('MEETING_STATUS', $new_status);
$this->db->where('ID', $id);
$this->db->update('MEETING');
redirect('meeting');
}else{
redirect('meeting');
}
}
}
public function delete($id=null){
if($id === null){
redirect('authentication/no_permission');
}else{
//load data
$this->db->select('ID');
$this->db->select('MEETING_STATUS');
$this->db->from('MEETING');
$this->db->where('ID', $id);
$query = $this->db->get();
$result = $query->result();
if($result !== null){
//Update Status di database
$this->db->set('MEETING_STATUS', '9');
$this->db->where('ID', $id);
$this->db->update('MEETING');
redirect('meeting');
}else{
redirect('meeting');
}
}
}
public function participant_delete($mid, $id){
if($id === null){
redirect('authentication/no_permission');
}else{
//load data
$this->db->select('ID');
$this->db->select('PARTICIPANT_STATUS');
$this->db->from('MEETING_PARTICIPANTS');
$this->db->where('ID', $id);
$query = $this->db->get();
$result = $query->result();
if($result !== null){
//Update Status di database
$this->db->set('PARTICIPANT_STATUS', '9');
$this->db->where('ID', $id);
$this->db->update('MEETING_PARTICIPANTS');
redirect('meeting/participant/'.$mid);
}else{
redirect('meeting/participant/'.$mid);
}
}
}
}
| mit |
silentsignal/duncan | duncansamples.py | 1783 | #!/usr/bin/env python
import duncan
import requests
class SimpleDuncan(duncan.Duncan): # Inherit from Duncan
def decide(self,guess): # Implement decide()
# Construct your query to split the search space into two at guess
# self._query holds the query to be executed from the command line
# self._pos is the position of the character to be guessed
url="http://localhost/demo/sqli/blind.php?p=1 and ord(substr((%s),%d,1))<%d" % (self._query,self._pos,guess)
self.debug(6,url) # You can use the parents method for debug output
# Your module can accept command line parameters through the self._args argument
# It will contain a list of every argument that wasn't parsed by the framework
# It is recommended to pass it to argparse.ArgumentParser.parse_args()
self.debug(6,"Command line arguments for the module: %s" % repr(self._args))
r=requests.get(url)
if r.content.find(':)')>-1:
return True
else:
return False
class TimeBasedDuncan(duncan.DuncanTime):
def decide(self,guess):
import time,math
# Initial RTT measurement - maybe we could move this to the base class
if self._rttmax==0:
for _ in xrange(0,10):
t0=time.time()
requests.get("http://localhost/demo/sqli/time.php?p=1")
t1=time.time()
self.update_rtt(t1-t0)
self._sleep=(self._rttmax-self._rttmin)*1.2
self._threshold=self._rttmin+self._sleep
t0=time.time()
url="http://localhost/demo/sqli/time.php?p=1 and case when ord(substr((%s),%d,1))<%d then benchmark(%d,md5(1)) else 1 end" % (self._query,self._pos,guess,math.ceil((self._sleep/0.1)*450000)) # Mesure first!
self.debug(6,url)
r=requests.get(url)
t1=time.time()
self.debug(6, "Guess: %d, Time: %f" % (guess,t1-t0))
if t1-t0>self._threshold:
return True
else:
return False
| mit |
t10471/java | Generics/src/observer/Publisher.java | 1845 | package observer;
import java.util.ArrayList;
import java.util.List;
public class Publisher {
@SuppressWarnings("rawtypes")
private static final ThreadLocal<List> subscribers = new ThreadLocal<List>();
// 全ての購読者を一配列に入れる(べつのイベントの購読者も同じ配列にはいる)
private static final ThreadLocal<Boolean> publishing =new ThreadLocal<Boolean>(){
@Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
public static Publisher instance(){
return new Publisher();
}
@SuppressWarnings("unchecked")
public <T> void publish(final T event){
if(publishing.get()) return;
System.out.println("event : " + event.toString());
try{
publishing.set(Boolean.TRUE);
List<Subscriber<T>> registeredSubscribers = subscribers.get();
if(registeredSubscribers == null) return;
Class<?> type = event.getClass();
for(Subscriber<T> subscriber : registeredSubscribers){
System.out.println("subscriber: " + subscriber.toString());
Class<?> subscribedTo = subscriber.subscribedToEventType();
if(subscribedTo == type || subscribedTo == Event.class){
subscriber.handleEvent(event);
}
}
} finally {
publishing.set(Boolean.FALSE);
}
}
public Publisher reset() {
if(!publishing.get()) subscribers.set(null);
return this;
}
@SuppressWarnings("unchecked")
public <T> Publisher subscribe(Subscriber<T> subscriber) {
if(publishing.get()) return this;
List<Subscriber<T>> registeredSubscribers = subscribers.get();
System.out.println("subscriber : " + subscriber.toString());
if(registeredSubscribers == null) {
System.out.println("subscribers create ");
registeredSubscribers = new ArrayList<Subscriber<T>>();
subscribers.set(registeredSubscribers);
}
registeredSubscribers.add(subscriber);
return this;
}
}
| mit |
LocalJoost/XamarinFormsDemos | XamarinFormsDemos/XamarinFormsDemos/Views/AnimationBehaviorsPage.xaml.cs | 173 | namespace XamarinFormsDemos.Views
{
public partial class AnimationBehaviorsPage
{
public AnimationBehaviorsPage()
{
InitializeComponent();
}
}
}
| mit |
ansin218/p2p-voidphone-nse | code/compute_time.py | 986 | import math
from datetime import datetime
from datetime import timedelta
"""
Gets current starting time with flooding delay
"""
def get_cst_and_fd(nw_size_estimate, overlapping_bits):
hr_in_ms = 3600000.0
flood_delay_in_ms = (hr_in_ms/2) - (hr_in_ms/math.pi) * (math.atan(overlapping_bits - nw_size_estimate))
starttime = datetime.utcnow().replace(minute = 0, second = 0, microsecond = 0)
ct_plus_fd = starttime + timedelta(milliseconds = flood_delay_in_ms)
return ct_plus_fd
"""
Computes processing delay of messages
"""
def compute_process_delay(send_time):
time_difference = send_time - datetime.utcnow()
(delay_in_min, delay_in_sec) = divmod(time_difference.total_seconds(), 60)
delay_min_to_sec = delay_in_min * 60
computed_time_sec = delay_min_to_sec + delay_in_sec
return computed_time_sec
if __name__ == "__main__":
current_time = datetime.utcnow().replace(minute = 0, second = 0, microsecond = 0)
print(current_time) | mit |
lewgun/cloudmusic | cmd/cloudmusicd/web/src/services/flux/flux-boot.ts | 977 |
import {Injectable, Inject} from 'angular2/core';
import {Dispatcher} from "./dispatcher/dispatcher";
import {UserInfoActionCreator} from "./actions/userinfo-action";
import {PlayListActionCreator} from "./actions/playlist-action";
import {PlayActionCreator} from "./actions/play-action";
import {UserInfoStore } from "./stores/userinfo-store";
import {PlayListStore } from "./stores/playlist-store";
import {PlayStore } from "./stores/play-store";
@Injectable()
export class FluxBoot {
constructor(
@Inject(Dispatcher) private _dipatcher: Dispatcher,
@Inject(UserInfoStore) private _uis: UserInfoStore,
@Inject(UserInfoActionCreator) private _uiac: UserInfoActionCreator,
@Inject(PlayListStore) private _pls: PlayListStore,
@Inject(PlayActionCreator) private _pac: PlayActionCreator,
@Inject(PlayStore) private _ps: PlayStore,
@Inject(PlayActionCreator) private _plac: PlayListActionCreator
) { }
} | mit |
MrSkinny/taskzapper | spec/views/lists/index.html.erb_spec.rb | 142 | require 'rails_helper'
RSpec.describe "lists/index.html.erb", :type => :view do
pending "add some examples to (or delete) #{__FILE__}"
end
| mit |
danneu/guild | legacy_html/showthread/139029-Sobetsu-Cloaked-Rancor-OOC_files/ncode_imageresizer.js | 6646 |
/*
FILE ARCHIVED ON 20:33:44 Aug 3, 2012 AND RETRIEVED FROM THE
INTERNET ARCHIVE ON 9:01:34 Apr 5, 2015.
JAVASCRIPT APPENDED BY WAYBACK MACHINE, COPYRIGHT INTERNET ARCHIVE.
ALL OTHER CONTENT MAY ALSO BE PROTECTED BY COPYRIGHT (17 U.S.C.
SECTION 108(a)(3)).
*/
// nCode Image Resizer for vBulletin 3.6.0
// /web/20120803203344/http://www.ncode.nl/vbulletinplugins/
// Version: 1.0.1
//
// (c) 2007 nCode
NcodeImageResizer.IMAGE_ID_BASE = 'ncode_imageresizer_container_';
NcodeImageResizer.WARNING_ID_BASE = 'ncode_imageresizer_warning_';
NcodeImageResizer.scheduledResizes = [];
function NcodeImageResizer(id, img) {
this.id = id;
this.img = img;
this.originalWidth = 0;
this.originalHeight = 0;
this.warning = null;
this.warningTextNode = null;
this.originalWidth = img.originalWidth;
this.originalHeight = img.originalHeight;
img.id = NcodeImageResizer.IMAGE_ID_BASE+id;
}
NcodeImageResizer.executeOnload = function() {
var rss = NcodeImageResizer.scheduledResizes;
for(var i = 0; i < rss.length; i++) {
NcodeImageResizer.createOn(rss[i], true);
}
}
NcodeImageResizer.schedule = function(img) {
if(NcodeImageResizer.scheduledResizes.length == 0) {
if(window.addEventListener) {
window.addEventListener('load', NcodeImageResizer.executeOnload, false);
} else if(window.attachEvent) {
window.attachEvent('onload', NcodeImageResizer.executeOnload);
}
}
NcodeImageResizer.scheduledResizes.push(img);
}
NcodeImageResizer.getNextId = function() {
var id = 1;
while(document.getElementById(NcodeImageResizer.IMAGE_ID_BASE+id) != null) {
id++;
}
return id;
}
NcodeImageResizer.createOnId = function(id) {
return NcodeImageResizer.createOn(document.getElementById(id));
}
NcodeImageResizer.createOn = function(img, isSchedule) {
if(typeof isSchedule == 'undefined') isSchedule = false;
if(!img || !img.tagName || img.tagName.toLowerCase() != 'img') {
alert(img+' is not an image ('+img.tagName.toLowerCase()+')');
}
if(img.width == 0 || img.height == 0) {
if(!isSchedule)
NcodeImageResizer.schedule(img);
return;
}
if(!img.originalWidth) img.originalWidth = img.width;
if(!img.originalHeight) img.originalHeight = img.height;
if((NcodeImageResizer.MAXWIDTH > 0 && img.originalWidth > NcodeImageResizer.MAXWIDTH) || (NcodeImageResizer.MAXHEIGHT > 0 && img.originalHeight > NcodeImageResizer.MAXHEIGHT)) {
var isRecovery = false; // if this is a recovery from QuickEdit, which only restores the HTML, not the OO structure
var newid, resizer;
if(img.id && img.id.indexOf(NcodeImageResizer.IMAGE_ID_BASE) == 0) {
newid = img.id.substr(NcodeImageResizer.IMAGE_ID_BASE.length);
if(document.getElementById(NcodeImageResizer.WARNING_ID_BASE+newid) != null) {
resizer = new NcodeImageResizer(newid, img);
isRecovery = true;
resizer.restoreImage();
}
} else {
newid = NcodeImageResizer.getNextId();
resizer = new NcodeImageResizer(newid, img);
}
if(isRecovery) {
resizer.reclaimWarning(newid);
} else {
resizer.createWarning();
}
resizer.scale();
}
}
NcodeImageResizer.prototype.restoreImage = function() {
newimg = document.createElement('IMG');
newimg.src = this.img.src;
this.img.width = newimg.width;
this.img.height = newimg.height;
}
NcodeImageResizer.prototype.reclaimWarning = function(id) {
this.warning = document.getElementById(NcodeImageResizer.WARNING_ID_BASE+id);
this.warningTextNode = this.warning.firstChild.firstChild.childNodes[1].firstChild;
this.warning.resize = this;
this.scale();
}
NcodeImageResizer.prototype.createWarning = function() {
var mtable = document.createElement('TABLE');
var mtbody = document.createElement('TBODY');
var mtr = document.createElement('TR');
var mtd1 = document.createElement('TD');
var mtd2 = document.createElement('TD');
var mimg = document.createElement('IMG');
var mtext = document.createTextNode('');
mimg.src = NcodeImageResizer.BBURL+'/images/statusicon/wol_error.gif';
mimg.width = 16;
mimg.height = 16;
mimg.alt = '';
mimg.border = 0;
mtd1.width = 20;
mtd1.className = 'td1';
mtd2.unselectable = 'on';
mtd2.className = 'td2';
mtable.className = 'ncode_imageresizer_warning';
mtable.textNode = mtext;
mtable.resize = this;
mtable.id = NcodeImageResizer.WARNING_ID_BASE+this.id;
mtd1.appendChild(mimg);
mtd2.appendChild(mtext);
mtr.appendChild(mtd1);
mtr.appendChild(mtd2);
mtbody.appendChild(mtr);
mtable.appendChild(mtbody);
this.img.parentNode.insertBefore(mtable, this.img);
this.warning = mtable;
this.warningTextNode = mtext;
}
NcodeImageResizer.prototype.setText = function(text) {
var newnode = document.createTextNode(text);
this.warningTextNode.parentNode.replaceChild(newnode, this.warningTextNode);
this.warningTextNode = newnode;
}
NcodeImageResizer.prototype.scale = function() {
this.img.height = this.originalHeight;
this.img.width = this.originalWidth;
if(NcodeImageResizer.MAXWIDTH > 0 && this.img.width > NcodeImageResizer.MAXWIDTH) {
this.img.height = (NcodeImageResizer.MAXWIDTH / this.img.width) * this.img.height;
this.img.width = NcodeImageResizer.MAXWIDTH;
}
if(NcodeImageResizer.MAXHEIGHT > 0 && this.img.height > NcodeImageResizer.MAXHEIGHT) {
this.img.width = (NcodeImageResizer.MAXHEIGHT / this.img.height) * this.img.width;
this.img.height = NcodeImageResizer.MAXHEIGHT;
}
this.warning.width = this.img.width;
this.warning.onclick = function() { return this.resize.unScale(); }
if(this.img.width < 450) {
this.setText(vbphrase['ncode_imageresizer_warning_small']);
} else if(this.img.fileSize && this.img.fileSize > 0) {
this.setText(vbphrase['ncode_imageresizer_warning_filesize'].replace('%1$s', this.originalWidth).replace('%2$s', this.originalHeight).replace('%3$s', Math.round(this.img.fileSize/1024)));
} else {
this.setText(vbphrase['ncode_imageresizer_warning_no_filesize'].replace('%1$s', this.originalWidth).replace('%2$s', this.originalHeight));
}
return false;
}
NcodeImageResizer.prototype.unScale = function() {
switch(NcodeImageResizer.MODE) {
case 'samewindow':
window.open(this.img.src, '_self');
break;
case 'newwindow':
window.open(this.img.src, '_blank');
break;
case 'enlarge':
default:
this.img.width = this.originalWidth;
this.img.height = this.originalHeight;
this.img.className = 'ncode_imageresizer_original';
if(this.warning != null) {
this.setText(vbphrase['ncode_imageresizer_warning_fullsize']);
this.warning.width = this.img.width;
this.warning.onclick = function() { return this.resize.scale() };
}
break;
}
return false;
} | mit |
ArnaudBuchholz/gpf-js | lost+found/test/attributes/xml.js | 61 | "use strict";
describe("attributes/xml", function () {
});
| mit |
iamandrebulatov/Profile | Post-Hack/2/public_html/thinkinglimoCOM/wp-content/themes/TheStyle/includes/breadcrumbs.php | 1528 | <div id="breadcrumbs">
<?php if(function_exists('bcn_display')) { bcn_display(); }
else { ?>
<a href="<?php echo home_url(); ?>"><?php esc_html_e('Home','TheStyle') ?></a> <span class="raquo">»</span>
<?php if( is_tag() ) { ?>
<?php esc_html_e('Posts Tagged ','TheStyle') ?><span class="raquo">"</span><?php single_tag_title(); echo('"'); ?>
<?php } elseif (is_day()) { ?>
<?php esc_html_e('Posts made in','TheStyle') ?> <?php the_time('F jS, Y'); ?>
<?php } elseif (is_month()) { ?>
<?php esc_html_e('Posts made in','TheStyle') ?> <?php the_time('F, Y'); ?>
<?php } elseif (is_year()) { ?>
<?php esc_html_e('Posts made in','TheStyle') ?> <?php the_time('Y'); ?>
<?php } elseif (is_search()) { ?>
<?php esc_html_e('Search results for','TheStyle') ?> <?php the_search_query() ?>
<?php } elseif (is_single()) { ?>
<?php $category = get_the_category();
$catlink = get_category_link( $category[0]->cat_ID );
echo ('<a href="'.esc_url($catlink).'">'.esc_html($category[0]->cat_name).'</a> '.'<span class="raquo">»</span> '.get_the_title()); ?>
<?php } elseif (is_category()) { ?>
<?php single_cat_title(); ?>
<?php } elseif (is_author()) { ?>
<?php global $wp_query; $curauth = $wp_query->get_queried_object(); esc_html_e('Posts by ','TheStyle'); echo ' ',$curauth->nickname; ?>
<?php } elseif (is_page()) { ?>
<?php wp_title(''); ?>
<?php }; ?>
<?php }; ?>
</div> <!-- end #breadcrumbs --> | mit |
thejavamonk/hackerrankAlgorithms | algorithms_warmup/src/com/codeprep/correctnessinvariant/Solution.java | 820 | package com.codeprep.correctnessinvariant;
import java.util.Scanner;
public class Solution {
public static void insertionSort(int[] A){
for(int i = 1; i < A.length; i++){
int value = A[i];
int j = i - 1;
while(j >= 0 && A[j] > value){
A[j + 1] = A[j];
j--;
}
A[j + 1] = value;
}
printArray(A);
}
static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i=0;i<n;i++){
ar[i]=in.nextInt();
}
in.close();
insertionSort(ar);
}
}
| mit |
Azure/azure-sdk-for-ruby | data/azure_service_fabric/lib/6.2.0.9/generated/azure_service_fabric/models/application_load_info.rb | 4110 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V6_2_0_9
module Models
#
# Load Information about a Service Fabric application.
#
class ApplicationLoadInfo
include MsRestAzure
# @return [String] The identity of the application. This is an encoded
# representation of the application name. This is used in the REST APIs
# to identify the application resource.
# Starting in version 6.0, hierarchical names are delimited with the "\~"
# character. For example, if the application name is
# "fabric:/myapp/app1",
# the application identity would be "myapp\~app1" in 6.0+ and
# "myapp/app1" in previous versions.
attr_accessor :id
# @return [Integer] The minimum number of nodes for this application.
# It is the number of nodes where Service Fabric will reserve Capacity in
# the cluster which equals to ReservedLoad * MinimumNodes for this
# Application instance.
# For applications that do not have application capacity defined this
# value will be zero.
attr_accessor :minimum_nodes
# @return [Integer] The maximum number of nodes where this application
# can be instantiated.
# It is the number of nodes this application is allowed to span.
# For applications that do not have application capacity defined this
# value will be zero.
attr_accessor :maximum_nodes
# @return [Integer] The number of nodes on which this application is
# instantiated.
# For applications that do not have application capacity defined this
# value will be zero.
attr_accessor :node_count
# @return [Array<ApplicationMetricDescription>] List of application
# capacity metric description.
attr_accessor :application_load_metric_information
#
# Mapper for ApplicationLoadInfo class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApplicationLoadInfo',
type: {
name: 'Composite',
class_name: 'ApplicationLoadInfo',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'Id',
type: {
name: 'String'
}
},
minimum_nodes: {
client_side_validation: true,
required: false,
serialized_name: 'MinimumNodes',
type: {
name: 'Number'
}
},
maximum_nodes: {
client_side_validation: true,
required: false,
serialized_name: 'MaximumNodes',
type: {
name: 'Number'
}
},
node_count: {
client_side_validation: true,
required: false,
serialized_name: 'NodeCount',
type: {
name: 'Number'
}
},
application_load_metric_information: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationLoadMetricInformation',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationMetricDescriptionElementType',
type: {
name: 'Composite',
class_name: 'ApplicationMetricDescription'
}
}
}
}
}
}
}
end
end
end
end
| mit |
bartosz-wozniak/StockExchangeInvestor | src/StockExchange.Common/Consts.cs | 2931 | namespace StockExchange.Common
{
/// <summary>
/// Global project constants
/// </summary>
public static class Consts
{
/// <summary>
/// Commands for the Task consola app
/// </summary>
public static class Commands
{
/// <summary>
/// The help command
/// </summary>
public const string Help = "help";
/// <summary>
/// The command synchronizing stock data
/// </summary>
public const string SyncData = "sync-data";
/// <summary>
/// The command synchronizing stock data from GPW sources
/// </summary>
public const string SyncDataGpw = "sync-data-gpw";
/// <summary>
/// The command synchronizing stock data from today
/// </summary>
public const string SyncTodayData = "sync-today-data";
/// <summary>
/// The command synchronizing stock data from today from GPW sources
/// </summary>
public const string SyncTodayDataGpw = "sync-today-data-gpw";
/// <summary>
/// The command for fixing data from the GPW
/// </summary>
public const string FixData = "fix-data";
/// <summary>
/// The command for adding company groups to the database
/// </summary>
public const string AddCompanyGroups = "add-company-groups";
}
/// <summary>
/// Global formats
/// </summary>
public static class Formats
{
/// <summary>
/// Date format used when synchronizing the data
/// </summary>
public const string DateFormat = "yyyyMMdd";
/// <summary>
/// Date format used by the GPW site
/// </summary>
public const string DateGpwFormat = "yyyy-MM-dd";
/// <summary>
/// Default currency format
/// </summary>
public const string Currency = "{0:#,##0.00}";
/// <summary>
/// Default integer format
/// </summary>
public const string Integer = "{0:###0}";
/// <summary>
/// Default date format
/// </summary>
public const string DisplayDate = "{0:dd/MM/yyyy}";
/// <summary>
/// Default currency code
/// </summary>
public const string CurrencyCode = "PLN";
}
/// <summary>
/// Default parameter values for syncing stock data commands
/// </summary>
public static class SyncDataParameters
{
/// <summary>
/// Default start date
/// </summary>
public const string StartDate = "2006/01/01";
}
}
}
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2019-11-01/generated/azure_mgmt_network/models/flow_log.rb | 6216 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_11_01
module Models
#
# A flow log resource.
#
class FlowLog < Resource
include MsRestAzure
# @return [String] ID of network security group to which flow log will be
# applied.
attr_accessor :target_resource_id
# @return [String] Guid of network security group to which flow log will
# be applied.
attr_accessor :target_resource_guid
# @return [String] ID of the storage account which is used to store the
# flow log.
attr_accessor :storage_id
# @return [Boolean] Flag to enable/disable flow logging.
attr_accessor :enabled
# @return [RetentionPolicyParameters] Parameters that define the
# retention policy for flow log.
attr_accessor :retention_policy
# @return [FlowLogFormatParameters] Parameters that define the flow log
# format.
attr_accessor :format
# @return [TrafficAnalyticsProperties] Parameters that define the
# configuration of traffic analytics.
attr_accessor :flow_analytics_configuration
# @return [ProvisioningState] The provisioning state of the flow log.
# Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
attr_accessor :provisioning_state
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for FlowLog class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'FlowLog',
type: {
name: 'Composite',
class_name: 'FlowLog',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: false,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
target_resource_id: {
client_side_validation: true,
required: true,
serialized_name: 'properties.targetResourceId',
type: {
name: 'String'
}
},
target_resource_guid: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.targetResourceGuid',
type: {
name: 'String'
}
},
storage_id: {
client_side_validation: true,
required: true,
serialized_name: 'properties.storageId',
type: {
name: 'String'
}
},
enabled: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enabled',
type: {
name: 'Boolean'
}
},
retention_policy: {
client_side_validation: true,
required: false,
serialized_name: 'properties.retentionPolicy',
type: {
name: 'Composite',
class_name: 'RetentionPolicyParameters'
}
},
format: {
client_side_validation: true,
required: false,
serialized_name: 'properties.format',
type: {
name: 'Composite',
class_name: 'FlowLogFormatParameters'
}
},
flow_analytics_configuration: {
client_side_validation: true,
required: false,
serialized_name: 'properties.flowAnalyticsConfiguration',
type: {
name: 'Composite',
class_name: 'TrafficAnalyticsProperties'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
PrinceOfAmber/Cyclic | src/main/java/com/lothrazar/cyclic/event/ClientInputEvents.java | 2224 | package com.lothrazar.cyclic.event;
import com.lothrazar.cyclic.ModCyclic;
import com.lothrazar.cyclic.base.IHasClickToggle;
import com.lothrazar.cyclic.item.storagebag.StorageBagItem;
import com.lothrazar.cyclic.net.PacketItemGui;
import com.lothrazar.cyclic.net.PacketItemToggle;
import com.lothrazar.cyclic.registry.PacketRegistry;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public class ClientInputEvents {
@OnlyIn(Dist.CLIENT)
@SubscribeEvent(priority = EventPriority.HIGH)
public void onMouseEvent(GuiScreenEvent.MouseClickedEvent.Pre event) {
if (event.getGui() == null || !(event.getGui() instanceof ContainerScreen<?>)) {
return;
}
ContainerScreen<?> gui = (ContainerScreen<?>) event.getGui();
boolean rightClickDown = event.getButton() == 1;
try {
if (rightClickDown && gui.getSlotUnderMouse() != null) {
Slot slotHit = gui.getSlotUnderMouse();
if (!slotHit.getStack().isEmpty()) {
ItemStack maybeCharm = slotHit.getStack();
if (maybeCharm.getItem() instanceof IHasClickToggle) {
PacketRegistry.INSTANCE.sendToServer(new PacketItemToggle(slotHit.slotNumber));
event.setCanceled(true);
// UtilSound.playSound(ModCyclic.proxy.getClientPlayer(), SoundEvents.UI_BUTTON_CLICK);
}
else if (maybeCharm.getItem() instanceof StorageBagItem) {
PacketRegistry.INSTANCE.sendToServer(new PacketItemGui(slotHit.slotNumber));
event.setCanceled(true);
}
}
}
}
catch (Exception e) {//array out of bounds, or we are in a strange third party GUI that doesnt have slots like this
//EXAMPLE: mod.chiselsandbits.bitbag.BagGui
ModCyclic.LOGGER.error("click error", e);
// so this fixes ithttps://github.com/PrinceOfAmber/Cyclic/issues/410
}
}
}
| mit |
elBukkit/MagicPlugin | Magic/src/main/java/com/elmakers/mine/bukkit/magic/MageContext.java | 3471 | package com.elmakers.mine.bukkit.magic;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import com.elmakers.mine.bukkit.api.magic.CasterProperties;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.wand.Wand;
import com.elmakers.mine.bukkit.effect.EffectContext;
import com.google.common.base.Preconditions;
public class MageContext extends EffectContext implements com.elmakers.mine.bukkit.api.magic.MageContext {
protected final @Nonnull Mage mage;
public MageContext(@Nonnull Mage mage) {
super(mage.getController());
this.mage = Preconditions.checkNotNull(mage);
}
@Nonnull
@Override
public Mage getMage() {
return this.mage;
}
@Override
@Nonnull
public String getName() {
return getMage().getName();
}
@Nullable
@Override
public Location getLocation() {
if (location != null) {
return location;
}
return mage.getLocation();
}
@Nullable
@Override
public Location getCastLocation() {
return getEyeLocation();
}
@Nullable
@Override
public Location getWandLocation() {
return getCastLocation();
}
@Override
public Location getEyeLocation() {
if (location != null) {
return location;
}
return mage.getEyeLocation();
}
@Override
public Entity getEntity() {
return mage.getEntity();
}
@Nullable
@Override
public LivingEntity getLivingEntity() {
return mage.getLivingEntity();
}
@Override
@Nullable
public Color getEffectColor() {
return mage.getEffectColor();
}
@Override
@Nullable
public String getEffectParticle() {
return mage.getEffectParticleName();
}
@Override
public boolean canTarget(Entity entity) {
return true;
}
@Override
public boolean canTarget(Entity entity, Class<?> targetType) {
return true;
}
@Nullable
@Override
public Wand getWand() {
return mage.getActiveWand();
}
@Nullable
@Override
public Wand checkWand() {
return mage.checkWand();
}
@Override
public boolean isTargetable(Block block) {
return true;
}
@Override
public Logger getLogger() {
return getController().getLogger();
}
@Override
@Nonnull
public CasterProperties getActiveProperties() {
return mage.getActiveProperties();
}
@Nullable
@Override
public Double getAttribute(String attributeKey) {
return mage.getAttribute(attributeKey);
}
@Override
@Nullable
public Double getVariable(String variable) {
ConfigurationSection mageVariables = mage.getVariables();
if (mageVariables.contains(variable)) {
return mageVariables.getDouble(variable);
}
return null;
}
@Override
@Nonnull
public String getMessage(String key) {
return getMessage(key, "");
}
@Override
@Nonnull
public String getMessage(String key, String def) {
return controller.getMessages().get(key, def);
}
}
| mit |
bhollis/XboxLiveGamercardWidget | XboxLiveGamercard.dcproj/project/widget.wdgt/main.js | 3292 | /*
This file was generated by Dashcode.
You may edit this file to customize your widget or web page
according to the license.txt file included in the project.
*/
//
// Function: load()
// Called by HTML body element's onload event when the widget is ready to start
//
function load()
{
dashcode.setupParts();
var gamertag = widget.preferenceForKey(dashcode.createInstancePreferenceKey("gamertag"));
if(!gamertag || gamertag == "")
gamertag = "Major Nelson";
window.gamertag = gamertag;
var gamercard = document.getElementById("gamercard");
gamercard.src = "http://gamercard.xbox.com/" + window.gamertag + ".card";
var gamertagInput = document.getElementById("gamertagInput");
gamertagInput.value = gamertag;
gamertagInput.onkeypress = function(e) {
if (e.which == 13) {
showFront();
}
}
}
function update() {
// Refresh
clearTimeout(window.updateTimer);
var gamercard = document.getElementById("gamercard");
gamercard.src = "http://gamercard.xbox.com/" + window.gamertag + ".card";
window.updateTimer = setTimeout("update()", 30 * 60 * 1000); // 30 mins
}
//
// Function: remove()
// Called when the widget has been removed from the Dashboard
//
function remove()
{
clearTimeout(window.updateTimer);
widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey("gamertag"));
}
//
// Function: hide()
// Called when the widget has been hidden
//
function hide()
{
clearTimeout(window.updateTimer);
}
//
// Function: show()
// Called when the widget has been shown
//
function show()
{
update();
}
//
// Function: sync()
// Called when the widget has been synchronized with .Mac
//
function sync()
{
// Retrieve any preference values that you need to be synchronized here
// Use this for an instance key's value:
window.gamertag = widget.preferenceForKey(dashcode.createInstancePreferenceKey("gamertag"));
update();
}
//
// Function: showBack(event)
// Called when the info button is clicked to show the back of the widget
//
// event: onClick event from the info button
//
function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
//
// Function: showFront(event)
// Called when the done button is clicked from the back of the widget
//
// event: onClick event from the done button
//
function showFront(event)
{
window.gamertag = document.getElementById("gamertagInput").value;
update();
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToFront");
}
front.style.display="block";
back.style.display="none";
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
if (window.widget) {
widget.onremove = remove;
widget.onhide = hide;
widget.onshow = show;
widget.onsync = sync;
}
function goToUrl(event)
{
widget.openURL("http://benhollis.net/software/dashboard/");
}
| mit |
joyce131480/master | app.js | 52745 | /* jshint -W117 */
/* application specific logic */
var connection = null;
var authenticatedUser = false;
var authenticationWindow = null;
var activecall = null;
var nickname = null;
var sharedKey = '';
var focusMucJid = null;
var roomUrl = null;
var roomName = null;
var ssrc2jid = {};
var bridgeIsDown = false;
//TODO: this array must be removed when firefox implement multistream support
var notReceivedSSRCs = [];
var jid2Ssrc = {};
/**
* Indicates whether ssrc is camera video or desktop stream.
* FIXME: remove those maps
*/
var ssrc2videoType = {};
/**
* Currently focused video "src"(displayed in large video).
* @type {String}
*/
var focusedVideoInfo = null;
var mutedAudios = {};
/**
* Remembers if we were muted by the focus.
* @type {boolean}
*/
var forceMuted = false;
/**
* Indicates if we have muted our audio before the conference has started.
* @type {boolean}
*/
var preMuted = false;
var localVideoSrc = null;
var flipXLocalVideo = true;
var isFullScreen = false;
var currentVideoWidth = null;
var currentVideoHeight = null;
/**
* Method used to calculate large video size.
* @type {function ()}
*/
var getVideoSize;
/**
* Method used to get large video position.
* @type {function ()}
*/
var getVideoPosition;
/* window.onbeforeunload = closePageWarning; */
var sessionTerminated = false;
function init() {
Toolbar.setupButtonsFromConfig();
RTC.addStreamListener(maybeDoJoin, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
RTC.addStreamListener(VideoLayout.onLocalStreamCreated, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED)
RTC.start();
var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
connect(jid);
}
function connect(jid, password) {
var localAudio, localVideo;
if (connection && connection.jingle) {
localAudio = connection.jingle.localAudio;
localVideo = connection.jingle.localVideo;
}
connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
var email = SettingsMenu.getEmail();
var displayName = SettingsMenu.getDisplayName();
if(email) {
connection.emuc.addEmailToPresence(email);
} else {
connection.emuc.addUserIdToPresence(SettingsMenu.getUID());
}
if(displayName) {
connection.emuc.addDisplayNameToPresence(displayName);
}
if (connection.disco) {
// for chrome, add multistream cap
}
connection.jingle.pc_constraints = RTC.getPCConstraints();
if (config.useIPv6) {
// https://code.google.com/p/webrtc/issues/detail?id=2828
if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
connection.jingle.pc_constraints.optional.push({googIPv6: true});
}
if (localAudio) connection.jingle.localAudio = localAudio;
if (localVideo) connection.jingle.localVideo = localVideo;
if(!password)
password = document.getElementById('password').value;
var anonymousConnectionFailed = false;
connection.connect(jid, password, function (status, msg) {
console.log('Strophe status changed to', Strophe.getStatusString(status));
if (status === Strophe.Status.CONNECTED) {
if (config.useStunTurn) {
connection.jingle.getStunAndTurnCredentials();
}
document.getElementById('connect').disabled = true;
console.info("My Jabber ID: " + connection.jid);
if(password)
authenticatedUser = true;
maybeDoJoin();
} else if (status === Strophe.Status.CONNFAIL) {
if(msg === 'x-strophe-bad-non-anon-jid') {
anonymousConnectionFailed = true;
}
} else if (status === Strophe.Status.DISCONNECTED) {
if(anonymousConnectionFailed) {
// prompt user for username and password
$(document).trigger('passwordrequired.main');
}
} else if (status === Strophe.Status.AUTHFAIL) {
// wrong password or username, prompt user
$(document).trigger('passwordrequired.main');
}
});
}
function maybeDoJoin() {
if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
&& (connection.jingle.localAudio || connection.jingle.localVideo)) {
doJoin();
}
}
function generateRoomName() {
var roomnode = null;
var path = window.location.pathname;
// determinde the room node from the url
// TODO: just the roomnode or the whole bare jid?
if (config.getroomnode && typeof config.getroomnode === 'function') {
// custom function might be responsible for doing the pushstate
roomnode = config.getroomnode(path);
} else {
/* fall back to default strategy
* this is making assumptions about how the URL->room mapping happens.
* It currently assumes deployment at root, with a rewrite like the
* following one (for nginx):
location ~ ^/([a-zA-Z0-9]+)$ {
rewrite ^/(.*)$ / break;
}
*/
if (path.length > 1) {
roomnode = path.substr(1).toLowerCase();
} else {
var word = RoomNameGenerator.generateRoomWithoutSeparator();
roomnode = word.toLowerCase();
window.history.pushState('VideoChat',
'Room: ' + word, window.location.pathname + word);
}
}
roomName = roomnode + '@' + config.hosts.muc;
}
function doJoin() {
if (!roomName) {
generateRoomName();
}
Moderator.allocateConferenceFocus(
roomName, doJoinAfterFocus);
}
function doJoinAfterFocus() {
var roomjid;
roomjid = roomName;
if (config.useNicks) {
var nick = window.prompt('Your nickname (optional)');
if (nick) {
roomjid += '/' + nick;
} else {
roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
}
} else {
var tmpJid = Strophe.getNodeFromJid(connection.jid);
if(!authenticatedUser)
tmpJid = tmpJid.substr(0, 8);
roomjid += '/' + tmpJid;
}
connection.emuc.doJoin(roomjid);
}
function waitForRemoteVideo(selector, ssrc, stream, jid) {
// XXX(gp) so, every call to this function is *always* preceded by a call
// to the RTC.attachMediaStream() function but that call is *not* followed
// by an update to the videoSrcToSsrc map!
//
// The above way of doing things results in video SRCs that don't correspond
// to any SSRC for a short period of time (to be more precise, for as long
// the waitForRemoteVideo takes to complete). This causes problems (see
// bellow).
//
// I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
// a second time in here and only then update the videoSrcToSsrc map? Why
// not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
// is called the first time? I actually do that in the lastN changed event
// handler because the "orphan" video SRC is causing troubles there. The
// purpose of this method would then be to fire the "videoactive.jingle".
//
// Food for though I guess :-)
if (selector.removed || !selector.parent().is(":visible")) {
console.warn("Media removed before had started", selector);
return;
}
if (stream.id === 'mixedmslabel') return;
if (selector[0].currentTime > 0) {
var videoStream = simulcast.getReceivingVideoStream(stream);
RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
// FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
// in order to get rid of too many maps
if (ssrc && jid) {
jid2Ssrc[Strophe.getResourceFromJid(jid)] = ssrc;
} else {
console.warn("No ssrc given for jid", jid);
// messageHandler.showError('Warning', 'No ssrc was given for the video.');
}
$(document).trigger('videoactive.jingle', [selector]);
} else {
setTimeout(function () {
waitForRemoteVideo(selector, ssrc, stream, jid);
}, 250);
}
}
$(document).bind('remotestreamadded.jingle', function (event, data, sid) {
waitForPresence(data, sid);
});
function waitForPresence(data, sid) {
var sess = connection.jingle.sessions[sid];
var thessrc;
// look up an associated JID for a stream id
if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
// look only at a=ssrc: and _not_ at a=ssrc-group: lines
var ssrclines
= SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
ssrclines = ssrclines.filter(function (line) {
// NOTE(gp) previously we filtered on the mslabel, but that property
// is not always present.
// return line.indexOf('mslabel:' + data.stream.label) !== -1;
return ((line.indexOf('msid:' + data.stream.id) !== -1));
});
if (ssrclines.length) {
thessrc = ssrclines[0].substring(7).split(' ')[0];
// We signal our streams (through Jingle to the focus) before we set
// our presence (through which peers associate remote streams to
// jids). So, it might arrive that a remote stream is added but
// ssrc2jid is not yet updated and thus data.peerjid cannot be
// successfully set. Here we wait for up to a second for the
// presence to arrive.
if (!ssrc2jid[thessrc]) {
// TODO(gp) limit wait duration to 1 sec.
setTimeout(function(d, s) {
return function() {
waitForPresence(d, s);
}
}(data, sid), 250);
return;
}
// ok to overwrite the one from focus? might save work in colibri.js
console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
if (ssrc2jid[thessrc]) {
data.peerjid = ssrc2jid[thessrc];
}
}
}
//TODO: this code should be removed when firefox implement multistream support
if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
{
if((notReceivedSSRCs.length == 0) ||
!ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])
{
// TODO(gp) limit wait duration to 1 sec.
setTimeout(function(d, s) {
return function() {
waitForPresence(d, s);
}
}(data, sid), 250);
return;
}
thessrc = notReceivedSSRCs.pop();
if (ssrc2jid[thessrc]) {
data.peerjid = ssrc2jid[thessrc];
}
}
RTC.createRemoteStream(data, sid, thessrc);
var container;
var remotes = document.getElementById('remoteVideos');
if (data.peerjid) {
VideoLayout.ensurePeerContainerExists(data.peerjid);
container = document.getElementById(
'participant_' + Strophe.getResourceFromJid(data.peerjid));
} else {
if (data.stream.id !== 'mixedmslabel'
// FIXME: default stream is added always with new focus
// (to be investigated)
&& data.stream.id !== 'default') {
console.error('can not associate stream',
data.stream.id,
'with a participant');
// We don't want to add it here since it will cause troubles
return;
}
// FIXME: for the mixed ms we dont need a video -- currently
container = document.createElement('span');
container.id = 'mixedstream';
container.className = 'videocontainer';
remotes.appendChild(container);
Util.playSoundNotification('userJoined');
}
var isVideo = data.stream.getVideoTracks().length > 0;
if (container) {
VideoLayout.addRemoteStreamElement( container,
sid,
data.stream,
data.peerjid,
thessrc);
}
// an attempt to work around https://github.com/jitsi/jitmeet/issues/32
if (isVideo &&
data.peerjid && sess.peerjid === data.peerjid &&
data.stream.getVideoTracks().length === 0 &&
connection.jingle.localVideo.getVideoTracks().length > 0) {
//
window.setTimeout(function () {
sendKeyframe(sess.peerconnection);
}, 3000);
}
}
// an attempt to work around https://github.com/jitsi/jitmeet/issues/32
function sendKeyframe(pc) {
console.log('sendkeyframe', pc.iceConnectionState);
if (pc.iceConnectionState !== 'connected') return; // safe...
pc.setRemoteDescription(
pc.remoteDescription,
function () {
pc.createAnswer(
function (modifiedAnswer) {
pc.setLocalDescription(
modifiedAnswer,
function () {
// noop
},
function (error) {
console.log('triggerKeyframe setLocalDescription failed', error);
messageHandler.showError();
}
);
},
function (error) {
console.log('triggerKeyframe createAnswer failed', error);
messageHandler.showError();
}
);
},
function (error) {
console.log('triggerKeyframe setRemoteDescription failed', error);
messageHandler.showError();
}
);
}
// Really mute video, i.e. dont even send black frames
function muteVideo(pc, unmute) {
// FIXME: this probably needs another of those lovely state safeguards...
// which checks for iceconn == connected and sigstate == stable
pc.setRemoteDescription(pc.remoteDescription,
function () {
pc.createAnswer(
function (answer) {
var sdp = new SDP(answer.sdp);
if (sdp.media.length > 1) {
if (unmute)
sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
else
sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
sdp.raw = sdp.session + sdp.media.join('');
answer.sdp = sdp.raw;
}
pc.setLocalDescription(answer,
function () {
console.log('mute SLD ok');
},
function (error) {
console.log('mute SLD error');
messageHandler.showError('Error',
'Oops! Something went wrong and we failed to ' +
'mute! (SLD Failure)');
}
);
},
function (error) {
console.log(error);
messageHandler.showError();
}
);
},
function (error) {
console.log('muteVideo SRD error');
messageHandler.showError('Error',
'Oops! Something went wrong and we failed to stop video!' +
'(SRD Failure)');
}
);
}
/**
* Callback for audio levels changed.
* @param jid JID of the user
* @param audioLevel the audio level value
*/
function audioLevelUpdated(jid, audioLevel)
{
var resourceJid;
if(jid === statistics.LOCAL_JID)
{
resourceJid = AudioLevels.LOCAL_LEVEL;
if(isAudioMuted())
{
audioLevel = 0;
}
}
else
{
resourceJid = Strophe.getResourceFromJid(jid);
}
AudioLevels.updateAudioLevel(resourceJid, audioLevel);
}
$(document).bind('callincoming.jingle', function (event, sid) {
var sess = connection.jingle.sessions[sid];
// TODO: do we check activecall == null?
activecall = sess;
statistics.onConferenceCreated(sess);
RTC.onConferenceCreated(sess);
// TODO: check affiliation and/or role
console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
sess.usedrip = true; // not-so-naive trickle ice
sess.sendAnswer();
sess.accept();
});
$(document).bind('conferenceCreated.jingle', function (event, focus)
{
statistics.onConfereceCreated(getConferenceHandler());
RTC.onConfereceCreated(focus);
});
$(document).bind('setLocalDescription.jingle', function (event, sid) {
// put our ssrcs into presence so other clients can identify our stream
var sess = connection.jingle.sessions[sid];
var newssrcs = [];
var media = simulcast.parseMedia(sess.peerconnection.localDescription);
media.forEach(function (media) {
if(Object.keys(media.sources).length > 0) {
// TODO(gp) maybe exclude FID streams?
Object.keys(media.sources).forEach(function (ssrc) {
newssrcs.push({
'ssrc': ssrc,
'type': media.type,
'direction': media.direction
});
});
}
else if(sess.localStreamsSSRC && sess.localStreamsSSRC[media.type])
{
newssrcs.push({
'ssrc': sess.localStreamsSSRC[media.type],
'type': media.type,
'direction': media.direction
});
}
});
console.log('new ssrcs', newssrcs);
// Have to clear presence map to get rid of removed streams
connection.emuc.clearPresenceMedia();
if (newssrcs.length > 0) {
for (var i = 1; i <= newssrcs.length; i ++) {
// Change video type to screen
if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
newssrcs[i-1].type = 'screen';
}
connection.emuc.addMediaToPresence(i,
newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
}
connection.emuc.sendPresence();
}
});
$(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
switch (session.peerconnection.iceConnectionState) {
case 'checking':
session.timeChecking = (new Date()).getTime();
session.firstconnect = true;
break;
case 'completed': // on caller side
case 'connected':
if (session.firstconnect) {
session.firstconnect = false;
var metadata = {};
metadata.setupTime = (new Date()).getTime() - session.timeChecking;
session.peerconnection.getStats(function (res) {
if(res && res.result) {
res.result().forEach(function (report) {
if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
metadata.localCandidateType = report.stat('googLocalCandidateType');
metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
// log pair as well so we can get nice pie charts
metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
if (report.stat('googRemoteAddress').indexOf('[') === 0) {
metadata.ipv6 = true;
}
}
});
trackUsage('iceConnected', metadata);
}
});
}
break;
}
});
$(document).bind('joined.muc', function (event, jid, info) {
updateRoomUrl(window.location.href);
document.getElementById('localNick').appendChild(
document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
);
// Add myself to the contact list.
ContactList.addContact(jid, SettingsMenu.getEmail() || SettingsMenu.getUID());
// Once we've joined the muc show the toolbar
ToolbarToggler.showToolbar();
// Show authenticate button if needed
Toolbar.showAuthenticateButton(
Moderator.isExternalAuthEnabled() && !Moderator.isModerator());
var displayName = !config.displayJids
? info.displayName : Strophe.getResourceFromJid(jid);
if (displayName)
$(document).trigger('displaynamechanged',
['localVideoContainer', displayName + ' (me)']);
});
$(document).bind('entered.muc', function (event, jid, info, pres) {
console.log('entered', jid, info);
if (info.isFocus)
{
focusMucJid = jid;
console.info("Ignore focus: " + jid +", real JID: " + info.jid);
return;
}
messageHandler.notify(info.displayName || 'Somebody',
'connected',
'connected');
// Add Peer's container
var id = $(pres).find('>userID').text();
var email = $(pres).find('>email');
if(email.length > 0) {
id = email.text();
}
VideoLayout.ensurePeerContainerExists(jid,id);
if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
{
APIConnector.triggerEvent("participantJoined",{jid: jid});
}
/*if (focus !== null) {
// FIXME: this should prepare the video
if (focus.confid === null) {
console.log('make new conference with', jid);
focus.makeConference(Object.keys(connection.emuc.members),
function(error) {
connection.emuc.addBridgeIsDownToPresence();
connection.emuc.sendPresence();
}
);
Toolbar.showRecordingButton(true);
} else {
console.log('invite', jid, 'into conference');
focus.addNewParticipant(jid);
}
}*/
});
$(document).bind('left.muc', function (event, jid) {
console.log('left.muc', jid);
var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
'>.displayname').html();
messageHandler.notify(displayName || 'Somebody',
'disconnected',
'disconnected');
// Need to call this with a slight delay, otherwise the element couldn't be
// found for some reason.
// XXX(gp) it works fine without the timeout for me (with Chrome 38).
window.setTimeout(function () {
var container = document.getElementById(
'participant_' + Strophe.getResourceFromJid(jid));
if (container) {
ContactList.removeContact(jid);
VideoLayout.removeConnectionIndicator(jid);
// hide here, wait for video to close before removing
$(container).hide();
VideoLayout.resizeThumbnails();
}
}, 10);
if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
{
APIConnector.triggerEvent("participantLeft",{jid: jid});
}
delete jid2Ssrc[jid];
// Unlock large video
if (focusedVideoInfo && focusedVideoInfo.jid === jid)
{
console.info("Focused video owner has left the conference");
focusedVideoInfo = null;
}
connection.jingle.terminateByJid(jid);
if (connection.emuc.getPrezi(jid)) {
$(document).trigger('presentationremoved.muc',
[jid, connection.emuc.getPrezi(jid)]);
}
});
$(document).bind('presence.muc', function (event, jid, info, pres) {
//check if the video bridge is available
if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
bridgeIsDown = true;
messageHandler.showError("Error",
"Jitsi Videobridge is currently unavailable. Please try again later!");
}
if (info.isFocus)
{
return;
}
// Remove old ssrcs coming from the jid
Object.keys(ssrc2jid).forEach(function (ssrc) {
if (ssrc2jid[ssrc] == jid) {
delete ssrc2jid[ssrc];
delete ssrc2videoType[ssrc];
}
});
$(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
//console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
var ssrcV = ssrc.getAttribute('ssrc');
ssrc2jid[ssrcV] = jid;
notReceivedSSRCs.push(ssrcV);
var type = ssrc.getAttribute('type');
ssrc2videoType[ssrcV] = type;
// might need to update the direction if participant just went from sendrecv to recvonly
if (type === 'video' || type === 'screen') {
var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
switch (ssrc.getAttribute('direction')) {
case 'sendrecv':
el.show();
break;
case 'recvonly':
el.hide();
// FIXME: Check if we have to change large video
//VideoLayout.updateLargeVideo(el);
break;
}
}
});
var displayName = !config.displayJids
? info.displayName : Strophe.getResourceFromJid(jid);
if (displayName && displayName.length > 0)
$(document).trigger('displaynamechanged',
[jid, displayName]);
/*if (focus !== null && info.displayName !== null) {
focus.setEndpointDisplayName(jid, info.displayName);
}*/
//check if the video bridge is available
if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
bridgeIsDown = true;
messageHandler.showError("Error",
"Jitsi Videobridge is currently unavailable. Please try again later!");
}
var id = $(pres).find('>userID').text();
var email = $(pres).find('>email');
if(email.length > 0) {
id = email.text();
}
Avatar.setUserAvatar(jid, id);
});
$(document).bind('presence.status.muc', function (event, jid, info, pres) {
VideoLayout.setPresenceStatus(
'participant_' + Strophe.getResourceFromJid(jid), info.status);
});
$(document).bind('kicked.muc', function (event, jid) {
console.info(jid + " has been kicked from MUC!");
if (connection.emuc.myroomjid === jid) {
sessionTerminated = true;
disposeConference(false);
connection.emuc.doLeave();
messageHandler.openMessageDialog("Session Terminated",
"Ouch! You have been kicked out of the meet!");
}
});
$(document).bind('role.changed.muc', function (event, jid, member, pres) {
console.info("Role changed for " + jid + ", new role: " + member.role);
VideoLayout.showModeratorIndicator();
if (member.role === 'moderator') {
var displayName = member.displayName;
if (!displayName) {
displayName = 'Somebody';
}
messageHandler.notify(
displayName,
'connected',
'Moderator rights granted to ' + displayName + '!');
}
}
);
$(document).bind('local.role.changed.muc', function (event, jid, info, pres) {
console.info("My role changed, new role: " + info.role);
var isModerator = Moderator.isModerator();
VideoLayout.showModeratorIndicator();
Toolbar.showAuthenticateButton(
Moderator.isExternalAuthEnabled() && !isModerator);
if (isModerator) {
if (authenticationWindow) {
authenticationWindow.close();
authenticationWindow = null;
}
messageHandler.notify(
'Me', 'connected', 'Moderator rights granted !');
}
}
);
$(document).bind('passwordrequired.muc', function (event, jid) {
console.log('on password required', jid);
// password is required
Toolbar.lockLockButton();
messageHandler.openTwoButtonDialog(null,
'<h2>Password required</h2>' +
'<input id="lockKey" type="text" placeholder="password" autofocus>',
true,
"Ok",
function (e, v, m, f) {},
function (event) {
document.getElementById('lockKey').focus();
},
function (e, v, m, f) {
if (v) {
var lockKey = document.getElementById('lockKey');
if (lockKey.value !== null) {
setSharedKey(lockKey.value);
connection.emuc.doJoin(jid, lockKey.value);
}
}
}
);
});
$(document).bind('passwordrequired.main', function (event) {
console.log('password is required');
messageHandler.openTwoButtonDialog(null,
'<h2>Password required</h2>' +
'<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
'<input id="passwordrequired.password" type="password" placeholder="user password">',
true,
"Ok",
function (e, v, m, f) {
if (v) {
var username = document.getElementById('passwordrequired.username');
var password = document.getElementById('passwordrequired.password');
if (username.value !== null && password.value != null) {
connect(username.value, password.value);
}
}
},
function (event) {
document.getElementById('passwordrequired.username').focus();
}
);
});
$(document).bind('auth_required.moderator', function () {
// extract room name from 'room@muc.server.net'
var room = roomName.substr(0, roomName.indexOf('@'));
messageHandler.openDialog(
'Stop',
'Authentication is required to create room:<br/>' + room,
true,
{
Authenticate: 'authNow',
Close: 'close'
},
function (onSubmitEvent, submitValue) {
console.info('On submit: ' + submitValue, submitValue);
if (submitValue === 'authNow') {
authenticateClicked();
} else {
Toolbar.showAuthenticateButton(true);
}
}
);
});
function authenticateClicked() {
// Get authentication URL
Moderator.getAuthUrl(function (url) {
// Open popup with authentication URL
authenticationWindow = messageHandler.openCenteredPopup(
url, 910, 660,
function () {
// On popup closed - retry room allocation
Moderator.allocateConferenceFocus(
roomName, doJoinAfterFocus);
authenticationWindow = null;
});
if (!authenticationWindow) {
Toolbar.showAuthenticateButton(true);
messageHandler.openMessageDialog(
null, "Your browser is blocking popup windows from this site." +
" Please enable popups in your browser security settings" +
" and try again.");
}
});
};
/**
* Checks if video identified by given src is desktop stream.
* @param videoSrc eg.
* blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
* @returns {boolean}
*/
function isVideoSrcDesktop(jid) {
// FIXME: fix this mapping mess...
// figure out if large video is desktop stream or just a camera
if(!jid)
return false;
var isDesktop = false;
if (connection.emuc.myroomjid &&
Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
// local video
isDesktop = isUsingScreenStream;
} else {
// Do we have associations...
var videoSsrc = jid2Ssrc[jid];
if (videoSsrc) {
var videoType = ssrc2videoType[videoSsrc];
if (videoType) {
// Finally there...
isDesktop = videoType === 'screen';
} else {
console.error("No video type for ssrc: " + videoSsrc);
}
} else {
console.error("No ssrc for jid: " + jid);
}
}
return isDesktop;
}
function getConferenceHandler() {
return activecall;
}
/**
* Mutes/unmutes the local video.
*
* @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
* @param options an object which specifies optional arguments such as the
* <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
* specifies whether the method was initiated in response to a user command (in
* contrast to an automatic decision taken by the application logic)
*/
function setVideoMute(mute, options) {
if (connection && connection.jingle.localVideo) {
var session = getConferenceHandler();
if (session) {
session.setVideoMute(
mute,
function (mute) {
var video = $('#video');
var communicativeClass = "icon-camera";
var muteClass = "icon-camera icon-camera-disabled";
if (mute) {
video.removeClass(communicativeClass);
video.addClass(muteClass);
} else {
video.removeClass(muteClass);
video.addClass(communicativeClass);
}
connection.emuc.addVideoInfoToPresence(mute);
connection.emuc.sendPresence();
},
options);
}
}
}
$(document).on('inlastnchanged', function (event, oldValue, newValue) {
if (config.muteLocalVideoIfNotInLastN) {
setVideoMute(!newValue, { 'byUser': false });
}
});
/**
* Mutes/unmutes the local video.
*/
function toggleVideo() {
buttonClick("#video", "icon-camera icon-camera-disabled");
if (connection && connection.jingle.localVideo) {
var session = getConferenceHandler();
if (session) {
setVideoMute(!session.isVideoMute());
}
}
}
/**
* Mutes / unmutes audio for the local participant.
*/
function toggleAudio() {
setAudioMuted(!isAudioMuted());
}
/**
* Sets muted audio state for the local participant.
*/
function setAudioMuted(mute) {
if (!(connection && connection.jingle.localAudio)) {
preMuted = mute;
// We still click the button.
buttonClick("#mute", "icon-microphone icon-mic-disabled");
return;
}
if (forceMuted && !mute) {
console.info("Asking focus for unmute");
connection.moderate.setMute(connection.emuc.myroomjid, mute);
// FIXME: wait for result before resetting muted status
forceMuted = false;
}
if (mute == isAudioMuted()) {
// Nothing to do
return;
}
// It is not clear what is the right way to handle multiple tracks.
// So at least make sure that they are all muted or all unmuted and
// that we send presence just once.
var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
if (localAudioTracks.length > 0) {
for (var idx = 0; idx < localAudioTracks.length; idx++) {
localAudioTracks[idx].enabled = !mute;
}
}
// isMuted is the opposite of audioEnabled
connection.emuc.addAudioInfoToPresence(mute);
connection.emuc.sendPresence();
VideoLayout.showLocalAudioIndicator(mute);
buttonClick("#mute", "icon-microphone icon-mic-disabled");
}
/**
* Checks whether the audio is muted or not.
* @returns {boolean} true if audio is muted and false if not.
*/
function isAudioMuted()
{
var localAudio = connection.jingle.localAudio;
for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
if(localAudio.getAudioTracks()[idx].enabled === true)
return false;
}
return true;
}
// Starts or stops the recording for the conference.
function toggleRecording() {
Recording.toggleRecording();
}
/**
* Returns an array of the video horizontal and vertical indents,
* so that if fits its parent.
*
* @return an array with 2 elements, the horizontal indent and the vertical
* indent
*/
function getCameraVideoPosition(videoWidth,
videoHeight,
videoSpaceWidth,
videoSpaceHeight) {
// Parent height isn't completely calculated when we position the video in
// full screen mode and this is why we use the screen height in this case.
// Need to think it further at some point and implement it properly.
var isFullScreen = document.fullScreen ||
document.mozFullScreen ||
document.webkitIsFullScreen;
if (isFullScreen)
videoSpaceHeight = window.innerHeight;
var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
return [horizontalIndent, verticalIndent];
}
/**
* Returns an array of the video horizontal and vertical indents.
* Centers horizontally and top aligns vertically.
*
* @return an array with 2 elements, the horizontal indent and the vertical
* indent
*/
function getDesktopVideoPosition(videoWidth,
videoHeight,
videoSpaceWidth,
videoSpaceHeight) {
var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
var verticalIndent = 0;// Top aligned
return [horizontalIndent, verticalIndent];
}
/**
* Returns an array of the video dimensions, so that it covers the screen.
* It leaves no empty areas, but some parts of the video might not be visible.
*
* @return an array with 2 elements, the video width and the video height
*/
function getCameraVideoSize(videoWidth,
videoHeight,
videoSpaceWidth,
videoSpaceHeight) {
if (!videoWidth)
videoWidth = currentVideoWidth;
if (!videoHeight)
videoHeight = currentVideoHeight;
var aspectRatio = videoWidth / videoHeight;
var availableWidth = Math.max(videoWidth, videoSpaceWidth);
var availableHeight = Math.max(videoHeight, videoSpaceHeight);
if (availableWidth / aspectRatio < videoSpaceHeight) {
availableHeight = videoSpaceHeight;
availableWidth = availableHeight * aspectRatio;
}
if (availableHeight * aspectRatio < videoSpaceWidth) {
availableWidth = videoSpaceWidth;
availableHeight = availableWidth / aspectRatio;
}
return [availableWidth, availableHeight];
}
$(document).ready(function () {
document.title = interfaceConfig.APP_NAME;
if(APIConnector.isEnabled())
APIConnector.init();
if(config.enableWelcomePage && window.location.pathname == "/" &&
(!window.localStorage.welcomePageDisabled
|| window.localStorage.welcomePageDisabled == "false"))
{
$("#videoconference_page").hide();
$("#domain_name").text(
window.location.protocol + "//" + window.location.host + "/");
$("span[name='appName']").text(interfaceConfig.APP_NAME);
if (interfaceConfig.SHOW_JITSI_WATERMARK) {
var leftWatermarkDiv
= $("#welcome_page_header div[class='watermark leftwatermark']");
if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
{
leftWatermarkDiv.css({display: 'block'});
leftWatermarkDiv.parent().get(0).href
= interfaceConfig.JITSI_WATERMARK_LINK;
}
}
if (interfaceConfig.SHOW_BRAND_WATERMARK) {
var rightWatermarkDiv
= $("#welcome_page_header div[class='watermark rightwatermark']");
if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
rightWatermarkDiv.css({display: 'block'});
rightWatermarkDiv.parent().get(0).href
= interfaceConfig.BRAND_WATERMARK_LINK;
rightWatermarkDiv.get(0).style.backgroundImage
= "url(images/rightwatermark.png)";
}
}
if (interfaceConfig.SHOW_POWERED_BY) {
$("#welcome_page_header>a[class='poweredby']")
.css({display: 'block'});
}
function enter_room()
{
var val = $("#enter_room_field").val();
if(!val) {
val = $("#enter_room_field").attr("room_name");
}
if (val) {
window.location.pathname = "/" + val;
}
}
$("#enter_room_button").click(function()
{
enter_room();
});
$("#enter_room_field").keydown(function (event) {
if (event.keyCode === 13 /* enter */) {
enter_room();
}
});
if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
var updateTimeout;
var animateTimeout;
$("#reload_roomname").click(function () {
clearTimeout(updateTimeout);
clearTimeout(animateTimeout);
update_roomname();
});
$("#reload_roomname").show();
function animate(word) {
var currentVal = $("#enter_room_field").attr("placeholder");
$("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
animateTimeout = setTimeout(function() {
animate(word.substring(1, word.length))
}, 70);
}
function update_roomname()
{
var word = RoomNameGenerator.generateRoomWithoutSeparator();
$("#enter_room_field").attr("room_name", word);
$("#enter_room_field").attr("placeholder", "");
clearTimeout(animateTimeout);
animate(word);
updateTimeout = setTimeout(update_roomname, 10000);
}
update_roomname();
}
$("#disable_welcome").click(function () {
window.localStorage.welcomePageDisabled
= $("#disable_welcome").is(":checked");
});
return;
}
if (interfaceConfig.SHOW_JITSI_WATERMARK) {
var leftWatermarkDiv
= $("#largeVideoContainer div[class='watermark leftwatermark']");
leftWatermarkDiv.css({display: 'block'});
leftWatermarkDiv.parent().get(0).href
= interfaceConfig.JITSI_WATERMARK_LINK;
}
if (interfaceConfig.SHOW_BRAND_WATERMARK) {
var rightWatermarkDiv
= $("#largeVideoContainer div[class='watermark rightwatermark']");
rightWatermarkDiv.css({display: 'block'});
rightWatermarkDiv.parent().get(0).href
= interfaceConfig.BRAND_WATERMARK_LINK;
rightWatermarkDiv.get(0).style.backgroundImage
= "url(images/rightwatermark.png)";
}
if (interfaceConfig.SHOW_POWERED_BY) {
$("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
}
$("#welcome_page").hide();
Chat.init();
$('body').popover({ selector: '[data-toggle=popover]',
trigger: 'click hover',
content: function() {
return this.getAttribute("content") +
KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
}
});
statistics.start();
statistics.addAudioLevelListener(audioLevelUpdated);
statistics.addConnectionStatsListener(ConnectionQuality.updateLocalStats);
statistics.addRemoteStatsStopListener(ConnectionQuality.stopSendingStats);
Moderator.init();
// Set the defaults for prompt dialogs.
jQuery.prompt.setDefaults({persistent: false});
// Set default desktop sharing method
setDesktopSharing(config.desktopSharing);
// Initialize Chrome extension inline installs
if (config.chromeExtensionId) {
initInlineInstalls();
}
// By default we use camera
getVideoSize = getCameraVideoSize;
getVideoPosition = getCameraVideoPosition;
VideoLayout.resizeLargeVideoContainer();
$(window).resize(function () {
VideoLayout.resizeLargeVideoContainer();
VideoLayout.positionLarge();
});
// Listen for large video size updates
document.getElementById('largeVideo')
.addEventListener('loadedmetadata', function (e) {
currentVideoWidth = this.videoWidth;
currentVideoHeight = this.videoHeight;
VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
});
document.getElementById('largeVideo').volume = 0;
if (!$('#settings').is(':visible')) {
console.log('init');
init();
} else {
loginInfo.onsubmit = function (e) {
if (e.preventDefault) e.preventDefault();
$('#settings').hide();
init();
};
}
toastr.options = {
"closeButton": true,
"debug": false,
"positionClass": "notification-bottom-right",
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "2000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut",
"reposition": function() {
if(PanelToggler.isVisible()) {
$("#toast-container").addClass("notification-bottom-right-center");
} else {
$("#toast-container").removeClass("notification-bottom-right-center");
}
},
"newestOnTop": false
};
$('#settingsmenu>input').keyup(function(event){
if(event.keyCode === 13) {//enter
SettingsMenu.update();
}
})
});
$(window).bind('beforeunload', function () {
if (connection && connection.connected) {
// ensure signout
$.ajax({
type: 'POST',
url: config.bosh,
async: false,
cache: false,
contentType: 'application/xml',
data: "<body rid='" + (connection.rid || connection._proto.rid)
+ "' xmlns='http://jabber.org/protocol/httpbind' sid='"
+ (connection.sid || connection._proto.sid)
+ "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
success: function (data) {
console.log('signed out');
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('signout error', textStatus + ' (' + errorThrown + ')');
}
});
}
disposeConference(true);
if(APIConnector.isEnabled())
APIConnector.dispose();
});
function disposeConference(onUnload) {
Toolbar.showAuthenticateButton(false);
var handler = getConferenceHandler();
if (handler && handler.peerconnection) {
// FIXME: probably removing streams is not required and close() should
// be enough
if (connection.jingle.localAudio) {
handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
}
if (connection.jingle.localVideo) {
handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
}
handler.peerconnection.close();
}
statistics.onDisposeConference(onUnload);
activecall = null;
}
function dump(elem, filename) {
elem = elem.parentNode;
elem.download = filename || 'meetlog.json';
elem.href = 'data:application/json;charset=utf-8,\n';
var data = populateData();
elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
return false;
}
/**
* Populates the log data
*/
function populateData() {
var data = {};
if (connection.jingle) {
Object.keys(connection.jingle.sessions).forEach(function (sid) {
var session = connection.jingle.sessions[sid];
if (session.peerconnection && session.peerconnection.updateLog) {
// FIXME: should probably be a .dump call
data["jingle_" + session.sid] = {
updateLog: session.peerconnection.updateLog,
stats: session.peerconnection.stats,
url: window.location.href
};
}
});
}
var metadata = {};
metadata.time = new Date();
metadata.url = window.location.href;
metadata.ua = navigator.userAgent;
if (connection.logger) {
metadata.xmpp = connection.logger.log;
}
data.metadata = metadata;
return data;
}
/**
* Changes the style class of the element given by id.
*/
function buttonClick(id, classname) {
$(id).toggleClass(classname); // add the class to the clicked element
}
/**
* Locks / unlocks the room.
*/
function lockRoom(lock) {
if (lock)
connection.emuc.lockRoom(sharedKey);
else
connection.emuc.lockRoom('');
}
/**
* Sets the shared key.
*/
function setSharedKey(sKey) {
sharedKey = sKey;
}
/**
* Updates the room invite url.
*/
function updateRoomUrl(newRoomUrl) {
roomUrl = newRoomUrl;
// If the invite dialog has been already opened we update the information.
var inviteLink = document.getElementById('inviteLinkRef');
if (inviteLink) {
inviteLink.value = roomUrl;
inviteLink.select();
document.getElementById('jqi_state0_buttonInvite').disabled = false;
}
}
/**
* Warning to the user that the conference window is about to be closed.
*/
function closePageWarning() {
/*
FIXME: do we need a warning when the focus is a server-side one now ?
if (focus !== null)
return "You are the owner of this conference call and"
+ " you are about to end it.";
else*/
return "You are about to leave this conversation.";
}
/**
* Resizes and repositions videos in full screen mode.
*/
$(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
function () {
VideoLayout.resizeLargeVideoContainer();
VideoLayout.positionLarge();
isFullScreen = document.fullScreen ||
document.mozFullScreen ||
document.webkitIsFullScreen;
}
);
$(document).bind('error.jingle',
function (event, session, error)
{
console.error("Jingle error", error);
}
);
$(document).bind('fatalError.jingle',
function (event, session, error)
{
sessionTerminated = true;
connection.emuc.doLeave();
messageHandler.showError( "Sorry",
"Internal application error[setRemoteDescription]");
}
);
function callSipButtonClicked()
{
var defaultNumber
= config.defaultSipNumber ? config.defaultSipNumber : '';
messageHandler.openTwoButtonDialog(null,
'<h2>Enter SIP number</h2>' +
'<input id="sipNumber" type="text"' +
' value="' + defaultNumber + '" autofocus>',
false,
"Dial",
function (e, v, m, f) {
if (v) {
var numberInput = document.getElementById('sipNumber');
if (numberInput.value) {
connection.rayo.dial(
numberInput.value, 'fromnumber', roomName);
}
}
},
function (event) {
document.getElementById('sipNumber').focus();
}
);
}
function hangup() {
disposeConference();
sessionTerminated = true;
connection.emuc.doLeave();
if(config.enableWelcomePage)
{
setTimeout(function()
{
window.localStorage.welcomePageDisabled = false;
window.location.pathname = "/";
}, 10000);
}
$.prompt("Session Terminated",
{
title: "You hung up the call",
persistent: true,
buttons: {
"Join again": true
},
closeText: '',
submit: function(event, value, message, formVals)
{
window.location.reload();
return false;
}
}
);
}
| mit |
manibs/StoreManage | Models/productModel.js | 286 | var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var productModel = new Schema({
skuid: {
type: String
},
name: {
type: String
},
category: {
type: String
}
});
module.exports = mongoose.model('Product', productModel); | mit |
gilday/mobtown | mobtown-services/src/main/java/mobtown/services/jaxrs/EventNotFoundExceptionMapper.java | 756 | package mobtown.services.jaxrs;
import mobtown.services.EventNotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* Maps custom exceptions which do not extend {@link javax.ws.rs.WebApplicationException}
*/
@Provider
public class EventNotFoundExceptionMapper implements ExceptionMapper<EventNotFoundException> {
@Override
public Response toResponse(final EventNotFoundException e) {
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN)
.entity("There exists no event with the special event permit id " + e.getId())
.build();
}
}
| mit |
webmasterersm/rsmsite | wp-content/themes/rsm-megasite/page-evento.php | 2765 | <?php
/**
* Template Name: Eventos
*
* @package WordPress
* @subpackage RSM Megasite
* @since RSM Megasite
*/
get_header(); ?>
<main class="main-eventos">
<?php while ( have_posts() ) : the_post(); ?>
<?php $thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size', true); ?>
<div class="page-name" style="background:url(<?php echo $thumb_url[0]; ?>)">
<div class="title-page">
<h1 class="animated fadeInLeft"><?php the_title(); ?></h1>
</div>
</div>
<?php endwhile; ?>
<section class="eventos">
<div class="container">
<?php $today = date('Y-m-d');
$args = array(
'post_type' => 'eventos',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_date',
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
),
),
);
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) :
while( $wp_query->have_posts() ) : $wp_query->the_post();
$event = get_field('event_date');
$today = date('Y-m-d'); ?>
<div class="evento">
<div class="date_place">
<?php
$date = get_field('event_date');
$date = new DateTime($date);
?>
<div class="fecha"><?php echo $date->format('d/M'); ?></div>
<div class="event_time">
<?php the_field('hour_entry'); ?> - <?php the_field('departured_hour'); ?>
</div>
</div>
<div class="date_time">
<div class="event_place">
<?php the_title(); ?>
</div>
<div class="event_description">
<?php the_field('event_location'); ?>
</div>
</div>
</div>
<?php endwhile; wp_reset_postdata();
else: ?>
<p>No eventos...</p>
<?php endif; ?>
</div>
</section>
</main>
<?php get_footer() ?> | mit |
jovanidash21/jandy | assets/scripts/main.js | 6731 | // Global varianbles
/*global Waypoint, lightbox, WOW */
// Detect IE version
var detectIEVersion = function() {
var userAgent = window.navigator.userAgent;
var internetExplorer = userAgent.indexOf('MSIE ');
if (internetExplorer > 0) {
return parseInt(userAgent.substring(internetExplorer + 5, userAgent.indexOf('.', internetExplorer)));
}
var trident = userAgent.indexOf('Trident/');
if (trident > 0) {
var rv = userAgent.indexOf('rv:');
return parseInt( userAgent.substring(rv + 3, userAgent.indexOf('.', rv)));
}
var edge = userAgent.indexOf('Edge/');
if (edge > 0) {
return parseInt(userAgent.substring(edge + 5, userAgent.indexOf('.', edge)));
}
return false;
};
var IEVersion = detectIEVersion();
var calculateScrollBarWidth = function() {
var scrollBarDiv = document.createElement('div');
scrollBarDiv.className = 'modal-scrollbar-measure';
$(document.body).append(scrollBarDiv);
var scrollBarWidth = scrollBarDiv.offsetWidth - scrollBarDiv.clientWidth;
$(document.body)[0].removeChild(scrollBarDiv);
return scrollBarWidth;
};
var scrollBarWidth = calculateScrollBarWidth();
// Body
var body = $('body');
$(window).load(function() {
$(".loader").fadeOut("slow");
})
$(document).ready(function() {
// Nav bar section
var navBarSection = body.find('.nav-bar-section');
if (navBarSection.length) {
navBarSection.find('.navbar-nav').onePageNav({
changeHash: true,
scrollSpeed: 400
});
navBarSection.find('.navbar-fixed-top').autoHidingNavbar({
hideOffset: 210
});
navBarSection.find('a.dropdown-toggle').hover(function(e) {
var _this = $(this);
var parent = _this.offsetParent('.dropdown-menu');
_this.parent('li').toggleClass('open');
if(!parent.parent().hasClass('nav')) {
_this.next().css({'top': _this[0].offsetTop, 'left': parent.outerWidth() - 4});
}
$('.nav li.open').not(_this.parents('li')).removeClass('open');
return false;
});
}
// Hero slider section
var heroSliderSection = body.find('.hero-slider-section');
if (heroSliderSection.length) {
var heroSlider = heroSliderSection.find('.owl-carousel');
var heroTitle = heroSlider.find('.hero-title');
var heroSubtitle = heroSlider.find('.hero-subtitle');
var animated = 'animated ';
var heroTitleAnimation = animated + heroTitle.data('animation');
var heroSubtitleAnimation = animated + heroSubtitle.data('animation');
var heroTitleDelay = heroTitle.data('delay');
var heroSubtitleDelay = heroSubtitle.data('delay');
setTimeout(function () {
heroTitle.addClass('animated ' + heroTitleAnimation);
}, heroTitleDelay
);
setTimeout(function () {
heroSubtitle.addClass('animated ' + heroSubtitleAnimation);
}, heroSubtitleDelay
);
heroSlider.owlCarousel({
autoplay: true,
autoplayHoverPause: true,
autoplayTimeout: 5000,
dots: false,
items: 1,
loop: true,
nav: true,
navText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
}).on('change.owl.carousel', function(event) {
heroTitle.removeClass('animated ' + heroTitleAnimation);
heroSubtitle.removeClass('animated ' + heroSubtitleAnimation);
heroSlider.find('.owl-item.cloned').find('.hero-title').removeClass(heroTitleAnimation);
heroSlider.find('.owl-item.cloned').find('.hero-subtitle').removeClass(heroSubtitleAnimation);
}).on('changed.owl.carousel', function(event) {
setTimeout(function () {
heroSlider.find('.owl-item.active').find('.hero-title').addClass(heroTitleAnimation);
}, heroTitleDelay
);
setTimeout(function () {
heroSlider.find('.owl-item.active').find('.hero-subtitle').addClass(heroSubtitleAnimation);
}, heroSubtitleDelay
);
});
}
// Gallery section
var gallerySection = body.find('.gallery-section');
if (gallerySection.length) {
if (!$('.lb-outerContainer').parent().hasClass('lb-wrapper')) {
$('.lb-outerContainer').wrap( "<div class='lb-wrapper'></div>" );
}
gallerySection.find('a[data-lightbox="main-gallery"]').on('click', function() {
$('body').css('padding-right', scrollBarWidth);
$('#lightboxOverlay, .lb-loader, .lb-close').on('click', function() {
$('body').css('padding-right', '0');
});
$('.lb-wrapper').on('click', function() {
$('body').css('padding-right', '0');
$('.lb-close').click();
});
});
}
// Services section
var servicesSection = body.find('.services-section');
if (servicesSection.length) {
servicesSection.find('.service-card .service-description').matchHeight();
}
// Counter section
var counterSection = body.find('.counter-section');
if (counterSection.length) {
var counterSectionWaypoint = new Waypoint({
element: counterSection,
handler: function() {
counterSection.find('.counter').countTo({
refreshInterval: 11,
speed: 900
});
this.destroy();
},
offset: '211px'
});
}
// Testimonials section
var testimonialsSection = body.find('.testimonials-section');
if (testimonialsSection.length) {
testimonialsSection.find('.owl-carousel').owlCarousel({
animateIn: 'fadeIn',
autoplay: true,
autoplayTimeout: 5000,
dots: false,
items: 1,
loop: true,
nav: true,
navText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
});
}
// Sponsors section
var sponsorsSection = body.find('.sponsors-section');
if (sponsorsSection.length) {
var sponsorsSLider = sponsorsSection.find('.owl-carousel');
sponsorsSLider.owlCarousel({
autoplay: true,
autoplayTimeout: 3000,
responsive:{
0:{
items: 1
},
500:{
items: 3
},
1000:{
items: 5
}
}
}).on('mousewheel', '.owl-stage', function (e) {
if (e.deltaY>0) {
sponsorsSLider.trigger('next.owl');
} else {
sponsorsSLider.trigger('prev.owl');
}
e.preventDefault();
});
}
// Lightbox Config
lightbox.option({
disableScrolling: true
});
// ScrollUp Config
$(function () {
$.scrollUp({
animation: 'slide',
scrollDistance: 400,
scrollSpeed: 400,
scrollText: "<i class='fa fa-angle-up fa-4x'></i>"
});
});
// jQuery stellar config
$.stellar({
responsive: true
});
// Wow js Config
var wow = body.find('.wow');
if (wow.length) {
new WOW().init();
}
});
| mit |