text:
package org.apache.maven.repository.metadata;

import java.util.Collection;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactScopeEnum;

/**
 * Artifact Metadata that is resolved independent of Artifact itself.
 *
 * @author Oleg Gusakov
 */
public class ArtifactMetadata
{
    /**
     * standard glorified artifact coordinates
     */
    protected String groupId;
    protected String artifactId;
    protected String version;
    protected String type;
    protected ArtifactScopeEnum artifactScope;
    protected String classifier;

    /**
     * explanation: why this MD was chosen over it's siblings
     * in the resulting structure (classpath for now)
     */
    protected String why;

    /** dependencies of the artifact behind this metadata */
    protected Collection<ArtifactMetadata> dependencies;

    /** metadata URI */
    protected String uri;

    /** is metadata found anywhere */
    protected boolean resolved = false;

    /** does the actual artifact for this metadata exists */
    protected boolean artifactExists = false;
    /** artifact URI */
    protected String artifactUri;

    /** error message  */
    private String error;

    //------------------------------------------------------------------
    /**
     *
     */
    public ArtifactMetadata( String name )
    {
        if ( name == null )
        {
            return;
        }
        int ind1 = name.indexOf( ':' );
        int ind2 = name.lastIndexOf( ':' );

        if ( ind1 == -1 || ind2 == -1 )
        {
            return;
        }

        this.groupId = name.substring( 0, ind1 );
        if ( ind1 == ind2 )
        {
            this.artifactId = name.substring( ind1 + 1 );
        }
        else
        {
            this.artifactId = name.substring( ind1 + 1, ind2 );
            this.version = name.substring( ind2 + 1 );
        }
    }

    // ------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version )
    {
        this( groupId, name, version, null );
    }
    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type )
    {
        this( groupId, name, version, type, null );
    }

    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope )
    {
        this( groupId, name, version, type, artifactScope, null );
    }

    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope,
                             String classifier )
    {
        this( groupId, name, version, type, artifactScope, classifier, null );
    }
    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope,
                             String classifier, String artifactUri )
    {
        this( groupId, name, version, type, artifactScope, classifier, artifactUri, null, true, null );
    }
    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope,
                             String classifier, String artifactUri, String why, boolean resolved, String error )
    {
        this.groupId = groupId;
        this.artifactId = name;
        this.version = version;
        this.type = type;
        this.artifactScope = artifactScope;
        this.classifier = classifier;
        this.artifactUri = artifactUri;
        this.why = why;
        this.resolved = resolved;
        this.error = error;
    }
    //------------------------------------------------------------------
    public ArtifactMetadata( String groupId, String name, String version, String type, String scopeString,
                             String classifier, String artifactUri, String why, boolean resolved, String error )
    {
        this( groupId, name, version, type,
              scopeString == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf( scopeString ),
              classifier, artifactUri, why, resolved, error );
    }

    //------------------------------------------------------------------
    public ArtifactMetadata( Artifact af )
    {
        /*
        if ( af != null )
        {
            init( af );
        }
        */
    }
    //------------------------------------------------------------------
//    public void init( ArtifactMetadata af )
//    {
//        setGroupId( af.getGroupId() );
//        setArtifactId( af.getArtifactId() );
//        setVersion( af.getVersion() );
//        setType( af.getType() );
//        setScope( af.getScope() );
//        setClassifier( af.getClassifier() );
//        //setUri( af.getDownloadUrl() );
//
//        this.resolved = af.isResolved();
//    }

    //------------------------------------------------------------------
    @Override
    public String toString()
    {
        return groupId + ":" + artifactId + ":" + version;
    }

    //------------------------------------------------------------------
    public String toDomainString()
    {
        return groupId + ":" + artifactId;
    }

    //------------------------------------------------------------------
    public String getGroupId()
    {
        return groupId;
    }

    public void setGroupId( String groupId )
    {
        this.groupId = groupId;
    }

    public String getArtifactId()
    {
        return artifactId;
    }

    public void setArtifactId( String name )
    {
        this.artifactId = name;
    }

    public String getVersion()
    {
        return version;
    }

    public void setVersion( String version )
    {
        this.version = version;
    }

    public String getType()
    {
        return type;
    }

    public String getCheckedType()
    {
        return type == null ? "jar" : type;
    }

    public void setType( String type )
    {
        this.type = type;
    }

    public ArtifactScopeEnum getArtifactScope()
    {
        return artifactScope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : artifactScope;
    }

    public void setArtifactScope( ArtifactScopeEnum artifactScope )
    {
        this.artifactScope = artifactScope;
    }

    public void setScope( String scope )
    {
        this.artifactScope = scope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf( scope );
    }

    public String getClassifier()
    {
        return classifier;
    }

    public void setClassifier( String classifier )
    {
        this.classifier = classifier;
    }

    public boolean isResolved()
    {
        return resolved;
    }

    public void setResolved( boolean resolved )
    {
        this.resolved = resolved;
    }

    public String getUri()
    {
        return uri;
    }

    public void setUri( String uri )
    {
        this.uri = uri;
    }

    public String getScope()
    {
        return getArtifactScope().getScope();
    }

    public ArtifactScopeEnum getScopeAsEnum()
    {
        return artifactScope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : artifactScope;
    }

    public boolean isArtifactExists()
    {
        return artifactExists;
    }

    public void setArtifactExists( boolean artifactExists )
    {
        this.artifactExists = artifactExists;
    }

    public Collection<ArtifactMetadata> getDependencies()
    {
        return dependencies;
    }

    public void setDependencies( Collection<ArtifactMetadata> dependencies )
    {
        this.dependencies = dependencies;
    }

    public String getArtifactUri()
    {
        return artifactUri;
    }

    public void setArtifactUri( String artifactUri )
    {
        this.artifactUri = artifactUri;
    }

    public String getWhy()
    {
        return why;
    }

    public void setWhy( String why )
    {
        this.why = why;
    }

    //-------------------------------------------------------------------
    public String getError()
    {
        return error;
    }

    public void setError( String error )
    {
        this.error = error;
    }

    public boolean isError()
    {
        return error == null;
    }

    //------------------------------------------------------------------
    public String getDependencyConflictId()
    {
        return groupId + ":" + artifactId;
    }
    //------------------------------------------------------------------
    //------------------------------------------------------------------
}


text:
package org.apache.olingo.client.core.edm.xml;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;

import org.apache.olingo.commons.api.edm.provider.CsdlAnnotations;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.IOException;
import java.io.Serializable;

@JsonDeserialize(using = ClientCsdlAnnotations.AnnotationsDeserializer.class)
class ClientCsdlAnnotations extends CsdlAnnotations implements Serializable {

  private static final long serialVersionUID = -5961207981571644200L;

  static class AnnotationsDeserializer extends AbstractClientCsdlEdmDeserializer<ClientCsdlAnnotations> {

    @Override
    protected ClientCsdlAnnotations doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
            throws IOException {

      final ClientCsdlAnnotations annotations = new ClientCsdlAnnotations();

      for (; jp.getCurrentToken() != null && jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
          if ("Target".equals(jp.getCurrentName())) {
            annotations.setTarget(jp.nextTextValue());
          } else if ("Qualifier".equals(jp.getCurrentName())) {
            annotations.setQualifier(jp.nextTextValue());
          } else if ("Annotation".equals(jp.getCurrentName())) {
            jp.nextToken();
            annotations.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
          }
        }
      }

      return annotations;
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
title: Printing the contents of a RadWindow
description: Printing the contents of a RadWindow. Check it now!
type: how-to
page_title: Printing the contents of a RadWindow
slug: window-printing-content
res_type: kb
---

## DESCRIPTION
RadWindow does not offer built-in printing functionality as regular browser popups do. There is also a difference whether an external page is loaded via the `NavigateUrl` or the `ContentTemplate` is used, as browser popups only load entire pages.

## SOLUTION
You ultimately need to rely on the `print()` command that the document and window objects provide.

>note We cannot control the way this works, after `print()` is called the behavior is entirely controlled by the browser and the user machine's settings.
>

There is also a difference how an external page and the `ContentTemplate` are handled.

The external page creates an iframe, which also has its own document and window objects and you can use them directly to print the entire page from within this page by using the following JavaScript function:

````JavaScript
if (document.all)
{
    document.execCommand("Print");
}
else
{
    window.print();
}
````

When the `ContentTemplate` is used the RadWindow's contents are part of the main page and we should not use its `print()` method directly, as this would print the entire page. We first need to take the contents of the RadWindow and then we can place them in a new browser popup, or a hidden iframe which provide the needed document and window objects:

````ASP.NET
<telerik:RadWindow runat="server" ID="RadWindow1">
    <ContentTemplate>
        <div id="contentHolder">
             . . . . . .
        </div>
        <asp:Button ID="btn" runat="server" OnClientClick="PrintContent();return false;"
            Text="Print" />
    </ContentTemplate>
</telerik:RadWindow>
````

This is easiest done by wrapping the contents in a simple div so you can obtain its `innerHTML` and place it in a popup:

````JavaScript
var content = $get("contentHolder").innerHTML;
var pwin = window.open('', 'print_content', 'width=300,height=300');
pwin.document.open();
pwin.document.write('<html><body onload="window.print()">' + content + '</body></html>');
pwin.document.close();
setTimeout(function () { pwin.close(); }, 1000);
````

or use a predefined, hidden iframe on the page to avoid the popup:

````HTML
<iframe id="ifmcontentstoprint" style="position: absolute; top: -1000px; left: -1000px;"></iframe>
````

then you combine both approaches from below to provide the content and call its `print()` method:

````JavaScript
var content = $get("contentHolder").innerHTML;

var printIframe = $get("ifmcontentstoprint");
var printDocument = printIframe.contentWindow.document;
printDocument.designMode = "on";
printDocument.open();
printDocument.write("<html><head></head><body>" + content + "</body></html>");
printDocument.close();
try
{
    if (document.all)
    {
        printDocument.execCommand("Print", null, false);
    }
    else
    {
        printIframe.contentWindow.print();
    }

}
catch (ex)
{
    alert("error printing");
}
````

 You may find useful [this KB article]({%slug window-adding-a-custom-button-to-radwindow-titlebar %}) on adding a custom button to the titlebar where you can attach the printing functionality. When working with external pages you would also need to call a function from the external page if you use a toolbar button, as its event is fired in the parent page. How to do this is explained in [this help article]({%slug window/how-to/calling-functions-in-windows %}).

 There is also a set of simple pages attached that shows this functionality in action:
* [custom-button-radwindow-after-q1-2016](files/custom-button-radwindow-after-q1-2016.zip.zip)

* [custom-button-radwindow-after-q1-2016-xhtml-10-transitional](files/window-custom-button-radwindow-after-q1-2016-xhtml-10-transitional.zip.zip)

* [custom-button-radwindow](files/custom-button-radwindow.zip.zip)


text:
[ng-click],
[data-ng-click],
[x-ng-click] {
    cursor: pointer;
}

body{
overflow-y: scroll;

    font-family: "Helvetica Neue", Roboto, Arial, "Droid Sans", sans-serif;

}
.container{
	width:100%;
}
#row1{
width:20%;
}

#row2{
width:20%;
}
#row3{
width:5%;
}
#row4{
width:5%;
}#row5{
width:5%;
}
#row6{
width:5%;
}
#row7{
width:20%;
}#row8{
width:20%;
}

/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}
.animate-repeat {
  line-height:40px;
  list-style:none;
  box-sizing:border-box;
}

.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
  -webkit-transition:all linear 0.5s;
  transition:all linear 0.5s;
}

.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
  opacity:0;
  max-height:0;
}

.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
  opacity:1;
  max-height:40px;
}

 .glyphicon-spin {
    -webkit-animation: spin 1000ms infinite linear;
    animation: spin 1000ms infinite linear;
}
@-webkit-keyframes spin {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
    }
}
@keyframes spin {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
    }
}


text:
<?php

namespace spec\PSB\Core\Routing;

use PhpSpec\ObjectBehavior;

use PSB\Core\Routing\UnicastRoutingTable;

/**
 * @mixin UnicastRoutingTable
 */
class UnicastRoutingTableSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('PSB\Core\Routing\UnicastRoutingTable');
    }

    function it_registers_routing_rules()
    {
        $this->routeToEndpoint('fqcn1', 'endpoint1');
        $this->routeToEndpoint('fqcn2', 'endpoint2');

        $this->getEndpointNamesFor(['fqcn1', 'fqcn2'])->shouldReturn(['endpoint1', 'endpoint2']);
    }

    function it_registers_multiple_rules_for_the_same_message()
    {
        $this->routeToEndpoint('fqcn1', 'endpoint1');
        $this->routeToEndpoint('fqcn1', 'endpoint2');
        $this->routeToEndpoint('fqcn3', 'endpoint3');

        $this->getEndpointNamesFor(['fqcn1'])->shouldReturn(['endpoint1', 'endpoint2']);
    }

    function it_registers_multiple_rules_for_the_same_endpoint()
    {
        $this->routeToEndpoint('fqcn1', 'endpoint1');
        $this->routeToEndpoint('fqcn2', 'endpoint1');
        $this->routeToEndpoint('fqcn3', 'endpoint3');

        $this->getEndpointNamesFor(['fqcn1'])->shouldReturn(['endpoint1']);
        $this->getEndpointNamesFor(['fqcn2'])->shouldReturn(['endpoint1']);
        $this->getEndpointNamesFor(['fqcn3'])->shouldReturn(['endpoint3']);
    }

    function it_provides_unique_endpoint_names_even_if_registrations_may_lead_to_duplication()
    {
        $this->routeToEndpoint('fqcn1', 'endpoint1');
        $this->routeToEndpoint('fqcn1', 'endpoint1');
        $this->routeToEndpoint('fqcn1', 'endpoint2');
        $this->routeToEndpoint('fqcn2', 'endpoint2');

        $this->getEndpointNamesFor(['fqcn1', 'fqcn2'])->shouldReturn(['endpoint1', 'endpoint2']);
    }
}


text:
namespace std {
template<class _Ep> class initializer_list { };
}

namespace cva {

template <class VT, unsigned int ROWS = 0, unsigned int COLS = 0>
class Matrix {
public:

    typedef VT value_type;
    inline __attribute__((always_inline)) value_type& at();
};

template <class VT, unsigned int SIZE> using Vector = Matrix<VT, SIZE, 1>;

template <class VT>
using RGBValue = Vector<VT, 3>;
using RGBFValue = RGBValue<float>;

template <class VT> class Matrix<VT, 0, 0> { // expected-note {{passing argument to parameter here}}
public:
    typedef VT value_type;
    Matrix(const unsigned int nRows, const unsigned int nColumns, const value_type* data = nullptr);

    Matrix(const std::initializer_list<value_type>& list) = delete; // expected-note {{'Matrix' has been explicitly marked deleted here}}

};

void getLaplacianClosedForm()
{
    Matrix<double> winI(0, 3);
    RGBFValue* inputPreL;
    winI = { inputPreL->at() }; // expected-error {{call to deleted constructor of 'cva::Matrix<double, 0, 0> &&'}}
}

}


text:
package term

import (
	"testing"
	"unicode/utf16"

	"src.elv.sh/pkg/sys/ewindows"
	"src.elv.sh/pkg/tt"
	"src.elv.sh/pkg/ui"
)

func TestConvertEvent(t *testing.T) {
	r1, r2 := utf16.EncodeRune('😀')

	tt.Test(t, tt.Fn("convertEvent", convertEvent), tt.Table{
		// Only convert KeyEvent
		Args(&ewindows.MouseEvent{}).Rets(nil),
		// Only convert KeyDown events
		Args(&ewindows.KeyEvent{BKeyDown: 0}).Rets(nil),

		Args(charKeyEvent('a', 0)).Rets(K('a')),
		Args(charKeyEvent('A', shift)).Rets(K('A')),
		Args(charKeyEvent('µ', leftCtrl|rightAlt)).Rets(K('µ')),
		Args(charKeyEvent('ẞ', leftCtrl|rightAlt|shift)).Rets(K('ẞ')),

		Args(charKeyEvent(uint16(r1), 0)).Rets(surrogateKeyEvent{r1}),
		Args(charKeyEvent(uint16(r2), 0)).Rets(surrogateKeyEvent{r2}),

		Args(funcKeyEvent(0x1b, 0)).Rets(K('[', ui.Ctrl)),

		// Functional key with modifiers
		Args(funcKeyEvent(0x08, 0)).Rets(K(ui.Backspace)),
		Args(funcKeyEvent(0x08, leftCtrl)).Rets(K(ui.Backspace, ui.Ctrl)),
		Args(funcKeyEvent(0x08, leftCtrl|leftAlt|shift)).Rets(K(ui.Backspace, ui.Ctrl, ui.Alt, ui.Shift)),

		// Functional keys with an alphanumeric base
		Args(funcKeyEvent('2', leftCtrl)).Rets(K('2', ui.Ctrl)),
		Args(funcKeyEvent('A', leftCtrl)).Rets(K('A', ui.Ctrl)),
		Args(funcKeyEvent('A', leftAlt)).Rets(K('a', ui.Alt)),

		// Unrecognized functional key
		Args(funcKeyEvent(0, 0)).Rets(nil),
	})
}

func charKeyEvent(r uint16, mod uint32) *ewindows.KeyEvent {
	return &ewindows.KeyEvent{
		BKeyDown: 1, DwControlKeyState: mod, UChar: [2]byte{byte(r), byte(r >> 8)}}
}

func funcKeyEvent(code uint16, mod uint32) *ewindows.KeyEvent {
	return &ewindows.KeyEvent{
		BKeyDown: 1, DwControlKeyState: mod, WVirtualKeyCode: code}
}


text:
package org.srcdeps.core;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.srcdeps.core.BuildRequest.BuildRequestBuilder;
import org.srcdeps.core.config.scalar.CharStreamSource;
import org.srcdeps.core.util.SrcdepsCoreUtils;

/**
 * @author Peter Palaga
 */
public class GradleBuildServiceTest extends AbstractBuildServiceTest {

    @Test
    public void testGradleGitRevision() throws BuildException, IOException {
        assertBuild("git:https://github.com/srcdeps/srcdeps-test-artifact-gradle.git",
                "0.0.1-SRC-revision-389765a9de4f8526b6b2776c39bb0de67668de62", //
                "org.srcdeps.test.gradle:srcdeps-test-artifact-gradle:${version}:[pom,jar]" //
        );
    }

    /**
     * Uses a custom Gradle model transformer so that some mockito subprojects are not installed to the local maven
     * repository.
     *
     * @throws BuildException
     * @throws IOException
     */
    @Test
    public void testGradleGitRevisionMockito() throws BuildException, IOException {
        final String srcVersion = "0.0.1-SRC-revision-6030bb9be4795870a47d41c0bff8615a0e6a54f9";
        final List<Path> unwantedPaths = resolve(srcVersion, //
                "org.mockito:mockito-testng:${version}:[pom,jar]", //
                "org.mockito:mockito-android:${version}:[pom,jar]", //
                "org.mockito:mockito-inline:${version}:[pom,jar]" //
        );

        for (Path path : unwantedPaths) {
            SrcdepsCoreUtils.deleteDirectory(path.getParent());
        }

        BuilderTransformer bt = new BuilderTransformer() {
            @Override
            public BuildRequestBuilder transform(BuildRequestBuilder builder) {
                final GavSet gavSet = GavSet.builder() //
                        .include("org.mockito") //
                        .exclude("org.mockito:mockito-testng") //
                        .exclude("org.mockito:mockito-android") //
                        .exclude("org.mockito:mockito-inline") //
                        .build();
                final CharStreamSource modelTransformer = CharStreamSource.of( //
                        "literal:" //
                                + "logger.error(\"srcdeps: executing custom model transformer\")\n" //
                                + "def name2ArtifactIdMap = [\n" + "    mockito: 'mockito-core',\n"
                                + "    android: 'mockito-android',\n" + "    extTest: 'mockito-extTest',\n"
                                + "    inline: 'mockito-inline',\n" + "    kotlinTest: 'mockito-kotlinTest',\n"
                                + "    testng: 'mockito-testng',\n" + "]\n" //
                                + "gradle.projectsLoaded {\n" //
                                + "\n" //
                                + "    gradle.rootProject.properties['allprojects'].each {\n" //
                                + "        it.afterEvaluate { project ->\n" //
                                + "            def groupId = project.group\n" //
                                + "            def artifactId = name2ArtifactIdMap.get(project.name)\n" //
                                + "            def version = project.version\n" //
                                + "\n" //
                                + "            logger.error(\"srcdeps: mapped project name ${project.name} to artifactId ${artifactId}\")\n" //
                                + "            logger.error(\"srcdeps: processing ${groupId}:${artifactId}:${version}\")\n" //
                                + "            def plugins = project.plugins;\n" //
                                + "            if (srcdepsInner.gavSet.contains(groupId, artifactId, version)) {\n" //
                                + "                if (!plugins.hasPlugin('maven')) {\n" //
                                + "                    logger.error(\"srcdeps: adding maven plugin to ${groupId}:${artifactId}\")\n" //
                                + "                    plugins.apply('maven')\n" //
                                + "                }\n" //
                                + "                logger.error(\"srcdeps: changing version of ${groupId}:${artifactId} from \"+ project.version +\" to \"+ srcdepsInner.version)\n" //
                                + "                project.version = srcdepsInner.version\n" //
                                + "            }\n" //
                                + "        }\n" //
                                + "    }\n" //
                                + "}"//
                );
                return builder //
                        .gavSet(gavSet) //
                        .gradleModelTransformer(modelTransformer) //
                        .buildArgument("--stacktrace");
            }
        };

        assertBuild("git:https://github.com/srcdeps/mockito.git", srcVersion, //
                bt, //
                1, //
                "org.mockito:mockito-core:${version}:[pom,jar]"//
        );

        for (Path path : unwantedPaths) {
            Assert.assertFalse(String.format("File should not exist [%s]", path), Files.exists(path));
        }

    }

    @Test
    public void testGradleGitRevisionMultiModule() throws BuildException, IOException {
        assertBuild("git:https://github.com/srcdeps/srcdeps-test-artifact-gradle.git",
                "0.0.1-SRC-revision-e63539236a94e8f6c2d720f8bda0323d1ce4db0f", //
                "org.srcdeps.test.gradle:srcdeps-test-artifact-gradle-api:${version}:[pom,jar]", //
                "org.srcdeps.test.gradle:srcdeps-test-artifact-gradle-impl:${version}:[pom,jar]" //
        );
    }

}


text:
<?php
$formHelper = $view['form'];
$formHelper->setTheme($form, __DIR__);
if ($form->count()) {
    echo $view['form']->label($form);
}
echo $view['form']->errors($form);
echo $view['form']->widget($form);
echo $view['form']->rest($form);


text:
\hypertarget{interface_s_c_transport_result}{}\section{S\+C\+Transport\+Result Class Reference}
\label{interface_s_c_transport_result}\index{S\+C\+Transport\+Result@{S\+C\+Transport\+Result}}
Inheritance diagram for S\+C\+Transport\+Result\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=2.000000cm]{interface_s_c_transport_result}
\end{center}
\end{figure}
\subsection*{Properties}
\begin{DoxyCompactItemize}
\item
N\+S\+String $\ast$ {\bfseries result}\hypertarget{interface_s_c_transport_result_ade1479362c4f59fb7c3d300bfa907077}{}\label{interface_s_c_transport_result_ade1479362c4f59fb7c3d300bfa907077}

\item
N\+S\+String $\ast$ {\bfseries request}\hypertarget{interface_s_c_transport_result_ab784109ba6d6b5fe1717e9fd0203bc85}{}\label{interface_s_c_transport_result_ab784109ba6d6b5fe1717e9fd0203bc85}

\end{DoxyCompactItemize}

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Pod/\+Classes/\+Model/\+Transport/S\+C\+Transport\+Result.\+h\end{DoxyCompactItemize}


text:
from django.conf.urls import patterns, url

import views

urlpatterns = patterns('',
    url(r'^$', views.home, name='judge'),
 )


text:
JS merge objects

https://davidwalsh.name/merge-objects


text:
/*
 * Developed by Qingkai Shi
 * Copy Right by Prism Research Group, HKUST and State Key Lab for Novel Software Tech., Nanjing University.
 */

#include "DyckGraph/DyckVertex.h"
#include <assert.h>

int DyckVertex::global_indx = 0;

DyckVertex::DyckVertex(void * v, const char * itsname) {
	name = itsname;
	index = global_indx++;

	if (v != NULL) {
		equivclass.insert(v);
	}
}

DyckVertex::~DyckVertex() {
}

const char * DyckVertex::getName() {
	return name;
}

unsigned int DyckVertex::outNumVertices(void* label) {
    auto it = out_vers.find(label);
    if (it != out_vers.end()) {
        return it->second.size();
    }
    return 0;
}

unsigned int DyckVertex::inNumVertices(void* label) {
    auto it = in_vers.find(label);
    if (it != in_vers.end()) {
        return it->second.size();
    }
    return 0;
}

unsigned int DyckVertex::degree() {
	unsigned int ret = 0;

	map<void*, set<DyckVertex*>>::iterator iit = in_vers.begin();
	while (iit != in_vers.end()) {
		ret = ret + iit->second.size();
		iit++;
	}

	map<void*, set<DyckVertex*>>::iterator oit = out_vers.begin();
	while (oit != out_vers.end()) {
		ret = ret + oit->second.size();
		oit++;
	}

	return ret;
}

set<void*>* DyckVertex::getEquivalentSet() {
	return &this->equivclass;
}

void DyckVertex::mvEquivalentSetTo(DyckVertex* rootRep) {
	if (rootRep == this) {
		return;
	}

	set<void*>* rootecls = rootRep->getEquivalentSet();
	set<void*>* thisecls = this->getEquivalentSet();

	rootecls->insert(thisecls->begin(), thisecls->end());
}

set<void*>& DyckVertex::getOutLabels() {
	return out_lables;
}

map<void*, set<DyckVertex*>>& DyckVertex::getOutVertices() {
	return out_vers;
}

set<void*>& DyckVertex::getInLabels() {
	return in_lables;
}

map<void*, set<DyckVertex*>>& DyckVertex::getInVertices() {
	return in_vers;
}

int DyckVertex::getIndex() {
	return index;
}

void DyckVertex::addTarget(DyckVertex* ver, void* label) {
	out_lables.insert(label);
	out_vers[label].insert(ver);

	ver->addSource(this, label);
}

void DyckVertex::removeTarget(DyckVertex* ver, void* label) {
    auto it = out_vers.find(label);
    if (it != out_vers.end()) {
        it->second.erase(ver);
    }

	ver->removeSource(this, label);
}

bool DyckVertex::containsTarget(DyckVertex* tar, void* label) {
    auto it = out_vers.find(label);
    if (it != out_vers.end()) {
        return it->second.count(tar);
    }

    return false;
}

set<DyckVertex*>* DyckVertex::getInVertices(void * label) {
    auto it = in_vers.find(label);
    if (it != in_vers.end()) {
        return &it->second;
    }
    return nullptr;
}

set<DyckVertex*>* DyckVertex::getOutVertices(void * label) {
    auto it = out_vers.find(label);
    if (it != out_vers.end()) {
        return &it->second;
    }
    return nullptr;
}

// the followings are private functions

void DyckVertex::addSource(DyckVertex* ver, void* label) {
	in_lables.insert(label);
	in_vers[label].insert(ver);
}

void DyckVertex::removeSource(DyckVertex* ver, void* label) {
    auto it = in_vers.find(label);
    if (it != in_vers.end()) {
        it->second.erase(ver);
    }
}


text:
"""Contains the logic for `aq show model --all`."""

from sqlalchemy.orm import joinedload, contains_eager

from aquilon.worker.broker import BrokerCommand
from aquilon.aqdb.model import Model, Vendor

class CommandShowModelAll(BrokerCommand):

    def render(self, session, **arguments):
        q = session.query(Model)
        q = q.join(Vendor)
        q = q.options(contains_eager('vendor'),
                      joinedload('machine_specs'),
                      joinedload('machine_specs.cpu'))
        q = q.order_by(Vendor.name, Model.name)
        return q.all()


text:
layout: post
title: "Full Width Pics"
slug: full-width-pics
source: /template-overviews/full-width-pics
categories: template landing-pages one-page unstyled
description: Full width picture backgrounds.
---

<img src="/assets/img/templates/full-width-pics.jpg" class="img-responsive" alt="Bootstrap Full Width Picture Page Backgrounds">


text:
package com.noveogroup.screen_shot_report.adapters;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.noveogroup.screen_shot_report.R;
import com.taskadapter.redmineapi.bean.Project;

/**
 * Created by oisupov on 5/13/2014.
 */
public class ProjectAdapter extends ArrayAdapter<Project> {

    public ProjectAdapter(Context context) {
        super(context, R.layout.item_redmine_spinner);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.item_redmine_spinner, null);
        }

        ((TextView)convertView).setText(getItem(position).getName());
        return convertView;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getView(position, convertView, parent);
    }
}


text:
import React from 'react';
import styles from './sso-providers.scss';
import TextCenter from 'components/TextCenter';
import SsoLink from 'components/SsoLink';

const SsoProviders = ({ providers }) => (

    <TextCenter>

        {(providers || []).map(provider => (

            <SsoLink
              url={provider.url}
              text={provider.text}
            />

        ))}

    </TextCenter>

);

export default SsoProviders;


text:
"use strict";

var EventEmitter	= require('events').EventEmitter;
var inherits		= require('util').inherits;

//======================================
// Execution Object
//======================================
function Execution (p, ctxt, opts) {
	this._p				= p;		// the instance of Possible
	this._emit			= p.emit.bind(p);
	this._context		= ctxt;
	this._state			= '';

	this._invokedArgs	= void 0;
	this._resultArgs	= void 0;
	this._threw			= void 0;

	this._execWithThis	= void 0;
	this._timeoutMS		= 0;
	this._timeout		= void 0;
	this._timeStart		= 0;
	this._timeEnd		= 0;

	if (opts) {
		if (opts.timeoutMS) {
			this._timeoutMS = opts.timeoutMS;
		}
		if (opts.execWithThis) {
			this._execWithThis = opts.execWithThis;
		}
	}
}

//===========================
// Public Methods
//===========================

Execution.prototype._handler = function (err) {
	// NOTE: ensure V8 will optimize this so:
	// do NOT leak arguments

	var args = new Array(arguments.length);
	var i;

	if (this._state === 'timeout') {
		// already timed out
		return;
	}

	// if there is a timeout timer, clear it
	if (this._timeout) {
		clearTimeout(this._timeout);
		this._timeout = void 0;
	}

	this._timeEnd = + new Date();
	this._elapsed = this._timeEnd - this._timeStart;

	if (err) {
		this._state = 'error';
		this._emit('error', err, this);
	} else {
		for (i = 1; i < args.length; ++i) {
			args[i] = arguments[i];
		}
		args.shift();	// get rid of the err argument
		this._state = 'complete';
		this._resultArgs = args;
		this._emit('complete', args, this);
	}

	this._emit('end', this);
};

Execution.prototype._timeoutHandler = function () {
	this._timeEnd = + new Date();
	this._elapsed = this._timeEnd - this._timeStart;
	this._state = 'timeout';
	this._timeout = void 0;
	this._emit('timeout', this._elapsed, this);
};

Execution.prototype.didBegin = function () {
	return this._state = 'begin';
};

Execution.prototype.didComplete = function () {
	return this._state = 'complete';
};

Execution.prototype.didEnd = function () {
	return ((this._state = 'complete') || (this._state = 'error') || (this._state = 'throw') || (this._state = 'timeout'));
};

Execution.prototype.didError = function () {
	return this._state = 'error';
};

Execution.prototype.didThrow = function () {
	return this._state = 'throw';
};

Execution.prototype.didTimeout = function () {
	return this._state = 'timeout';
};

Execution.prototype.getContext = function () {
	return this._context;
};

Execution.prototype.getInvokedArgs = function () {
	return this._invokedArgs;
};

Execution.prototype.getResultArgs = function () {
	return this._resultArgs;
};

Execution.prototype.getState = function () {
	return this._state;
};

Execution.prototype.getTimeElapsed = function () {
	return this._elapsed;
};

Execution.prototype.go = function (args) {
	// NOTE: V8 will NOT optimize this function because:
	// 1) arguments has been leked
	// 2) try-ctch is used

	// Because this will not optimize, do NOT:
	// a) allocate heap objects, i.e., use: new Constructor()
	// b) do math (which does implcicit object creation)

	var execWithThis;
	var f;
	var timeoutMS;
	var timeout;

	execWithThis = this._execWithThis || this;
	f = this._p.getFunction();
	timeoutMS = this._timeoutMS;

	this._invokedArgs = args;

	if (!Array.isArray(args)) {
		args = [args];
	}

	args.push(this._handler.bind(this));

	this._state = 'begin';
	this._timeStart = + new Date();

	if (timeoutMS) {
		this._timeout = setTimeout(this._timeoutHandler.bind(this), timeoutMS);
	}

	try {
		f.apply(execWithThis, args);
	}
	catch (e) {
		this._timeEnd = + new Date();
		this._elapsed = this._timeEnd - this._timeStart;
		this._state = 'throw';
		this._threw = e;
		this._emit('threw', e, this);
		this._emit('end', this);
	}
}

//======================================
// Public Interface
//======================================

function Possible (f) {
	this._function		= f;
}
inherits(Possible, EventEmitter);

//===========================
// Public Methods
//===========================

Possible.prototype.execute = function (args, ctxt, opts) {

	var exec = new Execution(this, ctxt, opts);

	exec.go(args);
}

Possible.prototype.getFunction = function () {
	return this._function;
};

//===========================
// exports
//===========================

exports = module.exports = Possible;


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [0.1.1.1] - 2015-06-20
### Fixed
- Actually use HTTP caching in static middleware
- Change "Server" header to mention spas

## [0.1.1.0] - 2015-06-20
### Added
- HTTP caching support for static files

## [0.1.0.0] - 2015-05-22
### Added
- Initial release


text:
package com.eixox.xml.adapters;

import org.w3c.dom.Element;

public interface XmlAdapter {

	public Object readXml(Element parent);

	public void writeXml(Element parent, Object value);

}


text:
package apimodels;

import apimodels.CauseUserIdCause;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.*;
import java.util.Set;
import javax.validation.*;
import java.util.Objects;
import javax.validation.constraints.*;
/**
 * CauseAction
 */
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen", date = "2022-06-04T08:08:33.694891Z[Etc/UTC]")
@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"})
public class CauseAction   {
  @JsonProperty("_class")

  private String propertyClass;

  @JsonProperty("causes")
  @Valid

  private List<CauseUserIdCause> causes = null;

  public CauseAction propertyClass(String propertyClass) {
    this.propertyClass = propertyClass;
    return this;
  }

   /**
   * Get propertyClass
   * @return propertyClass
  **/
  public String getPropertyClass() {
    return propertyClass;
  }

  public void setPropertyClass(String propertyClass) {
    this.propertyClass = propertyClass;
  }

  public CauseAction causes(List<CauseUserIdCause> causes) {
    this.causes = causes;
    return this;
  }

  public CauseAction addCausesItem(CauseUserIdCause causesItem) {
    if (causes == null) {
      causes = new ArrayList<>();
    }
    causes.add(causesItem);
    return this;
  }

   /**
   * Get causes
   * @return causes
  **/
  public List<CauseUserIdCause> getCauses() {
    return causes;
  }

  public void setCauses(List<CauseUserIdCause> causes) {
    this.causes = causes;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CauseAction causeAction = (CauseAction) o;
    return Objects.equals(propertyClass, causeAction.propertyClass) &&
        Objects.equals(causes, causeAction.causes);
  }

  @Override
  public int hashCode() {
    return Objects.hash(propertyClass, causes);
  }

  @SuppressWarnings("StringBufferReplaceableByString")
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CauseAction {\n");

    sb.append("    propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
    sb.append("    causes: ").append(toIndentedString(causes)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
MongoDB 3.6 NoSQL Database Server container image
====================

This repository contains Dockerfiles for MongoDB images for general usage and OpenShift.
Users can choose between RHEL and CentOS based images.
The RHEL image is available in the [Red Hat Container Catalog](https://access.redhat.com/containers/#/registry.access.redhat.com/rhscl/mongodb-36-rhel7)
as registry.access.redhat.com/rhscl/mongodb-36-rhel7.
The CentOS image is then available on [Docker Hub](https://hub.docker.com/r/centos/mongodb-36-centos7/)
as centos/mongodb-36-centos7.

Description
-----------

This container image provides a containerized packaging of the MongoDB mongod daemon
and client application. The mongod server daemon accepts connections from clients
and provides access to content from MongoDB databases on behalf of the clients.
You can find more information on the MongoDB project from the project Web site
(https://www.mongodb.com/).

Usage
-----

For this, we will assume that you are using the `rhscl/mongodb-36-rhel7` image.
If you want to set only the mandatory environment variables and store the database
in the `/home/user/database` directory on the host filesystem, execute the following command:

```
$ docker run -d -e MONGODB_USER=<user> -e MONGODB_PASSWORD=<password> -e MONGODB_DATABASE=<database> -e MONGODB_ADMIN_PASSWORD=<admin_password> -v /home/user/database:/var/lib/mongodb/data rhscl/mongodb-36-rhel7
```

If you are initializing the database and it's the first time you are using the
specified shared volume, the database will be created with two users: `admin`
and `MONGODB_USER`. After that the MongoDB daemon will be started. If you are
re-attaching the volume to another container, the creation of the database
user and admin user will be skipped, passwords of users will be changed and
only the MongoDB daemon will be started.

Environment variables and volumes
---------------------------------

The image recognizes the following environment variables that you can set
during initialization by passing `-e VAR=VALUE` to the Docker run command.

**`MONGODB_ADMIN_PASSWORD`**
       Password for the admin user

Optionally you can provide settings for user with 'readWrite' role.
(Note you MUST specify all three of these settings)

**`MONGODB_USER`**
       User name for MONGODB account to be created

**`MONGODB_PASSWORD`**
       Password for the user account

**`MONGODB_DATABASE`**
       Database name

The following environment variables influence the MongoDB configuration file.
They are all optional.

**`MONGODB_QUIET (default: true)`**
       Runs MongoDB in a quiet mode that attempts to limit the amount of output.

You can also set the following mount points by passing the `-v
/host:/container` flag to Docker.

**`/var/lib/mongodb/data`**
       MongoDB data directory

**Notice: When mounting a directory from the host into the container, ensure
that the mounted directory has the appropriate permissions and that the owner
and group of the directory matches the user UID or name which is running
inside the container.**

MongoDB admin user
---------------------------------

The admin user name is set to `admin` and you have to to specify the password by
setting the `MONGODB_ADMIN_PASSWORD` environment variable.

This user has 'dbAdminAnyDatabase', 'userAdminAnyDatabase',
'readWriteAnyDatabase', 'clusterAdmin' roles (for more information see
[MongoDB
reference](https://docs.mongodb.com/manual/reference/built-in-roles/)).

Optional unprivileged user
---------------------------------

The user with `$MONGODB_USER` name is created in database `$MONGODB_DATABASE`
and you have to to specify the password by setting the `MONGODB_PASSWORD`
environment variable.

This user has only 'readWrite' role in the database.

Changing passwords
---------------------------------

Since passwords are part of the image configuration, the only supported method
to change passwords for the database user (`MONGODB_USER`) and admin user is
by changing the environment variables `MONGODB_PASSWORD` and
`MONGODB_ADMIN_PASSWORD`, respectively.

Changing database passwords directly in MongoDB will cause a mismatch between
the values stored in the variables and the actual passwords. Whenever a
database container starts it will reset the passwords to the values stored in
the environment variables.

Extending image
---------------------------------

This image can be extended using
[source-to-image](https://github.com/openshift/source-to-image).

For example to build customized MongoDB database image `my-mongodb-centos7`
with configuration in `~/image-configuration/` run:

```
$ s2i build ~/image-configuration/ centos/mongodb-36-centos7 my-mongodb-centos7
```

The directory passed to `s2i build` should contain one or more of the
following directories:

----------------------------------------------

##### `mongodb-cfg/`

when running `run-mongod` or `run-mongod-replication` commands contained
`mongod.conf` file is used for `mongod` configuration

~~~~~
- `envsubst` command is run on this file to still allow customization of
  the image using environment variables

- custom configuration file does not affect name of replica set - it has
  to be set in `MONGODB_REPLICA_NAME` environment variable

- it is not possible to configure SSL using custom configuration file
~~~~~

#####  `mongodb-ssl/`

SSL/TLS certificates used to configure MongoDB server SSL/TLS support

~~~~~
- `mongodb.pem` - file containing a public key certificate and its
associated private key. See [upstream
documentation](https://docs.mongodb.com/manual/tutorial/configure-ssl/#pem-file)
(encryption of private key is not supported).

- `ca.pem` - optional file containing the root certificate chain from
the Certificate Authority. See [upstream
documentation](https://docs.mongodb.com/manual/tutorial/configure-ssl/#set-up-mongod-and-mongos-with-certificate-validation)
~~~~~

##### `mongodb-pre-init/`

contained shell scripts (`*.sh`) are sourced before `mongod` server is
started

##### `mongodb-init/`

contained shell scripts (`*.sh`) are sourced when `mongod` server is
started for the first time (= datadir is empty)
~~~~~
- `run-mongod` command doesn't have enabled authentication in this phase

- `run-mongod-replication` command has enabled authentication in this phase
~~~~~

##### `mongodb-start/`

same sematics as `mongodb-init/`, except that these scripts are always sourced
(after `mongodb-init/` scripts, if they exist)

these scripts are skipped if `run-mongod-replication` is run with already
initialized data directory

----------------------------------------------

Variables that can be used in the scripts provided to s2i:

~~~~~
- `mongo_common_args` -- contains arguments for the `mongod` server (changing
this can break existing customization scripts, e.g. default scripts)

- `shell_args` -- arguments to mongo shell which should be used with every `mongo`
invocation (e.g. it's used to set parameters for SSL connection). Same as in
internal scripts, `mongo_cmd` function, which uses `shell_args`, can be used.

- `$MEMBER_ID` -- contains 'id' of the container. It is defined only in
scripts for replication (`run-mongod-replication` command) and has different
value for each container in a replicaset cluster. Customization scripts are
run by all containers in replicaset - `MEMBER_ID` can be used to write scripts
which are run only by some container.
~~~~~

During `s2i build` all provided files are copied into `/opt/app-root/src`
directory in the new image. If some configuration files are present in
destination directory, files with the same name are overwritten. Also only one
file with the same name can be used for customization and user provided files
are preferred over default files in `/usr/share/container-scripts/mongodb/`-
so it is possible to overwrite them.

Same configuration directory structure can be used to customize the image
every time the image is started using `docker run`. The directory have to be
mounted into `/opt/app-root/src/` in the image (`-v
./image-configuration/:/opt/app-root/src/`). This overwrites customization
built into the image.

Troubleshooting
---------------
The mongod deamon in the container logs to the standard output, so the log is available in the container log. The log can be examined by running:

    docker logs <container>

See also
--------
Dockerfile and other sources for this container image are available on
https://github.com/sclorg/mongodb-container.
In that repository, Dockerfile for CentOS is called Dockerfile, Dockerfile
for RHEL is called Dockerfile.rhel7.


text:
/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , debug = require('debug')('engine:socket')

/**
 * Module exports.
 */

module.exports = Socket;

/**
 * Client class (abstract).
 *
 * @api private
 */

function Socket (id, server, transport) {
  this.id = id;
  this.server = server;
  this.upgraded = false;
  this.readyState = 'opening';
  this.writeBuffer = [];
  this.packetsFn = [];
  this.sentCallbackFn = [];

  this.setTransport(transport);
  this.onOpen();
}

/**
 * Inherits from EventEmitter.
 */

Socket.prototype.__proto__ = EventEmitter.prototype;

/**
 * Accessor for request that originated socket.
 *
 * @api public
 */

Socket.prototype.__defineGetter__('request', function () {
  return this.transport.request;
});

/**
 * Called upon transport considered open.
 *
 * @api private
 */

Socket.prototype.onOpen = function () {
  this.readyState = 'open';

  // sends an `open` packet
  this.transport.sid = this.id;
  this.sendPacket('open', JSON.stringify({
      sid: this.id
    , upgrades: this.getAvailableUpgrades()
    , pingInterval: this.server.pingInterval
    , pingTimeout: this.server.pingTimeout
  }));

  this.emit('open');
  this.setPingTimeout();
};

/**
 * Called upon transport packet.
 *
 * @param {Object} packet
 * @api private
 */

Socket.prototype.onPacket = function (packet) {
  if ('open' == this.readyState) {
    // export packet event
    debug('packet');
    this.emit('packet', packet);

    // Reset ping timeout on any packet, incoming data is a good sign of
    // other side's liveness
    this.setPingTimeout();

    switch (packet.type) {

      case 'ping':
        debug('got ping');
        this.sendPacket('pong');
        this.emit('heartbeat');
        break;

      case 'error':
        this.onClose('parse error');
        break;

      case 'message':
        this.emit('data', packet.data);
        this.emit('message', packet.data);
        break;
    }
  } else {
    debug('packet received with closed socket');
  }
};

/**
 * Called upon transport error.
 *
 * @param {Error} error object
 * @api private
 */

Socket.prototype.onError = function (err) {
  debug('transport error');
  this.onClose('transport error', err);
};

/**
 * Sets and resets ping timeout timer based on client pings.
 *
 * @api private
 */

Socket.prototype.setPingTimeout = function () {
  var self = this;
  clearTimeout(self.pingTimeoutTimer);
  self.pingTimeoutTimer = setTimeout(function () {
    self.onClose('ping timeout');
  }, self.server.pingInterval + self.server.pingTimeout);
};

/**
 * Attaches handlers for the given transport.
 *
 * @param {Transport} transport
 * @api private
 */

Socket.prototype.setTransport = function (transport) {
  this.transport = transport;
  this.transport.once('error', this.onError.bind(this));
  this.transport.on('packet', this.onPacket.bind(this));
  this.transport.on('drain', this.flush.bind(this));
  this.transport.once('close', this.onClose.bind(this, 'transport close'));
  //this function will manage packet events (also message callbacks)
  this.setupSendCallback();
};

/**
 * Upgrades socket to the given transport
 *
 * @param {Transport} transport
 * @api private
 */

Socket.prototype.maybeUpgrade = function (transport) {
  debug('might upgrade socket transport from "%s" to "%s"'
    , this.transport.name, transport.name);

  var self = this;

  // set transport upgrade timer
  self.upgradeTimeoutTimer = setTimeout(function () {
    debug('client did not complete upgrade - closing transport');
    clearInterval(self.checkIntervalTimer);
    if ('open' == transport.readyState) {
      transport.close();
    }
  }, this.server.upgradeTimeout);

  function onPacket (packet) {
    if ('ping' == packet.type && 'probe' == packet.data) {
      transport.send([{ type: 'pong', data: 'probe' }]);

      // we force a polling cycle to ensure a fast upgrade
      function check () {
        if ('polling' == self.transport.name && self.transport.writable) {
          debug('writing a noop packet to polling for fast upgrade');
          self.transport.send([{ type: 'noop' }]);
        }
      }

      self.checkIntervalTimer = setInterval(check, 100);
    } else if ('upgrade' == packet.type && self.readyState == 'open') {
      debug('got upgrade packet - upgrading');
      self.upgraded = true;
      self.emit('upgrade', transport);
      self.clearTransport();
      self.setTransport(transport);
      self.setPingTimeout();
      self.flush();
      clearInterval(self.checkIntervalTimer);
      clearTimeout(self.upgradeTimeoutTimer);
      transport.removeListener('packet', onPacket);
    } else {
      transport.close();
    }
  }
  transport.on('packet', onPacket);
};

/**
 * Clears listeners and timers associated with current transport.
 *
 * @api private
 */

Socket.prototype.clearTransport = function () {
  // silence further transport errors and prevent uncaught exceptions
  this.transport.on('error', function(){
    debug('error triggered by discarded transport');
  });
  clearTimeout(this.pingIntervalTimer);
  clearTimeout(this.pingTimeoutTimer);
};

/**
 * Called upon transport considered closed.
 * Possible reasons: `ping timeout`, `client error`, `parse error`,
 * `transport error`, `server close`, `transport close`
 */

Socket.prototype.onClose = function (reason, description) {
  if ('closed' != this.readyState) {
    clearTimeout(this.pingTimeoutTimer);
    clearInterval(this.checkIntervalTimer);
    clearTimeout(this.upgradeTimeoutTimer);
    var self = this;
    // clean writeBuffer in next tick, so developers can still
    // grab the writeBuffer on 'close' event
    process.nextTick(function() {
      self.writeBuffer = [];
    });
    this.packetsFn = [];
    this.sentCallbackFn = [];
    this.clearTransport();
    this.readyState = 'closed';
    this.emit('close', reason, description);
  }
};

/**
 * Setup and manage send callback
 *
 * @api private
 */

Socket.prototype.setupSendCallback = function () {
  var self = this;
  //the message was sent successfully, execute the callback
  this.transport.on('drain', function() {
    if (self.sentCallbackFn.length > 0) {
      var seqFn = self.sentCallbackFn.splice(0,1)[0];
      if ('function' == typeof seqFn) {
        debug('executing send callback');
        seqFn(self.transport);
      } else if (Array.isArray(seqFn)) {
        debug('executing batch send callback');
        for (var i in seqFn) {
          if ('function' == typeof seqFn[i]) {
            seqFn[i](self.transport);
          }
        }
      }
    }
  });
};

/**
 * Sends a message packet.
 *
 * @param {String} message
 * @param {Function} callback
 * @return {Socket} for chaining
 * @api public
 */

Socket.prototype.send =
Socket.prototype.write = function(data, callback){
  this.sendPacket('message', data, callback);
  return this;
};

/**
 * Sends a packet.
 *
 * @param {String} packet type
 * @param {String} optional, data
 * @api private
 */

Socket.prototype.sendPacket = function (type, data, callback) {
  if ('closing' != this.readyState) {
    debug('sending packet "%s" (%s)', type, data);

    var packet = { type: type };
    if (data) packet.data = data;

    // exports packetCreate event
    this.emit('packetCreate', packet);

    this.writeBuffer.push(packet);

    //add send callback to object
    this.packetsFn.push(callback);

    this.flush();
  }
};

/**
 * Attempts to flush the packets buffer.
 *
 * @api private
 */

Socket.prototype.flush = function () {
  if ('closed' != this.readyState && this.transport.writable
    && this.writeBuffer.length) {
    debug('flushing buffer to transport');
    this.emit('flush', this.writeBuffer);
    this.server.emit('flush', this, this.writeBuffer);
    var wbuf = this.writeBuffer;
    this.writeBuffer = [];
    if (!this.transport.supportsFraming) {
      this.sentCallbackFn.push(this.packetsFn)
    } else {
      this.sentCallbackFn.push.apply(this.sentCallbackFn, this.packetsFn);
    }
    this.packetsFn = [];
    this.transport.send(wbuf);
    this.emit('drain');
    this.server.emit('drain', this);
  }
};

/**
 * Get available upgrades for this socket.
 *
 * @api private
 */

Socket.prototype.getAvailableUpgrades = function () {
  var availableUpgrades = [];
  var allUpgrades = this.server.upgrades(this.transport.name);
  for (var i = 0, l = allUpgrades.length; i < l; ++i) {
    var upg = allUpgrades[i];
    if (this.server.transports.indexOf(upg) != -1) {
      availableUpgrades.push(upg);
    }
  }
  return availableUpgrades;
};

/**
 * Closes the socket and underlying transport.
 *
 * @return {Socket} for chaining
 * @api public
 */

Socket.prototype.close = function () {
  if ('open' == this.readyState) {
    this.readyState = 'closing';
    var self = this;
    this.transport.close(function () {
      self.onClose('forced close');
    });
  }
};


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
K. Iwatsuki et al. , Fl. Japan 2b:49. 2001

#### Original name
Saxifraga jotanii Honda

### Remarks
null


text:
/**
 * @author Anatoly F. Bondarenko
 */

/**
 * Created on 18.02.2005
 */
package org.apache.harmony.jpda.tests.jdwp.ReferenceType;

import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer;
import org.apache.harmony.jpda.tests.share.SyncDebuggee;

public class FieldsWithGenericDebuggee extends SyncDebuggee {

    static long staticLongField;
    String[] stringArrayField;
    Object[] objectArrayField;
//    Class<String> classObjectField_2;
    Class classObjectField;

    public void run() {
        synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_READY);
        logWriter.println("--> Debuggee: FieldsWithGenericDebuggee...");
        synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
    }

    public static void main(String [] args) {
        runDebuggee(FieldsWithGenericDebuggee.class);
    }

}


text:
'use strict';

/**
 * Ensure that all environment variables are configured.
 */

var dotenv = require('dotenv');
dotenv.config();

[
  'DOMAIN',
  'MAIN_PATH',
  'PORT',
  'TOKEN',
].forEach(varName => {
  if (!process.env.hasOwnProperty(varName)) {
    throw new Error('Missing environment variable: ' + varName);
  }
});

/**
 * Module dependencies.
 */

var spawn = require('child_process').spawn;
var fs = require('fs');
var http = require('http');
var path = require('path');

var bodyParser = require('body-parser');
var Docker = require('dockerode');
var express = require('express');
var helmet = require('helmet');
var touch = require("touch");
var uuidv4 = require('uuid/v4');

/**
 * Verify that Docker is running.
 */

var socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock';
var stats  = fs.statSync(socket);

if (!stats.isSocket()) {
  throw new Error('Are you sure docker is running?');
}

/**
 * Initialize express server.
 */

var app = express();
var docker = new Docker({ socketPath: socket });
app.use(helmet());
app.use(bodyParser.json());

// [private] Create a new build based on req.body.revision
app.post('/apps/:app_name/builds', function(req, res, next) {
  // Checks if token is present
  if (! req.query.token || req.query.token !== process.env.TOKEN) {
    var err = new Error();
    err.status = 404;
    return next(err);
  }

  // Verifies if app_name is valid
  var app_path = path.join(process.env.MAIN_PATH, req.params.app_name);
  if (! fs.existsSync(app_path)) {
    return res.status(500).json({ 'error': 'App not found' });
  }

  // Checks if revision field is supplied
  var revision = req.body.revision;
  if (! req.body || ! revision) {
    return res.status(500).json({ 'error': 'Invalid revision' });
  }

  // Verifies if file is there
  console.log(req.body);
  var source_file = path.join(app_path, 'sources', `${revision}.tgz`);
  if (! fs.existsSync(source_file)) {
    return res.status(500).json({ 'error': 'Invalid revision' });
  }

  console.log(`Build started for ${req.params.app_name}:`);
  console.log(`\tRevision: ${revision}`);

  // Generate build id and create directory for build
  var build_id;
  var build_dir;
  do {
    build_id = uuidv4();
    build_dir = path.join(app_path, 'builds', build_id);
  } while (fs.existsSync(build_dir));
  fs.mkdirSync(build_dir);

  // Create logs directory
  var logs_dir = path.join(build_dir, 'logs');
  fs.mkdirSync(logs_dir);

  // Touch slug.tgz so that we can mount it to container
  touch.sync(path.join(build_dir, 'slug.tgz'));

  // Write stream for build and error logs
  var log_stream = fs.createWriteStream(path.join(logs_dir, 'build.log'));
  var err_stream = fs.createWriteStream(path.join(logs_dir, 'error.log'));

  // Return response to user first
  res.json({
    output_stream_url: `${process.env.DOMAIN}/apps/${req.params.app_name}/builds/${build_id}/logs`
  });

  // Background work
  var statusCode;
  console.log('\tCreating container...');
  docker.run(
    'imjching/slugc',
    ['/bin/bash', '-c', 'tar -xzf /tmp/sources/source.tgz && /build'],
    [log_stream, err_stream], // closes the stream as well
    {
      HostConfig: {
        Binds: [
          `${process.env.MAIN_PATH}/${req.params.app_name}/sources/${revision}.tgz:/tmp/sources/source.tgz`,
          `${process.env.MAIN_PATH}/${req.params.app_name}/builds/${build_id}/slug.tgz:/tmp/slugs/slug.tgz`,
          `${process.env.MAIN_PATH}/${req.params.app_name}/cache:/tmp/cache`,
        ],
        AutoRemove: true
      },
      Tty: false
    }
  ).then(function({ output }) {
    console.log('\tContainer created...');
    statusCode = output.StatusCode;

    // Create log stream again since it was closed earlier
    log_stream = fs.createWriteStream(path.join(logs_dir, 'build.log'), {'flags': 'a'});
    log_stream.write('-----> Launching...\n');
    // Do not do docker.run here, since docker.run calls container.wait();
    return docker.createContainer({
      Image: 'imjching/slugr',
      Labels: {
        'traefik.backend': req.params.app_name,
        'traefik.docker.network': 'web',
        'traefik.frontend.rule': `Host:${req.params.app_name}.ceroku.com`,
        'traefik.enable': 'true'
      },
      Env: [
        'PORT=5000',
      ],
      ExposedPorts: {
        '5000/tcp': { }
      },
      HostConfig: {
        Binds: [
          `${process.env.MAIN_PATH}/${req.params.app_name}/builds/${build_id}/slug.tgz:/tmp/slugs/slug.tgz`
        ],
        AutoRemove: true,
        // PublishAllPorts: true,
        // RestartPolicy: {
        //   Name: 'always'
        // },
        NetworkMode: 'web'
      },
      Cmd: ['/bin/bash', '-c', 'tar -xzf /tmp/slugs/slug.tgz && /start web']
    });
  }).then(function(container) {
    console.log('\tStarting container...');
    return container.start();
  }).then(function(container) {
    return container.inspect();
  }).then(function(container) {
    var Ports = container.NetworkSettings.Ports;
    if (!('5000/tcp' in Ports)) {
      console.log('\tERROR');
      return;
    }
    // Here, we should get router to route url to this new port,
    // then filter based on app name and release id,
    // and finally remove old containers
    // insert new version into database
    log_stream.write('       Released v6\n');
    log_stream.write(`       http://${req.params.app_name}.ceroku.com/ deployed to Ceroku\n`);
    log_stream.end();
    err_stream.end();

    console.log('\tDONE');
    // console.log('\t' + JSON.stringify(Ports, null, 2));
    return docker.listContainers({
      filters: JSON.stringify({
        label: [`traefik.backend=${req.params.app_name}`],
        before: [container.Id]
      })
    });
  }).then(function(containers) {
    var tmp_stream = fs.createWriteStream(path.join(logs_dir, 'build.tmp'));
    tmp_stream.write(statusCode + '\n');
    tmp_stream.end();

    containers.forEach(function (containerInfo) {
      docker.getContainer(containerInfo.Id).stop(function(err, result) {
        // ignore
      });
    });
  }).catch(function(err) {
    console.log(err);
  });
});

// [public] path to stream build logs
app.get('/apps/:app_name/builds/:build_id/logs', function(req, res, next) {
  // Set Content-Type to text/plain
  res.type('.txt');

  // Verifies if app_name is valid
  var app_path = path.join(process.env.MAIN_PATH, req.params.app_name);
  if (! fs.existsSync(app_path)) {
    return res.status(404).send('404 Not Found');
  }

  // Verifies if build_id is valid
  var V4_UUID = /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
  if (! V4_UUID.test(req.params.build_id)) {
    return res.status(404).send('404 Not Found');
  }

  var logs_dir = path.join(app_path, 'builds', req.params.build_id, 'logs');
  var log = path.join(logs_dir, 'build.log');
  var tmp = path.join(logs_dir, 'build.tmp');

  // Check if log exists
  if (! fs.existsSync(log)) {
    return res.status(404).send('404 Not Found');
  }

  // If build is done, send everything
  if (fs.existsSync(tmp)) {
    return res.sendFile(log);
  }

  var ps = spawn('tail', ['-f', '-n', '+1', log]);
  var lastReceiveTime = new Date().getTime();

  ps.stdout.on('data', function(data) {
    lastReceiveTime = new Date().getTime();
    res.write(data);
  });

  var timerId = setInterval(function() {
    if (lastReceiveTime + 10000 < new Date() || fs.existsSync(tmp)) {
      // Check if ${req.params.build_id}.tmp exists
      // TODO: remove .tmp at end of build once database implementation is ready
      clearInterval(timerId);
      ps.kill();
      return res.end(); // Stop the streaming
    }
  }, 1000);

  req.on('close', function() {
    clearInterval(timerId);
    ps.kill();
  });
});

/**
 * 404 handler.
 */

app.use(function(req, res, next) {
  // console.log(req.url);
  // console.log(req.headers);
  var err = new Error();
  err.status = 404;
  next(err);
});

/**
 * Error handler.
 */

app.use(function(err, req, res, next) {
  err.status = err.status || 500;
  console.log(err);
  res.status(err.status).send(err.status + ' ' + http.STATUS_CODES[err.status]);
});

/**
 * Listen on provided port, on all network interfaces.
 */

var PORT = process.env.PORT || 9002;
app.listen(PORT, function(error) {
  error
  ? console.error(error)
  : console.log(`-----> Build Server listening on port ${PORT}`);
});


text:
package org.topology.bgp_ls.netty.protocol.update.bgplsnlri;

import org.topology.bgp_ls.net.SubsequentAddressFamily;
import org.topology.bgp_ls.net.attributes.MultiProtocolNLRIInformation;
import org.topology.bgp_ls.net.attributes.bgplsnlri.BgpLsNLRIInformation;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is used for decoding a BGP link-state NLRI for VPNs.
 * VPN topology is a special case of non-VPN topology, containing VPN
 * specific attributes, in addition to the regular topology data.
 * @author nitinb
 *
 */
public class BgpLsNLRIVpnCodec extends BgpLsNLRICodec {

	private static final Logger log = LoggerFactory.getLogger(BgpLsNLRIVpnCodec.class);

	/**
	 * Decodes the data portion of a MP-BGP link state NLRI
	 * @param buffer Data stream containing the tlv
	 */
	public MultiProtocolNLRIInformation decodeNLRI(ChannelBuffer buffer) {

		BgpLsNLRIInformation nlriInfo;

		int type = buffer.readUnsignedShort();
		int length = buffer.readUnsignedShort();

		// not enough bytes in the buffer to read the NLRI
		if (buffer.readableBytes() < length) {
			log.error("Failed to decode BGP-LS NLRI type " + type + " due to completely read NLRI");
			return null;
		}

		// get the route distinguisher
		byte[] routeDistinguisher = new byte[8];
		buffer.readBytes(routeDistinguisher);

		ChannelBuffer valueBuffer = ChannelBuffers.buffer(length - 8);
		buffer.readBytes(valueBuffer);

		nlriInfo = decodeNLRIInternal(valueBuffer, SubsequentAddressFamily.NLRI_MPLS_VPN, type);
		if (nlriInfo != null) {
			nlriInfo.setRouteDistinguisher(routeDistinguisher);
		}

		return nlriInfo;
	}
}


text:
package org.gradle.initialization;

import org.gradle.api.Transformer;
import org.gradle.api.internal.file.BasicFileResolver;
import org.gradle.internal.buildoption.BuildOption;
import org.gradle.internal.buildoption.BuildOptionSet;
import org.gradle.internal.buildoption.CommandLineOptionConfiguration;
import org.gradle.internal.buildoption.Origin;
import org.gradle.internal.buildoption.StringBuildOption;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BuildLayoutParametersBuildOptions extends BuildOptionSet<BuildLayoutParameters> {

    private static List<BuildOption<? super BuildLayoutParameters>> options;

    static {
        List<BuildOption<BuildLayoutParameters>> options = new ArrayList<BuildOption<BuildLayoutParameters>>();
        options.add(new GradleUserHomeOption());
        options.add(new ProjectDirOption());
        BuildLayoutParametersBuildOptions.options = Collections.unmodifiableList(options);
    }

    @Override
    public List<BuildOption<? super BuildLayoutParameters>> getAllOptions() {
        return options;
    }

    public static class GradleUserHomeOption extends StringBuildOption<BuildLayoutParameters> {
        public GradleUserHomeOption() {
            super(BuildLayoutParameters.GRADLE_USER_HOME_PROPERTY_KEY, CommandLineOptionConfiguration.create("gradle-user-home", "g", "Specifies the Gradle user home directory. Defaults to ~/.gradle"));
        }

        @Override
        public void applyTo(String value, BuildLayoutParameters settings, Origin origin) {
            Transformer<File, String> resolver = new BasicFileResolver(settings.getCurrentDir());
            settings.setGradleUserHomeDir(resolver.transform(value));
        }
    }

    public static class ProjectDirOption extends StringBuildOption<BuildLayoutParameters> {
        public ProjectDirOption() {
            super(null, CommandLineOptionConfiguration.create("project-dir", "p", "Specifies the start directory for Gradle. Defaults to current directory."));
        }

        @Override
        public void applyTo(String value, BuildLayoutParameters settings, Origin origin) {
            Transformer<File, String> resolver = new BasicFileResolver(settings.getCurrentDir());
            File projectDir = resolver.transform(value);
            settings.setCurrentDir(projectDir);
            settings.setProjectDir(projectDir);
        }
    }
}


text:
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace GooglePlayGames.Native.Cwrapper {
internal static class RealTimeRoomConfigBuilder {
    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_PopulateFromPlayerSelectUIResponse(
        HandleRef self,
         /* from(RealTimeMultiplayerManager_PlayerSelectUIResponse_t) */ IntPtr response);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_SetVariant(
        HandleRef self,
         /* from(uint32_t) */ uint variant);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_AddPlayerToInvite(
        HandleRef self,
         /* from(char const *) */ string player_id);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern /* from(RealTimeRoomConfig_Builder_t) */ IntPtr RealTimeRoomConfig_Builder_Construct();

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_SetExclusiveBitMask(
        HandleRef self,
         /* from(uint64_t) */ ulong exclusive_bit_mask);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_SetMaximumAutomatchingPlayers(
        HandleRef self,
         /* from(uint32_t) */ uint maximum_automatching_players);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern /* from(RealTimeRoomConfig_t) */ IntPtr RealTimeRoomConfig_Builder_Create(
        HandleRef self);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_SetMinimumAutomatchingPlayers(
        HandleRef self,
         /* from(uint32_t) */ uint minimum_automatching_players);

    [DllImport(SymbolLocation.NativeSymbolLocation)]
    internal static extern void RealTimeRoomConfig_Builder_Dispose(
        HandleRef self);
}
}
#endif // (UNITY_ANDROID || UNITY_IPHONE)


text:
title: Sampling 10 rows per groupb in PySpark
date: 2021-10-15
layout: post
---

You need to use a window partition by and let the random number do the shuffle for you.

	from pyspark.sql import Window

	(
	  df
	  .withColumn(
	    "random_number", F.rand()
	  )
	  .withColumn(
	    "row_id",
	    F.row_number().over(
	      Window().partitionBy("level0", "level1", "level2").orderBy(F.col("random_number").desc())
	    )
	  )
	  .where(F.col("row_id") < 10)
	  .orderBy("level0", "level1", "level2")
	  .show()
	)


text:
AndroidAdventure_tig055
=======================

Project in the summer course TIG055 GU 2014.


text:
package com.fjsg.linggan.service.dao.impl;

import org.junit.Test;

import com.fjsg.linggan.service.entity.Linggan;
import com.fjsg.linggan.service.enums.LingganTypeEnum;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Áé¸ÐDAOµ¥Ôª²âÊÔ
 *
 * @author zhaojun.wzj
 * @version $Id LingganDAOImplTest.java, v 0.1 2017-07-28 20:46 zhaojun.wzj Exp $$
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class LingganDAOImplTest {

    @Resource
    private LingganDAOImpl lingganDAO;

    @Test
    public void testSave() {
        Linggan linggan = new Linggan();
        linggan.setUserId("2");
        linggan.setContent("testXX");
        linggan.setContentType(LingganTypeEnum.LINGGAN_TYPE_TEXT.getCode());
        long curTime = System.currentTimeMillis();
        linggan.setCreateTime(curTime);
        linggan.setLastModified(curTime);

        lingganDAO.save(linggan);
    }

}


text:
.class final Landroid/text/util/Linkify$3;
.super Ljava/lang/Object;
.source "Linkify.java"

# interfaces
.implements Landroid/text/util/Linkify$MatchFilter;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/text/util/Linkify;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public final acceptMatch(Ljava/lang/CharSequence;II)Z
    .locals 12

    const/4 v0, 0x0

    move v5, p2

    :goto_0
    if-ge v5, p3, :cond_1

    invoke-interface {p1, v5}, Ljava/lang/CharSequence;->charAt(I)C

    move-result v10

    invoke-static {v10}, Ljava/lang/Character;->isDigit(C)Z

    move-result v10

    if-eqz v10, :cond_0

    add-int/lit8 v0, v0, 0x1

    :cond_0
    add-int/lit8 v5, v5, 0x1

    goto :goto_0

    :cond_1
    const/4 v7, 0x5

    const/16 v6, 0xd

    invoke-static {}, Lcom/samsung/android/feature/SemCscFeature;->getInstance()Lcom/samsung/android/feature/SemCscFeature;

    move-result-object v10

    const-string/jumbo v11, "CscFeature_Framework_ConfigLinkifyDigit"

    invoke-virtual {v10, v11}, Lcom/samsung/android/feature/SemCscFeature;->getString(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    invoke-static {v2}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z

    move-result v10

    if-nez v10, :cond_4

    const/4 v5, 0x0

    const/4 v10, 0x2

    new-array v1, v10, [I

    const/4 v10, 0x5

    const/4 v11, 0x0

    aput v10, v1, v11

    const/16 v10, 0xd

    const/4 v11, 0x1

    aput v10, v1, v11

    new-instance v8, Landroid/text/TextUtils$SimpleStringSplitter;

    const/16 v10, 0x3b

    invoke-direct {v8, v10}, Landroid/text/TextUtils$SimpleStringSplitter;-><init>(C)V

    invoke-virtual {v8, v2}, Landroid/text/TextUtils$SimpleStringSplitter;->setString(Ljava/lang/String;)V

    :cond_2
    :goto_1
    :try_start_0
    invoke-virtual {v8}, Landroid/text/TextUtils$SimpleStringSplitter;->hasNext()Z

    move-result v10

    if-eqz v10, :cond_3

    invoke-virtual {v8}, Landroid/text/TextUtils$SimpleStringSplitter;->next()Ljava/lang/String;

    move-result-object v9

    if-eqz v9, :cond_2

    invoke-static {v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I

    move-result v10

    aput v10, v1, v5

    add-int/lit8 v5, v5, 0x1

    goto :goto_1

    :cond_3
    const/4 v10, 0x0

    aget v7, v1, v10

    const/4 v10, 0x1

    aget v6, v1, v10
    :try_end_0
    .catch Ljava/lang/ArrayIndexOutOfBoundsException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/lang/NumberFormatException; {:try_start_0 .. :try_end_0} :catch_0

    if-gtz v7, :cond_4

    const/4 v7, 0x1

    :cond_4
    :goto_2
    if-lt v0, v7, :cond_5

    if-gt v0, v6, :cond_5

    const/4 v10, 0x1

    return v10

    :catch_0
    move-exception v4

    const-string/jumbo v10, "Linkify"

    const-string/jumbo v11, "NumberFormatException occured. CSC value is invalid."

    invoke-static {v10, v11}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_2

    :catch_1
    move-exception v3

    const-string/jumbo v10, "Linkify"

    const-string/jumbo v11, "ArrayIndexOutOfBoundsException occured. CSC value is invalid."

    invoke-static {v10, v11}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_2

    :cond_5
    const/4 v10, 0x0

    return v10
.end method


text:
using System;
using Sensus.Shared.UI.UiProperties;
using Syncfusion.SfChart.XForms;

namespace Sensus.Shared.Probes.Context
{
    public abstract class SoundProbe : PollingProbe
    {
        private int _sampleLengthMS;

        [EntryIntegerUiProperty("Sample Length (MS):", true, 5)]
        public int SampleLengthMS
        {
            get { return _sampleLengthMS; }
            set { _sampleLengthMS = value; }
        }

        public sealed override string DisplayName
        {
            get { return "Sound Level"; }
        }

        public override int DefaultPollingSleepDurationMS
        {
            get
            {
                return 60000 * 10; // every 10 minutes
            }
        }

        public sealed override Type DatumType
        {
            get { return typeof(SoundDatum); }
        }

        protected SoundProbe()
        {
            _sampleLengthMS = 5000;
        }

        protected override ChartSeries GetChartSeries()
        {
            return new LineSeries();
        }

        protected override ChartDataPoint GetChartDataPointFromDatum(Datum datum)
        {
            return new ChartDataPoint(datum.Timestamp.LocalDateTime, (datum as SoundDatum).Decibels);
        }

        protected override ChartAxis GetChartPrimaryAxis()
        {
            return new DateTimeAxis
            {
                Title = new ChartAxisTitle
                {
                    Text = "Time"
                }
            };
        }

        protected override RangeAxisBase GetChartSecondaryAxis()
        {
            return new NumericalAxis
            {
                Title = new ChartAxisTitle
                {
                    Text = "Decibels"
                }
            };
        }
    }
}


text:
TARGETS := $(notdir ${SOURCE_DIR}).cdl
ADL := DARPA.camkes

client_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/client/include/*.h))
client_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/client/src/*.c))

canbus_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/include/*.h)) \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/canbus/include/*.h))
canbus_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/canbus/src/*.c))

can_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/can/include/*.h))
can_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/can/src/*.c))

uart_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/uart/include/*.h))
uart_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/uart/src/*.c))

spi_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/spi/include/*.h))
spi_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/spi/src/*.c))

clk_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/clk/include/*.h))
clk_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/clk/src/*.c))

gpio_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/include/*.h)) \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/gpio/include/*.h))
gpio_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/gpio/src/*.c))

timer_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/timer/include/*.h))
timer_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/timer/src/*.c))

gyro_HFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/gyro/include/*.h)) \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/include/*.h))
gyro_CFILES := \
    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/gyro/src/*.c))

#mmc_HFILES := \
#    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/mmc/include/*.h))
#mmc_CFILES := \
#    $(patsubst ${SOURCE_DIR}/%,%,$(wildcard ${SOURCE_DIR}/components/mmc/src/*.c))

include ${PWD}/tools/camkes/camkes.mk


text:
/**
 * @author Nikolay A. Kuznetsov
 */
package java.util.regex;

/**
 * Node accepting substrings in unicode case insensitive manner.
 *
 * @author Nikolay A. Kuznetsov
 */
class UCISequenceSet extends LeafSet {

    private String string = null;

    UCISequenceSet(StringBuffer substring) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < substring.length(); i++) {
            res.append(Character.toLowerCase(Character.toUpperCase(substring
                    .charAt(i))));
        }
        this.string = res.toString();
        this.charCount = res.length();
    }

    public int accepts(int strIndex, CharSequence testString) {
        for (int i = 0; i < string.length(); i++) {
            if (string.charAt(i) != Character.toLowerCase(Character
                    .toUpperCase(testString.charAt(strIndex + i)))) {
                return -1;
            }
        }

        return string.length();

    }

    public String getName() {
        return "UCI sequence: " + string; //$NON-NLS-1$
    }
}


text:
package net.caustic.util;

import static org.junit.Assert.*;

import static net.caustic.util.TestUtils.*;
import net.caustic.util.StringUtils;

import org.junit.Test;

public class StringUtilsTest {
	private static final int repetitions = 200;
	private static final int strLen = 100;

	@Test
	public void testJoinStringArrayString() {
		String[] stringsToJoin = new String[] {
				"the", "quick", "brown", "fox"
		};
		String joinString = " ";

		String joinedString = StringUtils.join(stringsToJoin, joinString);
		assertEquals("Error joining array of strings.", "the quick brown fox", joinedString);
	}
/*
	@Test
	public void testJoinIntArrayString() {
		int[] intsToJoin = new int[] {
				1, 2, 3, 4
		};
		String joinString = "-";

		String joinedString = StringUtils.join(intsToJoin, joinString);
		assertEquals("Error joining array of ints.", "1-2-3-4", joinedString);
	}
*/
	@Test
	public void testTruncate() {
		int originalLength = 1000;
		int truncatedLength = 500;

		assertEquals("Unexpected length.", truncatedLength,
				StringUtils.quoteAndTruncate(randomString(originalLength), truncatedLength).length());
	}

	@Test
	public void testSplit() {
		for(int splitByLength = 1 ; splitByLength < strLen ; splitByLength ++) {
			String splitBy = "";
			for(int i = 0 ; i < splitByLength ; i ++) {
				splitBy += "-";
			}

			String stringToSplit = "";
			String[] componentStrings = new String[repetitions];
			for(int i = 0 ; i < repetitions ; i++) {
				componentStrings[i] = randomString(randomInt(strLen));
				stringToSplit += componentStrings[i] + splitBy; // stuck with trailing splitter, should be extra blank element at end.
			}
			String[] splitString = StringUtils.split(stringToSplit, splitBy);

			assertEquals("String '" + stringToSplit + "' split by '" + splitBy + "' is wrong length", componentStrings.length + 1, splitString.length);
			assertEquals("Missing trailing empty string", "", splitString[splitString.length - 1]);
			for(int i = 0 ; i < componentStrings.length ; i ++) {
				assertEquals(componentStrings[i], splitString[i]);
			}
		}
	}

	@Test
	public void testQuoteString() {
		String quoted = StringUtils.quote(randomString(strLen));
		assertEquals(true, quoted.startsWith(StringUtils.QUOTATION));
		assertEquals(true, quoted.endsWith(StringUtils.QUOTATION));
	}

	@Test
	public void testQuoteInt() {
		String quoted = StringUtils.quote(randomInt(strLen));
		assertEquals(true, quoted.startsWith(StringUtils.QUOTATION));
		assertEquals(true, quoted.endsWith(StringUtils.QUOTATION));
	}

	@Test
	public void testSimpleClassName() {
		Object obj = new Object();
		assertEquals("Object", StringUtils.simpleClassName(obj));
	}

}


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js sbt plugin        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */

package org.scalajs.core.tools.sourcemap

import org.scalajs.core.tools.classpath._

import com.google.debugging.sourcemap._

class SourceMapper(classpath: CompleteClasspath) {

  def map(ste: StackTraceElement, columnNumber: Int): StackTraceElement = {
    val mapped = for {
      sourceMap <- findSourceMap(ste.getFileName)
    } yield map(ste, columnNumber, sourceMap)

    mapped.getOrElse(ste)
  }

  def map(ste: StackTraceElement, columnNumber: Int,
      sourceMap: String): StackTraceElement = {

    val sourceMapConsumer =
      SourceMapConsumerFactory
        .parse(sourceMap)
        .asInstanceOf[SourceMapConsumerV3]

    /* **Attention**
     * - StackTrace positions are 1-based
     * - SourceMapConsumer.getMappingForLine() is 1-based
     */

    val lineNumber = ste.getLineNumber
    val column =
      if (columnNumber == -1) getFirstColumn(sourceMapConsumer, lineNumber)
      else columnNumber

    val originalMapping =
      sourceMapConsumer.getMappingForLine(lineNumber, column)

    if (originalMapping != null) {
      new StackTraceElement(
          ste.getClassName,
          ste.getMethodName,
          originalMapping.getOriginalFile,
          originalMapping.getLineNumber)
    } else ste
  }

  /** both `lineNumber` and the resulting column are 1-based */
  private def getFirstColumn(sourceMapConsumer: SourceMapConsumerV3,
      lineNumber1Based: Int) = {

    /* **Attention**
     * - SourceMapConsumerV3.EntryVisitor is 0-based!!!
     */

    val lineNumber = lineNumber1Based - 1

    var column: Option[Int] = None

    sourceMapConsumer.visitMappings(
      new SourceMapConsumerV3.EntryVisitor {
        def visit(sourceName: String,
          symbolName: String,
          sourceStartPosition: FilePosition,
          startPosition: FilePosition,
          endPosition: FilePosition): Unit =
          if (!column.isDefined && startPosition.getLine == lineNumber)
            column = Some(startPosition.getColumn)
      })

    val column0Based = column.getOrElse(0)
    column0Based + 1
  }

  private def findSourceMap(path: String) = {
    val candidates = classpath.allCode.filter(_.path == path)
    if (candidates.size != 1) None // better no sourcemap than a wrong one
    else candidates.head.sourceMap
  }
}


text:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}

module Views.Components.ComicsList (comicsListView) where

import BasicPrelude

import Text.Blaze.Html5 (Html, toValue, toHtml, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A

import Helpers.SPF (SPFHook(SPFLink))
import Models.Comic (Comic)
import qualified Models.Comic as C
import Routes (RouteUrl(ComicUrl))

comicsListView :: [Comic] -> Html
comicsListView comics =
  H.div ! A.class_ "list-group" $
    mapM_ comicsListItemView comics

comicsListItemView :: Comic -> Html
comicsListItemView comic =
  H.a ! A.href (toValue (ComicUrl (C.id comic)))
      ! A.class_ ("list-group-item " <> toValue SPFLink) $
    H.h4 ! A.class_ "list-group-item-heading" $ toHtml (C.title comic)


text:
Even for small changes, we ask that you please sign the CLA electronically
[here](https://developers.google.com/open-source/cla/individual).
The CLA is necessary because you own the copyright to your changes, even
after your contribution becomes part of our codebase, so we need your permission
to use and distribute your code. You can find more details
[here](https://code.google.com/p/dart/wiki/Contributing).

### Find the right place to change the code

A lot of the code in this repo is either generated automatically, or developed
elsewhere. For example, all elements definitions under `lib/src/paper-*` and
`lib/src/core-*` are downloaded automatically from other repositories using
`bower`.

If you would like to update HTML or Javascript code on a specific element, you
probably need to send a pull request in a different repository. The code for a
specific element lives under a repo of the same name under the [Polymer
organization](https://github.com/Polymer/). For example,
`lib/src/paper-input/paper-input.html` is actually developed on the [paper-input
repo](https://github.com/Polymer/paper-input), if you send the fix there, we
will get it automatically next time we run our update scripts.

In addition, the Dart libraries for each element are generated automatically by
running `tools/update.dart`. Most of the sources of this tool live in our
[core-elements repo](https://github.com/dart-lang/core-elements).


text:
require "http_proxy_from_env/version"
require "http_proxy_from_env/net/http"
require "http_proxy_from_env/open_uri"

module HttpProxyFromEnv
  # Your code goes here...
end


text:
package taijigoldfish.travelexpense;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import taijigoldfish.travelexpense.model.Trip;

public class AbstractFragment extends Fragment {
    protected static final String ARG_TRIP_JSON = "arg_trip_json";
    private static final String TAG = AbstractFragment.class.getName();
    protected ControlListener mListener;

    @BindView(R.id.txtTripTitle)
    TextView txtTripTitle;

    private Trip trip;

    private String tripTitle;

    private List<String> dateStrings;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            String json = getArguments().getString(ARG_TRIP_JSON);
            setTrip(new Gson().fromJson(json, Trip.class));

            this.tripTitle = genTripTitle(this.trip);
            this.dateStrings = Utils.genDateStrings(this.trip);
        }
    }

    public Trip getTrip() {
        return this.trip;
    }

    public void setTrip(Trip trip) {
        this.trip = trip;
    }

    public String getTripTitle() {
        return this.tripTitle;
    }

    public List<String> getDateStrings() {
        return this.dateStrings;
    }

    protected String genTripTitle(final Trip trip) {
        return Utils.getTripTitle(this.getContext(), trip);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            this.mListener = (ControlListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement ControlListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.mListener = null;
    }
}