code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
import random color_names=[ 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgreen', 'lightgray', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen', ] def getRandomColors(num): if num > len(color_names): return color_names ns = set() while num > len(ns): ns.add(random.choice(color_names)) return list(ns)
largetalk/tenbagger
draw/colors.py
Python
mit
2,176
using System.Collections.Generic; using System.Text; namespace SourceGenerators { internal static class Templates { public static string AppRoutes(IEnumerable<string> allRoutes) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class AppRoutes { public static ReadOnlyCollection<string> Routes { get; } = new ReadOnlyCollection<string>( new List<string> { "); foreach (var route in allRoutes) { sb.AppendLine($"\"{route}\","); } sb.Append(@" } ); } }"); return sb.ToString(); } public static string PageDetail() { return @" namespace BlazorApp1 { public record PageDetail(string Route, string Title, string Icon); } "; } public static string MenuItemAttribute() { return @" namespace BlazorApp1 { public class MenuItemAttribute : System.Attribute { public string Icon { get; } public string Description { get; } public int Order { get; } public MenuItemAttribute( string icon, string description, int order = 0 ) { Icon = icon; Description = description; Order = order; } } } "; } public static string MenuPages(IEnumerable<RouteableComponent> pages) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class PageDetails { public static ReadOnlyCollection<PageDetail> MenuPages { get; } = new ReadOnlyCollection<PageDetail>( new List<PageDetail> { "); foreach (var page in pages) { sb.AppendLine($"new PageDetail(\"{page.Route}\", \"{page.Title}\", \"{page.Icon}\"),"); } sb.Append(@" } ); } }"); return sb.ToString(); } } }
andrewlock/blog-examples
BlazorPreRender/BlazorApp1/SourceGenerators/Templates.cs
C#
mit
2,345
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </meta> <meta content="width=device-width, initial-scale=1" name="viewport"> </meta> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> </link> <link href="../../resources/stof-style.css" rel="stylesheet"> </link> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script> <script src="../../resources/search.js"> </script> <script src="../../resources/analytics.js"> </script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button aria-expanded="false" class="navbar-toggle collapsed" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button"> <span class="sr-only"> Toggle navigation </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> </button> <a class="navbar-brand" href="../../index.html"> Bob Dylan Lyrics </a> </div> <div aria-expanded="false" class="navbar-collapse collapse" id="bs-example-navbar-collapse-1" style="height: 1px"> <ul class="nav navbar-nav"> <li> <a href="../../full_lyrics_file_dumps/downloads.html"> Downloads </a> </li> <li> <a href="../../songs/song_index/song_index.html"> All Songs </a> </li> <li> <a href="../../albums/album_index/album_index.html"> All Albums </a> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 1960s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/bob_dylan.html"> Bob Dylan (1962) </a> </li> <li> <a class="album" href="../../albums/the_freewheelin_bob_dylan.html"> The Freewheelin' Bob Dylan (1963) </a> </li> <li> <a class="album" href="../../albums/the_times_they_are_a-changin.html"> The Times They Are A-Changin' (1964) </a> </li> <li> <a class="album" href="../../albums/another_side_of_bob_dylan.html"> Another Side of Bob Dylan (1964) </a> </li> <li> <a class="album" href="../../albums/bringing_it_all_back_home.html"> Bringing It All Back Home (1965) </a> </li> <li> <a class="album" href="../../albums/highway_61_revisited.html"> Highway 61 Revisited (1965) </a> </li> <li> <a class="album" href="../../albums/blonde_on_blonde.html"> Blonde on Blonde (1966)) </a> </li> <li> <a class="album" href="../../albums/bob_dylans_greatest_hits.html"> Bob Dylan's Greatest Hits (1967) </a> </li> <li> <a class="album" href="../../albums/john_wesley_harding.html"> John Wesley Harding (1967) </a> </li> <li> <a class="album" href="../../albums/nashville_skyline.html"> Nashville Skyline (1969) </a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 1970s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/self_portrait.html"> Self Portrait (1970) </a> </li> <li> <a class="album" href="../../albums/new_morning.html"> New Morning (1970) </a> </li> <li> <a class="album" href="../../albums/bob_dylans_greatest_hits_vol_ii.html"> Bob Dylan's Greatest Hits, Vol. II (1971) </a> </li> <li> <a class="album" href="../../albums/pat_garrett_and_billy_the_kid.html"> Pat Garrett &amp; Billy the Kid (1973) </a> </li> <li> <a class="album" href="../../albums/dylan.html"> Dylan (1973) </a> </li> <li> <a class="album" href="../../albums/planet_waves.html"> Planet Waves (1974) </a> </li> <li> <a class="album" href="../../albums/before_the_flood.html"> Before the Flood (1974) </a> </li> <li> <a class="album" href="../../albums/blood_on_the_tracks.html"> Blood on the Tracks (1975) </a> </li> <li> <a class="album" href="../../albums/the_basement_tapes.html"> The Basement Tapes (1975) </a> </li> <li> <a class="album" href="../../albums/desire.html"> Desire (1976) </a> </li> <li> <a class="album" href="../../albums/hard_rain.html"> Hard Rain (1976) </a> </li> <li> <a class="album" href="../../albums/street_legal.html"> Street-Legal (1978) </a> </li> <li> <a class="album" href="../../albums/bob_dylan_at_budokan.html"> Bob Dylan at Budokan (1979) </a> </li> <li> <a class="album" href="../../albums/slow_train_coming.html"> Slow Train Coming (1979) </a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 1980s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/saved.html"> Saved (1980) </a> </li> <li> <a class="album" href="../../albums/shot_of_love.html"> Shot of Love (1981) </a> </li> <li> <a class="album" href="../../albums/infidels.html"> Infidels (1983) </a> </li> <li> <a class="album" href="../../albums/real_live_1.html"> Real Live (1984) </a> </li> <li> <a class="album" href="../../albums/empire_burlesque.html"> Empire Burlesque (1985) </a> </li> <li> <a class="album" href="../../albums/biograph.html"> Biograph (1985) </a> </li> <li> <a class="album" href="../../albums/knocked_out_loaded.html"> Knocked Out Loaded (1986) </a> </li> <li> <a class="album" href="../../albums/down_in_the_groove.html"> Down in the Groove (1988) </a> </li> <li> <a class="album" href="../../albums/dylan_and_the_dead.html"> Dylan &amp; the Dead (1989) </a> </li> <li> <a class="album" href="../../albums/oh_mercy.html"> Oh Mercy (1989) </a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 1990s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/under_the_red_sky.html"> Under the Red Sky (1990) </a> </li> <li> <a class="album" href="../../albums/the_bootleg_series_volumes_1-3_rare_and_unreleased_1961-1991.html"> The Bootleg Series Volumes 1-3 (Rare &amp; Unreleased) 1961-1991 (1991) </a> </li> <li> <a class="album" href="../../albums/good_as_i_been_to_you.html"> Good As I Been to You (1992) </a> </li> <li> <a class="album" href="../../albums/world_gone_wrong.html"> World Gone Wrong (1993) </a> </li> <li> <a class="album" href="../../albums/bob_dylans_greatest_hits_volume_3.html"> Bob Dylan's Greatest Hits Volume 3 (1994) </a> </li> <li> <a class="album" href="../../albums/mtv_unplugged.html"> MTV Unplugged (1995) </a> </li> <li> <a class="album" href="../../albums/time_out_of_mind.html"> Time Out of Mind (1997) </a> </li> <li> <a class="album" href="../../albums/the_bootleg_series_vol_4_bob_dylan_live_1966.html"> The Bootleg Series Vol. 4: Bob Dylan Live 1966, The "Royal Albert Hall" Concert (1998) </a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 2000s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/the_essential_bob_dylan.html"> The Essential Bob Dylan (2000) </a> </li> <li> <a class="album" href="../../albums/love_and_theft.html"> Love and Theft (2001) </a> </li> <li> <a class="album" href="../../albums/the_bootleg_series_vol_5_bob_dylan_live_1975_the_rolling_thunder_revue.html"> The Bootleg Series Vol. 5: Bob Dylan Live 1975, The Rolling Thunder Revue (2002) </a> </li> <li> <a class="album" href="../../albums/the_bootleg_series_vol_6_bob_dylan_live_1964_concert_at_philharmonic_hall.html"> The Bootleg Series Vol. 6: Bob Dylan Live 1964, Concert at Philharmonic Hall (2004) </a> </li> <li> <a class="album" href="../../albums/the_best_of_bob_dylan.html"> The Best of Bob Dylan (2005) </a> </li> <li> <a class="album" href="../../albums/modern_times.html"> Modern Times (2006) </a> </li> <li> <a class="album" href="../../albums/together_through_life.html"> Together through Life (2009) </a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button"> 2010s <span class="caret"> </span> </a> <ul class="dropdown-menu"> <li> <a class="album" href="../../albums/tempest.html"> Tempest (2012) </a> </li> </ul> </li> </ul> <div class="col-md-3" style="border:0px solid;width:30%;height:auto;"> <gcse:search> <form class="navbar-form navbar-right" role="search"> </form> </gcse:search> </div> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-md-12"> <h1> Jokerman </h1> </div> </div> <div class="row"> <div class="col-md-12"> <p> <div> Standing on the water, casting your bread </div> <div> While the eyes of the idol with the iron head are glowing. </div> <div> Distant ships sailing in through the mist, </div> <div> You were born with a snake in both of your fists while a hurricane was blowing. </div> <div> Freedom, just around the corner for you, </div> <div> But, with the truth so far off, what good will it do? </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> <p> <div> So swiftly the sun sets in the sky, </div> <div> You rise up and say goodbye to no one. </div> <div> Fools rush in where angels fear to tread, </div> <div> Both of their futures so full of dread -- you don't show one. </div> <div> Shedding off one more layer of skin, </div> <div> Keeping one step ahead from the persecutor within. </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> <p> <div> You're a man of the mountains, you can walk on the clouds, </div> <div> Manipulator of crowds, you're a dream-twister. </div> <div> You're going to Sodom and Gomorrah, </div> <div> But what do you care? Ain't nobody there would want to marry your sister! </div> <div> Friend to the martyr, a friend to the woman of shame, </div> <div> You look into the fiery furnace, see the rich man without any name. </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> <p> <div> Well, the Book of Leviticus and Deuteronomy, </div> <div> The law of the jungle and the sea are your only teachers. </div> <div> In the smoke of the twilight, on a milk-white steed, </div> <div> Michelangelo indeed could've carved out your features. </div> <div> Resting in the fields, far from the turbulent space, </div> <div> Half asleep 'neath the stars with a small dog licking your face. </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> <p> <div> Well, the rifleman's stalking the sick and the lame, </div> <div> Preacherman seeks the same -- who'll get there first is uncertain. </div> <div> Night-sticks and water-cannons, tear gas, padlocks, </div> <div> Molotov cocktails and rocks behind every curtain. </div> <div> False-hearted judges dying in the webs that they spin, </div> <div> Only a matter of time till night comes stepping in. </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> <p> <div> It's a shadowy world, skies are slippery gray, </div> <div> A woman just gave birth to a prince today and dressed him in scarlet. </div> <div> He'll put the priest in his pocket, put the blade to the heat, </div> <div> Take the motherless children off the street, </div> <div> And place them at the feet of a harlot. </div> <div> Oh, Jokerman, you know what he wants, </div> <div> Oh, Jokerman, you don't show any response. </div> <div> Jokerman, dance to the nightingale tune, </div> <div> Bird, fly high by the light of the moon, </div> <div> Oh, oh, oh, Jokerman. </div> </p> </div> </div> </div> </body> </html>
mulhod/bob_dylan_lyrics
songs/html/jokerman_1.html
HTML
mit
13,790
#region Copyright //-------------------------------------------------------------------------------------------------------- // <copyright file="RecentChanges.ascx.cs" company="DNN Corp®"> // DNN Corp® - http://www.dnnsoftware.com Copyright (c) 2002-2013 by DNN Corp® // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> ////-------------------------------------------------------------------------------------------------------- #endregion Copyright using DotNetNuke.Services.Localization; using DotNetNuke.Wiki.Utilities; namespace DotNetNuke.Wiki.Views { /// <summary> /// Recent changes class based on WikiModuleBase /// </summary> public partial class RecentChanges : WikiModuleBase { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="RecentChanges"/> class. /// </summary> public RecentChanges() { this.Load += this.Page_Load; } #endregion Constructor #region Events /// <summary> /// Handles the Click event of the Last 7 Days control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast7Days_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(7); } /// <summary> /// Handles the Click event of the Last 24 hours control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast24Hrs_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(1); } /// <summary> /// Handles the Click event of the Last Month control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLastMonth_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(31); } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event /// data.</param> public new void Page_Load(object sender, System.EventArgs e) { this.LoadLocalization(); if (!this.IsPostBack) { this.HitTable.Text = this.CreateRecentChangeTable(1); } } #endregion Events #region Methods /// <summary> /// Loads the localization. /// </summary> private void LoadLocalization() { this.TitleLbl.Text = Localization.GetString("RCTitle", this.RouterResourceFile); this.cmdLast24Hrs.Text = Localization.GetString("RCLast24h", this.RouterResourceFile); this.cmdLast7Days.Text = Localization.GetString("RCLast7d", this.RouterResourceFile); this.cmdLastMonth.Text = Localization.GetString("RCLastMonth", this.RouterResourceFile); } #endregion Methods } }
DNNCommunity/DNN.Wiki
Views/RecentChanges.ascx.cs
C#
mit
4,659
// -------------------------------------------------------------------------------------------------------------------- // <auto-generated> // Generated using OBeautifulCode.CodeGen.ModelObject (1.0.177.0) // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.Domain.Test { using global::System; using global::System.CodeDom.Compiler; using global::System.Collections.Concurrent; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Diagnostics.CodeAnalysis; using global::System.Globalization; using global::System.Linq; using global::System.Reflection; using global::FakeItEasy; using global::OBeautifulCode.Assertion.Recipes; using global::OBeautifulCode.AutoFakeItEasy; using global::OBeautifulCode.CodeGen.ModelObject.Recipes; using global::OBeautifulCode.Equality.Recipes; using global::OBeautifulCode.Math.Recipes; using global::OBeautifulCode.Reflection.Recipes; using global::OBeautifulCode.Representation.System; using global::OBeautifulCode.Serialization; using global::OBeautifulCode.Serialization.Recipes; using global::OBeautifulCode.Type; using global::Xunit; using static global::System.FormattableString; public static partial class GetNextUniqueLongOpTest { private static readonly StringRepresentationTestScenarios<GetNextUniqueLongOp> StringRepresentationTestScenarios = new StringRepresentationTestScenarios<GetNextUniqueLongOp>() .AddScenario(() => new StringRepresentationTestScenario<GetNextUniqueLongOp> { Name = "Default Code Generated Scenario", SystemUnderTestExpectedStringRepresentationFunc = () => { var systemUnderTest = A.Dummy<GetNextUniqueLongOp>(); var result = new SystemUnderTestExpectedStringRepresentation<GetNextUniqueLongOp> { SystemUnderTest = systemUnderTest, ExpectedStringRepresentation = Invariant($"Naos.Database.Domain.GetNextUniqueLongOp: Details = {systemUnderTest.Details?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}."), }; return result; }, }); private static readonly ConstructorArgumentValidationTestScenarios<GetNextUniqueLongOp> ConstructorArgumentValidationTestScenarios = new ConstructorArgumentValidationTestScenarios<GetNextUniqueLongOp>() .AddScenario(() => new ConstructorArgumentValidationTestScenario<GetNextUniqueLongOp> { Name = "constructor should throw ArgumentNullException when parameter 'details' is null scenario", ConstructionFunc = () => { var result = new GetNextUniqueLongOp( null); return result; }, ExpectedExceptionType = typeof(ArgumentNullException), ExpectedExceptionMessageContains = new[] { "details", }, }) .AddScenario(() => new ConstructorArgumentValidationTestScenario<GetNextUniqueLongOp> { Name = "constructor should throw ArgumentException when parameter 'details' is white space scenario", ConstructionFunc = () => { var result = new GetNextUniqueLongOp( Invariant($" {Environment.NewLine} ")); return result; }, ExpectedExceptionType = typeof(ArgumentException), ExpectedExceptionMessageContains = new[] { "details", "white space", }, }); private static readonly ConstructorPropertyAssignmentTestScenarios<GetNextUniqueLongOp> ConstructorPropertyAssignmentTestScenarios = new ConstructorPropertyAssignmentTestScenarios<GetNextUniqueLongOp>() .AddScenario(() => new ConstructorPropertyAssignmentTestScenario<GetNextUniqueLongOp> { Name = "Details should return same 'details' parameter passed to constructor when getting", SystemUnderTestExpectedPropertyValueFunc = () => { var referenceObject = A.Dummy<GetNextUniqueLongOp>(); var result = new SystemUnderTestExpectedPropertyValue<GetNextUniqueLongOp> { SystemUnderTest = new GetNextUniqueLongOp( referenceObject.Details), ExpectedPropertyValue = referenceObject.Details, }; return result; }, PropertyName = "Details", }); private static readonly DeepCloneWithTestScenarios<GetNextUniqueLongOp> DeepCloneWithTestScenarios = new DeepCloneWithTestScenarios<GetNextUniqueLongOp>() .AddScenario(() => new DeepCloneWithTestScenario<GetNextUniqueLongOp> { Name = "DeepCloneWithDetails should deep clone object and replace Details with the provided details", WithPropertyName = "Details", SystemUnderTestDeepCloneWithValueFunc = () => { var systemUnderTest = A.Dummy<GetNextUniqueLongOp>(); var referenceObject = A.Dummy<GetNextUniqueLongOp>().ThatIs(_ => !systemUnderTest.Details.IsEqualTo(_.Details)); var result = new SystemUnderTestDeepCloneWithValue<GetNextUniqueLongOp> { SystemUnderTest = systemUnderTest, DeepCloneWithValue = referenceObject.Details, }; return result; }, }); private static readonly GetNextUniqueLongOp ReferenceObjectForEquatableTestScenarios = A.Dummy<GetNextUniqueLongOp>(); private static readonly EquatableTestScenarios<GetNextUniqueLongOp> EquatableTestScenarios = new EquatableTestScenarios<GetNextUniqueLongOp>() .AddScenario(() => new EquatableTestScenario<GetNextUniqueLongOp> { Name = "Default Code Generated Scenario", ReferenceObject = ReferenceObjectForEquatableTestScenarios, ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new GetNextUniqueLongOp[] { new GetNextUniqueLongOp( ReferenceObjectForEquatableTestScenarios.Details), }, ObjectsThatAreNotEqualToReferenceObject = new GetNextUniqueLongOp[] { new GetNextUniqueLongOp( A.Dummy<GetNextUniqueLongOp>().Whose(_ => !_.Details.IsEqualTo(ReferenceObjectForEquatableTestScenarios.Details)).Details), }, ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new object[] { A.Dummy<object>(), A.Dummy<string>(), A.Dummy<int>(), A.Dummy<int?>(), A.Dummy<Guid>(), A.Dummy<CancelRunningHandleRecordOp>(), A.Dummy<CompleteRunningHandleRecordOp>(), A.Dummy<CreateDatabaseOp>(), A.Dummy<DeleteDatabaseOp>(), A.Dummy<DisableHandlingForRecordOp>(), A.Dummy<DisableHandlingForStreamOp>(), A.Dummy<DoesAnyExistByIdOp<Version>>(), A.Dummy<EnableHandlingForStreamOp>(), A.Dummy<FailRunningHandleRecordOp>(), A.Dummy<GetAllRecordsByIdOp<Version>>(), A.Dummy<GetAllRecordsMetadataByIdOp<Version>>(), A.Dummy<GetAllResourceLocatorsOp>(), A.Dummy<GetCompositeHandlingStatusByIdsOp>(), A.Dummy<GetCompositeHandlingStatusByIdsOp<Version>>(), A.Dummy<GetCompositeHandlingStatusByTagsOp>(), A.Dummy<GetDistinctIdsOp<Version>>(), A.Dummy<GetHandlingHistoryOp>(), A.Dummy<GetHandlingStatusOp>(), A.Dummy<GetLatestObjectByIdOp<Version, Version>>(), A.Dummy<GetLatestObjectByTagsOp<Version>>(), A.Dummy<GetLatestObjectOp<Version>>(), A.Dummy<GetLatestRecordByIdOp<Version, Version>>(), A.Dummy<GetLatestRecordByIdOp<Version>>(), A.Dummy<GetLatestRecordMetadataByIdOp<Version>>(), A.Dummy<GetLatestRecordOp<Version>>(), A.Dummy<GetLatestStringSerializedObjectByIdOp<Version>>(), A.Dummy<GetResourceLocatorByIdOp<Version>>(), A.Dummy<GetResourceLocatorForUniqueIdentifierOp>(), A.Dummy<GetStreamFromRepresentationOp>(), A.Dummy<GetStreamFromRepresentationOp<FileStreamRepresentation, MemoryStandardStream>>(), A.Dummy<HandleRecordOp>(), A.Dummy<HandleRecordOp<Version>>(), A.Dummy<HandleRecordWithIdOp<Version, Version>>(), A.Dummy<HandleRecordWithIdOp<Version>>(), A.Dummy<PruneBeforeInternalRecordDateOp>(), A.Dummy<PruneBeforeInternalRecordIdOp>(), A.Dummy<PutAndReturnInternalRecordIdOp<Version>>(), A.Dummy<PutOp<Version>>(), A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>(), A.Dummy<PutWithIdOp<Version, Version>>(), A.Dummy<ResetFailedHandleRecordOp>(), A.Dummy<SelfCancelRunningHandleRecordOp>(), A.Dummy<StandardCreateStreamOp>(), A.Dummy<StandardDeleteStreamOp>(), A.Dummy<StandardGetDistinctStringSerializedIdsOp>(), A.Dummy<StandardGetHandlingHistoryOp>(), A.Dummy<StandardGetHandlingStatusOp>(), A.Dummy<StandardGetInternalRecordIdsOp>(), A.Dummy<StandardGetLatestRecordOp>(), A.Dummy<StandardGetLatestStringSerializedObjectOp>(), A.Dummy<StandardGetNextUniqueLongOp>(), A.Dummy<StandardPruneStreamOp>(), A.Dummy<StandardPutRecordOp>(), A.Dummy<StandardTryHandleRecordOp>(), A.Dummy<StandardUpdateHandlingStatusForRecordOp>(), A.Dummy<StandardUpdateHandlingStatusForStreamOp>(), A.Dummy<ThrowIfResourceUnavailableOp>(), A.Dummy<TryHandleRecordOp<Version>>(), A.Dummy<TryHandleRecordWithIdOp<Version, Version>>(), A.Dummy<TryHandleRecordWithIdOp<Version>>(), }, }); [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Structural { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetNextUniqueLongOp___Should_implement_IModel_of_GetNextUniqueLongOp___When_reflecting() { // Arrange var type = typeof(GetNextUniqueLongOp); var expectedModelMethods = typeof(IModel<GetNextUniqueLongOp>).GetInterfaceDeclaredAndImplementedMethods(); var expectedModelMethodHashes = expectedModelMethods.Select(_ => _.GetSignatureHash()); // Act var actualInterfaces = type.GetInterfaces(); var actualModelMethods = type.GetMethodsFiltered(MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public).ToList(); var actualModelMethodHashes = actualModelMethods.Select(_ => _.GetSignatureHash()); // Assert actualInterfaces.AsTest().Must().ContainElement(typeof(IModel<GetNextUniqueLongOp>)); expectedModelMethodHashes.Except(actualModelMethodHashes).AsTest().Must().BeEmptyEnumerable(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetNextUniqueLongOp___Should_be_attributed_with_Serializable____When_reflecting() { // Arrange var type = typeof(GetNextUniqueLongOp); // Act var actualAttributes = type.GetCustomAttributes(typeof(SerializableAttribute), false); // Assert actualAttributes.AsTest().Must().NotBeEmptyEnumerable(); } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class StringRepresentation { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void ToString___Should_generate_friendly_string_representation_of_object___When_called() { var scenarios = StringRepresentationTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.SystemUnderTest.ToString(); // Assert actual.AsTest().Must().BeEqualTo(scenario.ExpectedStringRepresentation, because: scenario.Id); } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Constructing { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Constructor___Should_throw___When_parameters_are_not_valid() { var scenarios = ConstructorArgumentValidationTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = Record.Exception(scenario.ConstructionFunc); // Assert actual.AsTest().Must().BeOfType(scenario.ExpectedExceptionType, because: scenario.Id); foreach(var expected in scenario.ExpectedExceptionMessageContains ?? new List<string>()) { actual.Message.AsTest().Must().ContainString(expected, because: scenario.Id); } if (scenario.ExpectedExceptionMessageEquals != null) { actual.Message.AsTest().Must().BeEqualTo(scenario.ExpectedExceptionMessageEquals, because: scenario.Id); } } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "referenceObject")] public static void Properties___Should_be_assigned_by_constructor_to_expected_value___When_getting() { var scenarios = ConstructorPropertyAssignmentTestScenarios.ValidateAndPrepareForTesting(); var asTestMethodInfo = typeof(WorkflowExtensions).GetMethodFiltered(nameof(WorkflowExtensions.AsTest)); var beEqualToMethodInfo = typeof(Verifications).GetMethodFiltered(nameof(Verifications.BeEqualTo)); foreach (var scenario in scenarios) { // Arrange if ((scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.NoPropertiesAssignedInConstructorScenarioPropertyName) || (scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.ForceGeneratedTestsToPassAndWriteMyOwnScenarioPropertyName)) { continue; } // Act var actual = scenario.Property.GetValue(scenario.SystemUnderTest); // Assert // When the scenario specifies CompareActualToExpectedUsing.DefaultStrategy, ValidateAndPrepareForTesting() // will check if ExpectedPropertyValue == null. If so, it sets CompareActualToExpectedUsing = ReferenceEquality. // If not, then it checks the runtime type of ExpectedPropertyValue and if it's a value type, // then it sets CompareActualToExpectedUsing = ValueEquality, otherwise it uses ValueEquality. // So a boxed value type is handled properly (using ValueEquality instead of ReferenceEquality). if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ValueEquality) { // The below reflection code is used in lieu of the following single line of code // so that equality is determined based on the property type instead of using // OBeautifulCode.Equality.Recipes.ObjectEqualityComparer, which will return false // when the objects being compared have different runtime types. For example, if // the property type is IReadOnlyCollection<string> and we are comparing an empty array // an empty List, the assertion below would fail inappropriately. // actual.AsTest().Must().BeEqualTo(scenario.ExpectedPropertyValue, because: scenario.Id); var propertyType = scenario.Property.PropertyType; var asTestMethodInfoToInvoke = asTestMethodInfo.MakeGenericMethod(propertyType); var assertionTracker = asTestMethodInfoToInvoke.Invoke(null, new[] { actual, Type.Missing }); assertionTracker.Must(); var mustBeEqualToMethodInfoToInvoke = beEqualToMethodInfo.MakeGenericMethod(propertyType); mustBeEqualToMethodInfoToInvoke.Invoke(null, new[]{ assertionTracker, scenario.ExpectedPropertyValue, scenario.Id, Type.Missing, Type.Missing }); } else if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ReferenceEquality) { actual.AsTest().Must().BeSameReferenceAs(scenario.ExpectedPropertyValue, because: scenario.Id); } else { throw new NotSupportedException("This CompareActualToExpectedUsing is not supported: " + scenario.CompareActualToExpectedUsing); } } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Cloning { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Clone___Should_clone_object___When_called() { // Arrange var systemUnderTest = A.Dummy<GetNextUniqueLongOp>(); // Act var actual = (GetNextUniqueLongOp)systemUnderTest.Clone(); // Assert actual.AsTest().Must().BeEqualTo(systemUnderTest); actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void DeepClone___Should_deep_clone_object___When_called() { // Arrange var systemUnderTest = A.Dummy<GetNextUniqueLongOp>(); // Act var actual = systemUnderTest.DeepClone(); // Assert actual.AsTest().Must().BeEqualTo(systemUnderTest); actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void DeepCloneWith___Should_deep_clone_object_and_replace_the_associated_property_with_the_provided_value___When_called() { var propertyNames = new string[] { "Details" }; var scenarios = DeepCloneWithTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange if (scenario.WithPropertyName == DeepCloneWithTestScenario.ForceGeneratedTestsToPassAndWriteMyOwnScenarioWithPropertyName) { continue; } // Act var actual = (GetNextUniqueLongOp)scenario.DeepCloneWithMethod.Invoke(scenario.SystemUnderTest, new[] { scenario.WithValue }); // Assert foreach(var propertyName in propertyNames) { var propertyInfo = typeof(GetNextUniqueLongOp).GetPropertyFiltered(propertyName, MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public); var actualPropertyValue = propertyInfo.GetValue(actual); var comparisonValue = propertyName == scenario.WithPropertyName ? scenario.WithValue : propertyInfo.GetValue(scenario.SystemUnderTest); if (actualPropertyValue == null) { comparisonValue.Must().BeNull(because: scenario.Id); } else { // We use the runtime type here to solve for the case where the object is a boxed value type. var actualPropertyValueRuntimeType = actualPropertyValue.GetType(); if (actualPropertyValueRuntimeType.IsValueType || (actualPropertyValueRuntimeType == typeof(string))) { // actualPropertyValue and comparisonValue are declared as typeof(object), but // BeEqualTo (which uses IsEqualTo), will do the right thing by comparing the // objects using their runtime type. actualPropertyValue.AsTest().Must().BeEqualTo(comparisonValue, because: scenario.Id); } else { if (propertyName == scenario.WithPropertyName) { actualPropertyValue.AsTest().Must().BeSameReferenceAs(comparisonValue, because: scenario.Id); } else { actualPropertyValue.AsTest().Must().NotBeSameReferenceAs(comparisonValue, because: scenario.Id); } } } } } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Serialization { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcBsonSerializer() { // Arrange var expected = A.Dummy<GetNextUniqueLongOp>(); var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.String }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcBsonSerializer() { // Arrange var expected = A.Dummy<GetNextUniqueLongOp>(); var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.Binary }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcJsonSerializer() { // Arrange var expected = A.Dummy<GetNextUniqueLongOp>(); var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.String }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcJsonSerializer() { // Arrange var expected = A.Dummy<GetNextUniqueLongOp>(); var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.Binary }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Equality { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_both_sides_of_operator_are_null() { // Arrange GetNextUniqueLongOp systemUnderTest1 = null; GetNextUniqueLongOp systemUnderTest2 = null; // Act var actual = systemUnderTest1 == systemUnderTest2; // Assert actual.AsTest().Must().BeTrue(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_one_side_of_operator_is_null_and_the_other_side_is_not_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange GetNextUniqueLongOp systemUnderTest = null; // Act var actual1 = systemUnderTest == scenario.ReferenceObject; var actual2 = scenario.ReferenceObject == systemUnderTest; // Assert actual1.AsTest().Must().BeFalse(because: scenario.Id); actual2.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_same_object_is_on_both_sides_of_operator() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act #pragma warning disable CS1718 // Comparison made to same variable var actual = scenario.ReferenceObject == scenario.ReferenceObject; #pragma warning restore CS1718 // Comparison made to same variable // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_both_sides_of_operator_are_null() { // Arrange GetNextUniqueLongOp systemUnderTest1 = null; GetNextUniqueLongOp systemUnderTest2 = null; // Act var actual = systemUnderTest1 != systemUnderTest2; // Assert actual.AsTest().Must().BeFalse(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_one_side_of_operator_is_null_and_the_other_side_is_not_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange GetNextUniqueLongOp systemUnderTest = null; // Act var actual1 = systemUnderTest != scenario.ReferenceObject; var actual2 = scenario.ReferenceObject != systemUnderTest; // Assert actual1.AsTest().Must().BeTrue(because: scenario.Id); actual2.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_same_object_is_on_both_sides_of_operator() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act #pragma warning disable CS1718 // Comparison made to same variable var actual = scenario.ReferenceObject != scenario.ReferenceObject; #pragma warning restore CS1718 // Comparison made to same variable // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange OperationBase systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals((OperationBase)systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((OperationBase)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_long___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange ReturningOperationBase<long> systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<long>)systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_long___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<long>)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_long___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_long___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_long___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_GetNextUniqueLongOp___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange GetNextUniqueLongOp systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals(systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_GetNextUniqueLongOp___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals(scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_GetNextUniqueLongOp___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_GetNextUniqueLongOp___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_GetNextUniqueLongOp___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((object)null); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_parameter_other_is_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); var actuals2 = scenario.ObjectsThatAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((object)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Hashing { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetHashCode___Should_not_be_equal_for_two_objects___When_objects_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var unexpected = scenario.ReferenceObject.GetHashCode(); var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _.GetHashCode()).ToList(); // Assert actuals.AsTest().Must().NotContainElement(unexpected, because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetHashCode___Should_be_equal_for_two_objects___When_objects_have_the_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var expected = scenario.ReferenceObject.GetHashCode(); var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _.GetHashCode()).ToList(); // Assert actuals.AsTest().Must().Each().BeEqualTo(expected, because: scenario.Id); } } } } }
NaosProject/Naos.Database
Naos.Database.Domain.Test/Operations/Classes/Stream/External/Write/GetNextUniqueLongOpTest.designer.cs
C#
mit
109,983
package ku_TR import ( "testing" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) func TestLocale(t *testing.T) { trans := New() expected := "ku_TR" if trans.Locale() != expected { t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale()) } } func TestPluralsRange(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsRange() // expected := 1 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsOrdinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleTwo, // }, // { // expected: locales.PluralRuleFew, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsOrdinal() // expected := 4 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsCardinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsCardinal() // expected := 2 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestRangePlurals(t *testing.T) { trans := New() tests := []struct { num1 float64 v1 uint64 num2 float64 v2 uint64 expected locales.PluralRule }{ // { // num1: 1, // v1: 1, // num2: 2, // v2: 2, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestOrdinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 2, // v: 0, // expected: locales.PluralRuleTwo, // }, // { // num: 3, // v: 0, // expected: locales.PluralRuleFew, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.OrdinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestCardinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.CardinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestDaysAbbreviated(t *testing.T) { trans := New() days := trans.WeekdaysAbbreviated() for i, day := range days { s := trans.WeekdayAbbreviated(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sun", // }, // { // idx: 1, // expected: "Mon", // }, // { // idx: 2, // expected: "Tue", // }, // { // idx: 3, // expected: "Wed", // }, // { // idx: 4, // expected: "Thu", // }, // { // idx: 5, // expected: "Fri", // }, // { // idx: 6, // expected: "Sat", // }, } for _, tt := range tests { s := trans.WeekdayAbbreviated(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysNarrow(t *testing.T) { trans := New() days := trans.WeekdaysNarrow() for i, day := range days { s := trans.WeekdayNarrow(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", string(day), s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "S", // }, // { // idx: 1, // expected: "M", // }, // { // idx: 2, // expected: "T", // }, // { // idx: 3, // expected: "W", // }, // { // idx: 4, // expected: "T", // }, // { // idx: 5, // expected: "F", // }, // { // idx: 6, // expected: "S", // }, } for _, tt := range tests { s := trans.WeekdayNarrow(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Su", // }, // { // idx: 1, // expected: "Mo", // }, // { // idx: 2, // expected: "Tu", // }, // { // idx: 3, // expected: "We", // }, // { // idx: 4, // expected: "Th", // }, // { // idx: 5, // expected: "Fr", // }, // { // idx: 6, // expected: "Sa", // }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sunday", // }, // { // idx: 1, // expected: "Monday", // }, // { // idx: 2, // expected: "Tuesday", // }, // { // idx: 3, // expected: "Wednesday", // }, // { // idx: 4, // expected: "Thursday", // }, // { // idx: 5, // expected: "Friday", // }, // { // idx: 6, // expected: "Saturday", // }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsAbbreviated(t *testing.T) { trans := New() months := trans.MonthsAbbreviated() for i, month := range months { s := trans.MonthAbbreviated(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "Jan", // }, // { // idx: 2, // expected: "Feb", // }, // { // idx: 3, // expected: "Mar", // }, // { // idx: 4, // expected: "Apr", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "Jun", // }, // { // idx: 7, // expected: "Jul", // }, // { // idx: 8, // expected: "Aug", // }, // { // idx: 9, // expected: "Sep", // }, // { // idx: 10, // expected: "Oct", // }, // { // idx: 11, // expected: "Nov", // }, // { // idx: 12, // expected: "Dec", // }, } for _, tt := range tests { s := trans.MonthAbbreviated(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsNarrow(t *testing.T) { trans := New() months := trans.MonthsNarrow() for i, month := range months { s := trans.MonthNarrow(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "J", // }, // { // idx: 2, // expected: "F", // }, // { // idx: 3, // expected: "M", // }, // { // idx: 4, // expected: "A", // }, // { // idx: 5, // expected: "M", // }, // { // idx: 6, // expected: "J", // }, // { // idx: 7, // expected: "J", // }, // { // idx: 8, // expected: "A", // }, // { // idx: 9, // expected: "S", // }, // { // idx: 10, // expected: "O", // }, // { // idx: 11, // expected: "N", // }, // { // idx: 12, // expected: "D", // }, } for _, tt := range tests { s := trans.MonthNarrow(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsWide(t *testing.T) { trans := New() months := trans.MonthsWide() for i, month := range months { s := trans.MonthWide(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "January", // }, // { // idx: 2, // expected: "February", // }, // { // idx: 3, // expected: "March", // }, // { // idx: 4, // expected: "April", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "June", // }, // { // idx: 7, // expected: "July", // }, // { // idx: 8, // expected: "August", // }, // { // idx: 9, // expected: "September", // }, // { // idx: 10, // expected: "October", // }, // { // idx: 11, // expected: "November", // }, // { // idx: 12, // expected: "December", // }, } for _, tt := range tests { s := string(trans.MonthWide(time.Month(tt.idx))) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeFull(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } // fixed := time.FixedZone("OTHER", -4) tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am Eastern Standard Time", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed), // expected: "8:05:01 pm OTHER", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeLong(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am EST", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc), // expected: "8:05:01 pm EST", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05:01 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05:01 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateFull(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Wednesday, February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateLong(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Feb 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/16", // }, // { // t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/500", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtNumber(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 1123456.5643, // v: 2, // expected: "1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // expected: "1,123,456.6", // }, // { // num: 221123456.5643, // v: 3, // expected: "221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: 0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtNumber(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtCurrency(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "-$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "-CAD 221,123,456.564", // }, // { // num: 0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtCurrency(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtAccounting(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "($221,123,456.564)", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "(CAD 221,123,456.564)", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtAccounting(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtPercent(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 15, // v: 0, // expected: "15%", // }, // { // num: 15, // v: 2, // expected: "15.00%", // }, // { // num: 434.45, // v: 0, // expected: "434%", // }, // { // num: 34.4, // v: 2, // expected: "34.40%", // }, // { // num: -34, // v: 0, // expected: "-34%", // }, } trans := New() for _, tt := range tests { s := trans.FmtPercent(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
go-playground/locales
ku_TR/ku_TR_test.go
GO
mit
19,303
--- layout: post title: Prim外部算法资料 published: true category: nosql tags: [data_structure, maizi] --- Stanford大学Schwarz老师的代码 ([Prim算法的Java实现](http://keithschwarz.com/interesting/code/?dir=prim)) 构建 Fabonacci Heap 维基百科 ((Fabonacci Heap)[http://en.wikipedia.org/wiki/Fibonacci_heap])
gothere/gothere.github.io
_posts/2015-1-9-Graph-Prim.md
Markdown
mit
331
var _for = require ('../index'); var should = require ('should'); describe ('passing data', function () { it ('should call the loop with the passed data', function (done) { var results = ''; var loop = _for ( 0, function (i) { return i < 2; }, function (i) { return i + 1; }, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); it ('should work when making a loop with two arguments', function (done) { var results = ''; var loop = _for (2, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); });
JosephJNK/async-for
tests/data.tests.js
JavaScript
mit
1,126
#region License // Copyright (c) 2013 Chandramouleswaran Ravichandran // // 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. #endregion using System; using System.Windows; using System.Windows.Data; using VEF.Interfaces.Controls; namespace VEF.Interfaces.Converters { public class MenuVisibilityConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { AbstractMenuItem menu = value as AbstractMenuItem; if (menu == null) return Visibility.Hidden; if (menu.Command != null && menu.Command.CanExecute(null) == false && menu.HideDisabled == true) return Visibility.Collapsed; if (menu.Children.Count > 0 || menu.Command != null || menu.IsCheckable == true) return Visibility.Visible; return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
devxkh/FrankE
Editor/VEF/VEF.Core.Shared/Interfaces/Converters/MenuVisibilityConverter.cs
C#
mit
2,235
using System; namespace Paramore.Darker.Builder { internal sealed class RegistryActionWrapper : IQueryHandlerDecoratorRegistry { private readonly Action<Type> _action; public RegistryActionWrapper(Action<Type> action) { _action = action; } public void Register(Type decoratorType) { _action(decoratorType); } } }
BrighterCommand/Darker
src/Paramore.Darker/Builder/RegistryActionWrapper.cs
C#
mit
407
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>exact-real-arithmetic: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / exact-real-arithmetic - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> exact-real-arithmetic <small> 8.6.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-20 03:22:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-20 03:22:08 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.1 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.0 Official release 4.10.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/exact-real-arithmetic&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/ExactRealArithmetic&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: correctness&quot; &quot;keyword: real numbers&quot; &quot;keyword: arithmetic&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Real numbers&quot; ] authors: [ &quot;Jérôme Creci&quot; ] bug-reports: &quot;https://github.com/coq-contribs/exact-real-arithmetic/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/exact-real-arithmetic.git&quot; synopsis: &quot;Exact Real Arithmetic&quot; description: &quot;&quot;&quot; This contribution contains a proof of correctness of some exact real arithmetic algorithms from the PhD thesis of Valérie Ménissier-Morain&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/exact-real-arithmetic/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=0286dd584cfca1f955924feae67845d8&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-exact-real-arithmetic.8.6.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-exact-real-arithmetic -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-exact-real-arithmetic.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.10.0-2.0.6/released/8.11.1/exact-real-arithmetic/8.6.0.html
HTML
mit
6,951
# encoding: utf-8 class LogoPhotoUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/logo/" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: process :resize_to_fit => [50, 50] # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end def filename "logo." + original_filename.split(".").last if original_filename end end
zhaoguobin/company_website
app/uploaders/logo_photo_uploader.rb
Ruby
mit
1,512
/** * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. * @author Toru Nagashima */ "use strict"; const astUtils = require("../util/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/; const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/; const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/; /** * Checks whether a given node is located at `ForStatement.init` or not. * * @param {ASTNode} node - A node to check. * @returns {boolean} `true` if the node is located at `ForStatement.init`. */ function isInitOfForStatement(node) { return node.parent.type === "ForStatement" && node.parent.init === node; } /** * Checks whether a given Identifier node becomes a VariableDeclaration or not. * * @param {ASTNode} identifier - An Identifier node to check. * @returns {boolean} `true` if the node can become a VariableDeclaration. */ function canBecomeVariableDeclaration(identifier) { let node = identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } return ( node.type === "VariableDeclarator" || ( node.type === "AssignmentExpression" && node.parent.type === "ExpressionStatement" && DECLARATION_HOST_TYPE.test(node.parent.parent.type) ) ); } /** * Checks if an property or element is from outer scope or function parameters * in destructing pattern. * * @param {string} name - A variable name to be checked. * @param {eslint-scope.Scope} initScope - A scope to start find. * @returns {boolean} Indicates if the variable is from outer scope or function parameters. */ function isOuterVariableInDestructing(name, initScope) { if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) { return true; } const variable = astUtils.getVariableByName(initScope, name); if (variable !== null) { return variable.defs.some(def => def.type === "Parameter"); } return false; } /** * Gets the VariableDeclarator/AssignmentExpression node that a given reference * belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Reference} reference - A reference to get. * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or * null. */ function getDestructuringHost(reference) { if (!reference.isWrite()) { return null; } let node = reference.identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { return null; } return node; } /** * Determines if a destructuring assignment node contains * any MemberExpression nodes. This is used to determine if a * variable that is only written once using destructuring can be * safely converted into a const declaration. * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. * @returns {boolean} True if the destructuring pattern contains * a MemberExpression, false if not. */ function hasMemberExpressionAssignment(node) { switch (node.type) { case "ObjectPattern": return node.properties.some(prop => { if (prop) { /* * Spread elements have an argument property while * others have a value property. Because different * parsers use different node types for spread elements, * we just check if there is an argument property. */ return hasMemberExpressionAssignment(prop.argument || prop.value); } return false; }); case "ArrayPattern": return node.elements.some(element => { if (element) { return hasMemberExpressionAssignment(element); } return false; }); case "AssignmentPattern": return hasMemberExpressionAssignment(node.left); case "MemberExpression": return true; // no default } return false; } /** * Gets an identifier node of a given variable. * * If the initialization exists or one or more reading references exist before * the first assignment, the identifier node is the node of the declaration. * Otherwise, the identifier node is the node of the first assignment. * * If the variable should not change to const, this function returns null. * - If the variable is reassigned. * - If the variable is never initialized nor assigned. * - If the variable is initialized in a different scope from the declaration. * - If the unique assignment of the variable cannot change to a declaration. * e.g. `if (a) b = 1` / `return (b = 1)` * - If the variable is declared in the global scope and `eslintUsed` is `true`. * `/*exported foo` directive comment makes such variables. This rule does not * warn such variables because this rule cannot distinguish whether the * exported variables are reassigned or not. * * @param {eslint-scope.Variable} variable - A variable to get. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {ASTNode|null} * An Identifier node if the variable should change to const. * Otherwise, null. */ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { if (variable.eslintUsed && variable.scope.type === "global") { return null; } // Finds the unique WriteReference. let writer = null; let isReadBeforeInit = false; const references = variable.references; for (let i = 0; i < references.length; ++i) { const reference = references[i]; if (reference.isWrite()) { const isReassigned = ( writer !== null && writer.identifier !== reference.identifier ); if (isReassigned) { return null; } const destructuringHost = getDestructuringHost(reference); if (destructuringHost !== null && destructuringHost.left !== void 0) { const leftNode = destructuringHost.left; let hasOuterVariables = false, hasNonIdentifiers = false; if (leftNode.type === "ObjectPattern") { const properties = leftNode.properties; hasOuterVariables = properties .filter(prop => prop.value) .map(prop => prop.value.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } else if (leftNode.type === "ArrayPattern") { const elements = leftNode.elements; hasOuterVariables = elements .map(element => element && element.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } if (hasOuterVariables || hasNonIdentifiers) { return null; } } writer = reference; } else if (reference.isRead() && writer === null) { if (ignoreReadBeforeAssign) { return null; } isReadBeforeInit = true; } } /* * If the assignment is from a different scope, ignore it. * If the assignment cannot change to a declaration, ignore it. */ const shouldBeConst = ( writer !== null && writer.from === variable.scope && canBecomeVariableDeclaration(writer.identifier) ); if (!shouldBeConst) { return null; } if (isReadBeforeInit) { return variable.defs[0].name; } return writer.identifier; } /** * Groups by the VariableDeclarator/AssignmentExpression node that each * reference of given variables belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Variable[]} variables - Variables to group by destructuring. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {Map<ASTNode, ASTNode[]>} Grouped identifier nodes. */ function groupByDestructuring(variables, ignoreReadBeforeAssign) { const identifierMap = new Map(); for (let i = 0; i < variables.length; ++i) { const variable = variables[i]; const references = variable.references; const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); let prevId = null; for (let j = 0; j < references.length; ++j) { const reference = references[j]; const id = reference.identifier; /* * Avoid counting a reference twice or more for default values of * destructuring. */ if (id === prevId) { continue; } prevId = id; // Add the identifier node into the destructuring group. const group = getDestructuringHost(reference); if (group) { if (identifierMap.has(group)) { identifierMap.get(group).push(identifier); } else { identifierMap.set(group, [identifier]); } } } } return identifierMap; } /** * Finds the nearest parent of node with a given type. * * @param {ASTNode} node – The node to search from. * @param {string} type – The type field of the parent node. * @param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise. * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. */ function findUp(node, type, shouldStop) { if (!node || shouldStop(node)) { return null; } if (node.type === type) { return node; } return findUp(node.parent, type, shouldStop); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "require `const` declarations for variables that are never reassigned after declared", category: "ECMAScript 6", recommended: false, url: "https://eslint.org/docs/rules/prefer-const" }, fixable: "code", schema: [ { type: "object", properties: { destructuring: { enum: ["any", "all"] }, ignoreReadBeforeAssign: { type: "boolean" } }, additionalProperties: false } ] }, create(context) { const options = context.options[0] || {}; const sourceCode = context.getSourceCode(); const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; const variables = []; let reportCount = 0; let name = ""; /** * Reports given identifier nodes if all of the nodes should be declared * as const. * * The argument 'nodes' is an array of Identifier nodes. * This node is the result of 'getIdentifierIfShouldBeConst()', so it's * nullable. In simple declaration or assignment cases, the length of * the array is 1. In destructuring cases, the length of the array can * be 2 or more. * * @param {(eslint-scope.Reference|null)[]} nodes - * References which are grouped by destructuring to report. * @returns {void} */ function checkGroup(nodes) { const nodesToReport = nodes.filter(Boolean); if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); const isVarDecParentNull = varDeclParent === null; if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { const firstDeclaration = varDeclParent.declarations[0]; if (firstDeclaration.init) { const firstDecParent = firstDeclaration.init.parent; /* * First we check the declaration type and then depending on * if the type is a "VariableDeclarator" or its an "ObjectPattern" * we compare the name from the first identifier, if the names are different * we assign the new name and reset the count of reportCount and nodeCount in * order to check each block for the number of reported errors and base our fix * based on comparing nodes.length and nodesToReport.length. */ if (firstDecParent.type === "VariableDeclarator") { if (firstDecParent.id.name !== name) { name = firstDecParent.id.name; reportCount = 0; } if (firstDecParent.id.type === "ObjectPattern") { if (firstDecParent.init.name !== name) { name = firstDecParent.init.name; reportCount = 0; } } } } } let shouldFix = varDeclParent && // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && /* * If options.destructuring is "all", then this warning will not occur unless * every assignment in the destructuring should be const. In that case, it's safe * to apply the fix. */ nodesToReport.length === nodes.length; if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { /* * Add nodesToReport.length to a count, then comparing the count to the length * of the declarations in the current block. */ reportCount += nodesToReport.length; shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length); } } nodesToReport.forEach(node => { context.report({ node, message: "'{{name}}' is never reassigned. Use 'const' instead.", data: node, fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null }); }); } } return { "Program:exit"() { groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); }, VariableDeclaration(node) { if (node.kind === "let" && !isInitOfForStatement(node)) { variables.push(...context.getDeclaredVariables(node)); } } }; } };
Aladdin-ADD/eslint
lib/rules/prefer-const.js
JavaScript
mit
16,721
""" Compare the regions predicted to be prophages to the regions that are marked as prophages in our testing set Probably the hardest part of this is the identifiers! """ import os import sys import argparse import gzip from Bio import SeqIO, BiopythonWarning from PhiSpyModules import message, is_gzip_file __author__ = 'Rob Edwards' __copyright__ = 'Copyright 2020, Rob Edwards' __credits__ = ['Rob Edwards'] __license__ = 'MIT' __maintainer__ = 'Rob Edwards' __email__ = 'raedwards@gmail.com' def genbank_seqio(gbkf): if is_gzip_file(gbkf): handle = gzip.open(gbkf, 'rt') else: handle = open(gbkf, 'r') return SeqIO.parse(handle, "genbank") def actual_phage_cds(gbkf, verbose=False): """ Read the genbank file and return a list of features that are actually phage regions :param gbkf: the test genbank file with CDS marked with is_phage :param verbose: more output :return: a set of phage features """ if verbose: message(f"Reading {gbkf}", "GREEN", "stderr") phage = {} nonphage = {} for seq in genbank_seqio(gbkf): for feat in seq.features: if feat.type == 'CDS': if 'product' not in feat.qualifiers: feat.qualifiers['product'] = [f"Hypothetical protein (not annotated in {gbkf})"] if 'is_phage' in feat.qualifiers: phage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: nonphage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] return phage, nonphage def predicted_genbank(predf, verbose=False): """ Read the predictions from the genbank file and return a set of features :param predf: the predictions file :param verbose: more output :return: a set of predicted phage genes """ if verbose: message(f"Reading {predf}", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(predf): for feat in seq.features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq, cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {predf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def predicted_regions(regf, gbkf, verbose): """ Pull the phage genes from the regions :param regf: the regions file with contigs/start/stop :param gbkf: the genbank file used to make those predictions :param verbose: more output :return: a set of predicted phage genes """ regions = {} if verbose: message(f"Reading {regf}", "GREEN", "stderr") with open(regf, 'r') as f: for l in f: p = l.strip().split("\t") assert(len(p) == 3), f"Expected a tple of [contig, start, stop] in {regf}" p[1] = int(p[1]) p[2] = int(p[2]) if p[0] not in regions: regions[p[0]] = [] if p[2] < p[1]: regions[p[0]].append([p[2], p[1]]) else: regions[p[0]].append([p[1], p[2]]) if verbose: message(f"Reading {gbkf} again to get the phage regions", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(gbkf): if seq.id in regions: for loc in regions[seq.id]: if verbose: message(f"Getting from {loc[0]} to {loc[1]}", "PINK", "stderr") for feat in seq[loc[0]:loc[1]].features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {gbkf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def compare_real_predicted(phage: dict, nonphage: dict, predicted: dict, print_fp: bool, print_fn: bool, verbose: bool): """ Compare the features that are real and predicted :param print_fn: print out the false negative matches :param print_fp: print out the false positive matches :param phage: actual phage features :param nonphage: actual non phage features :param predicted: predicted phage features :param verbose: more output :return: """ if verbose: message(f"Comparing real and predicted", "GREEN", "stderr") # TP = phage intersection predicted # TN = nonphage intersection [not in predicted] # FP = nonphage intersection predicted # FN = phage intersection [not in predicted] # convert the keys to sets phage_set = set(phage.keys()) nonphage_set = set(nonphage.keys()) predicted_set = set(predicted.keys()) # calculate not in predicted not_predicted = set() for s in phage_set.union(nonphage): if s not in predicted: not_predicted.add(s) print(f"Found:\nTest set:\n\tPhage: {len(phage)} Not phage: {len(nonphage)}") print(f"Predictions:\n\tPhage: {len(predicted)} Not phage: {len(not_predicted)}") tp = len(phage_set.intersection(predicted_set)) tn = len(nonphage_set.intersection(not_predicted)) fp = len(nonphage_set.intersection(predicted_set)) fn = len(phage_set.intersection(not_predicted)) print(f"TP: {tp} FP: {fp} TN: {tn} FN: {fn}") try: accuracy = (tp+tn)/(tp + tn + fp + fn) except ZeroDivisionError: accuracy = "NaN" try: precision = tp/(tp+fp) except ZeroDivisionError: precision = "NaN" try: recall = tp/(tp+fn) except ZeroDivisionError: recall = "NaN" try: specificity = tn/(tn+fp) except ZeroDivisionError: specificity = "NaN" f1_score = "NaN" if accuracy != "NaN" and precision != "NaN" and recall != "NaN" and specificity != "NaN": try: f1_score = 2*(recall * precision) / (recall + precision) except ZeroDivisionError: f1_score = "NaN" if accuracy != "NaN": print(f"Accuracy: {accuracy:.3f}\t(this is the ratio of the correctly labeled phage genes to the whole pool of genes") else: print("Accuracy: NaN") if precision != "NaN": print(f"Precision: {precision:.3f}\t(This is the ratio of correctly labeled phage genes to all predictions)") else: print("Precision: NaN") if recall != "NaN": print(f"Recall: {recall:.3f}\t(This is the fraction of actual phage genes we got right)") else: print("Recall: NaN") if specificity != "NaN": print(f"Specificity: {specificity:.3f}\t(This is the fraction of non phage genes we got right)") else: print("Specificity: NaN") if f1_score != "NaN": print(f"f1 score: {f1_score:.3f}\t(this is the harmonic mean of precision and recall, and is the best measure when, as in this case, there is a big difference between the number of phage and non-phage genes)") else: print("f1 score: NaN") if print_fp: for i in nonphage_set.intersection(predicted_set): print(f"FP\t{i}\t{nonphage[i]}") if print_fn: for i in phage_set.intersection(not_predicted): print(f"FN\t{i}\t{[phage[i]]}") if __name__ == '__main__': parser = argparse.ArgumentParser(description="Compare predictions to reality") parser.add_argument('-t', '--testfile', help='test file that has phage proteins marked with the is_phage qualifier', required=True) parser.add_argument('-p', '--predictfile', help='predictions genbank file that has each prophage as a sequence entry') parser.add_argument('-r', '--regionsfile', help='predictions regions file that has tuple of [contig, start, end]') parser.add_argument('--fp', help='print out the false positives', action='store_true') parser.add_argument('--fn', help='print out the false negatives', action='store_true') parser.add_argument('-v', help='verbose output', action='store_true') args = parser.parse_args() pred = None if args.predictfile: pred = predicted_genbank(args.predictfile, args.v) elif args.regionsfile: pred = predicted_regions(args.regionsfile, args.testfile, args.v) else: message("FATAL: Please provide either a predictions genbank or tsv file", "RED", "stderr") phage, nonphage = actual_phage_cds(args.testfile, args.v) compare_real_predicted(phage, nonphage, pred, args.fp, args.fn, args.v)
linsalrob/PhiSpy
scripts/compare_predictions_to_phages.py
Python
mit
8,988
from pymarkdownlint.tests.base import BaseTestCase from pymarkdownlint.config import LintConfig, LintConfigError from pymarkdownlint import rules class LintConfigTests(BaseTestCase): def test_get_rule_by_name_or_id(self): config = LintConfig() # get by id expected = rules.MaxLineLengthRule() rule = config.get_rule_by_name_or_id('R1') self.assertEqual(rule, expected) # get by name expected = rules.TrailingWhiteSpace() rule = config.get_rule_by_name_or_id('trailing-whitespace') self.assertEqual(rule, expected) # get non-existing rule = config.get_rule_by_name_or_id('foo') self.assertIsNone(rule) def test_default_rules(self): config = LintConfig() expected_rule_classes = [rules.MaxLineLengthRule, rules.TrailingWhiteSpace, rules.HardTab] expected_rules = [rule_cls() for rule_cls in expected_rule_classes] self.assertEqual(config.default_rule_classes, expected_rule_classes) self.assertEqual(config.rules, expected_rules) def test_load_config_from_file(self): # regular config file load, no problems LintConfig.load_from_file(self.get_sample_path("markdownlint")) # bad config file load foo_path = self.get_sample_path("foo") with self.assertRaisesRegexp(LintConfigError, "Invalid file path: {0}".format(foo_path)): LintConfig.load_from_file(foo_path) # error during file parsing bad_markdowlint_path = self.get_sample_path("badmarkdownlint") expected_error_msg = "Error during config file parsing: File contains no section headers." with self.assertRaisesRegexp(LintConfigError, expected_error_msg): LintConfig.load_from_file(bad_markdowlint_path)
jorisroovers/pymarkdownlint
pymarkdownlint/tests/test_config.py
Python
mit
1,809
Template.SightingsEdit.helpers({ onDelete: function () { return function (result) { //when record is deleted, go back to record listing Router.go('SightingsList'); }; }, }); Template.SightingsEdit.events({ }); Template.SightingsEdit.rendered = function () { }; AutoForm.hooks({ updateSightingsForm: { onSuccess: function (operation, result, template) { Router.go('SightingsView', { _id: template.data.doc._id }); }, } });
bdunnette/meleagris
client/views/sightings/sightingsEdit.js
JavaScript
mit
482
/** * Copyright (c) 2013 Egor Pushkin. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.scientificsoft.iremote.platform.net; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import com.scientificsoft.iremote.server.tools.TimeoutException; public class Socket { private java.net.Socket _socket = null; public Socket(String host, String port, long timeout) throws IOException, TimeoutException { try { _socket = new java.net.Socket(); _socket.connect(new InetSocketAddress(host, new Integer(port)), (int)timeout); } catch ( SocketTimeoutException e ) { throw new TimeoutException(); } catch ( Exception e ) { throw new IOException("Failed to establish connection."); } } public InputStream getInputStream() throws IOException { return _socket.getInputStream(); } public OutputStream getOutputStream() throws IOException { return _socket.getOutputStream(); } public void close() throws IOException { try { _socket.shutdownInput(); } catch ( Exception e ) { } try { _socket.shutdownOutput(); } catch ( Exception e ) { } _socket.close(); } }
egorpushkin/iremote
dev/iRemote.Android/src/com/scientificsoft/iremote/platform/net/Socket.java
Java
mit
2,463
/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.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, 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. ****************************************************************************/ #ifndef __cocos2d_libs__ProjectNodeReader__ #define __cocos2d_libs__ProjectNodeReader__ #include "cocos2d.h" #include "editor-support/cocostudio/CocosStudioExport.h" #include "editor-support/cocostudio/WidgetReader/NodeReaderProtocol.h" namespace cocostudio { class CC_STUDIO_DLL ProjectNodeReader : public cocos2d::Ref, public NodeReaderProtocol { public: ProjectNodeReader(); ~ProjectNodeReader(); static ProjectNodeReader* getInstance(); /** @deprecated Use method destroyInstance() instead */ CC_DEPRECATED_ATTRIBUTE static void purge(); static void destroyInstance(); flatbuffers::Offset<flatbuffers::Table> createOptionsWithFlatBuffers(const tinyxml2::XMLElement* objectData, flatbuffers::FlatBufferBuilder* builder); void setPropsWithFlatBuffers(cocos2d::Node* node, const flatbuffers::Table* projectNodeOptions); cocos2d::Node* createNodeWithFlatBuffers(const flatbuffers::Table* nodeOptions) { return nullptr; }; }; } #endif /* defined(__cocos2d_libs__ProjectNodeReader__) */
yangosoft/cocos2d-x-arm-opengles
editor-support/cocostudio/WidgetReader/ProjectNodeReader/ProjectNodeReader.h
C
mit
2,447
<!DOCTYPE html> <html> <head> <title>Logger Test</title> </head> <body> <small>(open the console)</small> <script src="../dist/logger.js"></script> <script src="logger.test.js"></script> </body> </html>
Lokua/lokua.net.logger
test/test.html
HTML
mit
210
# Roman Numerals Write a function to convert from normal numbers to Roman Numerals. The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis. One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programmes. The Romans wrote numbers using letters - I, V, X, L, C, D, M. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets). ```text 1 => I 10 => X 7 => VII ``` There is no need to be able to convert numbers larger than about 3000. (The Romans themselves didn't tend to go any higher) Wikipedia says: Modern Roman numerals ... are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. To see this in practice, consider the example of 1990. In Roman numerals 1990 is MCMXC: 1000=M 900=CM 90=XC 2008 is written as MMVIII: 2000=MM 8=VIII See also: http://www.novaroma.org/via_romana/numbers.html ## Hints This exercise requires you to write an extension method. For more information, see [this page](https://msdn.microsoft.com/en-us//library/bb383977.aspx). ## Source The Roman Numeral Kata [http://codingdojo.org/cgi-bin/index.pl?KataRomanNumerals](http://codingdojo.org/cgi-bin/index.pl?KataRomanNumerals) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise.
GKotfis/csharp
exercises/roman-numerals/README.md
Markdown
mit
1,698
package org.zenframework.easyservices.update; import java.util.Collection; @SuppressWarnings("rawtypes") public class CollectionUpdateAdapter implements UpdateAdapter<Collection> { @Override public Class<Collection> getValueClass() { return Collection.class; } @SuppressWarnings("unchecked") @Override public void update(Collection oldValue, Collection newValue, ValueUpdater updater) { if (oldValue == newValue || newValue == null) return; if (oldValue == null) throw new UpdateException("Old value is null"); oldValue.clear(); oldValue.addAll(newValue); } }
zenframework/easy-services
easy-services-core/src/main/java/org/zenframework/easyservices/update/CollectionUpdateAdapter.java
Java
mit
657
""" homeassistant.components.binary_sensor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component to interface with binary sensors (sensors which only know two states) that can be monitored. For more details about this component, please refer to the documentation at https://home-assistant.io/components/binary_sensor/ """ import logging from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity import Entity from homeassistant.const import (STATE_ON, STATE_OFF) DOMAIN = 'binary_sensor' DEPENDENCIES = [] SCAN_INTERVAL = 30 ENTITY_ID_FORMAT = DOMAIN + '.{}' def setup(hass, config): """ Track states and offer events for binary sensors. """ component = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) component.setup(config) return True # pylint: disable=no-self-use class BinarySensorDevice(Entity): """ Represents a binary sensor. """ @property def is_on(self): """ True if the binary sensor is on. """ return None @property def state(self): """ Returns the state of the binary sensor. """ return STATE_ON if self.is_on else STATE_OFF @property def friendly_state(self): """ Returns the friendly state of the binary sensor. """ return None
badele/home-assistant
homeassistant/components/binary_sensor/__init__.py
Python
mit
1,321
--- layout: post title: "Compilation veille Twitter & RSS #23" category: veille --- La moisson de liens pour les semaine du 8 au 12 décembre 2014. Ils ont, pour la plupart été publiés sur mon compte Twitter. Les voici rassemblés pour ceux qui les auraient raté. ### Architecture [Monoliths, Cookie-Cutter or Microservices](http://paulhammant.com/2014/12/07/moniliths-cookiecutters-or-microservices/) : The article posits that microservices is the antidote to monoliths. It doesn’t mention cookie cutter scaling at all, which is another antidote to monoliths, with the right build infrastructure and DevOps. #### Chef [Upcoming releases for Chef Client and Chef Development Kit](https://www.chef.io/blog/2014/12/11/upcoming-releases-for-chef-client-and-chef-development-kit/) : Recently we have been getting some questions about the versions of Chef Client and Chef Development Kit. I wanted to share some information about the background and the upcoming releases to shed some light into this topic. [Chef 12: Fix Untrusted Self Signed Certificates](https://www.chef.io/blog/2014/12/12/chef-12-fix-untrusted-self-signed-certificates/) : Scenario: You’ve started up a brand new Chef Server using version 12, and you have installed Chef 12 on your local system. You log into the Management Console to create a user and organization (or do this with the command-line chef-server-ctl commands), and you’re ready to rock with this knife.rb: [Guest Post: Creating Your Own Chef Cookbook Generator](https://www.chef.io/blog/2014/12/09/guest-post-creating-your-own-chef-cookbook-generator/) : The Chef Development Kit (Chef DK) comes with an awesome tool: chef. This command line utility can do a number of things to streamline chef development for you, so let’s look at one of the more valuable things you can do: create your own cookbook generator. ### Databases [If Eventual Consistency Seems Hard, Wait Till You Try MVCC](http://www.xaprb.com/blog/2014/12/08/eventual-consistency-simpler-than-mvcc/) : This should sound familiar: One of the great lies about NoSQL databases is that they’re simple. Simplicity done wrong makes things a lot harder and more complicated to develop and operate. Programmers and operations staff end up reimplementing (badly) things the database should do. Nobody argued this line of reasoning more vigorously than when trying to defend relational databases, especially during the darkest years (ca. 2009-2010), when NoSQL still meant NO SQL DAMMIT, all sorts of NoSQL databases were sprouting, and most of them were massively overhyped. #### Couchbase [Pure Storage and Couchbase](http://blog.couchbase.com/pure-storage-and-couchbase) : There is a lot of buzz around enterprise class storage, lately. One of our partners ,Pure Storage, is a leader in the space and recently gave us the opportunity to deploy Couchbase in one of their lab environments. The 8 node cluster was easily able to sustain a 100% write 1 million ops/second workload. A 1,000,000 writes/second workload was generated using our pillowfight tool run from one of the cluster nodes with the following parameters: #### InfluxDB [Clustering, tags, and enhancements to come in 0.9.0](Clustering, tags, and enhancements to come in 0.9.0) : We’ve been heads down working on InfluxDB v0.9.0 for a while and I’d like to update the community on what we’re working on and what the goals are for the upcoming release. It started out as a release to completely rewrite the clustering implementation, but it has turned into something much bigger. Not only are we significantly improving the clustering capabilities of Influx, we’re adding support for tags, cleaning up the API, rewriting a bunch of underlying implementation, changing storage engines, and moving to a pure Go codebase. #### MariaDB [MaxScale, manual control, external monitors and notification methods](https://mariadb.com/blog/maxscale-manual-control-external-monitors-and-notification-methods) : One of the nice things about the "plug and play" approach of MaxScale is that people constantly find ways of using it that were not originally envisaged when we designed MaxScale. One such configuration that I have heard of from multiple sources is using monitoring outside of MaxScale itself. This post will discuss a little about how monitoring works and how it can be moved outside of MaxScale. In particular a simplified example will be presented which shows how to use the notification mechanism in Galera to control MaxScale's use of the nodes in a Galera cluster. [MariaDB 10.1.2 alpha now available](https://blog.mariadb.org/mariadb-10-1-2-alpha-now-available/) : The MariaDB project is pleased to announce the immediate availability of MariaDB 10.1.2. This is an Alpha release. #### MySQL [MySQL 5.7: `only_full_group_by` Improved, Recognizing Functional Dependencies, Enabled by Default!](http://mysqlserverteam.com/mysql-5-7-only_full_group_by-improved-recognizing-functional-dependencies-enabled-by-default/) : Here’s an account of recent work which has kept me busy and excited for a few months. For those unfamiliar with the `only_full_group_by` sql mode, let me provide some context. I’ll use the world database, which can be downloaded from this MySQL Documentation page. You can find details on how to install the database on the same page. We have a table of countries and a table of languages spoken in each country. It’s a 1-to-N relationship: a country can have many languages so CountryLanguage.CountryCode is a foreign key referencing Country.Code: [Recover MySQL root password without restarting MySQL (no downtime!)](http://www.percona.com/blog/2014/12/10/recover-mysql-root-password-without-restarting-mysql-no-downtime/) : The situation is the classic “need to recover MySQL root password” but you cannot restart MySQL (because it is the master production server, or any other reason), which makes the –skip-grant-tables solution as a no-no possibility. [MySQL 5.6 Transportable Tablespaces best practices](http://www.percona.com/blog/2014/12/09/mysql-5-6-transportable-tablespaces-best-practices/) : In MySQL 5.6 Oracle introduced a Transportable Tablespace feature (copying tablespaces to another server) and Percona Server adopted it for partial backups which means you can now take individual database or table backups and your destination server can be a vanilla MySQL server. Moreover, since Percona Server 5.6, `innodb_import_table_from_xtrabackup` is obsolete as Percona Server also implemented Oracle MySQL’s transportable tablespaces feature which as I mentioned gives you the ability to copy tablespace (table.ibd) between servers. Let me demonstrate this through one example where I am going to take partial backup of selective tables instead of an entire MySQL server and restore it on a running MySQL server on destination without taking it offline. [Global Counters And Average Patient Temperature](https://vividcortex.com/blog/2014/12/08/global-counters-and-average-patient-temperature/) : Our recent blog post on finding wasted prepare/execute/close cycles showed how per-statement analysis can find individual queries that are not being repeatedly executed after being prepared. To recap, we found a number of statements in our own application that were being prepared, executed, and then never re-executed. This means 3 network round-trips instead of just executing the statement directly, which takes only 1 round-trip. By fixing this, we materially decreased load on our servers and improved latency for the service that issued the query. ### Big Data #### Hadoop [The Impala Cookbook](http://blog.cloudera.com/blog/2014/12/the-impala-cookbook/) : Impala, the open source MPP analytic database for Apache Hadoop, is now firmly entrenched in the Big Data mainstream. How do we know this? For one, Impala is now the standard against which alternatives measure themselves, based on a proliferation of new benchmark testing. Furthermore, Impala has been adopted by multiple vendors as their solution for letting customers do exploratory analysis on Big Data, natively and in place (without the need for redundant architecture or ETL). Also significant, we’re seeing the emergence of best practices and patterns out of customer experiences. [New in CDH 5.2: Improvements for Running Multiple Workloads on a Single HBase Cluster](http://blog.cloudera.com/blog/2014/12/new-in-cdh-5-2-improvements-for-running-multiple-workloads-on-a-single-hbase-cluster/) : Historically, Apache HBase treats all tables, users, and workloads with equal weight. This approach is sufficient for a single workload, but when multiple users and multiple workloads were applied on the same cluster or table, conflicts can arise. Fortunately, starting with HBase in CDH 5.2 (HBase 0.98 + backports), workloads and users can now be prioritized. #### Analytics [How to Track User Data Without Being Creepy](http://keenio.tumblr.com/post/104951439161/how-to-track-user-data-without-being-creepy) : There’s been a lot of scrutiny lately against companies who are acting irresponsibly with their data. This got me thinking a lot about data, ethics, and our moral responsibility as companies. Last month I gave a talk about ‘responsible analytics’ at Defrag 2014. My intention wasn’t to give a definitive decision-making guide, but to spark a discussion about the kinds of data we should and shouldn’t collect from our users. [Data science without statistics is possible, even desirable](http://www.datasciencecentral.com/xn/detail/6448529:BlogPost:231741) : The purpose of this article is to clarify a few misconceptions about data and statistical science. I will start with a controversial statement: data science barely uses statistical science and techniques. The truth is actually more nuanced, as explained below. [Open Sourcing Cubert: A High Performance Computation Engine for Complex Big Data Analytics](http://engineering.linkedin.com/big-data/open-sourcing-cubert-high-performance-computation-engine-complex-big-data-analytics) : What do you do when your Hadoop ETL script is mercilessly killed because it is hogging too many resources on the cluster, or if it starts missing completion deadlines by hours? We encountered this exact same problem more than a year ago while building the computation pipeline for XLNT, LinkedIn’s A/B testing platform. After wasting several months on optimization and tuning possibilities with Pig and Hive and still not meeting completion deadlines, we realized the problem needed an entirely new set of algorithms. Written completely in Java and built using several novel primitives, the new system proved effective in handling joins and aggregations on hefty datasets which allowed us to successfully launch XLNT #### Dataviz [What is the future of Data visualization and Dashboard solutions?](http://www.datasciencecentral.com/xn/detail/6448529:BlogPost:230684) : From time to time I keep pondering on what could be the future and I am sure lot of us get this science fiction imagery where the future data analyst will be given just a pair of holographic gloves and perform three dimensional analysis. ### Virtualization #### Docker [Advancing Docker Security: Docker 1.4.0 and 1.3.3 Releases](https://blog.docker.com/2014/12/advancing-docker-security-docker-1-4-0-and-1-3-3-releases/) : We’re pleased to announce that we have today released Docker Engine 1.4. What’s in it? As Solomon Hykes described last week at DockerCon Europe, its major “feature” is an emphasis on bug fixes and platform stability. Over 180 commits for fixes were merged! Docker 1.4 also adds the Overlay Filesystem as a new, experimental, storage driver. (see release notes and bump branch). [First experiment with Docker Machine](http://blog.loof.fr/2014/12/first-experiment-with-docker-machine.html) : Docker "machine" is a new command created by Docker team to manage docker servers you can deploy containers to. Think about boot2docker you use to run on your development workstation, but applied to all possible Cloud and on-premises hosting services. ### Log management [Operating Apache Samza at Scale](http://engineering.linkedin.com/samza/operating-apache-samza-scale) : At LinkedIn, we use a log-centric system called Apache Kafka to move tons of data around. If you're not familiar with Kafka, you can think of it as a publish-subscribe system that models each message as a log entry. However, it's difficult for a developer to spend their time thinking about a problem domain relevant to their application in addition to the complex fault tolerant semantics required to work with the log (Kafka's ISR is up there with Paxos in terms of understandability). [Alternative Logging Frameworks for Application Servers: WildFly](http://blog.c2b2.co.uk/2014/09/alternative-logging-frameworks-for.html) : Welcome to the third part of our blog series on configuring application servers to use alternative logging frameworks. This time we turn our gaze to WildFly, the open source application server from JBoss. Again, we'll be configuring it to use Log4j2 and SLF4J with Logback. ### Development #### PHP [Async – Cooperative Multitasking for Hack](http://hhvm.com/blog/7091/async-cooperative-multitasking-for-hack) : For several months now, Hack has had a feature available called async which enables writing code that cooperatively multitasks. This is somewhat similar to threading, in that multiple code paths are executed in parallel, however it avoids the lock contention issues common to multithreaded code by only actually executing one section at any given moment. ### Web performances [Reactive prefetch speeds Google's mobile search by 100-150 milliseconds.](http://highscalability.com/blog/2014/12/10/reactive-prefetch-speeds-googles-mobile-search-by-100-150-mi.html) : Increasing responsiveness by parallelizing and prefetching content using hints and dependency graphs, is an old concept, but seldom do we see such a nice tight example of the benefit as is given by the great Ilya Grigorik in this G+ post. [Beyond spreadsheets and waterfalls: 4 tools to make your performance data exciting (to people other than you)](http://www.webperformancetoday.com/2014/12/10/step-away-spreadsheet-4-great-tools-visualize-performance-data/) : One of my first experiences in witnessing the power of visualizing performance data was several years ago, when I started work at Strangeloop (which has since been acquired by Radware). We had been doing a proof of concept of our front-end optimization solution (then known as Site Optimizer, now called FastView) with a prospective customer. We had great results. Among other things, we cut start render and page load times by more than half on all the landing pages we tested on. [6 web performance books that every web developer should read](http://calendar.perfplanet.com/2014/6-web-performance-books-that-every-web-developer-should-read/) : For new developers that are starting to learn web development there is a lot to learn; HTML, CSS, and JavaScript just to mention a few! It’s important that new developers learn the importance of fast web pages and the positive effect that this can have on users. In this article I will list out my pick of 6 web performance books that every web developer should read. With Christmas just around the corner these books would make a great present for your web developers friends! ### Network [X-Raying the Internet Backbone: A 3D View of the AS Graph (Part 1)](http://labs.opendns.com/2014/12/11/macro-view-asn-part-1/) : Following up with our data visualization series, today we’re going to explore a brand new idea with OpenGraphiti. Everyday, network engineers manipulate real and virtual wires to connect people in the most efficient and reliable way possible. After decades of construction and evolution, it is fascinating to step back and contemplate the shape of this giant ecosystem. In this blog post, we will share some techniques to visualize the structure of the AS network: the backbone of our modern communication. #### SSL [SSL Performance Diary #4: Optimizing the TLS Handshake](http://zoompf.com/blog/2014/12/optimizing-tls-handshake) : In our prior SSL Performance Diary post, Optimizing Data Encryption, we mentioned there are 2 areas of TLS that can harbor performance problems: - Encrypting the data. Data sent back and forth between visiting web browsers and your web server must be encrypted and decrypted. If not configured properly, your page load times can become much slower than unencrypted traffic. - Establishing a secure connection. There are several steps that must occur before a browser establishes a secured connection to your website: identities must be confirmed, algorithms must be selected, and keys must be exchanged. This is known as the TLS Handshake and can have a significant impact on your site performance. [SSL Labs End of Year 2014 Updates](https://community.qualys.com/blogs/securitylabs/2014/12/08/ssl-labs-end-of-year-2014-updates) : From the SSL/TLS perspective, 2014 was quite an eventful year. The best way to describe what we at SSL Labs did is we kept running to stay in the same place. What I mean by this is that we spent a lot of time reacting to high profile vulnerabilities: Heartbleed, the ChangeCipherSpec protocol issue in OpenSSL, POODLE (against SSL 3 in October and against TLS in December), and others. Ultimately, this has been a very successful year for us, with millions of assessments carried out. [Poodle Bites TLS](https://community.qualys.com/blogs/securitylabs/2014/12/08/poodle-bites-tls) : There’s a new SSL/TLS problem being announced today and it’s likely to affect some of the most popular web sites in the world, owning largely to the popularity of F5 load balancers and the fact that these devices are impacted. There are other devices known to be affected, and it’s possible that the same flaw is present in some SSL/TLS stacks. We will learn more in the following days. ### Security [Best Practices for Cloud Logging, Security, & Data Protection](https://blog.logentries.com/2014/12/best-practices-for-cloud-logging-security-data-protection/) : When we first founded Logentries in 2010 a lot of people thought Viliam Holub (co-founder, CTO, and the brain behind processing billions and billions of log events in real time) and I were crazy. The common response was: “People are not going to send their logs to the cloud… logs might contain very sensitive data…” Like typical stubborn founders we persevered in spite of this, and today we have more than 35,000 users across 100 countries. Our customers also range from fortune 100 companies to individual developers across almost all verticals from SaaS companies, to healthcare, financial services, commerce and a bunch of others. So, why do companies now trust sending log data to a cloud based service? Id like to share some of the reasons we have found our customers are using secure, cloud-based logging. [Vulnerabilty disclosure - The Infinitely Delegating Name Servers (iDNS) Attack](http://www.ssi.gouv.fr/en/the-anssi/events/vulnerabilty-disclosure-the-infinitely-delegating-name-servers-idns-attack.html) : The French Network and Information Security Agency (ANSSI) identified a critical vulnerability in the three major open-source DNS recursive nameservers : BIND, Unbound and PowerDNS Recursor.
jbfavre/jbfavre.org
_posts/fr/2014-12-12-compilation-veille-twitter-rss.md
Markdown
mit
19,481
<HTML> <BODY BGCOLOR="white"> <PRE> <FONT color="green">001</FONT> /*<a name="line.1"></a> <FONT color="green">002</FONT> * Licensed to the Apache Software Foundation (ASF) under one or more<a name="line.2"></a> <FONT color="green">003</FONT> * contributor license agreements. See the NOTICE file distributed with<a name="line.3"></a> <FONT color="green">004</FONT> * this work for additional information regarding copyright ownership.<a name="line.4"></a> <FONT color="green">005</FONT> * The ASF licenses this file to You under the Apache License, Version 2.0<a name="line.5"></a> <FONT color="green">006</FONT> * (the "License"); you may not use this file except in compliance with<a name="line.6"></a> <FONT color="green">007</FONT> * the License. You may obtain a copy of the License at<a name="line.7"></a> <FONT color="green">008</FONT> *<a name="line.8"></a> <FONT color="green">009</FONT> * http://www.apache.org/licenses/LICENSE-2.0<a name="line.9"></a> <FONT color="green">010</FONT> *<a name="line.10"></a> <FONT color="green">011</FONT> * Unless required by applicable law or agreed to in writing, software<a name="line.11"></a> <FONT color="green">012</FONT> * distributed under the License is distributed on an "AS IS" BASIS,<a name="line.12"></a> <FONT color="green">013</FONT> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<a name="line.13"></a> <FONT color="green">014</FONT> * See the License for the specific language governing permissions and<a name="line.14"></a> <FONT color="green">015</FONT> * limitations under the License.<a name="line.15"></a> <FONT color="green">016</FONT> */<a name="line.16"></a> <FONT color="green">017</FONT> <a name="line.17"></a> <FONT color="green">018</FONT> package org.apache.commons.configuration;<a name="line.18"></a> <FONT color="green">019</FONT> <a name="line.19"></a> <FONT color="green">020</FONT> import java.util.Iterator;<a name="line.20"></a> <FONT color="green">021</FONT> <a name="line.21"></a> <FONT color="green">022</FONT> /**<a name="line.22"></a> <FONT color="green">023</FONT> * Strict comparator for configurations.<a name="line.23"></a> <FONT color="green">024</FONT> *<a name="line.24"></a> <FONT color="green">025</FONT> * @since 1.0<a name="line.25"></a> <FONT color="green">026</FONT> *<a name="line.26"></a> <FONT color="green">027</FONT> * @author &lt;a href="mailto:herve.quiroz@esil.univ-mrs.fr"&gt;Herve Quiroz&lt;/a&gt;<a name="line.27"></a> <FONT color="green">028</FONT> * @author &lt;a href="mailto:shapira@mpi.com"&gt;Yoav Shapira&lt;/a&gt;<a name="line.28"></a> <FONT color="green">029</FONT> * @version $Revision: 439648 $, $Date: 2006-09-02 22:42:10 +0200 (Sa, 02. Sep 2006) $<a name="line.29"></a> <FONT color="green">030</FONT> */<a name="line.30"></a> <FONT color="green">031</FONT> public class StrictConfigurationComparator implements ConfigurationComparator<a name="line.31"></a> <FONT color="green">032</FONT> {<a name="line.32"></a> <FONT color="green">033</FONT> /**<a name="line.33"></a> <FONT color="green">034</FONT> * Create a new strict comparator.<a name="line.34"></a> <FONT color="green">035</FONT> */<a name="line.35"></a> <FONT color="green">036</FONT> public StrictConfigurationComparator()<a name="line.36"></a> <FONT color="green">037</FONT> {<a name="line.37"></a> <FONT color="green">038</FONT> }<a name="line.38"></a> <FONT color="green">039</FONT> <a name="line.39"></a> <FONT color="green">040</FONT> /**<a name="line.40"></a> <FONT color="green">041</FONT> * Compare two configuration objects.<a name="line.41"></a> <FONT color="green">042</FONT> *<a name="line.42"></a> <FONT color="green">043</FONT> * @param a the first configuration<a name="line.43"></a> <FONT color="green">044</FONT> * @param b the second configuration<a name="line.44"></a> <FONT color="green">045</FONT> * @return true if keys from a are found in b and keys from b are<a name="line.45"></a> <FONT color="green">046</FONT> * found in a and for each key in a, the corresponding value<a name="line.46"></a> <FONT color="green">047</FONT> * is the sale in for the same key in b<a name="line.47"></a> <FONT color="green">048</FONT> */<a name="line.48"></a> <FONT color="green">049</FONT> public boolean compare(Configuration a, Configuration b)<a name="line.49"></a> <FONT color="green">050</FONT> {<a name="line.50"></a> <FONT color="green">051</FONT> if (a == null &amp;&amp; b == null)<a name="line.51"></a> <FONT color="green">052</FONT> {<a name="line.52"></a> <FONT color="green">053</FONT> return true;<a name="line.53"></a> <FONT color="green">054</FONT> }<a name="line.54"></a> <FONT color="green">055</FONT> else if (a == null || b == null)<a name="line.55"></a> <FONT color="green">056</FONT> {<a name="line.56"></a> <FONT color="green">057</FONT> return false;<a name="line.57"></a> <FONT color="green">058</FONT> }<a name="line.58"></a> <FONT color="green">059</FONT> <a name="line.59"></a> <FONT color="green">060</FONT> for (Iterator keys = a.getKeys(); keys.hasNext();)<a name="line.60"></a> <FONT color="green">061</FONT> {<a name="line.61"></a> <FONT color="green">062</FONT> String key = (String) keys.next();<a name="line.62"></a> <FONT color="green">063</FONT> Object value = a.getProperty(key);<a name="line.63"></a> <FONT color="green">064</FONT> if (!value.equals(b.getProperty(key)))<a name="line.64"></a> <FONT color="green">065</FONT> {<a name="line.65"></a> <FONT color="green">066</FONT> return false;<a name="line.66"></a> <FONT color="green">067</FONT> }<a name="line.67"></a> <FONT color="green">068</FONT> }<a name="line.68"></a> <FONT color="green">069</FONT> <a name="line.69"></a> <FONT color="green">070</FONT> for (Iterator keys = b.getKeys(); keys.hasNext();)<a name="line.70"></a> <FONT color="green">071</FONT> {<a name="line.71"></a> <FONT color="green">072</FONT> String key = (String) keys.next();<a name="line.72"></a> <FONT color="green">073</FONT> Object value = b.getProperty(key);<a name="line.73"></a> <FONT color="green">074</FONT> if (!value.equals(a.getProperty(key)))<a name="line.74"></a> <FONT color="green">075</FONT> {<a name="line.75"></a> <FONT color="green">076</FONT> return false;<a name="line.76"></a> <FONT color="green">077</FONT> }<a name="line.77"></a> <FONT color="green">078</FONT> }<a name="line.78"></a> <FONT color="green">079</FONT> <a name="line.79"></a> <FONT color="green">080</FONT> return true;<a name="line.80"></a> <FONT color="green">081</FONT> }<a name="line.81"></a> <FONT color="green">082</FONT> }<a name="line.82"></a> </PRE> </BODY> </HTML>
seeseekey/jenet
libs/commons-configuration-1.7/site/apidocs/src-html/org/apache/commons/configuration/StrictConfigurationComparator.html
HTML
mit
7,263
<?php $eZTranslationCacheCodeDate = 1058863428; $CacheInfo = array ( 'charset' => 'utf-8', ); $TranslationInfo = array ( 'context' => 'design/admin/content/edit', ); $TranslationRoot = array ( 'd5c6e07de8b9dccaac1d0452dee0b581' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> [%class_name]', 'comment' => NULL, 'translation' => 'Modifica <%object_name> [%class_name]', 'key' => 'd5c6e07de8b9dccaac1d0452dee0b581', ), 'e811c8a9685fbfaf39c964a635600fd5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translating content from %from_lang to %to_lang', 'comment' => NULL, 'translation' => 'Esecuzione traduzione del contenuto da %from_lang a %to_lang', 'key' => 'e811c8a9685fbfaf39c964a635600fd5', ), '11fb129ce59c549f147420ee3451ac24' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Send for publishing', 'comment' => NULL, 'translation' => 'Pubblica', 'key' => '11fb129ce59c549f147420ee3451ac24', ), '8c5749194e3baf11dddd5c34b1811596' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft', 'comment' => NULL, 'translation' => 'Registra bozza', 'key' => '8c5749194e3baf11dddd5c34b1811596', ), 'd506eed04b8a1daa90d9dbe145445605' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the contents of the draft that is being edited and continue editing. Use this button to periodically save your work while editing.', 'comment' => NULL, 'translation' => 'Registra i contenuti della bozza in fase di modifica e continua a modificare. Usa questo pulsante per salvare periodicamente il tuo lavoro mentre modifichi.', 'key' => 'd506eed04b8a1daa90d9dbe145445605', ), 'd7ebb04b02e47d0bd52637484b18f14e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard draft', 'comment' => NULL, 'translation' => 'Annulla bozza', 'key' => 'd7ebb04b02e47d0bd52637484b18f14e', ), '8ff4bdf4365cea79d60c64729aa5a3d7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published', 'comment' => NULL, 'translation' => 'Pubblicato', 'key' => '8ff4bdf4365cea79d60c64729aa5a3d7', ), 'd57eeb192509b0a21c9fb559e0875ee4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Modified', 'comment' => NULL, 'translation' => 'Modificato il', 'key' => 'd57eeb192509b0a21c9fb559e0875ee4', ), 'b5f9dcbfc8129dbad5a5a46430976cab' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Section', 'comment' => NULL, 'translation' => 'Sezione', 'key' => 'b5f9dcbfc8129dbad5a5a46430976cab', ), 'a8122643230a05433801fbfdc325b0ac' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Depth', 'comment' => NULL, 'translation' => 'Profondità', 'key' => 'a8122643230a05433801fbfdc325b0ac', ), 'de3a2815973e43df00aee9ea89c2e9ee' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Name', 'comment' => NULL, 'translation' => 'Nome', 'key' => 'de3a2815973e43df00aee9ea89c2e9ee', ), '0c449515a963c751510ea4a1c5ad5a16' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Priority', 'comment' => NULL, 'translation' => 'Priorità', 'key' => '0c449515a963c751510ea4a1c5ad5a16', ), '67bc86a3e97a3a3d92ea3beb65dd6e87' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations [%locations]', 'comment' => NULL, 'translation' => 'Collocazioni [%locations]', 'key' => '67bc86a3e97a3a3d92ea3beb65dd6e87', ), 'ab439be2c1960ef2864aba2706f3da54' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Invert selection.', 'comment' => NULL, 'translation' => 'Inverti selezione.', 'key' => 'ab439be2c1960ef2864aba2706f3da54', ), '49e8f0ddafe626663288d81e2fb49ca0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Location', 'comment' => NULL, 'translation' => 'Collocazione', 'key' => '49e8f0ddafe626663288d81e2fb49ca0', ), 'eef9b86d0bc32e55d39032df03d414f7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sub items', 'comment' => NULL, 'translation' => 'Sotto-elementi', 'key' => 'eef9b86d0bc32e55d39032df03d414f7', ), 'cc6dc33d8904d3c3b934998b16c5f64b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sorting of sub items', 'comment' => NULL, 'translation' => 'Ordinamento sotto-elementi', 'key' => 'cc6dc33d8904d3c3b934998b16c5f64b', ), '2f0a11483a590a1f6268a02200198343' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current visibility', 'comment' => NULL, 'translation' => 'Visibilità corrente', 'key' => '2f0a11483a590a1f6268a02200198343', ), '14d015346e3dcd669f6b7289e556c379' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visibility after publishing', 'comment' => NULL, 'translation' => 'Visibilità dopo la pubblicazione', 'key' => '14d015346e3dcd669f6b7289e556c379', ), 'f2d0aed249fd63a9ad7750f5e3b05826' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Main', 'comment' => NULL, 'translation' => 'Principale', 'key' => 'f2d0aed249fd63a9ad7750f5e3b05826', ), 'f0f5443a120379e97eaf90b672707d60' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Select location for removal.', 'comment' => NULL, 'translation' => 'Seleziona la collocazione da eliminare.', 'key' => 'f0f5443a120379e97eaf90b672707d60', ), '0de946921daa4f766d6cb8b899f50c1f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Desc.', 'comment' => NULL, 'translation' => 'Disc.', 'key' => '0de946921daa4f766d6cb8b899f50c1f', ), '876544ffd52dfaa722d262e22b1ccb50' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Asc.', 'comment' => NULL, 'translation' => 'Asc.', 'key' => '876544ffd52dfaa722d262e22b1ccb50', ), '783d1958da4861ba7dc9f1d396513661' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden by parent', 'comment' => NULL, 'translation' => 'Nascosto dal genitore', 'key' => '783d1958da4861ba7dc9f1d396513661', ), 'a7e239075d454945331613656140d9e4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visible', 'comment' => NULL, 'translation' => 'Visibile', 'key' => 'a7e239075d454945331613656140d9e4', ), '275526eb7c8f1a68977c1239e1905d67' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Unchanged', 'comment' => NULL, 'translation' => 'Non modificato', 'key' => '275526eb7c8f1a68977c1239e1905d67', ), '856d33ca67120cf3e125b3e674792f2d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden', 'comment' => NULL, 'translation' => 'Nascosto', 'key' => '856d33ca67120cf3e125b3e674792f2d', ), '9b78cdb793ba06dd24c1cb659fd8f18e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use these radio buttons to specify the main location (main node) for the object being edited.', 'comment' => NULL, 'translation' => 'Usa questi pulsanti radio per specificare la collocazione principale (nodo principale) dell\'oggetto in fase di modifica.', 'key' => '9b78cdb793ba06dd24c1cb659fd8f18e', ), '026f2a715a276e9d8d737446b9da0018' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Move to another location.', 'comment' => NULL, 'translation' => 'Sposta in un\'altra collocazione.', 'key' => '026f2a715a276e9d8d737446b9da0018', ), '30e0f7f35119baaa4d4454fbe2913660' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected', 'comment' => NULL, 'translation' => 'Elimina selezionati', 'key' => '30e0f7f35119baaa4d4454fbe2913660', ), '3bd76c0ad50229499785fd214b38a423' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected locations.', 'comment' => NULL, 'translation' => 'Elimina le collocazioni selezionate.', 'key' => '3bd76c0ad50229499785fd214b38a423', ), '91f558d19141ff4355d842ee41371638' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add locations', 'comment' => NULL, 'translation' => 'Aggiungi collocazioni', 'key' => '91f558d19141ff4355d842ee41371638', ), 'd1348b630823ba147fee6a3080b93e6a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add one or more locations for the object being edited.', 'comment' => NULL, 'translation' => 'Aggiungi una o più collocazioni per l\'oggetto in fase di modifica.', 'key' => 'd1348b630823ba147fee6a3080b93e6a', ), '24684de48a0e5f5cd59453cfaecf3fe2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Object information', 'comment' => NULL, 'translation' => 'Informazioni sull\'oggetto', 'key' => '24684de48a0e5f5cd59453cfaecf3fe2', ), '7ef3f2da93bc270f92af697bf09d2478' => array ( 'context' => 'design/admin/content/edit', 'source' => 'ID', 'comment' => NULL, 'translation' => 'ID', 'key' => '7ef3f2da93bc270f92af697bf09d2478', ), 'db6996ee096133dd3bf27a66d6c6a245' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Created', 'comment' => NULL, 'translation' => 'Creato il', 'key' => 'db6996ee096133dd3bf27a66d6c6a245', ), '3504c716aee9e860aea283ab634315f5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Not yet published', 'comment' => NULL, 'translation' => 'Non ancora pubblicato', 'key' => '3504c716aee9e860aea283ab634315f5', ), '8a20002c7443ef8d46e8fd516830827a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published version', 'comment' => NULL, 'translation' => 'Versione pubblicata', 'key' => '8a20002c7443ef8d46e8fd516830827a', ), '3b445a4b6127869d991f6b9f21540def' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Manage versions', 'comment' => NULL, 'translation' => 'Gestisci versioni', 'key' => '3b445a4b6127869d991f6b9f21540def', ), '459828e3bbf9aca1b85a34598762c68f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View and manage (copy, delete, etc.) the versions of this object.', 'comment' => NULL, 'translation' => 'Guarda ed amministra (copia, cancella, ecc.) le versioni di quest\'oggetto.', 'key' => '459828e3bbf9aca1b85a34598762c68f', ), '337ce19fed6e1043de7d521d5f20a58c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current draft', 'comment' => NULL, 'translation' => 'Bozza corrente', 'key' => '337ce19fed6e1043de7d521d5f20a58c', ), '3bc586e5f657cf80e47166d0049f6c75' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Version', 'comment' => NULL, 'translation' => 'Versione', 'key' => '3bc586e5f657cf80e47166d0049f6c75', ), '34ea08d6e0326ca7a804a034afd76eba' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View', 'comment' => NULL, 'translation' => 'Visualizza', 'key' => '34ea08d6e0326ca7a804a034afd76eba', ), 'e1668f1e0ee902c1ec6ce6b87fca974e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => 'e1668f1e0ee902c1ec6ce6b87fca974e', ), '9cfee90b36ba6a94a051395e41071d64' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store and exit', 'comment' => NULL, 'translation' => 'Registra ed esci', 'key' => '9cfee90b36ba6a94a051395e41071d64', ), '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modalità di modifica.', 'key' => '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e', ), 'deff3631a2a6a7aefe62c90e6f531393' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate', 'comment' => NULL, 'translation' => 'Traduci', 'key' => 'deff3631a2a6a7aefe62c90e6f531393', ), '15261022404c70f9d80d19670046617c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '15261022404c70f9d80d19670046617c', ), 'bdc9407d88adf5b51f71300747bc65b4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images [%related_images]', 'comment' => NULL, 'translation' => 'Immagini correlate [%related_images]', 'key' => 'bdc9407d88adf5b51f71300747bc65b4', ), '49e4893c354086bd227f26833da6fae3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files [%related_files]', 'comment' => NULL, 'translation' => 'File correlati [%related_files]', 'key' => '49e4893c354086bd227f26833da6fae3', ), 'fb0e2e8db005e5abbfc19f74d4d2ff59' => array ( 'context' => 'design/admin/content/edit', 'source' => 'File type', 'comment' => NULL, 'translation' => 'Tipo file', 'key' => 'fb0e2e8db005e5abbfc19f74d4d2ff59', ), 'cbe610719066288bb0f8f16e66eb60bf' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Size', 'comment' => NULL, 'translation' => 'Dimensione', 'key' => 'cbe610719066288bb0f8f16e66eb60bf', ), '7629938cdf31fb430956705c4f25915c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'XML code', 'comment' => NULL, 'translation' => 'Codice XML', 'key' => '7629938cdf31fb430956705c4f25915c', ), '2e759ee05aa1ad12add670edbc15d2c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '2e759ee05aa1ad12add670edbc15d2c2', ), '42720949af15fd05c21a1220ce7dcaed' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Type', 'comment' => NULL, 'translation' => 'Tipo', 'key' => '42720949af15fd05c21a1220ce7dcaed', ), 'a71c6cd033f06f84a746efa15bec425f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'There are no objects related to the one that is currently being edited.', 'comment' => NULL, 'translation' => 'Non vi sono oggetti correlati a quello attualmente in fase di modifica.', 'key' => 'a71c6cd033f06f84a746efa15bec425f', ), '7c9c383b8a6efc73a57865ea173956f4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove the selected items from the list(s) above. It is only the relations that will be removed. The items will not be deleted.', 'comment' => NULL, 'translation' => 'Elimina gli elementi selezionati dalla lista(e) in alto. Verranno eliminate solo le relazioni. Gli elementi non saranno eliminati.', 'key' => '7c9c383b8a6efc73a57865ea173956f4', ), 'e4bc8d93d24d7f58fcd273d10a85a787' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add existing', 'comment' => NULL, 'translation' => 'Aggiungi esistente', 'key' => 'e4bc8d93d24d7f58fcd273d10a85a787', ), '42bfc9071828350c26ed3c83b752a191' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add an existing item as a related object.', 'comment' => NULL, 'translation' => 'Aggiungi un elemento esistente come oggetto correlato.', 'key' => '42bfc9071828350c26ed3c83b752a191', ), 'ba94e70cabd1cb7edd98f029ed9e6219' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload new', 'comment' => NULL, 'translation' => 'Upload nuovo', 'key' => 'ba94e70cabd1cb7edd98f029ed9e6219', ), '5c9aa913f95d407fbb752e4cb03c31d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload a file and add it as a related object.', 'comment' => NULL, 'translation' => 'Carica un file e aggiungilo come oggetto correlato.', 'key' => '5c9aa913f95d407fbb752e4cb03c31d5', ), 'c32705fc7ed02108c0cc8637bfb014a3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft could not be stored.', 'comment' => NULL, 'translation' => 'La bozza non può essere registrata.', 'key' => 'c32705fc7ed02108c0cc8637bfb014a3', ), '0107a013d1906cdccde3185dac816952' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Required data is either missing or is invalid', 'comment' => NULL, 'translation' => 'I dati richiesti sono mancanti o non corretti', 'key' => '0107a013d1906cdccde3185dac816952', ), '4636bf4dbd364e83747d95d2e5291f09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following locations are invalid', 'comment' => NULL, 'translation' => 'Le seguenti collocazioni non sono valide', 'key' => '4636bf4dbd364e83747d95d2e5291f09', ), 'a4e029b88453feb1b89b03e5f94d7417' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was only partially stored.', 'comment' => NULL, 'translation' => 'Bozza registrata solo parzialmente.', 'key' => 'a4e029b88453feb1b89b03e5f94d7417', ), '5547c5c42894c60e4f4e423b62a29ea1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was successfully stored.', 'comment' => NULL, 'translation' => 'Registrazione bozza riuscita.', 'key' => '5547c5c42894c60e4f4e423b62a29ea1', ), '978390e9e54157ef85305dbab13222b8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Are you sure you want to discard the draft?', 'comment' => NULL, 'translation' => 'Sei sicuro di voler annullare la bozza?', 'key' => '978390e9e54157ef85305dbab13222b8', ), 'b2151a3ff3097b7918ffb0bf77ddd3d9' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard the draft that is being edited. This will also remove the translations that belong to the draft (if any).', 'comment' => NULL, 'translation' => 'Annulla la bozza in fase di modifica. Rimuoverai anche le traduzioni appartenenti alla bozza (se ve ne sono).', 'key' => 'b2151a3ff3097b7918ffb0bf77ddd3d9', ), '64b2382b215c4fa9830f9a21fb2c4ca8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate from', 'comment' => NULL, 'translation' => 'Traduci da', 'key' => '64b2382b215c4fa9830f9a21fb2c4ca8', ), '7410909128e3c35ccf9d14cceb80820e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'No translation', 'comment' => NULL, 'translation' => 'Nessuna traduzione', 'key' => '7410909128e3c35ccf9d14cceb80820e', ), 'a535d0e0c96877445a89aef4ee173dc4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit the current object showing the selected language as a reference.', 'comment' => NULL, 'translation' => 'Modifica i seguenti oggetti mostrando la lingua selezionata come riferimento.', 'key' => 'a535d0e0c96877445a89aef4ee173dc4', ), 'd692cfde1a62954707c8672718099413' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish data', 'comment' => NULL, 'translation' => 'Pubblica i dati', 'key' => 'd692cfde1a62954707c8672718099413', ), 'eb0ae2aa2dc3d1e21c38bb5c4216db5d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Back to edit', 'comment' => NULL, 'translation' => 'Torna alla modifica', 'key' => 'eb0ae2aa2dc3d1e21c38bb5c4216db5d', ), 'ec3eb846d3b45c2b95ac208645003f88' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Relation type', 'comment' => NULL, 'translation' => 'Tipo di relazione', 'key' => 'ec3eb846d3b45c2b95ac208645003f88', ), '54a0d205353a46d3d3a0e72dcb9de665' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Common', 'comment' => NULL, 'translation' => 'Comune', 'key' => '54a0d205353a46d3d3a0e72dcb9de665', ), '58e308c58d795fe23ce95b39e31631b0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Embedded', 'comment' => NULL, 'translation' => 'Incluso', 'key' => '58e308c58d795fe23ce95b39e31631b0', ), '3e931f75750447a56ff75badd13e66d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Linked', 'comment' => NULL, 'translation' => 'Collegato', 'key' => '3e931f75750447a56ff75badd13e66d5', ), '6f1be5a3016b77c751f014cba5abf62b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Attribute', 'comment' => NULL, 'translation' => 'Attributo', 'key' => '6f1be5a3016b77c751f014cba5abf62b', ), '630cf7951abe12d79a7d8e68e4e59b8c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to embed the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per includere l\'oggetto.', 'key' => '630cf7951abe12d79a7d8e68e4e59b8c', ), '88fc57c68a451c3ae68461cd1be0ac09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to link the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per collegare l\'oggetto.', 'key' => '88fc57c68a451c3ae68461cd1be0ac09', ), '2e6bc1eade5bc87d907d552c1f2850c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Top node', 'comment' => NULL, 'translation' => 'Nodo superiore', 'key' => '2e6bc1eade5bc87d907d552c1f2850c2', ), 'e21865e61399551e932cfa56e2f037c3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish the contents of the draft that is being edited. The draft will become the published version of the object.', 'comment' => NULL, 'translation' => 'Pubblica i contenuti della bozza in fase di modifica. La bozza diverrà la versione pubblicata dell\'oggetto.', 'key' => 'e21865e61399551e932cfa56e2f037c3', ), 'a0ff5452f01b802f02e9589528383468' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class identifier', 'comment' => NULL, 'translation' => 'Identificatore della classe', 'key' => 'a0ff5452f01b802f02e9589528383468', ), 'a03bc27f29960a05a2082afa54bd767f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class name', 'comment' => NULL, 'translation' => 'Nome della classe', 'key' => 'a03bc27f29960a05a2082afa54bd767f', ), '548d9e60b02ca3fea8f9eca6e5ea270b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will remain unchanged when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione non verrà modificata quando l\'oggetto verrà pubblicato.', 'key' => '548d9e60b02ca3fea8f9eca6e5ea270b', ), 'b84aa5ba3b4a29912b256550b85372d2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be created when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà creata quando l\'oggetto verrà pubblicato.', 'key' => 'b84aa5ba3b4a29912b256550b85372d2', ), '8dfc007c6f91ff521eb15a6ae1cfda44' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be moved when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà spostata quando l\'oggetto verrà pubblicato.', 'key' => '8dfc007c6f91ff521eb15a6ae1cfda44', ), '99deb2fe1a6237dcc341c6a0f3dc7980' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be removed when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà eliminata quando l\'oggetto verrà pubblicato.', 'key' => '99deb2fe1a6237dcc341c6a0f3dc7980', ), '1559f1473d1db10faf6251edb2bda77e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to remove this location.', 'comment' => NULL, 'translation' => 'Non hai i permessi per eliminare questa collocazione.', 'key' => '1559f1473d1db10faf6251edb2bda77e', ), 'fdd63332e502d8369d3cf5e937afc089' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting method for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare il metodo di ordinamento dei sotto-elementi di questa collocazione.', 'key' => 'fdd63332e502d8369d3cf5e937afc089', ), '6deedda369647ff46f481b752d545896' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting direction for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare la direzione di ordinamento dei sotto-elementi di questa collocazione.', 'key' => '6deedda369647ff46f481b752d545896', ), '657e97cded3ee381946c164372ca6986' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot add or remove locations because the object being edited belongs to a top node.', 'comment' => NULL, 'translation' => 'Non puoi aggiungere o eliminare collocazioni perché l\'oggetto in fase di modifica appartiene ad un nodo principale.', 'key' => '657e97cded3ee381946c164372ca6986', ), 'cc637428ff7420fa16299a1534569ba3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to view this object', 'comment' => NULL, 'translation' => 'Non sei abilitato a vedere quest\'oggetto', 'key' => 'cc637428ff7420fa16299a1534569ba3', ), 'e18abee452b4714bda51c8f4e41135ea' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot manage the versions of this object because there is only one version available (the one that is being edited).', 'comment' => NULL, 'translation' => 'Non puoi gestire le versioni di quest\'oggetto perché c\'è solo una versione disponibile (quella che viene modificata).', 'key' => 'e18abee452b4714bda51c8f4e41135ea', ), 'eb8bc6ee1e297b27503af0207afddca1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'States', 'comment' => NULL, 'translation' => 'Stati', 'key' => 'eb8bc6ee1e297b27503af0207afddca1', ), '6cd07f3dd6f612f4a629660e3f17f225' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following data is invalid according to the custom validation rules', 'comment' => NULL, 'translation' => 'I seguenti dati non sono validi sulla base delle regole di validazione impostate', 'key' => '6cd07f3dd6f612f4a629660e3f17f225', ), 'c134eae4296615056100774aba5c737c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Toggle fullscreen editing!', 'comment' => NULL, 'translation' => 'Tasto per la modifica a schermo intero!', 'key' => 'c134eae4296615056100774aba5c737c', ), '2b21fdd22aac1dc9d52badd4daa84cc8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft and exit', 'comment' => NULL, 'translation' => 'Registra bozza ed esci', 'key' => '2b21fdd22aac1dc9d52badd4daa84cc8', ), 'c19fe6950ef73d4a5aac038c6c2f3e1b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode. Use when you need to exit your work and return later to continue.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modifica. Usa questo pulsante per uscire dal tuo lavoro e tornare successivamente per continuare.', 'key' => 'c19fe6950ef73d4a5aac038c6c2f3e1b', ), '820c3bacd630fd295899e660ba22918c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> (%class_name)', 'comment' => NULL, 'translation' => 'Modifica <%object_name> (%class_name)', 'key' => '820c3bacd630fd295899e660ba22918c', ), '8950a2381757b6dd0db5091483661bb0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations (%locations)', 'comment' => NULL, 'translation' => 'Collocazioni (%locations)', 'key' => '8950a2381757b6dd0db5091483661bb0', ), '3965117f5e3158b59fe549e6cdba2c9a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview', 'comment' => NULL, 'translation' => 'Anteprima', 'key' => '3965117f5e3158b59fe549e6cdba2c9a', ), '6042d6c6f7e4f2e7e22e7c65162514ae' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Existing translations', 'comment' => NULL, 'translation' => 'Traduzioni esistenti', 'key' => '6042d6c6f7e4f2e7e22e7c65162514ae', ), '6763edccdd45769450ffd1434299bf10' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Base translation on', 'comment' => NULL, 'translation' => 'Traduzione di base su', 'key' => '6763edccdd45769450ffd1434299bf10', ), '21d0fdacb0a7736484e419ed81e22956' => array ( 'context' => 'design/admin/content/edit', 'source' => 'None', 'comment' => NULL, 'translation' => 'Nessuna', 'key' => '21d0fdacb0a7736484e419ed81e22956', ), '06304ec517378373e9de1c95fb429df1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '06304ec517378373e9de1c95fb429df1', ), 'b104c545ae07332644ae2d20a9f1384b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images (%related_images)', 'comment' => NULL, 'translation' => 'Immagini correlate (%related_images)', 'key' => 'b104c545ae07332644ae2d20a9f1384b', ), '3d94b5daec0e506ade7e107b6b73d978' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files (%related_files)', 'comment' => NULL, 'translation' => 'File correlati (%related_files)', 'key' => '3d94b5daec0e506ade7e107b6b73d978', ), '8adb2a84570bcb0cc99ec5ae9d73bf95' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '8adb2a84570bcb0cc99ec5ae9d73bf95', ), '58607b576d3d0e5e08333fccc24d840c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => '58607b576d3d0e5e08333fccc24d840c', ), '21cf1f883c2e361d5810fa6bc0eac58e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Path String', 'comment' => NULL, 'translation' => 'Stringa percorso', 'key' => '21cf1f883c2e361d5810fa6bc0eac58e', ), '03fb656941a080471b673d39a3d6d0fb' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Go to the top', 'comment' => NULL, 'translation' => 'Vai all\'inizio', 'key' => '03fb656941a080471b673d39a3d6d0fb', ), ); ?>
SnceGroup/snce-website
web/var/cache/translation/f1fa2db4683ed697d014961bf03dd47c/ita-IT/e1865bb9511c2e58519696970e878347.php
PHP
mit
32,257
--- layout: docs title: Abordagem description: Aprenda sobre o princípio deste guia, estratégias e técnicas usadas para construir e manter o Bootstrap de forma que você possa extender e customizá-lo mais facilmente. group: extend --- Enquanto as páginas _getting started_ servem como um _tour_ introdutório do projeto, esta foca no _porquê_ de fazermos as coisas da maneira que fazemos, no Bootstrap. Aqui, explicaremos nossa filosofia para desenvolver na web de maneira que outros possam aprender conosco, contribuir e nos ajudar a melhorar. Viu alguma coisa que não soou bem ou, talvez, poderia ser feita melhor? [Abra um issue](https://github.com/twbs/bootstrap/issues/new) e nós amaremos discutir com você! ## Sumário Nós vamos mergulhar de cabeça em cada um desses, mais a frente. No entanto, em resumo, isso resume nossa abordagem: - Componentes devem ser responsivos e mobile-first; - Componentes devem ser construídos com uma classe base e extendidos através de uma modificadora; - Estados de componentes devem seguir um padrão de escala z-index; - Sempre que possível, prefira uma implementação de HTML e CSS via JavaScript; - Sempre que possível, use utilitários invés de estilos customizados; - Sempre que possível, evite o uso de requisitos rígidos do HTML (seletor de filhos). ## Responsividade Os estilos responsivos do Bootstrap são construídos para serem responsivos, usando uma abordagem denominada _mobile-first_. Nós usamos esse termo em nossos documentos e, fortemente, concordamos com ele (apesar de algumas vezes ser complexo). Enquanto nem todos componentes _precisam_ ser responsivos no Bootstrap, essa abordagem responsiva ajuda a reduzir sobrescrição de CSS, te forçando a adicionar estilos de acordo com o crescimendo da _viewport_. Bootstrap adentro, você vai ver isso mais claramente com nossas _media queries_. Na maioria dos casos, nós usamos _media queries_ com `min-width` e que começam em um breakpoint específico e vão aumentando até outro breakpoint. Por exemplo, um seletor `.d-none` começa em `min-width: 0` e escala infinitamente. Por outro lado, um seletor `d-md-none` começa a escalar à partir de um breakpoint mediano. Algumas vezes, vamos usar `max-width` quando um dado componente precisar. Às vezes, essas sobrescrições são funcional e mentalmente mais fáceis de implementar e manter, invés de reescrever as funcionalidades principais dos nossos componentes. Nós tentamos limitar essa abordagem, mas nós vamos usá-la de tempo em tempo. ## Classes Excluindo o Reboot, nosso _reset_ cross-browser, todos nossos estilos visam usar classes como seletores. Isso significa que ficamos longe dos seletores de tipo (ex: `input[type="text"]`) e classes pais questionáveis (ex: `.pai .filho`) que fazem os estilos muito específicos, para que seja facil sobrescrever. De tal maneira, componentes devem ser construídos com uma classe base para propriedades e valores comuns que não serão sobrescritos. Por exemplo, `.btn` e `.btn-primary`. Nós usamos `.btn` para todos os estilos em comum como `display`, `padding` e `border-width`. Então, usamos modificadores como `.btn-primary` para adicionar a `color`, `background-color`, `border-color` e etc. Modificadores de classes devem apenas serem usados quando existirem diversas propriedades ou valores para serem alterados, em diversas variáveis. Modificadores não são sempre necessários, então, tenha certeza que você está realmente economizando linhas de código e evitando sobrescrições desnecessárias, quando for criá-los. Bons exemplos de modificadores são nossas classes de cores e as variantes de tamanhos. ## Escalas z-index Existem duas escalas `z-index` no Bootstrap: uma para elementos dentro de um componente e outra para sobreposição de componentes. ### Elementos de componentes - Alguns componentes no Bootstrap são construídos com elementos sobrepostos para evitar borda dupla, sem modificar a propriedade `border`. Por exemplo: grupos de botões, grupos de inputs e paginação; - Esses componentes compartilham uma escala `z-index` padrão de `0` até `3`; - `0` é o padrão (valor inicial), `1` é `:hover`, `2` é `:active`/`.active` e `3` é `:focus`; - Essa abordagem corresponde as nossas expectativas de maior prioridades do usuário. Se um elemento está focado, está à vista e recebendo atenção do usuário. Já elementos ativos são os segundos maiores porque indicam estado. Hover é o terceiro maior porque indica intenção de usuários, apesar que quase _nada_ usa `:hover`. ### Componentes de sobreposição Bootstrap possui vários componentes que funcionam como uma sobreposição de algum tipo. Isso inclui (de acordo com maior `z-index`): dropdowns, navbar fixas e sticky, modais, tooltips e popovers. Estes componentes possuem as próprias escalas `z-index` que começam em `1000`. Esse número inicial é aleatório e serve como um pequeno espaçamento entre nossos estilos e os estilos de seus próprios projetos. Cada componente de sobreposição possui seu valor `z-index` um pouco maior, de modo que princípios de UI comuns permitem que elementos com foco ou `:hover` estejam visíveis sempre. Por exemplo, um modal é um bloqueador de documentos (você não pode fazer mais nada, além de usar o modal), então, nós criamos ele com valor acima das navbars. Aprenda mais sobre isso na nossa [página de layout `z-index`]({{ site.baseurl }}/docs/{{ site.docs_version }}/layout/overview/#z-index). ## HTML e CSS invés de JS Sempre que possível, nós preferimos escrever HTML e CSS invés de JavaScript. No geral, HTML e CSS são mais presentes e acessívels para pessoas de diferentes níveis de experiência. HTML e CSS também são mais rápidos que JavaScript e seu navegador, geralmente, provê uma boa gama de funcionalidades para você. Nesse princípio, nossa API JavaScript principal é o atributo `data`. Você não precisa escrever quase nenhum JavaScript para usar nossos plugins JS, mas sim HTML. Leia mais sobre isso na nossa página de [visão geral JavaScript]({{ site.baseurl }}/docs/{{ site.docs_version }}/getting-started/javascript/#data-attributes). Por último, nossos estilos ajudam a desenvolver baseados em comportamentos fundamentais de elementos comuns na web. Sempre que possível, nós preferimos usar o que o navegador provê. Por exemplo, você pode colocar uma classe `.btn` em quase qualquer elemento, mas a maioria dos elementos não possuem valores semânticos ou funcionalidades em browsers. Desse modo, pelo contrário, nós usamos `<button>` e `<a>`. O mesmo acontece em componentes mais complexos. Enquanto nós *poderíamos* escrever nossos próprios plugins de validações de formulários para adicionarem classem a elementos pais (baseados em um estado de input) e, portanto, nos permitindo estilizar um texto em vermelho, nós preferimos usar os pseudo-elementos `:valid`/`:invalid` que todo browser suporta. ## Utilitários Classes "utilitárias" (antes "ajudantes", no Bootstrap 3) são poderosos aliados no combate ao CSS repetitivo e páginas pouco performáticas. Uma classe utilitária é, tipicamente, um único e imutável par propriedade-valor expresso como uma classe (ex: `.d-block` representa `display: block;`). A melhor vantagem delas é velocidade de uso quando escrevendo HTML e limitando a quantidade de CSS customizados que você tem que escrever. Especificamente, no que diz a respeito de CSS customizado, utilitários podem combater o crescimento de tamanho dos arquivos, reduzindo suas propriedades e valores mais usados à classes únicas. Isso pode ter um efeito incrível, nos seus projetos em escala. ## HTML Flexível Apesar de nem sempre ser possível, nós tentamos evitar sermos rígidos em nossos requisitos HTML para componentes. Portanto, nós focamos em classes únicas nos nossos seletores CSS, além de evitar seletores de filhos imediatos (`>`). Isto lhe dá mais flexibilidade em sua implementação e ajuda manter nosso CSS mais simples e menos específico.
bootstrapbrasil/bootstrap
site/docs/4.1/extend/approach.md
Markdown
mit
8,071
// Copyright (c) 2012-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; extern int nStakeMaxAge; extern int nStakeTargetSpacing; typedef std::map<int, unsigned int> MapModifierCheckpoints; // Hard checkpoints of stake modifiers to ensure they are deterministic static std::map<int, unsigned int> mapStakeModifierCheckpoints = boost::assign::map_list_of ( 0, 0xfd11f4e7 ) ( 1, 0x2dcbe358 ) ; // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet) static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Get time weight int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd) { // Kernel hash weight starts from 0 at the 30-day min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low // // Maximum TimeWeight is 90 days. return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge); } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64 GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64 GetStakeModifierSelectionInterval() { int64 nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash(); CDataStream ss(SER_GETHASH, 0); ss << hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } if (fDebug && GetBoolArg("-printstakemodifier")) printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64 nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); if (fDebug) { printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str()); } if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing); int64 nSelectionInterval = GetStakeModifierSelectionInterval(); int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64 nStakeModifierNew = 0; int64 nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); if (fDebug && GetBoolArg("-printstakemodifier")) printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (fDebug && GetBoolArg("-printstakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str()); } if (fDebug) { printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str()); } nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // The stake modifier used to hash for a stake kernel is chosen as the stake // modifier about a selection interval later than the coin generating the kernel static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake) { nStakeModifier = 0; if (!mapBlockIndex.count(hashBlockFrom)) return error("GetKernelStakeModifier() : block not indexed"); const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom]; nStakeModifierHeight = pindexFrom->nHeight; nStakeModifierTime = pindexFrom->GetBlockTime(); int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval(); const CBlockIndex* pindex = pindexFrom; // loop to find the stake modifier later by a selection interval while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) { if (!pindex->pnext) { // reached best block; may happen if node is behind on block chain if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime())) return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s", pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str()); else return false; } pindex = pindex->pnext; if (pindex->GeneratedStakeModifier()) { nStakeModifierHeight = pindex->nHeight; nStakeModifierTime = pindex->GetBlockTime(); } } nStakeModifier = pindex->nStakeModifier; return true; } // ppcoin kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coin age one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake at the time of the coin's confirmation // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage // txPrev.offset: offset of txPrev inside block, to reduce the chance of // nodes generating coinstake at the same time // txPrev.nTime: reduce the chance of nodes generating coinstake at the same // time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); int64 nValueIn = txPrev.vout[prevout.n].nValue; uint256 hashBlockFrom = blockFrom.GetHash(); CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60); targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256(); // Calculate hash CDataStream ss(SER_GETHASH, 0); uint64 nStakeModifier = 0; int nStakeModifierHeight = 0; int64 nStakeModifierTime = 0; if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) return false; ss << nStakeModifier; ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay) return false; if (fDebug && !fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, true, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx) { // v0.3 protocol return (nTimeBlock == nTimeTx); } // Get stake modifier checksum unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex) { assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); // Hash previous checksum with flags, hashProofOfStake and nStakeModifier CDataStream ss(SER_GETHASH, 0); if (pindex->pprev) ss << pindex->pprev->nStakeModifierChecksum; ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier; uint256 hashChecksum = Hash(ss.begin(), ss.end()); hashChecksum >>= (256 - 32); return hashChecksum.Get64(); } // Check stake modifier hard checkpoints bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum) { MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints); if (checkpoints.count(nHeight)) return nStakeModifierChecksum == checkpoints[nHeight]; return true; }
Rimbit/Wallets
src/kernel.cpp
C++
mit
18,814
<?php class Html { public static function LinkCSS($filename) { $link = Configuration::$base_dir."/Ressources/css/".$filename; return($link); } public static function LinkImage($filename) { $link = Configuration::$base_dir."/Ressources/images/".$filename; return($link); } public static function LinkJS($filename) { $link = Configuration::$base_dir."/Ressources/js/".$filename; return($link); } public static function Link($bundle, $action, array $params = null) { if (!isset($params)) return(Configuration::$base_dir."/".$bundle."/".$action); else { $link = Configuration::$base_dir."/".$bundle."/".$action; foreach ($params as $p) $link = $link."/".$p; return ($link); } } }
abclive/Lightning
Core/Html.php
PHP
mit
729
require 'cnpj' module Presenter class CNPJ < Each def output ::CNPJ.new(value).formatted end end end
thiagoa/super_form
lib/presenter/cnpj.rb
Ruby
mit
120
package main import ( "net/http" "github.com/freehaha/token-auth" "github.com/freehaha/token-auth/memory" "github.com/gorilla/mux" ) // Route type is used to define a route of the API type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } // Routes type is an array of Route type Routes []Route // NewRouter is the constructeur of the Router // It will create every routes from the routes variable just above func NewRouter() *mux.Router { tokenAuth := tauth.NewTokenAuth(nil, nil, memStore, nil) router := mux.NewRouter().StrictSlash(true) for _, route := range publicRoutes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } for _, route := range routes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(tokenAuth.HandleFunc(route.HandlerFunc)) } return router } var memStore = memstore.New("salty") var publicRoutes = Routes{ Route{"LogUser", "GET", "/user/{id}/login/{token}", LogUserController}, } var routes = Routes{ //Debt Route{"GetDebt", "GET", "/debt/{id}", GetDebtController}, Route{"DeleteDebt", "DELETE", "/debt/{id}", DeleteDebtController}, Route{"AddImageDebt", "POST", "/debt/{id}/image", AddImageDebtController}, Route{"ReimburseDebt", "PUT", "/debt/{id}", ReimburseDebtController}, //User + Debt Route{"GetMyDebts", "GET", "/user/{userID}/mydebt", GetMyDebtsController}, Route{"GetTheirDebts", "GET", "/user/{userID}/debt", GetTheirDebtsController}, Route{"CreateDebt", "POST", "/user/{userID}/debt", CreateDebtController}, //User Route{"GetUser", "GET", "/user/{id}", GetUserController}, Route{"CreateUser", "POST", "/user", CreateUserController}, Route{"DeleteUser", "DELETE", "/user/{id}", DeleteUserController}, Route{"AddPayee", "POST", "/user/{id}/payee/{payeeID}", AddPayeeController}, Route{"RemovePayee", "DELETE", "/user/{id}/payee/{payeeID}", RemovePayeeController}, //Notification Route{"GetNotification", "GET", "/user/{id}/notification", GetNotificationController}, }
fthomasmorel/reimburse-me-golang
routes.go
GO
mit
2,108
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <title>Psalm 151 151 (WEB)</title> <link href="../../../build/mobile.css" rel="stylesheet" /> <script src="../../../build/mobile.js"></script> </head> <body dir="ltr" class="section-document"> <div class="header"><div class="nav"> <a class="name" href="PX.html">World English Bible</a><a class="location" href="PX.html">Psalm 151 151</a><a class="prev" href=".html">&lt;</a> <a class="home" href="index.html">=</a> <a class="next" href="M31.html">&gt;</a> </div></div> <div class="section chapter PX PX151 eng_web eng " dir="ltr" lang="en" data-id="PX151" data-nextid="M31" data-previd=""> <div class="c">151</div> <div class="cp"> <span class="v null" data-id="null">151</span> </div> <div class="d">This Psalm is a genuine one of David, though extra,<span class="note" id="note-1"><a class="key" href="#footnote-1">+</a></span> composed when he fought in single combat with Goliath. </div> <div class="q"> <span class="v-num v-1">1&nbsp;</span><span class="v PX151_1" data-id="PX151_1">I was small among my brothers,</span> </div> <div class="q2"> <span class="v PX151_1" data-id="PX151_1">and youngest in my father’s house.</span> </div> <div class="q2"> <span class="v PX151_1" data-id="PX151_1">I tended my father’s sheep.</span> </div> <div class="q"> <span class="v-num v-2">2&nbsp;</span><span class="v PX151_2" data-id="PX151_2">My hands formed a musical instrument,</span> </div> <div class="q2"> <span class="v PX151_2" data-id="PX151_2">and my fingers tuned a lute.</span> </div> <div class="q"> <span class="v-num v-3">3&nbsp;</span><span class="v PX151_3" data-id="PX151_3">Who shall tell my Lord?</span> </div> <div class="q2"> <span class="v PX151_3" data-id="PX151_3">The Lord himself, he himself hears.</span> </div> <div class="q"> <span class="v-num v-4">4&nbsp;</span><span class="v PX151_4" data-id="PX151_4">He sent forth his angel and took me from my father’s sheep,</span> </div> <div class="q2"> <span class="v PX151_4" data-id="PX151_4">and he anointed me with his anointing oil.</span> </div> <div class="q"> <span class="v-num v-5">5&nbsp;</span><span class="v PX151_5" data-id="PX151_5">My brothers were handsome and tall;</span> </div> <div class="q2"> <span class="v PX151_5" data-id="PX151_5">but the Lord did not take pleasure in them.</span> </div> <div class="q"> <span class="v-num v-6">6&nbsp;</span><span class="v PX151_6" data-id="PX151_6">I went out to meet the Philistine,</span> </div> <div class="q2"> <span class="v PX151_6" data-id="PX151_6">and he cursed me by his idols.</span> </div> <div class="q"> <span class="v-num v-7">7&nbsp;</span><span class="v PX151_7" data-id="PX151_7">But I drew his own sword and beheaded him,</span> </div> <div class="q2"> <span class="v PX151_7" data-id="PX151_7">and removed reproach from the children of Israel.</span> </div> </div> <div class="footnotes"> <span class="footnote" id="footnote-1"><a class="key" href="#note-1">+</a><span class="text">undefined</span></span> </div> <div class="footer"><div class="nav"> <a class="prev" href=".html">&lt;</a> <a class="home" href="index.html">=</a> <a class="next" href="M31.html">&gt;</a> </div></div> </body> </html>
khangpng/VietnameseBible
app/content/texts/eng_web/PX151.html
HTML
mit
3,303
#include "smd3d.h" #define SMSFACE_MAX 1000 //Àӽà ÆäÀ̽º ¸ñ·Ï ÀúÀå Àå¼Ò smSTAGE_FACE *smFaceList[ SMSFACE_MAX ]; int smFaceListCnt; //°É¾î ´Ù´Ò¼ö ÀÖ´Â ÃÖ´ë °íÀúÂ÷ int Stage_StepHeight = 10*fONE; int smStage_WaterChk; //¹° ýũ¿ë Ç÷¢ smSTAGE_FACE *CheckFace=0; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetPlaneProduct( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *p ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int result; //º¤ÅÍ °è»ê ux = (p2->x - p1->x)>>6 ; uy = (p2->y - p1->y)>>6 ; uz = (p2->z - p1->z)>>6 ; vx = (p3->x - p1->x)>>6 ; vy = (p3->y - p1->y)>>6 ; vz = (p3->z - p1->z)>>6 ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>2 ; ny = (uz*vx - ux*vz)>>2 ; nz = (ux*vy - uy*vx)>>2 ; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( nx*((p->x-p1->x)>>6) + ny*((p->y-p1->y)>>6) + nz*((p->z-p1->z)>>6) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetThroughPlane( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep , POINT3D *cp ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int denominator , t; int lx,ly,lz; //º¤ÅÍ °è»ê ux = (p2->x - p1->x) ; uy = (p2->y - p1->y) ; uz = (p2->z - p1->z) ; vx = (p3->x - p1->x) ; vy = (p3->y - p1->y) ; vz = (p3->z - p1->z) ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>3; ny = (uz*vx - ux*vz)>>3; nz = (ux*vy - uy*vx)>>3; lx = ep->x - sp->x; ly = ep->y - sp->y; lz = ep->z - sp->z; denominator = ( nx * lx + ny * ly + nz * lz )>>3; if ( denominator!=0 ) { t = (( ( -nx * sp->x + nx * p1->x ) + ( -ny * sp->y + ny * p1->y ) + ( -nz * sp->z + nz * p1->z ) )<<3)/ denominator; // if ( t>=0 && t<=fONE ) { if ( t>=0 && t<=8 ) { cp->x = sp->x + ((lx * t)>>3); cp->y = sp->y + ((ly * t)>>3); cp->z = sp->z + ((lz * t)>>3); return TRUE; } } return FALSE; }; /* BOOL CollisionLineVSPolygon( LPD3DVECTOR lpCollisionPoint, LPD3DVECTOR lpLineBegin, LPD3DVECTOR lpLineEnd, LPD3DVECTOR lpPolygonVtx1, LPD3DVECTOR lpPolygonVtx2, LPD3DVECTOR lpPolygonVtx3 ) { // 1) get Polygon normal vector(CrossProduct) D3DVECTOR PolygonNormal, u, v; u.x = lpPolygonVtx2->x - lpPolygonVtx1->x; u.y = lpPolygonVtx2->y - lpPolygonVtx1->y; u.z = lpPolygonVtx2->z - lpPolygonVtx1->z; v.x = lpPolygonVtx3->x - lpPolygonVtx1->x; v.y = lpPolygonVtx3->y - lpPolygonVtx1->y; v.z = lpPolygonVtx3->z - lpPolygonVtx1->z; PolygonNormal.x = u.y*v.z - u.z*v.y; PolygonNormal.y = u.z*v.x - u.x*v.z; PolygonNormal.z = u.x*v.y - u.y*v.x; // 2) get t of Line equation( 0 <= t <= 1 ) D3DVALUE denominator = ((PolygonNormal.x * ( lpLineEnd->x - lpLineBegin->x) ) + (PolygonNormal.y * ( lpLineEnd->y - lpLineBegin->y) ) + (PolygonNormal.z * ( lpLineEnd->z - lpLineBegin->z) ) ); D3DVALUE t; if( denominator != 0 ) { t = (( -PolygonNormal.x * lpLineBegin->x + PolygonNormal.x * lpPolygonVtx1->x) + ( -PolygonNormal.y * lpLineBegin->y + PolygonNormal.y * lpPolygonVtx1->y) + ( -PolygonNormal.z * lpLineBegin->z + PolygonNormal.z * lpPolygonVtx1->z) ) / denominator; if( ( t >= 0.0f ) && ( t <= 1.0f ) ) { lpCollisionPoint->x = lpLineBegin.x + (lpLineEnd->x - lpLineBegin->x) * t; lpCollisionPoint->y = lpLineBegin.y + (lpLineEnd->y - lpLineBegin->y) * t; lpCollisionPoint->z = lpLineBegin.z + (lpLineEnd->z - lpLineBegin->z) * t; return TRUE; } else return FALSE; } else return FALSE; } */ int smGetTriangleImact( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep ) { int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1,c2; c1 = smGetPlaneProduct( p1 , p2 , p3 , sp ); c2 = smGetPlaneProduct( p1 , p2 , p3 , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) return FALSE; vx = (ep->x - sp->x)<<4; vy = (ep->y - sp->y)<<4; vz = (ep->z - sp->z)<<4; cp1.x = p1->x + vx; cp1.y = p1->y + vy; cp1.z = p1->z + vz; cp2.x = p2->x + vx; cp2.y = p2->y + vy; cp2.z = p2->z + vz; cp3.x = p3->x + vx; cp3.y = p3->y + vy; cp3.z = p3->z + vz; c1 = smGetPlaneProduct( p1 , p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p2 , p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p3 , p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; int smGetTriangleOnArea( smSTAGE_VERTEX *sp1 , smSTAGE_VERTEX *sp2 , smSTAGE_VERTEX *sp3 , POINT3D *sp ) { // int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1;//,c2; POINT3D p1,p2,p3; p1.x = sp1->x; p1.y = sp1->y; p1.z = sp1->z; p2.x = sp2->x; p2.y = sp2->y; p2.z = sp2->z; p3.x = sp3->x; p3.y = sp3->y; p3.z = sp3->z; cp1.x = p1.x; cp1.y = p1.y - 32*fONE; cp1.z = p1.z; cp2.x = p2.x; cp2.y = p2.y - 32*fONE; cp2.z = p2.z; cp3.x = p3.x; cp3.y = p3.y - 32*fONE; cp3.z = p3.z; c1 = smGetPlaneProduct( &p1 , &p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p2 , &p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p3 , &p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetPlaneProduct( smSTAGE_FACE *face , POINT3D *p ) { int result; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( (face->VectNormal[0]>>4) * ((p->x - vp->x)>>4) + (face->VectNormal[1]>>4) * ((p->y - vp->y)>>4) + (face->VectNormal[2]>>4) * ((p->z - vp->z)>>4) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetThroughPlane( smSTAGE_FACE *face , POINT3D *sp , POINT3D *ep ) { // int result; POINT3D p1,p2,p3,cp,ssp,eep; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x>>5; p1.y = vp->y>>5; p1.z = vp->z>>5; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x>>5; p2.y = vp->y>>5; p2.z = vp->z>>5; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x>>5; p3.y = vp->y>>5; p3.z = vp->z>>5; ssp.x = sp->x>>5; ssp.y = sp->y>>5; ssp.z = sp->z>>5; eep.x = ep->x>>5; eep.y = ep->y>>5; eep.z = ep->z>>5; return smGetThroughPlane( &p1,&p2,&p3,&ssp,&eep,&cp ); }; //smGetThroughPlane smSTAGE_FACE *DebugFace = 0; WORD DebugFaceMat = 0; //°¢ ¶óÀÎÀÌ ÆäÀ̽º¸¦ °üÅëÇÏ´ÂÁö °Ë»çÇÑ´Ù ( ¸ðµç ¼±ºÐÀÌ °üÅëÇÏÁö ¾ÊÀ» °æ¿ì TRUE ±×¿ÜÀÇ °æ¿ì FALSE ) int smSTAGE3D::GetTriangleImact( smSTAGE_FACE *face, smLINE3D *pLines , int LineCnt ) { int vx,vy,vz; POINT3D p1,p2,p3; POINT3D cp; POINT3D *sp,*ep; int c1,c2; smSTAGE_VERTEX *vp; int cnt; int flag , TrueCnt; //ÆäÀ̽ºÀÇ ÁÂÇ¥3°³¸¦ Æ÷ÀÎÅÍ·Î ¸¸µë vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x; p1.y = vp->y; p1.z = vp->z; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x; p2.y = vp->y; p2.z = vp->z; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x; p3.y = vp->y; p3.z = vp->z; TrueCnt = 0; for(int cnt=0;cnt<LineCnt;cnt++ ) { sp = &pLines[cnt].sp; ep = &pLines[cnt].ep; flag = TRUE; if ( ((sp->y<p1.y && sp->y<p2.y && sp->y<p3.y) || (sp->y>p1.y && sp->y>p2.y && sp->y>p3.y) ) && ((ep->y<p1.y && ep->y<p2.y && ep->y<p3.y) || (ep->y>p1.y && ep->y>p2.y && ep->y>p3.y) ) ) flag = FALSE; if ( flag ) { //Æò¸éÀ» °üÅëÇÏ´ÂÁö È®ÀÎ c1 = GetPlaneProduct( face , sp ); c2 = GetPlaneProduct( face , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) flag = FALSE; // if ( GetThroughPlane( face , sp , ep )==FALSE ) // flag = FALSE; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( flag == TRUE ) //{ // vx = (ep->x - sp->x)<<8; // vy = (ep->y - sp->y)<<8; // vz = (ep->z - sp->z)<<8; //} //»ï°¢Çü°ú ¿¬Àå¼± ÁÂÇ¥ Æò¸é Á¦ÀÛ if ( c1<=0 ) { vx = (ep->x - sp->x)<<8; vy = (ep->y - sp->y)<<8; vz = (ep->z - sp->z)<<8; } else { vx = (sp->x - ep->x)<<8; vy = (ep->y - ep->y)<<8; vz = (ep->z - ep->z)<<8; } //###################################################################################### // Åë°úÇÏ´Â ¼±ÀÌ »ï°¢Çü ¿µ¿ª ¾È¿¡ ÀÖ´ÂÁö Á¶»ç // 3°³ÀÇ °¡»óÀÇ Æò¸éÀ» ¸¸µé¾î Æò¸éÀ§Ä¡¸¦ È®ÀÎÇÏ´Â ¹æ¹ý if ( flag==TRUE ) { cp.x = p1.x + vx; cp.y = p1.y + vy; cp.z = p1.z + vz; c1 = smGetPlaneProduct( &p1 , &p2 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p2.x + vx; cp.y = p2.y + vy; cp.z = p2.z + vz; c1 = smGetPlaneProduct( &p2 , &p3 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p3.x + vx; cp.y = p3.y + vy; cp.z = p3.z + vz; c1 = smGetPlaneProduct( &p3 , &p1 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if ( flag==TRUE ) { return TRUE; } } } return FALSE; } //TÀ̵¿ÇÒ À§Ä¡¸¦ TÀÚ ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeTLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*12; int PosiMaxY = ObjHeight-(ObjHeight>>2); width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=Posi->x+GeoResult_X; Lines[2].sp.y=Posi->y+GeoResult_Y; Lines[2].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=Posi->x+GeoResult_X; Lines[2].ep.y=Posi->y+GeoResult_Y; Lines[2].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=Posi->x+GeoResult_X; Lines[3].sp.y=Posi->y+GeoResult_Y; Lines[3].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=Posi->x+GeoResult_X; Lines[3].ep.y=Posi->y+GeoResult_Y; Lines[3].ep.z=Posi->z+GeoResult_Z; return 4; } //XÀ̵¿ÇÒ À§Ä¡¸¦ X ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeXLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*15; int PosiMaxY = ObjHeight-(ObjHeight>>2); int left,right,top,bottom; width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; left = -width; right = width; top = -width; bottom = width; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, -width, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=ep->x+GeoResult_X; Lines[2].sp.y=ep->y+GeoResult_Y; Lines[2].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, width, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=ep->x+GeoResult_X; Lines[2].ep.y=ep->y+GeoResult_Y; Lines[2].ep.z=ep->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, width, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=ep->x+GeoResult_X; Lines[3].sp.y=ep->y+GeoResult_Y; Lines[3].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, -width, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=ep->x+GeoResult_X; Lines[3].ep.y=ep->y+GeoResult_Y; Lines[3].ep.z=ep->z+GeoResult_Z; return 6; } class smCHAR; //´Ù¸¥ ij¸¯ÅÍ¿ÍÀÇ À§Ä¡ °ãÄ¡´ÂÁö È®ÀÎ extern smCHAR *CheckOtherPlayPosi( int x, int y, int z ); //À̵¿ÇÒ ¹æÇâ°ú À§Ä¡¸¦ °Ë»çÇÏ¿© ÁÂÇ¥¸¦ µ¹·ÁÁØ´Ù int smSTAGE3D::CheckNextMove( POINT3D *Posi, POINT3D *Angle , POINT3D *MovePosi, int dist , int ObjWidth , int ObjHeight , int CheckOverLap ) { int he,height; // int num, fnum; int cnt; smSTAGE_FACE *face; // int CalcSum; POINT3D ep; POINT3D zAngle[3]; smLINE3D Lines[8]; //int left,right,top,bottom; if ( !Head ) return NULL; CheckFace = 0; smStage_WaterChk = CLIP_OUT; height = CLIP_OUT; zAngle[0].x = Angle->x; zAngle[0].y = Angle->y; zAngle[0].z = Angle->z; zAngle[1].x = Angle->x; zAngle[1].y = (Angle->y- 768) & ANGCLIP; zAngle[1].z = Angle->z; zAngle[2].x = Angle->x; zAngle[2].y = (Angle->y+ 768) & ANGCLIP; zAngle[2].z = Angle->z; int hy; int heFace; int acnt; int cnt2; int Sucess = 0; int Oly = Posi->y; int WaterHeight; int whe; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return NULL; int ccnt; int LineCnt; WaterHeight = CLIP_OUT; for( ccnt=0;ccnt<3;ccnt++ ) { LineCnt = smMakeTLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); // LineCnt = smMakeXLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , ep.x, ep.z ); if ( he!=CLIP_OUT ) { hy = he-ep.y; if ( hy< Stage_StepHeight ) {//10*fONE ) { if ( height<he ) { height = he; heFace = cnt; } } CheckFace = face; } } else { //if (smMaterial[ face->Vertex[3] ].Transparency!=0.1) { // //±âÁ¸¿¡ ¿øº». if (smMaterial[ face->Vertex[3] ].Transparency>0.1) { //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( smMaterial[face->Vertex[3]].Transparency > 0.1 || smMaterial[face->Vertex[3]].MeshState & sMATS_SCRIPT_ORG_WATER ) //###################################################################################### { //¹° ³ôÀÌ °è»ê he = GetPolyHeight( face , ep.x, ep.z ); if ( WaterHeight<he ) WaterHeight = he; } } } if ( height!=CLIP_OUT ) { smStage_WaterChk = WaterHeight; whe = (height+(ObjHeight>>1))+10*fONE; if ( WaterHeight!=CLIP_OUT && WaterHeight>whe && WaterHeight<whe+5*fONE ) { //¹°¼Ó¿¡ Àá±è //return FALSE; cnt2 = 0; } else { for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], Lines ,LineCnt )==TRUE ) { cnt2=-1; break; } } } } if ( cnt2>0 ) { if ( CheckOverLap ) { if ( ccnt>0 && CheckOtherPlayPosi( ep.x , height, ep.z )==NULL ) { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } else { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } } if ( ccnt==0 ) dist>>=1; } CheckFace = 0; return NULL; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy<10*fONE ) { if ( height<he ) { height = he; } } } } } return height; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight2( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy>10*fONE ) { if ( height>he ) { height = he; } } } } } return height; } //ÇöÀç ³ôÀÌ¿¡ °ãÄ¡´Â Æú¸®°ïÀÌ ÀÖ´Â Áö È®ÀÎÈÄ ÀÖÀ¸¸é Àüü ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetEmptyHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; int fchk; fchk = 0; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { if ( height<he ) { height = he; } if ( he<y+ObjHeight && he>y ) fchk++; } } } if ( fchk==0 ) return NULL; return height; } //¹Ù´Ú Æú¸®°ï ¸é¿¡ y==height ¿Í ÀÏÄ¡ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckFloorFaceHeight( int x, int y, int z , int hSize ) { int cnt; smSTAGE_FACE *face; int height = 1000000; int acnt; int he; int hy = fONE*16384; acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = abs(GetPolyHeight( face , x, z )-y); if ( he<height ) height = he; if ( he<=hSize ) return 0; } } if ( height==1000000 ) height = CLIP_OUT; return height; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact( POINT3D *Posi, POINT3D *Angle , int dist ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*64); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return TRUE; memcpy( &sLine[0].sp , Posi , sizeof( POINT3D ) ); GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); sLine[0].ep.x = Posi->x+GeoResult_X; sLine[0].ep.y = Posi->y+GeoResult_Y; sLine[0].ep.z = Posi->z+GeoResult_Z; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return FALSE; } } } Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return TRUE; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact2( int sx,int sy,int sz, int ex,int ey,int ez ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*128); acnt = MakeAreaFaceList( sx-fONE*64*1 , sz-fONE*64*1 , fONE*64*2 , fONE*64*2 , sy+hy , sy-hy ); if ( !acnt ) return TRUE; sLine[0].sp.x = sx; sLine[0].sp.y = sy; sLine[0].sp.z = sz; sLine[0].ep.x = ex; sLine[0].ep.y = ey; sLine[0].ep.z = ez; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { return FALSE; } } } return TRUE; } smSTAGE3D::smSTAGE3D() { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; } smSTAGE3D::~smSTAGE3D() { Close(); } smSTAGE3D::smSTAGE3D( int nv , int nf ) { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; Init( nv, nf ); } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® void smSTAGE3D::Init(void) { nLight = 0; nTexLink = 0; nFace = 0; nVertex = 0; ::ZeroMemory( StageArea, sizeof(StageArea) ); AreaList = NULL; Vertex = NULL; Face = NULL; TexLink = NULL; smLight = NULL; smMaterialGroup = NULL; StageObject = NULL; smMaterial = NULL; lpwAreaBuff = NULL; } //###################################################################################### int smSTAGE3D::Init( int nv , int nf ) { Vertex = new smSTAGE_VERTEX[ nv ]; Face = new smSTAGE_FACE[ nf ]; TexLink = new smTEXLINK[ nf * 4 ]; StageObject = new smSTAGE_OBJECT; nVertex = 0; nFace = 0; nTexLink = 0; nVertColor = 0; SumCount = 0; CalcSumCount = 0; smMaterialGroup = 0; lpwAreaBuff = 0; StageMapRect.top = 0; StageMapRect.bottom = 0; StageMapRect.left = 0; StageMapRect.right = 0; clearStageArea(); return TRUE; } int smSTAGE3D::Close() { Head = 0; /* int cnt,cnt2; int num; for( cnt2=MAP_SIZE-1;cnt2>=0;cnt2--) { for( cnt=MAP_SIZE-1;cnt>=0;cnt-- ) { num = (int)StageArea[ cnt ][ cnt2 ]; if ( num>0 ) { delete StageArea[cnt][cnt2]; } } } */ /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö */ if ( nLight ) delete smLight; if ( lpwAreaBuff ) delete lpwAreaBuff; if ( nTexLink ) delete TexLink; if ( nFace ) delete Face; if ( nVertex ) delete Vertex; if ( StageObject ) delete StageObject; if ( smMaterialGroup ) delete smMaterialGroup; return TRUE; } //¹öÅØ½º ÁÂÇ¥ Ãß°¡ int smSTAGE3D::AddVertex ( int x, int y, int z ) { Vertex[nVertex].sum = 0; Vertex[nVertex].x = x; Vertex[nVertex].y = y; Vertex[nVertex].z = z; Vertex[nVertex].sDef_Color[ SMC_R ] = 255; Vertex[nVertex].sDef_Color[ SMC_G ] = 255; Vertex[nVertex].sDef_Color[ SMC_B ] = 255; Vertex[nVertex].sDef_Color[ SMC_A ] = 255; if ( nVertex==0 ) { //¸ÇóÀ½ °ªÀ¸·Î ÃʱâÈ­ StageMapRect.top = z; StageMapRect.bottom = z; StageMapRect.left = x; StageMapRect.right = x; } else { //Á¸Àç ÇÏ´Â ±¸¿ªÅ©±â ¼³Á¤ if ( StageMapRect.top>z ) StageMapRect.top = z; if ( StageMapRect.bottom<z ) StageMapRect.bottom = z; if ( StageMapRect.left>x ) StageMapRect.left = x; if ( StageMapRect.right<x ) StageMapRect.right = x; } nVertex++; return (nVertex-1); } //ÆäÀ̽º Ãß°¡ int smSTAGE3D::AddFace ( int a, int b, int c , int matrial ) { Face[nFace].sum = 0; Face[nFace].Vertex[0] = a; Face[nFace].Vertex[1] = b; Face[nFace].Vertex[2] = c; Face[nFace].Vertex[3] = matrial; Face[nFace].lpTexLink = 0; // ÅØ½ºÃÄ ¿¬°á ÁÂÇ¥ nFace++; /* //µð¹ö±ë¿ë int x,z,sx,sz; x = abs( Vertex[a].x - Vertex[b].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].x - Vertex[c].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].x - Vertex[a].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[a].z - Vertex[b].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].z - Vertex[c].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].z - Vertex[a].z ); if ( x>64*30*fONE ) { x = x; } */ return nFace-1; } //ÆäÀ̽º¿¡ ¸ÞÆ®¸®¾ó ÀÔ·Â int smSTAGE3D::SetFaceMaterial( int FaceNum , int MatNum ) { Face[ FaceNum ].Vertex[3] = MatNum; return TRUE; } //¹öÅØ½º¿¡ »ö ¼³Á¤ int smSTAGE3D::SetVertexColor ( DWORD NumVertex , BYTE r , BYTE g, BYTE b , BYTE a ) { Vertex[ NumVertex ].sDef_Color[ SMC_R ] = r; Vertex[ NumVertex ].sDef_Color[ SMC_G ] = g; Vertex[ NumVertex ].sDef_Color[ SMC_B ] = b; Vertex[ NumVertex ].sDef_Color[ SMC_A ] = a; return TRUE; } //ÅØ½ºÃÄ ÁÂÇ¥¿¬°áÀ» Ãß°¡ÇÑ´Ù int smSTAGE3D::AddTexLink( int FaceNum , DWORD *hTex , smFTPOINT *t1 , smFTPOINT *t2 , smFTPOINT *t3 ) { int cnt; smTEXLINK *tl; //ÁÂÇ¥¼³Á¤ TexLink[ nTexLink ].u[0] = t1->u; TexLink[ nTexLink ].v[0] = t1->v; TexLink[ nTexLink ].u[1] = t2->u; TexLink[ nTexLink ].v[1] = t2->v; TexLink[ nTexLink ].u[2] = t3->u; TexLink[ nTexLink ].v[2] = t3->v; TexLink[ nTexLink ].hTexture = hTex; TexLink[ nTexLink ].NextTex = 0; //ÁöÁ¤µÈ ÆäÀ̽º¿Í ¿¬°á½ÃŲ´Ù if ( !Face[FaceNum].lpTexLink ) { //ÃÖÃÊÀÇ ÅØ½ºÃÄÁÂÇ¥ÀÏ °æ¿ì Face[FaceNum].lpTexLink = &TexLink[ nTexLink ]; } else { //ÀÌ¹Ì ¿¬°áµÇÀÖ´Â ÁÂÇ¥°¡ Àִ°æ¿ì tl = Face[FaceNum].lpTexLink; for(int cnt=0;cnt<8;cnt++ ) { if ( !tl->NextTex ) { //¸¶Áö¸·À¸·Î ¿¬°áµÈ ÁÂÇ¥¸¦ ã¾Æ ¿¬°á tl->NextTex = &TexLink[ nTexLink ]; break; } else { //´ÙÀ½ ÁÂÇ¥·Î ³Ñ±è tl = tl->NextTex; } } } nTexLink++; return nTexLink-1; } //³ë¸» °ªÀ» ±¸ÇÏ¿© ¹öÅØ½º¿¡ ½¦À̵ù ¸í¾ÏÀ» Ãß°¡ÇÑ´Ù //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::SetVertexShade( int isSetLight ) //###################################################################################### { int cnt; int cnt2; POINT3D p[3]; POINT3D pn; POINT3D *normal; POINT3D pLight; int *NormalCnt; int gShade; int r,g,b; memcpy( &pLight , &VectLight , sizeof( POINT3D ) ); normal = new POINT3D[nVertex]; NormalCnt = new int [nVertex]; // Normal°ª ÃʱâÈ­ for(int cnt=0; cnt<nVertex ;cnt++) { normal[cnt].x = 0; normal[cnt].y = 0; normal[cnt].z = 0; NormalCnt[cnt] = 0; } // NormalÁÂÇ¥ ±¸ÇÔ for(int cnt=0; cnt<nFace; cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } SetNormal( &p[0], &p[1], &p[2] , &pn ); //Face ³ë¸»º¤ÅÍ ¼³Á¤ Face[cnt].VectNormal[0] = (short)pn.x; Face[cnt].VectNormal[1] = (short)pn.y; Face[cnt].VectNormal[2] = (short)pn.z; for(cnt2=0;cnt2<3;cnt2++) { normal[ Face[cnt].Vertex[cnt2] ].x += pn.x; normal[ Face[cnt].Vertex[cnt2] ].y += pn.y; normal[ Face[cnt].Vertex[cnt2] ].z += pn.z; NormalCnt[ Face[cnt].Vertex[cnt2] ] ++; } } // gShade ³ë¸» ±¸ÇÑµÚ RGBA·Î ¹öÅØ½º¿¡ ÀúÀå for(int cnt=0; cnt<nVertex; cnt++ ) { if ( NormalCnt[ cnt ]>0 ) { normal[ cnt ].x /= NormalCnt[cnt]; normal[ cnt ].y /= NormalCnt[cnt]; normal[ cnt ].z /= NormalCnt[cnt]; } pn.x = normal[ cnt ].x; pn.y = normal[ cnt ].y; pn.z = normal[ cnt ].z; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( isSetLight ) { gShade = ((pn.x * pLight.x) + (pn.y * pLight.y) + (pn.z * pLight.z)) >> FLOATNS; gShade /= Contrast; //CONTRAST gShade += Bright; //BRIGHT r = Vertex[ cnt ].sDef_Color[ SMC_R ]; g = Vertex[ cnt ].sDef_Color[ SMC_G ]; b = Vertex[ cnt ].sDef_Color[ SMC_B ]; r = ( r*gShade )>>8; // %1ºñÀ² x 0 ~ 2 ±îÁö g = ( g*gShade )>>8; b = ( b*gShade )>>8; Vertex[ cnt ].sDef_Color[SMC_R] = r; Vertex[ cnt ].sDef_Color[SMC_G] = g; Vertex[ cnt ].sDef_Color[SMC_B] = b; Vertex[ cnt ].sDef_Color[SMC_A] = 255; //Alpha } //###################################################################################### } float transp; for(int cnt=0;cnt<nFace;cnt++) { transp = smMaterial[ Face[cnt].Vertex[3] ].Transparency; if ( transp>0 ) { for( cnt2=0;cnt2<3;cnt2++ ) { Vertex[ Face[cnt].Vertex[cnt2] ].sDef_Color[ SMC_A ] = 255-((BYTE)(transp * 255)); } } } delete NormalCnt; delete normal; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddVertexLightRound( POINT3D *LightPos , int r, int g, int b, int Range ) { int cnt; double ddist; int dist; int dr,dg,db; int lx,ly,lz; int dRange; int x,y,z; int eLight; dRange = ((Range/256)*72) >>FLOATNS; dRange *= dRange; lx = LightPos->x; ly = LightPos->y; lz = LightPos->z; /* r/=8; g/=8; b/=8; */ for(int cnt=0; cnt<nVertex; cnt++ ) { x = (lx - Vertex[ cnt ].x)>>FLOATNS; y = (ly - Vertex[ cnt ].y)>>FLOATNS; z = (lz - Vertex[ cnt ].z)>>FLOATNS; /* if ( abs(x)>Range || abs(y)>Range || abs(z)>Range ) ddist = dRange; else ddist = x*x+y*y+z*z; */ ddist = x*x+y*y+z*z; if ( ddist<dRange ) { //Á¶¸í ¹üÀ§ ¾È¿¡ ÀÖÀ½ dist = (int)sqrt( ddist ); eLight = (Range>>FLOATNS)-dist; //eLight = dRange-ddist; eLight = fONE - ((eLight<<FLOATNS)/dRange); dr = (r * eLight)>>FLOATNS; dg = (g * eLight)>>FLOATNS; db = (b * eLight)>>FLOATNS; Vertex[cnt].sDef_Color[SMC_R] += dr; Vertex[cnt].sDef_Color[SMC_G] += dg; Vertex[cnt].sDef_Color[SMC_B] += db; if ( Vertex[cnt].sDef_Color[SMC_R]>360 ) Vertex[cnt].sDef_Color[SMC_R] = 360; if ( Vertex[cnt].sDef_Color[SMC_G]>360 ) Vertex[cnt].sDef_Color[SMC_G] = 360; if ( Vertex[cnt].sDef_Color[SMC_B]>360 ) Vertex[cnt].sDef_Color[SMC_B] = 360; /* Vertex[cnt].sDef_Color[0] += db; Vertex[cnt].sDef_Color[1] += dg; Vertex[cnt].sDef_Color[2] += dr; */ /* if ( Vertex[cnt].sDef_Color[0]>420 ) Vertex[cnt].sDef_Color[0]=420; if ( Vertex[cnt].sDef_Color[1]>420 ) Vertex[cnt].sDef_Color[1]=420; if ( Vertex[cnt].sDef_Color[2]>420 ) Vertex[cnt].sDef_Color[2]=420; */ } } return TRUE; } //µ¿Àû Á¶¸í ÃʱâÈ­ ( ¼³Á¤ °¹¼ö ) int smSTAGE3D::InitDynLight( int nl ) { nLight = 0; smLight = new smLIGHT3D[ nl ]; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddDynLight( int type , POINT3D *LightPos , int r, int g, int b, int Range ) { smLight[nLight].type = type; smLight[nLight].x = LightPos->x; smLight[nLight].y = LightPos->y; smLight[nLight].z = LightPos->z; smLight[nLight].r = r; smLight[nLight].g = g; smLight[nLight].b = b; smLight[nLight].Range = Range; nLight++; return TRUE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::CheckFaceIceFoot( POINT3D *Pos, POINT3D *Angle, int CheckHeight ) { int num = CheckHeight + (fONE*16384); int acnt = MakeAreaFaceList( Pos->x - (fONE*64*1), Pos->z - (fONE*64*1), fONE*64*2, fONE*64*2, Pos->y+num, Pos->y-num ); if( ! acnt ) return 0; smSTAGE_FACE *face; int faceNum = 0, faceheight = CLIP_OUT; for( int cnt=0; cnt < acnt; cnt++ ) { face = smFaceList[ cnt ]; num = smMaterial[ face->Vertex[3] ].MeshState; if( (num & SMMAT_STAT_CHECK_FACE) && (num & sMATS_SCRIPT_CHECK_ICE) ) { num = GetPolyHeight( face, Pos->x, Pos->z ); if( num != CLIP_OUT ) { if( (num - Pos->y) < 10 * fONE ) { if( faceheight < num ) { faceheight = num; faceNum = cnt; } } } } } if( faceNum == 0 ) return 0; face = smFaceList[ faceNum ]; Angle->x = GetRadian2D( 0, -1024, face->VectNormal[2], face->VectNormal[1] ); Angle->z = GetRadian2D( 0, -1024, face->VectNormal[0], face->VectNormal[1] ); Pos->y = faceheight + (1*fONE); return 1; } //###################################################################################### /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö struct smLIGHT3D { int type; int x,y,z; int Range; BYTE r,g,b; }; */ /* // ¹öÅØ½º struct smSTAGE_VERTEX { DWORD sum; // ÃÖ±Ù ¿¬»ê ¹øÈ£ smRENDVERTEX *lpRendVertex; // ·»´õ¸µÀ» À§ÇÑ ¹öÅØ½º Æ÷ÀÎÅÍ // ¼Ò½º ¹öÅØ½º int x,y,z; // ¿ùµå ÁÂÇ¥ //BYTE bDef_Color[4]; // ±âº» »ö»ó (RGBA)(Color ) //BYTE bDef_Specular[4]; // ±âº» »ö»ó (RGBA)(Specular ) short sDef_Color[4]; // ±âº» »ö»ó ( RGBA ) }; // ÇöÀç Å©±â 28 ¹ÙÀÌÆ® */ //Àӽà ÆäÀ̽º ¸ñ·ÏÀ» ÀÛ¼ºÇÑ´Ù int smSTAGE3D::MakeAreaFaceList( int x,int z, int width, int height , int top , int bottom ) { int cnt; smSTAGE_FACE *face; int CalcSum; int wx,wz; int lx,lz; int num,fnum; int cntX , cntZ; int sx,sz; int y1,y2,y3; smFaceListCnt = 0; CalcSumCount++; CalcSum = CalcSumCount; sx = (x>>(FLOATNS+6))&0xFF; sz = (z>>(FLOATNS+6))&0xFF; wx = sx+(width>>(FLOATNS+6)); wz = sz+(height>>(FLOATNS+6)); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //for( cntX=sx; cntX <= wx; cntX++ ) //{ // for( cntZ=sz; cntZ <= wz; cntZ++ ) for( cntX=sx; cntX < wx; cntX++ ) { for( cntZ=sz; cntZ < wz; cntZ++ ) { //###################################################################################### lx=cntX&0xFF; lz=cntZ&0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; y1 = Vertex[face->Vertex[0]].y; y2 = Vertex[face->Vertex[1]].y; y3 = Vertex[face->Vertex[2]].y; if ( (y1<top && y1>bottom) || (y2<top && y2>bottom) || (y3<top && y3>bottom) ) smFaceList[ smFaceListCnt ++] = face; } } } } } CalcSumCount++; return smFaceListCnt; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetPolyHeight( smSTAGE_FACE *face , int x, int z ) { smSTAGE_VERTEX *p[3]; smSTAGE_VERTEX *ptop, *pmid , *pbot; int cnt; int lx , tx , bx; int ly , ty , by; int lz , tz , bz; int x1 , x2; int y1 , y2; int ye,xe; int yl; p[0] = &Vertex[ face->Vertex[0] ]; p[1] = &Vertex[ face->Vertex[1] ]; p[2] = &Vertex[ face->Vertex[2] ]; ptop = p[0]; pbot = p[1]; pmid = p[2]; //ÃÖ»óÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z<ptop->z ) ptop = p[cnt]; } if ( ptop==pbot ) pbot = pmid; //ÃÖÇÏÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z>pbot->z && ptop!=p[cnt] ) pbot = p[cnt]; } //Áß°£ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( ptop!=p[cnt] && pbot!=p[cnt] ) { pmid = p[cnt]; break; } } if ( z<ptop->z || z>pbot->z ) return CLIP_OUT; lz = pbot->z - ptop->z; tz = pmid->z - ptop->z; bz = pbot->z - pmid->z; if ( lz!=0 ) lx = ((pbot->x - ptop->x)<<FLOATNS) / lz ; else lx = 0; if ( tz!=0 ) tx = ((pmid->x - ptop->x)<<FLOATNS) / tz ; else tx = 0; if ( bz!=0 ) bx = ((pbot->x - pmid->x)<<FLOATNS) / bz ; else bx = 0; x1 = (( lx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; if( z<pmid->z ) { x2 = (( tx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; } else { x2 = (( bx * ( z - pmid->z ) )>>FLOATNS) + pmid->x; } if ( lz!=0 ) ly = ((pbot->y - ptop->y)<<FLOATNS) / lz ; else ly = 0; if ( tz!=0 ) ty = ((pmid->y - ptop->y)<<FLOATNS) / tz ; else ty = 0; if ( bz!=0 ) by = ((pbot->y - pmid->y)<<FLOATNS) / bz ; else by = 0; y1 = (( ly * ( z - ptop->z ) ) >>FLOATNS) + ptop->y; if( z<pmid->z ) { y2 = (( ty * ( z - ptop->z ) )>>FLOATNS) + ptop->y; } else { y2 = (( by * ( z - pmid->z ) )>>FLOATNS) + pmid->y; } if ( x1>x2 ) { cnt=x1; x1=x2; x2=cnt; cnt=y1; y1=y2; y2=cnt; } if ( x<x1 || x>x2 ) return CLIP_OUT; xe = x2-x1; ye = y2-y1; if ( xe!=0 ) yl = (ye<<FLOATNS) / xe; else yl = y1; return (( yl * (x - x1 ))>>FLOATNS)+y1; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetAreaHeight( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù ( ¹ÝÅõ¸í °ªµµ À¯È¿ ó¸® ) int smSTAGE3D::GetAreaHeight2( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; //if ( face->CalcSum!=CalcSum && // ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE || smMaterial[ face->Vertex[3] ].Transparency!=0 ) ) { if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight( lx,lz , x, z ); CalcSumCount ++; return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight2( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight2( lx,lz , x, z ); CalcSumCount ++; return height; } //À̵¿ÇÒ À§Ä¡ÀÇ Àå¾Ö¹°À» °Ë»çÇÑ´Ù int smSTAGE3D::CheckSolid( int sx, int sy, int sz , int dx, int dy, int dz ) { int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; POINT3D p1,p2,p3,sp,dp; sp.x=sx; sp.y=sy; sp.z=sz; dp.x=dx; dp.y=dy; dp.z=dz; CalcSum = CalcSumCount; lx = dx >> (6+FLOATNS); lz = dz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } lx = sx >> (6+FLOATNS); lz = sz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } CalcSumCount ++; return FALSE; } // StageArea¸¦ 0 À¸·Î ÃʱâÈ­ void smSTAGE3D::clearStageArea() { int x,y; for(y=0;y<MAP_SIZE;y++) { for(x=0;x<MAP_SIZE;x++) { StageArea[x][y] = 0; } } } // »ï°¢ÆäÀ̽º°¡ À§Ä¡ÇÑ ±¸¿ª(64x64) À» ±¸ÇÏ¿© AreaList ¿¡ ¼³Á¤ int smSTAGE3D::getPolyAreas( POINT3D *ip1 , POINT3D *ip2, POINT3D *ip3 ) { POINT3D p1, p2 , p3; POINT3D *p[3]; int cnt; int left , right , top , bottom; int cntX,cntY; memcpy( &p1, ip1 , sizeof( POINT3D ) ); memcpy( &p2, ip2 , sizeof( POINT3D ) ); memcpy( &p3, ip3 , sizeof( POINT3D ) ); p[0] = &p1; p[1] = &p2; p[2] = &p3; left = p[0]->x; right = p[0]->x; top = p[0]->z; bottom = p[0]->z; for( cnt=1; cnt<3; cnt++ ) { if ( p[cnt]->x < left ) left = p[cnt]->x; if ( p[cnt]->x > right ) right = p[cnt]->x; if ( p[cnt]->z < top ) top = p[cnt]->z; if ( p[cnt]->z > bottom ) bottom = p[cnt]->z; } left >>=6; right >>=6; top >>=6; bottom>>=6; right++; bottom++; AreaListCnt = 0; for( cntX=left; cntX<right; cntX++ ) { for( cntY=top; cntY<bottom; cntY++ ) { AreaList[ AreaListCnt ].x = cntX & 0xFF ; // AreaList[ AreaListCnt ].y = cntY & 0xFF ; // AreaListCnt ++; } } return TRUE; } //°¢ Æú¸®°ïÀÌ À§Ä¡ÇÑ ¿µ¿ª Á¤º¸¸¦ ¸¸µé¾î ÀúÀåÇÑ´Ù int smSTAGE3D::SetupPolyAreas() { POINT3D p[3]; int cnt,cnt2; int num; // ±¸¿ª ¹è¿­ ¿µ¿ªÀÇ ¸ðµç °ªÀ» 0 À¸·Î ÃʱâÈ­ clearStageArea(); AreaList = new POINT [ 4096 ]; // ¸ðµç Face¸¦ °Ë»çÇÏ¿© Â÷ÁöÇÏ´Â °ø°£ ±¸¿ªÀ» È®ÀÎÇÏ¿© ±¸¿ª ¹è¿­ ¿µ¿ª¿¡ ÇÒ´çµÉ °ø°£À» ±¸ÇÑ´Ù for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); //ÀÏ´Ü StageArea¿¡ ÀúÀåµÉ ÆäÀ̽º ¼ö¸¦ ÀúÀå if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y]++; } } } delete AreaList; // lpwAreaBuff = 0; int wbCnt; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { wbCnt += num+1; } } } wAreaSize = wbCnt; lpwAreaBuff = new WORD[ wbCnt ]; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { StageArea[cnt][cnt2] = &lpwAreaBuff[wbCnt]; StageArea[cnt][cnt2][0] = 0; wbCnt += num+1; } } } /* // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { num/=sizeof( WORD ); StageArea[cnt][cnt2] = new WORD[ num+1 ]; if ( StageArea[cnt][cnt2] ) StageArea[cnt][cnt2][0] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö else StageArea[cnt][cnt2] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö } } } */ AreaList = new POINT [ 4096 ]; // ´Ù½Ã Face¸¦ °Ë»çÇϰí È®º¸µÈ ¿µ¿ª¿¡ °ªÀ» ¼³Á¤ for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]++; num = StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]; StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][ num ] = cnt; } } } delete AreaList; return TRUE; } // ·»´õ¸µÀ» À§ÇÑ ¿¬»ê°ú Á¤·Ä int smSTAGE3D::RenderGeom() { int cnt; int x1,x2; int t; int h,w; int num; int fnum; smSTAGE_FACE *face; int clipW,clipH; smRENDFACE *rendface; int k=0; if ( smMaterialGroup ) smRender.SetMaterialGroup( smMaterialGroup ); //·»´õ¸µ¿ë Àӽà ¹öÆÛ ÃʱâÈ­ ( ¹öÅØ½º Æ÷ÀÎÅÍ ¾Ë·ÁÁÜ ) smRender.InitStageMesh ( Vertex , SumCount ); for( h=MapPosiTop; h<MapPosiBot ; h++ ) { x1 = MapPosiLeft[ h&0xFF ]; x2 = MapPosiRight[ h&0xFF ]; if ( x1>x2 ) { t=x1; x1=x2 ; x2=t; } // x1<->x2 ¹Ù²Þ clipH = h&0xFF; for( w=x1; w<x2 ; w++ ) { clipW = w&0xFF; if ( StageArea[clipW][clipH] ) { //·»´õ¸µ µÉ ¿µ¿ª num = StageArea[clipW][clipH][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[clipW][clipH][cnt]; face = &Face[ fnum ]; // if ( face->sum != SumCount && CheckFace!=face ) { if ( face->sum != SumCount ) { //&& (smMaterial[Face[ fnum ].Vertex[3]].UseState&Display sMATS_SCRIPT_NOTVIEW) ) { rendface = smRender.AddStageFace( face ); // ·»´õ¸µ ÆäÀ̽º·Î Ãß°¡ } k++; } } } } smRender.ClipRendFace(); // Àüü ·»´õ¸µ ÆäÀ̽º¸¦ Ŭ¸®ÇÎ smRender.GeomVertex2D(); // ¹öÅØ½º¸¦ 2DÁÂÇ¥·Î º¯È¯ return TRUE; } #define STAGE_RECT_LIMIT (30*64*fONE) #define STAGE_RECT_LIMIT2 (240*64*fONE) int smSTAGE3D::DrawStage(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); /* int cnt,dx,dy,dz,dist; for(cnt=0;cnt<nLight;cnt++) { dx = (x-smLight[cnt].x)>>FLOATNS; dy = (y-smLight[cnt].y)>>FLOATNS; dz = (z-smLight[cnt].z)>>FLOATNS; dist = dx*dx+dy*dy+dz*dz; if ( dist<0x300000 ) { smRender.AddDynamicLight( smLight[cnt].x,smLight[cnt].y,smLight[cnt].z, smLight[cnt].r,smLight[cnt].g,smLight[cnt].b, 0 , smLight[cnt].Range ); } } */ RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->Draw( x, y, z, angX, angY, angZ ); } return FALSE; } int smSTAGE3D::DrawStage2(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; if ( z<(StageMapRect.bottom-STAGE_RECT_LIMIT2) ) return FALSE; if ( z>(StageMapRect.top+STAGE_RECT_LIMIT2) ) return FALSE; if ( x<(StageMapRect.right-STAGE_RECT_LIMIT2) ) return FALSE; if ( x>(StageMapRect.left+STAGE_RECT_LIMIT2) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); return TRUE; } return FALSE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::DrawOpeningStage(int x, int y, int z, int angX, int angY, int angZ, int FrameStep ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->DrawOpening( x, y, z, angX, angY, angZ, FrameStep ); } return FALSE; } //###################################################################################### static char *szSMDFileHeader = "SMD Stage data Ver 0.72"; //µ¥ÀÌŸ¸¦ ÆÄÀÏ·Î ÀúÀå int smSTAGE3D::SaveFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2,slen; int pFile; // int size; smDFILE_HEADER FileHeader; lstrcpy( FileHeader.szHeader , szSMDFileHeader ); Head = FALSE; //Çì´õ Á¦ÀÛ if ( smMaterialGroup ) FileHeader.MatCounter = smMaterialGroup->MaterialCount; else FileHeader.MatCounter = 0; //ÆÄÀÏ Æ÷ÀÎÅÍ pFile = sizeof( smDFILE_HEADER );// + sizeof( smPAT3D ); FileHeader.MatFilePoint = pFile; //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå Å©±â if ( smMaterialGroup ) pFile+= smMaterialGroup->GetSaveSize(); FileHeader.First_ObjInfoPoint = pFile; //ÆÄÀÏ·Î ÀúÀå hFile = CreateFile( szFile , GENERIC_WRITE , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL ); if ( hFile == INVALID_HANDLE_VALUE ) return FALSE; //Çì´õ ÀúÀå WriteFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //ÇöÀç Ŭ·¡½ºÀÇ µ¥ÀÌŸ ÀúÀå WriteFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå if ( smMaterialGroup ) smMaterialGroup->SaveFile( hFile ); // °¢ ¸Þ½Ã µ¥ÀÌŸ¸¦ ÀúÀå WriteFile( hFile , Vertex , sizeof( smSTAGE_VERTEX )* nVertex , &dwAcess , NULL ); WriteFile( hFile , Face , sizeof( smSTAGE_FACE )* nFace , &dwAcess , NULL ); WriteFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) WriteFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀúÀå for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { slen = (StageArea[cnt][cnt2][0]+1) ; WriteFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); WriteFile( hFile , StageArea[cnt][cnt2] , slen * sizeof( WORD ), &dwAcess , NULL ); } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return TRUE; } //ÆÄÀÏ¿¡¼­ µ¥ÀÌŸ¸¦ ·Îµå int smSTAGE3D::LoadFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2; int size; int slen; int wbCnt; smTEXLINK *lpOldTexLink; int SubTexLink; smDFILE_HEADER FileHeader; hFile = CreateFile( szFile , GENERIC_READ , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL ); //Çì´õÀÇ ³»¿ëÀ» Àоî¿È size=ReadFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //Çì´õ°¡ Ʋ¸² ( ¹öÀüÀÌ Æ²¸®°Å³ª.. ) if ( lstrcmp( FileHeader.szHeader , szSMDFileHeader )!=0 ) { //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return FALSE; } //Ŭ·¡½ºÀÇ ³»¿ëÀ» ÀÐÀ½ ReadFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); lpOldTexLink = TexLink; //¸ÞÆ®¸®¾ó Àоî¿È if ( FileHeader.MatCounter ) { smMaterialGroup = new smMATERIAL_GROUP; smMaterialGroup->LoadFile( hFile ); smMaterial = smMaterialGroup->smMaterial; } //»õ·Î¿î ¸Þ¸ð¸® ºí·° ÇÒ´ç Vertex = new smSTAGE_VERTEX[ nVertex ]; ReadFile( hFile , Vertex , sizeof( smSTAGE_VERTEX ) * nVertex , &dwAcess , NULL ); Face = new smSTAGE_FACE[ nFace ]; ReadFile( hFile , Face , sizeof( smSTAGE_FACE ) * nFace , &dwAcess , NULL ); TexLink = new smTEXLINK[ nTexLink ]; ReadFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) { smLight = new smLIGHT3D[nLight]; ReadFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); } //ÅØ½ºÃÄ ÁÂÇ¥°¡ ¾îµå·¹½º Æ÷ÀÎÅÍ·Î µÇ ÀÖÀ¸¹Ç·Î »õ·Î º¸Á¤ÇÔ SubTexLink = TexLink-lpOldTexLink; for(int cnt=0;cnt<nTexLink;cnt++) { if ( TexLink[cnt].NextTex ) { SubTexLink = TexLink[cnt].NextTex-lpOldTexLink; TexLink[cnt].NextTex = TexLink + SubTexLink; } } for(int cnt=0;cnt<nFace;cnt++) { if ( Face[cnt].lpTexLink ) { SubTexLink = Face[cnt].lpTexLink-lpOldTexLink; Face[cnt].lpTexLink = TexLink + SubTexLink; } } StageObject = new smSTAGE_OBJECT; lpwAreaBuff = new WORD[ wAreaSize ]; wbCnt = 0; // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀÐÀ½ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { ReadFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); StageArea[cnt][cnt2] = &lpwAreaBuff[ wbCnt ]; ReadFile( hFile , StageArea[cnt][cnt2] , slen*sizeof(WORD) , &dwAcess , NULL ); wbCnt += slen; } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); CalcSumCount++; return TRUE; }
rafaellincoln/Source-Priston-Tale
J_Server/smLib3d/smStage3d.cpp
C++
mit
55,585
body{ font-size:80px; font-family:"HG丸ゴシックM-PRO", "メイリオ", Meiryo, Osaka, "MS Pゴシック", "MS PGothic", sans-serif; } .register{ font-size:80px; color:#ffffff; background-color:#404040; text-align:center; padding:0.1px 0 0.1px 0; } article{ color:#029f49; background-color:#f2f2f2; padding:25.25px 10px 25.5px; margin-bottom:20px; } .station { font-size:60px; width: 100%; margin-left: 7.5%; } .station input { -webkit-appearance: none; -moz-appearance: none; appearance: none; font-size:60px; border:4.0px #000000 groove; border-radius:20px; width:50%; height:64px; margin-top: 10px; } .station input:focus { box-shadow:inset 0 0 5px #222222; border:groove 5.0px #000000; } .station-box { overflow: hidden; margin: 20px 0 0 19px; } .station-form { float: left; margin: 20px 50px 0 0; } .time { font-size:60px; margin: 78px 0 0 5%; } select{ font-size:42px; border:3.5px #000000 groove; border-radius:10px; height:80px; margin-top:29px; margin-bottom: 27px; position:relative; top:-5px; right:2px; } select:focus{ box-shadow:inset 0 0 5px #222222; border:groove 5.0px #000000; } .time-box { overflow:hidden; margin: 30px 0 0 0; } .time-form{ float:left; margin:15px 40px 0 0; } .submit { text-align:center; margin:90px 0 0 0; } .submit input{ color:#404040; background-color:#ff6500; font-size:43px; border:4.0px #000000 ridge; border-radius:10px; } .reset{ text-align:center; margin:25px 0 0 0; } .reset input{ color:#000000; font-size:37px; border:4.0px #000000 ridge; border-radius:10px; }
DiamondOhana/jphacks
web_main/style.css
CSS
mit
1,761
#! /usr/bin/env python import sys sys.setrecursionlimit(150000) import time count = 0 def my_yield(): global count count = count + 1 yield def run_co(c): global count count = 0 t0 = time.clock() for r in c: () t = time.clock() dt = t-t0 print(dt,count,count / dt) return r def parallel_(p1,p2): r1 = None r2 = None while(r1 == None or r2 == None): if(r1 == None): r1 = next(p1) if(r2 == None): r2 = next(p2) for x in my_yield() : yield for x in my_yield() : yield r1,r2 def parallel_many_aux(ps,l,u): if(l < u): for x in parallel_(ps[l],parallel_many_aux(ps,l+1,u)): for y in my_yield(): yield x yield 0 def parallel_many_(ps): return parallel_many_aux(ps,0,len(ps)) def parallel_first_(p1,p2): r1 = None r2 = None while(r1 == None and r2 == None): if(r1 == None): r1 = next(p1) if(r2 == None): r2 = next(p2) for x in my_yield() : yield for x in my_yield() : yield r1,r2 def wait(max_dt): t0 = time.clock() t = time.clock() while(t - t0 < max_dt): for x in my_yield() : yield #print(t - t0) t = time.clock() for x in my_yield() : yield 0 def fibo_co(n): if(n==0): for x in my_yield() : yield 0 else: if(n==1): for x in my_yield() : yield 1 else: for x in my_yield() : yield for n1 in fibo_co(n-1): for x in my_yield() : yield for n2 in fibo_co(n-2): for x in my_yield() : yield for x in my_yield() : yield n1+n2 def log(i): #print("log ", i) for x in wait(2.0): for x in my_yield() : yield for x in log(i+1): for x in my_yield() : yield def fibo_test(): run_co(parallel_first_(fibo_co(25),log(0))) def many_fibs(n): #yield return log(0); for i in range(0,n+1): yield fibo_co(i + 5) def many_fibs_test(): run_co(parallel_many_(list(many_fibs(15)))) #fibo_test() #many_fibs_test() class Entity: pass class State: pass def simple_mk_ship(n): s = Entity() s.Position = 100.0 - n return s def add_ship(new_ship, run_ship, state): state.Entities.append(new_ship) for result in run_ship(new_ship): for x in my_yield(): yield state.Entities.remove(new_ship) for x in my_yield(): yield result def simple_run_ship(self): while(self.Position > 0.0): self.Position = self.Position - 0.1 for x in my_yield(): yield yield 0 def many_ships(n,state): if(n > 0): for x in parallel_(add_ship(simple_mk_ship(n), simple_run_ship, state), many_ships(n-1,state)): for x in my_yield(): yield yield 0 def log_ships(state): while(True): print("there are ", len(state.Entities), " ships") for x in wait(2.0): for x in my_yield(): yield def state_access_test(): state = State() state.Entities = [] #test = parallel_(many_ships(200,state),log_ships(state)) test = many_ships(200,state) run_co(test) state_access_test()
vs-team/Papers
0. MonadicCoroutines/Src/MonadicCoroutines/CSharp/main.py
Python
mit
3,063
package io.reactivesw.order.order.infrastructure.enums; /** * Created by Davis on 16/11/17. */ public enum OrderState { /** * Open order state. */ Open, /** * Confirmed order state. */ Confirmed, /** * Complete order state. */ Complete, /** * Cancelled order state. */ Cancelled; }
reactivesw/customer_server
src/main/java/io/reactivesw/order/order/infrastructure/enums/OrderState.java
Java
mit
327
<?php namespace Ibw\MagSoftBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ProiecteRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ProiecteRepository extends EntityRepository { public function getLastProiectGeneratId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrProiectGenerat)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastDosarDefinitivId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrDosarDefinitiv)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastProiectId() { $qb = $this->createQueryBuilder('j') ->select('max(j.id)'); return $qb->getQuery()->getResult(); } public function getRaportLucrari($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getRaportProiecte($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt, pr') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt') ->innerJoin('p.pret', 'pr'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getSumPret() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('sum(p.pret)') ->from('IbwMagSoftBundle:Proiecte', 'p'); return $qb->getQuery()->getSingleScalarResult(); } public function getProiectPriceByPartener() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p.valoarePret') ->from('IbwMagSoftBundle:Pret', 'p') ->where('p.parteneri = :partener') ->setParameter('partener', 'numePartener1'); return $qb->getQuery()->getArrayResult(); } }
annonnim/magsoft
src/Ibw/MagSoftBundle/Entity/ProiecteRepository.php
PHP
mit
3,167
<!DOCTYPE html> <html> <!-- debag: HEAD section --> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta content="Vatarus's blog" property="og:site_name"><meta content="This is first post!" property="og:title"><meta content="article" property="og:type"><meta content="<h3>Official Vatarus's blog</h3>" property="og:description"> <meta content="https://vatarus.github.io/news/2016/05/13/welcome-to-jekyll.html" property="og:url"><meta content="2016-05-13T02:31:43+10:00" property="article:published_time"> <meta content="https://vatarus.github.io/about/" property="article:author"><meta property="og:image" content=""><meta content="News" property="article:section"><title>This is first post!</title> <meta name="description" content="Привет всем! Как дела? _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but..."> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script type="text/javascript" src="/assets/js/bs/bootstrap.min.js"></script> <link rel="stylesheet" href="/assets/js/bs/bootstrap.css"> <link rel="canonical" href="https://vatarus.github.io/news/2016/05/13/welcome-to-jekyll.html"> <link rel="alternate" type="application/rss+xml" title="Vatarus's blog" href="https://vatarus.github.io/feed.xml"> <link rel="stylesheet" href="/assets/css/main.css"> <script type="text/javascript" src="/assets/js/lettering/jquery.lettering.js"></script> </head> <!-- debag: HEAD section END --> <body> <!-- debag: HEADER section --> <section> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a id="logo-text" class="navbar-brand" href="/">Vatarus's blog</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="https://vatarus.github.io">Ньюсы</a></li> <li class="dropdown"> <!-- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Гайды <span class="">:alien:</span></a> --> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Артиклы <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="/about/">КтоЯ</a></li> <li><a href="/download/">Download</a></li> <li><a href="/hobbies/">&gt;&gt; PixelArt</a></li> </ul> </li> <li><a href="/about/">КтоЯ <span class=""><img class="emoji" title=":alien:" alt="alien-gray" src="/assets/img/grays.png" height="20" width="20"></span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </section> <!-- debag: HEADER section END --> <!-- debag: CONTENT section --> <article> <div class="jumbotron"> <div class="container"> <h1 class="post-title-main" itemprop="name headline">This is first post!</h1> <p class="post-meta"> <time datetime="2016-05-13T02:31:43+10:00" itemprop="datePublished">&gt;&gt; 05.13.2016</time> • Vadim Vinogradov <span class=""><img class="emoji" title=":alien:" alt="alien-gray" src="/assets/img/grays.png" height="20" width="20"></span> </p> </div> </div> <div class="post-content container" itemprop="articleBody"> <p>Привет всем! Как дела? <code class="highlighter-rouge">_posts</code> directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run <code class="highlighter-rouge">jekyll serve</code>, which launches a web server and auto-regenerates your site when a file is updated.</p> <p>To add new posts, simply add a file in the <code class="highlighter-rouge">_posts</code> directory that follows the convention <code class="highlighter-rouge">YYYY-MM-DD-name-of-post.ext</code> and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.</p> <p>Jekyll also offers powerful support for code snippets:</p> <figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="cp">&lt;!DOCTYPE html&gt;</span> <span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"ru"</span><span class="nt">&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;</span> <span class="nt">&lt;title&gt;</span>AvatarusGames Official Website<span class="nt">&lt;/title&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="nt">&lt;script&gt;</span> <span class="kd">var</span> <span class="nx">lang</span> <span class="o">=</span> <span class="nb">navigator</span><span class="p">.</span><span class="nx">language</span> <span class="o">||</span> <span class="nb">navigator</span><span class="p">.</span><span class="nx">userLanguage</span><span class="p">;</span> <span class="k">if</span> <span class="p">(</span><span class="nx">lang</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'en'</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="nb">window</span><span class="p">.</span><span class="nx">location</span> <span class="o">=</span> <span class="s1">'/en/'</span><span class="p">;</span> <span class="k">else</span> <span class="nb">window</span><span class="p">.</span><span class="nx">location</span> <span class="o">=</span> <span class="s1">'/ru/'</span><span class="p">;</span> <span class="nt">&lt;/script&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span></code></pre></figure> <p>Check out the <a href="http://jekyllrb.com/docs/home">Jekyll docs</a> for more info on how to get the most out of Jekyll. File all bugs/feature requests at <a href="https://github.com/jekyll/jekyll">Jekyll’s GitHub repo</a>. If you have questions, you can ask them on <a href="https://talk.jekyllrb.com/">Jekyll Talk</a>.</p> </div> </article> <!-- debag: CONTENT section END --> <!-- debag: FOOTER section --> <nav class="navbar navbar-default navbar-fixed-bottom"> <div class="container footer-content"> Made with <img class="emoji" title=":alien:" alt=":alien:" src="https://github.githubassets.com/images/icons/emoji/unicode/1f47d.png" height="20" width="20"> by Vatarus<br> Powered By Jekyll. </div> </nav> <script type="text/javascript"> $(document).ready(function(){ $("#logo-text").lettering(); }); </script> <!-- debag: FOOTER section END --> </body> </html>
Vatarus/vatarus.github.io
news/2016/05/13/welcome-to-jekyll.html
HTML
mit
7,912
Скрипты, написанные на хакатоне и не только. Не все доделанные, поэтому требуют описания JavaScript * car-parkings.js - Попытка рассчитать количество мест для парковки * package.json - Файл для установки JavaScript зыависимостей Python * csv2sqlite.py - Скрипт для конвертации CSV в SQLite * osm-extract.py - Попытка извлечь данные из OSM
opendataby/city-dashboard
scripts/README.md
Markdown
mit
533
package org.adaptlab.chpir.android.survey.utils; import org.adaptlab.chpir.android.survey.models.DeviceUser; public class AuthUtils { private static DeviceUser sCurrentUser = null; public static boolean isSignedIn() { return sCurrentUser != null; } public static void signOut() { sCurrentUser = null; } public static void signIn(DeviceUser deviceUser) { sCurrentUser = deviceUser; } public static DeviceUser getCurrentUser() { return sCurrentUser; } }
DukeMobileTech/AndroidSurvey
app/src/main/java/org/adaptlab/chpir/android/survey/utils/AuthUtils.java
Java
mit
543
USE Gringotts SELECT COUNT(Id) AS [Count] FROM WizzardDeposits
flyelmos/Software-University
07. MSSQL Server - Databases Basics/04. Data Aggregation Exercises/Data Aggregation Exercises/01. Records Count.sql
SQL
mit
63
trait Printer { def print:String } trait ConstantPrinter extends Printer { override def print = "constant" }
littlenag/scala-enthusiasts
scala-decompiled-pt-2/04_trait_extends_trait/04_traits.scala
Scala
mit
114
# window 10 Mockup The project consists of window 10 mock up for the Web. Supports Data storage in a familiar environment and tools to modify the data. # [Demo](https://riteshkukreja.github.io/window10/)
riteshkukreja/window10
README.md
Markdown
mit
205
using System; namespace SDNUMobile.SDK.Entity.Bathroom { /// <summary> /// 浴室使用用量实体 /// </summary> public class BathroomUsageAmount { #region 字段 private DateTime _logTime; private Int32[] _amount; #endregion #region 属性 /// <summary> /// 获取或设置记录时间 /// </summary> public DateTime LogTime { get { return this._logTime; } set { this._logTime = value; } } /// <summary> /// 获取或设置使用数量 /// </summary> public Int32[] Amount { get { return this._amount; } set { this._amount = value; } } #endregion } }
isdnu/DotNetSDK
SDNUMobile.SDK/Entity/Bathroom/BathroomUsageAmount.cs
C#
mit
809
;(function() { 'use strict'; const nodemailer = require('nodemailer'); const htmlToText = require('nodemailer-html-to-text').htmlToText; module.exports = Extension => class Mailer extends Extension { _constructor() { this.send.context = Extension.ROUTER; } send(ctx) { let subject = ctx.arg('subject'); let formKeys = Object.keys(ctx.body) .filter(key => key.startsWith(ctx.arg('prefix'))) .reduce((map, key) => map.set(key.slice(ctx.arg('prefix').length), ctx.body[key]), new Map()); formKeys.forEach((key, value) => subject = subject.replace(`{${key}}`, value)); let content = ctx.render(formKeys); let transporter = nodemailer.createTransport(); transporter.use('compile', htmlToText()); ctx.logger.log(ctx.logger.debug, 'sending mail...'); transporter.sendMail({ from: ctx.arg('from'), to: ctx.arg('to'), subject: subject, html: content }, function(err, info) { if (err) { ctx.logger.log(ctx.logger.error, 'can\'t send mail: {0}', err); } else { ctx.logger.log(ctx.logger.info, 'mail sent: {0}', info.response); } ctx.set('status', err); return ctx.success(); }); } } })();
xabinapal/verlag
extensions/mailer.js
JavaScript
mit
1,288
<?php include('dbconnect.php'); include('_admin_session.php'); if(isset($_POST['form1'])){ $acc_date = $_POST['acc_date']; $acc_desc = $_POST['acc_desc']; $acc_amo = $_POST['acc_amo']; $acc_dr_cr = $_POST['acc_dr_cr']; $acc_total = $_POST['acc_total']; $result = mysql_query("insert into accounts (acc_date, acc_desc, acc_amo, acc_dr_cr, acc_total) values('$acc_date','$acc_desc','$acc_amo','$acc_dr_cr','$acc_total')")or die(mysql_error()); if ($result) { echo ("<p style='font-size:20px;'>Accounts Data input successfully</p>"); } else { echo ("<p style='font-size:20px;'>Accounts Data input Failed</p>"); } } //header("location: index.php?action=_accounts_view"); ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>প্রতিষ্ঠানের একাউন্টস</title> <script type="text/javascript"> function confirm_del() { return confirm('Do you want to delete this data ?'); } </script> </head> <body> <h2>প্রতিষ্ঠানের একাউন্টস</h2> <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>তারিখ: </td> <td><input type="text" name="acc_date" placeholder="ex: ১২/০৯।২০১৫ " required /></td> </tr> <tr> <td>টাকার বিবরণ: </td> <td><input type="text" name="acc_desc" placeholder="ex: টাকার বিবরণ লিখুন " required /></td> </tr> <tr> <td>পরিমান: </td> <td><input type="text" name="acc_amo" placeholder="ex: ৪,০০০ /=" required /></td> </tr> <tr> <td>জমা/ খরচ: </td> <td> <select name="acc_dr_cr" id=""> <option value="--Select--">--Select A Option--</option> <option value="জমা">জমা</option> <option value="খরচ">খরচ</option> </select> </td> </tr> <tr> <td>মোট পরিমাণ: </td> <td><input type="text" name="acc_total" placeholder="ex: ১২,০০০ /=" required /></td> </tr> <tr> <td></td> <td><input type="submit" value="সেভ করুন" name="form1"/></td> </tr> </table> </form> <br /> <table border="1" id="mytable"> <tr> <th>ক্রমিক নং</th> <th>তারিখ</th> <th>টাকার বিবরণ</th> <th>পরিমান</th> <th>জমা/ খরচ</th> <th>মোট পরিমাণ</th> <th>নিয়ন্ত্রণ করুন</th> </tr> <?php $i = 0; $result= mysql_query("select * from accounts" ) or die (mysql_error()); while ($row = mysql_fetch_array ($result)){ $i++; ?> <tr> <td><?php echo $i;?></td> <td><?php echo $row['acc_date'];?></td> <td><?php echo $row['acc_desc'];?></td> <td><?php echo $row['acc_amo'];?>/=</td> <td><?php echo $row['acc_dr_cr'];?></td> <td><?php echo $row['acc_total'];?>/=</td> <td> <a href="_accounts_edit.php?id=<?php echo $row['acc_id'];?>">এডিট </a> | <a onClick="return confirm_del();" href="_accounts_del.php?id=<?php echo $row['acc_id'];?>">ডিলিট </a> </td> </tr> <?php } ?> </table> </body> </html>
saidurwd/muradschool
backend/_accounts_view.php
PHP
mit
3,202
require 'spec_helper' require_relative '../../lib/concerns/linkable' describe Linkable do context 'link' do class Example include Linkable def initialize(response) @response = response end end it 'removes all \ from strings' do e = Example.new("\"https:\\/\\/ead.local.co\\/videos\\/aulas\\/cooolllllller\\/asdfasdf.pdf?secure=asdfasdf\"") expect(e.link).to eq('https://ead.local.co/videos/aulas/cooolllllller/asdfasdf.pdf?secure=asdfasdf') end end end
fortesinformatica/iesde
spec/concerns/linkable_spec.rb
Ruby
mit
514
export class VendorTest { private expe: string = 'z100123'; constructor(props:any){ //console.log(props); //this.expe = props; } }
ferrugemjs/library
src/example/ui-vendor-example/vendor-test.ts
TypeScript
mit
144
from django import forms class SearchForm(forms.Form): criteria = forms.CharField(label='Criteria', max_length=100, required=True)
chaocodes/playlist-manager-django
manager/search/forms.py
Python
mit
135
# frozen_string_literal: true module DropletKit class DomainMapping include Kartograph::DSL kartograph do mapping Domain root_key plural: 'domains', singular: 'domain', scopes: [:read] property :name, scopes: [:read, :create] property :ttl, scopes: [:read] property :zone_file, scopes: [:read] property :ip_address, scopes: [:create] end end end
digitalocean/droplet_kit
lib/droplet_kit/mappings/domain_mapping.rb
Ruby
mit
400
package com.example.author.boundary; import com.example.author.entity.Author; import com.example.author.repository.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.IdGenerator; import java.util.Collection; import java.util.UUID; /** * Implementation for {@link AuthorService}. */ @Service @Transactional(readOnly = true) public class AuthorServiceImpl implements AuthorService { private final AuthorRepository authorRepository; private final IdGenerator idGenerator; /** * Constructor. * * @param authorRepository the {@link AuthorRepository} * @param idGenerator the {@link IdGenerator} */ @Autowired public AuthorServiceImpl(AuthorRepository authorRepository, IdGenerator idGenerator) { this.authorRepository = authorRepository; this.idGenerator = idGenerator; } @Transactional @Override public Author createAuthor(Author author) { if (author.getIdentifier() == null) { author.setIdentifier(idGenerator.generateId()); } return this.authorRepository.save(author); } @Override public Author findByIdentifier(UUID identifier) { return this.authorRepository.findByIdentifier(identifier); } @Override public Collection<Author> findAllAuthors() { return this.authorRepository.findAll(); } @Override public Collection<Author> findByLastname(String lastName) { return this.authorRepository.findByLastname(lastName); } @Transactional @Override public boolean deleteAuthor(UUID identifier) { return this.authorRepository.deleteByIdentifier(identifier); } }
andifalk/spring-rest-docs-demo
src/main/java/com/example/author/boundary/AuthorServiceImpl.java
Java
mit
1,838
using System.Collections.Generic; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.Computers.AmstradCPC { /// <summary> /// CPCHawk: Core Class /// * Controllers * /// </summary> public partial class AmstradCPC { /// <summary> /// The one CPCHawk ControllerDefinition /// </summary> public ControllerDefinition AmstradCPCControllerDefinition { get { ControllerDefinition definition = new ControllerDefinition(); definition.Name = "AmstradCPC Controller"; // joysticks List<string> joys1 = new List<string> { // P1 Joystick "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Fire1", "P1 Fire2", "P1 Fire3" }; foreach (var s in joys1) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J1"; } List<string> joys2 = new List<string> { // P2 Joystick "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Fire", }; foreach (var s in joys2) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J2"; } // keyboard List<string> keys = new List<string> { // http://www.cpcwiki.eu/index.php/Programming:Keyboard_scanning // http://www.cpcwiki.eu/index.php/File:Grimware_cpc464_version3_case_top.jpg // Keyboard - row 1 "Key ESC", "Key 1", "Key 2", "Key 3", "Key 4", "Key 5", "Key 6", "Key 7", "Key 8", "Key 9", "Key 0", "Key Dash", "Key Hat", "Key CLR", "Key DEL", // Keyboard - row 2 "Key TAB", "Key Q", "Key W", "Key E", "Key R", "Key T", "Key Y", "Key U", "Key I", "Key O", "Key P", "Key @", "Key LeftBracket", "Key RETURN", // Keyboard - row 3 "Key CAPSLOCK", "Key A", "Key S", "Key D", "Key F", "Key G", "Key H", "Key J", "Key K", "Key L", "Key Colon", "Key SemiColon", "Key RightBracket", // Keyboard - row 4 "Key SHIFT", "Key Z", "Key X", "Key C", "Key V", "Key B", "Key N", "Key M", "Key Comma", "Key Period", "Key ForwardSlash", "Key BackSlash", // Keyboard - row 5 "Key SPACE", "Key CONTROL", // Keyboard - Cursor "Key CURUP", "Key CURDOWN", "Key CURLEFT", "Key CURRIGHT", "Key COPY", // Keyboard - Numpad "Key NUM0", "Key NUM1", "Key NUM2", "Key NUM3", "Key NUM4", "Key NUM5", "Key NUM6", "Key NUM7", "Key NUM8", "Key NUM9", "Key NUMPERIOD", "KEY ENTER" }; foreach (var s in keys) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Keyboard"; } // Power functions List<string> power = new List<string> { // Power functions "Reset", "Power" }; foreach (var s in power) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Power"; } // Datacorder (tape device) List<string> tape = new List<string> { // Tape functions "Play Tape", "Stop Tape", "RTZ Tape", "Record Tape", "Insert Next Tape", "Insert Previous Tape", "Next Tape Block", "Prev Tape Block", "Get Tape Status" }; foreach (var s in tape) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Datacorder"; } // Datacorder (tape device) List<string> disk = new List<string> { // Tape functions "Insert Next Disk", "Insert Previous Disk", /*"Eject Current Disk",*/ "Get Disk Status" }; foreach (var s in disk) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Amstrad Disk Drive"; } return definition; } } } /// <summary> /// The possible joystick types /// </summary> public enum JoystickType { NULL, Joystick1, Joystick2 } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs
C#
mit
4,843
#include <iostream> #include <cstdlib> #include <stdio.h> #include <math.h> #include<cstdio> #include<string.h> using namespace std; int main(){ int in=0,x,o=0,n; cin>>n; for (int i = 0; i < n; i++) { cin>>x; if(x>=10&&x<=20) in++; else o++; } printf("%d in\n%d out\n",in,o); return 0; }
ahmedengu/URI-solutions
Beginner/1072 - Interval 2.cpp
C++
mit
354
namespace p03_WildFarm.Models.Foods { public class Vegetable : Food { public Vegetable(int quantity) : base(quantity) { } } }
DimitarIvanov8/software-university
C#_OOP_Basics/Polymorphism/p03_WildFarm/Models/Foods/Vegetable.cs
C#
mit
164
<?php /** * PHPExcel * * Copyright (c) 2006 - 2013 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Reader * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.9, 2013-06-02 */ /** PHPExcel root directory */ if (!defined('PHPEXCEL_ROOT')) { /** * @ignore */ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); } /** * PHPExcel_Reader_SYLK * * @category PHPExcel * @package PHPExcel_Reader * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader { /** * Input encoding * * @var string */ private $_inputEncoding = 'ANSI'; /** * Sheet index to read * * @var int */ private $_sheetIndex = 0; /** * Formats * * @var array */ private $_formats = array(); /** * Format Count * * @var int */ private $_format = 0; /** * Create a new PHPExcel_Reader_SYLK */ public function __construct() { $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); } /** * Validate that the current file is a SYLK file * * @return boolean */ protected function _isValidFormat() { // Read sample data (first 2 KB will do) $data = fread($this->_fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); if ($delimiterCount < 1) { return FALSE; } // Analyze first line looking for ID; signature $lines = explode("\n", $data); if (substr($lines[0],0,4) != 'ID;P') { return FALSE; } return TRUE; } /** * Set input encoding * * @param string $pValue Input encoding */ public function setInputEncoding($pValue = 'ANSI') { $this->_inputEncoding = $pValue; return $this; } /** * Get input encoding * * @return string */ public function getInputEncoding() { return $this->_inputEncoding; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * * @param string $pFilename * @throws PHPExcel_Reader_Exception */ public function listWorksheetInfo($pFilename) { // Open file $this->_openFile($pFilename); if (!$this->_isValidFormat()) { fclose ($this->_fileHandle); throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->_fileHandle; rewind($fileHandle); $worksheetInfo = array(); $worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['totalRows'] = 0; $worksheetInfo[0]['totalColumns'] = 0; // Loop through file $rowData = array(); // loop through one row (line) at a time in the file $rowIndex = 0; while (($rowData = fgets($fileHandle)) !== FALSE) { $columnIndex = 0; // convert SYLK encoded $rowData to UTF-8 $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData))))); $dataType = array_shift($rowData); if ($dataType == 'C') { // Read cell value data foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $columnIndex = substr($rowDatum,1) - 1; break; case 'R' : case 'Y' : $rowIndex = substr($rowDatum,1); break; } $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); } } } $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads PHPExcel from file * * @param string $pFilename * @return PHPExcel * @throws PHPExcel_Reader_Exception */ public function load($pFilename) { // Create new PHPExcel $objPHPExcel = new PHPExcel(); // Load into this instance return $this->loadIntoExisting($pFilename, $objPHPExcel); } /** * Loads PHPExcel from file into PHPExcel instance * * @param string $pFilename * @param PHPExcel $objPHPExcel * @return PHPExcel * @throws PHPExcel_Reader_Exception */ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) { // Open file $this->_openFile($pFilename); if (!$this->_isValidFormat()) { fclose ($this->_fileHandle); throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->_fileHandle; rewind($fileHandle); // Create new PHPExcel while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { $objPHPExcel->createSheet(); } $objPHPExcel->setActiveSheetIndex( $this->_sheetIndex ); $fromFormats = array('\-', '\ '); $toFormats = array('-', ' '); // Loop through file $rowData = array(); $column = $row = ''; // loop through one row (line) at a time in the file while (($rowData = fgets($fileHandle)) !== FALSE) { // convert SYLK encoded $rowData to UTF-8 $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData))))); $dataType = array_shift($rowData); // Read shared styles if ($dataType == 'P') { $formatArray = array(); foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1)); break; case 'E' : case 'F' : $formatArray['font']['name'] = substr($rowDatum,1); break; case 'L' : $formatArray['font']['size'] = substr($rowDatum,1); break; case 'S' : $styleSettings = substr($rowDatum,1); for ($i=0;$i<strlen($styleSettings);++$i) { switch ($styleSettings{$i}) { case 'I' : $formatArray['font']['italic'] = true; break; case 'D' : $formatArray['font']['bold'] = true; break; case 'T' : $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'B' : $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'L' : $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'R' : $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; } } break; } } $this->_formats['P'.$this->_format++] = $formatArray; // Read cell value data } elseif ($dataType == 'C') { $hasCalculatedValue = false; $cellData = $cellDataFormula = ''; foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; case 'K' : $cellData = substr($rowDatum,1); break; case 'E' : $cellDataFormula = '='.substr($rowDatum,1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"',$cellDataFormula); $key = false; foreach($temp as &$value) { // Only count/replace in alternate array entries if ($key = !$key) { preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE); // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // through the formula from left to right. Reversing means that we work right to left.through // the formula $cellReferences = array_reverse($cellReferences); // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, // then modify the formula to use that new reference foreach($cellReferences as $cellReference) { $rowReference = $cellReference[2][0]; // Empty R reference is the current row if ($rowReference == '') $rowReference = $row; // Bracketed R references are relative to the current row if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]'); $columnReference = $cellReference[4][0]; // Empty C reference is the current column if ($columnReference == '') $columnReference = $column; // Bracketed C references are relative to the current column if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]'); $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; $value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string $cellDataFormula = implode('"',$temp); $hasCalculatedValue = true; break; } } $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); $cellData = PHPExcel_Calculation::_unwrapResult($cellData); // Set cell value $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = PHPExcel_Calculation::_unwrapResult($cellData); $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); } // Read cell formatting } elseif ($dataType == 'F') { $formatStyle = $columnWidth = $styleSettings = ''; $styleData = array(); foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; case 'P' : $formatStyle = $rowDatum; break; case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1)); break; case 'S' : $styleSettings = substr($rowDatum,1); for ($i=0;$i<strlen($styleSettings);++$i) { switch ($styleSettings{$i}) { case 'I' : $styleData['font']['italic'] = true; break; case 'D' : $styleData['font']['bold'] = true; break; case 'T' : $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'B' : $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'L' : $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'R' : $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; } } break; } } if (($formatStyle > '') && ($column > '') && ($row > '')) { $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); if (isset($this->_formats[$formatStyle])) { $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]); } } if ((!empty($styleData)) && ($column > '') && ($row > '')) { $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); } if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); } else { $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); $endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); do { $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); } while ($startCol != $endCol); } } } else { foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; } } } } // Close file fclose($fileHandle); // Return return $objPHPExcel; } /** * Get sheet index * * @return int */ public function getSheetIndex() { return $this->_sheetIndex; } /** * Set sheet index * * @param int $pValue Sheet index * @return PHPExcel_Reader_SYLK */ public function setSheetIndex($pValue = 0) { $this->_sheetIndex = $pValue; return $this; } }
cigiko/brdnc.cafe24.com
os/PHPExcel/Classes/PHPExcel/Reader/SYLK.php
PHP
mit
14,181
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Phelsuma factsheet on ARKive - Phelsuma vanheygeni</title> <link rel="canonical" href="http://www.arkive.org/phelsuma/phelsuma-vanheygeni/" /> <link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> </head> <body> <!-- onload="window.print()">--> <div id="container"> <div id="header"><a href="/"><img src="/rimg/factsheet/header_left.png" alt="" border="0" /><img src="/rimg/factsheet/header_logo.png" alt="" border="0" /><img src="/rimg/factsheet/header_right.png" alt="" border="0" /></a></div> <div id="content"> <h1>Phelsuma (<i>Phelsuma vanheygeni</i>)</h1> <img alt="" src="/media/86/869B06F3-B0C7-4B93-8565-7A27CAF0F582/Presentation.Large/phelsuma-vanheygeni-juvenile-close-up.jpg"/> <table cellspacing="0" cellpadding="0" id="factList"> <tbody> <tr class="kingdom"><th align="left">Kingdom</th><td align="left">Animalia</td></tr> <tr class="phylum"><th align="left">Phylum</th><td align="left">Chordata</td></tr> <tr class="class"><th align="left">Class</th><td align="left">Reptilia</td></tr> <tr class="order"><th align="left">Order</th><td align="left">Squamata</td></tr> <tr class="family"><th align="left">Family</th><td align="left">Gekkonidae</td></tr> <tr class="genus"><th align="left">Genus</th><td align="left"><em>Phelsuma (1)</em></td></tr> </tbody> </table> <h2><img src="/rimg/factsheet/Status.png" class="heading" /></h2><p class="Status"><p><em>Phelsuma vanheygeni </em>is classified as Endangered (EN) on the IUCN Red List (1) and listed on Appendix II of CITES (2).</p></p><h2><img src="/rimg/factsheet/Description.png" class="heading" /></h2><p class="Description"><p>Information on&nbsp;<em>Phelsuma vanheygeni </em>is currently being researched and written and will appear here shortly.</p></p><h2><img src="/rimg/factsheet/Authentication.png" class="heading" /></h2><p class="AuthenticatioModel"><p>This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: <br/><a href="mailto:arkive@wildscreen.org.uk">arkive@wildscreen.org.uk</a></p></p><h2><img src="/rimg/factsheet/References.png" class="heading" /></h2> <ol id="references"> <li id="ref1"> <a id="reference_1" name="reference_1"></a> IUCN Red List (August, 2012) <br/><a href="http://www.iucnredlist.org/" target="_blank">http://www.iucnredlist.org/</a></li> <li id="ref2"> <a id="reference_2" name="reference_2"></a> CITES (August, 2012) <br/><a href="http://www.cites.org/" target="_blank">http://www.cites.org/</a></li> </ol> </div> </div> </body> </html>
andrewedstrom/cs638project
raw_data/arkive-endangered-html/phelsuma-vanheygeni.html
HTML
mit
3,069
package com.polydes.common.comp.utils; import java.awt.AWTEvent; import java.awt.Component; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; public class HierarchyLeaveListener extends TemporaryAWTListener implements FocusListener { private boolean inHierarchy; //was the last click in the component's hierarchy private final Component component; private final Runnable callback; public HierarchyLeaveListener(Component component, final Runnable callback) { super(AWTEvent.MOUSE_EVENT_MASK); this.component = component; this.callback = callback; component.addFocusListener(this); } @Override public void eventDispatched(AWTEvent e) { if(e instanceof MouseEvent) { MouseEvent me = (MouseEvent) e; if(me.getClickCount() > 0 && e.toString().contains("PRESSED")) { Component c = (Component) me.getSource(); if(inHierarchy != SwingUtils.isDescendingFrom(c, component)) { inHierarchy = !inHierarchy; if(!inHierarchy) callback.run(); } } } } @Override public void dispose() { super.dispose(); component.removeFocusListener(this); } @Override public void focusGained(FocusEvent e) { inHierarchy = true; start(); } @Override public void focusLost(FocusEvent e) { if(!inHierarchy) stop(); } }
justin-espedal/polydes
Common/src/com/polydes/common/comp/utils/HierarchyLeaveListener.java
Java
mit
1,420
import {bindable} from 'aurelia-framework'; export class SideBarLeft { @bindable router; @bindable layoutCnf = {}; }
hoalongntc/aurelia-material
src/components/layout/sidebar-left.js
JavaScript
mit
122
/** * @depends nothing * @name core.array * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Remove a element, or a set of elements from an array * @version 1.0.0 * @date June 30, 2010 * @copyright John Resig * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; /** * Get a element from an array at [index] * if [current] is set, then set this index as the current index (we don't care if it doesn't exist) * @version 1.0.1 * @date July 09, 2010 * @since 1.0.0 June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.get = function(index, current) { // Determine if ( index === 'first' ) { index = 0; } else if ( index === 'last' ) { index = this.length-1; } else if ( index === 'prev' ) { index = this.index-1; } else if ( index === 'next' ) { index = this.index+1; } else if ( !index && index !== 0 ) { index = this.index; } // Set current? if ( current||false !== false ) { this.setIndex(index); } // Return return this.exists(index) ? this[index] : undefined; }; /** * Apply the function {handler} to each element in the array * Return false in the {handler} to break the cycle. * @param {Function} handler * @version 1.0.1 * @date August 20, 2010 * @since June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.each = function(handler){ for (var i = 0; i < this.length; ++i) { var value = this[i]; if ( handler.apply(value,[i,value]) === false ) { break; } } return this; } /** * Checks whether the index is a valid index * @version 1.0.0 * @date July 09, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.validIndex = function(index){ return index >= 0 && index < this.length; }; /** * Set the current index of the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.setIndex = function(index){ if ( this.validIndex(index) ) { this.index = index; } else { this.index = null; } return this; }; /** * Get the current index of the array * If [index] is passed then set that as the current, and return it's value * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.current = function(index){ return this.get(index, true); }; /** * Get whether or not the array is empty * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isEmpty = function(){ return this.length === 0; }; /** * Get whether or not the array has only one item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isSingle = function(){ return this.length === 1; }; /** * Get whether or not the array is not empty * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isNotEmpty = function(){ return this.length !== 0; }; /** * Get whether or not the array has more than one item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isNotEmpty = function(){ return this.length > 1; }; /** * Get whether or not the current index is the last one * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isLast = function(index){ index = typeof index === 'undefined' ? this.index : index; return !this.isEmpty() && index === this.length-1; } /** * Get whether or not the current index is the first one * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isFirst = function(index){ index = typeof index === 'undefined' ? this.index : index; return !this.isEmpty() && index === 0; } /** * Clear the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.clear = function(){ this.length = 0; }; /** * Set the index as the next one, and get the item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.next = function(update){ return this.get(this.index+1, update); }; /** * Set the index as the previous one, and get the item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.prev = function(update){ return this.get(this.index-1, update); }; /** * Reset the index * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.reset = function(){ this.index = null; return this; }; /** * Set the [index] to the [item] * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.set = function(index, item){ // We want to set the item if ( index < this.length && index >= 0 ) { this[index] = item; } else { throw new Error('Array.prototype.set: [index] above this.length'); // return false; } return this; }; /** * Set the index as the next item, and return it. * If we reach the end, then start back at the beginning. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.loop = function(){ if ( !this.index && this.index !== 0 ) { // index is not a valid value return this.current(0); } return this.next(); }; /** * Add the [arguments] to the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.add = function(){ this.push.apply(this,arguments); return this; }; /** * Insert the [item] at the [index] or at the end of the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.insert = function(index, item){ if ( typeof index !== 'number' ) { index = this.length; } index = index<=this.length ? index : this.length; var rest = this.slice(index); this.length = index; this.push(item); this.push.apply(this, rest); return this; }; /** * Get whether or not the index exists in the array * @version 1.0.0 * @date July 09, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.exists = Array.prototype.exists || function(index){ return typeof this[index] !== 'undefined'; }; /** * Get whether or not the value exists in the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.has = Array.prototype.has || function(value){ var has = false; for ( var i=0, n=this.length; i<n; ++i ) { if ( value == this[i] ) { has = true; break; } } return has; }; /** * @depends nothing * @name core.console * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Console Emulator * We have to convert arguments into arrays, and do this explicitly as webkit (chrome) hates function references, and arguments cannot be passed as is * @version 1.0.3 * @date August 31, 2010 * @since 0.1.0-dev, December 01, 2009 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ // Check to see if console exists, if not define it if ( typeof window.console === 'undefined' ) { window.console = {}; } // Check to see if we have emulated the console yet if ( typeof window.console.emulated === 'undefined' ) { // Emulate Log if ( typeof window.console.log === 'function' ) { window.console.hasLog = true; } else { if ( typeof window.console.log === 'undefined' ) { window.console.log = function(){}; } window.console.hasLog = false; } // Emulate Debug if ( typeof window.console.debug === 'function' ) { window.console.hasDebug = true; } else { if ( typeof window.console.debug === 'undefined' ) { window.console.debug = !window.console.hasLog ? function(){} : function(){ var arr = ['console.debug:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); }; } window.console.hasDebug = false; } // Emulate Warn if ( typeof window.console.warn === 'function' ) { window.console.hasWarn = true; } else { if ( typeof window.console.warn === 'undefined' ) { window.console.warn = !window.console.hasLog ? function(){} : function(){ var arr = ['console.warn:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); }; } window.console.hasWarn = false; } // Emulate Error if ( typeof window.console.error === 'function' ) { window.console.hasError = true; } else { if ( typeof window.console.error === 'undefined' ) { window.console.error = function(){ var msg = "An error has occured."; // Log if ( window.console.hasLog ) { var arr = ['console.error:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); // Adjust Message msg = 'An error has occured. More information is available in your browser\'s javascript console.' } // Prepare Arguments for ( var i = 0; i < arguments.length; ++i ) { if ( typeof arguments[i] !== 'string' ) { break; } msg += "\n"+arguments[i]; } // Throw Error if ( typeof Error !== 'undefined' ) { throw new Error(msg); } else { throw(msg); } }; } window.console.hasError = false; } // Emulate Trace if ( typeof window.console.trace === 'function' ) { window.console.hasTrace = true; } else { if ( typeof window.console.trace === 'undefined' ) { window.console.trace = function(){ window.console.error('console.trace does not exist'); }; } window.console.hasTrace = false; } // Done window.console.emulated = true; } /** * @depends nothing * @name core.date * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Apply the Datetime string to the current Date object * Datetime string in the format of "year month day hour min sec". "hour min sec" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setDatetimestr = Date.prototype.setDatetimestr || function(timestamp){ // Set the datetime from a string var pieces = timestamp.split(/[\-\s\:]/g); var year = pieces[0]; var month = pieces[1]; var day = pieces[2]; var hour = pieces[3]||0; var min = pieces[4]||0; var sec = pieces[5]||0; this.setUTCFullYear(year,month-1,day); this.setUTCHours(hour); this.setUTCMinutes(min); this.setUTCSeconds(sec); return this; }; /** * Apply the Date string to the current Date object * Date string in the format of "year month day". "year month day" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setDatestr = Date.prototype.setDatestr || function(timestamp){ // Set the date from a string var pieces = timestamp.split(/[\-\s\:]/g); var year = pieces[0]||1978; var month = pieces[1]||0; var day = pieces[2]||1; this.setUTCFullYear(year,month-1,day); return this; }; /** * Apply the Time string to the current Date object * Time string in the format of "hour min sec". "hour min sec" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setTimestr = Date.prototype.setTimestr || function(timestamp){ // Set the time from a string var pieces = timestamp.split(/[\-\s\:]/g); var hour = pieces[0]||0; var min = pieces[1]||0; var sec = pieces[2]||0; this.setUTCHours(hour); this.setUTCMinutes(min); this.setUTCSeconds(sec); return this; }; /** * Return the Date as a Datetime string * Datetime string in the format of "year-month-date hours:minutes:seconds". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatetimestr = Date.prototype.getDatetimestr || function() { // Get the datetime as a string var date = this; return date.getDatestr()+' '+date.getTimestr(); }; /** * Return the Date as a Datetime string * Datetime string in the format of "year-month-date". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatestr = Date.prototype.getDatestr || function() { // Get the date as a string var date = this; var year = date.getUTCFullYear(); var month = (this.getUTCMonth() + 1).padLeft(0,2); var date = this.getUTCDate().padLeft(0,2); return year+'-'+month+'-'+date; }; /** * Return the Date as a Datetime string * Datetime string in the format of "hours:minutes:seconds". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getTimestr = Date.prototype.getTimestr || function(){ // Get the time as a string var date = this; var hours = date.getUTCHours().padLeft(0,2); var minutes = date.getUTCMinutes().padLeft(0,2); var seconds = date.getUTCSeconds().padLeft(0,2); return hours+':'+minutes+':'+seconds; }; /** * Return the Date as a ISO 8601 date string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatetime = String.prototype.getDatetime || function(){ // Get a ISO 8601 date var now = this; var datetime = now.getUTCFullYear() + '-' + (now.getUTCMonth()+1).zeroise(2) + '-' + now.getUTCDate().zeroise(2) + 'T' + now.getUTCHours().zeroise(2) + ':' + now.getUTCMinutes().zeroise(2) + ':' + now.getUTCSeconds().zeroise(2) + '+00:00'; return datetime; }; /** * @depends nothing * @name core.number * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Return a new string with zeroes added correctly to the front of the number, given the threshold * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.zeroise = String.prototype.zeroise = String.prototype.zeroise ||function(threshold){ var number = this, str = number.toString(); if (number < 0) { str = str.substr(1, str.length) } while (str.length < threshold) { str = '0' + str } if (number < 0) { str = '-' + str } return str; }; /** * Return a new string with the string/number padded left using [ch] of [num] length * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.padLeft = String.prototype.padLeft = String.prototype.padLeft ||function(ch, num){ var val = String(this); var re = new RegExp('.{' + num + '}$'); var pad = ''; if ( !ch && ch !== 0 ) ch = ' '; do { pad += ch; } while(pad.length < num); return re.exec(pad + val)[0]; }; /** * Return a new string with the string/number padded right using [ch] of [num] length * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.padRight = String.prototype.padRight = String.prototype.padRight ||function(ch, num){ var val = String(this); var re = new RegExp('^.{' + num + '}'); var pad = ''; if ( !ch && ch !== 0 ) ch = ' '; do { pad += ch; } while (pad.length < num); return re.exec(val + pad)[0]; }; /** * Return a new number with the current number rounded to [to] * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.roundTo = String.prototype.roundTo = String.prototype.roundTo || function(to){ var val = String(parseInt(this,10)); val = parseInt(val.replace(/[1,2]$/, 0).replace(/[3,4]$/, 5),10); return val; }; /** * @depends nothing * @name core.string * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Return a new string with any spaces trimmed the left and right of the string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.trim = String.prototype.trim || function() { // Trim off any whitespace from the front and back return this.replace(/^\s+|\s+$/g, ''); }; /** * Return a new string with the value stripped from the left and right of the string * @version 1.1.1 * @date July 22, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.strip = String.prototype.strip || function(value,regex){ // Strip a value from left and right, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/^'+value+'+|'+value+'+$/g'), ''); } return String(str); } /** * Return a new string with the value stripped from the left of the string * @version 1.1.1 * @date July 22, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.stripLeft = String.prototype.stripLeft || function(value,regex){ // Strip a value from the left, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/^'+value+'+/g'), ''); } return String(str); } /** * Return a new string with the value stripped from the right of the string * @version 1.1.1 * @date July 22, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.stripRight = String.prototype.stripRight || function(value,regex){ // Strip a value from the right, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/'+value+'+$/g'), ''); } return String(str); } /** * Return a int of the string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.toInt = String.prototype.toInt || function(){ // Convert to a Integer return parseInt(this,10); }; /** * Return a new string of the old string wrapped with the start and end values * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.wrap = String.prototype.wrap || function(start,end){ // Wrap the string return start+this+end; }; /** * Return a new string of a selection of the old string wrapped with the start and end values * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.wrapSelection = String.prototype.wrapSelection || function(start,end,a,z){ // Wrap the selection if ( typeof a === 'undefined' || a === null ) a = this.length; if ( typeof z === 'undefined' || z === null ) z = this.length; return this.substring(0,a)+start+this.substring(a,z)+end+this.substring(z); }; /** * Return a new string of the slug of the old string * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.toSlug = String.prototype.toSlug || function(){ // Convert a string to a slug return this.toLowerCase().replace(/[\s_]/g, '-').replace(/[^-a-z0-9]/g, '').replace(/--+/g, '-').replace(/^-+|-+$/g,''); } /** * Return a new JSON object of the old string. * Turns: * file.js?a=1&amp;b.c=3.0&b.d=four&a_false_value=false&a_null_value=null * Into: * {"a":1,"b":{"c":3,"d":"four"},"a_false_value":false,"a_null_value":null} * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.queryStringToJSON = String.prototype.queryStringToJSON || function ( ) { // Turns a params string or url into an array of params // Prepare var params = String(this); // Remove url if need be params = params.substring(params.indexOf('?')+1); // params = params.substring(params.indexOf('#')+1); // Change + to %20, the %20 is fixed up later with the decode params = params.replace(/\+/g, '%20'); // Do we have JSON string if ( params.substring(0,1) === '{' && params.substring(params.length-1) === '}' ) { // We have a JSON string return eval(decodeURIComponent(params)); } // We have a params string params = params.split(/\&(amp\;)?/); var json = {}; // We have params for ( var i = 0, n = params.length; i < n; ++i ) { // Adjust var param = params[i] || null; if ( param === null ) { continue; } param = param.split('='); if ( param === null ) { continue; } // ^ We now have "var=blah" into ["var","blah"] // Get var key = param[0] || null; if ( key === null ) { continue; } if ( typeof param[1] === 'undefined' ) { continue; } var value = param[1]; // ^ We now have the parts // Fix key = decodeURIComponent(key); value = decodeURIComponent(value); try { // value can be converted value = eval(value); } catch ( e ) { // value is a normal string } // Set // window.console.log({'key':key,'value':value}, split); var keys = key.split('.'); if ( keys.length === 1 ) { // Simple json[key] = value; } else { // Advanced (Recreating an object) var path = '', cmd = ''; // Ensure Path Exists $.each(keys,function(ii,key){ path += '["'+key.replace(/"/g,'\\"')+'"]'; jsonCLOSUREGLOBAL = json; // we have made this a global as closure compiler struggles with evals cmd = 'if ( typeof jsonCLOSUREGLOBAL'+path+' === "undefined" ) jsonCLOSUREGLOBAL'+path+' = {}'; eval(cmd); json = jsonCLOSUREGLOBAL; delete jsonCLOSUREGLOBAL; }); // Apply Value jsonCLOSUREGLOBAL = json; // we have made this a global as closure compiler struggles with evals valueCLOSUREGLOBAL = value; // we have made this a global as closure compiler struggles with evals cmd = 'jsonCLOSUREGLOBAL'+path+' = valueCLOSUREGLOBAL'; eval(cmd); json = jsonCLOSUREGLOBAL; delete jsonCLOSUREGLOBAL; delete valueCLOSUREGLOBAL; } // ^ We now have the parts added to your JSON object } return json; }; /** * @depends jquery * @name jquery.appendscriptstyle * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Append a Stylesheet to the DOM * @version 1.1.0 * @date July 23, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.appendStylesheet = $.appendStylesheet || function(url, overwrite){ // Check if ( !(document.body||false) ) { setTimeout(function(){ $.appendStylesheet.apply($,[url,overwrite]); },500); // Chain return $; } // Prepare var id = 'stylesheet-'+url.replace(/[^a-zA-Z0-9]/g, '');; var $old = $('#'+id); if ( typeof overwrite === 'undefined' ) { overwrite = false; } // Check if ( $old.length === 1 ) { if ( overwrite ) { $old.remove(); } else { // Chain return $; } } // Create var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0]; var linkEl = document.createElement('link'); linkEl.type = 'text/css'; linkEl.rel = 'stylesheet'; linkEl.media = 'screen'; linkEl.href = url; linkEl.id = id; bodyEl.appendChild(linkEl); // Chain return $; }; /** * Append a Script to the DOM * @version 1.1.0 * @date July 23, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.appendScript = $.appendScript || function(url, overwrite){ // Check if ( !(document.body||false) ) { setTimeout(function(){ $.appendScript.apply($,[url,overwrite]); },500); // Chain return $; } // Prepare var id = 'script-'+url.replace(/[^a-zA-Z0-9]/g, '');; var $old = $('#'+id); if ( typeof overwrite === 'undefined' ) { overwrite = false; } // Check if ( $old.length === 1 ) { if ( overwrite ) { $old.remove(); } else { // Chain return $; } } // Create var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0]; var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.src = url; scriptEl.id = id; bodyEl.appendChild(scriptEl); // Chain return $; }; })(jQuery); /** * @depends jquery * @name jquery.extra * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Opacity Fix for Text without Backgrounds * Fixes the text corrosion during opacity effects by forcing a background-color value on the element. * The background-color value is the the same value as the first parent div which has a background-color. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.opacityFix = $.fn.opacityFix || function(){ var $this = $(this); // Check if this fix applies var color = $this.css('background-color'); if ( color && color !== 'rgba(0, 0, 0, 0)' ) { return this; } // Apply the background colour of the first parent which has a background colour var $parent = $this; while ( $parent.inDOM() ) { $parent = $parent.parent(); color = $parent.css('background-color'); if ( color && color !== 'rgba(0, 0, 0, 0)' ) { $this.css('background-color',color); break; } } // Chain return this; }; /** * Get all elements above ourself which match the selector, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.parentsAndSelf = $.fn.parentsAndSelf || function(selector){ var $this = $(this); return $this.parents(selector).andSelf().filter(selector); }; /** * Get all elements within ourself which match the selector, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.findAndSelf = $.fn.findAndSelf || function(selector){ var $this = $(this); return $this.find(selector).andSelf().filter(selector); }; /** * Find the first input, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.firstInput = $.fn.firstInput || function(){ var $this = $(this); return $this.findAndSelf(':input').filter(':first'); }; /** * Select a option within options, checkboxes, radios and selects. * Rather than setting the actual value of a element which $el.val does. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.choose = $.fn.choose||function(value){ var $this = $(this); if ( typeof value === 'undefined' ) { value = $this.val(); } else if ( $this.val() !== value ) { // Return early, don't match return this; } switch ( true ) { case this.is('option'): $this.parents('select:first').choose(value); break; case $this.is(':checkbox'): $this.attr('checked', true); break; case $this.is(':radio'): $this.attr('checked', true); break; case $this.is('select'): $this.val(value); break; default: break; } return this; }; /** * Deselect a option within options, checkboxes, radios and selects. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.unchoose = $.fn.unchoose||function(){ var $this = $(this); switch ( true ) { case $this.is('option'): $this.parents(':select:first').unchoose(); break; case $this.is(':checkbox'): $this.attr('checked', false); break; case $this.is(':radio'): $this.attr('checked', false); break; case $this.is('select'): $this.val($this.find('option:first').val()); break; default: break; } return this; }; /** * Checks if the element would be passed with the form if the form was submitted. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.wouldSubmit = $.fn.wouldSubmit || function(){ var $input = $(this).findAndSelf(':input'); var result = true; if ( !$input.length || !($input.attr('name')||false) || ($input.is(':radio,:checkbox') && !$input.is(':selected,:checked')) ) { result = false; } return result; }; /** * Grab all the values of a form in JSON format if the form would be submitted. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.values = $.fn.values || function(){ var $inputs = $(this).findAndSelf(':input'); var values = {}; $inputs.each(function(){ var $input = $(this); var name = $input.attr('name') || null; var value = $input.val(); // Skip if wouldn't submit if ( !$input.wouldSubmit() ) { return true; } // Set value if (name.indexOf('[]') !== -1) { // We want an array if (typeof values[name] === 'undefined') { values[name] = []; } values[name].push(value); } else { values[name] = value; } }); return values; }; /** * Submit the form which the element is associated with. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.submitForm = $.fn.submitForm || function(){ // Submit the parent form or our form var $this = $(this); // Handle var $form = $this.parentsAndSelf('form:first').trigger('submit'); // Chain return $this; }; /** * Checks if the element is attached within the DOM * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.inDOM = $.fn.inDOM || function(){ var $ancestor = $(this).parent().parent(); return $ancestor.size() && ($ancestor.height()||$ancestor.width()); }; /** * Wrap the element's value with the passed start and end text * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.valWrap = $.fn.valWrap || function(start,end){ // Wrap a value var $field = $(this); return $field.val($field.val().wrap(start,end)); }; /** * Wrap a selection of the element's value with the passed start and end text * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.valWrapSelection = $.fn.valWrapSelection || function(start,end,a,z){ // Wrap the selected text var $field = $(this); var field = $field.get(0); start = start||''; end = end||''; if ( a || z ) { $field.val($field.val().wrapSelection(start,end,a,z)); } else { var a = field.selectionStart, z = field.selectionEnd; if ( document.selection) { field.focus(); var sel = document.selection.createRange(); sel.text = start + sel.text + end; } else { var scrollTop = field.scrollTop; $field.val($field.val().wrapSelection(start,end,a,z)); field.focus(); field.selectionStart = a+start.length; field.selectionEnd = z+start.length; field.scrollTop = scrollTop; } } return $field; }; /** * Find (with regards to the element) the first visible input element, and give focus to it * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.giveFocus = $.fn.giveFocus || function(){ // Give focus to the current element var $this = $(this); var selector = ':input:visible:first'; $this.findAndSelf(selector).focus(); return this; }; /** * Gives target to the element, and removes target from everything else * @version 1.0.0 * @date August 23, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.giveTarget = $.fn.giveTarget || function(){ // Give focus to the current element var $this = $(this); $('.target').removeClass('target'); $this.addClass('target'); return this; }; /** * Perform the highlight effect * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.highlight = $.fn.highlight || function(duration){ // Perform the Highlight Effect return $(this).effect('highlight', {}, duration||3000); }; /** * Get a elements html including it's own tag * @version 1.0.1 * @date August 07, 2010 * @since 1.0.0, August 07, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.htmlAndSelf = $.fn.htmlAndSelf || function(){ // Get a elements html including it's own tag return $(this).attr('outerHTML'); }; /** * Prevent the default action when a click is performed * @version 1.0.1 * @date August 31, 2010 * @since 1.0.0, August 19, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.preventDefaultOnClick = $.fn.preventDefaultOnClick || function(){ return $(this).click(function(event){ event.preventDefault(); return false; }); }; /** * Attempts to change the element type to {$type} * @version 1.0.1 * @date August 07, 2010 * @since 1.0.0, August 07, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.attemptTypeChangeTo = $.fn.attemptTypeChangeTo || function(type){ // Prepare var $input = $(this), result = false, el = $input.get(0), oldType = el.type; // Handle if ( type === oldType ) { // Setting to the same result = true; } else if ( $input.is('input') ) { // We are in fact an input if ( !$.browser.msie ) { // We are not IE, this is due to bug mentioned here: http://stackoverflow.com/questions/1544317/jquery-change-type-of-input-field el.type = type; if ( el.type !== oldType ) { // It stuck, so we successfully applied the type result = true; } } } // Return result return result; }; })(jQuery); /** * @depends jquery * @name jquery.events * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Bind a event, with or without data * Benefit over $.bind, is that $.binder(event, callback, false|{}|''|false) works. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.binder = $.fn.binder || function(event, data, callback){ // Help us bind events properly var $this = $(this); // Handle if ( (callback||false) ) { $this.bind(event, data, callback); } else { callback = data; $this.bind(event, callback); } // Chain return $this; }; /** * Bind a event only once * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.once = $.fn.once || function(event, data, callback){ // Only apply a event handler once var $this = $(this); // Handle if ( (callback||false) ) { $this.unbind(event, callback); $this.bind(event, data, callback); } else { callback = data; $this.unbind(event, callback); $this.bind(event, callback); } // Chain return $this; }; /** * Event for pressing the enter key * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.enter = $.fn.enter || function(data,callback){ return $(this).binder('enter',data,callback); }; $.event.special.enter = $.event.special.enter || { setup: function( data, namespaces ) { $(this).bind('keypress', $.event.special.enter.handler); }, teardown: function( namespaces ) { $(this).unbind('keypress', $.event.special.enter.handler); }, handler: function( event ) { // Prepare var $el = $(this); // Setup var enterKey = event.keyCode === 13; if ( enterKey ) { // Our event event.type = 'enter'; $.event.handle.apply(this, [event]); return true; } // Not our event return; } }; /** * Event for pressing the escape key * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.cancel = $.fn.cancel || function(data,callback){ return $(this).binder('cancel',data,callback); }; $.event.special.cancel = $.event.special.cancel || { setup: function( data, namespaces ) { $(this).bind('keyup', $.event.special.cancel.handler); }, teardown: function( namespaces ) { $(this).unbind('keyup', $.event.special.cancel.handler); }, handler: function( event ) { // Prepare var $el = $(this); // Setup var moz = typeof event.DOM_VK_ESCAPE === 'undefined' ? false : event.DOM_VK_ESCAPE; var escapeKey = event.keyCode === 27; if ( moz || escapeKey ) { // Our event event.type = 'cancel'; $.event.handle.apply(this, [event]); return true; } // Not our event return; } }; /** * Event for the last click for a series of one or more clicks * @version 1.0.0 * @date July 16, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.lastclick = $.fn.lastclick || function(data,callback){ return $(this).binder('lastclick',data,callback); }; $.event.special.lastclick = $.event.special.lastclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.lastclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.lastclick.handler); }, handler: function( event ) { // Setup var clear = function(){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('lastclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('lastclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Store the amount of times we have been clicked $el.data('lastclick-clicks', ($el.data('lastclick-clicks')||0)+1); // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Fetch Clicks Count var clicks = $el.data('lastclick-clicks'); // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('lastclick-clicks',0); // Fire Event event.type = 'lastclick'; $.event.handle.apply(Me, [event,clicks]) },500); // Store Timeout $el.data('lastclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; /** * Event for the first click for a series of one or more clicks * @version 1.0.0 * @date July 16, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.firstclick = $.fn.firstclick || function(data,callback){ return $(this).binder('firstclick',data,callback); }; $.event.special.firstclick = $.event.special.firstclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.firstclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.firstclick.handler); }, handler: function( event ) { // Setup var clear = function(event){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('firstclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('firstclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Update the amount of times we have been clicked $el.data('firstclick-clicks', ($el.data('firstclick-clicks')||0)+1); // Check we are the First of the series of many if ( $el.data('firstclick-clicks') === 1 ) { // Fire Event event.type = 'firstclick'; $.event.handle.apply(Me, [event]) } // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('firstclick-clicks',0); },500); // Store Timeout $el.data('firstclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; /** * Event for performing a singleclick * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.singleclick = $.fn.singleclick || function(data,callback){ return $(this).binder('singleclick',data,callback); }; $.event.special.singleclick = $.event.special.singleclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.singleclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.singleclick.handler); }, handler: function( event ) { // Setup var clear = function(event){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('singleclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('singleclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Update the amount of times we have been clicked $el.data('singleclick-clicks', ($el.data('singleclick-clicks')||0)+1); // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Fetch Clicks Count var clicks = $el.data('singleclick-clicks'); // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('singleclick-clicks',0); // Check Click Status if ( clicks === 1 ) { // There was only a single click performed // Fire Event event.type = 'singleclick'; $.event.handle.apply(Me, [event]) } },500); // Store Timeout $el.data('singleclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; })(jQuery); /** * @depends jquery * @name jquery.utilities * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Creates a new object, which uses baseObject's structure, and userObject's values when applicable * @params {Object} baseObject * @params {Object} userObject * @params {Object} ... * @return {Object} newObject * @version 1.0.0 * @date August 01, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.prepareObject = $.prepareObject || function(baseObject,userObject) { var newObject = {}; var skipValue = '$.prepareObject.skipValue'; // Extend newObject $.extend(newObject,baseObject||{}); // Intercept with the userObject $.intercept(true,newObject,userObject); // Handle additional params var objects = arguments; objects[0] = objects[1] = skipValue; // Cycle through additional objects $.each(objects,function(i,object){ // Check if we want to skip if ( object === skipValue ) return true; // continue // Intercept with the object $.intercept(true,newObject,object); }); // Return the newObject return newObject; }; /** * Intercept two objects * @params [deep], &object1, object2, ... * @version 1.0.0 * @date August 01, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.intercept = $.intercept || function() { // Prepare var objects = arguments, object, deep = false, copy = false; var skipValue = '$.intercept.skipValue'; // Check Deep if ( typeof objects[0] === 'boolean' ) { deep = objects[0]; objects[0] = skipValue; // Check Copy if ( typeof objects[1] === 'boolean' ) { copy = objects[1]; objects[1] = skipValue; // Handle Copy if ( copy ) { object = {}; } else { object = objects[2]; objects[2] = skipValue; } } else { object = objects[1]; objects[1] = skipValue; } } else { object = objects[0]; objects[0] = skipValue; } // Grab Keys var keys = {}; $.each(object,function(key){ keys[key] = true; }); // Intercept Objects if ( deep ) { // Cycle through objects $.each(objects, function(i,v){ // Check if we want to skip if ( v === skipValue ) return true; // continue // Cycle through arguments $.each(v, function(key,value){ // Check if the key exists so we can intercept if ( typeof keys[key] === 'undefined' ) return true; // continue // It exists, check value type if ( typeof value === 'object' && !(value.test||false && value.exec||false) ) { // Extend this object $.extend(object[key],value||{}); } else { // Copy value over object[key] = value; } }); }) } else { // Cycle through objects $.each(objects, function(i,v){ // Cycle through arguments $.each(v, function(key,value){ // Check if the key exists so we can intercept if ( typeof keys[key] === 'undefined' ) return true; // continue // It exists, check value type if ( typeof value === 'object' && !(value.test||false && value.exec||false) ) { // Intercept this object $.intercept(true,object[key],value); } else { // Copy value over object[key] = value; } }); }) } // Return object return object; }; /** * Handle a Promise * @param {Object} options.object * @param {String} options.handlers * @param {String} options.flag * @param {Funtion} options.handler * @return {Boolean} Whether or not the promise is ready * @version 1.0.0 * @date August 31, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.promise = $.promise || function(options){ // Extract var object = options.object||this; // Check if ( typeof object[options.handlers] === 'undefined' ) { object[options.handlers] = []; } if ( typeof object[options.flag] === 'undefined' ) { object[options.flag] = false; } // Extract var handlers = object[options.handlers], flag = object[options.flag], handler = options.arguments[0]; // Handle switch ( typeof handler ) { case 'boolean': // We want to set the flag as true or false, then continue on flag = object[options.flag] = handler; // no break, as we want to continue on case 'undefined': // We want to fire the handlers, so check if the flag is true if ( flag && handlers.length ) { // Fire the handlers $.each(handlers, function(i,handler){ handler.call(object); }); // Clear the handlers object[options.handlers] = []; } break; case 'function': // We want to add or fire a handler, so check the flag if ( flag ) { // Fire the event handler handler.call(object); } else { // Add to the handlers object[options.handlers].push(handler); } break; default: window.console.error('Unknown arguments for $.promise', [this, arguments]); break; } // Return flag return flag; } })(jQuery); /** * @depends jquery * @name jquery.passwordstrength * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * String.prototype.passwordStrength * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.passwordstrength = String.prototype.passwordstrength || function(confirm,username){ var password = this.toString(), symbolSize = 0, natLog, score; confirm = confirm||''; username = username||''; // Short if ( password.length < 4 ) { return "short"; }; // Username if ( username.length && password.toLowerCase() == username.toLowerCase()) { return "username"; } // Confirm if ( confirm.length && password != confirm ) { return "mismatch"; } // Strength if ( password.match(/[0-9]/) ) symbolSize +=10; if ( password.match(/[a-z]/) ) symbolSize +=26; if ( password.match(/[A-Z]/) ) symbolSize +=26; if ( password.match(/[^a-zA-Z0-9]/) ) symbolSize +=31; // Score natLog = Math.log( Math.pow(symbolSize,password.length) ); score = natLog / Math.LN2; // Check if (score < 40 ) { return "low"; } else if (score < 56 ) { return "medium"; } // Strong return "high"; }; /** * jQuery Password Strength * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.fn.passwordstrength||false) ) { $.fn.passwordstrength = function(options) { // Prepare var passwordstrength = $.fn.passwordstrength; passwordstrength.config = passwordstrength.config || { content: '<div class="sparkle-passwordstrength-result"></div><div class="sparkle-passwordstrength-description"></div>', contentSelectors: { result: '.sparkle-passwordstrength-result', description: '.sparkle-passwordstrength-description' }, strengthCss: { "short": "invalid", mismatch: "invalid", username: "invalid", low: "low", medium: "medium", high: "high", empty: "" }, il8n: { description: "Hint: The password should be have a strength of at least medium. To make it stronger, use upper and lower case letters, numbers and symbols like ! \" ? $ % ^ &amp; ).", empty: "Strength indicator", username: "Password should not match username", mismatch: "Confirm password does not match", "short": "Password is too short", low: "Weak", medium: "Medium", high: "Strongest" } }; var config = $.extend({}, passwordstrength.config); // Options $.extend(true, config, options); // Fetch var $this = $(this); var $container = $this.html(config.content).hide(); // Implode var $result = $container.find(config.contentSelectors.result); var $description = $container.find(config.contentSelectors.description).html(config.il8n.description); if ( !config.il8n.description ) { $description.remove(); } // Prepare var classes = [ config.strengthCss["short"], config.strengthCss.mismatch, config.strengthCss.username, config.strengthCss.low, config.strengthCss.medium, config.strengthCss.high, config.strengthCss.empty ].join(' '); // Fetch var $password = $(config.password), $confirm = $(config.confirm||null), $username = $(config.username||null); // Apply var check = function(){ // Fetch var password = $password.val(), confirm = $confirm.val(), username = $username.val(); // Strength var strength = password ? password.passwordstrength(confirm,username) : "empty"; var strength_css = config.strengthCss[strength]; var strength_text = config.il8n[strength]; // Apply $result.removeClass(classes).addClass(strength_css).html(strength_text); }; $password .keyup(function(){ var $password = $(this); $confirm.val(''); if ( $password.val() !== '' && !$container.data('shown') ) { $container.animate({'height':'show','opacity':'show'},'slow').data('shown',true); } }); $password.add($confirm).add($username).keyup(check); check(); // Chain return $this; } } else { window.console.warn("$.fn.passwordstrength has already been defined..."); } })(jQuery);/** * @depends jquery, core.console * @name jquery.balclass * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * BalClass * @version 1.5.0 * @date August 28, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.BalClass||false) ) { // Constructor $.BalClass = function(extend){ this.construct(extend); }; // Prototype $.extend($.BalClass.prototype, { config: { }, construct: function(){ var Me = this, extend = {}; // Handle if ( typeof arguments[0] === 'object' && typeof arguments[1] === 'object' ) { // config, extend extend = arguments[1]; extend.config = arguments[0]||{}; } else if ( typeof arguments[0] === 'object' ) { // extend extend = arguments[0]; extend.config = extend.config||{}; } else if ( typeof arguments[0] === 'undefined' ) { // No arguments were passed extend = false; } else { window.console.error('BalClass.construct: Invalid Input'); } // Check if ( extend !== false ) { // Configure Me.configure(extend.config); delete extend.config; // Extend $.extend(Me,extend); } // Build if ( typeof Me.built === 'function' ) { return Me.built(); } // Return true return true; }, configure: function(config){ var Me = this; Me.config = Me.config||{}; Me.config = $.extend({},Me.config,config||{}); // we want to clone return Me; }, clone: function(extend){ // Clone a BalClass (Creates a new BalClass type) var Me = this; var clone = function(extend){ this.construct(extend); }; $.extend(clone.prototype, Me.prototype, extend||{}); clone.clone = clone.prototype.clone; clone.create = clone.prototype.create; return clone; }, create: function(Extension){ // Create a BalClass (Creates a new instance of a BalClass) var Me = this; var Obj = new Me(Extension); return Obj; }, addConfig: function(name, config){ var Me = this; if ( typeof config === 'undefined' ) { if ( typeof name === 'object' ) { // Series $.each(name,function(key,value){ Me.applyConfig(key, value); }); } return false; } else if ( typeof config === 'object' ) { // Single Me.applyConfig(name, config); } return Me; }, applyConfig: function(name,config){ var Me = this; Me.config[name] = Me.config[name]||{}; $.extend(true,Me.config[name],config||{}); return Me; }, setConfig: function(name,config){ var Me = this; Me.config[name] = config||{}; return Me; }, hasConfig: function(name){ var Me = this; return typeof Me.config[name] !== 'undefined'; }, getConfig: function(name){ var Me = this; if ( typeof name !== 'string' ) { return this.config; } return this.getConfigWith(name); }, getConfigWith: function(name,config){ var Me = this; if ( typeof name !== 'string' ) { if ( typeof config === 'undefined' ) { config = name; } name = 'default'; } if ( typeof config !== 'object' ) { config = {}; } var result = {}; $.extend(true, result, Me.config[name]||{}, config||{}); return result; }, getConfigWithDefault: function(name,config){ var Me = this; return Me.getConfigWith('default',Me.getConfigWith(name,config)); }, setDefaults: function(config){ var Me = this; return Me.applyConfig('default',config); } }); // Instance $.BalClass.clone = $.BalClass.prototype.clone; $.BalClass.create = $.BalClass.prototype.create; // ^ we alias these as they should be both in prototype and instance // however we do not want to create a full instance yet... } else { window.console.warn("$.BalClass has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass, bespin * @name jquery.balclass.bespin * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Bespin Extender * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Bespin||false) ) { $.Bespin = $.BalClass.create({ // Configuration config: { "default": { "content": null, "bespin": { "settings": { "tabstop": 4 } }, "toolbar": { "fullscreen": true } }, "rich": { "bespin": { "syntax": "html" } }, "html": { "bespin": { "syntax": "html" } }, "plain": { "toolbar": false } }, // Functions fn: function(mode, options) { // Prepare var Me = $.Bespin; var config = Me.getConfigWithDefault(mode,options); // Elements var element = this; // Bespin var onBespinLoad = function(){ // Use Bespin Me.useBespin(element, config); }; $(window).bind('onBespinLoad', onBespinLoad); // Events var events = { onBespinLoad: function(){ $(window).trigger('onBespinLoad'); } }; // Check Loaded if ( bespin.bootLoaded ) { // Fire Event setTimeout(function(){ events.onBespinLoad(); },500); } else { // Add Event window.onBespinLoad = events.onBespinLoad; } // ^ we have this check as if bespin has already loaded, then the onBespinLoad will never fire! // Chain return this; }, useBespin: function(element, config) { // Prepare var Me = $.Bespin; // Elements var $element = $(element), $bespin, bespin_id; // Check if ( $element.is('textarea') ) { // Editor is a textarea // So we have to create a div to use as our bespin editor // Update id bespin_id = $element.attr('id')+'-bespin'; // Create div $bespin = $('<div id="'+bespin_id+'"/>').html($element.val()).css({ height: $element.css('height'), width: $element.css('width') }); // Insert div $bespin.insertAfter($element); // Hide textarea $element.hide(); } else { // Editor is likely a div // So we can use that as our bespin editor $bespin = $element; bespin_id = $bespin.attr('id'); } // Use Bespin bespin.useBespin(bespin_id,config.bespin).then( function(env){ // Success Me.postBespin(bespin_id, env, config); }, function(error){ // Error window.console.error("Bespin Launch Failed: " + error); } ); // Chain return this; }, postBespin: function(bespin_id, env, config) { // Prepare var Me = $.Bespin; // Elements var $bespin = $('#'+bespin_id); var $textarea = $bespin.siblings('textarea'); var editor = env.editor; // Ensure overflow is set to hidden // stops bespin from having text outside it's box in rare circumstances $bespin.css('overflow','hidden'); // Wrap our div $bespin.wrap('<div class="bespin-wrap" />'); var $bespin_wrap = $bespin.parent(); // Update Textarea on submit if ( $textarea.length ) { var updateFunction = function(){ var val = editor.value; $textarea.val(val); }; $textarea.parents('form:first').submit(updateFunction); } // Change the value if ( config.content || config.content === '' ) { editor.value = config.content; } // Toolbar if ( config.toolbar||false ) { var $toolbar = $('<div class="bespin-toolbar" />'); $toolbar.insertBefore($bespin); // Fullscreen if (config.toolbar.fullscreen||false ) { var $fullscreen = $('<span class="bespin-toolbar-fullscreen" title="Toggle Fullscreen"></span>'); $fullscreen.appendTo($toolbar); $fullscreen.click(function(){ if ( $bespin_wrap.hasClass('bespin-fullscreen') ) { // Destroy fullscreen $('body').add($bespin_wrap).removeClass('bespin-fullscreen'); } else { // Make fullscreen $('body').add($bespin_wrap).addClass('bespin-fullscreen'); } env.dimensionsChanged(); }); } } // Chain return this; }, built: function(){ // Prepare var Me = this; // Attach $.fn.Bespin = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Bespin has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.datepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Date Picker * @version 1.0.1 * @date August 20, 2010 * @since 1.0.0, August 18, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Datepicker||false) ) { $.Datepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Datepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-date-has') ) { // Already done return this; } $input.addClass('sparkle-date').addClass('sparkle-date-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.date && $input.attemptTypeChangeTo('date') ) { // Chain return this; } // Instantiate $input.datepicker(config); // Chain return this; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.Datepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Datepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.datetimepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Date Time Picker * @version 1.3.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Datetimepicker||false) ) { $.Datetimepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false, datepickerOptions: { }, timepickerOptions: { } }, '12hr': { timepickerOptions: { timeConvention: 12 } }, '24hr': { timepickerOptions: { timeConvention: 24 } } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Datetimepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-datetime-has') ) { // Already done return this; } $input.addClass('sparkle-datetime').addClass('sparkle-datetime-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.datetime && $input.attemptTypeChangeTo('datetime') ) { // Chain return this; } // -------------------------- // Defaults var value = $input.val(); var date = new Date(); var datestr = '', timestr = ''; if ( value ) { date.setDatetimestr(value); datestr = date.getDatestr(); timestr = date.getTimestr(); } // -------------------------- // DOM Manipulation // Hide $input.hide(); // Create date part var $date = $('<input type="text" class="sparkle-date"/>'); var $sep = $('<span class="sparkle-datetime-sep"> @ </span>'); var $time = $('<input type="text" class="sparkle-time"/>'); // Append $time.insertAfter($input); $sep.insertAfter($input); $date.insertAfter($input); // Apply $date.val(datestr); $time.val(timestr); // -------------------------- // Bind var updateFunction = function(){ var value = $date.val()+' '+$time.val(); $input.val(value).trigger('change'); }; $date.add($time).change(updateFunction); // Instantiate $date.Datepicker(config.datepickerOptions); $time.Timepicker(config.timepickerOptions); // Chain return $input; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.datetimepicker = $.fn.Datetimepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Datetimepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.eventcalendar * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Event Calendar * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.EventCalendar||false) ) { $.EventCalendar = $.BalClass.create({ // Configuration config: { // Default Mode "default": { // Ajax Variables /** The JSON variable that will be return on the AJAX request which will contain our entries */ ajaxEntriesVariable: 'entries', /** The AJAX url to request for our entries */ ajaxEntriesUrl: '', /** The JSON Object to send via POST to our AJAX request */ ajaxPostData: {}, /** Whether or not to Cache the AJAX data */ ajaxCache: true, // Data Variables /* If you are not using AJAX, you can define your entries here */ calendarEntries: [], // Customisation Variables /** The CSS class which will be assigned to the Event Calendar */ calendarClass: 'hasEventCalendar', /** The CSS class which will be assigned to day when the day contains a entry */ dayEventClass: 'ui-state-active hasEvent', /** The standard options to send to the datepicker */ datepickerOptions: {}, /** Whether or not to disable the datepicker date selection click */ disableClick: true, /** * Whatever events you would like to assign to a $day * You will recieve the arguments: domEvent, day, dayEntries, entries */ domEvents: {} } }, // Functions /** * jQuery Object Function */ fn: function(mode,options){ var EventCalendar = $.EventCalendar; // Group? var $calendar = $(this); if ( $calendar.length > 1 ) { $calendar.each(function(){ $(this).EventCalendar(mode,options); }); return this; } // Prepare var Me = $.EventCalendar; var config = Me.getConfigWithDefault(mode,options); // Initialise var Entries = { /** * Calendar Entries Stored by {entryId:entry} */ entriesById: {}, /** * Calendar Entries Stored by {"year-month":[entry,entry]} */ entriesByYearMonth: {}, /** * Whether or not the "year-month" is cacheable */ cacheableByYearMonth: {}, /** * Get whether or not a "year-month" is cacheable */ isCacheable: function(year,month,value){ return (this.cacheableByYearMonth[year+'-'+month]||false) ? true : false; }, /** * Set whether or not a "year-month" is cacheable */ setCacheable: function(year,month,value){ if ( typeof value === 'undefined' ) value = this.cacheableByYearMonth[year+'-'+month] = value; return this; }, /** * Calendar Entries Undefined */ isYearMonthSet: function(year,month) { return typeof this.entriesByYearMonth[year+'-'+month] !== 'undefined'; }, /** * Calendar Entries Empty */ isYearMonthEmpty: function(year,month) { var notempty = (typeof this.entriesByYearMonth[year+'-'+month] === 'array' && this.entriesByYearMonth[year+'-'+month].length !== 0) || (typeof this.entriesByYearMonth[year+'-'+month] === 'object' && !$.isEmptyObject(this.entriesByYearMonth[year+'-'+month])) ; return !notempty; }, /** * Calendar Entries Getter */ getEntriesByYearMonth: function(year,month) { return this.entriesByYearMonth[year+'-'+month]||[]; }, /** * Calendar Entries Getter */ getEntryById: function(id) { return this.entriesById[id]||undefined; }, /** * Get Days in a Month by passing a date */ getDaysInMonth: function(date){ // http://snippets.dzone.com/posts/show/2099 return 32 - new Date(date.getFullYear(), date.getMonth(), 32).getDate(); }, /** * Get Date */ getDate: function(timestamp){ // Convert var date; if ( typeof timestamp === 'string' ) { date = new Date(timestamp); } else if ( typeof timestamp === 'number' ) { date = new Date(); date.setTime(timestamp); } else if ( typeof timestamp === 'object' ) { date = new Date(); date.setTime(timestamp.getTime()); } else { throw Error("Unknown date format."); } // Fix for Firefox if ( isNaN(date) || date.toString() === "Invalid Date" ) { date = new Date(); date.setDatetimestr(timestamp); } // Return date return date; }, /** * Calendar Entries Setter */ addEntries: function(entries) { // Prepare var Me = this; // Add $.each(entries,function(index,entry){ // Prepare entry.id = entry.id||index; // Add Entry Me.addEntry(entry); }); // Chain return true; }, /** * Calendar Entries Setter */ addEntry: function(entry) { // Prepare entry entry.start = this.getDate(entry.start); entry.finish = this.getDate(entry.finish); // Cycle through years and months var currentDate = this.getDate(entry.start); currentDate.setDate(1); currentDate.setHours(0); currentDate.setMinutes(0); currentDate.setSeconds(0); currentDate.setMilliseconds(0); var finishDate = this.getDate(entry.finish); finishDate.setDate(2); finishDate.setHours(0); finishDate.setMinutes(0); finishDate.setSeconds(0); finishDate.setMilliseconds(0); while ( currentDate < finishDate ) { // Fetch var year = currentDate.getFullYear(), month = currentDate.getMonth()+1; /* // Add entry.span = entry.span||{}; entry.span[year] = entry.span[year]||{}; entry.span[year][month] = entry.span[year][month]||{}; // Cycle through days // Determine span var firstMonth = (year === entry.start.getFullYear() && month === entry.start.getMonth()+1), lastMonth = (year === entry.finish.getFullYear() && month === entry.finish.getMonth()+1), daysInMonth = this.getDaysInMonth(currentDate); // Ifs if ( firstMonth && lastMonth ) { // First + Last // Get days between (inclusive) var startDay = entry.start.getDate(), finishDay = entry.finish.getDate(); else if ( ) { // First // Get days from (inclusive) var startDay = entry.start.getDate(), finishDay = daysInMonth; } else if ( ) { // Last // Get days to (inclusive) var startDay = 1, finishDay = entry.finish.getDate(); } else { // Intermediate // Get all days var startDay = 1, finishDay = daysInMonth; } // Apply for ( var day = startDay; day<=finishDay; ++day ) { entry.span[year][month][day] = true; } */ // Add to Year-Month Indexed if ( typeof this.entriesByYearMonth[year+'-'+month] === 'undefined' ) { this.entriesByYearMonth[year+'-'+month] = {}; } this.entriesByYearMonth[year+'-'+month][entry.id] = entry; // Increment date by one month if ( month === 11 ) { currentDate.setMonth(0); currentDate.setYear(year+1); } else { currentDate.setMonth(month+1); } } // Add to ID Indexed this.entriesById[entry.id] = entry; // Return entry return entry; } }; // Add the passed entries (if any) Entries.addEntries(config.calendarEntries); // Our Extender Event var calendarEntriesRender = function(datepicker, year, month) { // Fetch the Entries var monthEntries = Entries.getEntriesByYearMonth(year,month), $datepicker = $(datepicker); // Reset the Render var $days_tds = $datepicker.find('tbody td'), $days = $days_tds.find('a'); // Disable Click if ( config.disableClick ) { $days_tds.unbind('click').removeAttr('onclick'); $days.removeAttr('href').css('cursor','default'); } // Cycle Through Entries $.each(monthEntries, function(entryIndex,entry){ // Fetch stat and finish days var startMonth = entry.start.getMonth()+1, finishMonth = entry.finish.getMonth()+1, startDay = entry.start.getDate(), finishDay = entry.finish.getDate(); // Determine start and finish days in the rendered calendar var $startDay = startMonth == month ? $days.filter(':contains('+startDay+'):first') : $days.filter(':first'), $finishDay = finishMonth == month ? $days.filter(':contains('+finishDay+'):first') : $days.filter(':last'); // Determine the indexes var start = startMonth == month ? $days.index($startDay) : 0, finish = finishMonth == month ? $days.index($finishDay) : $days.length-1, duration = finish-start+1; // +1 to be inclusive // Betweens var $entryDays = []; if ( start == finish ) { $entryDays = $startDay; } else if ( start == finish-1 ) { $entryDays = $startDay.add($finishDay); } else { $entryDays = $startDay.add($days.filter(':lt('+(finish)+')').filter(':gt('+(start)+')')).add($finishDay); } // Add the Entry to These Days $entryDays.addClass(config.dayEventClass).each(function(dayIndex,dayElement){ // Fetch var $day = $(dayElement), day = $day.text().trim(), dayEntriesIds = $day.data('dayEntriesIds'); // Handle if ( typeof dayEntriesIds === 'undefined' ) { dayEntriesIds = entry.id; } else { dayEntriesIds = String(dayEntriesIds).split(/,/g); dayEntriesIds.push(entry.id); dayEntriesIds = dayEntriesIds.join(','); } // Apply $day.data('dayEntriesIds',dayEntriesIds); // Bind Entries $.each(config.domEvents,function(domEventName,domEventHandler){ $day.unbind(domEventName).bind(domEventName,function(domEvent){ // Prepare var $day = $(this), day = $day.text().trim(), dayEntriesIds = String($day.data('dayEntriesIds')).split(/,/g), date = new Date(); date.setDatestr(year+'-'+month+'-'+day); // Entries var dayEntries = [] $.each(dayEntriesIds,function(i,entryId){ var dayEntry = Entries.getEntryById(entryId); dayEntries.push(dayEntry); }); // Fire domEventHandler.apply(this, [domEvent, { "year":year, "month":month, "day":day, "date":date, "dayEntries":dayEntries, "monthEntries":monthEntries, "datepicker":datepicker }]); // Done return true; }); }); // Done }); }); // Done return true; }; // Change Month Year var calendarChangeMonthYear = function(year, month, inst) { // Prepare var datepicker = inst.dpDiv||inst; // Check if ( typeof config.ajaxEntriesUrl === 'string' && config.ajaxEntriesUrl.length ) { // Ajax Enabled if ( config.ajaxCache && Entries.isCacheable(year,month) && !Entries.isYearMonthEmpty(year,month) ) { // We can use the cache // And we have entries setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); } else { // Prepare var data = $.extend({},{ year: year, month: month }, config.ajaxPostData ); // Fetch into the cache $.ajax({ "url": config.ajaxEntriesUrl, "method": 'post', "dataType": 'json', "data": data, success: function(data, status){ // Cycle var entries = data[config.ajaxEntriesVariable]||[]; // Enable caching for this year month Entries.setCacheable(year,month,true) // Check if we have entries if ( entries.length === 0 ) { return true; } // Store the Entries in the Calendar Data Entries.addEntries(entries); // Render the year and month, as we have new data setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); // Done return true; }, error: function(XMLHttpRequest, textStatus, errorThrown, response_data){ // Error window.console.warn('$.EventCalendar.calendarChangeMonthYear.ajax.error:', [this, arguments]); } }); } } else if ( !Entries.isYearMonthEmpty(year,month) ) { // We are not using cache // And we have entries setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); } // Done return true; }; // Prepare initial render var calendarInitialised = false; var calendarInit = function(year,month,inst){ // Prepare if ( calendarInitialised ) return; calendarInitialised = true; // Apply $(inst).addClass(config.calendarClass); calendarChangeMonthYear(year, month, inst); }; // Calendar Options var datepickerOptions = $.extend({}, config.datepickerOptions, { onChangeMonthYear: function(year, month, inst) { // Our Event calendarChangeMonthYear(year,month,inst); // Users' Event if ( typeof config.datepickerOptions.onChangeMonthYear === 'function' ) { calendarInit(year,month,inst); } }, beforeShow: function(input, inst) { datepickerShowed = true; // Users' Event if ( typeof config.datepickerOptions.beforeShow === 'function' ) { config.datepickerOptions.beforeShow.apply(this,[input,inst]); } // Our Event setTimeout(function(){ calendarInit(inst.drawYear, inst.drawMonth+1, inst); },1000); } }); // Apply Options so we can hook into the events $calendar.datepicker(datepickerOptions); // Fallback in case beforeShow fails us setTimeout(function(){ var date = $calendar.datepicker("getDate"); calendarInit(date.getFullYear(), date.getMonth()+1, $calendar); },2000); // Chain return $calendar; }, built: function(){ // Prepare var Me = this; // Attach $.fn.EventCalendar = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.EventCalendar has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.help * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Help * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Help||false) ) { $.Help = $.BalClass.create({ // Configuration config: { 'default': { // Elements wrap: '<span class="sparkle-help-wrap"/>', icon: '<span class="sparkle-help-icon"/>', text: '<span class="sparkle-help-text"/>', parentClass: '', title: '' } }, // Functions fn: function(options){ var Me = $.Help; if ( typeof options === 'string' ) { options = { title: options }; } var config = Me.getConfigWithDefault('default',options); // Fetch var $this = $(this); var $wrap = $(config.wrap); var $icon = $(config.icon); var $text = $(config.text); var $parent = $this.parent().addClass(config.parentClass); // Build var $contents = $this.contents(); $this.append($wrap.append($text).append($icon)); $contents.appendTo($text); $this.attr('title', config.title); // Done return $this; }, built: function(){ // Prepare var Me = this; // Attach $.fn.help = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Help has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.timepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Time Picker * @version 1.3.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Timepicker||false) ) { /** * $.timepicker */ $.Timepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false, timeConvention: 12 }, '12hr': { timeConvention: 12 }, '24hr': { timeConvention: 24 } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Timepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-time-has') ) { // Already done return this; } $input.addClass('sparkle-time').addClass('sparkle-time-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.date && $input.attemptTypeChangeTo('time') ) { // Chain return this; } // -------------------------- // Defaults var value = $input.val(), date = new Date(), timeConvention = config.timeConvention, hours = 12, minutes = 0, meridian = 'am'; // Assign if ( value ) { date.setTimestr(value); hours = date.getUTCHours(); minutes = date.getUTCMinutes(); } // Adjust if ( timeConvention === 12 && hours > 12 ) { meridian = 'pm'; hours -= 12; } minutes = minutes.roundTo(5); // Check if ( timeConvention === 12 ) { if ( hours > 12 || hours < 1 ) { hours = 1; window.console.warn('timepicker.fn: Invalid Hours.', [this,arguments]); } } else { if ( hours > 23 || hours < 0 ) { hours = 1; window.console.warn('timepicker.fn: Invalid Hours.', [this,arguments]); } } if ( minutes > 60 || minutes < 0 ) { minutes = 0; window.console.warn('timepicker.fn: Invalid Minutes.', [this,arguments]); } // -------------------------- // DOM Manipulation // Hide $input.hide(); // Meridian if ( timeConvention === 12 ) { var $meridian = $('<select class="sparkle-time-meridian" />'); $meridian.append('<option>am</option>'); $meridian.append('<option>pm</option>'); $meridian.val(meridian).insertAfter($input); } // Minutes var $minutes = $('<select class="sparkle-time-minutes" />'); for ( var mins=55,min=0; min<=mins; min+=5) { $minutes.append('<option value="'+min+'">'+min.padLeft('0',2)+'</option>'); } $minutes.val(minutes).insertAfter($input); // Hours var $hours = $('<select class="sparkle-time-hours" />'); if ( timeConvention === 12 ) { for ( var hours=timeConvention,hour=1; hour<=hours; ++hour ) { $hours.append('<option value="'+hour+'">'+hour.padLeft('0',2)+'</option>'); } $hours.val(hours-1).insertAfter($input); } else { for ( var hours=timeConvention,hour=0; hour<hours; ++hour ) { $hours.append('<option value="'+hour+'">'+hour.padLeft('0',2)+'</option>'); } $hours.val(hours).insertAfter($input); } // -------------------------- // Bind var updateFunction = function(){ var hours = parseInt($hours.val(),10); var minutes = $minutes.val(); if ( timeConvention === 12 ) { var meridian = $meridian.val(); // PM Adjustment if ( hours !== 12 && meridian === 'pm' ) { hours += 12; } // AM Adjustment if ( hours === 12 && meridian === 'am' ) { hours = 0; } } // Apply var value = hours.padLeft(0,2)+':'+minutes.padLeft(0,2)+':00'; $input.val(value).trigger('change'); }; $hours.add($minutes).add($meridian).change(updateFunction); $input.parent('form:first').submit(updateFunction); // Done return $input; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.timepicker = $.fn.Timepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Timepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass, tinymce * @name jquery.balclass.tinymce * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery TinyMCE Extender * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Tinymce||false) ) { $.Tinymce = $.BalClass.create({ // Configuration config: { 'default': { // Location of TinyMCE script script_url: '/scripts/tiny_mce/tiny_mce.js', // General options theme: "advanced", plugins: "autoresize,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", // Theme options theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|,code,", theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,undo,redo,|,link,unlink,image,|,preview,|,forecolor,backcolor,|,bullist,numlist,|,outdent,indent,blockquote,|,fullscreen", theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_path: false, theme_advanced_resizing: false, width: "100%", // Compat //add_form_submit_trigger: false, //submit_patch: false, // Example content CSS (should be your site CSS) // content_css : "css/content.css", // Replace values for the template plugin template_replace_values: { } }, 'rich': { }, 'simple': { theme_advanced_buttons2: "", theme_advanced_buttons3: "" } }, // Functions fn: function(mode,options) { var Me = $.Tinymce; var config = Me.getConfigWithDefault(mode,options); var $this = $(this); // Apply + Return return $this.tinymce(config); }, built: function(){ // Prepare var Me = this; // Attach $.fn.Tinymce = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Tinymce has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.extra, jquery.balclass * @name jquery.balclass.bespin.sparkle * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Prepare Body */ $(document.body).addClass('js'); /** * jQuery Sparkle - jQuery's DRY Effect Library * @version 1.5.0 * @date August 28, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Sparkle||false) ) { /** * $.SparkleClass */ $.SparkleClass = $.BalClass.clone({ /** * Alias for Sparkle.addExtension */ addExtensions: function() { // Prepare var Sparkle = this; // Handle var result = Sparkle.addExtension.apply(Sparkle,arguments); // Fire the Configured Promise Sparkle.onConfigured(true); // Return result return result; }, /** * Add an Extension */ addExtension: function() { // Prepare var Sparkle = this, Extension = {}; // Determine switch ( true ) { case Boolean(arguments[2]||false): // name, config, extension // name, extension, config if ( typeof arguments[0] === 'string' && typeof arguments[2] === 'function' && typeof arguments[1] === 'object' ) { Extension.extension = arguments[2]; Extension.config = arguments[1]; Extension.name = arguments[0]; } if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' && typeof arguments[2] === 'object' ) { Extension.extension = arguments[1]; Extension.config = arguments[2]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[1]||false): // name, Extension // name, extension if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' ) { Extension.extension = arguments[1]; Extension.name = arguments[0]; } else if ( typeof arguments[0] === 'string' && Sparkle.isExtension(arguments[1]) ){ Extension = arguments[1]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[0]||false): // Extension // Series if ( Sparkle.isExtension(arguments[0]) ) { Extension = arguments[0]; } else if ( typeof arguments[0] === 'object' || typeof arguments[0] === 'array' ) { // Series $.each(arguments[0],function(key,value){ Sparkle.addExtension(key,value); }); // Chain return this; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; } // Ensure Extension.config = Extension.config||{}; Extension.extension = Extension.extension||{}; // Add Extension Sparkle.addConfig(Extension.name, Extension); // Bind Ready Handler Sparkle.onReady(function(){ // Fire Extension Sparkle.triggerExtension($('body'),Extension); }); // Chain return this; }, /** * Do we have that Extension */ hasExtension: function (extension) { // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension); // Return return Extension !== 'undefined'; }, /** * Is the passed Extension an Extension */ isExtension: function (extension) { // Return return Boolean(extension && (extension.extension||false)); }, /** * Get the Extensions */ getExtensions: function ( ) { // Prepare var Sparkle = this, Config = Sparkle.getConfig(), Extensions = {}; // Handle $.each(Config,function(key,value){ if ( Sparkle.isExtension(value) ) { Extensions[key] = value; } }); // Return Extensions return Extensions; }, /** * Get an Extension */ getExtension: function(extension) { // Prepare var Sparkle = this, Extension = undefined; // HAndle if ( Sparkle.isExtension(extension) ) { Extension = extension; } else { var fetched = Sparkle.getConfigWithDefault(extension); if ( Sparkle.isExtension(fetched) ) { Extension = fetched; } } // Return Extension return Extension; }, /** * Get Config from an Extension */ getExtensionConfig: function(extension) { // Prepare var Sparkle = this Extension = Sparkle.getExtension(extension); // Return return Extension.config||{}; }, /** * Apply Config to an Extension */ applyExtensionConfig: function(extension, config) { // Prepare var Sparkle = this; // Handle Sparkle.applyConfig(extension, {'config':config}); // Chain return this; }, /** * Trigger all the Extensions */ triggerExtensions: function(element){ // Prepare var Sparkle = this, Extensions = Sparkle.getExtensions(); // Handle $.each(Extensions,function(extension,Extension){ Sparkle.triggerExtension(element,Extension); }); // Chain return this; }, /** * Trigger Extension */ triggerExtension: function(element,extension){ // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension), element = element instanceof jQuery ? element : $('body'); // Handle if ( Extension ) { return Extension.extension.apply(element, [Sparkle, Extension.config, Extension]); } else { window.console.error('Sparkle.triggerExtension: Could not find the extension.', [this,arguments], [extension,Extension]); } // Chain return this; }, /** * Sparkle jQuery Function */ fn: function(Sparkle,extension){ // Prepare var $el = $(this); // HAndle if ( extension ) { // Individual Sparkle.triggerExtension.apply(Sparkle, [$el,extension]); } else { // Series Sparkle.triggerExtensions.apply(Sparkle, [$el]); } // Chain return this; }, /** * Sparkle Constructor */ built: function(){ // Prepare var Sparkle = this; // -------------------------- // Attach $.fn.sparkle = function(extension) { // Alias return Sparkle.fn.apply(this,[Sparkle,extension]); }; // -------------------------- // Setup Promises // Bind DomReady Handler $(function(){ // Fire DocumentReady Promise Sparkle.onDocumentReady(true); }); // Bind Configured Handler Sparkle.onConfigured(function(){ // Bind DocumentReady Handler Sparkle.onDocumentReady(function(){ // Fire Ready Promise Sparkle.onReady(true); }); }); // -------------------------- // Return true return true; }, /** * Handle the Configured Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onConfigured: function(){ var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onConfiguredHandlers', 'flag': 'isConfigured', 'arguments': arguments }); }, /** * Handle the DocumentReady Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onDocumentReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onDocumentReadyHandlers', 'flag': 'isDocumentReady', 'arguments': arguments }); }, /** * Handle the Ready Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onReadyHandlers', 'flag': 'isReady', 'arguments': arguments }); } }); /** * $.Sparkle */ $.Sparkle = $.SparkleClass.create().addExtensions({ 'date': { config: { selector: '.sparkle-date', datepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.', demo: '<input type="text" class="sparkle-date" value="2010-08-05" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datepicker === 'undefined' ) { window.console.warn('Datepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datepicker(config.datepickerOptions); // Done return true; } }, 'time': { config: { selector: '.sparkle-time', timepickerOptions: { }, demoText: 'Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-time" value="23:11" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Timepicker === 'undefined' ) { window.console.warn('Timepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Timepicker(config.timepickerOptions); // Done return true; } }, 'datetime': { config: { selector: '.sparkle-datetime', datepickerOptions: { }, timepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.<br/>\ Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-datetime" value="2010-08-05 23:10:09" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datetimepicker === 'undefined' ) { window.console.warn('Datetimepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datetimepicker({ datepickerOptions: Sparkle.getExtensionConfig('date').datepickerOptions, timepickerOptions: Sparkle.getExtensionConfig('time').timepickerOptions }); // Done return true; } }, 'hide-if-empty': { config: { selector: '.sparkle-hide-if-empty:empty', demo: '<div class="sparkle-hide-if-empty" style="border:1px solid black"></div>'+"\n"+ '<div class="sparkle-hide-if-empty" style="border:1px solid black">Hello World</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.hide(); // Done return true; } }, 'hide': { config: { selector: '.sparkle-hide', demo: '<div class="sparkle-hide">Something to Hide when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).hide(); // Done return true; } }, 'show': { config: { selector: '.sparkle-show', demo: '<div class="sparkle-show" style="display:none;">Something to Show when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).show(); // Done return true; } }, 'subtle': { config: { selector: '.sparkle-subtle', css: { }, inSpeed: 200, inCss: { 'opacity': 1 }, outSpeed: 400, outCss: { 'opacity': 0.5 }, demo: '<div class="sparkle-subtle">This is some subtle text. (mouseover)</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply var css = {}; $.extend(css, config.outCss, config.css); $elements.css(css).opacityFix().hover(function() { // Over $(this).stop(true, false).animate(config.inCss, config.inSpeed); }, function() { // Out $(this).stop(true, false).animate(config.outCss, config.outSpeed); }); // Done return true; } }, 'panelshower': { config: { selectorSwitch: '.sparkle-panelshower-switch', selectorPanel: '.sparkle-panelshower-panel', inSpeed: 200, outSpeed: 200, demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $switches = $this.findAndSelf(config.selectorSwitch); var $panels = $this.findAndSelf(config.selectorPanel); if ( !$switches.length && !$panels.length ) { return true; } // Events var events = { clickEvent: function(event) { var $switch = $(this); var $panel = $switch.siblings(config.selectorPanel).filter(':first'); var value = $switch.val(); var show = $switch.is(':checked,:selected') && !(!value || value === 0 || value === '0' || value === 'false' || value === false || value === 'no' || value === 'off'); if (show) { $panel.fadeIn(config.inSpeed); } else { $panel.fadeOut(config.outSpeed); } } }; // Apply $switches.once('click',events.clickEvent); $panels.hide(); // Done return true; } }, 'autogrow': { config: { selector: 'textarea.autogrow,textarea.autosize', demo: '<textarea class="autogrow">This textarea will autogrow with your input. - Only if jQuery Autogrow has been loaded.</textarea>' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if (typeof $.fn.autogrow === 'undefined') { window.console.warn('autogrow not loaded. Did you forget to include it?'); return false; } // Apply $elements.autogrow(); // Done return true; } }, 'gsfnwidget': { config: { selector: '.gsfnwidget', demo: '<a class="gsfnwidget" href="#">This link will show a GetSatisfaction Widget onclick. - Only if GetSatisfaction has been loaded.</a>' }, extension: function(Sparkle, config) { var $this = $(this); // Events var events = { clickEvent: function(event) { if ( typeof GSFN_feedback_widget === 'undefined' ) { window.console.warn('GSFN not loaded. Did you forget to include it?'); return true; // continue with click event } GSFN_feedback_widget.show(); //event.stopPropagation(); event.preventDefault(); return false; } }; // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.once('click',events.clickEvent); // Done return true; } }, 'hint': { config: { selector: '.form-input-tip,.sparkle-hint,.sparkle-hint-has,:text[placeholder]', hasClass: 'sparkle-hint-has', hintedClass: 'sparkle-hint-hinted', demoText: 'Simulates HTML5\'s <code>placeholder</code> attribute for non HTML5 browsers. Placeholder can be the <code>title</code> or <code>placeholder</code> attribute. Placeholder will not be sent with the form (unlike most other solutions). The <code>sparkle-hint</code> class is optional if you are using the <code>placeholder</code> attribute.', demo: '<input type="text" class="sparkle-hint" placeholder="This is some hint text." title="This is a title." /><br/>'+"\n"+ '<input type="text" class="sparkle-hint" title="This is some hint text." />' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $inputs = $this.findAndSelf(config.selector).addClass(config.hasClass); if ( !$inputs.length ) { return true; } // Events var events = { focusEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val) { $input.val('').removeClass(config.hintedClass); } // Done return true; }, blurEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val || !val) { $input.val('').addClass(config.hintedClass).val(tip); } // Done return true; }, submitEvent: function(){ $inputs.trigger('focus'); } }; // Apply if ( typeof Modernizr !== 'undefined' && Modernizr.input.placeholder ) { // We Support HTML5 Hinting $inputs.each(function(){ var $input = $(this); // Set the placeholder as the title if the placeholder does not exist // We could use a filter selector, however we believe this should be faster - not benchmarked though var title = $input.attr('title'); if ( title && !$input.attr('placeholder') ) { $input.attr('placeholder',title); } }); } else { // We Support Javascript Hinting $inputs.each(function(){ var $input = $(this); $input.once('focus',events.focusEvent).once('blur',events.blurEvent).trigger('blur'); }); $this.find('form').once('submit',events.submitEvent); } // Done return $this; } }, 'debug': { config: { selector: '.sparkle-debug', hasClass: 'sparkle-debug-has', hintedClass: 'sparkle-debug-hinted', showVar: 'sparkle-debug-show', demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $debug = $this.findAndSelf(config.selector); if ( !$debug.length ) { return true; } // Apply $debug.addClass(config.hasClass).find('.value:has(.var)').hide().siblings('.name,.type').addClass('link').once('singleclick',events.clickEvent).once('dblclick',events.dblclickEvent); // Events var events = { clickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = !$parent.data(config.showVar); $parent.data(config.showVar, show); $this.siblings('.value').toggle(show); }, dblclickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = $parent.data(config.showVar); // first click will set this off $parent.data(config.showVar, show); $parent.find('.value').toggle(show); } }; // Done return $this; } }, 'submit': { config: { selector: '.sparkle-submit', demoText: 'Adding the <code>sparkle-submit</code> class to an element within a <code>form</code> will submit the form when that element is clicked.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ var $this = $(this).submitForm(); return true; } }; // Apply $submit.once('singleclick',events.clickEvent); // Done return $this; } }, 'submitswap': { config: { selector: '.sparkle-submitswap', demoText: 'Adding the <code>sparkle-submitswap</code> class to a submit button, will swap it\'s value with it\'s title when it has been clicked. Making it possible for a submit value which isn\'t the submit button\'s text.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ // Fetch var $submit = $(this); // Put correct value back $submit.val($submit.data('sparkle-submitswap-value')); // Continue with Form Submission return true; } }; // Apply $submit.once('singleclick',events.clickEvent); $submit.each(function(){ var $submit = $(this); $submit.data('sparkle-submitswap-value', $submit.val()); $submit.val($submit.attr('title')); $submit.removeAttr('title'); }); // Done return $this; } }, 'highlight-values': { config: { selector: '.sparkle-highlight-values', innerSelector: 'td,.column', empty: ['',false,null,'false','null',0,'-'], emptyClass: 'sparkle-highlight-values-empty', notemptyClass: 'sparkle-highlight-values-notempty', demoText: 'Adding the <code>sparkle-highlight-values</code> class to a table will highlight all <code>td</code> elements with non empty values. By adding <code>sparkle-highlight-values-notempty</code> or <code>sparkle-highlight-values-empty</code> to the corresponding <code>td</code> element - which can by styled by yourself. Benefit over css\'s <code>:empty</code> as 0, false, null and - are counted as empty values (not just "").' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $container = $this.findAndSelf(config.selector); if ( !$container.length ) { return true; } // Apply var $inner = $container.findAndSelf(config.innerSelector); $inner.each(function(){ var $this = $(this); var value = $this.text().trim(); var empty = config.empty.has(value); if ( empty ) { $this.addClass(config.emptyClass); } else { $this.addClass(config.notemptyClass); } }); // Done return $this; } }, 'demo': { config: { selector: '.sparkle-demo', hasClass: 'sparkle-debug-has', demoText: 'Adding the <code>sparkle-demo</code> will display all these demo examples used on this page.' }, extension: function(Sparkle, config){ var $this = $(this); var $container = $this.findAndSelf(config.selector); // Prepare if ( $container.hasClass(config.hasClass) || !$container.length ) { // Only run once return true; } $container.addClass(config.hasClass); // Fetch var Extensions = Sparkle.getExtensions(); // Cycle $.each(Extensions,function(extension,Extension){ var demo = Extension.config.demo||''; var demoText = Extension.config.demoText||''; if ( !demo && !demoText ) { return true; // continue } var $demo = $( '<div class="sparkle-demo-section" id="sparkle-demo-'+extension+'">\ <h3>'+extension+'</h3>\ </div>' ); if ( demoText ) { $demo.append('<div class="sparkle-demo-text">'+demoText+'</div>'); } if ( demo ) { var demoCode = demo.replace(/</g,'&lt;').replace(/>/g,'&gt;'); $demo.append( '<h4>Example Code:</h4>\ <pre class="code language-html sparkle-demo-code">'+demoCode+'</pre>\ <h4>Example Result:</h4>\ <div class="sparkle-demo-result">'+demo+'</div>' ); } $demo.appendTo($container); }); // Sparkle $container.sparkle(); // Done return $this; } } }); } else { window.console.warn('$.Sparkle has already been defined...'); } })(jQuery);
balupton/jquery-sparkle
scripts/jquery.sparkle.js
JavaScript
mit
134,797
/* globals document, ajaxurl, tinymce, window */ define([ 'jquery', 'modal', 'jquery-ui.sortable' ], function ($, modal) { return function(areas, callback) { var $areas = $(areas).filter(':not(.initialized)'); $areas.addClass('initialized'); var updateData = function() { if(typeof tinymce !== 'undefined' && tinymce.get('content')) { //use WordPress native beforeunload warning if content is modified tinymce.get('content').isNotDirty = false; } var data = {}; $areas.each(function () { var col = []; $(this).find('> ul, > div > ul').find('> li[data-widget]:not(.removed)').each(function () { col.push({ "widgetId": $(this).data('widget'), "instance": $(this).data('instance') }); }); data[$(this).data('id')] = col; }); callback(data); }; $areas.find('> ul, > div > ul').sortable({ connectWith: $areas.find('> ul, > div > ul'), placeholder: "neochic-woodlets-placeholder", delay: 250, update: updateData, receive: function (e, ui) { var $area = $(this).closest('.woodlets-content-area'); var widgetId = ui.item.data('widget'); var allowed = $area.data('allowed'); if ($.inArray(widgetId, allowed) < 0) { ui.sender.sortable("cancel"); } } }); $areas.on('click', '.add-element', function (e) { var $button = $(this); if ($button.hasClass('blocked')) { return; } $button.addClass('blocked'); e.preventDefault(); var $area = $(this).closest('.woodlets-content-area'); $.ajax({ method: "post", url: ajaxurl, data: { action: "neochic_woodlets_get_widget_list", allowed: $area.data('allowed') } }).done(function (data) { var $content = $(data); var selectWidget = function($widget, preventClose) { var widget = $widget.closest('.widget').data('widget'); $button.removeClass('blocked'); $.ajax({ method: "post", url: ajaxurl, data: { "action": "neochic_woodlets_get_widget_preview", "widget": widget, "instance": null } }).done(function (result) { var item = $(result); $area.find('> ul, > div > ul').append(item); updateData(); if (!preventClose) { modal.close(); } item.trigger('click'); }); }; var $widgets = $content.find('.widget-top'); if ($widgets.length === 1) { selectWidget($widgets, true); return; } $content.on('click', '.widget-top', function () { selectWidget($(this)); }); $content.on('click', '.cancel', function() { modal.close(); }); modal.open($content, 'Add item'); }); }); $areas.on('click', '.delete', function () { var removed = $(this).closest('.neochic-woodlets-widget'); removed.addClass('removed'); updateData(); }); $areas.on('click', '.revert-removal a', function() { var reverted = $(this).closest('.neochic-woodlets-widget'); //we wan't the click event to bubble first window.setTimeout(function() { reverted.removeClass('removed'); updateData(); }, 4); }); $areas.on('click', '> ul > li.neochic-woodlets-widget, > div > ul > li.neochic-woodlets-widget', function (e) { var el = $(this); if (el.hasClass('blocked') || el.hasClass('removed')) { return; } el.addClass('blocked'); /* * stop propagation to prevent widget getting collapsed by WordPress */ e.stopPropagation(); /* * do not open widget form if an action (like "delete") is clicked */ if (!$(e.target).is('.edit') && $(e.target).closest('.row-actions').length > 0) { return; } var widget = $(this).data('widget'); //this should be done more elegant! var name = $(this).find(".widget-title h4").text(); var data = { action: "neochic_woodlets_get_widget_form", widget: widget, instance: JSON.stringify(el.data('instance')) }; var pageIdEle = $("#post_ID"); if (pageIdEle.length) { data.woodletsPageId = pageIdEle.val(); } $.ajax({ method: "post", url: ajaxurl, data: data }).done(function (data) { var form = $('<form>' + data + '<span class="button cancel">Cancel</span> <button type="submit" class="button button-primary">Save</button></form>'); form.on('submit', function (e) { $(document).trigger('neochic-woodlets-form-end', form); $.ajax({ method: "post", url: ajaxurl, data: $(this).serialize() + '&widget=' + widget + '&action=neochic_woodlets_get_widget_update' + (pageIdEle.length ? '&woodletsPageId=' + pageIdEle.val() : "") }).done(function (result) { var instance = $.parseJSON(result); el.data('instance', instance); var previewData = { "action": "neochic_woodlets_get_widget_preview", "widget": widget, "instance": JSON.stringify(instance) }; if (pageIdEle.length) { previewData.woodletsPageId = pageIdEle.val(); } $.ajax({ method: "post", url: ajaxurl, data: previewData }).done(function (result) { el.replaceWith($(result)); }); modal.close(); updateData(); }); e.preventDefault(); }); form.on('click', '.cancel', function() { modal.close(); }); modal.open(form, name); $(document).trigger('neochic-woodlets-form-init', form); el.removeClass('blocked'); }); }); }; });
Neochic/Woodlets
js/content-area-manager.js
JavaScript
mit
7,553
Factory.define :content_element_text do |p| p.content_element { |c| c.association(:content_element, :element_type => "ContentElementText") } end
dkd/palani
spec/factories/content_element_text_factory.rb
Ruby
mit
146
--- title: "Information for Students" layout: single permalink: "/for-students/" author_profile: true --- ## Office Hours My office is 410 Briggs Hall. My office hours this fall are * Monday 3:10-5:00 p.m. * Tuesday 1:50-3:20 p.m. * Thursday 1:50-3:20 p.m. * Friday 3:10 - 4:20 p.m. ## Lawrence's Academic Calendar and Exam Schedule I find myself looking for Lawrence's academic calendar and exam schedule every now and then. * [Academic calendar](https://www.lawrence.edu/s/registrar/calendar) * [Exam schedule](https://www.lawrence.edu/s/registrar/final_exams) ## Letters of recommendation Letters of recommendation are key elements of a job or graduate school application, and I take these letters seriously. To this end, I like to meet with every student that I write a letter for to discuss the jobs or graduate programs they are applying to and how they fit with their goals. If you're wondering whether I would write a letter of recommendation, just ask! If I have agreed to write a letter of recommendation for you, then the following information will help me write the strongest letter possible: * an unofficial copy of your transcript, * a copy of your personal statement, and * any necessary forms. Additionally, please ask at least two weeks before the first letter is due. Finally, please send me email reminders as the deadlines approach.
aloy/aloy.github.io
_pages/for-students.md
Markdown
mit
1,367
$(document).ready(function() { var $sandbox = $('#sandbox'); module('typographer_punctuation', { teardown: function() { teardownSandbox($sandbox); } }); var bdquo = '\u201E'; // &bdquo; var rdquo = '\u201D'; // &rdquo; var laquo = '\u00AB'; // &laquo; var raquo = '\u00BB'; // &raquo; var nbsp = '\u00A0'; // &nbsp; var ellip = '\u2026'; // &hellip; var apos = '\u2019'; // &rsquo; var ndash = '\u2013'; // '&ndash; półpauza var mdash = '\u2014'; // '&ndash; pauza test('Initialization', function() { $sandbox.typographer_punctuation(); ok($.fn.typographer_punctuation.defaults, '$.fn.typographer_punctuation.defaults present'); ok($sandbox.hasClass($.fn.typographer_punctuation.defaults.contextClass), 'Context has valid class'); }); test('Quotes correction', function() { var testSpec = [ { init: 'Lorem "ipsum" dolor sit amet.', expected: 'Lorem \u201Eipsum\u201D dolor sit amet.' }, { init: 'Oto "źdźbło" trawy.', expected: 'Oto \u201Eźdźbło\u201D trawy.' }, { init: 'kolegom, że "...moja to trzyma buty".', expected: 'kolegom, że \u201E...moja to trzyma buty\u201D.' }, { init: 'Taką "długą grę" lubię.', expected: 'Taką \u201Edługą grę\u201D lubię.' }, { init: '"jakimi butami jesteś", mój wynik ', expected: '\u201Ejakimi butami jesteś\u201D, mój wynik ' }, { init: 'Lorem "ipsum »dolor« sit" amet.', expected: 'Lorem \u201Eipsum \u00ABdolor\u00BB sit\u201D amet.' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['quotes']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Ellipsis correction', function() { var testSpec = [ { init: 'Dawno, dawno temu...', expected: 'Dawno, dawno temu' + ellip }, { init: 'Wprost do... domu.', expected: 'Wprost do' + ellip + ' domu.' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['ellipsis']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Apostrophe correction', function() { var testSpec = [ { init: 'Alfabet Morse\'a', expected: 'Alfabet Morse' + apos + 'a' }, { init: 'prawo Murphy\'ego', expected: 'prawo Murphy' + apos + 'ego' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['apostrophe']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Dash correction', function() { var testSpec = [ { init: 'A to jest - rzecz oczywista - najlepsze wyjście.', expected: 'A to jest ' + ndash + ' rzecz oczywista ' + ndash + ' najlepsze wyjście.' }, { init: 'Wiedza - to potęga.', expected: 'Wiedza ' + ndash + ' to potęga.' }, { init: 'Działalność PAN-u', expected: 'Działalność PAN-u' }, { init: 'Działalność PAN' + ndash + 'u', expected: 'Działalność PAN-u' }, { init: 'Elżbieta Nowak-Kowalska', expected: 'Elżbieta Nowak-Kowalska' }, { init: 'W latach 1999-2001', expected: 'W latach 1999' + ndash + '2001' }, { init: 'W latach 1999 - 2001', expected: 'W latach 1999' + ndash + '2001' }, { init: 'W latach 1999 ' + ndash + ' 2001', expected: 'W latach 1999' + ndash + '2001' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'dash': ['dash']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); });
mir3z/jquery.typographer
test/jquery.typographer.punctuation.test.js
JavaScript
mit
4,996
A non-empty array `A` consisting of `N` integers is given. The leader of this array is the value that occurs in more than half of the elements of `A`. An equi leader is an index `S` such that `0 ≤ S < N − 1` and two sequences `A[0], A[1], ..., A[S]` and `A[S + 1], A[S + 2], ..., A[N − 1]` have leaders of the same value. For example, given array A such that: ``` A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 ``` we can find two equi leaders: - `0`, because sequences: `(4)` and `(3, 4, 4, 4, 2)` have the same leader, whose value is `4`. - `2`, because sequences: `(4, 3, 4)` and `(4, 4, 2)` have the same leader, whose value is `4`. The goal is to count the number of equi leaders. Write a function: ```c int solution(int A[], int N); ``` that, given a non-empty array `A` consisting of `N` integers, returns the number of equi leaders. For example, given: ``` A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 ``` the function should return `2`, as explained above. Write an efficient algorithm for the following assumptions: - `N` is an integer within the range `[1..100,000]`; - each element of array `A` is an integer within the range `[−1,000,000,000..1,000,000,000]`. [Link to Codility](https://app.codility.com/programmers/lessons/8-leader/equi_leader/)
amaslenn/Codility
Lesson 8 - Leader/EquiLeader.md
Markdown
mit
1,339
# 271. Encode and Decode Strings Difficulty: Medium https://leetcode.com/problems/encode-and-decode-strings/ Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings. Machine 1 (sender) has the function: ``` string encode(vector<string> strs) { // ... your code return encoded_string; } ``` Machine 2 (receiver) has the function: ``` vector<string> decode(string s) { //... your code return strs; } ``` So Machine 1 does: ``` string encoded_string = encode(strs); ``` and Machine 2 does: ``` vector<string> strs2 = decode(encoded_string); ``` strs2 in Machine 2 should be the same as strs in Machine 1. Implement the encode and decode methods. **Note:** * The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters. * Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless. * Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
jiadaizhao/LeetCode
0201-0300/0271-Encode and Decode Strings/README.md
Markdown
mit
1,186
<?php include('head.php'); global $TPL; ?> <div class="page-header"> <h1>Dateiliste</h1> </div> <?php if($_SESSION['login_msg']) { $_SESSION['login_msg']=false; ?> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h4>Erfolgreich eingeloggt.</h4> Willkommen <?php echo $_SESSION['whoami']; ?> </div> <?php } ?> <p>Folgende Dateien wurden gefunden:</p> <?php include('foot.php'); ?> <script type="text/javascript"> var filelist = <?php echo json_encode($TPL['files']) . ';'; ?> </script> <script src="tpl/default/js/filelist.js"></script>
jnugh/php-miniupload
tpl/default/list.php
PHP
mit
603
# Firego A Firebase client written in Go ##### Under Development The API may or may not change radically within the next upcoming weeks. ## Installation ```bash go get -u github.com/zabawaba99/firego ``` ## Usage Import firego ```go import "github.com/zabawaba/firego" ``` Create a new firego reference ```go f := firego.New("https://my-firebase-app.firebaseIO.com") ``` ### Get Value ```go var v map[string]interface{} if err := f.Value(&v); err != nil { log.Fatal(err) } fmt.Printf("%s\n", v) ``` ### Set Value ```go v := map[string]string{"foo":"bar"} if err := f.Set(v); err != nil { log.Fatal(err) } ``` ### Push Value ```go v := "bar" pushedFirego, err := f.Push(v) if err != nil { log.Fatal(err) } var bar string if err := pushedFirego.Value(&bar); err != nil { log.Fatal(err) } // prints "https://my-firebase-app.firebaseIO.com/-JgvLHXszP4xS0AUN-nI: bar" fmt.Printf("%s: %s\n", pushedFirego, bar) ``` ### Update Child ```go v := map[string]string{"foo":"bar"} if err := f.Update(v); err != nil { log.Fatal(err) } ``` ### Remove Value ```go if err := f.Remove(); err != nil { log.Fatal(err) } ``` Check the [GoDocs](http://godoc.org/github.com/zabawaba99/firego) or [Firebase Documentation](https://www.firebase.com/docs/rest/) for more details ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b new-feature`) 3. Commit your changes (`git commit -am 'Some cool reflection'`) 4. Push to the branch (`git push origin new-feature`) 5. Create new Pull Request
apita1973/firego
README.md
Markdown
mit
1,523
module.exports = { general: { lenguage (){ temp['locale'] = event.target.value }, close (){ temp['exit_without_ask'] = event.target.checked }, minimize (){ temp['exit_forced'] = event.target.checked }, hide (){ temp['start_hide'] = event.target.checked }, delete (){ temp['ask_on_delete'] = event.target.checked }, theme (){ temp['theme'] = event.target.value } }, network: { conections (){ temp['conections_max'] = event.target.value }, directory (){ temp['dir_downloads'] = event.target.value }, announces (){ temp['announces'] = event.target.value } }, advance: { table (){ temp_interval['table'] = event.target.value }, tray (){ temp_interval['tray'] = event.target.value }, footer (){ temp_interval['footer'] = event.target.value }, reset() { dialog.showMessageBox({ type: "question", title: locale.dialog.reset.title, message: locale.dialog.reset.ask, defaultId: 0, cancelId: 0, buttons: [locale.cancel, locale.dialog.reset.accept] }, select => { if(select === 0) return false gui.send('reset-settings') $('#modal_configs').modal('hide') }) } }, gui: { open() { temp = [] temp_interval = [] modal = $('#modal_configs') modal.modal('toggle') configs.gui.set(modal); }, save() { for (config in temp) settings[config] = temp[config] for (config in temp_interval) settings.interval[config] = temp_interval[config] ipcRenderer.send('save-settings', settings) }, set(modal) { let checkboxs = ['exit_without_ask', 'start_hide', 'exit_forced', 'ask_on_delete'] for (var i = checkboxs.length - 1; i >= 0; i--) { modal.find('#opt-'+checkboxs[i]).prop("checked", settings[checkboxs[i]]) } let textboxs = ['announces', 'conections_max', 'dir_downloads'] for (var i = textboxs.length - 1; i >= 0; i--) { modal.find('#opt-'+textboxs[i]).val(settings[textboxs[i]]) } let intervals = ["table", "tray", "footer"] for (var i = intervals.length - 1; i >= 0; i--) { modal.find('#opt-interval_'+intervals[i]).val(settings.interval[intervals[i]]) } modal.find('#opt-locale-'+ settings.locale).prop("selected", true) } } }
FaCuZ/torrentmedia
app/js/configs.js
JavaScript
mit
2,228
/* This file has been generated by yabbler.js */ require.define({ "program": function(require, exports, module) { var test = require('test'); var a = require('submodule/a'); var b = require('submodule/b'); test.assert(a.foo == b.foo, 'a and b share foo through a relative require'); test.print('DONE', 'info'); }}, ["test", "submodule/a", "submodule/b"]);
jbrantly/yabble
test/modules1.0/wrappedTests/relative/program.js
JavaScript
mit
356
package org.bitcoins.core.protocol.transaction import org.bitcoins.core.crypto.{ECPrivateKey, EmptyDigitalSignature} import org.bitcoins.testkit.core.gen.WitnessGenerators import org.bitcoins.core.protocol.script._ import org.scalacheck.Prop import org.scalatest.{FlatSpec, MustMatchers} /** * Created by chris on 11/28/16. */ class TransactionWitnessSpec extends FlatSpec with MustMatchers { behavior of "TransactionWitness" it must "have serialization symmetry" in { Prop.forAll(WitnessGenerators.transactionWitness) { witness => TransactionWitness(witness.hex, witness.witnesses.size) == witness } } it must "be able to resize a witness to the given index" in { val empty = EmptyWitness val pubKey = ECPrivateKey.freshPrivateKey.publicKey val p2pkh = P2PKHScriptSignature(EmptyDigitalSignature, pubKey) val scriptWit = P2WPKHWitnessV0.fromP2PKHScriptSig(p2pkh) val updated = empty.updated(2, scriptWit) updated.witnesses.length must be(3) } it must "fail to update a negative index witness" in { intercept[IndexOutOfBoundsException] { EmptyWitness.updated(-1, EmptyScriptWitness) } } }
bitcoin-s/bitcoin-s-core
core-test/src/test/scala/org/bitcoins/core/protocol/transaction/TransactionWitnessSpec.scala
Scala
mit
1,167
(function() { 'use strict'; angular .module('material') .controller('MainController', MainController); /** @ngInject */ function MainController($timeout, webDevTec, toastr) { var vm = this; vm.awesomeThings = []; vm.classAnimation = ''; vm.creationDate = 1437577753474; vm.showToastr = showToastr; activate(); function activate() { getWebDevTec(); $timeout(function() { vm.classAnimation = 'rubberBand'; }, 4000); } function showToastr() { toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>'); vm.classAnimation = ''; } function getWebDevTec() { vm.awesomeThings = webDevTec.getTec(); angular.forEach(vm.awesomeThings, function(awesomeThing) { awesomeThing.rank = Math.random(); }); } } })();
LuukMoret/gulp-angular-examples
es5/material/src/app/main/main.controller.js
JavaScript
mit
906
package io.github.intrainos.samsungltool; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.content.Intent; import android.view.View; import android.widget.Button; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button gotoAppops = (Button) findViewById(R.id.gotoAppops); gotoAppops.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent AppopsIntent = new Intent(); AppopsIntent.setClassName("com.android.settings", "com.android.settings.Settings"); AppopsIntent.setAction("android.intent.action.MAIN"); AppopsIntent.addCategory("android.intent.category.DEFAULT"); AppopsIntent.setFlags(268468224); AppopsIntent.putExtra(":android:show_fragment", "com.android.settings.applications.AppOpsSummary"); startActivity(AppopsIntent); } }); Button TouchLightSetting = (Button) findViewById(R.id.gotoTouchlightSetting); TouchLightSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent TouchLightSetting = new Intent(getApplicationContext(), TouchLight.class); startActivity(TouchLightSetting); } }); Button gotoSViewWPSetting = (Button) findViewById(R.id.gotoSViewWPSetting); gotoSViewWPSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoSViewWPSetting = new Intent(); gotoSViewWPSetting.setClassName("com.android.settings", "com.android.settings.SViewColor2014"); gotoSViewWPSetting.setAction("android.intent.action.MAIN"); gotoSViewWPSetting.addCategory("android.intent.category.DEFAULT"); gotoSViewWPSetting.setFlags(268468224); startActivity(gotoSViewWPSetting); } }); Button gotoToolBoxSetting = (Button) findViewById(R.id.gotoToolBoxSetting); gotoToolBoxSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoToolBoxSetting = new Intent(); gotoToolBoxSetting.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxMenuActivity"); gotoToolBoxSetting.setAction("android.intent.action.MAIN"); gotoToolBoxSetting.addCategory("android.intent.category.DEFAULT"); gotoToolBoxSetting.setFlags(268468224); startActivity(gotoToolBoxSetting); } }); Button gotoToolBoxList = (Button) findViewById(R.id.gotoToolBoxList); gotoToolBoxList.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoToolBoxList = new Intent(); gotoToolBoxList.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxListActivity"); gotoToolBoxList.setAction("android.intent.action.MAIN"); gotoToolBoxList.addCategory("android.intent.category.DEFAULT"); gotoToolBoxList.setFlags(268468224); startActivity(gotoToolBoxList); } }); Button gotoDownloadBoosterSetting = (Button) findViewById(R.id.gotoDownloadBoosterSetting); gotoDownloadBoosterSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoDownloadBoosterSetting = new Intent(); gotoDownloadBoosterSetting.setClassName("com.android.settings", "com.android.settings.Settings$SmartBondingSettingsActivity"); gotoDownloadBoosterSetting.setAction("android.intent.action.MAIN"); gotoDownloadBoosterSetting.addCategory("android.intent.category.DEFAULT"); gotoDownloadBoosterSetting.setFlags(268468224); startActivity(gotoDownloadBoosterSetting); } }); Button goto2014PowerSavingModeSetting = (Button) findViewById(R.id.goto2014PowerSavingModeSetting); goto2014PowerSavingModeSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent goto2014PowerSavingModeSetting = new Intent(); goto2014PowerSavingModeSetting.setClassName("com.android.settings", "com.android.settings.Settings$PowerSavingModeSettings2014Activity"); goto2014PowerSavingModeSetting.setAction("android.intent.action.MAIN"); goto2014PowerSavingModeSetting.addCategory("android.intent.category.DEFAULT"); goto2014PowerSavingModeSetting.setFlags(268468224); startActivity(goto2014PowerSavingModeSetting); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); /* //Not Use //noinspection SimplifiableIfStatement if (id == R.id.action_about) { return true; } return super.onOptionsItemSelected(item); */ return false; } }
Intrainos/SamsungLTool
src/main/java/io/github/intrainos/samsungltool/Main.java
Java
mit
5,768
<li data-post-id="[%= id %]" class="media"> <div class="pull-left"><img width="48px" height="48px" src="http://oz.st-n.ru/publish/users/userpics/48x48/photo.png" class="media-object"/></div> <div class="media-body"> <h4 class="media-heading"> [%= author.company %] &nbsp;<small class="muted">[%= author.firstname %] [%= author.lastname %]</small></h4> <div class="alert alert-send alert-info hide">Пожалуйста подождите, идет загрузка данных...</div> <div class="alert alert-error hide"></div> <div class="post-text">[%= formatting %]</div> <div class="post-edit hide"> <textarea wrap="hard" rows="4" data-post="[%= id %]" class="feed-post-edit span12"></textarea> </div> <div class="post-photos clear-both"> [% if (typeof attachments !== 'undefined' && attachments !== null) { %] [% if (typeof attachments.files !== 'undefined' && attachments.files !== null) { %] [% if (attachments.files.length !== null && attachments.files.length > 0) { %] [% for (i = 0; i < attachments.files.length; i++) { %] [% if (attachments.files[i].type.match(/^image/)) { %]<a href="[%= attachments.files[i].url %]" target="_blank" style="width: 200px; height: 200px;" class="thumbnail"><img src="[%= attachments.files[i].preview %]" style="width: 200px; height: 200px;"/></a>[% } %] [% } %] [% } %] [% } %] [% } %]</div> <div class="post-files clear-both"> [% if (typeof attachments !== 'undefined' && attachments !== null) { %] [% if (typeof attachments.files !== 'undefined' && attachments.files !== null) { %] [% if (attachments.files.length !== null && attachments.files.length > 0) { %] <p> [% for (i = 0; i < attachments.files.length; i++) { %] [% if (!attachments.files[i].type.match(/^image/)) { %] <div class="attachments-file"><i class="icon-file"></i>&nbsp;<a href="[%= attachments.files[i].url %]" target="_blank">[%= attachments.files[i].name %]</a>&nbsp; &nbsp;<small class="muted">[%= attachments.files[i].sizeFormat %]</small>&nbsp; &nbsp;<small><a href="[%= attachments.files[i].url %]" target="_blank">Скачать</a></small> </div>[% } %] [% } %] </p>[% } %] [% } %] [% } %] </div> <div class="post-tools-edit hide clear-both"><a href="#" data-action="save post" data-post="[%= id %]" class="btn btn-success btn-small">Сохранить</a>&nbsp;<a href="#" data-action="blur post" data-post="[%= id %]" class="btn btn-small">Отмена</a></div> <div class="post-tools-remove hide clear-both"><a href="#" data-action="delete post" data-post="[%= id %]" class="btn btn-danger btn-small">Удалить</a>&nbsp;<a href="#" data-action="blur post" data-post="[%= id %]" class="btn btn-small">Отмена</a></div> <div class="post-footer clear-both"><small class="muted"> <div class="post-footer-date pull-left">[%= moment(post_dt).fromNow() %]</div> <div class="post-footer-tools pull-left"> [% if (our) { %] &nbsp; &nbsp;<a href="#" data-action="edit post" data-post="[%= id %]">редактировать</a>&nbsp; &nbsp;<a href="#" data-action="remove post" data-post="[%= id %]">удалить</a>[% } %] </div></small></div> </div> <hr/> </li>
standart-n/sn-oz-client
view/feed/feedNews.html
HTML
mit
3,386
<!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <html prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>مصلحة الهجرة السويدية تدعو طالبي لعدم تصديق الشائعات</title> <link href="//cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/foundation-icons.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="http://nabd-sharqi.com/assets/css/styles_feeling_responsive.css" /> <link rel="stylesheet" type="text/css" href="/assets/css/overrides.css" /> <script src="http://nabd-sharqi.com/assets/js/modernizr.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"></script> <script> WebFont.load({ google: { families: [ 'Lato:400,700,400italic:latin', 'Volkhov::latin' ] } }); </script> <noscript> <link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic|Volkhov' rel='stylesheet' type='text/css' /> </noscript> <meta name="google-site-verification" content="Vk0IOJ2jwG_qEoG7fuEXYqv0m2rLa8P778Fi_GrsgEQ" /> <meta name="msvalidate.01" content="0FB4C028ABCF07C908C54386ABD2D97F" /> <meta name="description" content="ذكرت مصلحة الهجرة Migrationsverket في تقرير نشرته على موقعها الإلكتروني أن عدد طالبي اللجوء الذين وصلوا السويد يوم الاثنين الماضي وتم استقبالهم في مصلحة الهجرة بمدينة مالمو، بلغ حوالي 320 لاجئ" /> <link rel="author" href="https://plus.google.com/+karammelkon/posts"/> <link rel="icon" sizes="32x32" href="http://nabd-sharqi.com/assets/img/favicon-32x32.png" /> <link rel="icon" sizes="192x192" href="http://nabd-sharqi.com/assets/img/touch-icon-192x192.png" /> <link rel="apple-touch-icon-precomposed" sizes="180x180" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-180x180-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-152x152-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-144x144-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="120x120" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-120x120-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-114x114-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="76x76" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-76x76-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-72x72-precomposed.png" /> <link rel="apple-touch-icon-precomposed" href="http://nabd-sharqi.com/assets/img/apple-touch-icon-precomposed.png" /> <meta name="msapplication-TileImage" content="http://nabd-sharqi.com/assets/img/msapplication_tileimage.png" /> <meta name="msapplication-TileColor" content="#fabb00" /> <!-- Facebook Optimization --> <meta property="og:locale" content="ar_AR" /> <meta property="og:type" content="website" /> <meta property="og:title" content="مصلحة الهجرة السويدية تدعو طالبي لعدم تصديق الشائعات" /> <meta property="og:description" content="ذكرت مصلحة الهجرة Migrationsverket في تقرير نشرته على موقعها الإلكتروني أن عدد طالبي اللجوء الذين وصلوا السويد يوم الاثنين الماضي وتم استقبالهم في مصلحة الهجرة بمدينة مالمو، بلغ حوالي 320 لاجئ" /> <meta property="og:url" content="http://nabd-sharqi.com/abroad/migrationsverket/" /> <meta property="og:site_name" content="نبض شرقي" /> <meta property="og:image" content="http://nabd-sharqi.com/images/migrationsverket.jpg" /> <!-- <meta property="og:image:width" content="450"/> --> <!-- <meta property="og:image:height" content="298"/> --> <meta property="fb:admins" content="https://www.facebook.com/karam.melkon"> <meta property="fb:app_id" content="577006852437471"> <!-- Search Engine Optimization --> <link type="text/plain" rel="author" href="http://nabd-sharqi.com/humans.txt" /> </head> </head> <body id="top-of-page" class="post"> <div id="navigation" class="sticky"> <nav class="top-bar" role="navigation" data-topbar> <ul class="title-area"> <li class="name"> <h1 class="show-for-small-only"><a href="http://nabd-sharqi.com" > نبض شرقي</a></h1> </li> <!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone --> <li class="toggle-topbar menu-icon"><a href="#"><span>القائمة</span></a></li> </ul> <section class="top-bar-section" style="padding-right: 10px;"> <ul class="right text-right"> <li class="divider"></li> <li ><a class="blogs" href="http://nabd-sharqi.com/newspapers/index.html">مدونات - جرائد</a></li> <li class="divider"></li> <li ><a class="it" href="http://nabd-sharqi.com/IT/index.html">IT</a></li> <li class="divider"></li> <li ><a class="books" href="http://nabd-sharqi.com/book-in-episodes/index.html">كتاب في حلقات</a></li> <li class="divider"></li> <li ><a class="abroad" href="http://nabd-sharqi.com/abroad/index.html">مهاجرون</a></li> <li class="divider"></li> <li ><a class="fields" href="http://nabd-sharqi.com/fields/index.html">ملاعب</a></li> <li class="divider"></li> <li ><a class="art" href="http://nabd-sharqi.com/art/index.html">فنون</a></li> <li class="divider"></li> <li ><a class="crossed" href="http://nabd-sharqi.com/crossed-words/index.html">أفكار متقاطعة</a></li> <li class="divider"></li> <li ><a class="culture" href="http://nabd-sharqi.com/culture/index.html">فضاءات ثقافية</a></li> <li class="divider"></li> <li ><a class="ew" href="http://nabd-sharqi.com/east-west/index.html">شرق - غرب</a></li> <li class="divider"></li> <li ><a class="" href="http://nabd-sharqi.com/">الصفحة الرئيسية</a></li> </ul> <ul class="left"> </ul> </section> </nav> </div><!-- /#navigation --> <!-- Look the author details up from the site config. --> <!-- Output author details if some exist. --> <div class="row t30"> <div class="medium-8 columns medium-offset-2 end"> <article itemscope itemtype="http://schema.org/Article" class="text-right"> <header> <figure> <img src="/images/migrationsverket.jpg" width="970" alt="مصلحة الهجرة السويدية تدعو طالبي لعدم تصديق الشائعات" itemprop="image"> </figure> <span itemprop="name"> <p class="subheadline">مهاجرون</p> <h1>مصلحة الهجرة السويدية تدعو طالبي لعدم تصديق الشائعات</h1> </span> </header> <span itemprop="articleSection"> <p>ذكرت مصلحة الهجرة Migrationsverket في تقرير نشرته على موقعها الإلكتروني أن عدد طالبي اللجوء الذين وصلوا السويد يوم الاثنين الماضي .وتم استقبالهم في مصلحة الهجرة بمدينة مالمو، بلغ حوالي 320 لاجئ</p> <p>ووصل عدد طالبي اللجوء خلال الفترة الممتدة من بعد ظهر يوم الاثنين ولغاية مساء يوم الثلاثاء الماضي نحو 280 لاجئ، في حين قدر عدد الذين .وصلوا السويد في منتصف ليلة أمس الثلاثاء قرابة 40 طالب لجوء</p> <p>.وقالت رئيسة قسم مصلحة الهجرة في مالمو Jennie Sörman إن المصلحة استعدت بشكل مناسب لاستقبال هؤلاء اللاجئين وتقديم المساعدة اللازمة لهم</p> <p>وأكدت سورمان أن المصلحة تعمل على مدار الساعة وبشكل يومي لتقديم الخدمات اللازمة لطالبي اللجوء واستقبالهم في مختلف الأوقات وتأمين .الطعام والمأوى لهم في مراكز اللجوء في Midhem و Jägersro ببلدية مالمو</p> <p>وأوضحت أن غالبية طالبي اللجوء يعرفون إلى أين يتوجهون عند وصولهم لمالمو، أما أولئك الذين لا يعرفون كيف أو إلى أين يذهبون فإنهم يطلبون .مساعدة عناصر الشرطة الذين يقدمون لهم المساعدة التي يحتاجونها ويدلوهم على كيفية التصرف والإجراءات المطلوبة منهم</p> <p>ونبهت سورمان إلى عدم صحة الشائعات التي يطلقها البعض في مالمو، داعيةً طالبي اللجوء إلى استغلال الوقت سريعاً والتقدم بطلبات لجوئهم إلى .مصلحة الهجرة</p> </span> <!-- --> <div id="page-meta" class="t30"> <p> <!-- Look the author details up from the site config. --> <time class="icon-calendar pr20" datetime="2015-09-12" itemprop="datePublished"> 2015-09-12</time> <!-- Output author details if some exist. --> <br /> </p> </div><!-- /.page-meta --> <!-- --> <div class="share-page"> Share this on &rarr; <a href="https://twitter.com/intent/tweet?text=مصلحة الهجرة السويدية تدعو طالبي لعدم تصديق الشائعات&url=http://nabd-sharqi.com/abroad/migrationsverket/&via=nabdsharqi&related=nabdsharqi" rel="nofollow" target="_blank" title="Share on Twitter">Twitter</a> <a href="https://facebook.com/sharer.php?u=http://nabd-sharqi.com/abroad/migrationsverket/" rel="nofollow" target="_blank" title="Share on Facebook">Facebook</a> <a href="https://plus.google.com/share?url=http://nabd-sharqi.com/abroad/migrationsverket/" rel="nofollow" target="_blank" title="Share on Google+">Google+</a> </div> <style> .share-page { text-align: center; background: #009688; color: white; padding: 8px 15px; border-radius: 5px; margin: 1.5px 0; } .share-page a { font-weight: 700; color: #fff; margin-left: 10px; } .share-page a:hover { border-bottom: 1px dashed #fff; } </style> <!-- --> </article> </div><!-- /.medium-8.columns --> </div><!-- /.row --> <div id="up-to-top" class="row"> <div class="small-12 columns" style="text-align: right;"> <a class="iconfont" href="#top-of-page">&#xf108;</a> </div><!-- /.small-12.columns --> </div><!-- /.row --> <footer id="footer-content" class="bg-grau"> <div id="footer"> <div class="row"> <div class="medium-6 large-5 columns text-right right"> <h5 class="shadow-black">عن هذا الموقع</h5> <p class="shadow-black"> موقع الكتروني يهتم بأخبار المهاجرين و يسعى لنشر الثقافة و المعرفة و التنوير و الإنسانية <a href="http://nabd-sharqi.com/info/"> المزيد</a> </p> </div><!-- /.large-6.columns --> <div class="medium-6 large-5 columns text-right right shadow-black"> <h5 class="shadow-black">تواصلوا معنا</h5> :للاتصال و إرسال المواد على أحد الايميلين التاليين <a href="mailto:nabdsharqi@gmail.com">nabdsharqi@gmail.com</a> - <a href="mailto:mkmc65@gmail.com">mkmc65@gmail.com</a> </div><!-- /.large-6.columns --> </div><!-- /.row --> </div><!-- /#footer --> <div id="subfooter"> <nav class="row"> <section id="subfooter-left" class="b30 small-12 medium-6 columns credits"> <p> Handmade by&nbsp;<a href="">Karam</a> with&nbsp;<a href="http://jekyllrb.com/" target="_blank">Jekyll</a> based&nbsp;on&nbsp;<a href="http://phlow.github.io/feeling-responsive/">Feeling&nbsp;Responsive</a>. </p> </section> <section id="subfooter-right" class="small-12 medium-6 columns social-icons"> <ul class="inline-list right"> <li><a href="http://twitter.com/nabdsharqi" target="_blank" class="icon-twitter" title="نبض شرقي على تويتر"></a></li> <li><a href="http://facebook.com/pages/%D9%86%D8%A8%D8%B6-%D8%B4%D8%B1%D9%82%D9%8A/975137169215945" target="_blank" class="icon-facebook" title="نبض شرقي على الفيسبوك"></a></li> <li><a href="http://plus.google.com/u/0/104600327080975018022/posts" target="_blank" class="fi-social-google-plus" title="نبض شرقي على غوغل بلس"></a></li> </ul> </section> </nav> </div><!-- /#subfooter --> </footer> <script src="http://nabd-sharqi.com/assets/js/javascript.min.js"></script> <script src="http://nabd-sharqi.com/assets/js/extra.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-67086307-1', 'auto'); // ga('set', 'anonymizeIp', true); ga('send', 'pageview'); </script> </body> </html>
nabdsharqi/nabdsharqi.github.io
_site/abroad/migrationsverket/index.html
HTML
mit
16,555
import { makeStyles } from '@material-ui/core/styles'; const drawerWidth = 240; export const useStyles = makeStyles((theme) => ({ root: { display: 'flex', height: '100vh', }, appBar: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, toolbar: { display: 'flex', 'justify-content': 'space-between', background: '#5700FA', }, toolbarSpacer: theme.mixins.toolbar, content: { flexGrow: 1, backgroundColor: theme.palette.background.default, position: 'relative', height: 'calc(100% - 64px)', }, headerButtonText: { marginLeft: '0.5rem', }, headerButton: { paddingLeft: '0.5rem', paddingRight: '0.5rem', height: '34px', }, iframe: { border: 'none', }, }));
diegodoumecq/joymap
examples/Main/styles.ts
TypeScript
mit
872
# Crowd Finance Infographic ## Intro This assessment has been deployed showcasing my abilities as a Data Scientist. For more information on how to make use of this project, please read the [Documentation](docs/index.md). ## Assessment A user wants to produce an infographic that summaries the state of the crowdfunding market over time for use in marketing material and news feeds. Two types of analysis were proposed: a) Trending market segments: a ranking of the top trending segments within crowd finance at the end of a given period, with an indication of where each segment was ranked at the end of a preceding period of time of the same length. b) Market index: a metric that reflects how well the crowd finance market as a whole performs over a given period. Projects adhere to the following schema: ```json { "url": "Link to the campaign on the platform website", "platform_name": "Name of Platform", "status": "Campaign status", "concepts": { "title": ["The concepts within the title"], "subtitle": ["The concepts within the sub title"], "description": ["The concepts within the description"], "category": ["The concepts within the category"] }, "start_time": "Project start date.", "end_time": "Project end date. ", "goal_fx": { "GBP": "Amount of money campaigning for, in GBP" }, "raised_fx": { "GBP": "Amount of money currently raised, in GBP" } } ``` Where concepts are defined as a list of the following structures: ```json { "start": "The position of the last character of what the concept represents in the corresponding text field (starts at 0)", "end": "The position of the last character of what the concept represents in the corresponding text field (starts at 0)", "concept": "The actual concept" } ``` ## Task Please submit a Python program to generate the analytics results described in a), over an arbitrary time period. One way of ranking market segments is by the number of times the concepts occur in campaigns. Consider the limitations of this approaches and please improve on it with your solution so it is more informative. __Hint__: Does the popularity of a concept over previous months define whether it is trending this month? You should output the results in a format that makes it easy to render as a chart (e.g as a JSON document). You should create at least one unit test to verify your code. ### Bonus question One way to implement the market index would be to compute the total amount raised by all campaigns that end before the specified date. Discuss the limitations and any improvements on this approach that you can think of. ## Instructions Please submit: - Your solution for each part of the question. - Your reasons behind any design decision. - The limitations of your solution. - How you could extend your work. - Instructions on how to use your solutions. Don't forget to include the requirements.txt file if you've used any external libraries.
ohduran/CrowdFinanceInfographic
README.md
Markdown
mit
2,956
--- title: Gatsby repo: gatsbyjs/gatsby date: 2015-10-02T21:18:00.000+00:00 posted_date: '2015-10-02T21:18:00.000+00:00' featured: true slug: gatsby tools: - Hosting-Deployment - Static Site Generator urls: website: https://www.gatsbyjs.org/ github: https://github.com/gatsbyjs/gatsby twitter: https://twitter.com/gatsbyjs other: '' license: Commercial language: Javascript description: Blazing-fast static site generator for React headless-cms: '' related_tools: - tool/stein.md tags: - React resources: - name: Gatsby Manor Themes url: https://www.gatsbymanor.com/ cat_test: '' weight: 3 data_model: '' interactions: [] --- Transform plain text into dynamic blogs and websites using the latest web technologies. A React.js static site generator. --- {{< youtube G4LVKJOOj7o >}}
budparr/thenewdynamic
content/tool/gatsby.md
Markdown
mit
793
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace IIS.Склад { using System; using System.Xml; using ICSSoft.STORMNET; // *** Start programmer edit section *** (Using statements) // *** End programmer edit section *** (Using statements) /// <summary> /// Товар на складе. /// </summary> // *** Start programmer edit section *** (ТоварНаСкладе CustomAttributes) // *** End programmer edit section *** (ТоварНаСкладе CustomAttributes) [AutoAltered()] [Caption("Товар на складе")] [AccessType(ICSSoft.STORMNET.AccessType.none)] [View("ТоварНаСкладеE", new string[] { "Склад", "Товар.Наименование", "Товар", "Количество", "Склад.Название"}, Hidden=new string[] { "Склад", "Товар.Наименование", "Склад.Название"})] [MasterViewDefineAttribute("ТоварНаСкладеE", "Товар", ICSSoft.STORMNET.LookupTypeEnum.Standard, "", "Наименование")] public class ТоварНаСкладе : ICSSoft.STORMNET.DataObject { private double fКоличество; private IIS.Склад.Товар fТовар; private IIS.Склад.Склад fСклад; // *** Start programmer edit section *** (ТоварНаСкладе CustomMembers) private ICSSoft.STORMNET.UserDataTypes.NullableDecimal cashedPurchaseSum = null; //переменная для хранения кэша поля СуммаОплаченныхПокупок private ICSSoft.STORMNET.UserDataTypes.NullableDecimal cashedAvailableSum = null; //переменная для хранения кэша поля ДоступнаяСумма private double fКоличество2; // *** End programmer edit section *** (ТоварНаСкладе CustomMembers) /// <summary> /// Количество. /// </summary> // *** Start programmer edit section *** (ТоварНаСкладе.Количество CustomAttributes) // *** End programmer edit section *** (ТоварНаСкладе.Количество CustomAttributes) public virtual double Количество { get { // *** Start programmer edit section *** (ТоварНаСкладе.Количество Get start) // *** End programmer edit section *** (ТоварНаСкладе.Количество Get start) double result = this.fКоличество; // *** Start programmer edit section *** (ТоварНаСкладе.Количество Get end) // *** End programmer edit section *** (ТоварНаСкладе.Количество Get end) return result; } set { // *** Start programmer edit section *** (ТоварНаСкладе.Количество Set start) // *** End programmer edit section *** (ТоварНаСкладе.Количество Set start) this.fКоличество = value; // *** Start programmer edit section *** (ТоварНаСкладе.Количество Set end) // *** End programmer edit section *** (ТоварНаСкладе.Количество Set end) } } /// <summary> /// Количество2. /// </summary> // *** Start programmer edit section *** (ТоварНаСкладе.Количество2 CustomAttributes) // *** End programmer edit section *** (ТоварНаСкладе.Количество2 CustomAttributes) [ICSSoft.STORMNET.NotStored()] [DataServiceExpression(typeof(ICSSoft.STORMNET.Business.SQLDataService), "Select Sum(Количество) from Поставки where Товар = @Товар@ and Склад = @Склад@")] public virtual double Количество2 { get { // *** Start programmer edit section *** (ТоварНаСкладе.Количество2 Get) //return (decimal)this.cashedPurchaseSum; return fКоличество2; // *** End programmer edit section *** (ТоварНаСкладе.Количество2 Get) } set { // *** Start programmer edit section *** (ТоварНаСкладе.Количество2 Set) /*if (value != null) {*/ //this.cashedPurchaseSum = (ICSSoft.STORMNET.UserDataTypes.NullableDecimal)value; //this. fКоличество2 = value; //}* // *** End programmer edit section *** (ТоварНаСкладе.Количество2 Set) } } /// <summary> /// Товар на складе. /// </summary> // *** Start programmer edit section *** (ТоварНаСкладе.Товар CustomAttributes) // *** End programmer edit section *** (ТоварНаСкладе.Товар CustomAttributes) [PropertyStorage(new string[] { "Товар"})] [NotNull()] public virtual IIS.Склад.Товар Товар { get { // *** Start programmer edit section *** (ТоварНаСкладе.Товар Get start) // *** End programmer edit section *** (ТоварНаСкладе.Товар Get start) IIS.Склад.Товар result = this.fТовар; // *** Start programmer edit section *** (ТоварНаСкладе.Товар Get end) // *** End programmer edit section *** (ТоварНаСкладе.Товар Get end) return result; } set { // *** Start programmer edit section *** (ТоварНаСкладе.Товар Set start) // *** End programmer edit section *** (ТоварНаСкладе.Товар Set start) this.fТовар = value; // *** Start programmer edit section *** (ТоварНаСкладе.Товар Set end) // *** End programmer edit section *** (ТоварНаСкладе.Товар Set end) } } /// <summary> /// мастеровая ссылка на шапку IIS.Склад.Склад. /// </summary> // *** Start programmer edit section *** (ТоварНаСкладе.Склад CustomAttributes) // *** End programmer edit section *** (ТоварНаСкладе.Склад CustomAttributes) [Agregator()] [NotNull()] [PropertyStorage(new string[] { "Склад"})] public virtual IIS.Склад.Склад Склад { get { // *** Start programmer edit section *** (ТоварНаСкладе.Склад Get start) // *** End programmer edit section *** (ТоварНаСкладе.Склад Get start) IIS.Склад.Склад result = this.fСклад; // *** Start programmer edit section *** (ТоварНаСкладе.Склад Get end) // *** End programmer edit section *** (ТоварНаСкладе.Склад Get end) return result; } set { // *** Start programmer edit section *** (ТоварНаСкладе.Склад Set start) // *** End programmer edit section *** (ТоварНаСкладе.Склад Set start) this.fСклад = value; // *** Start programmer edit section *** (ТоварНаСкладе.Склад Set end) // *** End programmer edit section *** (ТоварНаСкладе.Склад Set end) } } /// <summary> /// Class views container. /// </summary> public class Views { /// <summary> /// "ТоварНаСкладеE" view. /// </summary> public static ICSSoft.STORMNET.View ТоварНаСкладеE { get { return ICSSoft.STORMNET.Information.GetView("ТоварНаСкладеE", typeof(IIS.Склад.ТоварНаСкладе)); } } } } /// <summary> /// Detail array of ТоварНаСкладе. /// </summary> // *** Start programmer edit section *** (DetailArrayDetailArrayOfТоварНаСкладе CustomAttributes) // *** End programmer edit section *** (DetailArrayDetailArrayOfТоварНаСкладе CustomAttributes) public class DetailArrayOfТоварНаСкладе : ICSSoft.STORMNET.DetailArray { // *** Start programmer edit section *** (IIS.Склад.DetailArrayOfТоварНаСкладе members) // *** End programmer edit section *** (IIS.Склад.DetailArrayOfТоварНаСкладе members) /// <summary> /// Construct detail array. /// </summary> /// <summary> /// Returns object with type ТоварНаСкладе by index. /// </summary> /// <summary> /// Adds object with type ТоварНаСкладе. /// </summary> public DetailArrayOfТоварНаСкладе(IIS.Склад.Склад fСклад) : base(typeof(ТоварНаСкладе), ((ICSSoft.STORMNET.DataObject)(fСклад))) { } public IIS.Склад.ТоварНаСкладе this[int index] { get { return ((IIS.Склад.ТоварНаСкладе)(this.ItemByIndex(index))); } } public virtual void Add(IIS.Склад.ТоварНаСкладе dataobject) { this.AddObject(((ICSSoft.STORMNET.DataObject)(dataobject))); } } }
Flexberry/FlexberryStudy2015
Belikova Anastasiya/Individual work/Objects/ТоварНаСкладе.cs
C#
mit
11,027
*{ margin:0px; padding:0px; } body{ text-align:left; font-family:Arial; font-size:20px; display:-webkit-box; -webkit-box-pack:center; margin:0px; background-image: url('../images/gray.jpg'); } #time{float:left; color:#ddd; padding: 20px; } #wrapper{/*position:relative;*/ height:665px; width: 100%; max-width:1460px; clear:both; display:-webkit-box; -webkit-box-orient:vertical; -webkit-box-flex:0; } #logout{ margin-right:50px; } #header{ border:1; height:50px; background-image: url('../images/darkgray.jpg'); } #content{ font-family: 'Roboto Light'; src: url('../fonts/Roboto-Light.ttf'); font-weight: normal; font-style: normal; font-size: 15px; text-align:left; width:60%; padding:15px; padding-top: 5px; border:5px solid rgb(137, 129, 168); -webkit-border-radius: 20px; margin-left:300px; margin-right:300px; margin-bottom:50px; font-size:20px; width:1100px; } #out { height:210px; } .ques { max-height:200px; overflow:auto; width:100%; float:left; } .ques1 { max-height:200px; width:100%; float:left; } .aside { float:left; left:50px; top:150px; position:absolute; display:-webkit-box; } .button{padding:7px; font-size:20px; background-color: #939CB4; -webkit-border-radius: 15px; color:#fff; } input{padding:10px; font-size:20px; } footer{ display:-webkit-box; position:absolute; padding:5px; font-size:30px; margin-left:500px;/*border:1px solid blue;*/ } #copyright{ display:-webkit-box; position:absolute; width:300px; left:10px; font-size:15px; font-family:Arial; margin-top:20px; margin-left:500px; float: right; padding: 50px } #up { margin-top: 70px; } .r { float: right; } a { color: #ddd; text-decoration: none; } a:hover { color:#fff; text-decoration: underline; } .m15{ font-size: 15px; } .h{ font-family: 'ChunkFive Roman'; src: url('../fonts/Chunkfive.otf'); font-size: 30px; padding-top: 5px; color: #ddd; font-weight: normal; font-style: normal; margin-left: 170px; } .answered { padding:7px; font-size:20px; background-color: #02113C; -webkit-border-radius: 15px; color:#fff; } #next{ margin-left: 480px; float:right; } .nav{ margin-top:10px; background: -webkit-linear-gradient(top, #55AEAE, #436788); background-color: #4888AC; -webkit-box-shadow: inset 0 1px 1px #a4e388; border-color: #22596E #34648A #0A232B; border: 1px solid; border-radius: 10px; font-size: 12px; width:80px; } .l{ float:left; } .r{ float: right; } .ml450{ margin-left: 630px; } .fontr{ font-family: 'Roboto Medium'; src: url('../fonts/Roboto-MediumItalic.ttf'); font-weight: normal; font-style: normal; } #options { height:320px; border: 1px solid; width:99%; clear: both; padding-left: 10px; border:5px solid rgb(137, 129, 168); -webkit-border-radius: 20px; } #opt1{ height: 75px; padding-bottom: 5px; overflow:auto; } #opt2{ height: 75px; padding-bottom: 5px; overflow:auto; } #opt3{ height: 75px; padding-bottom: 5px; overflow:auto; } #opt4{ height: 75px; padding-bottom: 5px; overflow:auto; } .enlarge { display:inline-block; position: relative; z-index: 0; margin:10px 40px 0 20px; } .enlarge span{ position:absolute; left: -9999px; } .enlarge img{ background-color:#eae9d4; padding: 6px; -webkit-box-shadow: 0 0 6px rgba(132, 132, 132, .75); -moz-box-shadow: 0 0 6px rgba(132, 132, 132, .75); box-shadow: 0 0 6px rgba(132, 132, 132, .75); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .enlarge:hover{ z-index: 50; cursor:pointer; } .enlarge:hover span{ top: -80px; left: -20px; } /***Override the styling of images set in step 3 to make the frame smaller and the background darker***/ .enlarge span img{ padding: 2px; /*size of the frame*/ background: #ccc; /*colour of the frame*/ } /***Style the <span> containing the framed images and the caption***/ .enlarge span{ /**Style the frame**/ padding: 10px; /*size of the frame*/ background:#eae9d4; /*colour of the frame*/ /*add a drop shadow to the frame*/ -webkit-box-shadow: 0 0 20px rgba(0,0,0, .75)); -moz-box-shadow: 0 0 20px rgba(0,0,0, .75); box-shadow: 0 0 20px rgba(0,0,0, .75); /*give the corners a curve*/ -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius:8px; /**Style the caption**/ font-family: 'Droid Sans', sans-serif; /*Droid Sans is available from Google fonts*/ font-size:.9em; text-align: center; color: #495a62; } #program { padding:10px; margin:10px; overflow:auto; }
melvin0008/quizcreator
css/quiz.css
CSS
mit
4,738
import getValue from './getValue.js'; import getNumberValue from './getNumberValue.js'; export default function getOverlayPlaneModule(metaData) { const overlays = []; for (let overlayGroup = 0x00; overlayGroup <= 0x1e; overlayGroup += 0x02) { let groupStr = `x60${overlayGroup.toString(16)}`; if (groupStr.length === 4) { groupStr = `x600${overlayGroup.toString(16)}`; } const data = getValue(metaData[`${groupStr}3000`]); if (!data) { continue; } const pixelData = []; for (let i = 0; i < data.length; i++) { for (let k = 0; k < 8; k++) { const byte_as_int = metaData.Value[data.dataOffset + i]; pixelData[i * 8 + k] = (byte_as_int >> k) & 0b1; // eslint-disable-line no-bitwise } } overlays.push({ rows: getNumberValue(metaData[`${groupStr}0010`]), columns: getNumberValue(metaData[`${groupStr}0011`]), type: getValue(metaData[`${groupStr}0040`]), x: getNumberValue(metaData[`${groupStr}0050`], 1) - 1, y: getNumberValue(metaData[`${groupStr}0050`], 0) - 1, pixelData, description: getValue(metaData[`${groupStr}0022`]), label: getValue(metaData[`${groupStr}1500`]), roiArea: getValue(metaData[`${groupStr}1301`]), roiMean: getValue(metaData[`${groupStr}1302`]), roiStandardDeviation: getValue(metaData[`${groupStr}1303`]), }); } return { overlays, }; }
chafey/cornerstoneWADOImageLoader
src/imageLoader/wadors/metaData/getOverlayPlaneModule.js
JavaScript
mit
1,430
class Solution: def combine(self, n, k): return [list(elem) for elem in itertools.combinations(xrange(1, n + 1), k)]
rahul-ramadas/leetcode
combinations/Solution.6808610.py
Python
mit
132
'use strict'; /********************************************************************** * Angular Application (client side) **********************************************************************/ angular.module('SwagApp', ['ngRoute', 'appRoutes', 'ui.bootstrap', 'ui.bootstrap.tpls' , 'MainCtrl', 'LoginCtrl', 'MySwagCtrl', 'MySwagService', 'GeekCtrl', 'GeekService']) .config(function($routeProvider, $locationProvider, $httpProvider) { //================================================ // Add an interceptor for AJAX errors //================================================ $httpProvider.responseInterceptors.push(function($q, $location) { return function(promise) { return promise.then( // Success: just return the response function(response){ return response; }, // Error: check the error status to get only the 401 function(response) { if (response.status === 401) $location.url('/login'); return $q.reject(response); } ); } }); //================================================ }) //end of config .run(function($rootScope, $http){ $rootScope.message = ''; // Logout function is available in any pages $rootScope.logout = function(){ $rootScope.message = 'Logged out.'; $http.post('/logout'); }; });
e2themillions/swaggatar
public/js/app.js
JavaScript
mit
1,462
import os import unittest from erettsegit import argparse, yearify, monthify, levelify from erettsegit import MessageType, message_for class TestErettsegit(unittest.TestCase): def test_yearify_raises_out_of_bounds_years(self): with self.assertRaises(argparse.ArgumentTypeError): yearify(2003) yearify(1999) yearify(2) yearify(2999) def test_yearify_pads_short_year(self): self.assertEqual(yearify(12), 2012) def test_monthify_handles_textual_dates(self): self.assertEqual(monthify('Feb'), 2) self.assertEqual(monthify('majus'), 5) self.assertEqual(monthify('ősz'), 10) def test_levelify_handles_multi_lang(self): self.assertEqual(levelify('mid-level'), 'k') self.assertEqual(levelify('advanced'), 'e') def test_messages_get_interpolated_with_extra(self): os.environ['ERETTSEGIT_LANG'] = 'EN' self.assertEqual(message_for(MessageType.e_input, MessageType.c_year), 'incorrect year') def test_messages_ignore_unnecessary_extra(self): self.assertNotIn('None', message_for(MessageType.i_quit, extra=None))
z2s8/erettsegit
test_erettsegit.py
Python
mit
1,186
module Boxy class HomesickHandler def install(url, options) url = URI.parse(url) name = File.basename(url.path) unless castle_cloned?(name) system "homesick clone #{url.to_s}" system "homesick symlink #{name}" else puts "skipping #{name}, already installed" end end private def castle_cloned?(name) `homesick status #{name} > /dev/null 2>&1` $? == 0 end end Boxy.register(:homesick, HomesickHandler.new) end
fooheads/boxy
lib/boxy/homesick.rb
Ruby
mit
505
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from django.core.paginator import InvalidPage, Paginator from django.db import models from django.http import HttpResponseRedirect from django.template.response import SimpleTemplateResponse, TemplateResponse from django.utils.datastructures import SortedDict from django.utils.encoding import force_unicode, smart_unicode from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from nadmin.util import lookup_field, display_for_field, label_for_field, boolean_icon from base import ModelAdminView, filter_hook, inclusion_tag, csrf_protect_m # List settings ALL_VAR = 'all' ORDER_VAR = 'o' PAGE_VAR = 'p' TO_FIELD_VAR = 't' COL_LIST_VAR = '_cols' ERROR_FLAG = 'e' DOT = '.' # Text to display within change-list table cells if the value is blank. EMPTY_CHANGELIST_VALUE = _('Null') class FakeMethodField(object): """ This class used when a column is an model function, wrap function as a fake field to display in select columns. """ def __init__(self, name, verbose_name): # Initial comm field attrs self.name = name self.verbose_name = verbose_name self.primary_key = False class ResultRow(dict): pass class ResultItem(object): def __init__(self, field_name, row): self.classes = [] self.text = '&nbsp;' self.wraps = [] self.tag = 'td' self.tag_attrs = [] self.allow_tags = False self.btns = [] self.menus = [] self.is_display_link = False self.row = row self.field_name = field_name self.field = None self.attr = None self.value = None @property def label(self): text = mark_safe( self.text) if self.allow_tags else conditional_escape(self.text) if force_unicode(text) == '': text = mark_safe('&nbsp;') for wrap in self.wraps: text = mark_safe(wrap % text) return text @property def tagattrs(self): return mark_safe( '%s%s' % ((self.tag_attrs and ' '.join(self.tag_attrs) or ''), (self.classes and (' class="%s"' % ' '.join(self.classes)) or ''))) class ResultHeader(ResultItem): def __init__(self, field_name, row): super(ResultHeader, self).__init__(field_name, row) self.tag = 'th' self.tag_attrs = ['scope="col"'] self.sortable = False self.allow_tags = True self.sorted = False self.ascending = None self.sort_priority = None self.url_primary = None self.url_remove = None self.url_toggle = None class ListAdminView(ModelAdminView): """ Display models objects view. this class has ordering and simple filter features. """ list_display = ('__str__',) list_display_links = () list_display_links_details = False list_select_related = None list_per_page = 50 list_max_show_all = 200 list_exclude = () search_fields = () paginator_class = Paginator ordering = None # Change list templates object_list_template = None def init_request(self, *args, **kwargs): if not self.has_view_permission(): raise PermissionDenied request = self.request request.session['LIST_QUERY'] = (self.model_info, self.request.META['QUERY_STRING']) self.pk_attname = self.opts.pk.attname self.lookup_opts = self.opts self.list_display = self.get_list_display() self.list_display_links = self.get_list_display_links() # Get page number parameters from the query string. try: self.page_num = int(request.GET.get(PAGE_VAR, 0)) except ValueError: self.page_num = 0 # Get params from request self.show_all = ALL_VAR in request.GET self.to_field = request.GET.get(TO_FIELD_VAR) self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] @filter_hook def get_list_display(self): """ Return a sequence containing the fields to be displayed on the list. """ self.base_list_display = (COL_LIST_VAR in self.request.GET and self.request.GET[COL_LIST_VAR] != "" and \ self.request.GET[COL_LIST_VAR].split('.')) or self.list_display return list(self.base_list_display) @filter_hook def get_list_display_links(self): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if self.list_display_links or not self.list_display: return self.list_display_links else: # Use only the first item in list_display as link return list(self.list_display)[:1] def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.list_queryset.query.where: self.full_result_count = self.result_count else: self.full_result_count = self.base_queryset.count() self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('nadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list)) @filter_hook def get_result_list(self): return self.make_result_list() @filter_hook def post_result_list(self): return self.make_result_list() @filter_hook def get_list_queryset(self): """ Get model queryset. The query has been filted and ordered. """ # First, get queryset from base class. queryset = self.queryset() # Use select_related() if one of the list_display options is a field # with a relationship and the provided queryset doesn't already have # select_related defined. if not queryset.query.select_related: if self.list_select_related: queryset = queryset.select_related() elif self.list_select_related is None: related_fields = [] for field_name in self.list_display: try: field = self.opts.get_field(field_name) except models.FieldDoesNotExist: pass else: if isinstance(field.rel, models.ManyToOneRel): related_fields.append(field_name) if related_fields: queryset = queryset.select_related(*related_fields) else: pass # Then, set queryset ordering. queryset = queryset.order_by(*self.get_ordering()) # Return the queryset. return queryset # List ordering def _get_default_ordering(self): ordering = [] if self.ordering: ordering = self.ordering elif self.opts.ordering: ordering = self.opts.ordering return ordering @filter_hook def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None) @filter_hook def get_ordering(self): """ Returns the list of ordering fields for the change list. First we check the get_ordering() method in model admin, then we check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by ensuring the primary key is used as the last ordering field. """ ordering = list(super(ListAdminView, self).get_ordering() or self._get_default_ordering()) if ORDER_VAR in self.params and self.params[ORDER_VAR]: # Clear ordering and used params ordering = [pfx + self.get_ordering_field(field_name) for n, pfx, field_name in map( lambda p: p.rpartition('-'), self.params[ORDER_VAR].split('.')) if self.get_ordering_field(field_name)] # Ensure that the primary key is systematically present in the list of # ordering fields so we can guarantee a deterministic order across all # database backends. pk_name = self.opts.pk.name if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])): # The two sets do not intersect, meaning the pk isn't present. So # we add it. ordering.append('-pk') return ordering @filter_hook def get_ordering_field_columns(self): """ Returns a SortedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = SortedDict() if ORDER_VAR not in self.params or not self.params[ORDER_VAR]: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for attr in self.list_display: if self.get_ordering_field(attr) == field: ordering_fields[field] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, field_name = p.rpartition('-') ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc' return ordering_fields def get_check_field_url(self, f): """ Return the select column menu items link. We must use base_list_display, because list_display maybe changed by plugins. """ fields = [fd for fd in self.base_list_display if fd != f.name] if len(self.base_list_display) == len(fields): if f.primary_key: fields.insert(0, f.name) else: fields.append(f.name) return self.get_query_string({COL_LIST_VAR: '.'.join(fields)}) def get_model_method_fields(self): """ Return the fields info defined in model. use FakeMethodField class wrap method as a db field. """ methods = [] for name in dir(self): try: if getattr(getattr(self, name), 'is_column', False): methods.append((name, getattr(self, name))) except: pass return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' ')))) for name, method in methods] @filter_hook def get_context(self): """ Prepare the context for templates. """ self.title = _('%s List') % force_unicode(self.opts.verbose_name) model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f)) for f in (self.opts.fields + tuple(self.get_model_method_fields())) if f.name not in self.list_exclude] new_context = { 'model_name': force_unicode(self.opts.verbose_name_plural), 'title': self.title, 'cl': self, 'model_fields': model_fields, 'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]), 'has_add_permission': self.has_add_permission(), 'app_label': self.app_label, 'brand_name': self.opts.verbose_name_plural, 'brand_icon': self.get_model_icon(self.model), 'add_url': self.model_admin_url('add'), 'result_headers': self.result_headers(), 'results': self.results() } context = super(ListAdminView, self).get_context() context.update(new_context) return context @filter_hook def get_response(self, context, *args, **kwargs): pass @csrf_protect_m @filter_hook def get(self, request, *args, **kwargs): """ The 'change list' admin view for this model. """ response = self.get_result_list() if response: return response context = self.get_context() context.update(kwargs or {}) response = self.get_response(context, *args, **kwargs) return response or TemplateResponse(request, self.object_list_template or self.get_template_list('views/model_list.html'), context, current_app=self.admin_site.name) @filter_hook def post_response(self, *args, **kwargs): pass @csrf_protect_m @filter_hook def post(self, request, *args, **kwargs): return self.post_result_list() or self.post_response(*args, **kwargs) or self.get(request, *args, **kwargs) @filter_hook def get_paginator(self): return self.paginator_class(self.list_queryset, self.list_per_page, 0, True) @filter_hook def get_page_number(self, i): if i == DOT: return mark_safe(u'<span class="dot-page">...</span> ') elif i == self.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1)) # Result List methods @filter_hook def result_header(self, field_name, row): ordering_field_columns = self.ordering_field_columns item = ResultHeader(field_name, row) text, attr = label_for_field(field_name, self.model, model_admin=self, return_attr=True ) item.text = text item.attr = attr if attr and not getattr(attr, "admin_order_field", None): return item # OK, it is sortable if we got this far th_classes = ['sortable'] order_type = '' new_order_type = 'desc' sort_priority = 0 sorted = False # Is it currently being sorted on? if field_name in ordering_field_columns: sorted = True order_type = ordering_field_columns.get(field_name).lower() sort_priority = ordering_field_columns.keys().index(field_name) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_asc = [] # URL for making this field the primary sort o_list_desc = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == field_name: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_asc.insert(0, j) o_list_desc.insert(0, '-' + j) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_asc.append(param) o_list_desc.append(param) o_list_toggle.append(param) o_list_remove.append(param) if field_name not in ordering_field_columns: o_list_asc.insert(0, field_name) o_list_desc.insert(0, '-' + field_name) item.sorted = sorted item.sortable = True item.ascending = (order_type == "asc") item.sort_priority = sort_priority menus = [ ('asc', o_list_asc, 'caret-up', _(u'Sort ASC')), ('desc', o_list_desc, 'caret-down', _(u'Sort DESC')), ] if sorted: row['num_sorted_fields'] = row['num_sorted_fields'] + 1 menus.append((None, o_list_remove, 'times', _(u'Cancel Sort'))) item.btns.append('<a class="toggle" href="%s"><i class="fa fa-%s"></i></a>' % ( self.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), 'sort-up' if order_type == "asc" else 'sort-down')) item.menus.extend(['<li%s><a href="%s" class="active"><i class="fa fa-%s"></i> %s</a></li>' % ( (' class="active"' if sorted and order_type == i[ 0] else ''), self.get_query_string({ORDER_VAR: '.'.join(i[1])}), i[2], i[3]) for i in menus]) item.classes.extend(th_classes) return item @filter_hook def result_headers(self): """ Generates the list column headers. """ row = ResultRow() row['num_sorted_fields'] = 0 row.cells = [self.result_header( field_name, row) for field_name in self.list_display] return row @filter_hook def result_item(self, obj, field_name, row): """ Generates the actual list of data. """ item = ResultItem(field_name, row) try: f, attr, value = lookup_field(field_name, obj, self) except (AttributeError, ObjectDoesNotExist): item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: if f is None: item.allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: item.allow_tags = True item.text = boolean_icon(value) else: item.text = smart_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(obj, f.name) if field_val is None: item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: item.text = field_val else: item.text = display_for_field(value, f) if isinstance(f, models.DateField)\ or isinstance(f, models.TimeField)\ or isinstance(f, models.ForeignKey): item.classes.append('nowrap') item.field = f item.attr = attr item.value = value # If list_display_links not defined, add the link tag to the first field if (item.row['is_display_first'] and not self.list_display_links) \ or field_name in self.list_display_links: item.row['is_display_first'] = False item.is_display_link = True if self.list_display_links_details: item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname)) if item_res_uri: if self.has_change_permission(obj): edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname)) else: edit_url = "" item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>' % (item_res_uri, edit_url, _(u'Details of %s') % str(obj))) else: url = self.url_for_result(obj) item.wraps.append(u'<a href="%s">%%s</a>' % url) return item @filter_hook def result_row(self, obj): row = ResultRow() row['is_display_first'] = True row['object'] = obj row.cells = [self.result_item( obj, field_name, row) for field_name in self.list_display] return row @filter_hook def results(self): results = [] for obj in self.result_list: results.append(self.result_row(obj)) return results @filter_hook def url_for_result(self, result): return self.get_object_url(result) # Media @filter_hook def get_media(self): media = super(ListAdminView, self).get_media() + self.vendor('nadmin.page.list.js', 'nadmin.page.form.js') if self.list_display_links_details: media += self.vendor('nadmin.plugin.details.js', 'nadmin.form.css') return media # Blocks @inclusion_tag('nadmin/includes/pagination.html') def block_pagination(self, context, nodes, page_type='normal'): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = self.paginator, self.page_num pagination_required = ( not self.show_all or not self.can_show_all) and self.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = {'normal': 5, 'small': 3}.get(page_type, 3) ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so that there are always ON_ENDS # links at either end of the list of pages, and there are always # ON_EACH_SIDE links at either end of the "current page" link. page_range = [] if page_num > (ON_EACH_SIDE + ON_ENDS): page_range.extend(range(0, ON_EACH_SIDE - 1)) page_range.append(DOT) page_range.extend( range(page_num - ON_EACH_SIDE, page_num + 1)) else: page_range.extend(range(0, page_num + 1)) if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): page_range.extend( range(page_num + 1, page_num + ON_EACH_SIDE + 1)) page_range.append(DOT) page_range.extend(range( paginator.num_pages - ON_ENDS, paginator.num_pages)) else: page_range.extend(range(page_num + 1, paginator.num_pages)) need_show_all_link = self.can_show_all and not self.show_all and self.multi_page return { 'cl': self, 'pagination_required': pagination_required, 'show_all_url': need_show_all_link and self.get_query_string({ALL_VAR: ''}), 'page_range': map(self.get_page_number, page_range), 'ALL_VAR': ALL_VAR, '1': 1, }
A425/django-nadmin
nadmin/views/list.py
Python
mit
25,811
<?php namespace Dragoon\MoviesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class DragoonMoviesBundle extends Bundle { }
lboulay/sonata
src/Dragoon/MoviesBundle/DragoonMoviesBundle.php
PHP
mit
134
import { bindable, customAttribute, inject } from 'aurelia-framework'; import { AttributeManager } from '../common/attributeManager'; @customAttribute('b-button') @inject(Element) export class BButton { @bindable bStyle = 'default'; @bindable bSize = null; @bindable bBlock = null; @bindable bDisabled = false; @bindable bActive = false; constructor(element) { this.element = element; this.fixedAttributeManager = new AttributeManager(this.element); } attached() { this.fixedAttributeManager.addClasses('btn'); this.fixedAttributeManager.addClasses(`btn-${this.bStyle}`); if (this.bSize) { this.fixedAttributeManager.addClasses(`btn-${this.bSize}`); } if (this.bBlock) { this.fixedAttributeManager.addClasses('btn-block'); } if (this.bDisabled === true) { this.fixedAttributeManager.addClasses('disabled'); } if (this.bActive === true) { this.fixedAttributeManager.addClasses('active'); } } }
aurelia-ui-toolkits/aurelia-bootstrap-bridge
src/button/button.js
JavaScript
mit
1,041
.leftColumn { flex-grow: 1; } .rightColumn { max-width: 500px; display: flex; flex-flow: column; flex-grow: 1; } .box { width: 480px; height: calc(50vh - 20px); border-radius: 2px; background-color: rgb(255, 255, 255); box-shadow: 0px 0px 5px 0px rgba(120, 120, 120,0.5); margin: 10px; box-sizing: border-box; padding: 20px; }
Odder/OddRace
src/room/room.style.css
CSS
mit
382
<?php namespace ZPB\AdminBundle\Entity; use Doctrine\ORM\EntityRepository; /** * AnimationProgramRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class AnimationProgramRepository extends EntityRepository { public function animationsInMonth($month, $year = 2014) { $m = \DateTime::createFromFormat('j/n/Y', '1/'.$month.'/'.$year); $daysInMonth = (int)$m->format('t') + 1; $result = []; for($i = 1; $i < $daysInMonth; $i++){ $d = \DateTime::createFromFormat('Y/n/j',$year.'/'.$month.'/'.$i); $qb = $this->createQueryBuilder('p')->where('p.daytime = :theDate') ->setParameter('theDate', $d, \Doctrine\DBAL\Types\Type::DATE); $result[] = $qb->getQuery()->getOneOrNullResult(); } return $result; } public function getAnimationsInMonth($month, $year = 2014) { $programs = $this->animationsInMonth($month, $year); $result = ['error'=>false, 'message'=>'NO ERROR','year'=>$year, 'month'=>$month, 'days'=>[]]; foreach($programs as $prog){ if($prog != null){ /** @var \ZPB\AdminBundle\Entity\AnimationProgram $prog */ $days = $prog->getAnimationDays(); $tmp = []; foreach($days as $day){ /** @var \ZPB\AdminBundle\Entity\AnimationDay $day */ $tmp[] = $day->toArray(); } $result['days'][] = $tmp; } else { $result['days'][] = []; } } return $result; } }
Grosloup/multisite3
src/ZPB/AdminBundle/Entity/AnimationProgramRepository.php
PHP
mit
1,680
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ namespace lithium\tests\cases\net\http; use lithium\action\Request; use lithium\net\http\Route; use lithium\net\http\Router; use lithium\action\Response; class RouterTest extends \lithium\test\Unit { public $request = null; protected $_routes = array(); public function setUp() { $this->request = new Request(); $this->_routes = Router::get(); Router::reset(); } public function tearDown() { Router::reset(); foreach ($this->_routes as $route) { Router::connect($route); } } public function testBasicRouteConnection() { $result = Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $expected = array( 'template' => '/hello', 'pattern' => '@^/hello$@', 'params' => array('controller' => 'posts', 'action' => 'index'), 'match' => array('controller' => 'posts', 'action' => 'index'), 'meta' => array(), 'persist' => array('controller'), 'defaults' => array(), 'keys' => array(), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); $result = Router::connect('/{:controller}/{:action}', array('action' => 'view')); $this->assertTrue($result instanceof Route); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\\/]+))(?:/(?P<action>[^\\/]+)?)?$@', 'params' => array('action' => 'view'), 'defaults' => array('action' => 'view'), 'match' => array(), 'meta' => array(), 'persist' => array('controller'), 'keys' => array('controller' => 'controller', 'action' => 'action'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } /** * Tests generating routes with required parameters which are not present in the URL. * * @return void */ public function testConnectingWithRequiredParams() { $result = Router::connect('/{:controller}/{:action}', array( 'action' => 'view', 'required' => true )); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\\/]+))(?:/(?P<action>[^\\/]+)?)?$@', 'keys' => array('controller' => 'controller', 'action' => 'action'), 'params' => array('action' => 'view', 'required' => true), 'defaults' => array('action' => 'view'), 'match' => array('required' => true), 'meta' => array(), 'persist' => array('controller'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } public function testConnectingWithDefaultParams() { $result = Router::connect('/{:controller}/{:action}', array('action' => 'archive')); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\/]+))(?:/(?P<action>[^\/]+)?)?$@', 'keys' => array('controller' => 'controller', 'action' => 'action'), 'params' => array('action' => 'archive'), 'match' => array(), 'meta' => array(), 'persist' => array('controller'), 'defaults' => array('action' => 'archive'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } /** * Tests basic options for connecting routes. * * @return void */ public function testBasicRouteMatching() { Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $expected = array('controller' => 'posts', 'action' => 'index'); foreach (array('/hello/', '/hello', 'hello/', 'hello') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); $this->assertEqual(array('controller'), $result->persist); } } public function testRouteMatchingWithDefaultParameters() { Router::connect('/{:controller}/{:action}', array('action' => 'view')); $expected = array('controller' => 'posts', 'action' => 'view'); foreach (array('/posts/view', '/posts', 'posts', 'posts/view', 'posts/view/') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); $this->assertEqual(array('controller'), $result->persist); } $expected['action'] = 'index'; foreach (array('/posts/index', 'posts/index', 'posts/index/') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); } $this->request->url = '/posts/view/1'; $result = Router::parse($this->request); $this->assertNull($result); } /** * Tests that URLs specified as "Controller::action" are interpreted properly. * * @return void */ public function testStringActions() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'create')); Router::connect('/{:controller}/{:action}'); $result = Router::match("Sessions::create"); $this->assertEqual('/login', $result); $result = Router::match("Posts::index"); $this->assertEqual('/posts', $result); $result = Router::match("ListItems::archive"); $this->assertEqual('/list_items/archive', $result); } public function testNamedAnchor() { Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match(array('Posts::edit', '#' => 'foo')); $this->assertEqual('/posts/edit#foo', $result); $result = Router::match(array('Posts::edit', 'id' => 42, '#' => 'foo')); $this->assertEqual('/posts/edit/42#foo', $result); $result = Router::match(array('controller' => 'users', 'action' => 'view', '#' => 'blah')); $this->assertEqual('/users/view#blah', $result); $result = Router::match(array( 'controller' => 'users', 'action' => 'view', 'id' => 47, '#' => 'blargh' )); $this->assertEqual('/users/view/47#blargh', $result); } public function testQueryString() { Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match(array('Posts::edit', '?' => array('key' => 'value'))); $this->assertEqual('/posts/edit?key=value', $result); $result = Router::match(array( 'Posts::edit', 'id' => 42, '?' => array('key' => 'value', 'test' => 'foo') )); $this->assertEqual('/posts/edit/42?key=value&test=foo', $result); } /** * Tests that URLs specified as "Controller::action" and including additional parameters are * interpreted properly. * * @return void */ public function testEmbeddedStringActions() { Router::connect('/logout/{:id:[0-9]{5,6}}', array( 'controller' => 'sessions', 'action' => 'destroy', 'id' => null )); Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match("Sessions::create"); $this->assertEqual('/sessions/create', $result); $result = Router::match(array("Sessions::create")); $this->assertEqual('/sessions/create', $result); $result = Router::match(array("Sessions::destroy", 'id' => '03815')); $this->assertEqual('/logout/03815', $result); $result = Router::match("Posts::index"); $this->assertEqual('/posts', $result); $ex = "No parameter match found for URL "; $ex .= "`('controller' => 'sessions', 'action' => 'create', 'id' => 'foo')`."; $this->expectException($ex); $result = Router::match(array("Sessions::create", 'id' => 'foo')); } /** * Tests that routes can be created with shorthand strings, i.e. `'Controller::action'` and * `array('Controller::action', 'id' => '...')`. * * @return void */ public function testStringParameterConnect() { Router::connect('/posts/{:id:[0-9a-f]{24}}', 'Posts::edit'); $result = Router::match(array( 'controller' => 'posts', 'action' => 'edit', 'id' => '4bbf25bd8ead0e5180130000' )); $expected = '/posts/4bbf25bd8ead0e5180130000'; $this->assertEqual($expected, $result); $ex = "No parameter match found for URL `("; $ex .= "'controller' => 'posts', 'action' => 'view', 'id' => '4bbf25bd8ead0e5180130000')`."; $this->expectException($ex); $result = Router::match(array( 'controller' => 'posts', 'action' => 'view', 'id' => '4bbf25bd8ead0e5180130000' )); } public function testShorthandParameterMatching() { Router::reset(); Router::connect('/posts/{:page:[0-9]+}', array('Posts::index', 'page' => '1')); $result = Router::match(array('controller' => 'posts', 'page' => '5')); $expected = '/posts/5'; $this->assertEqual($expected, $result); $result = Router::match(array('Posts::index', 'page' => '10')); $expected = '/posts/10'; $this->assertEqual($expected, $result); $request = new Request(array('url' => '/posts/13')); $result = Router::process($request); $expected = array('controller' => 'posts', 'action' => 'index', 'page' => '13'); $this->assertEqual($expected, $result->params); } /** * Tests that routing is fully reset when calling `Router::reset()`. * * @return void */ public function testResettingRoutes() { Router::connect('/{:controller}', array('controller' => 'posts')); $this->request->url = '/hello'; $expected = array('controller' => 'hello', 'action' => 'index'); $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); Router::reset(); $this->assertNull(Router::parse($this->request)); } /** * Tests matching routes where the route template is a static string with no insert parameters. */ public function testRouteMatchingWithNoInserts() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'add')); $result = Router::match(array('controller' => 'sessions', 'action' => 'add')); $this->assertEqual('/login', $result); $this->expectException( "No parameter match found for URL `('controller' => 'sessions', 'action' => 'index')`." ); Router::match(array('controller' => 'sessions', 'action' => 'index')); } /** * Test matching routes with only insert parameters and no default values. */ public function testRouteMatchingWithOnlyInserts() { Router::connect('/{:controller}'); $this->assertEqual('/posts', Router::match(array('controller' => 'posts'))); $this->expectException( "No parameter match found for URL `('controller' => 'posts', 'action' => 'view')`." ); Router::match(array('controller' => 'posts', 'action' => 'view')); } /** * Test matching routes with insert parameters which have default values. */ public function testRouteMatchingWithInsertsAndDefaults() { Router::connect('/{:controller}/{:action}', array('action' => 'archive')); $this->assertEqual('/posts', Router::match(array('controller' => 'posts'))); $result = Router::match(array('controller' => 'posts', 'action' => 'archive')); $this->assertEqual('/posts/archive', $result); Router::reset(); Router::connect('/{:controller}/{:action}', array('controller' => 'users')); $result = Router::match(array('action' => 'view')); $this->assertEqual('/users/view', $result); $result = Router::match(array('controller' => 'posts', 'action' => 'view')); $this->assertEqual('/posts/view', $result); $ex = "No parameter match found for URL "; $ex .= "`('controller' => 'posts', 'action' => 'view', 'id' => '2')`."; $this->expectException($ex); Router::match(array('controller' => 'posts', 'action' => 'view', 'id' => '2')); } /** * Tests matching routes and returning an absolute (protocol + hostname) URL. */ public function testRouteMatchAbsoluteUrl() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'add')); $result = Router::match('Sessions::add', $this->request); $base = $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('absolute' => true)); $base = $this->request->env('HTTPS') ? 'https://' : 'http://'; $base .= $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('host' => 'test.local', 'absolute' => true) ); $base = $this->request->env('HTTPS') ? 'https://' : 'http://'; $base .= 'test.local'; $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('scheme' => 'https://', 'absolute' => true) ); $base = 'https://' . $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('scheme' => 'https://', 'absolute' => true) ); $base = 'https://' . $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); } /** * Tests getting routes using `Router::get()`, and checking to see if the routes returned match * the routes connected. */ public function testRouteRetrieval() { $expected = Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $result = Router::get(0); $this->assertIdentical($expected, $result); list($result) = Router::get(); $this->assertIdentical($expected, $result); } public function testStringUrlGeneration() { $result = Router::match('/posts'); $expected = '/posts'; $this->assertEqual($expected, $result); $result = Router::match('/posts'); $this->assertEqual($expected, $result); $result = Router::match('/posts/view/5'); $expected = '/posts/view/5'; $this->assertEqual($expected, $result); $request = new Request(array('base' => '/my/web/path')); $result = Router::match('/posts', $request); $expected = '/my/web/path/posts'; $this->assertEqual($expected, $result); $request = new Request(array('base' => '/my/web/path')); $result = Router::match('/some/where', $request, array('absolute' => true)); $prefix = $this->request->env('HTTPS') ? 'https://' : 'http://'; $prefix .= $this->request->env('HTTP_HOST'); $this->assertEqual($prefix . '/my/web/path/some/where', $result); $result = Router::match('mailto:foo@localhost'); $expected = 'mailto:foo@localhost'; $this->assertEqual($expected, $result); $result = Router::match('#top'); $expected = '#top'; $this->assertEqual($expected, $result); } public function testWithWildcardString() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $expected = '/add'; $result = Router::match('/add'); $this->assertEqual($expected, $result); $expected = '/add/alke'; $result = Router::match('/add/alke'); $this->assertEqual($expected, $result); } public function testWithWildcardArray() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $expected = '/add'; $result = Router::match(array('controller' => 'tests', 'action' => 'add')); $this->assertEqual($expected, $result); $expected = '/add/alke'; $result = Router::match(array( 'controller' => 'tests', 'action' => 'add', 'args' => array('alke') )); $this->assertEqual($expected, $result); $expected = '/add/alke/php'; $result = Router::match(array( 'controller' => 'tests', 'action' => 'add', 'args' => array('alke', 'php') )); $this->assertEqual($expected, $result); } public function testProcess() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $request = Router::process(new Request(array('url' => '/add/foo/bar'))); $params = array('controller' => 'tests', 'action' => 'add', 'args' => array('foo', 'bar')); $this->assertEqual($params, $request->params); $this->assertEqual(array('controller'), $request->persist); $request = Router::process(new Request(array('url' => '/remove/foo/bar'))); $this->assertFalse($request->params); } /** * Tests that the order of the parameters is respected so it can trim * the URL correctly. */ public function testParameterOrderIsRespected() { Router::connect('/{:locale}/{:controller}/{:action}/{:args}'); Router::connect('/{:controller}/{:action}/{:args}'); $request = Router::process(new Request(array('url' => 'posts'))); $url = Router::match('Posts::index', $request); $this->assertEqual($this->request->env('base') . '/posts', $url); $request = Router::process(new Request(array('url' => 'fr/posts'))); $params = array('Posts::index', 'locale' => 'fr'); $url = Router::match($params, $request); $this->assertEqual($this->request->env('base') . '/fr/posts', $url); } /** * Tests that a request context with persistent parameters generates URLs where those parameters * are properly taken into account. */ public function testParameterPersistence() { Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array(), array( 'persist' => array('controller', 'id') )); // URLs generated with $request will now have the 'controller' and 'id' // parameters copied to new URLs. $request = Router::process(new Request(array('url' => 'posts/view/1138'))); $params = array('action' => 'edit'); $url = Router::match($params, $request); // Returns: '/posts/edit/1138' $this->assertEqual($this->request->env('base') . '/posts/edit/1138', $url); Router::connect( '/add/{:args}', array('controller' => 'tests', 'action' => 'add'), array('persist' => array('controller', 'action')) ); $request = Router::process(new Request(array('url' => '/add/foo/bar', 'base' => ''))); $path = Router::match(array('args' => array('baz', 'dib')), $request); $this->assertEqual('/add/baz/dib', $path); } /** * Tests that persistent parameters can be overridden with nulled-out values. */ public function testOverridingPersistentParameters() { Router::connect( '/admin/{:controller}/{:action}', array('admin' => true), array('persist' => array('admin', 'controller')) ); Router::connect('/{:controller}/{:action}'); $request = Router::process(new Request(array('url' => '/admin/posts/add', 'base' => ''))); $expected = array('controller' => 'posts', 'action' => 'add', 'admin' => true); $this->assertEqual($expected, $request->params); $this->assertEqual(array('admin', 'controller'), $request->persist); $url = Router::match(array('action' => 'archive'), $request); $this->assertEqual('/admin/posts/archive', $url); $url = Router::match(array('action' => 'archive', 'admin' => null), $request); $this->assertEqual('/posts/archive', $url); } /** * Tests passing a closure handler to `Router::connect()` to bypass or augment default * dispatching. * * @return void */ public function testRouteHandler() { Router::connect('/login', 'Users::login'); Router::connect('/users/login', array(), function($request) { return new Response(array( 'location' => array('controller' => 'users', 'action' => 'login') )); }); $result = Router::process(new Request(array('url' => '/users/login'))); $this->assertTrue($result instanceof Response); $headers = array('location' => '/login'); $this->assertEqual($headers, $result->headers); } /** * Tests that a successful match against a route with template `'/'` operating at the root of * a domain never returns an empty string. * * @return void */ public function testMatchingEmptyRoute() { Router::connect('/', 'Users::view'); $request = new Request(array('base' => '/')); $url = Router::match(array('controller' => 'users', 'action' => 'view'), $request); $this->assertEqual('/', $url); $request = new Request(array('base' => '')); $url = Router::match(array('controller' => 'users', 'action' => 'view'), $request); $this->assertEqual('/', $url); } /** * Tests routing based on content type extensions, with HTML being the default when types are * not defined. * * @return void */ public function testTypeBasedRouting() { Router::connect('/{:controller}/{:id:[0-9]+}', array( 'action' => 'index', 'type' => 'html', 'id' => null )); Router::connect('/{:controller}/{:id:[0-9]+}.{:type}', array( 'action' => 'index', 'id' => null )); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array( 'type' => 'html', 'id' => null )); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}.{:type}', array('id' => null)); $url = Router::match(array('controller' => 'posts', 'type' => 'html')); $this->assertEqual('/posts', $url); $url = Router::match(array('controller' => 'posts', 'type' => 'json')); $this->assertEqual('/posts.json', $url); } /** * Tests that routes can be connected and correctly match based on HTTP headers or method verbs. * * @return void */ public function testHttpMethodBasedRouting() { Router::connect('/{:controller}/{:id:[0-9]+}', array( 'http:method' => 'GET', 'action' => 'view' )); Router::connect('/{:controller}/{:id:[0-9]+}', array( 'http:method' => 'PUT', 'action' => 'edit' )); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'GET' ))); $params = Router::process($request)->params; $expected = array('controller' => 'posts', 'action' => 'view', 'id' => '13'); $this->assertEqual($expected, $params); $this->assertEqual('/posts/13', Router::match($params)); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'PUT' ))); $params = Router::process($request)->params; $expected = array('controller' => 'posts', 'action' => 'edit', 'id' => '13'); $this->assertEqual($expected, $params); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'POST' ))); $params = Router::process($request)->params; $this->assertFalse($params); } /** * Tests that the class dependency configuration can be modified. * * @return void */ public function testCustomConfiguration() { $old = Router::config(); $config = array('classes' => array('route' => 'my\custom\Route')); Router::config($config); $this->assertEqual($config, Router::config()); Router::config($old); $this->assertEqual($old, Router::config()); } } ?>
WarToaster/HangOn
libraries/lithium/tests/cases/net/http/RouterTest.php
PHP
mit
22,379
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "stdafx.h" #include "CullDataVisualizer.h" #include "DXSampleHelper.h" using namespace DirectX; namespace { const wchar_t* s_boundingSphereMsFilename = L"BoundingSphereMS.cso"; const wchar_t* s_normalConeMsFilename = L"NormalConeMS.cso"; const wchar_t* s_debugDrawPsFilename = L"DebugDrawPS.cso"; std::wstring GetAssetFullPath(const wchar_t* path) { WCHAR assetsPath[512]; GetAssetsPath(assetsPath, _countof(assetsPath)); return std::wstring(assetsPath) + path; } } CullDataVisualizer::CullDataVisualizer() : m_constantData(nullptr) , m_frameIndex(0) { } void CullDataVisualizer::CreateDeviceResources(ID3D12Device2* device, DXGI_FORMAT rtFormat, DXGI_FORMAT dsFormat) { // Load shader bytecode and extract root signature struct { byte* data; uint32_t size; } normalConeMs, boundingSphereMs, pixelShader; ReadDataFromFile(GetAssetFullPath(s_normalConeMsFilename).c_str(), &normalConeMs.data, &normalConeMs.size); ReadDataFromFile(GetAssetFullPath(s_boundingSphereMsFilename).c_str(), &boundingSphereMs.data, &boundingSphereMs.size); ReadDataFromFile(GetAssetFullPath(s_debugDrawPsFilename).c_str(), &pixelShader.data, &pixelShader.size); ThrowIfFailed(device->CreateRootSignature(0, normalConeMs.data, normalConeMs.size, IID_PPV_ARGS(&m_rootSignature))); // Disable culling CD3DX12_RASTERIZER_DESC rasterDesc = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); rasterDesc.CullMode = D3D12_CULL_MODE_NONE; // Disable depth test & writes CD3DX12_DEPTH_STENCIL_DESC dsDesc = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); dsDesc.DepthEnable = false; dsDesc.StencilEnable = false; dsDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; // Populate the Mesh Shader PSO descriptor D3DX12_MESH_SHADER_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.PS = { pixelShader.data, pixelShader.size }; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = rtFormat; psoDesc.DSVFormat = dsFormat; psoDesc.RasterizerState = rasterDesc; psoDesc.DepthStencilState = dsDesc; psoDesc.SampleMask = UINT_MAX; psoDesc.SampleDesc = DefaultSampleDesc(); // Create normal cone pipeline { // Cone lines are drawn opaquely psoDesc.MS = { normalConeMs.data, normalConeMs.size }; psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); // Opaque auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc); // Populate the stream desc with our defined PSO descriptor D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {}; streamDesc.SizeInBytes = sizeof(meshStreamDesc); streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc; ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_normalConePso))); } // Create bounding sphere pipeline { // bounding sphere pipeline requires additive blending D3D12_BLEND_DESC blendDesc = {}; blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_MAX; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; psoDesc.MS = { boundingSphereMs.data, boundingSphereMs.size }; psoDesc.BlendState = blendDesc; auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc); // Populate the stream desc with our defined PSO descriptor D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {}; streamDesc.SizeInBytes = sizeof(meshStreamDesc); streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc; ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_boundingSpherePso))); } const CD3DX12_HEAP_PROPERTIES constantBufferHeapProps(D3D12_HEAP_TYPE_UPLOAD); const CD3DX12_RESOURCE_DESC constantBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(Constants) * 2); // Create shared constant buffer ThrowIfFailed(device->CreateCommittedResource( &constantBufferHeapProps, D3D12_HEAP_FLAG_NONE, &constantBufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_constantResource) )); ThrowIfFailed(m_constantResource->Map(0, nullptr, &m_constantData)); } void CullDataVisualizer::ReleaseResources() { m_rootSignature.Reset(); m_boundingSpherePso.Reset(); m_normalConePso.Reset(); m_constantResource.Reset(); } void CullDataVisualizer::SetConstants(FXMMATRIX world, CXMMATRIX view, CXMMATRIX proj, CXMVECTOR color) { m_frameIndex = (m_frameIndex + 1) % 2; XMVECTOR scl, rot, pos; XMMatrixDecompose(&scl, &rot, &pos, world); XMMATRIX viewToWorld = XMMatrixTranspose(view); XMVECTOR camUp = XMVector3TransformNormal(g_XMIdentityR1, viewToWorld); // Y-axis is up direction XMVECTOR camForward = XMVector3TransformNormal(g_XMNegIdentityR2, viewToWorld); // -Z-axis is forward direction auto& constants = *(reinterpret_cast<Constants*>(m_constantData) + m_frameIndex); XMStoreFloat4x4(&constants.ViewProj, XMMatrixTranspose(view * proj)); XMStoreFloat4x4(&constants.World, XMMatrixTranspose(world)); XMStoreFloat4(&constants.Color, color); XMStoreFloat4(&constants.ViewUp, camUp); XMStoreFloat3(&constants.ViewForward, camForward); constants.Scale = XMVectorGetX(scl); constants.Color.w = 0.3f; } void CullDataVisualizer::Draw(ID3D12GraphicsCommandList6* commandList, const Mesh& mesh, uint32_t offset, uint32_t count) { // Push constant data to GPU for our shader invocations assert(offset + count <= static_cast<uint32_t>(mesh.Meshlets.size())); // Shared root signature between two shaders commandList->SetGraphicsRootSignature(m_rootSignature.Get()); commandList->SetGraphicsRootConstantBufferView(0, m_constantResource->GetGPUVirtualAddress() + sizeof(Constants) * m_frameIndex); commandList->SetGraphicsRoot32BitConstant(1, offset, 0); commandList->SetGraphicsRoot32BitConstant(1, count, 1); commandList->SetGraphicsRootShaderResourceView(2, mesh.CullDataResource->GetGPUVirtualAddress()); // Dispatch bounding sphere draw commandList->SetPipelineState(m_boundingSpherePso.Get()); commandList->DispatchMesh(count, 1, 1); // Dispatch normal cone draw commandList->SetPipelineState(m_normalConePso.Get()); commandList->DispatchMesh(count, 1, 1); }
SuperWangKai/DirectX-Graphics-Samples
Samples/Desktop/D3D12MeshShaders/src/MeshletCull/CullDataVisualizer.cpp
C++
mit
7,493
#ifndef FUDGE_LOAD_MATRIX_H_ #define FUDGE_LOAD_MATRIX_H_ #include <string> #include <vector> #include <fstream> #include "util/log.h" namespace fudge { template <typename WeightType> static std::vector<WeightType> load_matrix(const std::string &filename) { std::vector<WeightType> v; std::ifstream ifs(filename); if(ifs.is_open()) { while(ifs.good()) { std::string line; getline(ifs, line); std::istringstream ss(line); std::string s; while (getline(ss, s, ',' ) && s.find_first_not_of(" \t\r\n") != s.npos ) { std::istringstream is(s); WeightType i; is >> i; v.push_back(i); } } } else { ERROR("File not found.\n"); } return v; } } #endif /* FUDGE_LOAD_MATRIX_H_ */
silmerusse/fudge_pathfinding
include/load_matrix.h
C
mit
776
package com.wrapper.spotify.requests.data.player; import com.wrapper.spotify.TestUtil; import com.wrapper.spotify.enums.CurrentlyPlayingType; import com.wrapper.spotify.enums.ModelObjectType; import com.wrapper.spotify.exceptions.SpotifyWebApiException; import com.wrapper.spotify.model_objects.miscellaneous.CurrentlyPlaying; import com.wrapper.spotify.model_objects.specification.Episode; import com.wrapper.spotify.model_objects.specification.Track; import com.wrapper.spotify.requests.data.AbstractDataTest; import org.apache.hc.core5.http.ParseException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.class) public class GetUsersCurrentlyPlayingTrackRequestTest extends AbstractDataTest<CurrentlyPlaying> { private final GetUsersCurrentlyPlayingTrackRequest defaultRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/player/GetUsersCurrentlyPlayingTrackRequest.json")) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); private final GetUsersCurrentlyPlayingTrackRequest defaultEpisodeRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/player/GetUsersCurrentlyPlayingTrackRequest_Episode.json")) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); private final GetUsersCurrentlyPlayingTrackRequest emptyRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson(null)) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); public GetUsersCurrentlyPlayingTrackRequestTest() throws Exception { } @Test public void shouldComplyWithReference() { assertHasAuthorizationHeader(defaultRequest); assertEquals( "https://api.spotify.com:443/v1/me/player/currently-playing?market=SE&additional_types=track%2Cepisode", defaultRequest.getUri().toString()); } @Test public void shouldReturnDefault_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefault(defaultRequest.execute()); } @Test public void shouldReturnDefault_async() throws ExecutionException, InterruptedException { shouldReturnDefault(defaultRequest.executeAsync().get()); } public void shouldReturnDefault(final CurrentlyPlaying currentlyPlaying) { assertNull( currentlyPlaying.getContext()); assertEquals( 1516669900630L, (long) currentlyPlaying.getTimestamp()); assertEquals( 78810, (int) currentlyPlaying.getProgress_ms()); assertFalse( currentlyPlaying.getIs_playing()); assertNotNull( currentlyPlaying.getItem()); assertTrue( currentlyPlaying.getItem() instanceof Track); assertNotNull( currentlyPlaying.getActions()); assertEquals( 4, currentlyPlaying.getActions().getDisallows().getDisallowedActions().size()); assertEquals( CurrentlyPlayingType.TRACK, currentlyPlaying.getCurrentlyPlayingType()); } @Test public void shouldReturnDefaultEpisode_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefaultEpisode(defaultEpisodeRequest.execute()); } @Test public void shouldReturnDefaultEpisode_async() throws ExecutionException, InterruptedException { shouldReturnDefaultEpisode(defaultEpisodeRequest.executeAsync().get()); } public void shouldReturnDefaultEpisode(final CurrentlyPlaying currentlyPlaying) { assertEquals( 1516669848357L, (long) currentlyPlaying.getTimestamp()); assertNotNull( currentlyPlaying.getContext()); assertEquals( currentlyPlaying.getContext().getType(), ModelObjectType.SHOW); assertEquals( 3636145, (int) currentlyPlaying.getProgress_ms()); assertNotNull( currentlyPlaying.getItem()); assertTrue( currentlyPlaying.getItem() instanceof Episode); assertEquals( CurrentlyPlayingType.EPISODE, currentlyPlaying.getCurrentlyPlayingType()); assertNotNull( currentlyPlaying.getActions()); assertEquals( 4, currentlyPlaying.getActions().getDisallows().getDisallowedActions().size()); assertTrue( currentlyPlaying.getIs_playing()); } @Test public void shouldReturnEmpty_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnEmpty(emptyRequest.execute()); } @Test public void shouldReturnEmpty_async() throws ExecutionException, InterruptedException { shouldReturnEmpty(emptyRequest.executeAsync().get()); } public void shouldReturnEmpty(final CurrentlyPlaying currentlyPlaying) { assertNull( currentlyPlaying); } }
thelinmichael/spotify-web-api-java
src/test/java/com/wrapper/spotify/requests/data/player/GetUsersCurrentlyPlayingTrackRequestTest.java
Java
mit
4,985
package org.javacs.rewrite; /** JavaType represents a potentially parameterized named type. */ public class JavaType { final String name; final JavaType[] parameters; public JavaType(String name, JavaType[] parameters) { this.name = name; this.parameters = parameters; } }
georgewfraser/vscode-javac
src/main/java/org/javacs/rewrite/JavaType.java
Java
mit
307
/* * Copyright (c) 2018 Rain Agency <contact@rain.agency> * Author: Rain Agency <contact@rain.agency> * * 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. */ export function toSSML(statement?: string): string | undefined { if (!statement) { return undefined; } if (statement.startsWith("<speak>")) { return statement; } // Hack. Full xml escaping would be better, but the & is currently the only special character used. statement = statement.replace(/&/g, "&amp;"); return `<speak>${statement}</speak>`; }
armonge/voxa
src/ssml.ts
TypeScript
mit
1,552
MRuby::Build.new do |conf| toolchain :gcc conf.gembox 'default' conf.gem '../m-activerecord' conf.enable_test end
yasuyuki/m-activerecord
.travis_build_config.rb
Ruby
mit
122
$(document).ready(function(){ var nav = navigator.userAgent.toLowerCase(); //La variable nav almacenará la información del navegador del usuario if(nav.indexOf("firefox") != -1){ //En caso de que el usuario este usando el navegador MozillaFirefox $("#fecha_inicio").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput $("#fecha_fin").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput } $("#accordion").on("show.bs.collapse", ".collapse", function(e){ $(this).parent(".panel").find(".panel-heading .panel-title a span").removeClass("glyphicon-plus").addClass("glyphicon-minus"); }); $("#accordion").on("hide.bs.collapse", ".collapse", function(e){ $(this).parent(".panel").find(".panel-heading .panel-title a span").addClass("glyphicon-plus").removeClass("glyphicon-minus"); }); $("#hora_inicio").mask("99:99",{placeholder:"00:00"}); $("#hora_fin").mask("99:99",{placeholder:"00:00"}); $('#registro-evento').validator(); $("#registro-evento").on("submit", function(){ $(this).attr("disabled","disabled"); $('#seccion2').animate({scrollTop : 0}, 500); }); $("#imagen").fileinput({ language: "es", fileType: "image", showUpload: false, browseLabel: 'Examinar &hellip;', removeLabel: 'Remover' }); $("#img-change").on("click", function(){ if ($("#img-change").is(":checked")) { $("#imagen-content figure").hide(); $("#imagen-content h4").hide(); $("#imagen-content .form-group").removeClass("hidden"); }else{ $("#imagen-content figure").show(); $("#imagen-content h4").show(); $("#imagen-content .form-group").addClass("hidden"); } }); });
JoseSoto33/proyecto-sismed
assets/js/funciones-formulario-evento.js
JavaScript
mit
1,944
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["shared-components"] = factory(require("react")); else root["shared-components"] = factory(root["react"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var NumberPicker = function (_React$Component) { _inherits(NumberPicker, _React$Component); function NumberPicker(props) { _classCallCheck(this, NumberPicker); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(NumberPicker).call(this, props)); _this.MAX_VALUE = _this.maxValue(); return _this; } _createClass(NumberPicker, [{ key: "maxValue", value: function maxValue() { var str_max = ""; for (var i = 0; i < this.props.digits; i++) { str_max += "9"; }if (this.props.showDecimal) str_max += ".99"; return parseFloat(str_max); } }, { key: "digitInteger", value: function digitInteger(ltr_digit) { var sValue = this.props.value.toString(); var a_sValue = sValue.split("."); var integer = a_sValue[0]; var rtl_digit = this.props.digits - (ltr_digit - 1); if (rtl_digit > integer.length) return "0"; return integer[integer.length - rtl_digit]; } }, { key: "digitDecimal", value: function digitDecimal(ltr_digit) { var sValue = this.props.value.toString(); var a_sValue = sValue.split("."); var decimal = a_sValue.length > 1 && a_sValue[1].length > 0 ? a_sValue[1] : "00"; if (decimal.length > 2) decimal = decimal.substr(0, 2); if (decimal.length < 2) decimal = decimal + "0"; return decimal[ltr_digit - 1]; } }, { key: "modifyValue", value: function modifyValue(type, value, event) { event.preventDefault(); if (!this.props.onChange) return; var value_to_add = type === "down" ? value * -1 : value; var new_value = this.props.value + value_to_add; /* adjust float operations */ var str_new_value = this.props.showDecimal ? new_value.toFixed(2) : new_value.toFixed(0); var adjusted_new_value = parseFloat(str_new_value); /* dont work with negative values, YET */ if (adjusted_new_value < 0) adjusted_new_value = 0; /* prevent from exceed maximum possible values */ if (adjusted_new_value > this.MAX_VALUE) adjusted_new_value = this.MAX_VALUE; this.props.onChange(adjusted_new_value); } }, { key: "renderButtons", value: function renderButtons(type) { var elements = []; /* display an invisible cell */ if (this.props.currency) { elements.push(_react2.default.createElement("div", { key: "currency", className: "NumberPicker__cell button" })); } /* display tob/bottom buttons */ for (var i = 0; i < this.props.digits; i++) { var value_to_add = Math.pow(10, this.props.digits - i - 1); elements.push(_react2.default.createElement( "div", { key: "integer-" + i, className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, value_to_add) }) )); } /* display invisible cell to decimal separator and tob/bottom buttons for decimals */ if (this.props.showDecimal) { elements.push(_react2.default.createElement("div", { key: "decimal-separator", className: "NumberPicker__cell decimal-separator" })); elements.push(_react2.default.createElement( "div", { key: "decimal-1", className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.1) }) )); elements.push(_react2.default.createElement( "div", { key: "decimal-2", className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.01) }) )); } return elements; } }, { key: "renderDigits", value: function renderDigits() { var elements = []; if (this.props.currency) { elements.push(_react2.default.createElement( "div", { key: "currency", className: "NumberPicker__cell currency" }, _react2.default.createElement( "span", { className: "currency" }, this.props.currency ) )); } for (var i = 0; i < this.props.digits; i++) { var digit = i + 1; elements.push(_react2.default.createElement( "div", { key: digit, className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitInteger(digit) ) )); } if (this.props.showDecimal) { elements.push(_react2.default.createElement( "div", { key: "decimal-separator", className: "NumberPicker__cell decimal-separator" }, _react2.default.createElement( "span", { className: "decimal-separator" }, this.props.decimalSeparator ) )); elements.push(_react2.default.createElement( "div", { key: "decimal-1", className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitDecimal(1) ) )); elements.push(_react2.default.createElement( "div", { key: "decimal-2", className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitDecimal(2) ) )); } return elements; } }, { key: "render", value: function render() { return _react2.default.createElement( "div", { className: "NumberPicker__wrapper" }, _react2.default.createElement( "div", { className: "NumberPicker__table" }, _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderButtons("up") ), _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderDigits() ), _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderButtons("down") ) ) ); } }]); return NumberPicker; }(_react2.default.Component); NumberPicker.propTypes = { onChange: _react2.default.PropTypes.func, digits: _react2.default.PropTypes.number.isRequired, currency: _react2.default.PropTypes.string, value: _react2.default.PropTypes.number.isRequired, showDecimal: _react2.default.PropTypes.bool.isRequired, decimalSeparator: _react2.default.PropTypes.string.isRequired }; NumberPicker.defaultProps = { digits: 1, currency: null, value: 0.00, decimalSeparator: ".", showDecimal: false }; exports.default = NumberPicker; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ } /******/ ]) }); ;
mrlew/react-number-picker
dist/react-number-picker.js
JavaScript
mit
10,328
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | WARNING: You MUST set this value! | | If it is not set, then CodeIgniter will try guess the protocol and path | your installation, but due to security concerns the hostname will be set | to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise. | The auto-detection mechanism exists only for convenience during | development and MUST NOT be used in production! | | If you need to allow multiple domains, remember that this file is still | a PHP script and you can easily do that on your own. | */ $config['base_url'] = 'http://training_ci.happy.cba/'; //$config['base_url'] = 'http://localhost:81/Training_CI-master/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | WARNING: If you're using the database driver, don't forget to update | your session table's PRIMARY KEY when changing this setting. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. | | This is particularly useful for portability between UNIX-based OSes, | (usually \n) and Windows (\r\n). | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | | Note: You need to have eval() enabled for this to work. | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
DeRossi/Training_CI
application/config/config.php
PHP
mit
18,210
import json import re from pygeocoder import Geocoder from pygeolib import GeocoderError import requests # from picasso.index.models import Tag from picasso.index.models import Address, Listing, Tag __author__ = 'tmehta' url = 'http://www.yellowpages.ca/ajax/search/music+teachers/Toronto%2C+ON?sType=si&sort=rel&pg=1&' + \ 'skipNonPaids=56&trGeo=43.797452066539165,-79.15031040820315&blGeo=43.55112164714018,-79.6419485917969' base_url = 'http://www.yellowpages.ca/bus/' city = 'Toronto' def extract_cats(p): try: p_s = p.split('Products and Services</h3>')[1].split('</span>')[0].replace('<span>', '') except IndexError: return [] p_s = p_s.split("'>")[1:] cats = [] for line in p_s: cats.append(line.split('</li>')[0]) return cats def extract_phone(p): try: phone = p.split('class="phone"')[1].split('<span >')[1].split('</span>')[0] except IndexError: phone = '' return phone r = requests.get(url) listings = json.loads(r.text)['features'] for l in listings: name = l['properties']['name'] scraped_url = base_url + str(l['properties']['id']) + '.html' try: lst = Listing.objects.get(scraped_url=scraped_url) page = requests.get(scraped_url).text try: location = page.split('itemprop="streetAddress">')[1].split('</span>')[0] except IndexError: location = '' try: postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0] except IndexError: postalCode = '' lat = l["geometry"]["coordinates"][0] lon = l["geometry"]["coordinates"][1] point = "POINT(%s %s)" % (lon, lat) lst.address.point = point lst.save() except Listing.DoesNotExist: active = True place = 'Sch' email = '' page = requests.get(scraped_url).text categories = extract_cats(page) tags = [] for cat in categories: t = Tag.objects.get_or_create(tag_name=cat) phone_number = extract_phone(page) try: location = page.split('itemprop="streetAddress">')[1].split('</span>')[0] except IndexError: location = '' try: postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0] except IndexError: postalCode = '' try: description = page.split('itemprop="description">')[1].split('</article>')[0].split('<a href')[0].replace( '<span', '').replace('</span>', '') except IndexError: description = '' lat = l["geometry"]["coordinates"][0] lon = l["geometry"]["coordinates"][1] point = "POINT(%s %s)" % (lon, lat) add = Address.objects.create(location=location, postal_code=postalCode, city=city, point=point) lst = Listing.objects.create(address=add, listing_name=name, scraped_url=scraped_url, description=description, phone=phone_number) for t in tags: lst.tags.add(t) lst.save()
TejasM/picasso
picasso/yellow_pages.py
Python
mit
3,125
require 'timeout' require 'spec_helper' shared_examples 'using a mysql database' do before :all do within 'form#jira-setup-database' do # select using external database choose 'jira-setup-database-field-database-external' # allow some time for the DOM to change sleep 1 # fill in database configuration select "MySQL", from: 'jira-setup-database-field-database-type' fill_in 'jdbcHostname', with: @container_db.host fill_in 'jdbcPort', with: '3306' fill_in 'jdbcDatabase', with: 'jiradb' fill_in 'jdbcUsername', with: 'root' fill_in 'jdbcPassword', with: 'mysecretpassword' # continue database setup click_button 'Next' end end end
wpxgit/docker-atlassian-jira
spec/support/shared_examples/using_a_mysql_database_shared_example.rb
Ruby
mit
678