text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
    public class EnumAndCompletionListTagCompletionProviderTests : AbstractCSharpCompletionProviderTests
    {
        public EnumAndCompletionListTagCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
        {
        }

        internal override CompletionProvider CreateCompletionProvider()
            => new EnumAndCompletionListTagCompletionProvider();

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NullableEnum()
        {
            var markup = @"class Program
{
    static void Main(string[] args)
    {
        Colors? d = $$
        Colors c = Colors.Blue;
    }
}

enum Colors
{
    Red,
    Blue,
    Green,
}
";
            await VerifyItemExistsAsync(markup, "Colors");
        }

        [Fact]
        [WorkItem(545678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")]
        [Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task EditorBrowsable_EnumMemberAlways()
        {
            var markup = @"
class Program
{
    public void M()
    {
        Goo d = $$
    }
}
";
            var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public enum Goo
{
    Member
}";
            await VerifyItemInEditorBrowsableContextsAsync(
                markup: markup,
                referencedCode: referencedCode,
                item: "Goo",
                expectedSymbolsSameSolution: 1,
                expectedSymbolsMetadataReference: 1,
                sourceLanguage: LanguageNames.CSharp,
                referencedLanguage: LanguageNames.CSharp);
        }

        [Fact]
        [WorkItem(545678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")]
        [Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task EditorBrowsable_EnumMemberNever()
        {
            var markup = @"
class Program
{
    public void M()
    {
        Goo d = $$
    }
}
";
            var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum Goo
{
    Member
}";
            await VerifyItemInEditorBrowsableContextsAsync(
                markup: markup,
                referencedCode: referencedCode,
                item: "Goo",
                expectedSymbolsSameSolution: 1,
                expectedSymbolsMetadataReference: 0,
                sourceLanguage: LanguageNames.CSharp,
                referencedLanguage: LanguageNames.CSharp);
        }

        [Fact]
        [WorkItem(545678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")]
        [Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task EditorBrowsable_EnumMemberAdvanced()
        {
            var markup = @"
class Program
{
    public void M()
    {
        Goo d = $$
    }
}
";
            var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public enum Goo
{
    Member
}";
            await VerifyItemInEditorBrowsableContextsAsync(
                markup: markup,
                referencedCode: referencedCode,
                item: "Goo",
                expectedSymbolsSameSolution: 1,
                expectedSymbolsMetadataReference: 0,
                sourceLanguage: LanguageNames.CSharp,
                referencedLanguage: LanguageNames.CSharp,
                hideAdvancedMembers: true);

            await VerifyItemInEditorBrowsableContextsAsync(
                markup: markup,
                referencedCode: referencedCode,
                item: "Goo",
                expectedSymbolsSameSolution: 1,
                expectedSymbolsMetadataReference: 1,
                sourceLanguage: LanguageNames.CSharp,
                referencedLanguage: LanguageNames.CSharp,
                hideAdvancedMembers: false);
        }

        [WorkItem(854099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854099")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInComment()
        {
            var markup = @"class Program
{
    static void Main(string[] args)
    {
        Colors c = // $$
    }
}

enum Colors
{
    Red,
    Blue,
    Green,
}
";
            await VerifyNoItemsExistAsync(markup);
        }

        [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InYieldReturnInMethod()
        {
            var markup =
@"using System;
using System.Collections.Generic;

class Program
{
    IEnumerable<DayOfWeek> M()
    {
        yield return $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [WorkItem(30235, "https://github.com/dotnet/roslyn/issues/30235")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InYieldReturnInLocalFunction()
        {
            var markup =
@"using System;
using System.Collections.Generic;

class Program
{
    void M()
    {
        IEnumerable<DayOfWeek> F()
        {
            yield return $$
        }
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InAsyncMethodReturnStatement()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

class Program
{
    async Task<DayOfWeek> M()
    {
        await Task.Delay(1);
        return $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InSimpleLambdaAfterArrow()
        {
            var markup =
@"using System;

class Program
{
    Func<bool, DayOfWeek> M()
    {
        return _ => $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InParenthesizedLambdaAfterArrow()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return () => $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInAnonymousMethodAfterParameterList()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return delegate () $$
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInSimpleLambdaAfterAsync()
        {
            var markup =
@"using System;

class Program
{
    Func<bool, DayOfWeek> M()
    {
        return async $$ _ =>
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInParenthesizedLambdaAfterAsync()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return async $$ () =>
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInAnonymousMethodAfterAsync()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return async $$ delegate ()
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInSimpleLambdaBlock()
        {
            var markup =
@"using System;

class Program
{
    Func<bool, DayOfWeek> M()
    {
        return _ => { $$ }
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInParenthesizedLambdaBlock()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return () => { $$ }
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInAnonymousMethodBlock()
        {
            var markup =
@"using System;

class Program
{
    Func<DayOfWeek> M()
    {
        return delegate () { $$ }
    }
}";
            await VerifyItemIsAbsentAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InExpressionTreeSimpleLambdaAfterArrow()
        {
            var markup =
@"using System;
using System.Linq.Expressions;

class Program
{
    Expression<Func<bool, DayOfWeek>> M()
    {
        return _ => $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InExpressionTreeParenthesizedLambdaAfterArrow()
        {
            var markup =
@"using System;
using System.Linq.Expressions;

class Program
{
    Expression<Func<DayOfWeek>> M()
    {
        return () => $$
    }
}";
            await VerifyItemExistsAsync(markup, "DayOfWeek");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NoCompletionListTag()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

class C
{

}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyNoItemsExistAsync(markup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task CompletionList()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

/// <completionlist cref=""C""/>
class C
{

}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyItemExistsAsync(markup, "C");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task CompletionListCrefToString()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

/// <completionlist cref=""string""/>
class C
{

}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyItemExistsAsync(markup, "string", glyph: (int)Glyph.ClassPublic);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task CompletionListEmptyCref()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

/// <completionlist cref=""""/>
class C
{

}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyNoItemsExistAsync(markup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task CompletionListInaccessibleType()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

/// <completionlist cref=""C.Inner""/>
class C
{
    private class Inner
    {
    }
}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyNoItemsExistAsync(markup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task CompletionListNotAType()
        {
            var markup =
@"using System;
using System.Threading.Tasks;

/// <completionlist cref=""C.Z()""/>
class C
{
    public void Z()
    {
    }
}

class Program
{
    void Goo()
    {
        C c = $$
    }
}";
            await VerifyNoItemsExistAsync(markup);
        }

        [WorkItem(828196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task SuggestAlias()
        {
            var markup = @"
using D = System.Globalization.DigitShapes;
class Program
{
    static void Main(string[] args)
    {
        D d=  $$
    }
}";
            await VerifyItemExistsAsync(markup, "D");
        }

        [WorkItem(828196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task SuggestAlias2()
        {
            var markup = @"
namespace N
{
using D = System.Globalization.DigitShapes;

class Program
{
    static void Main(string[] args)
    {
        D d=  $$
    }
}
}
";
            await VerifyItemExistsAsync(markup, "D");
        }

        [WorkItem(828196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task SuggestAlias3()
        {
            var markup = @"
namespace N
{
using D = System.Globalization.DigitShapes;

class Program
{
    private void Goo(System.Globalization.DigitShapes shape)
    {
    }

    static void Main(string[] args)
    {
        Goo($$
    }
}
}
";
            await VerifyItemExistsAsync(markup, "D");
        }

        [WorkItem(828196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotInParameterNameContext()
        {
            var markup = @"
enum E
{
    a
}

class C
{
    void goo(E first, E second)
    {
        goo(first: E.a, $$
    }
}
";
            await VerifyItemIsAbsentAsync(markup, "E");
        }

        [WorkItem(4310, "https://github.com/dotnet/roslyn/issues/4310")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InExpressionBodiedProperty()
        {
            var markup =
@"class C
{
    Colors Colors => $$
}

enum Colors
{
    Red,
    Blue,
    Green,
}
";
            await VerifyItemExistsAsync(markup, "Colors");
        }

        [WorkItem(4310, "https://github.com/dotnet/roslyn/issues/4310")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task InExpressionBodiedMethod()
        {
            var markup =
@"class C
{
    Colors GetColors() => $$
}

enum Colors
{
    Red,
    Blue,
    Green,
}
";
            await VerifyItemExistsAsync(markup, "Colors");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotAfterDot()
        {
            var markup =
@"namespace ConsoleApplication253
{
    class Program
    {
        static void Main(string[] args)
        {
            M(E.$$)
        }

        static void M(E e) { }
    }

    enum E
    {
        A,
        B,
    }
}
";
            await VerifyNoItemsExistAsync(markup);
        }

        [WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task NotAfterDotWithTextTyped()
        {
            var markup =
@"namespace ConsoleApplication253
{
    class Program
    {
        static void Main(string[] args)
        {
            M(E.a$$)
        }

        static void M(E e) { }
    }

    enum E
    {
        A,
        B,
    }
}
";
            await VerifyNoItemsExistAsync(markup);
        }

        [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task TestInEnumInitializer1()
        {
            var markup =
@"using System;

[Flags]
internal enum ProjectTreeWriterOptions
{
    None,
    Tags,
    FilePath,
    Capabilities,
    Visibility,
    AllProperties = FilePath | Visibility | $$
}";
            await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
        }

        [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task TestInEnumInitializer2()
        {
            var markup =
@"using System;

[Flags]
internal enum ProjectTreeWriterOptions
{
    None,
    Tags,
    FilePath,
    Capabilities,
    Visibility,
    AllProperties = FilePath | $$ Visibility
}";
            await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
        }

        [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task TestInEnumInitializer3()
        {
            var markup =
@"using System;

[Flags]
internal enum ProjectTreeWriterOptions
{
    None,
    Tags,
    FilePath,
    Capabilities,
    Visibility,
    AllProperties = FilePath | $$ | Visibility
}";
            await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
        }

        [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task TestInEnumInitializer4()
        {
            var markup =
@"using System;

[Flags]
internal enum ProjectTreeWriterOptions
{
    None,
    Tags,
    FilePath,
    Capabilities,
    Visibility,
    AllProperties = FilePath ^ $$
}";
            await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
        }

        [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
        [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
        public async Task TestInEnumInitializer5()
        {
            var markup =
@"using System;

[Flags]
internal enum ProjectTreeWriterOptions
{
    None,
    Tags,
    FilePath,
    Capabilities,
    Visibility,
    AllProperties = FilePath & $$
}";
            await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Advanced Sounding — MetPy 1.0</title>

  <link href="../_static/css/theme.css" rel="stylesheet" />
  <link href="../_static/css/index.f6b7ca918bee2f46fd9abac01cfb07d5.css" rel="stylesheet" />

  <link rel="stylesheet"
    href="../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery-rendered-html.css" />
    <link rel="stylesheet" type="text/css" href="../_static/theme-unidata.css" />

  <link rel="preload" as="script" href="../_static/js/index.1e043a052b0af929e4d8.js">

    <link rel="shortcut icon" href="../_static/metpy_32x32.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Cross Section Analysis" href="cross_section.html" />
    <link rel="prev" title="Sigma to Pressure Interpolation" href="sigma_to_pressure_interpolation.html" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="en" />
    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/examples/Advanced_Sounding.html" />

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-menu" aria-controls="navbar-menu" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Version 1.0

            User Guide

            Reference Guide

            Developer's Guide

            Example Gallery

            Support

            Release Notes

      <form class="bd-search d-flex align-items-center" action="../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

   XArray Projection Handling

   Sigma to Pressure Interpolation

   Advanced Sounding

   Cross Section Analysis

   Four Panel Map

   Isentropic Analysis

   Meteogram

   Parse angles

   Dewpoint and Mixing Ratio

   Angle to Direction

   Gradient

   Smoothing

   GINI Water Vapor Imagery

   NEXRAD Level 3 File

   NEXRAD Level 2 File

   Find Natural Neighbors Verification

   Wind and Sea Level Pressure Interpolation

   Point Interpolation

   Inverse Distance Verification: Cressman and Barnes

   Natural Neighbor Verification

   Simple Plotting

   US Counties

   Combined Plotting

   Upper Air Analysis using Declarative Syntax

   Surface Analysis using Declarative Syntax

   Skew-T with Complex Layout

   Hodograph Inset

   Simple Sounding

   Mesonet Station Plot

   Station Plot

   Station Plot with Layout

Note

Click here
to download the full example code

Advanced Sounding¶

Plot a sounding using MetPy with more advanced features.

Beyond just plotting data, this uses calculations from metpy.calc to find the lifted
condensation level (LCL) and the profile of a surface-based parcel. The area between the
ambient profile and the parcel profile is colored as well.

import matplotlib.pyplot as plt
import pandas as pd

import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, SkewT
from metpy.units import units

Upper air data can be obtained using the siphon package, but for this example we will use
some of MetPy's sample data.

col_names = ['pressure', 'height', 'temperature', 'dewpoint', 'direction', 'speed']

df = pd.read_fwf(get_test_data('may4_sounding.txt', as_file_obj=False),
                 skiprows=5, usecols=[0, 1, 2, 3, 6, 7], names=col_names)

# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature', 'dewpoint', 'direction', 'speed'), how='all'
               ).reset_index(drop=True)

We will pull the data out of the example dataset into individual variables and
assign units.

p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)

Create a new figure. The dimensions here give a good aspect ratio.

fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 115, 100)
skew = SkewT(fig, rotation=45)

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot.
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)
skew.ax.set_xlim(-40, 60)

# Calculate LCL height and plot as black dot. Because `p`'s first value is
# ~1000 mb and its last value is ~250 mb, the `0` index is selected for
# `p`, `T`, and `Td` to lift the parcel from the surface. If `p` was inverted,
# i.e. start from low value, 250 mb, to a high value, 1000 mb, the `-1` index
# should be selected.
lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

# Calculate full parcel profile and add to plot as black line
prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')
skew.plot(p, prof, 'k', linewidth=2)

# Shade areas of CAPE and CIN
skew.shade_cin(p, T, prof, Td)
skew.shade_cape(p, T, prof)

# An example of a slanted line at constant T -- in this case the 0
# isotherm
skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)

# Add the relevant special lines
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()

# Show the plot
plt.show()

Total running time of the script: ( 0 minutes  0.634 seconds)

Download Python source code: Advanced_Sounding.py

Download Jupyter notebook: Advanced_Sounding.ipynb

Gallery generated by Sphinx-Gallery

    Sigma to Pressure Interpolation
    Cross Section Analysis

          © Copyright 2008–2021, MetPy Developers. Development supported by National Science Foundation grants AGS-1344155, OAC-1740315, and AGS-1901712.

        Last updated on Apr 28, 2021 at 23:12:45.

        Created using Sphinx 3.5.4.

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace jk204\Torino\Types\Message;

class RPSMessageTest extends \PHPUnit_Framework_TestCase
{

	function testConstruct()
	{

		$message = new RPSMessage;

	}

}


text:
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;

namespace NetOffice.ExcelApi
{
	/// <summary>
	/// Interface ICalculatedMember
	/// SupportByVersion Excel, 10,11,12,14,15,16
	/// </summary>
	[SupportByVersion("Excel", 10,11,12,14,15,16)]
	[EntityType(EntityType.IsInterface)]
 	public class ICalculatedMember : COMObject
	{
		#pragma warning disable

		#region Type Information

        /// <summary>
        /// Instance Type
        /// </summary>
		[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
        public override Type InstanceType
        {
            get
            {
                return LateBindingApiWrapperType;
            }
        }

        private static Type _type;

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public static Type LateBindingApiWrapperType
        {
            get
            {
                if (null == _type)
                    _type = typeof(ICalculatedMember);
                return _type;
            }
        }

        #endregion

		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public ICalculatedMember(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public ICalculatedMember(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        ///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ICalculatedMember(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public NetOffice.ExcelApi.Application Application
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlCreator Creator
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// Unknown COM Proxy
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16), ProxyResult]
		public object Parent
		{
			get
			{
				return Factory.ExecuteReferencePropertyGet(this, "Parent");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public string Name
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "Name");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public string Formula
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "Formula");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public string SourceName
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "SourceName");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public Int32 SolveOrder
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "SolveOrder");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public bool IsValid
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "IsValid");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public string _Default
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "_Default");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlCalculatedMemberType Type
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCalculatedMemberType>(this, "Type");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 14,15,16)]
		public bool Dynamic
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "Dynamic");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 14,15,16)]
		public string DisplayFolder
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "DisplayFolder");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 14,15,16)]
		public bool HierarchizeDistinct
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "HierarchizeDistinct");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "HierarchizeDistinct", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 14,15,16)]
		public bool FlattenHierarchies
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "FlattenHierarchies");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "FlattenHierarchies", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 15,16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 15, 16)]
		public string MeasureGroup
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "MeasureGroup");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 15,16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 15, 16)]
		public string ParentHierarchy
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "ParentHierarchy");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 15,16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 15, 16)]
		public string ParentMember
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "ParentMember");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 15,16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 15, 16)]
		public NetOffice.ExcelApi.Enums.XlCalcMemNumberFormatType NumberFormat
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCalcMemNumberFormatType>(this, "NumberFormat");
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
		/// </summary>
		[SupportByVersion("Excel", 10,11,12,14,15,16)]
		public Int32 Delete()
		{
			return Factory.ExecuteInt32MethodGet(this, "Delete");
		}

		#endregion

		#pragma warning restore
	}
}


text:
using Discord;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace NadekoBot.Modules.CustomReactions
{
    public static class Extensions
    {
        public static Dictionary<string, Func<IUserMessage, string, string>> responsePlaceholders = new Dictionary<string, Func<IUserMessage, string, string>>()
        {
            {"%target%", (ctx, trigger) => { return ctx.Content.Substring(trigger.Length).Trim(); } }
        };

        public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>()
        {
            {"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser.Id}>"; } },
            {"%user%", (ctx) => { return ctx.Author.Mention; } },
            {"%rnduser%", (ctx) => {
                var ch = ctx.Channel as ITextChannel;
                if(ch == null)
                    return "";

                var usrs = (ch.Guild.GetUsersAsync().GetAwaiter().GetResult());

                return usrs.Skip(new NadekoRandom().Next(0,usrs.Count-1)).Shuffle().FirstOrDefault()?.Mention ?? "";
            } }
            //{"%rng%", (ctx) => { return new NadekoRandom().Next(0,10).ToString(); } }
        };

        private static readonly Regex rngRegex = new Regex("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%", RegexOptions.Compiled);

        private static readonly NadekoRandom rng = new NadekoRandom();

        public static Dictionary<Regex, MatchEvaluator> regexPlaceholders = new Dictionary<Regex, MatchEvaluator>()
        {
            { rngRegex, (match) => {
                int from = 0;
                int.TryParse(match.Groups["from"].ToString(), out from);

                int to = 0;
                int.TryParse(match.Groups["to"].ToString(), out to);

                if(from == 0 && to == 0)
                {
                    return rng.Next(0, 11).ToString();
                }

                if(from >= to)
                    return "";

                return rng.Next(from,to+1).ToString();
            } }
        };

        private static string ResolveTriggerString(this string str, IUserMessage ctx)
        {
            foreach (var ph in placeholders)
            {
                str = str.ToLowerInvariant().Replace(ph.Key, ph.Value(ctx));
            }
            return str;
        }

        private static string ResolveResponseString(this string str, IUserMessage ctx, string resolvedTrigger)
        {
            foreach (var ph in placeholders)
            {
                str = str.Replace(ph.Key.ToLowerInvariant(), ph.Value(ctx));
            }

            foreach (var ph in responsePlaceholders)
            {
                str = str.Replace(ph.Key.ToLowerInvariant(), ph.Value(ctx, resolvedTrigger));
            }

            foreach (var ph in regexPlaceholders)
            {
                str = ph.Key.Replace(str, ph.Value);
            }
            return str;
        }

        public static string TriggerWithContext(this CustomReaction cr, IUserMessage ctx)
            => cr.Trigger.ResolveTriggerString(ctx);

        public static string ResponseWithContext(this CustomReaction cr, IUserMessage ctx)
            => cr.Response.ResolveResponseString(ctx, cr.Trigger.ResolveTriggerString(ctx));
    }
}


text:
time
====

Single entry point for getting timestamps


text:
=============
URL Shortener
=============

.. module:: zinnia.url_shortener

.. versionadded:: 0.9

The URL shortening has becoming a big deal of the Internet especially for
transfering long URLs.

And so many URL shortening services exist, each with his own features.

Originally Zinnia provided a only way to generate short URLs for your
entries, and you needed to install mod:`django-bitly`.

One way it's not bad, but it's not enough.

Now Zinnia provides his own backend by default for making the URLs of the
entries shorter, example:

  http://mydomain.com/blog/2S/

This backend use the primary key of the entries, encoded in base 36 for
more privacy.

Of course the URL is short (and can be shorter) but if you have a long
domain, the URL can be not so short, example:

  http://mysuperverylongdomain.com/blog/15R/ (42 characters !)

But now you can easily change this behavior and use your favorite URL
shortener service by writing a backend shortening your URLs.

.. note:: The default backend is limited. When reaching the primary key
          **46656**, the short URLs generated enter in conflict with the
          archives by year.

          If you have reached this number of entries, it's effectively a
          good idea to change the default backend for a more scalable
          solution.

.. _writing-url-shortener:

Writing your own URL shortener backend
======================================

Writing a backend for using your custom URL shortener is simple as
possible, you only needs to follows 4 rules.

#. In a new Python file write a function named **backend** taking an
   :class:`~zinnia.models.entry.Entry` instance in parameters.

#. The **backend** function should returns an URL including the protocol
   and the domain.

#. If the **backend** requires initial configuration you must raise a
   :exc:`~django.core.exceptions.ImproperlyConfigured` exception if the
   configuration is not valid. The error will be displayed in the console.

#. Register your backend to be used in your project with this setting: ::

    ZINNIA_URL_SHORTENER_BACKEND = 'path.to.your.url.shortener.module'

Here the source code of the default backend. ::

    from django.contrib.sites.models import Site
    from django.core.urlresolvers import reverse
    from zinnia.settings import PROTOCOL

    def backend(entry):
        return '%s://%s%s' % (PROTOCOL, Site.objects.get_current().domain,
                              reverse('zinnia_entry_shortlink', args=[entry.pk]))

For a more examples take a look in this folder: :file:`zinnia/url_shortener/backends/`.


text:
<?php

/**
 * TOP API: taobao.udp.shop.get request
 *
 * @author auto create
 * @since  1.0, 2013-09-13 16:51:03
 */
class Taobao_Request_UdpShopGetRequest {
	/**
	 * 地区ID(参阅地区编号)
	 **/
	private $area;

	/**
	 * 开始时间
	 **/
	private $beginTime;

	/**
	 * 结束时间
	 **/
	private $endTime;

	/**
	 * 指标ID(参阅指标编号)
	 **/
	private $fields;

	/**
	 * 备用
	 **/
	private $parameters;

	private $apiParas = array();

	public function setArea($area) {
		$this->area = $area;
		$this->apiParas["area"] = $area;
	}

	public function getArea() {
		return $this->area;
	}

	public function setBeginTime($beginTime) {
		$this->beginTime = $beginTime;
		$this->apiParas["begin_time"] = $beginTime;
	}

	public function getBeginTime() {
		return $this->beginTime;
	}

	public function setEndTime($endTime) {
		$this->endTime = $endTime;
		$this->apiParas["end_time"] = $endTime;
	}

	public function getEndTime() {
		return $this->endTime;
	}

	public function setFields($fields) {
		$this->fields = $fields;
		$this->apiParas["fields"] = $fields;
	}

	public function getFields() {
		return $this->fields;
	}

	public function setParameters($parameters) {
		$this->parameters = $parameters;
		$this->apiParas["parameters"] = $parameters;
	}

	public function getParameters() {
		return $this->parameters;
	}

	public function getApiMethodName() {
		return "taobao.udp.shop.get";
	}

	public function getApiParas() {
		return $this->apiParas;
	}

	public function check() {

		Taobao_RequestCheckUtil::checkNotNull($this->area, "area");
		Taobao_RequestCheckUtil::checkNotNull($this->beginTime, "beginTime");
		Taobao_RequestCheckUtil::checkNotNull($this->endTime, "endTime");
		Taobao_RequestCheckUtil::checkNotNull($this->fields, "fields");
		Taobao_RequestCheckUtil::checkMaxListSize($this->fields, 10, "fields");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
import os
import mimetypes
import shutil
import zipfile

from django.conf import settings
from django.core.cache import cache
from django.core.files.storage import default_storage as storage
from django import forms

from mock import Mock, patch
from nose.tools import eq_

import amo.tests
from amo.urlresolvers import reverse
from files.helpers import FileViewer, DiffHelper
from files.models import File
from files.utils import SafeUnzip

root = os.path.join(settings.ROOT, 'apps/files/fixtures/files')

def get_file(filename):
    return os.path.join(root, filename)

def make_file(pk, file_path, **kwargs):
    obj = Mock()
    obj.id = pk
    for k, v in kwargs.items():
        setattr(obj, k, v)
    obj.file_path = file_path
    obj.current_file_path = file_path
    obj.__str__ = lambda x: x.pk
    obj.version = Mock()
    obj.version.version = 1
    return obj

class TestFileHelper(amo.tests.TestCase):

    def setUp(self):
        super(TestFileHelper, self).setUp()
        self.viewer = FileViewer(make_file(1, get_file('dictionary-test.xpi')))

    def tearDown(self):
        self.viewer.cleanup()
        super(TestFileHelper, self).tearDown()

    def test_files_not_extracted(self):
        eq_(self.viewer.is_extracted(), False)

    def test_files_extracted(self):
        self.viewer.extract()
        eq_(self.viewer.is_extracted(), True)

    def test_recurse_extract(self):
        self.viewer.src = get_file('recurse.xpi')
        self.viewer.extract()
        eq_(self.viewer.is_extracted(), True)

    def test_recurse_contents(self):
        self.viewer.src = get_file('recurse.xpi')
        self.viewer.extract()
        files = self.viewer.get_files()
        nm = ['recurse/recurse.xpi/chrome/test-root.txt',
              'recurse/somejar.jar/recurse/recurse.xpi/chrome/test.jar',
              'recurse/somejar.jar/recurse/recurse.xpi/chrome/test.jar/test']
        for name in nm:
            eq_(name in files, True, 'File %r not extracted' % name)

    def test_cleanup(self):
        self.viewer.extract()
        self.viewer.cleanup()
        eq_(self.viewer.is_extracted(), False)

    def test_isbinary(self):
        binary = self.viewer._is_binary
        for f in ['foo.rdf', 'foo.xml', 'foo.js', 'foo.py'
                  'foo.html', 'foo.txt', 'foo.dtd', 'foo.xul', 'foo.sh',
                  'foo.properties', 'foo.json', 'foo.src', 'CHANGELOG']:
            m, encoding = mimetypes.guess_type(f)
            assert not binary(m, f), '%s should not be binary' % f

        for f in ['foo.png', 'foo.gif', 'foo.exe', 'foo.swf']:
            m, encoding = mimetypes.guess_type(f)
            assert binary(m, f), '%s should be binary' % f

        filename = os.path.join(settings.TMP_PATH, 'test_isbinary')
        for txt in ['#!/usr/bin/python', '#python', u'\0x2']:
            open(filename, 'w').write(txt)
            m, encoding = mimetypes.guess_type(filename)
            assert not binary(m, filename), '%s should not be binary' % txt

        for txt in ['MZ']:
            open(filename, 'w').write(txt)
            m, encoding = mimetypes.guess_type(filename)
            assert binary(m, filename), '%s should be binary' % txt
        os.remove(filename)

    def test_truncate(self):
        truncate = self.viewer.truncate
        for x, y in (['foo.rdf', 'foo.rdf'],
                     ['somelongfilename.rdf', 'somelongfilenam...rdf'],
                     [u'unicode삮.txt', u'unicode\uc0ae.txt'],
                     [u'unicodesomelong삮.txt', u'unicodesomelong...txt'],
                     ['somelongfilename.somelongextension',
                      'somelongfilenam...somelonge..'],):
            eq_(truncate(x), y)

    def test_get_files_not_extracted(self):
        assert not self.viewer.get_files()

    def test_get_files_size(self):
        self.viewer.extract()
        files = self.viewer.get_files()
        eq_(len(files), 14)

    def test_get_files_directory(self):
        self.viewer.extract()
        files = self.viewer.get_files()
        eq_(files['install.js']['directory'], False)
        eq_(files['install.js']['binary'], False)
        eq_(files['__MACOSX']['directory'], True)
        eq_(files['__MACOSX']['binary'], False)

    def test_url_file(self):
        self.viewer.extract()
        files = self.viewer.get_files()
        url = reverse('files.list', args=[self.viewer.file.id,
                                          'file', 'install.js'])
        file_url = files['install.js']['url']
        assert file_url == url
        assert file_url.startswith('/en-US')

        # Make sure that the locale is properly used (see bug 1168794).
        with self.activate('fr'):
            self.viewer._files = {}  # Reset the viewer's internal cache.
            files = self.viewer.get_files()
            url = reverse('files.list', args=[self.viewer.file.id,
                                              'file', 'install.js'])
            file_url = files['install.js']['url']
            assert file_url == url
            assert file_url.startswith('/fr')

    def test_get_files_depth(self):
        self.viewer.extract()
        files = self.viewer.get_files()
        eq_(files['dictionaries/license.txt']['depth'], 1)

    def test_bom(self):
        dest = os.path.join(settings.TMP_PATH, 'test_bom')
        open(dest, 'w').write('foo'.encode('utf-16'))
        self.viewer.select('foo')
        self.viewer.selected = {'full': dest, 'size': 1}
        eq_(self.viewer.read_file(), u'foo')
        os.remove(dest)

    def test_syntax(self):
        for filename, syntax in [('foo.rdf', 'xml'),
                                 ('foo.xul', 'xml'),
                                 ('foo.json', 'js'),
                                 ('foo.jsm', 'js'),
                                 ('foo.bar', 'plain')]:
            eq_(self.viewer.get_syntax(filename), syntax)

    def test_file_order(self):
        self.viewer.extract()
        dest = self.viewer.dest
        open(os.path.join(dest, 'chrome.manifest'), 'w')
        subdir = os.path.join(dest, 'chrome')
        os.mkdir(subdir)
        open(os.path.join(subdir, 'foo'), 'w')
        cache.clear()
        files = self.viewer.get_files().keys()
        rt = files.index(u'chrome')
        eq_(files[rt:rt + 3], [u'chrome', u'chrome/foo', u'dictionaries'])

    @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
    def test_file_size(self):
        self.viewer.extract()
        self.viewer.get_files()
        self.viewer.select('install.js')
        res = self.viewer.read_file()
        eq_(res, '')
        assert self.viewer.selected['msg'].startswith('File size is')

    @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
    def test_file_size_unicode(self):
        with self.activate(locale='he'):
            self.viewer.extract()
            self.viewer.get_files()
            self.viewer.select('install.js')
            res = self.viewer.read_file()
            eq_(res, '')
            assert self.viewer.selected['msg'].startswith('File size is')

    @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
    def test_contents_size(self):
        self.assertRaises(forms.ValidationError, self.viewer.extract)

    def test_default(self):
        eq_(self.viewer.get_default(None), 'install.rdf')

    def test_delete_mid_read(self):
        self.viewer.extract()
        self.viewer.select('install.js')
        os.remove(os.path.join(self.viewer.dest, 'install.js'))
        res = self.viewer.read_file()
        eq_(res, '')
        assert self.viewer.selected['msg'].startswith('That file no')

    @patch('files.helpers.get_md5')
    def test_delete_mid_tree(self, get_md5):
        get_md5.side_effect = IOError('ow')
        self.viewer.extract()
        eq_({}, self.viewer.get_files())

class TestSearchEngineHelper(amo.tests.TestCase):
    fixtures = ['base/addon_4594_a9']

    def setUp(self):
        super(TestSearchEngineHelper, self).setUp()
        self.left = File.objects.get(pk=25753)
        self.viewer = FileViewer(self.left)

        if not os.path.exists(os.path.dirname(self.viewer.src)):
            os.makedirs(os.path.dirname(self.viewer.src))
            with storage.open(self.viewer.src, 'w') as f:
                f.write('some data\n')

    def tearDown(self):
        self.viewer.cleanup()
        super(TestSearchEngineHelper, self).tearDown()

    def test_is_search_engine(self):
        assert self.viewer.is_search_engine()

    def test_extract_search_engine(self):
        self.viewer.extract()
        assert os.path.exists(self.viewer.dest)

    def test_default(self):
        self.viewer.extract()
        eq_(self.viewer.get_default(None), 'a9.xml')

    def test_default_no_files(self):
        self.viewer.extract()
        os.remove(os.path.join(self.viewer.dest, 'a9.xml'))
        eq_(self.viewer.get_default(None), None)

class TestDiffSearchEngine(amo.tests.TestCase):

    def setUp(self):
        super(TestDiffSearchEngine, self).setUp()
        src = os.path.join(settings.ROOT, get_file('search.xml'))
        if not storage.exists(src):
            with storage.open(src, 'w') as f:
                f.write(open(src).read())
        self.helper = DiffHelper(make_file(1, src, filename='search.xml'),
                                 make_file(2, src, filename='search.xml'))

    def tearDown(self):
        self.helper.cleanup()
        super(TestDiffSearchEngine, self).tearDown()

    @patch('files.helpers.FileViewer.is_search_engine')
    def test_diff_search(self, is_search_engine):
        is_search_engine.return_value = True
        self.helper.extract()
        shutil.copyfile(os.path.join(self.helper.left.dest, 'search.xml'),
                        os.path.join(self.helper.right.dest, 's-20010101.xml'))
        assert self.helper.select('search.xml')
        eq_(len(self.helper.get_deleted_files()), 0)

class TestDiffHelper(amo.tests.TestCase):

    def setUp(self):
        super(TestDiffHelper, self).setUp()
        src = os.path.join(settings.ROOT, get_file('dictionary-test.xpi'))
        self.helper = DiffHelper(make_file(1, src), make_file(2, src))

    def tearDown(self):
        self.helper.cleanup()
        super(TestDiffHelper, self).tearDown()

    def test_files_not_extracted(self):
        eq_(self.helper.is_extracted(), False)

    def test_files_extracted(self):
        self.helper.extract()
        eq_(self.helper.is_extracted(), True)

    def test_get_files(self):
        eq_(self.helper.left.get_files(),
            self.helper.get_files())

    def test_diffable(self):
        self.helper.extract()
        self.helper.select('install.js')
        assert self.helper.is_diffable()

    def test_diffable_one_missing(self):
        self.helper.extract()
        os.remove(os.path.join(self.helper.right.dest, 'install.js'))
        self.helper.select('install.js')
        assert self.helper.is_diffable()

    def test_diffable_allow_empty(self):
        self.helper.extract()
        self.assertRaises(AssertionError, self.helper.right.read_file)
        eq_(self.helper.right.read_file(allow_empty=True), '')

    def test_diffable_both_missing(self):
        self.helper.extract()
        self.helper.select('foo.js')
        assert not self.helper.is_diffable()

    def test_diffable_deleted_files(self):
        self.helper.extract()
        os.remove(os.path.join(self.helper.left.dest, 'install.js'))
        eq_('install.js' in self.helper.get_deleted_files(), True)

    def test_diffable_one_binary_same(self):
        self.helper.extract()
        self.helper.select('install.js')
        self.helper.left.selected['binary'] = True
        assert self.helper.is_binary()

    def test_diffable_one_binary_diff(self):
        self.helper.extract()
        self.change(self.helper.left.dest, 'asd')
        cache.clear()
        self.helper.select('install.js')
        self.helper.left.selected['binary'] = True
        assert self.helper.is_binary()

    def test_diffable_two_binary_diff(self):
        self.helper.extract()
        self.change(self.helper.left.dest, 'asd')
        self.change(self.helper.right.dest, 'asd123')
        cache.clear()
        self.helper.select('install.js')
        self.helper.left.selected['binary'] = True
        self.helper.right.selected['binary'] = True
        assert self.helper.is_binary()

    def test_diffable_one_directory(self):
        self.helper.extract()
        self.helper.select('install.js')
        self.helper.left.selected['directory'] = True
        assert not self.helper.is_diffable()
        assert self.helper.left.selected['msg'].startswith('This file')

    def test_diffable_parent(self):
        self.helper.extract()
        self.change(self.helper.left.dest, 'asd',
                    filename='__MACOSX/._dictionaries')
        cache.clear()
        files = self.helper.get_files()
        eq_(files['__MACOSX/._dictionaries']['diff'], True)
        eq_(files['__MACOSX']['diff'], True)

    def change(self, file, text, filename='install.js'):
        path = os.path.join(file, filename)
        data = open(path, 'r').read()
        data += text
        open(path, 'w').write(data)

class TestSafeUnzipFile(amo.tests.TestCase, amo.tests.AMOPaths):

    # TODO(andym): get full coverage for existing SafeUnzip methods, most
    # is covered in the file viewer tests.
    @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
    def test_unzip_limit(self):
        zip_file = SafeUnzip(self.xpi_path('langpack-localepicker'))
        self.assertRaises(forms.ValidationError, zip_file.is_valid)

    def test_unzip_fatal(self):
        zip_file = SafeUnzip(self.xpi_path('search.xml'))
        self.assertRaises(zipfile.BadZipfile, zip_file.is_valid)

    def test_unzip_not_fatal(self):
        zip_file = SafeUnzip(self.xpi_path('search.xml'))
        assert not zip_file.is_valid(fatal=False)

    def test_extract_path(self):
        zip_file = SafeUnzip(self.xpi_path('langpack-localepicker'))
        assert zip_file.is_valid()
        assert'locale browser de' in zip_file.extract_path('chrome.manifest')

    def test_not_secure(self):
        zip_file = SafeUnzip(self.xpi_path('extension'))
        zip_file.is_valid()
        assert not zip_file.is_signed()

    def test_is_secure(self):
        zip_file = SafeUnzip(self.xpi_path('signed'))
        zip_file.is_valid()
        assert zip_file.is_signed()

    def test_is_broken(self):
        zip_file = SafeUnzip(self.xpi_path('signed'))
        zip_file.is_valid()
        zip_file.info_list[2].filename = 'META-INF/foo.sf'
        assert not zip_file.is_signed()


text:
package com.teamtter.test.categories;

public interface DummyTest {
}


text:
import uuid

from oslo_log import log as logging
from tacker.common import log
from tacker.nfvo.drivers.vnffg.sfc_drivers import abstract_driver

LOG = logging.getLogger(__name__)

class VNFFGNoop(abstract_driver.SfcAbstractDriver):

    """Noop driver for VNFFG tests"""

    def __init__(self):
        super(VNFFGNoop, self).__init__()
        self._instances = set()

    def get_type(self):
        return 'noop'

    def get_name(self):
        return 'noop'

    def get_description(self):
        return 'VNFFG Noop driver'

    @log.log
    def create_chain(self, name, fc_id, vnfs, auth_attr=None):
        instance_id = str(uuid.uuid4())
        self._instances.add(instance_id)
        return instance_id

    @log.log
    def update_chain(self, chain_id, fc_ids, vnfs, auth_attr=None):
        if chain_id not in self._instances:
            LOG.debug(_('Chain not found'))
            raise ValueError('No chain instance %s' % chain_id)

    @log.log
    def delete_chain(self, chain_id, auth_attr=None):
        self._instances.remove(chain_id)

    @log.log
    def create_flow_classifier(self, name, fc, auth_attr=None):
        instance_id = str(uuid.uuid4())
        self._instances.add(instance_id)
        return instance_id

    @log.log
    def update_flow_classifier(self, fc_id, fc, auth_attr=None):
        if fc_id not in self._instances:
            LOG.debug(_('FC not found'))
            raise ValueError('No FC instance %s' % fc_id)

    @log.log
    def delete_flow_classifier(self, fc_id, auth_attr=None):
        self._instances.remove(fc_id)


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\output;

use coding_exception;
use moodle_exception;
use core_component;
use theme_config;

/**
 * Get information about valid locations for mustache templates.
 *
 * @copyright  2015 Damyon Wiese
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      2.9
 */
class mustache_template_finder {

    /**
     * Helper function for getting a list of valid template directories for a specific component.
     *
     * @param string $component The component to search
     * @param string $themename The current theme name
     * @return string[] List of valid directories for templates for this compoonent. Directories are not checked for existence.
     */
    public static function get_template_directories_for_component($component, $themename = '') {
        global $CFG, $PAGE;

        // Default the param.
        if ($themename == '') {
            $themename = $PAGE->theme->name;
        }

        // Clean params for safety.
        $component = clean_param($component, PARAM_COMPONENT);
        $themename = clean_param($themename, PARAM_COMPONENT);

        // Validate the component.
        $dirs = array();
        $compdirectory = core_component::get_component_directory($component);
        if (!$compdirectory) {
            throw new coding_exception("Component was not valid: " . s($component));
        }

        // Find the parent themes.
        $parents = array();
        if ($themename === $PAGE->theme->name) {
            $parents = $PAGE->theme->parents;
        } else {
            $themeconfig = theme_config::load($themename);
            $parents = $themeconfig->parents;
        }

        // First check the theme.
        $dirs[] = $CFG->dirroot . '/theme/' . $themename . '/templates/' . $component . '/';
        // Now check the parent themes.
        // Search each of the parent themes second.
        foreach ($parents as $parent) {
            $dirs[] = $CFG->dirroot . '/theme/' . $parent . '/templates/' . $component . '/';
        }

        $dirs[] = $compdirectory . '/templates/';

        return $dirs;
    }

    /**
     * Helper function for getting a filename for a template from the template name.
     *
     * @param string $name - This is the componentname/templatename combined.
     * @param string $themename - This is the current theme name.
     * @return string
     */
    public static function get_template_filepath($name, $themename = '') {
        global $CFG, $PAGE;

        if (strpos($name, '/') === false) {
            throw new coding_exception('Templates names must be specified as "componentname/templatename"' .
                                       ' (' . s($name) . ' requested) ');
        }
        list($component, $templatename) = explode('/', $name, 2);
        $component = clean_param($component, PARAM_COMPONENT);
        if (strpos($templatename, '/') !== false) {
            throw new coding_exception('Templates cannot be placed in sub directories (' . s($name) . ' requested)');
        }

        $dirs = self::get_template_directories_for_component($component, $themename);

        foreach ($dirs as $dir) {
            $candidate = $dir . $templatename . '.mustache';
            if (file_exists($candidate)) {
                return $candidate;
            }
        }

        throw new moodle_exception('filenotfound', 'error');
    }
}


text:
@interface HFRearTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

- (void) reloadData;

@property (nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic) IBOutlet UIButton *settingButton;

@end


text:
define(['../config/custom'], function (customConfig) {
    "use strict";

    var config = {

    };

    return config;
});


text:
import { ADataType } from '../../data/datatype';
import { AGraph, IGraphDataDescription } from './graph';
import { IGraphFactory } from './GraphBase';
export declare class GraphProxy extends ADataType<IGraphDataDescription> {
    private cache;
    private loaded;
    get nnodes(): number;
    get nedges(): number;
    get dim(): number[];
    impl(factory?: IGraphFactory): PromiseLike<AGraph>;
    get idtypes(): import("../../idtype").IDType[];
    /**
     * module entry point for creating a datatype
     * @param desc
     * @returns {IMatrix}
     */
    static create(desc: IGraphDataDescription): GraphProxy;
}
//# sourceMappingURL=GraphProxy.d.ts.map


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * upgrade this assignment instance - this function could be skipped but it will be needed later
 * @param int $oldversion The old version of the assign module
 * @return bool
 */
function xmldb_assign_upgrade($oldversion) {
    global $CFG, $DB;

    $dbman = $DB->get_manager();

    if ($oldversion < 2014051201) {

        // Cleanup bad database records where assignid is missing.

        $DB->delete_records('assign_user_mapping', array('assignment'=>0));
        // Assign savepoint reached.
        upgrade_mod_savepoint(true, 2014051201, 'assign');
    }

    if ($oldversion < 2014072400) {

        // Add "latest" column to submissions table to mark the latest attempt.
        $table = new xmldb_table('assign_submission');
        $field = new xmldb_field('latest', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'attemptnumber');

        // Conditionally launch add field latest.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Assign savepoint reached.
        upgrade_mod_savepoint(true, 2014072400, 'assign');
    }
    if ($oldversion < 2014072401) {

         // Define index latestattempt (not unique) to be added to assign_submission.
        $table = new xmldb_table('assign_submission');
        $index = new xmldb_index('latestattempt', XMLDB_INDEX_NOTUNIQUE, array('assignment', 'userid', 'groupid', 'latest'));

        // Conditionally launch add index latestattempt.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }

        // Assign savepoint reached.
        upgrade_mod_savepoint(true, 2014072401, 'assign');
    }
    if ($oldversion < 2014072405) {

        // Prevent running this multiple times.

        $countsql = 'SELECT COUNT(id) FROM {assign_submission} WHERE latest = ?';

        $count = $DB->count_records_sql($countsql, array(1));
        if ($count == 0) {

            // Mark the latest attempt for every submission in mod_assign.
            $maxattemptsql = 'SELECT assignment, userid, groupid, max(attemptnumber) AS maxattempt
                                FROM {assign_submission}
                            GROUP BY assignment, groupid, userid';

            $maxattemptidssql = 'SELECT souter.id
                                   FROM {assign_submission} souter
                                   JOIN (' . $maxattemptsql . ') sinner
                                     ON souter.assignment = sinner.assignment
                                    AND souter.userid = sinner.userid
                                    AND souter.groupid = sinner.groupid
                                    AND souter.attemptnumber = sinner.maxattempt';

            // We need to avoid using "WHERE ... IN(SELECT ...)" clause with MySQL for performance reason.
            // TODO MDL-29589 Remove this dbfamily exception when implemented.
            if ($DB->get_dbfamily() === 'mysql') {
                $params = array('latest' => 1);
                $sql = 'UPDATE {assign_submission}
                    INNER JOIN (' . $maxattemptidssql . ') souterouter ON souterouter.id = {assign_submission}.id
                           SET latest = :latest';
                $DB->execute($sql, $params);
            } else {
                $select = 'id IN(' . $maxattemptidssql . ')';
                $DB->set_field_select('assign_submission', 'latest', 1, $select);
            }

            // Look for grade records with no submission record.
            // This is when a teacher has marked a student before they submitted anything.
            $records = $DB->get_records_sql('SELECT g.id, g.assignment, g.userid
                                               FROM {assign_grades} g
                                          LEFT JOIN {assign_submission} s
                                                 ON s.assignment = g.assignment
                                                AND s.userid = g.userid
                                              WHERE s.id IS NULL');
            $submissions = array();
            foreach ($records as $record) {
                $submission = new stdClass();
                $submission->assignment = $record->assignment;
                $submission->userid = $record->userid;
                $submission->status = 'new';
                $submission->groupid = 0;
                $submission->latest = 1;
                $submission->timecreated = time();
                $submission->timemodified = time();
                array_push($submissions, $submission);
            }

            $DB->insert_records('assign_submission', $submissions);
        }

        // Assign savepoint reached.
        upgrade_mod_savepoint(true, 2014072405, 'assign');
    }

    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.

    if ($oldversion < 2014122600) {
        // Delete any entries from the assign_user_flags and assign_user_mapping that are no longer required.
        if ($DB->get_dbfamily() === 'mysql') {
            $sql1 = "DELETE {assign_user_flags}
                       FROM {assign_user_flags}
                  LEFT JOIN {assign}
                         ON {assign_user_flags}.assignment = {assign}.id
                      WHERE {assign}.id IS NULL";

            $sql2 = "DELETE {assign_user_mapping}
                       FROM {assign_user_mapping}
                  LEFT JOIN {assign}
                         ON {assign_user_mapping}.assignment = {assign}.id
                      WHERE {assign}.id IS NULL";
        } else {
            $sql1 = "DELETE FROM {assign_user_flags}
                WHERE NOT EXISTS (
                          SELECT 'x' FROM {assign}
                           WHERE {assign_user_flags}.assignment = {assign}.id)";

            $sql2 = "DELETE FROM {assign_user_mapping}
                WHERE NOT EXISTS (
                          SELECT 'x' FROM {assign}
                           WHERE {assign_user_mapping}.assignment = {assign}.id)";
        }

        $DB->execute($sql1);
        $DB->execute($sql2);

        upgrade_mod_savepoint(true, 2014122600, 'assign');
    }

    if ($oldversion < 2015022300) {

        // Define field preventsubmissionnotingroup to be added to assign.
        $table = new xmldb_table('assign');
        $field = new xmldb_field('preventsubmissionnotingroup',
            XMLDB_TYPE_INTEGER,
            '2',
            null,
            XMLDB_NOTNULL,
            null,
            '0',
            'sendstudentnotifications');

        // Conditionally launch add field preventsubmissionnotingroup.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Assign savepoint reached.
        upgrade_mod_savepoint(true, 2015022300, 'assign');
    }

    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.

    // Moodle v3.0.0 release upgrade line.
    // Put any upgrade step following this.

    // Moodle v3.1.0 release upgrade line.
    // Put any upgrade step following this.

    return true;
}


text:
.errorNotification {
	background : #F2DEDE;
    color: #A94442;
    border-bottom: solid 1px #EBCCD1;
}

.battery:after {
    background-color: #ccc;
    border: 2px solid #ccc;
	border-radius: 5px;
    content: "";
    display: block;
    height: 12px;
    position: absolute;
    right: -6px;
    top: 8px;
    width: 6px;
}
.battery {
    background-color: #fff;
    border: 2px solid #ccc;
	border-radius: 5px;
    height: 32px;
    margin-right: auto;
    position: relative;
    width: 100%;
	max-width: 100px;
	text-align: center;
}

.batteryStatus {
	width: 50%;
	height: 100%;
	background-color: #0A0;
	border-radius: 2px;
	height:100%;
}

#tools {
	padding: 15px;
	vertical-align: middle;
}

.cros-logo {
    background: url("../img/logo_small.png") !important;
    background-size: contain !important;
}

.btn.btn-swap {
	margin-bottom: 10px;
}

.well.route-well {
	margin-bottom: 10px;
}

.basestation {
	margin-top: -20px;
	margin-bottom: 8px;
	margin-right: -17px;
}

.leaflet-control-center-interior
{
    width: 35px;
    height: 32px;
    display: block;
    padding: 3px;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    box-shadow: 0 1px 7px rgba(0, 0, 0, 0.65);
    cursor: auto;
    text-align: center;
    background-color: #FFFFFF;
}

.leaflet-control-center-active {
    color: #1ABC9C;
}

.leaflet-control-center-interior:hover
{
    background-color: #F4F4F4;
    cursor: pointer;
    color: #1ABC9C;
}

#customTableHeader
{
    color: black;
    font-weight: bold;
    padding: 0px 0px;

}
#customTableHeader:hover
{
    color: #1abc9c;
    text-decoration: none;
}

#customTableHeader:active
{
    webkit-box-shadow: none;
    box-shadow: none;
}

.list-group-item.extra-padding {
	padding-bottom: 20px;
}

.list-group-item.notifications-title {
	background-color: #CCC;
}

.list-group-item.no-notifications {
	color: #BBB;
}

.time {
	color: #AAA;
	position: absolute;
	bottom: 0;
	right: 10px;
	font-size: small;
}

.remove {
	position: absolute;
	top: -19px;
	right: 0px;
}

.scroll {
	height: 415px;
	overflow-y:auto;
}

#notificationSlider {
	display: none;
}

.label-charging {
    background-color: #d62728;
}

.label-available {
    background-color: #2ca02c;
}

.label-inactive {
    background-color: #1f77b4;
}

.label-inflight {
    background-color: #ff7f0e;
}

.label-manual {
    background-color: #9467bd;
}

.label-emergency {
    background-color: #8c564b;
}

.label-error {
    background-color: #e377c2;
}

.label-unreachable {
    background-color: #7f7f7f;
}

.label-unknown {
    background-color: #bcbd22;
}

#legend {
    padding-top: 100px;
    height: 350px;
}

.disabledLink {
    pointer-events: none !important;
    cursor: not-allowed !important;
}

.controlButtonActive {
    color: #333;
    background-color: #e6e6e6;
    border-color: #adadad;
}

.controlButtonContainer {
    margin:3px !important;
}

.controlButtonContainerParent {
    margin-right: 3px !important;
}

.whitespaceBottom {
    margin-bottom: 10px;
}

.videoClick {
    height:365px;
    background: black;
}

.videoClick button {
    margin-top: 180px;
}

.unavailable {
    background-image: url('../img/unavailable.png');
    background-size: cover;
    width: 150px;
    height: 150px;
    margin: auto;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Cookies</title>

   <link href="/RoboX/cookies/cookies.css" rel = "stylesheet" type="text/css">

Please update your browser settings to view this page

Your web browser settings are blocking cookies.

"Cookies" are small files that are placed on the hard drive of your computer when you visit various websites. RoboX uses cookies to provide services to you, and to help ensure the security of your account. Your web browser must accept cookies in order to access all of the features that RoboX has to offer. Here's how you can get your web browser to accept cookies:

Sign in again. If your browser asks you to accept cookies, choose "accept" or "continue."

Learn how to change your browser settings to accept cookies.

Check that your computer's clock and calendar settings are current.

Try updating your web browser to the latest version of Microsoft Internet Explorer or Mozilla Firefox.

Learn more about cookies


text:
package io.cloudslang.content.amazon.entities.aws;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static io.cloudslang.content.amazon.entities.constants.Constants.Miscellaneous.NOT_RELEVANT;

/**
 * Created by TusaM
 * 10/24/2016.
 */
public enum Attribute {
    INSTANCE_TYPE("instanceType"),
    KERNEL("kernel"),
    RAMDISK("ramdisk"),
    USER_DATA("userData"),
    DISABLE_API_TERMINATION("disableApiTermination"),
    INSTANCE_INITIATED_SHUTDOWN_BEHAVIOR("instanceInitiatedShutdownBehavior"),
    ROOT_DEVICE_NAME("rootDeviceName"),
    BLOCK_DEVICE_MAPPING("blockDeviceMapping"),
    PRODUCT_CODES("productCodes"),
    SOURCE_DEST_CHECK("sourceDestCheck"),
    GROUP_SET("groupSet"),
    EBS_OPTIMIZED("ebsOptimized"),
    SRIOV_NET_SUPPORT("sriovNetSupport"),
    ENA_SUPPORT("enaSupport");

    private final String value;

    Attribute(String value) {
        this.value = value;
    }

    private String getValue() {
        return value;
    }

    public static String getAttribute(String input) {
        if (isBlank(input)) {
            return NOT_RELEVANT;
        }

        for (Attribute attribute : Attribute.values()) {
            if (attribute.getValue().equalsIgnoreCase(input)) {
                return attribute.getValue();
            }
        }

        throw new IllegalArgumentException("Invalid attribute value: [" + input + "]. Valid values: instanceType | kernel | " +
                "ramdisk | userData | disableApiTermination | instanceInitiatedShutdownBehavior | rootDeviceName | " +
                "blockDeviceMapping | productCodes | sourceDestCheck | groupSet | ebsOptimized | sriovNetSupport | enaSupport");
    }
}


text:
import crossFetch from 'cross-fetch'
import delayFetch from './delay-fetch.js'
import serialFetch from 'serial-fetch'
import { requestDelay } from './config.js'

const serial = serialFetch.default || serialFetch
const serialDelayedFetch = serial(function () {
  // defer calling delayFetch so config setup can be called
  return delayFetch(crossFetch, requestDelay).apply(this, arguments)
})

export default function fetch () {
  return serialDelayedFetch.apply(this, arguments)
}


text:
<md-dialog aria-label="View skill dialog">
  <md-toolbar flex="none">

      <md-button aria-label="Cancel button" type="button" class="md-icon-button" ng-click="dialogVm.cancel()">
        <md-tooltip>

        </md-tooltip>
        <md-icon md-svg-icon="close" aria-label="Close Icon"></md-icon>
      </md-button>

  </md-toolbar>
  <md-dialog-content layout-margin>

      <md-icon md-svg-icon="{{::dialogVm.skill.icon}}" aria-label="Skill Icon" class="md-icon-128 margin-10px" ng-if="::dialogVm.skill.icon"></md-icon>

        <star-rating ng-model="::dialogVm.skill.level" readonly="true"></star-rating>

      :

 0">
      :
      <md-chips ng-model="::dialogVm.skill.profiles" readonly="true">
        <md-chip-template>

        </md-chip-template>
      </md-chips>

      :

      :

  </md-dialog-content>
</md-dialog>


text:
package edu.ucla.cs.starai.graph

import scala.collection.immutable
import scala.collection.mutable
import edu.ucla.cs.starai.util.Caching

/**
 * A singly-connected DAG, with nodes N
 */
trait Tree[+N <: Tree[N]] extends DAG[N] {

  self: N =>

  override def foldUp[T](
    propagate: (N,Seq[T]) => T): T = {
      propagate(self,children.map(_.foldUp(propagate)))
  }

  override def iterator: Iterator[N] =
    children.map(_.iterator).foldRight(Iterator(this))(_ ++ _)

}

trait DoubleLinkedTree[+N <: DoubleLinkedTree[N]] extends Tree[N] {

  self: N =>

    def parent: Option[N]

    def ancestors: List[N] = parent.map(p => p :: p.ancestors).getOrElse(Nil)

    def root = (this :: ancestors).last

    // prefer exception over option return type here
    def lca[U >: N <: DoubleLinkedTree[U]](that: U): U = {
      if(this == that) this
      else if(this.containsNode(that)) this
      else if (that.containsNode(this)) that.asSelf
      else {
        val thisParents = this.ancestors.toSet[U]
        for(parent <- that.ancestors)
          if(thisParents.contains(parent))
            return parent
        throw new IllegalArgumentException(s"$this and $that share no common ancestor")
      }
    }

    /**
     * Returns first ancestor (including this) that satisfies a predicate
     */
    // prefer exception over option return type here
    def ancestor(pred: (N => Boolean)): N = {
      if(pred(this)) this
      else if(parent.nonEmpty) parent.get.ancestor(pred)
      else throw new IllegalArgumentException(s"$this does not have an ancestor that satisfies the given predicate")
    }

}


text:
<?php

namespace Google\Service\Dataflow;

class SendDebugCaptureResponse extends \Google\Model
{
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SendDebugCaptureResponse::class, 'Google_Service_Dataflow_SendDebugCaptureResponse');


text:
/**
 Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 http://www.programcreek.com/2013/01/leetcode-convert-sorted-array-to-binary-search-tree-java/
 **/

class TreeNode {
    int value;
    TreeNode left;
    TreeNode right;

    TreeNode(int value) {
        this.value = value;
    }
}

public class SortedArrayBST {
    public TreeNode sortedArrayBST(int[] sorted_array) {
        if (sorted_array.length == 0)
            return null;

        return sortedArrayBST(sorted_array, 0, sorted_array.length - 1);
    }

    public TreeNode sortedArrayBST(int[] sorted_array, int start, int end) {
        // First find the mid of start and end
        int mid = (start + end) / 2;

        if (start > end)
            return null;

        // Divide and conquer to solve left and right
        TreeNode root = new TreeNode(sorted_array[mid]);
        root.left = sortedArrayBST(sorted_array, start, mid - 1);
        root.right = sortedArrayBST(sorted_array, mid + 1, end);

        return root;
    }

    public static void main(String[] args) {
        int[] sorted_array = { 1, 2, 3, 4, 5, 6 };
        SortedArrayBST bst = new SortedArrayBST();
        TreeNode root;
        root = bst.sortedArrayBST(sorted_array);
        System.out.println(root.value);
    }
}


text:
package co.cask.cdap.security.auth;

import co.cask.cdap.common.conf.CConfiguration;

import java.io.IOException;

/**
 * Maintains secret keys in memory and uses them to sign and validate authentication tokens.
 */
public class InMemoryKeyManager extends MapBackedKeyManager {

  /**
   * Create an InMemoryKeyManager that stores keys in memory only.
   * @param conf
   */
  public InMemoryKeyManager(CConfiguration conf) {
    super(conf);
  }

  @Override
  public void doInit() throws IOException {
    generateKey();
  }

  @Override
  public void shutDown() {
    // nothing to do
  }
}


text:
{% extends "bootstrap/base.html" %}

{% block title %}We Are Indivisible{% endblock %}
{% block head %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="/static/css/style.css">

{% endblock %}

{% block content %}
{{ super() }}

      We Are Indivisible

Find Your Reps

What's Hot

Learn About the Data

Support Us

{% endblock %}


text:
'use strict';

angular.module('<%= appname %>')
.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("<%= defaultUrl %>");
    $stateProvider
        <% for (count = 0; count < routes.length; count += 1) { %>.state(
            '<%= routes[count].name %>',
            {
                url: '<%= routes[count].url %>',
                templateUrl: '<%= routes[count].templateUrl %>'
            }
        )<% } %>;
});


text:
My problem message.

Chuck


text:
import pygame
from constants import SCREEN, SCREEN_HEIGHT, SCREEN_WIDTH, MAX_FPS, CHROMA_KEY, SHOW_FPS
import sound
from misc_functions import show_fps
from LevelSelect import Level_Select
#from savegame import save_write
import level

def save_write(save_num, lastlevel):
	archivo = open('saves/save' + str(save_num) + '.txt', 'w')
	archivo.write('lastlevel=' + str(lastlevel))
	archivo.close()

def Adventure(save_num, MUTE_MUSIC, prev_song, lvl = 0):
	clock = pygame.time.Clock()

	EXIT_MENU = True
	EXIT_GAME = False
	if lvl == 'COMPLETADO':
		return Level_Select(MUTE_MUSIC, prev_song)

	lvl += 1 #Nivel de donde continua el modo aventura
	prev_song = 'None'

	while EXIT_MENU:
		finished_level, EXIT_MENU, EXIT_GAME, MUTE_MUSIC, prev_song = level.Level('level' + str(lvl), MUTE_MUSIC, prev_song, 'main/')
		if finished_level:
			save_write(save_num, lvl)
			print 'SAVED'
			lvl += 1
		if EXIT_GAME: #Si en algun momento se necesita salir del juego
			return True, MUTE_MUSIC, prev_song
		elif lvl > 22: #Ultimo nivel del modo aventura
			return False, MUTE_MUSIC, prev_song

		clock.tick(MAX_FPS)
	return False, MUTE_MUSIC, prev_song


text:
package klawisch.jimdo.statistics.statisticsdemo.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.Log;
import android.view.View;

/**
 * Created by Klawisch on 08.07.15.
 */
public class CustomProgressBar extends View {
    private static final String TAG = CustomProgressBar.class.getSimpleName();

    private int progress;
    private Paint progressPaint;
    private Paint innerCirclePaint;
    private Paint textPaint;
    private Paint blurPaint;
    private RectF oval;
    private int diameter;
    private int strokeWidth;
    private boolean logProgress = false;
    private boolean displayText = true;

    public CustomProgressBar(Context context) {
        super(context);
        init();
    }

    /**
     * Updates the progress
     *
     * @param progress Percentage of completion
     */
    public void setProgress(int progress) {
        this.progress = progress;
        if (logProgress) Log.e(TAG, "Progress: " + progress + "%");
        invalidate();
    }

    public void setLogProgress(boolean log) {
        this.logProgress = log;
    }

    public void setColor(int color) {
        progressPaint.setColor(color);
    }

    public void setDiameter(int diameter) {
        this.diameter = diameter;
        oval.set(0, 0, diameter, diameter);
    }

    public void setStrokeWidth(int width) {
        this.strokeWidth = width;
    }

    /**
     * Initializes the used Paint objects and sets all parameters to their standard values
     */
    private void init() {
        progress = 0;
        diameter = 300;
        strokeWidth = 50;
        progressPaint = new Paint();
        progressPaint.setColor(Color.BLACK);

        innerCirclePaint = new Paint();
        innerCirclePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        oval = new RectF(0, 0, diameter, diameter);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(60);

        blurPaint = new Paint();
        blurPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(diameter + 5, diameter + 5);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawBitmap(getBitmap(), null, oval, progressPaint);

        if (displayText) {
            String text = progress + "%";
            canvas.drawText(text, oval.centerX() - getShift(text, textPaint) / 2, oval.centerY(), textPaint);
        }
    }

    /**
     * Calculates the shift of the percentage-text in the middle of the progressbar. Used to center
     * the text in the progressbar
     *
     * @param s The current progress as text
     * @param p Textpaint
     * @return The width of the string
     */
    private float getShift(String s, Paint p) {
        float[] widths = new float[s.length()];
        p.getTextWidths(s, widths);

        float shift = 0;
        for (float width : widths) shift += width;

        return shift;
    }

    /**
     * Merges the big and the small circle to create a ring-shape
     *
     * @return Returns the ring as a bitmap
     */
    private Bitmap getBitmap() {
        Bitmap b = Bitmap.createBitmap(diameter, diameter, Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        final float startAngle = 0f;
        final float drawTo = startAngle + (progress * 3.6f);
        canvas.rotate(-90f, oval.centerX(), oval.centerY());
        canvas.drawArc(oval, startAngle, drawTo, true, progressPaint);

        int stroke = diameter / 2 - strokeWidth;
        canvas.drawCircle(oval.centerX(), oval.centerY(), stroke, innerCirclePaint);

        return b;
    }

    private void setDisplayText(boolean display) {
        this.displayText = display;
    }

    private void setTextPaint(Paint paint) {
        if (paint != null)
            this.textPaint = paint;
    }

    private void setTextColor(int color) {
        textPaint.setColor(color);
    }

    private void setTextSize(float size) {
        if (size > 0)
            textPaint.setTextSize(size);
    }

    private float getTextSize() {
        return textPaint.getTextSize();
    }

    private int getTextColor() {
        return textPaint.getColor();
    }
}


text:
package org.camunda.bpm.engine.impl.cmd;

import java.util.Collection;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.impl.UpdateProcessInstancesSuspensionStateBuilderImpl;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.impl.runtime.UpdateProcessInstanceSuspensionStateBuilderImpl;
import org.camunda.bpm.engine.impl.util.EnsureUtil;

public class UpdateProcessInstancesSuspendStateCmd extends AbstractUpdateProcessInstancesSuspendStateCmd<Void> {

  public UpdateProcessInstancesSuspendStateCmd(CommandExecutor commandExecutor, UpdateProcessInstancesSuspensionStateBuilderImpl builder, boolean suspendstate) {
    super(commandExecutor, builder, suspendstate);
  }

  public Void execute(CommandContext commandContext) {

    Collection<String> processInstanceIds = collectProcessInstanceIds();

    EnsureUtil.ensureNotEmpty(BadUserRequestException.class, "No process instance ids given", "Process Instance ids", processInstanceIds);
    EnsureUtil.ensureNotContainsNull(BadUserRequestException.class, "Cannot be null.", "Process Instance ids", processInstanceIds);

    writeUserOperationLog(commandContext, processInstanceIds.size(), false);

    UpdateProcessInstanceSuspensionStateBuilderImpl suspensionStateBuilder = new UpdateProcessInstanceSuspensionStateBuilderImpl(commandExecutor);
    if (suspending) {
      // suspending
      for (String processInstanceId : processInstanceIds) {
        suspensionStateBuilder.byProcessInstanceId(processInstanceId).suspend();
      }
    } else {
      // activating
      for (String processInstanceId : processInstanceIds) {
        suspensionStateBuilder.byProcessInstanceId(processInstanceId).activate();
      }
    }

    return null;
  }

}


text:
namespace ui {

DriVSyncProvider::DriVSyncProvider(DriWindowDelegate* window_delegate)
    : window_delegate_(window_delegate) {
}

DriVSyncProvider::~DriVSyncProvider() {}

void DriVSyncProvider::GetVSyncParameters(const UpdateVSyncCallback& callback) {
  HardwareDisplayController* controller = window_delegate_->GetController();
  if (!controller)
    return;

  // The value is invalid, so we can't update the parameters.
  if (controller->get_time_of_last_flip() == 0 ||
      controller->get_mode().vrefresh == 0)
    return;

  // Stores the time of the last refresh.
  base::TimeTicks timebase =
      base::TimeTicks::FromInternalValue(controller->get_time_of_last_flip());
  // Stores the refresh rate.
  base::TimeDelta interval =
      base::TimeDelta::FromSeconds(1) / controller->get_mode().vrefresh;

  callback.Run(timebase, interval);
}

}  // namespace ui