text:
<?xml version="1.0" encoding="UTF-8"?>
<adapter>
  <unique-id>${adapter.unique.id}</unique-id>
  <shared-components>
    <connections>
      <jdbc-pooled-connection>
        <unique-id>LocalMySQL</unique-id>
        <test-statement>SELECT DATABASE(), VERSION(), NOW(), USER();</test-statement>
        <driver-imp>com.mysql.jdbc.Driver</driver-imp>
        <username>${local_db_username}</username>
        <password>${local_db_password}</password>
        <connect-url>${local_db_connect_url}</connect-url>
      </jdbc-pooled-connection>
      <jetty-embedded-connection>
        <unique-id>jetty-connection</unique-id>
      </jetty-embedded-connection>
    </connections>
  </shared-components>
  <channel-list>
    <channel>
      <unique-id>ContactManager</unique-id>
      <message-error-handler class="standard-processing-exception-handler">
        <processing-exception-service class="service-list">
          <services>
            <exception-report-service>
              <exception-serializer class="exception-as-json-with-stacktrace"/>
            </exception-report-service>
            <standalone-producer>
              <producer class="jetty-standard-response-producer">
                <status-provider class="http-configured-status">
                  <status>INTERNAL_ERROR_500</status>
                </status-provider>
                <content-type-provider class="http-configured-content-type-provider">
                  <mime-type>application/json</mime-type>
                </content-type-provider>
                <send-payload>true</send-payload>
              </producer>
            </standalone-producer>
          </services>
        </processing-exception-service>
      </message-error-handler>
      <consume-connection class="shared-connection">
        <lookup-name>jetty-connection</lookup-name>
      </consume-connection>
      <produce-connection class="null-connection"/>
      <workflow-list>
        <standard-workflow>
          <consumer class="jetty-message-consumer">
            <unique-id>/contacts/*</unique-id>
            <destination class="configured-consume-destination">
              <destination>/contacts/*</destination>
            </destination>
            <parameter-handler class="jetty-http-parameters-as-metadata"/>
            <header-handler class="jetty-http-ignore-headers"/>
          </consumer>
          <service-collection class="service-list">
            <services>
              <log-message-service>
                <include-payload>true</include-payload>
                <log-level>DEBUG</log-level>
              </log-message-service>
              <branching-service-collection>
                <unique-id>HTTP Router</unique-id>
                <first-service-id>route</first-service-id>
                <services>
                  <jetty-routing-service>
                    <unique-id>route</unique-id>
                    <route>
                      <url-pattern>^/contacts/swagger$</url-pattern>
                      <method>GET</method>
                      <service-id>swagger</service-id>
                    </route>
                    <route>
                      <url-pattern>^/contacts$</url-pattern>
                      <method>GET</method>
                      <service-id>list</service-id>
                    </route>
                    <route>
                      <url-pattern>^/contacts/(.*)$</url-pattern>
                      <method>GET</method>
                      <metadata-key>ContactId</metadata-key>
                      <service-id>retrieve</service-id>
                    </route>
                    <route>
                      <url-pattern>^/contacts/(.*)$</url-pattern>
                      <method>DELETE</method>
                      <metadata-key>ContactId</metadata-key>
                      <service-id>delete</service-id>
                    </route>
                    <route>
                      <url-pattern>^/contacts$</url-pattern>
                      <method>POST</method>
                      <service-id>save</service-id>
                    </route>
                    <route>
                      <url-pattern>^/contacts/(.*)$</url-pattern>
                      <method>PATCH</method>
                      <metadata-key>ContactId</metadata-key>
                      <service-id>update</service-id>
                    </route>
                    <default-service-id>NotHandled</default-service-id>
                  </jetty-routing-service>
                  <service-list>
                    <unique-id>save</unique-id>
                    <services>
                      <!--
                      {
                        "FirstName" : "Lewin",
                        "LastName" : "Chan",
                        "Email" : "lchan@adaptris-abclabs.com",
                        "Phone" : "0700 987654",
                      }
                      -->
                      <json-path-service>
                        <source class="string-payload-data-input-parameter"/>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.FirstName</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>FirstName</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.LastName</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>LastName</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.Email</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>Email</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.Phone</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>Phone</metadata-key>
                          </target>
                        </json-path-execution>
                      </json-path-service>
                      <!-- Generate a UID -->
                      <generate-unique-metadata-value-service>
                        <unique-id>Generate ContactID</unique-id>
                        <metadata-key>ContactId</metadata-key>
                      </generate-unique-metadata-value-service>
                      <jdbc-raw-data-capture-service>
                        <unique-id>Insert Contact</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-timeout>
                          <unit>SECONDS</unit>
                          <interval>30</interval>
                        </statement-timeout>
                        <statement>INSERT INTO `contacts` (id, FirstName, LastName, Phone, Email, LastUpdated, Created) VALUES ('%message{ContactId}','%message{FirstName}','%message{LastName}','%message{Phone}','%message{Email}',NOW(),NOW());</statement>
                      </jdbc-raw-data-capture-service>
                      <payload-from-metadata-service>
                        <unique-id>Return ID</unique-id>
                        <metadata-tokens>
                          <key-value-pair>
                            <key>ContactId</key>
                            <value>__CONTACT_ID__</value>
                          </key-value-pair>
                        </metadata-tokens>
                        <template><![CDATA[{"id" : "__CONTACT_ID__"}]]></template>
                      </payload-from-metadata-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>update</unique-id>
                    <services>
                    <!--
                      {
                        "FirstName" : "Lewin",
                        "LastName" : "Chan",
                        "Email" : "lchan@adaptris-abclabs.com",
                        "Phone" : "0700 987654",
                      }
                    -->
                      <json-path-service>
                        <source class="string-payload-data-input-parameter"/>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.FirstName</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>FirstName</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.LastName</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>LastName</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.Email</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>Email</metadata-key>
                          </target>
                        </json-path-execution>
                        <json-path-execution>
                          <source class="constant-data-input-parameter">
                            <value>$.Phone</value>
                          </source>
                          <target class="metadata-data-output-parameter">
                            <metadata-key>Phone</metadata-key>
                          </target>
                        </json-path-execution>
                      </json-path-service>

                      <jdbc-raw-data-capture-service>
                        <unique-id>Update Contact</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-timeout>
                          <unit>SECONDS</unit>
                          <interval>30</interval>
                        </statement-timeout>
                        <statement>UPDATE contacts SET FirstName='%message{FirstName}', LastName='%message{LastName}', Phone='%message{Phone}', Email='%message{Email}', LastUpdated=NOW() where id='%message{ContactId}'</statement>
                      </jdbc-raw-data-capture-service>
                      <jdbc-data-query-service>
                        <unique-id>Select Contact Records</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-creator class="jdbc-configured-sql-statement">
                          <statement>select * from contacts where id='%message{ContactId}'</statement>
                        </statement-creator>
                        <result-set-translator class="jdbc-json-payload-translator"/>
                      </jdbc-data-query-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>delete</unique-id>
                    <services>
                      <jdbc-raw-data-capture-service>
                        <unique-id>Delete Contact</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-timeout>
                          <unit>SECONDS</unit>
                          <interval>30</interval>
                        </statement-timeout>
                        <statement>DELETE FROM contacts where id='%message{ContactId}'</statement>
                      </jdbc-raw-data-capture-service>
                      <payload-from-metadata-service>
                        <unique-id>Return ID</unique-id>
                        <metadata-tokens>
                          <key-value-pair>
                            <key>ContactId</key>
                            <value>__CONTACT_ID__</value>
                          </key-value-pair>
                        </metadata-tokens>
                        <template><![CDATA[{"id" : "__CONTACT_ID__", "status": "deleted"}]]></template>
                      </payload-from-metadata-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>list</unique-id>
                    <services>
                      <jdbc-data-query-service>
                        <unique-id>Select ALL Records</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-creator class="jdbc-configured-sql-statement">
                          <statement>select * from contacts</statement>
                        </statement-creator>
                        <result-set-translator class="jdbc-json-payload-translator"/>
                      </jdbc-data-query-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>retrieve</unique-id>
                    <services>
                      <jdbc-data-query-service>
                        <unique-id>Select By ContactID</unique-id>
                        <connection class="shared-connection">
                          <lookup-name>LocalMySQL</lookup-name>
                        </connection>
                        <statement-creator class="jdbc-configured-sql-statement">
                          <statement>select * from contacts where id='%message{ContactId}'</statement>
                        </statement-creator>
                        <result-set-translator class="jdbc-json-payload-translator"/>
                      </jdbc-data-query-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>swagger</unique-id>
                    <services>
                      <aggregating-fs-consume-service>
                        <fs-consumer>
                          <destination class="consume-destination-from-metadata">
                            <default-destination>${swagger.yaml.file}</default-destination>
                          </destination>
                          <delete-aggregated-files>false</delete-aggregated-files>
                          <message-aggregator class="replace-with-first-message-aggregator"/>
                        </fs-consumer>
                      </aggregating-fs-consume-service>
                      <yaml-to-json>
                        <source class="string-payload-data-input-parameter"/>
                        <target class="string-payload-data-output-parameter"/>
                      </yaml-to-json>
                      <!-- rewrite the swagger so it has the correct hostname -->
                      <json-transform-service>
                        <source-json class="string-payload-data-input-parameter"/>
                        <target-json class="string-payload-data-output-parameter"/>
                        <mapping-spec class="constant-data-input-parameter">
                          <value>[{ "operation": "remove", "spec": {"host": "" }},{"operation": "shift", "spec": { "*": "&","#${adapter.api.hostname}": "host"}}]</value>
                        </mapping-spec>
                        <metadata-filter class="regex-metadata-filter"/>
                      </json-transform-service>
                    </services>
                  </service-list>

                  <service-list>
                    <unique-id>NotHandled</unique-id>
                    <services>
                      <add-metadata-service>
                        <metadata-element>
                          <key>ResponseCode</key>
                          <value>400</value>
                        </metadata-element>
                      </add-metadata-service>
                      <payload-from-metadata-service>
                        <metadata-tokens/>
                        <template><![CDATA[{"Status" : "Not Handled; please check"}]]></template>
                      </payload-from-metadata-service>
                    </services>
                  </service-list>

                </services>
              </branching-service-collection>
              <standalone-producer>
                <unique-id>Send Response</unique-id>
                <producer class="jetty-standard-response-producer">
                  <status-provider class="http-metadata-status">
                    <code-key>ResponseCode</code-key>
                    <default-status>OK_200</default-status>
                  </status-provider>
                  <response-header-provider class="jetty-no-response-headers"/>
                  <content-type-provider class="http-configured-content-type-provider">
                    <mime-type>application/json</mime-type>
                  </content-type-provider>
                  <send-payload>true</send-payload>
                </producer>
              </standalone-producer>
            </services>
          </service-collection>
        </standard-workflow>
      </workflow-list>
    </channel>
  </channel-list>
  <message-error-digester class="standard-message-error-digester">
    <digest-max-size>100</digest-max-size>
    <unique-id>ErrorDigest</unique-id>
  </message-error-digester>
</adapter>


text:
! { dg-do run }
program value_tests_f03
  use, intrinsic :: iso_c_binding
  real(c_double) :: myDouble
  interface
     subroutine value_test(myDouble) bind(c)
       use, intrinsic :: iso_c_binding
       real(c_double), value :: myDouble
     end subroutine value_test
  end interface

  myDouble = 9.0d0
  call value_test(myDouble)
end program value_tests_f03

subroutine value_test(myDouble) bind(c)
  use, intrinsic :: iso_c_binding
  real(c_double), value :: myDouble
  interface
     subroutine mySub(myDouble)
       use, intrinsic :: iso_c_binding
       real(c_double), value :: myDouble
     end subroutine mySub
  end interface

  myDouble = 10.0d0

  call mySub(myDouble)
end subroutine value_test

subroutine mySub(myDouble)
  use, intrinsic :: iso_c_binding
  real(c_double), value :: myDouble

  myDouble = 11.0d0
end subroutine mySub

redpajama_set_name: RedPajamaGithub


text:
package jadx.tests.integration.arrays;

import org.junit.jupiter.api.Test;

import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestRedundantType extends IntegrationTest {

	public static class TestCls {

		public byte[] method() {
			return new byte[] { 10, 11, 12 };
		}
	}

	@Test
	public void test() {
		ClassNode cls = getClassNode(TestCls.class);
		String code = cls.getCode().toString();

		assertThat(code, containsString("return new byte[]{10, 11, 12};"));
	}

	public static class TestByte {

		public byte[] method() {
			byte[] arr = new byte[50];
			arr[10] = 126;
			arr[20] = 127;
			arr[30] = (byte) 128;
			arr[40] = (byte) 129;
			return arr;
		}
	}

	@Test
	public void testByte() {
		ClassNode cls = getClassNode(TestByte.class);
		String code = cls.getCode().toString();

		assertThat(code, containsString("arr[10] = 126"));
		assertThat(code, containsString("arr[20] = Byte.MAX_VALUE"));
		assertThat(code, containsString("arr[30] = Byte.MIN_VALUE"));
		assertThat(code, containsString("arr[40] = -127"));
		assertEquals(-127, new TestByte().method()[40]);
	}

	public static class TestShort {

		public short[] method() {
			short[] arr = new short[50];
			arr[10] = 32766;
			arr[20] = 32767;
			arr[30] = (short) 32768;
			arr[40] = (short) 32769;
			return arr;
		}
	}

	@Test
	public void testShort() {
		ClassNode cls = getClassNode(TestShort.class);
		String code = cls.getCode().toString();

		assertThat(code, containsString("arr[10] = 32766"));
		assertThat(code, containsString("arr[20] = Short.MAX_VALUE"));
		assertThat(code, containsString("arr[30] = Short.MIN_VALUE"));
		assertThat(code, containsString("arr[40] = -32767"));
		assertEquals(-32767, new TestShort().method()[40]);
	}
}


text:
supported_attrs(::GadflyBackend) = merge_with_base_supported([
    :annotations,
    :background_color, :foreground_color, :color_palette,
    :group, :label, :seriestype,
    :seriescolor, :seriesalpha,
    :linecolor, :linestyle, :linewidth, :linealpha,
    :markershape, :markercolor, :markersize, :markeralpha,
    :markerstrokewidth, :markerstrokecolor, :markerstrokealpha,
    :fillrange, :fillcolor, :fillalpha,
    :bins, :n, :nc, :nr, :layout, :smooth,
    :title, :window_title, :show, :size,
    :x, :xguide, :xlims, :xticks, :xscale, :xflip,
    :y, :yguide, :ylims, :yticks, :yscale, :yflip,
    :z,
    :tickfont, :guidefont, :legendfont,
    :grid, :legend, :colorbar,
    :marker_z, :levels,
    :xerror, :yerror,
    :ribbon, :quiver,
    :orientation,
  ])
supported_types(::GadflyBackend) = [
        :path,
        :scatter, :hexbin,
        :bar,
        :contour, :shape
    ]
supported_styles(::GadflyBackend) = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot]
supported_markers(::GadflyBackend) = vcat(_allMarkers, Shape)
supported_scales(::GadflyBackend) = [:identity, :ln, :log2, :log10, :asinh, :sqrt]
is_subplot_supported(::GadflyBackend) = true

# --------------------------------------------------------------------------------------

function _initialize_backend(::GadflyBackend; kw...)
    @eval begin
        import Gadfly, Compose
        export Gadfly, Compose
        include(joinpath(dirname(@__FILE__), "gadfly_shapes.jl"))
    end
end

# ---------------------------------------------------------------------------

# immutable MissingVec <: AbstractVector{Float64} end
# Base.size(v::MissingVec) = (1,)
# Base.getindex(v::MissingVec, i::Integer) = 0.0

function createGadflyPlotObject(d::KW)
    gplt = Gadfly.Plot()
    gplt.mapping = Dict()
    gplt.data_source = Gadfly.DataFrames.DataFrame()
    # gplt.layers = gplt.layers[1:0]
    gplt.layers = [Gadfly.layer(Gadfly.Geom.point(tag=:remove), x=zeros(1), y=zeros(1));] # x=MissingVec(), y=MissingVec());]
    gplt.guides = Gadfly.GuideElement[Gadfly.Guide.xlabel(d[:xguide]),
                                   Gadfly.Guide.ylabel(d[:yguide]),
                                   Gadfly.Guide.title(d[:title])]
    gplt
end

# ---------------------------------------------------------------------------

function getLineGeom(d::KW)
    st = d[:seriestype]
    xbins, ybins = maketuple(d[:bins])
    if st == :hexb
        Gadfly.Geom.hexbin(xbincount = xbins, ybincount = ybins)
    elseif st == :histogram2d
        Gadfly.Geom.histogram2d(xbincount = xbins, ybincount = ybins)
    elseif st == :histogram
        Gadfly.Geom.histogram(bincount = xbins,
                              orientation = isvertical(d) ? :vertical : :horizontal,
                              position = d[:bar_position] == :stack ? :stack : :dodge)
    elseif st == :path
        Gadfly.Geom.path
    elseif st in (:bar, :sticks)
        Gadfly.Geom.bar
    elseif st == :steppost
        Gadfly.Geom.step
    elseif st == :steppre
        Gadfly.Geom.step(direction = :vh)
    elseif st == :hline
        Gadfly.Geom.hline
    elseif st == :vline
        Gadfly.Geom.vline
    elseif st == :contour
        Gadfly.Geom.contour(levels = d[:levels])
    # elseif st == :shape
    #     Gadfly.Geom.polygon(fill = true, preserve_order = true)
    else
        nothing
    end
end

function get_extra_theme_args(d::KW, k::Symbol)
    # gracefully handles old Gadfly versions
    extra_theme_args = KW()
    try
        extra_theme_args[:line_style] = Gadfly.get_stroke_vector(d[k])
    catch err
        if string(err) == "UndefVarError(:get_stroke_vector)"
            Base.warn_once("Gadfly.get_stroke_vector failed... do you have an old version of Gadfly?")
        else
            rethrow()
        end
    end
    extra_theme_args
end

function getGadflyLineTheme(d::KW)
    st = d[:seriestype]
    lc = convertColor(getColor(d[:linecolor]), d[:linealpha])
    fc = convertColor(getColor(d[:fillcolor]), d[:fillalpha])

    Gadfly.Theme(;
        default_color = (st in (:histogram,:histogram2d,:hexbin,:bar,:sticks) ? fc : lc),
        line_width = (st == :sticks ? 1 : d[:linewidth]) * Gadfly.px,
        # line_style = Gadfly.get_stroke_vector(d[:linestyle]),
        lowlight_color = x->RGB(fc),  # fill/ribbon
        lowlight_opacity = alpha(fc), # fill/ribbon
        bar_highlight = RGB(lc),      # bars
        get_extra_theme_args(d, :linestyle)...
    )
end

# add a line as a new layer
function addGadflyLine!(plt::Plot, numlayers::Int, d::KW, geoms...)
    gplt = getGadflyContext(plt)
    gfargs = vcat(geoms..., getGadflyLineTheme(d))
    kwargs = KW()
    st = d[:seriestype]

    # add a fill?
    if d[:fillrange] != nothing && st != :contour
        fillmin, fillmax = map(makevec, maketuple(d[:fillrange]))
        nmin, nmax = length(fillmin), length(fillmax)
        kwargs[:ymin] = Float64[min(y, fillmin[mod1(i, nmin)], fillmax[mod1(i, nmax)]) for (i,y) in enumerate(d[:y])]
        kwargs[:ymax] = Float64[max(y, fillmin[mod1(i, nmin)], fillmax[mod1(i, nmax)]) for (i,y) in enumerate(d[:y])]
        push!(gfargs, Gadfly.Geom.ribbon)
    end

    if st in (:hline, :vline)
        kwargs[st == :hline ? :yintercept : :xintercept] = d[:y]

    else
        if st == :sticks
            w = 0.01 * mean(diff(d[:x]))
            kwargs[:xmin] = d[:x] - w
            kwargs[:xmax] = d[:x] + w
        elseif st == :contour
            kwargs[:z] = d[:z].surf
            addGadflyContColorScale(plt, d[:linecolor])
        end

        kwargs[:x] = d[st == :histogram ? :y : :x]
        kwargs[:y] = d[:y]

    end

    # # add the layer
    Gadfly.layer(gfargs...; order=numlayers, kwargs...)
end

# ---------------------------------------------------------------------------

get_shape(sym::Symbol) = _shapes[sym]
get_shape(shape::Shape) = shape

# extract the underlying ShapeGeometry object(s)
getMarkerGeom(shapes::AVec) = gadflyshape(map(get_shape, shapes))
getMarkerGeom(other) = gadflyshape(get_shape(other))

# getMarkerGeom(shape::Shape) = gadflyshape(shape)
# getMarkerGeom(shape::Symbol) = gadflyshape(_shapes[shape])
# getMarkerGeom(shapes::AVec) = gadflyshape(map(gadflyshape, shapes)) # map(getMarkerGeom, shapes)
function getMarkerGeom(d::KW)
    if d[:seriestype] == :shape
        Gadfly.Geom.polygon(fill = true, preserve_order = true)
    else
        getMarkerGeom(d[:markershape])
    end
end

function getGadflyMarkerTheme(d::KW, attr::KW)
    c = getColor(d[:markercolor])
    α = d[:markeralpha]
    if α != nothing
        c = RGBA(RGB(c), α)
    end

    ms = d[:markersize]
    ms = if typeof(ms) <: AVec
        warn("Gadfly doesn't support variable marker sizes... using the average: $(mean(ms))")
        mean(ms) * Gadfly.px
    else
        ms * Gadfly.px
    end

    Gadfly.Theme(;
        default_color = c,
        default_point_size = ms,
        discrete_highlight_color = c -> RGB(getColor(d[:markerstrokecolor])),
        highlight_width = d[:markerstrokewidth] * Gadfly.px,
        line_width = d[:markerstrokewidth] * Gadfly.px,
        # get_extra_theme_args(d, :markerstrokestyle)...
    )
end

function addGadflyContColorScale(plt::Plot{GadflyBackend}, c)
    plt.attr[:colorbar] == :none && return
    if !isa(c, ColorGradient)
        c = default_gradient()
    end
    push!(getGadflyContext(plt).scales, Gadfly.Scale.ContinuousColorScale(p -> RGB(getColorZ(c, p))))
end

function addGadflyMarker!(plt::Plot, numlayers::Int, d::KW, attr::KW, geoms...)
    gfargs = vcat(geoms..., getGadflyMarkerTheme(d, attr), getMarkerGeom(d))
    kwargs = KW()

    # handle continuous color scales for the markers
    zcolor = d[:marker_z]
    if zcolor != nothing && typeof(zcolor) <: AVec
        kwargs[:color] = zcolor
        addGadflyContColorScale(plt, d[:markercolor])
    end

    Gadfly.layer(gfargs...; x = d[:x], y = d[:y], order=numlayers, kwargs...)
end

# ---------------------------------------------------------------------------

function addToGadflyLegend(plt::Plot, d::KW)
    if plt.attr[:legend] != :none && d[:label] != ""
        gplt = getGadflyContext(plt)

        # add the legend if needed
        if all(g -> !isa(g, Gadfly.Guide.ManualColorKey), gplt.guides)
            unshift!(gplt.guides, Gadfly.Guide.manual_color_key("", AbstractString[], Color[]))
        end

        # now add the series to the legend
        for guide in gplt.guides
            if isa(guide, Gadfly.Guide.ManualColorKey)
                # TODO: there's a BUG in gadfly if you pass in the same color more than once,
                # since gadfly will call unique(colors), but doesn't also merge the rows that match
                # Should ensure from this side that colors which are the same are merged together

                c = getColor(d[d[:markershape] == :none ? :linecolor : :markercolor])
                foundit = false

                # extend the label if we found this color
                for i in 1:length(guide.colors)
                    if RGB(c) == guide.colors[i]
                        guide.labels[i] *= ", " * d[:label]
                        foundit = true
                    end
                end

                # didn't find the color, so add a new entry into the legend
                if !foundit
                    push!(guide.labels, d[:label])
                    push!(guide.colors, c)
                end
            end
        end
    end
end

getGadflySmoothing(smooth::Bool) = smooth ? [Gadfly.Geom.smooth(method=:lm)] : Any[]
getGadflySmoothing(smooth::Real) = [Gadfly.Geom.smooth(method=:loess, smoothing=float(smooth))]

function addGadflySeries!(plt::Plot, d::KW)
    layers = Gadfly.Layer[]
    gplt = getGadflyContext(plt)

    # add a regression line?
    # TODO: make more flexible
    smooth = getGadflySmoothing(d[:smooth])

    # lines
    geom = getLineGeom(d)
    if geom != nothing
        prepend!(layers, addGadflyLine!(plt, length(gplt.layers), d, geom, smooth...))
        smooth = Any[] # don't add a regression for markers too
    end

    # special handling for ohlc and scatter
    st = d[:seriestype]
    # if st == :ohlc
    #     error("Haven't re-implemented after refactoring")
    if st in (:histogram2d, :hexbin) && (isa(d[:fillcolor], ColorGradient) || isa(d[:fillcolor], ColorFunction))
        push!(gplt.scales, Gadfly.Scale.ContinuousColorScale(p -> RGB(getColorZ(d[:fillcolor], p))))
    elseif st == :scatter && d[:markershape] == :none
        d[:markershape] = :circle
    end

    # markers
    if d[:markershape] != :none || st == :shape
        prepend!(layers, addGadflyMarker!(plt, length(gplt.layers), d, plt.attr, smooth...))
    end

    st in (:histogram2d, :hexbin, :contour) || addToGadflyLegend(plt, d)

    # now save the layers that apply to this series
    d[:gadflylayers] = layers
    prepend!(gplt.layers, layers)
end

# ---------------------------------------------------------------------------

# NOTE: I'm leaving this here and commented out just in case I want to implement again... it was hacky code to create multi-colored line segments

#   # colorgroup
#   z = d[:z]

#   # handle line segments of different colors
#   cscheme = d[:linecolor]
#   if isa(cscheme, ColorVector)
#     # create a color scale, and set the color group to the index of the color
#     push!(gplt.scales, Gadfly.Scale.color_discrete_manual(cscheme.v...))

#     # this is super weird, but... oh well... for some reason this creates n separate line segments...
#     # create a list of vertices that go: [x1,x2,x2,x3,x3, ... ,xi,xi, ... xn,xn] (same for y)
#     # then the vector passed to the "color" keyword should be a vector: [1,1,2,2,3,3,4,4, ..., i,i, ... , n,n]
#     csindices = Int[mod1(i,length(cscheme.v)) for i in 1:length(d[:y])]
#     cs = collect(repmat(csindices', 2, 1))[1:end-1]
#     grp = collect(repmat((1:length(d[:y]))', 2, 1))[1:end-1]
#     d[:x], d[:y] = map(createSegments, (d[:x], d[:y]))
#     colorgroup = [(:linecolor, cs), (:group, grp)]

# ---------------------------------------------------------------------------

function addGadflyTicksGuide(gplt, ticks, isx::Bool)
    ticks == :auto && return

    # remove the ticks?
    if ticks in (:none, false, nothing)
        return addOrReplace(gplt.guides, isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks; label=false)
    end

    ttype = ticksType(ticks)

    # just the values... put ticks here, but use standard labels
    if ttype == :ticks
        gtype = isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks
        replaceType(gplt.guides, gtype(ticks = collect(ticks)))

    # set the ticks and the labels
    # Note: this is pretty convoluted, but I think it works.  We set the ticks using Gadfly.Guide,
    #   and then set the label function (wraps a dict lookup) through a continuous Gadfly.Scale.
    elseif ttype == :ticks_and_labels
        gtype = isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks
        replaceType(gplt.guides, gtype(ticks = collect(ticks[1])))

        # # TODO add xtick_label function (given tick, return label??)
        # # Scale.x_discrete(; labels=nothing, levels=nothing, order=nothing)
        # filterGadflyScale(gplt, isx)
        # gfunc = isx ? Gadfly.Scale.x_discrete : Gadfly.Scale.y_discrete
        # labelmap = Dict(zip(ticks...))
        # labelfunc = val -> labelmap[val]
        # push!(gplt.scales, gfunc(levels = collect(ticks[1]), labels = labelfunc))

        filterGadflyScale(gplt, isx)
        gfunc = isx ? Gadfly.Scale.x_continuous : Gadfly.Scale.y_continuous
        labelmap = Dict(zip(ticks...))
        labelfunc = val -> labelmap[val]
        push!(gplt.scales, gfunc(labels = labelfunc))

    else
        error("Invalid input for $(isx ? "xticks" : "yticks"): ", ticks)
    end
end

continuousAndSameAxis(scale, isx::Bool) = isa(scale, Gadfly.Scale.ContinuousScale) && scale.vars[1] == (isx ? :x : :y)
filterGadflyScale(gplt, isx::Bool) = filter!(scale -> !continuousAndSameAxis(scale, isx), gplt.scales)

function getGadflyScaleFunction(d::KW, isx::Bool)
    scalekey = isx ? :xscale : :yscale
    hasScaleKey = haskey(d, scalekey)
    if hasScaleKey
        scale = d[scalekey]
        scale == :ln && return isx ? Gadfly.Scale.x_log : Gadfly.Scale.y_log, hasScaleKey, log
        scale == :log2 && return isx ? Gadfly.Scale.x_log2 : Gadfly.Scale.y_log2, hasScaleKey, log2
        scale == :log10 && return isx ? Gadfly.Scale.x_log10 : Gadfly.Scale.y_log10, hasScaleKey, log10
        scale == :asinh && return isx ? Gadfly.Scale.x_asinh : Gadfly.Scale.y_asinh, hasScaleKey, asinh
        scale == :sqrt && return isx ? Gadfly.Scale.x_sqrt : Gadfly.Scale.y_sqrt, hasScaleKey, sqrt
    end
    isx ? Gadfly.Scale.x_continuous : Gadfly.Scale.y_continuous, hasScaleKey, identity
end

function addGadflyLimitsScale(gplt, d::KW, isx::Bool)
    gfunc, hasScaleKey, func = getGadflyScaleFunction(d, isx)

    # do we want to add min/max limits for the axis?
    limsym = isx ? :xlims : :ylims
    limargs = Any[]

    # map :auto to nothing, otherwise add to limargs
    lims = get(d, limsym, :auto)
    if lims == :auto
        lims = nothing
    else
        if limsType(lims) == :limits
            push!(limargs, (:minvalue, min(lims...)))
            push!(limargs, (:maxvalue, max(lims...)))
        else
            error("Invalid input for $(isx ? "xlims" : "ylims"): ", lims)
        end
    end

    # replace any current scales with this one
    if hasScaleKey || !isempty(limargs)
        filterGadflyScale(gplt, isx)
        push!(gplt.scales, gfunc(; limargs...))
    end

    lims, func
end

function updateGadflyAxisFlips(gplt, d::KW, xlims, ylims, xfunc, yfunc)
    if isa(gplt.coord, Gadfly.Coord.Cartesian)
        gplt.coord = Gadfly.Coord.cartesian(
            gplt.coord.xvars,
            gplt.coord.yvars;
            xmin = xlims == nothing ? gplt.coord.xmin : xfunc(minimum(xlims)),
            xmax = xlims == nothing ? gplt.coord.xmax : xfunc(maximum(xlims)),
            ymin = ylims == nothing ? gplt.coord.ymin : yfunc(minimum(ylims)),
            ymax = ylims == nothing ? gplt.coord.ymax : yfunc(maximum(ylims)),
            xflip = get(d, :xflip, gplt.coord.xflip),
            yflip = get(d, :yflip, gplt.coord.yflip),
            fixed = gplt.coord.fixed,
            aspect_ratio = gplt.coord.aspect_ratio,
            raster = gplt.coord.raster
        )
    else
        gplt.coord = Gadfly.Coord.Cartesian(
            xflip = get(d, :xflip, false),
            yflip = get(d, :yflip, false)
        )
    end
end

function findGuideAndSet(gplt, t::DataType, args...; kw...)
    for (i,guide) in enumerate(gplt.guides)
        if isa(guide, t)
            gplt.guides[i] = t(args...; kw...)
        end
    end
end

function updateGadflyGuides(plt::Plot, d::KW)
    gplt = getGadflyContext(plt)
    haskey(d, :title) && findGuideAndSet(gplt, Gadfly.Guide.title, string(d[:title]))
    haskey(d, :xguide) && findGuideAndSet(gplt, Gadfly.Guide.xlabel, string(d[:xguide]))
    haskey(d, :yguide) && findGuideAndSet(gplt, Gadfly.Guide.ylabel, string(d[:yguide]))

    xlims, xfunc = addGadflyLimitsScale(gplt, d, true)
    ylims, yfunc = addGadflyLimitsScale(gplt, d, false)

    ticks = get(d, :xticks, :auto)
    if ticks == :none
        _remove_axis(plt, true)
    else
        addGadflyTicksGuide(gplt, ticks, true)
    end
    ticks = get(d, :yticks, :auto)
    if ticks == :none
        _remove_axis(plt, false)
    else
        addGadflyTicksGuide(gplt, ticks, false)
    end

    updateGadflyAxisFlips(gplt, d, xlims, ylims, xfunc, yfunc)
end

function updateGadflyPlotTheme(plt::Plot, d::KW)
    kwargs = KW()

    # colors
    insidecolor, gridcolor, textcolor, guidecolor, legendcolor =
        map(s -> getColor(d[s]), (
            :background_color_inside,
            :foreground_color_grid,
            :foreground_color_text,
            :foreground_color_guide,
            :foreground_color_legend
        ))

    # # hide the legend?
    leg = d[d[:legend] == :none ? :colorbar : :legend]
    if leg != :best
        kwargs[:key_position] = leg == :inside ? :right : leg
    end

    if !get(d, :grid, true)
        kwargs[:grid_color] = gridcolor
    end

    # fonts
    tfont, gfont, lfont = d[:tickfont], d[:guidefont], d[:legendfont]

    getGadflyContext(plt).theme = Gadfly.Theme(;
        background_color = insidecolor,
        minor_label_color = textcolor,
        minor_label_font = tfont.family,
        minor_label_font_size = tfont.pointsize * Gadfly.pt,
        major_label_color = guidecolor,
        major_label_font = gfont.family,
        major_label_font_size = gfont.pointsize * Gadfly.pt,
        key_title_color = guidecolor,
        key_title_font = gfont.family,
        key_title_font_size = gfont.pointsize * Gadfly.pt,
        key_label_color = legendcolor,
        key_label_font = lfont.family,
        key_label_font_size = lfont.pointsize * Gadfly.pt,
        plot_padding = 1 * Gadfly.mm,
        kwargs...
    )
end

# ----------------------------------------------------------------

function createGadflyAnnotationObject(x, y, val::AbstractString)
    Gadfly.Guide.annotation(Compose.compose(
                              Compose.context(),
                              Compose.text(x, y, val)
                            ))
end

function createGadflyAnnotationObject(x, y, txt::PlotText)
    halign = (txt.font.halign == :hcenter ? Compose.hcenter : (txt.font.halign == :left ? Compose.hleft : Compose.hright))
    valign = (txt.font.valign == :vcenter ? Compose.vcenter : (txt.font.valign == :top ? Compose.vtop : Compose.vbottom))
    rotations = (txt.font.rotation == 0.0 ? [] : [Compose.Rotation(txt.font.rotation, Compose.Point(Compose.x_measure(x), Compose.y_measure(y)))])
    Gadfly.Guide.annotation(Compose.compose(
                              Compose.context(),
                              Compose.text(x, y, txt.str, halign, valign, rotations...),
                              Compose.font(string(txt.font.family)),
                              Compose.fontsize(txt.font.pointsize * Gadfly.pt),
                              Compose.stroke(txt.font.color),
                              Compose.fill(txt.font.color)
                            ))
end

function _add_annotations{X,Y,V}(plt::Plot{GadflyBackend}, anns::AVec{Tuple{X,Y,V}})
    for ann in anns
        push!(plt.o.guides, createGadflyAnnotationObject(ann...))
    end
end

# ---------------------------------------------------------------------------

# create a blank Gadfly.Plot object
# function _create_plot(pkg::GadflyBackend, d::KW)
#     gplt = createGadflyPlotObject(d)
#     Plot(gplt, pkg, 0, d, KW[])
# end
function _create_backend_figure(plt::Plot{GadflyBackend})
    createGadflyPlotObject(plt.attr)
end

# plot one data series
# function _series_added(::GadflyBackend, plt::Plot, d::KW)
function _series_added(plt::Plot{GadflyBackend}, series::Series)
    # first clear out the temporary layer
    gplt = getGadflyContext(plt)
    if gplt.layers[1].geom.tag == :remove
        gplt.layers = gplt.layers[2:end]
    end

    addGadflySeries!(plt, series.d)
    # push!(plt.seriesargs, d)
    # plt
end

function _update_plot_object(plt::Plot{GadflyBackend}, d::KW)
    updateGadflyGuides(plt, d)
    updateGadflyPlotTheme(plt, d)
end

# ----------------------------------------------------------------

# accessors for x/y data

# TODO: need to save all the layer indices which apply to this series
function getGadflyMappings(plt::Plot, i::Integer)
    @assert i > 0 && i <= plt.n
    mappings = [l.mapping for l in plt.seriesargs[i][:gadflylayers]]
end

function getxy(plt::Plot{GadflyBackend}, i::Integer)
    mapping = getGadflyMappings(plt, i)[1]
    mapping[:x], mapping[:y]
end

function setxy!{X,Y}(plt::Plot{GadflyBackend}, xy::Tuple{X,Y}, i::Integer)
    for mapping in getGadflyMappings(plt, i)
        mapping[:x], mapping[:y] = xy
    end
    plt
end

# ----------------------------------------------------------------

# # create the underlying object (each backend will do this differently)
# function _create_subplot(subplt::Subplot{GadflyBackend}, isbefore::Bool)
#     isbefore && return false # wait until after plotting to create the subplots
#     subplt.o = nothing
#     true
# end

function _remove_axis(plt::Plot{GadflyBackend}, isx::Bool)
    gplt = getGadflyContext(plt)
    addOrReplace(gplt.guides, isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks; label=false)
    addOrReplace(gplt.guides, isx ? Gadfly.Guide.xlabel : Gadfly.Guide.ylabel, "")
end

function _expand_limits(lims, plt::Plot{GadflyBackend}, isx::Bool)
    for l in getGadflyContext(plt).layers
        _expand_limits(lims, l.mapping[isx ? :x : :y])
    end
end

# ----------------------------------------------------------------

getGadflyContext(plt::Plot{GadflyBackend}) = plt.o
# getGadflyContext(subplt::Subplot{GadflyBackend}) = buildGadflySubplotContext(subplt)

# # create my Compose.Context grid by hstacking and vstacking the Gadfly.Plot objects
# function buildGadflySubplotContext(subplt::Subplot)
#     rows = Any[]
#     row = Any[]
#     for (i,(r,c)) in enumerate(subplt.layout)
#
#         # add the Plot object to the row
#         push!(row, getGadflyContext(subplt.plts[i]))
#
#         # add the row
#         if c == ncols(subplt.layout, r)
#             push!(rows, Gadfly.hstack(row...))
#             row = Any[]
#         end
#     end
#
#     # stack the rows
#     Gadfly.vstack(rows...)
# end

setGadflyDisplaySize(w,h) = Compose.set_default_graphic_size(w * Compose.px, h * Compose.px)
setGadflyDisplaySize(plt::Plot) = setGadflyDisplaySize(plt.attr[:size]...)
# setGadflyDisplaySize(subplt::Subplot) = setGadflyDisplaySize(getattr(subplt, 1)[:size]...)
# -------------------------------------------------------------------------

function doshow{P<:Union{GadflyBackend,ImmerseBackend}}(io::IO, func, plt::AbstractPlot{P})
    gplt = getGadflyContext(plt)
    setGadflyDisplaySize(plt)
    Gadfly.draw(func(io, Compose.default_graphic_width, Compose.default_graphic_height), gplt)
end

getGadflyWriteFunc(::MIME"image/png") = Gadfly.PNG
getGadflyWriteFunc(::MIME"image/svg+xml") = Gadfly.SVG
# getGadflyWriteFunc(::MIME"text/html") = Gadfly.SVGJS
getGadflyWriteFunc(::MIME"application/pdf") = Gadfly.PDF
getGadflyWriteFunc(::MIME"application/postscript") = Gadfly.PS
getGadflyWriteFunc(::MIME"application/x-tex") = Gadfly.PGF
getGadflyWriteFunc(m::MIME) = error("Unsupported in Gadfly/Immerse: ", m)

for mime in (MIME"image/png", MIME"image/svg+xml", MIME"application/pdf", MIME"application/postscript", MIME"application/x-tex")
    @eval function Base.show{P<:Union{GadflyBackend,ImmerseBackend}}(io::IO, ::$mime, plt::AbstractPlot{P})
        func = getGadflyWriteFunc($mime())
        doshow(io, func, plt)
    end
end

function Base.display(::PlotsDisplay, plt::Plot{GadflyBackend})
    setGadflyDisplaySize(plt.attr[:size]...)
    display(plt.o)
end

# function Base.display(::PlotsDisplay, subplt::Subplot{GadflyBackend})
#     setGadflyDisplaySize(getattr(subplt,1)[:size]...)
#     ctx = buildGadflySubplotContext(subplt)
#
#     # taken from Gadfly since I couldn't figure out how to do it directly
#
#     filename = string(Gadfly.tempname(), ".html")
#     output = open(filename, "w")
#
#     plot_output = IOBuffer()
#     Gadfly.draw(Gadfly.SVGJS(plot_output, Compose.default_graphic_width,
#              Compose.default_graphic_height, false), ctx)
#     plotsvg = takebuf_string(plot_output)
#
#     write(output,
#       """
#       <!DOCTYPE html>
#       <html>
#         <head>
#           <title>Gadfly Plot</title>
#           <meta charset="utf-8">
#         </head>
#           <body>
#           <script charset="utf-8">
#               $(readall(Compose.snapsvgjs))
#           </script>
#           <script charset="utf-8">
#               $(readall(Gadfly.gadflyjs))
#           </script>
#           $(plotsvg)
#         </body>
#       </html>
#       """)
#     close(output)
#     Gadfly.open_file(filename)
# end


text:
id: 2235
title: Cliff McIntosh uses his software development skills for social good through Code for Nepal
date: 2018-11-10T10:34:18-05:00
author: Shrijana Khanal
layout: post
guid: https://codefornepal.org/?p=2235
permalink: /2018/11/cliff-mcintosh/
sidebar:
  - choice
categories:
  - dataviz
  - General
  - member
tags:
  - Code for Nepal
  - nepal
  - opendata
  - volunteer
---

    Photo: Cliff McIntosh

Code for Nepal is made by volunteers. We believe everyone can contribute. If you would like to join Code for Nepal, [contact us](https://codefornepal.org/en/help/).

Read about **Cliff McIntosh**, a member of Code for Nepal who leads the development of [NepalMap](https://nepalmap.org/), a web app that puts Nepal’s data at your fingertips.

**_Who are you and tell us how/where did you grow up?
_**
I am Cliff McIntosh. I grew up in west Texas in the U.S. These days, I live in Chicago and work as a software developer.

**_How did you become involved with Code for Nepal?
_**
I have had an interest in Nepal from the time that I was a Peace Corps volunteer teaching English in Dadeldhura district. I was looking for a volunteer opportunity and answered a call for volunteers on the Code for Nepal website. Ravi Nepal asked if I would be interested in helping launch a tool that makes census and other data available. That's how I became involved with Code for Nepal and our NepalMap project.

**_Code for Nepal is a volunteer-run organization, many of the volunteers have daytime jobs outside of Code for Nepal. Therefore, where is your passion and dedication for this organization derived from?
_**
I want to be able to use my software development skills for social good. Working with Code for Nepal on the NepalMap project allows me to do that.

****_What is your role in Code for Nepal? Do you see yourself changing this role anytime in the future?_****

I am a developer on the NepalMap project. Amit Chaudhary and I worked closely with other Code for Nepal team members and volunteers to launch the first version of the project. I am the team member who serves as the primary resource for working with the Wazimap framework that we use for NepalMap. I hope to continue to serve as a developer with NepalMap, but I would also like to have the opportunity to mentor other developers so that responsibility and skills can be shared.

**_How is Code for Nepal different or special from other non-profits?
_** **_
_** Code for Nepal is different because it allows us to get involved by using our technical skills to serve a social good.


text:
<?php

use Nette\Application\UI\Form;
use Nette\Utils\Json;

class CommunityFormPlugin extends Form
{
  static $events = array();

  public $tags;
  public $projects;

  public function __construct()
  {
    parent::__construct();

    $this->tags = array();
    $tags = PagesModel::getPageById(27)->getMeta('tag_options');
    foreach (explode("\n", $tags) as $t) {
      $t = trim($t);
      $this->tags[$t] = $t;
    }

    $this->projects = PagesModel::getPagesByMeta("project_tag")->getPairs('');

    $this->addText('username', 'OSM.org username')->setDisabled();

    $this->addText('fullname', 'Celé jméno')
      ->setOption('description', 'Ať se poznáme!')
      ->addRule(Form::FILLED, '%label není vyplněn.')
      ->addRule(Form::MIN_LENGTH, '%label musí mít alespoň 5 znaků.', 5);

    $this->addText('email', 'Talk-cz')
      ->setOption(
        'description',
        'Email použivaný pro spočítání příspěvků v talk-cz (neveřejný)'
      )
      ->addRule(Form::FILLED, '%label není vyplněn.')
      ->addRule(Form::EMAIL, '%label není validní.');

    $this->addText('contact', 'Veřejný e-mail')
      ->setOption('description', '(nepovinné)')
      ->addCondition(Form::FILLED)
      ->addRule(Form::EMAIL, '%label není validní.');

    $this->addText('twitter', 'Twitter')->setOption(
      'description',
      '(nepovinné) Uživatelské jméno bez zavináče'
    );
    $this->addText('github', 'Github')->setOption(
      'description',
      '(nepovinné) Uživatelské jméno'
    );

    $this->addText('places', 'Výskyt')->setOption(
      'description',
      '(nepovinné) Kde se vyskystuju - typicky jaká města.'
    );
    $this['places']->getControlPrototype()->placeholder = 'oddělené čárkou';
    $this['places']->getControlPrototype()->style = 'width: 40%';

    $this->addText('tags', 'Oblasti zájmu')->setOption(
      'description',
      '(nepovinné)'
    );
    $this['tags']->getControlPrototype()->placeholder = 'oddělené čárkou';
    $this['tags']->getControlPrototype()->style = 'width: 60%';
    $this['tags']->getControlPrototype()->{'data-options'} = Json::encode(
      array_values($this->tags)
    );

    $this->addMultiSelect('projects', 'Projekty', $this->projects)
      ->setOption(
        'description',
        '(nepovinné) Projektovou stránku možno přidat v administraci. Případně napiš na dev@openstreetmap.cz'
      )
      ->getControlPrototype()->style = 'height:150px;width:40%';

    $this->addCheckbox('public', 'Zveřejnit údaje na openstreetmap.cz');

    $this->addSubmit('submit', 'Uložit údaje');
    $this->onSuccess[] = callback($this, 'submitted');

    $renderer = $this->getRenderer();
    $renderer->wrappers['controls']['container'] =
      'table class="table form-inline"';
    $renderer->wrappers['error']['container'] = 'ul class="bg-danger"';
    $renderer->wrappers['control']['.text'] = 'form-control';
    $renderer->wrappers['control']['.email'] = 'form-control';
    $renderer->wrappers['control']['.submit'] = 'btn btn-primary';
  }

  protected function attached($presenter)
  {
    parent::attached($presenter);

    if (!$this->isSubmitted()) {
      $row = dibi::fetch(
        "SELECT * FROM users WHERE username = %s",
        $presenter->user->id
      );
      $row['tags'] = $row['tags'];
      $row['projects'] = array_map(function ($a) {
        return trim($a, '()');
      }, explode(",", $row['projects']));
      if ($row) {
        $this->setValues($row);
      }
    }
  }

  public function submitted()
  {
    if ($this->presenter->user->id) {
      $values = $this->values;
      $values['projects'] = join(
        ",",
        array_map(function ($a) {
          return "($a)";
        }, $values['projects'])
      );
      dibi::query(
        "UPDATE users SET",
        $values,
        "WHERE username = %s",
        $this->presenter->user->id
      ); //our id is username
      $this->presenter->flashMessage(
        'Profil upraven pro ' . $this->presenter->user->id
      );
    }

    $this->presenter->redirect('this');
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DirectoryPickerView.xaml.cs" company="CatenaLogic">
//   Copyright (c) 2014 - 2015 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace RepositoryCleaner.Views
{
    using System.Windows;
    using Catel.MVVM.Views;

    /// <summary>
    ///     Interaction logic for DirectoryPickerView.xaml
    /// </summary>
    public partial class DirectoryPickerView
    {
        static DirectoryPickerView()
        {
            typeof (DirectoryPickerView).AutoDetectViewPropertiesToSubscribe();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DirectoryPickerView"/> class.
        /// </summary>
        /// <remarks>This method is required for design time support.</remarks>
        public DirectoryPickerView()
        {
            InitializeComponent();
        }

        #region Properties
        [ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)]
        public double LabelWidth
        {
            get { return (double) GetValue(LabelWidthProperty); }
            set { SetValue(LabelWidthProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LabelWidth.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LabelWidthProperty = DependencyProperty.Register(nameof(LabelWidth), typeof (double), typeof (DirectoryPickerView), new PropertyMetadata(125d));

        [ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)]
        public string LabelText
        {
            get { return (string) GetValue(LabelTextProperty); }
            set { SetValue(LabelTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LabelText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LabelTextProperty = DependencyProperty.Register(nameof(LabelText), typeof (string), typeof (DirectoryPickerView), new PropertyMetadata(string.Empty));

        [ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)]
        public string SelectedDirectory
        {
            get { return (string) GetValue(SelectedDirectoryProperty); }
            set { SetValue(SelectedDirectoryProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedDirectory.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedDirectoryProperty = DependencyProperty.Register(nameof(SelectedDirectory), typeof (string),
            typeof (DirectoryPickerView), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        #endregion
    }
}


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=ISO-8859-1" /><title>DocumentException xref</title>
<link type="text/css" rel="stylesheet" href="../../stylesheet.css" />

View Javadoc

1
7
8   package org.dom4j;
9
10  import java.io.PrintStream;
11  import java.io.PrintWriter;
12
13  /***
14   * <p>
15   * <code>DocumentException</code> is a nested Exception which may be thrown
16   * during the processing of a DOM4J document.
17   * </p>
18   *
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.7 $
21   */
22  public class DocumentException extends Exception {
23      /*** A wrapped <code>Throwable</code> */
24      private Throwable nestedException;
25
26      public DocumentException() {
27          super("Error occurred in DOM4J application.");
28      }
29
30      public DocumentException(String message) {
31          super(message);
32      }
33
34      public DocumentException(Throwable nestedException) {
35          super(nestedException.getMessage());
36          this.nestedException = nestedException;
37      }
38
39      public DocumentException(String message, Throwable nestedException) {
40          super(message);
41          this.nestedException = nestedException;
42      }
43
44      public Throwable getNestedException() {
45          return nestedException;
46      }
47
48      public String getMessage() {
49          if (nestedException != null) {
50              return super.getMessage() + " Nested exception: "
51                      + nestedException.getMessage();
52          } else {
53              return super.getMessage();
54          }
55      }
56
57      public void printStackTrace() {
58          super.printStackTrace();
59
60          if (nestedException != null) {
61              System.err.print("Nested exception: ");
62              nestedException.printStackTrace();
63          }
64      }
65
66      public void printStackTrace(PrintStream out) {
67          super.printStackTrace(out);
68
69          if (nestedException != null) {
70              out.println("Nested exception: ");
71              nestedException.printStackTrace(out);
72          }
73      }
74
75      public void printStackTrace(PrintWriter writer) {
76          super.printStackTrace(writer);
77
78          if (nestedException != null) {
79              writer.println("Nested exception: ");
80              nestedException.printStackTrace(writer);
81          }
82      }
83  }
84
85  /*
86   * Redistribution and use of this software and associated documentation
87   * ("Software"), with or without modification, are permitted provided that the
88   * following conditions are met:
89   *
90   * 1. Redistributions of source code must retain copyright statements and
91   * notices. Redistributions must also contain a copy of this document.
92   *
93   * 2. Redistributions in binary form must reproduce the above copyright notice,
94   * this list of conditions and the following disclaimer in the documentation
95   * and/or other materials provided with the distribution.
96   *
97   * 3. The name "DOM4J" must not be used to endorse or promote products derived
98   * from this Software without prior written permission of MetaStuff, Ltd. For
99   * written permission, please contact dom4j-info@metastuff.com.
100  *
101  * 4. Products derived from this Software may not be called "DOM4J" nor may
102  * "DOM4J" appear in their names without prior written permission of MetaStuff,
103  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
104  *
105  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
106  *
107  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
108  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
109  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
110  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
111  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
112  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
113  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
114  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
115  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
116  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
117  * POSSIBILITY OF SUCH DAMAGE.
118  *
119  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
120  */

This page was automatically generated by Maven


text:
import torch

from . import BaseWrapperDataset

class ColorizeDataset(BaseWrapperDataset):
    """ Adds 'colors' property to net input that is obtained from the provided color getter for use by models """
    def __init__(self, dataset, color_getter):
        super().__init__(dataset)
        self.color_getter = color_getter

    def collater(self, samples):
        base_collate = super().collater(samples)
        if len(base_collate) > 0:
            base_collate["net_input"]["colors"] = torch.tensor(
                list(self.color_getter(self.dataset, s["id"]) for s in samples),
                dtype=torch.long,
            )
        return base_collate


text:
import sys
import time
import pmclient as pmc

# ENDPOINT = "http://sp.int3.sonata-nfv.eu:8001"
# ENDPOINT = "http://127.0.0.1:8001"

def _get_test_plugin():
    ENDPOINT = sys.argv[1]
    uuid_list = pmc.plugin_list(ENDPOINT)
    print(uuid_list)
    # try to identify test plugin record
    for uuid in uuid_list:
        info = pmc.plugin_info(uuid, ENDPOINT)
        print(info)
        if info.get("name") == "son-plugin.TestPlugin":
            return info
    return None

def main():
    """
    Assumption: Testplugin was recently started.
    We now ask the PM about the running testplugin and validate
    that its registered correctly.
    After this, we try to remotely stop the plugin.
    """
    if len(sys.argv) < 2:
        print("PM endpoint needed as first argument.")
        exit(1)
    ENDPOINT = sys.argv[1]
    # check if test plugin is not there
    test_info = _get_test_plugin()
    if test_info is None:
        raise BaseException("Test plugin record was not found!")

    # check test plugin record
    if test_info.get("state") != "RUNNING":
        raise BaseException("Test plugin state != RUNNING")

    # try to stop test plugin
    print("REMOVE: %r" % test_info.get("uuid"))
    pmc.plugin_remove(test_info.get("uuid"), ENDPOINT)

    # check if plugin is not there anymore
    time.sleep(3)
    test_info2 = _get_test_plugin()
    if test_info2 is not None:
        raise BaseException("Test plugin record was not removed correctly!")

if __name__ == '__main__':
    print("=" * 48)
    print("BEGIN test.py")
    main()
    print("END test.py")
    print("=" * 48)


text:
@implementation PageScroll
- (id)initWithScrollView:(UIScrollView *)sv andRefreshBlock:(void(^)(UIScrollView *scrollView,BOOL loadFromBottom))block{
    self = [super init];
    if (self) {
        [self setScrollView:sv];
        [self setRefreshBlock:block];
        _distanceFromTopToReload = 150;
        _distanceFromBottomToReload = 150;
    }
    return self;
}

- (void)setScrollView:(UIScrollView *)scrollView{
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
    _scrollView = scrollView;
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)dealloc{
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if(([keyPath isEqualToString:@"contentOffset"]) && object == _scrollView && !_paused) {
        if (_scrollView.contentOffset.y + _scrollView.frame.size.height > _scrollView.contentSize.height - _distanceFromBottomToReload) {
            if (self.refreshBlock) {
                self.refreshBlock(_scrollView,YES);
            }
        }else if(_scrollView.contentOffset.y < _distanceFromTopToReload){
            if (self.refreshBlock) {
                self.refreshBlock(_scrollView,NO);
            }
        }
    }
}

@end


text:
"""Tests for print_functions module."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gast

from tensorflow.contrib.py2tf.converters import converter_test_base
from tensorflow.contrib.py2tf.converters import print_functions
from tensorflow.contrib.py2tf.pyct import compiler
from tensorflow.python.platform import test

class PrintFunctionsTest(converter_test_base.TestCase):

  def test_transform(self):

    def test_fn(a):
      print(a)

    node = self.parse_and_analyze(test_fn, {'print': print})
    node = print_functions.transform(node)
    result = compiler.ast_to_object(node)

    result.test_fn('a')
    self.assertTrue(isinstance(node.body[0].body[0].value, gast.Call))

if __name__ == '__main__':
  test.main()


text:
class AccessibilityLabelsMenuObserver;
class ClickToCallContextMenuObserver;
class LinkToTextMenuObserver;
class PrintPreviewContextMenuObserver;
class Profile;
class QuickAnswersMenuObserver;
class SharedClipboardContextMenuObserver;
class SpellingMenuObserver;
class SpellingOptionsSubMenuObserver;
class NotesSubMenuObserver;

namespace content {
class RenderFrameHost;
class WebContents;
}

namespace extensions {
class Extension;
class MenuItem;
}

namespace gfx {
class Point;
}

namespace blink {
namespace mojom {
class MediaPlayerAction;
}
}

namespace ui {
class DataTransferEndpoint;
}

namespace web_app {
class SystemWebAppDelegate;
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
namespace policy {
class DlpRulesManager;
}  // namespace policy
#endif

class RenderViewContextMenu
    : public RenderViewContextMenuBase,
      public custom_handlers::ProtocolHandlerRegistry::Observer {
 public:
  using ExecutePluginActionCallback =
      base::OnceCallback<void(content::RenderFrameHost*,
                              blink::mojom::PluginActionType)>;

  RenderViewContextMenu(content::RenderFrameHost& render_frame_host,
                        const content::ContextMenuParams& params);

  RenderViewContextMenu(const RenderViewContextMenu&) = delete;
  RenderViewContextMenu& operator=(const RenderViewContextMenu&) = delete;

  ~RenderViewContextMenu() override;

  // Adds the spell check service item to the context menu.
  static void AddSpellCheckServiceItem(ui::SimpleMenuModel* menu,
                                       bool is_checked);

  // RenderViewContextMenuBase:
  bool IsCommandIdChecked(int command_id) const override;
  bool IsCommandIdVisible(int command_id) const override;
  bool IsCommandIdEnabled(int command_id) const override;
  void ExecuteCommand(int command_id, int event_flags) override;
  void AddSpellCheckServiceItem(bool is_checked) override;
  void AddAccessibilityLabelsServiceItem(bool is_checked) override;

  // Registers a one-time callback that will be called the next time a context
  // menu is shown.
  static void RegisterMenuShownCallbackForTesting(
      base::OnceCallback<void(RenderViewContextMenu*)> cb);

  // Register a one-time callback that will be called the next time a plugin
  // action is executed from a given render frame.
  void RegisterExecutePluginActionCallbackForTesting(
      base::OnceCallback<void(content::RenderFrameHost*,
                              blink::mojom::PluginActionType)> cb);

 protected:
  Profile* GetProfile() const;

  // This may return nullptr (e.g. for WebUI dialogs).
  Browser* GetBrowser() const;

  // Returns a (possibly truncated) version of the current selection text
  // suitable for putting in the title of a menu item.
  std::u16string PrintableSelectionText();

  // Helper function to escape "&" as "&&".
  void EscapeAmpersands(std::u16string* text);

#if BUILDFLAG(ENABLE_EXTENSIONS)
  extensions::ContextMenuMatcher extension_items_;
#endif
  void RecordUsedItem(int id) override;

  // Returns true if the browser is in HTML fullscreen mode, initiated by the
  // page (as opposed to the user). Used to determine which shortcut to display.
  bool IsHTML5Fullscreen() const;

  // Returns true if keyboard lock is active and requires the user to press and
  // hold escape to exit exclusive access mode.
  bool IsPressAndHoldEscRequiredToExitFullscreen() const;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  virtual const policy::DlpRulesManager* GetDlpRulesManager() const;
#endif

 private:
  friend class RenderViewContextMenuTest;
  friend class TestRenderViewContextMenu;
  friend class FormatUrlForClipboardTest;

  static bool IsDevToolsURL(const GURL& url);
#if BUILDFLAG(ENABLE_EXTENSIONS)
  static bool ExtensionContextAndPatternMatch(
      const content::ContextMenuParams& params,
      const extensions::MenuItem::ContextList& contexts,
      const extensions::URLPatternSet& target_url_patterns);
  static bool MenuItemMatchesParams(const content::ContextMenuParams& params,
                                    const extensions::MenuItem* item);
#endif

  // Formats a URL to be written to the clipboard and returns the formatted
  // string. Used by WriteURLToClipboard(), but kept in a separate function so
  // the formatting behavior can be tested without having to initialize the
  // clipboard. |url| must be valid and non-empty.
  static std::u16string FormatURLForClipboard(const GURL& url);

  // Writes the specified text/url to the system clipboard.
  void WriteURLToClipboard(const GURL& url);

  // RenderViewContextMenuBase:
  void InitMenu() override;
  void RecordShownItem(int id) override;
#if BUILDFLAG(ENABLE_PLUGINS)
  void HandleAuthorizeAllPlugins() override;
#endif
  void NotifyMenuShown() override;

  // Gets the extension (if any) associated with the WebContents that we're in.
  const extensions::Extension* GetExtension() const;

  // Queries the translate service to obtain the user's transate target
  // language.
  std::string GetTargetLanguage() const;

  void AppendDeveloperItems();
  void AppendDevtoolsForUnpackedExtensions();
  void AppendLinkItems();
  void AppendOpenWithLinkItems();
  void AppendSmartSelectionActionItems();
  void AppendOpenInWebAppLinkItems();
  void AppendQuickAnswersItems();
  void AppendImageItems();
  void AppendAudioItems();
  void AppendCanvasItems();
  void AppendVideoItems();
  void AppendMediaItems();
  void AppendPluginItems();
  void AppendPageItems();
  void AppendExitFullscreenItem();
  void AppendCopyItem();
  void AppendLinkToTextItems();
  void AppendPrintItem();
  void AppendMediaRouterItem();
  void AppendRotationItems();
  void AppendEditableItems();
  void AppendLanguageSettings();
  void AppendSpellingSuggestionItems();
  // Returns true if the items were appended. This might not happen in all
  // cases, e.g. these are only appended if a screen reader is enabled.
  bool AppendAccessibilityLabelsItems();
  void AppendSearchProvider();
#if BUILDFLAG(ENABLE_EXTENSIONS)
  void AppendAllExtensionItems();
  void AppendCurrentExtensionItems();
#endif
  void AppendPrintPreviewItems();
  void AppendSearchLensForImageItems();
  void AppendSearchWebForImageItems();
  void AppendProtocolHandlerSubMenu();
  void AppendPasswordItems();
  void AppendPictureInPictureItem();
  void AppendSharingItems();
#if !defined(OS_FUCHSIA)
  void AppendClickToCallItem();
#endif
  void AppendSharedClipboardItem();
  void AppendRegionSearchItem();
  void AppendQRCodeGeneratorItem(bool for_image, bool draw_icon);

  std::unique_ptr<ui::DataTransferEndpoint> CreateDataEndpoint(
      bool notify_if_restricted) const;

  // Helper function for checking policies.
  bool IsSaveAsItemAllowedByPolicy() const;

  // Command enabled query functions.
  bool IsReloadEnabled() const;
  bool IsViewSourceEnabled() const;
  bool IsDevCommandEnabled(int id) const;
  bool IsTranslateEnabled() const;
  bool IsSaveLinkAsEnabled() const;
  bool IsSaveImageAsEnabled() const;
  bool IsSaveAsEnabled() const;
  bool IsSavePageEnabled() const;
  bool IsPasteEnabled() const;
  bool IsPasteAndMatchStyleEnabled() const;
  bool IsPrintPreviewEnabled() const;
  bool IsQRCodeGeneratorEnabled() const;
  bool IsRouteMediaEnabled() const;
  bool IsOpenLinkOTREnabled() const;
  bool IsSearchWebForEnabled() const;
  bool IsRegionSearchEnabled() const;

  // Command execution functions.
  void ExecOpenWebApp();
  void ExecProtocolHandler(int event_flags, int handler_index);
  void ExecOpenLinkInProfile(int profile_index);
  void ExecInspectElement();
  void ExecInspectBackgroundPage();
  void ExecSaveLinkAs();
  void ExecSaveAs();
  void ExecExitFullscreen();
  void ExecCopyLinkText();
  void ExecCopyImageAt();
  void ExecSearchLensForImage();
  void ExecRegionSearch(int event_flags,
                        bool is_google_default_search_provider);
  void ExecSearchWebForImage();
  void ExecLoadImage();
  void ExecPlayPause();
  void ExecMute();
  void ExecLoop();
  void ExecControls();
  void ExecRotateCW();
  void ExecRotateCCW();
  void ExecReloadPackagedApp();
  void ExecRestartPackagedApp();
  void ExecPrint();
  void ExecRouteMedia();
  void ExecTranslate();
  void ExecLanguageSettings(int event_flags);
  void ExecProtocolHandlerSettings(int event_flags);
  void ExecPictureInPicture();

  void MediaPlayerActionAt(const gfx::Point& location,
                           const blink::mojom::MediaPlayerAction& action);
  void PluginActionAt(const gfx::Point& location,
                      blink::mojom::PluginActionType plugin_action);

  // Returns a list of registered ProtocolHandlers that can handle the clicked
  // on URL.
  custom_handlers::ProtocolHandlerRegistry::ProtocolHandlerList
  GetHandlersForLinkUrl();

  // ProtocolHandlerRegistry::Observer:
  void OnProtocolHandlerRegistryChanged() override;

  // The destination URL to use if the user tries to search for or navigate to
  // a text selection.
  GURL selection_navigation_url_;

  ui::SimpleMenuModel profile_link_submenu_model_;
  std::vector<base::FilePath> profile_link_paths_;
  bool multiple_profiles_open_;

  // Protocol handling:
  // - The submenu containing the installed protocol handlers.
  ui::SimpleMenuModel protocol_handler_submenu_model_;
  // - The registry with the protocols.
  raw_ptr<custom_handlers::ProtocolHandlerRegistry> protocol_handler_registry_;
  // - The observation of the registry.
  base::ScopedObservation<custom_handlers::ProtocolHandlerRegistry,
                          custom_handlers::ProtocolHandlerRegistry::Observer>
      protocol_handler_registry_observation_{this};
  // - Whether or not the registered protocols have changed since the menu was
  //   built.
  bool is_protocol_submenu_valid_ = false;

  // An observer that handles spelling suggestions, "Add to dictionary", and
  // "Use enhanced spell check" items.
  std::unique_ptr<SpellingMenuObserver> spelling_suggestions_menu_observer_;

  // An observer that handles accessibility labels items.
  std::unique_ptr<AccessibilityLabelsMenuObserver>
      accessibility_labels_menu_observer_;
  ui::SimpleMenuModel accessibility_labels_submenu_model_;

#if !defined(OS_MAC)
  // An observer that handles the submenu for showing spelling options. This
  // submenu lets users select the spelling language, for example.
  std::unique_ptr<SpellingOptionsSubMenuObserver>
      spelling_options_submenu_observer_;
#endif

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // An observer that handles "Open with <app>" items.
  std::unique_ptr<RenderViewContextMenuObserver> open_with_menu_observer_;
  // An observer that handles smart text selection action items.
  std::unique_ptr<RenderViewContextMenuObserver>
      start_smart_selection_action_menu_observer_;
  std::unique_ptr<QuickAnswersMenuObserver> quick_answers_menu_observer_;
#endif

#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
  // An observer that disables menu items when print preview is active.
  std::unique_ptr<PrintPreviewContextMenuObserver> print_preview_menu_observer_;
#endif

  std::unique_ptr<LinkToTextMenuObserver> link_to_text_menu_observer_;

  // In the case of a MimeHandlerView this will point to the WebContents that
  // embeds the MimeHandlerViewGuest. Otherwise this will be the same as
  // |source_web_contents_|.
  const raw_ptr<content::WebContents> embedder_web_contents_;

  // Send tab to self submenu.
  std::unique_ptr<send_tab_to_self::SendTabToSelfSubMenuModel>
      send_tab_to_self_sub_menu_model_;

  // Sharing submenu, if present.
  std::unique_ptr<share::ShareSubmenuModel> share_submenu_model_;

  // Click to call menu observer.
  std::unique_ptr<ClickToCallContextMenuObserver>
      click_to_call_context_menu_observer_;

  // Shared clipboard menu observer.
  std::unique_ptr<SharedClipboardContextMenuObserver>
      shared_clipboard_context_menu_observer_;

  // The system app (if any) associated with the WebContents we're in.
  raw_ptr<const web_app::SystemWebAppDelegate> system_app_ = nullptr;

  // A one-time callback that will be called the next time a plugin action is
  // executed from a given render frame.
  ExecutePluginActionCallback execute_plugin_action_callback_;

#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  // Controller for Lens Region Search feature. This controller will be
  // destroyed as soon as the RenderViewContextMenu object is destroyed. The
  // RenderViewContextMenu is reset every time it is shown, but persists between
  // uses so that it doesn't go out of scope before finishing work. This means
  // that when another context menu opens, the Lens Region Search feature will
  // close if active.
  std::unique_ptr<lens::LensRegionSearchController>
      lens_region_search_controller_;
#endif

  // Vivaldi
  std::unique_ptr<NotesSubMenuObserver> insert_note_submenu_observer_;

#ifdef VIVALDI_BUILD
#include "browser/menus/vivaldi_render_view_context_menu.inc"
#endif // VIVALDI_BUILD
};

#endif  // CHROME_BROWSER_RENDERER_CONTEXT_MENU_RENDER_VIEW_CONTEXT_MENU_H_


text:
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, TextAreaField, SubmitField, SelectField, BooleanField, Label
from wtforms.validators import DataRequired, EqualTo, Email
from views.constants import *

class LoginForm(Form):
    email = StringField('email', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])

class PasswordChangeform(Form):
    old_password = PasswordField('old_password', validators=[DataRequired()])
    new_password = PasswordField('new_password', validators=[DataRequired()])
    confirm = PasswordField('confirm', validators=[DataRequired(), EqualTo('new_password', message='Passwords must match')])

class SignUpForm(Form):
    email = StringField('email', validators=[DataRequired(), Email()])
    password = PasswordField('password', validators=[DataRequired()])
    confirm = PasswordField('confirm', validators=[DataRequired(), EqualTo('password', message='Passwords must match')])
    name = StringField('name')
    company = StringField('name')

class SearchForm(Form):
    name = StringField('name')
    submit = SubmitField('Search')

class CreateGroupForm(Form):
    name = StringField('name')
    description = TextAreaField('desc')
    submit = SubmitField('Create')

class PlotCreationForm(Form):
    name = StringField('name')
    fields = StringField('fields')
    submit = SubmitField('Create')

class AddReleaseForm(Form):
    name = StringField('name')
    version = StringField('fields')
    submit = SubmitField('Add')

class SearchReportsForm(Form):
    choices = [('user_identifier', 'User'), ('application_name', 'Application Name'),
               ('application_version', 'Application Version'), ('after_version', 'After Version'),
               ('before_version', 'Before Version'), ('id', 'Report Number'),
               ('error_message', 'Error Message'), ('error_type', 'Error Type'),
               ('date', 'Date'), ('before_date', 'Before Date'), ('after_date', 'After Date')]
    field1 = SelectField(choices=choices, default='user')
    value1 = StringField('Value')

    field2 = SelectField(choices=choices, default='application_name')
    value2 = StringField('Value')

    field3 = SelectField(choices=choices, default='application_version')
    value3 = StringField('Value')

    fields = field1, field2, field3
    values = value1, value2, value3

    hide_aliased_label = Label('hide_aliased_label', 'Aliases:')
    hide_aliased = SelectField(choices=[(str(ANY), '----'),
                                        (str(NONE), 'No Aliases'),
                                        (str(ONLY), 'Only Aliases')])

    releases_only_label = Label('releases_only_label', 'Versions:')
    releases_only = SelectField(choices=[(str(ANY), '----'),
                                         (str(NONE), 'Non-Released Versions'),
                                         (str(ONLY), 'Released Versions')])

class CreateAliasForm(Form):
    alias = StringField('alias', validators=[DataRequired()])
    uuid = StringField('uuid', validators=[DataRequired()])
    submit = SubmitField('Create')

class YoutrackSubmitForm(Form):
    server = StringField('YouTrack Server', validators=[DataRequired()])
    project = StringField('Project', validators=[DataRequired()])
    assignee = StringField('Assignee', validators=[DataRequired()])
    summary = StringField('Summary', validators=[DataRequired()])
    description = TextAreaField('Description', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    priority = StringField('Priority')
    type = StringField('Type')
    subsystem = StringField('Subsystem')
    state = StringField('State')
    affects_versions = StringField('Affects_versions')
    permitted_group = StringField('Permitted Group')
    submit = SubmitField("Submit")


text:
<bill session="110" type="h" number="3694" updated="2009-01-09T00:36:47-05:00">
	<status><introduced date="1190865600" datetime="2007-09-27"/></status>

	<introduced date="1190865600" datetime="2007-09-27"/>
	<titles>
		<title type="short" as="introduced">Alternative Minimum Tax Reform Act of 2007</title>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to provide corporate alternative minimum tax reform.</title>
	</titles>
	<sponsor id="400123"/>
	<cosponsors>
		<cosponsor id="400647" joined="2007-11-08"/>
		<cosponsor id="400206" joined="2008-01-28"/>
	</cosponsors>
	<actions>
		<action date="1190865600" datetime="2007-09-27"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/27/2007--Introduced.
Alternative Minimum Tax Reform Act of 2007 - Amends the Internal Revenue Code to allow corporate taxpayers to offset alternative minimum tax liabilities with long-term unused minimum tax credits and increased net operating loss allowances.

</bill>


text:
package org.apache.flink.state.api;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.state.api.runtime.metadata.SavepointMetadata;

/**
 * A new savepoint. Operator states can be removed from and added to the savepoint, and eventually, written to
 * distributed storage as a new savepoint.
 *
 * @see WritableSavepoint
 */
@PublicEvolving
public class NewSavepoint extends WritableSavepoint<NewSavepoint> {
	NewSavepoint(SavepointMetadata metadata, StateBackend stateBackend) {
		super(metadata, stateBackend);
	}
}


text:
/* UBUNTU FONTS */
@import url(http://fonts.googleapis.com/css?family=Ubuntu|Ubuntu+Mono);

/* UBUNTU CURSORS */
* {
	cursor: url("usr/share/images/themes/adwaita/cursors/default.png"), default;
}
p, textarea, input[type="text"], input[type="password"],
*::selection, *::-moz-selection, *::-webkit-selection, *::-o-selection {
	cursor: url("usr/share/images/themes/adwaita/cursors/text.png"), text;
}
a, a * {
	cursor: url("usr/share/images/themes/adwaita/cursors/pointer.png"), pointer, hand;
}

.cursor-default,.cursor-default * {
	cursor: url("usr/share/images/themes/adwaita/cursors/default.png"), default;
}

.cursor-text, .cursor-text * {
	cursor: url("usr/share/images/themes/adwaita/cursors/text.png"), text;
}

.cursor-pointer, .cursor-pointer * {
	cursor: url("usr/share/images/themes/adwaita/cursors/pointer.png"), pointer, hand;
}

.cursor-wait, .cursor-wait * {
	cursor: url("usr/share/images/themes/adwaita/cursors/wait.ani"), wait;
}

.cursor-move, .cursor-move * {
	cursor: url("usr/share/images/themes/adwaita/cursors/move.png"), move;
}

.cursor-none, .cursor-none * {
	cursor: none;
}

img {
	border-width: 0px;
}

table {
	border-collapse: collapse;
}

a, a:hover, a:active {
	color: #dd4814;
}

*::selection, *::-moz-selection, *::-webkit-selection, *::-o-selection {
	background:#f07746;
	color:#fff;
}

body {
	overflow: hidden;
}

/* Ensemble de l'interface */
.gnome-panel {
	width: 100%;
	height: 100%;
	padding: 0px;
	margin: 0px;
	font-size: 14px;
	font-family: Ubuntu, Verdana, serif;
	overflow: hidden;
	position: absolute;
}

#header {
	background: url('usr/share/images/themes/ambiance/menu/background.png') repeat-x;
	width: 100%;
	height: 25px;
	color: white;
	padding: 0px;
	position:absolute;
	top: 0px;
	-moz-box-shadow: 5px 4px 12px black;
	-webkit-box-shadow: 5px 4px 12px black;
	box-shadow: 5px 4px 12px black;
}

#desktop {
	position: absolute;
	width:100%;
	height:100%;
	color: white;
	overflow:hidden;
	top: 27px;
	bottom: 25px;
}

#desktop-files, #desktop .fileiconzone {
	width: 100%;
	height: 100%;
}

#desktop-files {
	top: 0px;
	bottom: 0px;
}

#footer {
	background: url('usr/share/images/themes/ambiance/menu/background.png') repeat-x;
	height: 24px;
	width:100%;
	color: white;
	position:absolute;
	bottom:0px;
	left:0px;
	z-index: 2000;
}

/* BOUTONS DES FENETRES */
.windows-buttons {
	overflow: hidden;
	height: 24px;
	display: inline-block;
	margin: 0;
	padding: 0;
}
.windows-buttons .window-button {
	padding: 2px;
	float: left;
	list-style-type: none;
	width: 176px;
	height: 19px;
	border-left: 1px solid #383733;
	overflow: hidden;
	padding-right: 0px;
	white-space: nowrap;
}
.windows-buttons .window-button img {
	max-height:17px;
	max-width:17px;
	margin-right:3px;

	margin-left: 3px;

	float: left;
}
.windows-buttons .window-button:hover {
	background: url('usr/share/images/themes/ambiance/bg-window-button.png');
	background-position: 0% 48px;
}
.windows-buttons .active, #windows-buttons .window-button:active {
	background: url('usr/share/images/themes/ambiance/bg-window-button.png');
	background-position: 0% 24px;
}
.windows-buttons:last-child {
	border-right:1px solid #383733;
}

.desktop-button { background: url('usr/share/images/themes/ambiance/desktop-button.png'); height: 24px; width: 30px; float:left; }
.desktop-button:hover { background-position: 0% 24px; }

.ui-resizable-handle .ui-resizable-e {
	height:2px;
	position:relative;
	bottom:2px;
}
.ui-selectable-helper {
	border: 1px solid #f07746;
	background: rgba(240, 119, 70, 0.3);
}

#desktop-welcome { display:none; }

.workspace-button {
	background-color:#333331;
	margin-right:1px;
	padding-left:23px;
	display:inline;
}
.workspace-button.selected {
	background-color:#ad502b;
}

.webos-nautilus ul.icons li.active span.filename {
	background-color: #d76741;
	color: white;
	-moz-border-radius: 2px;
	-webkit-border-radius: 2px;
	border-radius: 2px;
}


text:
namespace nacl_io {

class TtyNode : public CharNode {
 public:
  explicit TtyNode(Filesystem* filesystem);

  virtual EventEmitter* GetEventEmitter();

  virtual Error VIoctl(int request, va_list args);

  virtual Error Read(const HandleAttr& attr,
                     void* buf,
                     size_t count,
                     int* out_bytes);

  virtual Error Write(const HandleAttr& attr,
                      const void* buf,
                      size_t count,
                      int* out_bytes);

  virtual Error Tcgetattr(struct termios* termios_p);
  virtual Error Tcsetattr(int optional_actions,
                          const struct termios* termios_p);

  virtual Error Isatty() { return 0; }

 private:
  ScopedEventEmitter emitter_;

  Error ProcessInput(PP_Var var);
  Error ProcessInput(const char* buffer, size_t num_bytes);
  Error Echo(const char* string, int count);
  void InitTermios();

  std::deque<char> input_buffer_;
  struct termios termios_;

  /// Current height of terminal in rows.  Set via ioctl(2).
  int rows_;
  /// Current width of terminal in columns.  Set via ioctl(2).
  int cols_;

  // Output handler for TTY.  This is set via ioctl(2).
  struct tioc_nacl_output output_handler_;
  // Lock to protect output_handler_.  This lock gets acquired whenever
  // output_handler_ is used or set.
  sdk_util::SimpleLock output_lock_;
};

}  // namespace nacl_io

#endif  // LIBRARIES_NACL_IO_DEVFS_TTY_NODE_H_


text:
package com.intellij.grazie.text;

import org.jetbrains.annotations.NotNull;

/**
 * An extension allowing to prevent some text problems from being reported,
 * registered in {@code plugin.xml} under {@code "com.intellij.grazie.problemFilter"} qualified name.
 */
public abstract class ProblemFilter {
  /** @return whether the given problem should not be reported by grammar checking highlighting */
  public abstract boolean shouldIgnore(@NotNull TextProblem problem);
}


text:
import {Component, OnInit} from '@angular/core';
import {PlaceCrudService} from './place-crud.service';
import {ToastComponent} from '../shared/toast/toast.component';

@Component({
  selector: 'app-place',
  templateUrl: './place.component.html'
})
export class PlaceComponent implements OnInit {
  formTitle: string;
  places: any[];
  isLoading: boolean;
  showEditor = false;
  selectedModel: any;

  constructor(private placeCrudSvc: PlaceCrudService,
              public toast: ToastComponent) {
  }

  ngOnInit() {
    this.getPlaces();
  }

  private getPlaces() {
    this.isLoading = true;
    this.placeCrudSvc.getPlaces()
      .subscribe(data =>
          this.places = data,
        error => console.log(error),
        () => this.isLoading = false);
  }

  save(place: any) {
    this.isLoading = true;
    const observable = place._id ? this.placeCrudSvc.edit(place) : this.placeCrudSvc.add(place);
    observable.subscribe(() => {
        this.getPlaces();
        this.toast.setMessage('Place saved successfully', 'success');
      }, error => console.log(error),
      () => {
        this.showEditor = false;
        this.isLoading = false;
      });
  }

  startEdit(place: any) {
    this.selectedModel = place;
    this.formTitle = 'Edit Place';
    this.showForm();
  }

  deletePlace(id: any) {
    this.isLoading = true;
    this.placeCrudSvc
      .deletePlace(id)
      .subscribe(res => {
        if (res.status === 200) {
          this.toast.setMessage('Place removed successfully', 'success');
          this.getPlaces();
        }
      }, err => {
        if (err.status === 409) {
          this.toast.setMessage(JSON.parse(err._body).msg, 'danger');
          this.isLoading = false;
        }
        console.log(err);
      });
  }

  showForm() {
    this.showEditor = true;
  }

  startAdd() {
    this.selectedModel = null;
    this.formTitle = 'Add Place';
    this.showForm();
  }

  hideAndResetForm() {
    this.showEditor = false;
  }
}


text:
import pytest

@pytest.mark.parametrize('qc_type, old_version, new_version', [
    ('bismark_quality_metric', '8', '9'),
    ('chipseq_filter_quality_metric', '7', '8'),
    ('complexity_xcorr_quality_metric', '7', '8'),
    ('correlation_quality_metric', '7', '8'),
    ('cpg_correlation_quality_metric', '7', '8'),
    ('duplicates_quality_metric', '6', '7'),
    ('edwbamstats_quality_metric', '7', '8'),
    ('filtering_quality_metric', '7', '8'),
    ('gencode_category_quality_metric', '1', '2'),
    ('generic_quality_metric', '7', '8'),
    ('histone_chipseq_quality_metric', '1', '2'),
    ('hotspot_quality_metric', '7', '8'),
    ('idr_quality_metric', '6', '7'),
    ('idr_summary_quality_metric', '7', '8'),
    ('long_read_rna_mapping_quality_metric', '1', '2'),
    ('long_read_rna_quantification_quality_metric', '1', '2'),
    ('mad_quality_metric', '6', '7'),
    ('micro_rna_mapping_quality_metric', '1', '2'),
    ('micro_rna_quantification_quality_metric', '1', '2'),
    ('samtools_flagstats_quality_metric', '7', '8'),
    ('samtools_stats_quality_metric', '7', '8'),
    ('star_quality_metric', '7', '8'),
    ('trimming_quality_metric', '7', '8')
])
def test_upgrade_snATAC_name(upgrader, quality_metric_1, qc_type, old_version, new_version):
    quality_metric_1['schema_version'] = old_version
    quality_metric_1['assay_term_name'] = 'single-nuclei ATAC-seq'
    value = upgrader.upgrade(qc_type, quality_metric_1, current_version=old_version, target_version=new_version)
    assert value['assay_term_name'] == 'single-nucleus ATAC-seq'
    assert value['schema_version'] == new_version
    value['assay_term_name'] = 'HiC'
    value = upgrader.upgrade(qc_type, quality_metric_1, current_version=old_version, target_version=new_version)
    assert value['assay_term_name'] != 'single-nucleus ATAC-seq'


text:
<!DOCTYPE html>

  	<meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>牧羊人</title>

    <link rel="stylesheet" href="bootstrap.min.css">
    <link rel="stylesheet" href="bootstrap-theme.min.css">

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      Toggle navigation

    </button>
    Home

        node.js

html

css

javascript

bootstrap

ejs

express

node.js

mongodb

mongoose

        android

UI

layout

thread

net

        ios

UI

layout

thread

net

        game

        smartphone

android-mtk

feature-mtk

    <form class="navbar-form navbar-right" role="search">

        <input type="text" class="form-control" placeholder="Search">

      <button type="submit" class="btn btn-default">Submit</button>
    </form>


text:
RSpec.describe CertificationValidator, type: :validator do
  subject(:certification) { build(:certification, certification_type: certification_type, claim: claim) }

  let(:certification_type) { create(:certification_type) }
  let(:claim) { build(:claim) }

  describe '#validate_certification_type_id' do
    context 'when agfs final claim' do
      let(:claim) { build(:advocate_final_claim) }

      context 'with certification type' do
        before { certification.certification_type_id = certification_type.id }

        it { expect(certification).to be_valid }
      end

      context 'with no certification type' do
        before { certification.certification_type_id = nil }

        it { expect(certification).to be_invalid }

        it {
          certification.valid?
          expect(certification.errors.messages[:certification_type_id]).to include('Choose a certification type')
        }
      end
    end

    context 'with advocate interim claim' do
      let(:claim) { build(:advocate_interim_claim) }

      context 'with no certification type' do
        before { certification.certification_type_id = nil }

        it { expect(certification).to be_valid }
      end
    end

    context 'with litigator claim' do
      let(:claim) { build(:litigator_final_claim) }

      context 'with no certification type' do
        before { certification.certification_type_id = nil }

        it { expect(certification).to be_valid }
      end
    end
  end

  describe '#validate_certified_by' do
    before { certification.certified_by = nil }

    it { expect(certification).to be_invalid }

    it {
      certification.valid?
      expect(certification.errors.messages[:certified_by])
        .to include('Enter the name of person certifying')
    }
  end

  describe '#validate_certification_date' do
    context 'when before the claim creation date' do
      let(:claim) { build(:claim, created_at: 2.days.ago) }

      before do
        certification.certification_date = 3.days.ago
      end

      it { expect(certification).to be_invalid }

      it {
        certification.valid?
        expect(certification.errors.messages[:certification_date])
          .to include('Certification date must be same day or after claim submission day')
      }
    end

    context 'when in the future' do
      before do
        certification.certification_date = 10.days.from_now
      end

      it { expect(certification).to be_invalid }

      it {
        certification.valid?
        expect(certification.errors.messages[:certification_date])
          .to include('Certification date cannot be in the future')
      }
    end
  end
end