text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How young people can help fight COVID-19 with code)
[#]: via: (https://opensource.com/article/20/4/covid19-hackathon)
[#]: author: (Melissa Sasi https://opensource.com/users/mesassi)

How young people can help fight COVID-19 with code
======
Youth developers are invited to submit ideas by April 15 to counter the
educational, informational, social, and health challenges uncovered by
the COVID-19 pandemic.
![woman on laptop sitting at the window][1]

More than 91% of students around the world are impacted by school closures due to COVID-19, and most governments have temporarily closed academic institutions. That's nearly [1.6 billion young people in 188 countries][2]. Also, most of the learning platforms available online today aren't practical, engaging, or interactive, and lack true virtual collaboration.

This big and wicked challenge got me thinking about how these circumstances are impacting my children, their friends, and my passions of empowering youth, fostering tech entrepreneurship, and inspiring under-represented communities to find their purpose through building digital skills. These all came together in [CodeTheCurve][3], "a global, virtual hackathon for students, educators, teachers, and the research community to build tech skills, entrepreneurial spirit, and professional competencies to build digital creativity and cooperation to mobilize the world."

We hope you'll want to participate, but you need to act fast: the deadline to submit proposals is April 15.

### My story

The passions mentioned above stem from a deeply personal journey: My children and I are victims of parental kidnapping, and access to the internet and digital literacy are my pathways to being a mother from afar. My children, Zahra (age 13), Zahran (15), and Youmna (18), are safe and healthy, and we are frequently connected. They're living the same life youth all over the world are living these days, trying to social distance and remain in good health while figuring out this school thing (or lack thereof)—only one of my children has access to formal virtual learning during to COVID-19 school closures. The other two, without school-driven online learning options, tend to stay up all night playing Fortnight and making TikTok videos.

I have always been passionate about digital inclusion and empowering the world through computer science, and the effects of COVID-19 have increased my desire to make a difference. About four years ago, I created a non-profit organization, [MentorNations][4], to inspire youth and the world via technology. My non-profit has taught tens of thousands of young people in 12 countries to code. In my work at IBM as a developer advocate, I focus on empowering early-stage entrepreneurs, developers, and students with access to tech skills, professional development, and entrepreneurial thinking. My major focus areas include inspiring students to discover their career potential in enterprise computing while recognizing that we are all ANDs and not ORs.

Teaching the next generation about the power of collaboration, teamwork, problem-solving, and critical thinking that happen through open source code and principles empowers them to be creators and innovators who focus on solving relevant and real-world problems.

Looking through the lens of my children, my non-profit work, my roles within a variety of United Nations Task Forces, and my position as IEEE Chair over the Digital Skills Working Group, I wondered, _**what can I do to make a difference with open source technology?**_ So I reached out to my network, and the world responded in a much bigger way than I had ever imagined.

### CodeTheCurve

In response, we launched UNESCO's [CodeTheCurve][3] hackathon in collaboration with 14 partners, including UN EQUALS, SAP, iHackOnline, Angel Hack, Internet Society, and YPO. Participants are invited to bring their open source ideas to combat the current and future environment and challenges relating to COVID-19. This initiative is centered around youth empowerment, gender inclusion, and making the world a better place for our communities, including for people we may not directly encounter daily.

CodeTheCurve is for anyone above the age of 16. To ensure gender, age, and experience diversity, teams must include a developer or data scientist (early-stage chops are fine); at least one person under the age of 25; and at least one male and one female. The 40 teams selected to participate in CodeTheCurve will have access to more than 80 business and technical mentors (experts!) from around the world to help turn their ideas into reality.

My vision for this hackathon is to train young talent; enable them with free, online resources and access to real people with real answers; and encourage the creation of real-world problem solving in real-time. The results of the hackathon, I hope, will be open source utilities and information that can be used, in some way, to combat COVID-19.

#### Week-long learning, bootcamp, and hacking experience

CodeTheCurve is a three-day virtual hackathon experience guided by expert business and technical mentors. Before the hackathon proper, participants begin with two days of self-paced, online learning from content curated by CodeTheCurve collaborators, followed by a two-day, instructor-led learning journey where the 40 selected teams will collaborate in virtual breakout rooms with activity kits, hands-on computing resources in machine learning, and expert-guided plenary sessions.

#### CodeTheCurve hackathon themes

CodeTheCurve includes three themes:

  * Education
  * Information and data management
  * Current and post-COVID-19 health and social issues

#### Professional development, entrepreneurship, and hands-on open source skills

The 40 teams will be empowered with expert-guided, engaging activities, including the following skill-building opportunities:

  * **Hand-on tech skills**
    * Using Jupyter Notebooks for data science
    * Data protection, privacy, security, and encryption
    * Machine learning and artificial intelligence
    * Architectural diagrams and frameworks
    * Technical roadmaps
  * **Professional development**
    * Design thinking
    * Personal branding
    * Communication skills
    * How not to feel like an imposter
    * Conflict resolution
    * Working in global, virtual teams
    * Media literacy
    * Ethics in machine learning and artificial intelligence
  * **Entrepreneurship**
    * Problem statements
    * Mission and vision statements
    * Value propositions
    * Audience and target markets
    * Business model canvassing
    * Pitch decks
    * Pitch practice

### April 15: CodeTheCurve deadline

Did I mention that the initial application deadline is April 15? Here's the full timeline:

  * Video submission deadline: **April 15**
  * 40 selected teams announced: **April 20**
  * Learning resources for pre-collaboration: **April 20-21**
  * Instructor-led learning: **April 22-23**
  * Hacking: **April 24-26**
  * CodeTheCurve winners announced: **April 30**

#### Prizes. Prizes. Prizes.

Prizes include free access to [IBM LinuxONE Community Cloud][5] for one year, free training courses from SAP, four pitch opportunities at IBM and SAP events, free access to enterprise-grade IBM Z and its machine learning suite for six months, and one-on-one technical and business mentorship for a full year with industry experts.

### How to apply

Interested in applying? Know someone who should apply? Simply [submit a video][6] of your **amazing** open source idea, the problem you're trying to solve, and who you expect to reach.

If you'd like to learn more, here are some other articles about CodeTheCurve:

  * [UN News CodeTheCurve article][7]
  * [UNESCO CodeTheCurve blog][8]
  * [Forbes CodeTheCurve article][9]
  * [IBM CodeTheCurve blog][10]

I cannot wait to see all the amazing open source ideas the world brings our way!

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

via: https://opensource.com/article/20/4/covid19-hackathon

作者:[Melissa Sasi][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/mesassi
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/lenovo-thinkpad-laptop-window-focus.png?itok=g0xPm2kD (young woman working on a laptop)
[2]: https://en.unesco.org/covid19/educationresponse
[3]: https://www.codethecurve.org/
[4]: https://mentornations.org/
[5]: https://developer.ibm.com/linuxone/
[6]: http://ibm.biz/codethecurve-apply
[7]: https://news.un.org/en/story/2020/04/1061142
[8]: http://ibm.biz/unesco-pr
[9]: https://www.forbes.com/sites/danielnewman/2020/04/10/digital-transformation-for-good-shines-as-we-fight-covid-19/#78d51a4c4946
[10]: http://ibm.biz/codethecurve


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
AsyncDiskService (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.util

Class AsyncDiskService

java.lang.Object
  org.apache.hadoop.util.AsyncDiskService

public class AsyncDiskService
extends java.lang.Object

Field Summary

static org.apache.commons.logging.Log
LOG

Constructor Summary

AsyncDiskService(java.lang.String[] volumes)

          Create a AsyncDiskServices with a set of volumes (specified by their
 root directories).

AsyncDiskService(java.lang.String[] volumes,
                 Configuration conf)

          Create a AsyncDiskServices with a set of volumes (specified by their
 root directories).

Method Summary

 boolean
awaitTermination(long milliseconds)

          Wait for the termination of the thread pools.

 void
execute(java.lang.String root,
        java.lang.Runnable task)

          Execute the task sometime in the future, using ThreadPools.

 void
shutdown()

          Gracefully start the shut down of all ThreadPools.

 java.util.List<java.lang.Runnable>
shutdownNow()

          Shut down all ThreadPools immediately.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

LOG

public static final org.apache.commons.logging.Log LOG

Constructor Detail

AsyncDiskService

public AsyncDiskService(java.lang.String[] volumes)
                 throws java.io.IOException

Create a AsyncDiskServices with a set of volumes (specified by their
 root directories).

 The AsyncDiskServices uses one ThreadPool per volume to do the async
 disk operations.

Parameters:
volumes - The roots of the file system volumes.

Throws:

java.io.IOException

AsyncDiskService

public AsyncDiskService(java.lang.String[] volumes,
                        Configuration conf)
                 throws java.io.IOException

Create a AsyncDiskServices with a set of volumes (specified by their
 root directories).

 The AsyncDiskServices uses one ThreadPool per volume to do the async
 disk operations.

Parameters:
volumes - The roots of the file system volumes.
conf - The configuration which determines number of threads per volume

Throws:

java.io.IOException

Method Detail

execute

public void execute(java.lang.String root,
                    java.lang.Runnable task)

Execute the task sometime in the future, using ThreadPools.

shutdown

public void shutdown()

Gracefully start the shut down of all ThreadPools.

awaitTermination

public boolean awaitTermination(long milliseconds)
                         throws java.lang.InterruptedException

Wait for the termination of the thread pools.

Parameters:
milliseconds - The number of milliseconds to wait

Returns:
true if all thread pools are terminated without time limit

Throws:

java.lang.InterruptedException

shutdownNow

public java.util.List<java.lang.Runnable> shutdownNow()

Shut down all ThreadPools immediately.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

This release is based on the Facebook's version of Hadoop.
Copyright © 2009 The Apache Software Foundation.

redpajama_set_name: RedPajamaGithub


text:
#include <modules/webbrowser/webbrowsermodule.h>

#include <modules/webbrowser/include/browserinstance.h>
#include <modules/webbrowser/include/cefhost.h>
#include <modules/webbrowser/include/eventhandler.h>
#include <modules/webbrowser/include/screenspacebrowser.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/util/factorymanager.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/misc/profiling.h>
#include <filesystem>

namespace {
    constexpr std::string_view _loggerCat = "WebBrowser";

    #ifdef _MSC_VER
        constexpr std::string_view SubprocessPath = "OpenSpace_Helper.exe";
    #elif defined(__APPLE__)
        constexpr std::string_view SubprocessPath =
            "../Frameworks/OpenSpace Helper.app/Contents/MacOS/OpenSpace_Helper";
    #else
        constexpr std::string_view SubprocessPath = "OpenSpace_Helper";
    #endif

    constexpr openspace::properties::Property::PropertyInfo
        UpdateBrowserBetweenRenderablesInfo =
    {
        "UpdateBrowserBetweenRenderables",
        "Update Browser Between Renderables",
        "Run the message loop of the browser between calls to render individual "
        "renderables. When disabled, the browser message loop only runs "
        "once per frame"
    };

    constexpr openspace::properties::Property::PropertyInfo BrowserUpdateIntervalInfo = {
        "BrowserUpdateInterval",
        "Browser Update Interval",
        "The time in microseconds between running the message loop of the browser. "
        "Only used if UpdateBrowserBetweenRenderables is true"
    };
} // namespace

namespace openspace {

WebBrowserModule::WebBrowserModule()
    : OpenSpaceModule(WebBrowserModule::Name)
    , _updateBrowserBetweenRenderables(UpdateBrowserBetweenRenderablesInfo, true)
    , _browserUpdateInterval(BrowserUpdateIntervalInfo, 1.f, 1.0f, 1000.f)
    , _eventHandler(new EventHandler)
{
    global::callback::deinitialize->emplace_back([this]() {
        ZoneScopedN("WebBrowserModule")

        deinitialize();
    });

    _browserUpdateInterval.onChange([this]() {
        webbrowser::interval = std::chrono::microseconds(
            static_cast<long long>(_browserUpdateInterval)
        );
    });

    _updateBrowserBetweenRenderables.onChange([this]() {
        if (_updateBrowserBetweenRenderables && !_browsers.empty()) {
            global::callback::webBrowserPerformanceHotfix = webbrowser::update;
        }
        else {
            global::callback::webBrowserPerformanceHotfix = nullptr;
        }
    });

    addProperty(_updateBrowserBetweenRenderables);
    addProperty(_browserUpdateInterval);
}

void WebBrowserModule::internalDeinitialize() {
    ZoneScoped

    if (!_enabled) {
        return;
    }

    _eventHandler->resetBrowserInstance();

    bool forceBrowserShutdown = true;
    for (BrowserInstance* browser : _browsers) {
        browser->close(forceBrowserShutdown);
    }
}

std::filesystem::path WebBrowserModule::findHelperExecutable() {
    std::filesystem::path execLocation = absPath("${BIN}/" + std::string(SubprocessPath));
    if (!std::filesystem::is_regular_file(execLocation)) {
        LERROR(fmt::format(
            "Could not find web helper executable at location: {}" , execLocation
        ));
    }
    return execLocation;
}

void WebBrowserModule::internalInitialize(const ghoul::Dictionary& dictionary) {
    ZoneScoped

    if (dictionary.hasValue<bool>("WebHelperLocation")) {
        _webHelperLocation = absPath(dictionary.value<std::string>("WebHelperLocation"));
    }
    else {
        _webHelperLocation = findHelperExecutable();
    }

    if (dictionary.hasValue<bool>("Enabled")) {
        _enabled = dictionary.value<bool>("Enabled");
    }

    LDEBUG(fmt::format("CEF using web helper executable: {}", _webHelperLocation));
    _cefHost = std::make_unique<CefHost>(_webHelperLocation.string());
    LDEBUG("Starting CEF... done");

    if (dictionary.hasValue<bool>(UpdateBrowserBetweenRenderablesInfo.identifier)) {
        _updateBrowserBetweenRenderables =
            dictionary.value<bool>(UpdateBrowserBetweenRenderablesInfo.identifier);
    }

    if (dictionary.hasValue<double>(BrowserUpdateIntervalInfo.identifier)) {
        _browserUpdateInterval = static_cast<float>(
            dictionary.value<double>(BrowserUpdateIntervalInfo.identifier)
        );
    }

    _eventHandler->initialize();

    // register ScreenSpaceBrowser
    ghoul::TemplateFactory<ScreenSpaceRenderable>* fScreenSpaceRenderable =
        FactoryManager::ref().factory<ScreenSpaceRenderable>();
    ghoul_assert(fScreenSpaceRenderable, "ScreenSpaceRenderable factory was not created");
    fScreenSpaceRenderable->registerClass<ScreenSpaceBrowser>("ScreenSpaceBrowser");
}

void WebBrowserModule::addBrowser(BrowserInstance* browser) {
    ZoneScoped

    if (_enabled) {
        _browsers.push_back(browser);
        if (_updateBrowserBetweenRenderables) {
            global::callback::webBrowserPerformanceHotfix = webbrowser::update;
        }
    }
}

void WebBrowserModule::removeBrowser(BrowserInstance* browser) {
    if (!_enabled) {
        return;
    }
    const auto p = std::find(_browsers.begin(), _browsers.end(), browser);
    if (p != _browsers.end()) {
        _browsers.erase(p);
    }
    else {
        LWARNING("Could not find browser in list of browsers");
    }

    if (_browsers.empty()) {
        global::callback::webBrowserPerformanceHotfix = nullptr;
    }

    LDEBUG(fmt::format("Number of browsers stored: {}", _browsers.size()));
}

void WebBrowserModule::attachEventHandler(BrowserInstance* browserInstance) {
    if (_enabled) {
        _eventHandler->setBrowserInstance(browserInstance);
    }
}

void WebBrowserModule::detachEventHandler() {
    if (_enabled) {
        _eventHandler->setBrowserInstance(nullptr);
    }
}

bool WebBrowserModule::isEnabled() const {
    return _enabled;
}

/// Logic for the webbrowser performance hotfix, described in globalscallbacks.h
namespace webbrowser {

/**
 * The time interval to describe how often the CEF message loop needs to be pumped to work
 * properly. A value of 10000 us updates CEF a 100 times per second which is enough for
 * fluid interaction without wasting resources
 */
std::chrono::microseconds interval = std::chrono::microseconds(10000);
std::chrono::time_point<std::chrono::high_resolution_clock> latestCall;
CefHost* cefHost = nullptr;

void update() {
    const std::chrono::time_point<std::chrono::high_resolution_clock> timeBefore =
        std::chrono::high_resolution_clock::now();

    std::chrono::microseconds duration =
        std::chrono::duration_cast<std::chrono::microseconds>(timeBefore - latestCall);

    if (duration > interval) {
        cefHost->doMessageLoopWork();

        const std::chrono::time_point<std::chrono::high_resolution_clock> timeAfter =
            std::chrono::high_resolution_clock::now();

        latestCall = timeAfter;
    }
}

} // namespace webbrowser

} // namespace openspace


text:
package runtime

import (
	"context"
	"net/http"
	"testing"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)

func TestResponseUnmarshalXML(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	// include UTF8 BOM
	srv.SetResponse(mock.WithBody([]byte("\xef\xbb\xbf<testXML><SomeInt>1</SomeInt><SomeString>s</SomeString></testXML>")))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	var tx testXML
	if err := UnmarshalAsXML(resp, &tx); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
	if tx.SomeInt != 1 || tx.SomeString != "s" {
		t.Fatal("unexpected value")
	}
}

func TestResponseFailureStatusCode(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithStatusCode(http.StatusForbidden))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
}

func TestResponseUnmarshalJSON(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte(`{ "someInt": 1, "someString": "s" }`)))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	var tx testJSON
	if err := UnmarshalAsJSON(resp, &tx); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
	if tx.SomeInt != 1 || tx.SomeString != "s" {
		t.Fatal("unexpected value")
	}
}

func TestResponseUnmarshalJSONskipDownload(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte(`{ "someInt": 1, "someString": "s" }`)))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	SkipBodyDownload(req)
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	var tx testJSON
	if err := UnmarshalAsJSON(resp, &tx); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
	if tx.SomeInt != 1 || tx.SomeString != "s" {
		t.Fatal("unexpected value")
	}
}

func TestResponseUnmarshalJSONNoBody(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte{}))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	if err := UnmarshalAsJSON(resp, nil); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
}

func TestResponseUnmarshalXMLNoBody(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte{}))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	if err := UnmarshalAsXML(resp, nil); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
}

func TestResponseUnmarshalAsByteArrayURLFormat(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte(`"YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw"`)))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	var ba []byte
	if err := UnmarshalAsByteArray(resp, &ba, Base64URLFormat); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
	if string(ba) != "a string that gets encoded with base64url" {
		t.Fatalf("bad payload, got %s", string(ba))
	}
}

func TestResponseUnmarshalAsByteArrayStdFormat(t *testing.T) {
	srv, close := mock.NewServer()
	defer close()
	srv.SetResponse(mock.WithBody([]byte(`"YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw="`)))
	pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
	req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	resp, err := pl.Do(req)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !HasStatusCode(resp, http.StatusOK) {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}
	var ba []byte
	if err := UnmarshalAsByteArray(resp, &ba, Base64StdFormat); err != nil {
		t.Fatalf("unexpected error unmarshalling: %v", err)
	}
	if string(ba) != "a string that gets encoded with base64url" {
		t.Fatalf("bad payload, got %s", string(ba))
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/ServerJavaProjetDrone.iml" filepath="$PROJECT_DIR$/ServerJavaProjetDrone.iml" />
    </modules>
  </component>
</project>


text:
'use strict';

// Load requirements
const path = require('path'),
      fs = require('fs'),
      os = require('os');

// Load our modules
const utils = __require('libs/utils'),
      config = require('../config')();

module.exports = function(answers) {

  // Variables
  let file = path.join(config.directories.settings, 'settings.json');

  // Build the base settings object
  let settings = {
    language: answers.language,
    platform: {},
    server: {
      enable: true,
      port: 3001,
      address: '0.0.0.0'
    },
    video: {
      formats: answers.formats
    }
  };

  // Add os specific settings
  settings.platform[os.platform()] = {
    root: answers.root,
    temp: answers.temp,
    directories: {
      show: answers.show,
      movie: answers.movie
    }
  };

  // Write the settings object
  fs.writeFileSync(file, JSON.stringify(settings, null, 4));
};


text:
<?php
namespace Wandu\Migrator\Commands;

use Wandu\Console\Command;
use Wandu\Migrator\Migrator;

class CreateCommand extends Command
{
    /** @var string */
    protected $description = 'Create a migration file.';

    /** @var array */
    protected $arguments = [
        'name' => 'the name for the migration',
    ];

    /** @var \Wandu\Migrator\Migrator */
    protected $migrator;

    public function __construct(Migrator $migrator)
    {
        $this->migrator = $migrator;
    }

    public function execute()
    {
        $name = $this->input->getArgument('name');
        $filePath = $this->migrator->createTemplate($name);
        $this->output->writeln(
            '<info>create</info> .' . str_replace(getcwd(), '', $filePath)
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using I8Beef.Denon.Commands;
using I8Beef.Denon.Events;
using Timer = System.Timers.Timer;

namespace I8Beef.Denon.HttpClient
{
    /// <summary>
    /// HTTP implementation of Denon <see cref="IClient"/>.
    /// </summary>
    public class Client : IClient
    {
        private readonly IDenonHttpClient _httpClient;
        private readonly int _refreshInterval;

        private bool _disposed;
        private MainStatus _status;
        private Timer _refresh;

        /// <summary>
        /// Initializes a new instance of the <see cref="Client"/> class.
        /// </summary>
        /// <param name="host">Host address for HTTP client.</param>
        /// <param name="refreshInterval">Refresh interval for client.</param>
        public Client(string host, int refreshInterval = 30000)
        {
            _refreshInterval = refreshInterval;
            _httpClient = new DenonHttpClient(host);
            _httpClient.MessageReceived += MessageReceived;
            _httpClient.MessageSent += MessageSent;
        }

        /// <inheritdoc/>
        public event EventHandler<ErrorEventArgs> Error;

        /// <inheritdoc/>
        public event EventHandler<MessageReceivedEventArgs> MessageReceived;

        /// <inheritdoc/>
        public event EventHandler<MessageSentEventArgs> MessageSent;

        /// <inheritdoc/>
        public event EventHandler<CommandEventArgs> EventReceived;

        /// <inheritdoc/>
        public Task SendCommandAsync(Command command, CancellationToken cancellationToken = default)
        {
            return _httpClient.FireAndForgetAsync(command, cancellationToken);
        }

        /// <inheritdoc/>
        public async Task<Command> SendQueryAsync(Command command, CancellationToken cancellationToken = default)
        {
            if (_status == null)
                await RefreshStatusAsync(false).ConfigureAwait(false);

            if (command is PowerCommand)
                return new PowerCommand { Value = _status.Power ? "ON" : "OFF" };

            if (command is VolumeCommand)
                return new VolumeCommand { Value = _status.Volume.ToString() };

            if (command is MuteCommand)
                return new MuteCommand { Value = _status.Mute ? "ON" : "OFF" };

            if (command is InputCommand)
                return new InputCommand { Value = _status.Input };

            if (command is SurroundModeCommand)
                return new SurroundModeCommand { Value = _status.SurroundMode };

            /*
            if (command is TunerFrequencyCommand)
                return new TunerFrequencyCommand { Value = _status.Volume.ToString() };

            if (command is TunerModeCommand)
                return new TunerModeCommand { Value = _status.Volume.ToString() };
            */

            if (command is ZoneCommand zoneCommand)
            {
                if (command is ZonePowerCommand)
                    return new ZonePowerCommand { ZoneId = zoneCommand.ZoneId, Value = _status.SecondaryZoneStatus[$"ZONE{zoneCommand.ZoneId}"].Power ? "ON" : "OFF" };

                if (command is ZoneVolumeCommand)
                    return new ZoneVolumeCommand { ZoneId = zoneCommand.ZoneId, Value = _status.SecondaryZoneStatus[$"ZONE{zoneCommand.ZoneId}"].Volume.ToString() };

                if (command is ZoneMuteCommand)
                    return new ZoneMuteCommand { ZoneId = zoneCommand.ZoneId, Value = _status.SecondaryZoneStatus[$"ZONE{zoneCommand.ZoneId}"].Mute ? "ON" : "OFF" };

                if (command is ZoneInputCommand)
                    return new ZoneInputCommand { ZoneId = zoneCommand.ZoneId, Value = _status.SecondaryZoneStatus[$"ZONE{zoneCommand.ZoneId}"].Input };
            }

            return null;
        }

        #region Connection management

        /// <summary>
        /// Connect to Denon.
        /// </summary>
        public void Connect()
        {
            // Enable refresh
            if (_refresh != null)
                _refresh.Dispose();

            _refresh = new Timer();
            _refresh.Elapsed += RefreshAsync;
            _refresh.Interval = _refreshInterval;
            _refresh.Start();
        }

        /// <summary>
        /// Allows for explicit closing of session.
        /// </summary>
        public void Close()
        {
            Dispose();
        }

        /// <summary>
        /// Heartbeat ping. Failure will result in the heartbeat being stopped, which will
        /// make any future calls throw an exception as the heartbeat indicator will be disabled.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e"><see cref="ElapsedEventArgs"/>.</param>
        private async void RefreshAsync(object sender, ElapsedEventArgs e)
        {
            try
            {
                await RefreshStatusAsync(true).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
                Timer timer = (Timer)sender;
                timer.Stop();
            }
        }

        /// <summary>
        /// Refreshes the current Denon status.
        /// </summary>
        /// <param name="publishChanges">Indiactes if changes should be published or not.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task RefreshStatusAsync(bool publishChanges = false)
        {
            // Make all of the calls to get current status
            var status = new MainStatus();

            var mainZoneStatusTask = _httpClient.GetDenonMainZoneStatusAsync();
            var secondaryZoneStatusTask = _httpClient.GetAllDenonSecondaryZonesStatusAsync(1);
            await Task.WhenAll(mainZoneStatusTask, secondaryZoneStatusTask).ConfigureAwait(false);

            var mainZoneStatus = await mainZoneStatusTask.ConfigureAwait(false);
            var secondaryZoneStatus = await secondaryZoneStatusTask.ConfigureAwait(false);

            status.Power = mainZoneStatus.Power.Value.ToUpper() == "ON";
            status.Volume = 80 + decimal.Parse(mainZoneStatus.MasterVolume.Value);
            status.Mute = mainZoneStatus.Mute.Value.ToUpper() == "ON";
            status.Input = mainZoneStatus.InputFuncSelect.Value;
            status.SurroundMode = mainZoneStatus.SurrMode.Value;

            foreach (var zone in secondaryZoneStatus)
            {
                var statusLite = new StatusLite
                {
                    Power = zone.Value.Power.Value.ToUpper() == "ON",
                    Volume = 80 + decimal.Parse(zone.Value.MasterVolume.Value),
                    Mute = zone.Value.Mute.Value.ToUpper() == "ON",
                    Input = zone.Value.InputFuncSelect.Value
                };
                status.SecondaryZoneStatus.Add($"ZONE{zone.Key}", statusLite);
            }

            // Initialize state
            if (_status == null)
                _status = status;

            // Compare to current cached status
            var updates = CompareStatusObjects(_status, status);

            // If updated, publish changes
            if (publishChanges && updates.Count > 0)
            {
                foreach (var update in updates)
                {
                    EventReceived?.Invoke(this, new CommandEventArgs(update));
                }

                _status = status;
            }
        }

        /// <summary>
        /// Compares twomaster state objects.
        /// </summary>
        /// <param name="status1">First status.</param>
        /// <param name="status2">Second status.</param>
        /// <returns>List of changes.</returns>
        private IList<Command> CompareStatusObjects(MainStatus status1, MainStatus status2)
        {
            var updates = new List<Command>();

            // Power: PW
            if (status1.Power != status2.Power)
                updates.Add(new PowerCommand { Value = status2.Power ? "ON" : "OFF" });

            // Volume: MV
            if (status1.Volume != status2.Volume)
                updates.Add(new VolumeCommand { Value = status2.Volume.ToString() });

            // Mute: MU
            if (status1.Mute != status2.Mute)
                updates.Add(new MuteCommand { Value = status2.Mute ? "ON" : "OFF" });

            // Input: SI
            if (status1.Input != status2.Input)
                updates.Add(new InputCommand { Value = status2.Input });

            // Surround mode: MS
            if (status1.SurroundMode != status2.SurroundMode)
                updates.Add(new SurroundModeCommand { Value = status2.SurroundMode });

            foreach (var zone in status1.SecondaryZoneStatus)
            {
                var zoneNumber = int.Parse(zone.Key.Substring(4));

                // Zone power: Z#
                if (status1.SecondaryZoneStatus[zone.Key].Power != status2.SecondaryZoneStatus[zone.Key].Power)
                    updates.Add(new ZonePowerCommand { ZoneId = zoneNumber, Value = status2.SecondaryZoneStatus[zone.Key].Power ? "ON" : "OFF" });

                // Zone input: Z#
                if (status1.SecondaryZoneStatus[zone.Key].Input != status2.SecondaryZoneStatus[zone.Key].Input)
                    updates.Add(new ZoneInputCommand { ZoneId = zoneNumber, Value = status2.SecondaryZoneStatus[zone.Key].Input });

                // Zone volume: Z#
                if (status1.SecondaryZoneStatus[zone.Key].Volume != status2.SecondaryZoneStatus[zone.Key].Volume)
                    updates.Add(new ZoneVolumeCommand { ZoneId = zoneNumber, Value = status2.SecondaryZoneStatus[zone.Key].Volume.ToString() });

                // Zone input: Z#MU
                if (status1.SecondaryZoneStatus[zone.Key].Mute != status2.SecondaryZoneStatus[zone.Key].Mute)
                    updates.Add(new ZoneMuteCommand { ZoneId = zoneNumber, Value = status2.SecondaryZoneStatus[zone.Key].Mute ? "ON" : "OFF" });
            }

            return updates;
        }

        #endregion

        #region IDisposable implementation

        /// <summary>
        /// Releases all resources used by the current instance of the XmppIm class.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        /// Releases all resources used by the current instance of the XmppIm class, optionally disposing of managed resource.
        /// </summary>
        /// <param name="disposing">true to dispose of managed resources, otherwise false.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                // Get rid of managed resources.
                if (disposing)
                {
                    // Kill heartbeat
                    if (_refresh != null)
                    {
                        _refresh.Stop();
                        _refresh.Dispose();
                    }
                }

                // Indicate that the instance has been disposed.
                _disposed = true;
            }
        }

        #endregion
    }
}


text:
import unittest

class Test_2_():  # [test description]

    def test_(self):
        pass

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


text:
.class public final Landroid/R$dimen;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "dimen"
.end annotation

# static fields
.field public static final accessibility_touch_slop:I = 0x105006b

.field public static final action_bar_default_height:I = 0x105003a

.field public static final action_bar_icon_vertical_padding:I = 0x105003b

.field public static final action_bar_stacked_max_height:I = 0x1050053

.field public static final action_bar_stacked_tab_max_width:I = 0x1050054

.field public static final action_bar_subtitle_bottom_margin:I = 0x105003f

.field public static final action_bar_subtitle_text_size:I = 0x105003d

.field public static final action_bar_subtitle_top_margin:I = 0x105003e

.field public static final action_bar_title_text_size:I = 0x105003c

.field public static final action_button_min_width:I = 0x1050052

.field public static final activity_chooser_popup_min_width:I = 0x1050047

.field public static final alert_dialog_button_bar_height:I = 0x1050039

.field public static final alert_dialog_title_height:I = 0x1050038

.field public static final app_icon_size:I = 0x1050000

.field public static final config_minScalingSpan:I = 0x1050009

.field public static final config_minScalingTouchMajor:I = 0x105000a

.field public static final config_prefDialogWidth:I = 0x1050007

.field public static final config_viewConfigurationTouchSlop:I = 0x1050008

.field public static final default_app_widget_padding_bottom:I = 0x1050051

.field public static final default_app_widget_padding_left:I = 0x105004e

.field public static final default_app_widget_padding_right:I = 0x1050050

.field public static final default_app_widget_padding_top:I = 0x105004f

.field public static final default_gap:I = 0x1050048

.field public static final dialog_fixed_height_major:I = 0x105002f

.field public static final dialog_fixed_height_minor:I = 0x1050030

.field public static final dialog_fixed_width_major:I = 0x105002d

.field public static final dialog_fixed_width_minor:I = 0x105002e

.field public static final dialog_min_width_major:I = 0x1050003

.field public static final dialog_min_width_minor:I = 0x1050004

.field public static final dropdownitem_icon_width:I = 0x105004b

.field public static final dropdownitem_text_padding_left:I = 0x1050049

.field public static final dropdownitem_text_padding_right:I = 0x105004a

.field public static final face_unlock_height:I = 0x1050046

.field public static final fastscroll_overlay_size:I = 0x1050015

.field public static final fastscroll_thumb_height:I = 0x1050017

.field public static final fastscroll_thumb_width:I = 0x1050016

.field public static final glowpadview_glow_radius:I = 0x1050020

.field public static final glowpadview_inner_radius:I = 0x1050022

.field public static final glowpadview_snap_margin:I = 0x1050021

.field public static final glowpadview_target_placement_radius:I = 0x105001f

.field public static final keyguard_avatar_frame_shadow_radius:I = 0x1050071

.field public static final keyguard_avatar_frame_stroke_width:I = 0x1050070

.field public static final keyguard_avatar_name_size:I = 0x1050073

.field public static final keyguard_avatar_size:I = 0x1050072

.field public static final keyguard_lockscreen_clock_font_size:I = 0x1050040

.field public static final keyguard_lockscreen_outerring_diameter:I = 0x105001e

.field public static final keyguard_lockscreen_pin_margin_left:I = 0x1050045

.field public static final keyguard_lockscreen_status_line_clockfont_bottom_margin:I = 0x1050044

.field public static final keyguard_lockscreen_status_line_clockfont_top_margin:I = 0x1050043

.field public static final keyguard_lockscreen_status_line_font_right_margin:I = 0x1050042

.field public static final keyguard_lockscreen_status_line_font_size:I = 0x1050041

.field public static final keyguard_muliuser_selector_margin:I = 0x105006f

.field public static final keyguard_pattern_unlock_clock_font_size:I = 0x1050079

.field public static final keyguard_pattern_unlock_status_line_font_size:I = 0x105007a

.field public static final keyguard_security_height:I = 0x105006d

.field public static final keyguard_security_view_margin:I = 0x105006e

.field public static final keyguard_security_width:I = 0x105006c

.field public static final kg_clock_top_margin:I = 0x1050060

.field public static final kg_edge_swipe_region_size:I = 0x1050074

.field public static final kg_emergency_button_shift:I = 0x1050077

.field public static final kg_key_horizontal_gap:I = 0x1050061

.field public static final kg_key_vertical_gap:I = 0x1050062

.field public static final kg_pin_key_height:I = 0x1050063

.field public static final kg_runway_lights_height:I = 0x1050065

.field public static final kg_runway_lights_top_margin:I = 0x105006a

.field public static final kg_runway_lights_vertical_padding:I = 0x1050066

.field public static final kg_secure_padding_height:I = 0x1050064

.field public static final kg_security_panel_height:I = 0x1050058

.field public static final kg_security_view_height:I = 0x1050059

.field public static final kg_small_widget_height:I = 0x1050076

.field public static final kg_squashed_layout_threshold:I = 0x1050075

.field public static final kg_status_clock_font_size:I = 0x105005c

.field public static final kg_status_date_font_size:I = 0x105005d

.field public static final kg_status_line_font_right_margin:I = 0x105005f

.field public static final kg_status_line_font_size:I = 0x105005e

.field public static final kg_widget_pager_bottom_padding:I = 0x1050069

.field public static final kg_widget_pager_horizontal_padding:I = 0x1050067

.field public static final kg_widget_pager_top_padding:I = 0x1050068

.field public static final kg_widget_view_height:I = 0x105005b

.field public static final kg_widget_view_width:I = 0x105005a

.field public static final min_xlarge_screen_width:I = 0x1050018

.field public static final navigation_bar_height:I = 0x105000d

.field public static final navigation_bar_height_landscape:I = 0x105000e

.field public static final navigation_bar_height_portrait:I = 0x105007b

.field public static final navigation_bar_width:I = 0x105000f

.field public static final notification_large_icon_height:I = 0x1050006

.field public static final notification_large_icon_width:I = 0x1050005

.field public static final notification_subtext_size:I = 0x1050057

.field public static final notification_text_size:I = 0x1050055

.field public static final notification_title_text_size:I = 0x1050056

.field public static final password_keyboard_height:I = 0x1050078

.field public static final password_keyboard_horizontalGap:I = 0x105001c

.field public static final password_keyboard_key_height_alpha:I = 0x1050019

.field public static final password_keyboard_key_height_numeric:I = 0x105001a

.field public static final password_keyboard_spacebar_vertical_correction:I = 0x105001b

.field public static final password_keyboard_verticalGap:I = 0x105001d

.field public static final preference_breadcrumb_paddingLeft:I = 0x105002a

.field public static final preference_breadcrumb_paddingRight:I = 0x105002b

.field public static final preference_child_padding_side:I = 0x1050035

.field public static final preference_fragment_padding_bottom:I = 0x1050028

.field public static final preference_fragment_padding_side:I = 0x1050029

.field public static final preference_icon_minWidth:I = 0x105002c

.field public static final preference_item_padding_inner:I = 0x1050034

.field public static final preference_item_padding_side:I = 0x1050033

.field public static final preference_screen_bottom_margin:I = 0x1050026

.field public static final preference_screen_header_padding_side:I = 0x1050032

.field public static final preference_screen_header_vertical_padding:I = 0x1050031

.field public static final preference_screen_side_margin:I = 0x1050023

.field public static final preference_screen_side_margin_negative:I = 0x1050024

.field public static final preference_screen_top_margin:I = 0x1050025

.field public static final preference_widget_width:I = 0x1050027

.field public static final search_view_preferred_width:I = 0x1050037

.field public static final search_view_text_min_width:I = 0x1050036

.field public static final status_bar_content_number_size:I = 0x1050011

.field public static final status_bar_edge_ignore:I = 0x1050014

.field public static final status_bar_height:I = 0x105000c

.field public static final status_bar_icon_size:I = 0x1050010

.field public static final system_bar_height:I = 0x1050012

.field public static final system_bar_icon_size:I = 0x1050013

.field public static final textview_error_popup_default_width:I = 0x105004c

.field public static final thumbnail_height:I = 0x1050001

.field public static final thumbnail_width:I = 0x1050002

.field public static final toast_y_offset:I = 0x105000b

.field public static final volume_panel_top:I = 0x105004d

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

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

    return-void
.end method


text:
title:  "Jony Ive: The Genius Behind Apple's Greatest Products"
author: "Wojciech Adam Koszek"
description: >
  Jony Ive is someone who I, as a amateur designer, envy. And the design
  world envies. It was cool to learn more about him in a structured form. If
  you're a design junkie, you'll like this one.
address: "Menlo Park, CA"
klayout: book
tags:
- books
categories: books
read:	2015-11-03
ads:
-
spellcheck-allow:
-
---


text:
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), "..", "lib")

require "rspec"
require "her"

# Require everything in `spec/support`
Dir[File.expand_path("../../spec/support/**/*.rb", __FILE__)].map(&method(:require))

# Remove ActiveModel deprecation message
I18n.enforce_available_locales = false

RSpec.configure do |config|
  config.include Her::Testing::Macros::ModelMacros
  config.include Her::Testing::Macros::RequestMacros

  config.before :each do
    @spawned_models = []
  end

  config.after :each do
    @spawned_models.each do |model|
      Object.instance_eval { remove_const model } if Object.const_defined?(model)
    end
  end
end


text:
import fn from '../../getDecade/index'
import convertToFP from '../_lib/convertToFP/index'

export default convertToFP(fn, 1)


text:
import {LitElement, html, css} from 'lit';
import {customElement, property} from 'lit/decorators.js';

/**
 * A button with lit.dev styling.
 *
 * If an svg element is slotted as the first child, its size and margin is set
 * automatically.
 */
@customElement('litdev-icon-button')
export class LitDevIconButton extends LitElement {
  /**
   * Whether this button is disabled.
   */
  @property({type: Boolean, reflect: true})
  disabled = false;

  static override styles = css`
    :host {
      border: 1px solid currentcolor;
      box-sizing: border-box;
      cursor: pointer;
      display: inline-block;
      font-family: 'Open Sans', sans-serif;
      font-size: 16px;
    }

    :host([disabled]) {
      opacity: 0.5;
      pointer-events: none;
    }

    :host(:hover) {
      background-color: rgba(0, 0, 0, 0.25);
    }

    button {
      align-items: center;
      background: transparent;
      border: none;
      color: inherit;
      cursor: inherit;
      display: flex;
      font-family: inherit;
      font-size: inherit;
      margin: 0;
      padding: 5px 8px;
    }

    slot {
      display: flex;
      align-items: center;
    }

    ::slotted(svg:first-child) {
      height: 1.5em;
      margin-right: 1em;
      width: 1.5em;
    }
  `;

  override render() {
    return html`
      <button ?disabled=${this.disabled}>
        <slot></slot>
      </button>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'litdev-icon-button': LitDevIconButton;
  }
}


text:
package io.reflectoring.staticdata;

import org.springframework.boot.context.properties.ConstructorBinding;

@ConstructorBinding
class Quote {

    private final String text;
    private final String author;

    Quote(String text, String author) {
        this.text = text;
        this.author = author;
    }

    String getText() {
        return text;
    }

    String getAuthor() {
        return author;
    }

}


text:
    <form name="changePasswordForm" ng-submit="changePassword()" class="form-horizontal" >
        <fieldset>
            <legend>Change Password</legend>

                Email

                    <input ng-model="oldPassword" class="form-control" id="oldPassword" placeholder="Old Password" type="password">

                New Password

                    <input ng-model="newPassword" class="form-control" id="newPassword" placeholder="New Password" type="password">

                New Password

                    <input ng-model="confirmPassword" class="form-control" id="confirmPassword" placeholder="Confirm Password" type="password">

                    <button type="reset" class="btn btn-default">Cancel</button>
                    <button type="submit" class="btn btn-primary">Submit</button>

        </fieldset>
    </form>


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

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

	<title>Friendly</title>

Welcome to Friendly!

Place install instructions right here.


text:
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;

public class Data {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Locale locale = new Locale("pt","BR");

		GregorianCalendar calendar = new GregorianCalendar();

		SimpleDateFormat formatador = new SimpleDateFormat("dd' de 'MMMMM' de 'yyyy' - 'HH':'mm'h'",locale);

		System.out.println(formatador.format(calendar.getTime()));

	}

}


text:
jq(function () {
    jq("#generatedTimePeriod").on("change", function () {
        var val = jq(this).val();
        switch (val) {
            case "week":
                jq("#month").addClass("display-none");
                jq("#week").removeClass("display-none");
                break;
            case "month":
                jq("#week").addClass("display-none");
                jq("#month").removeClass("display-none");
                break;
            default:
                jq("#week, #month").addClass("display-none");
        }
    });
})


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.messages;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.components.browser_ui.widget.BoundedLinearLayout;
import org.chromium.components.browser_ui.widget.gesture.SwipeGestureListener;
import org.chromium.components.browser_ui.widget.gesture.SwipeGestureListener.SwipeHandler;
import org.chromium.components.browser_ui.widget.listmenu.BasicListMenu;
import org.chromium.components.browser_ui.widget.listmenu.ListMenu;
import org.chromium.components.browser_ui.widget.listmenu.ListMenuButton;
import org.chromium.components.browser_ui.widget.listmenu.ListMenuButton.PopupMenuShownListener;
import org.chromium.components.browser_ui.widget.listmenu.ListMenuButtonDelegate;
import org.chromium.components.browser_ui.widget.listmenu.ListMenuItemProperties;
import org.chromium.ui.base.ViewUtils;
import org.chromium.ui.modelutil.MVCListAdapter;
import org.chromium.ui.modelutil.PropertyModel;

/**
 * View representing the message banner.
 */
public class MessageBannerView extends BoundedLinearLayout {
    private ImageView mIconView;
    private TextView mTitle;
    private TextView mDescription;
    private TextView mPrimaryButton;
    private ListMenuButton mSecondaryButton;
    private View mDivider;
    private String mSecondaryButtonMenuText;
    private Runnable mSecondaryActionCallback;
    private SwipeGestureListener mSwipeGestureDetector;
    private Runnable mOnTitleChanged;
    private int mCornerRadius = -1;
    private PopupMenuShownListener mPopupMenuShownListener;

    public MessageBannerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mTitle = findViewById(R.id.message_title);
        mDescription = findViewById(R.id.message_description);
        mPrimaryButton = findViewById(R.id.message_primary_button);
        mIconView = findViewById(R.id.message_icon);
        mSecondaryButton = findViewById(R.id.message_secondary_button);
        mDivider = findViewById(R.id.message_divider);
        mSecondaryButton.setOnClickListener((View v) -> { handleSecondaryButtonClick(); });
    }

    void setTitle(String title) {
        mTitle.setText(title);
        if (mOnTitleChanged != null) mOnTitleChanged.run();
    }

    void setDescription(CharSequence description) {
        mDescription.setVisibility(TextUtils.isEmpty(description) ? GONE : VISIBLE);
        mDescription.setText(description);
    }

    void setDescriptionMaxLines(int maxLines) {
        mDescription.setMaxLines(maxLines);
        mDescription.setEllipsize(TextUtils.TruncateAt.END);
    }

    void setIcon(Drawable icon) {
        mIconView.setImageDrawable(icon);
        // Reset radius to generate a new drawable with expected radius.
        if (mCornerRadius >= 0) setIconCornerRadius(mCornerRadius);
    }

    void setIconTint(@ColorInt int color) {
        if (color == MessageBannerProperties.TINT_NONE) {
            ApiCompatibilityUtils.setImageTintList(mIconView, null);
        } else {
            ApiCompatibilityUtils.setImageTintList(mIconView, ColorStateList.valueOf(color));
        }
    }

    void setIconCornerRadius(int cornerRadius) {
        mCornerRadius = cornerRadius;
        if (!(mIconView.getDrawable() instanceof BitmapDrawable)) {
            return;
        }
        BitmapDrawable drawable = (BitmapDrawable) mIconView.getDrawable();
        RoundedBitmapDrawable bitmap = ViewUtils.createRoundedBitmapDrawable(
                getResources(), drawable.getBitmap(), cornerRadius);
        mIconView.setImageDrawable(bitmap);
    }

    void setPrimaryButtonText(String text) {
        mPrimaryButton.setVisibility(VISIBLE);
        mPrimaryButton.setText(text);
    }

    void setPrimaryButtonClickListener(OnClickListener listener) {
        mPrimaryButton.setOnClickListener(listener);
    }

    void setSecondaryIcon(Drawable icon) {
        mSecondaryButton.setImageDrawable(icon);
        mSecondaryButton.setVisibility(VISIBLE);
        mDivider.setVisibility(VISIBLE);
    }

    void setSecondaryActionCallback(Runnable callback) {
        mSecondaryActionCallback = callback;
    }

    void setSecondaryButtonMenuText(String text) {
        mSecondaryButtonMenuText = text;
    }

    void setSecondaryIconContentDescription(String description) {
        mSecondaryButton.setContentDescription(description);
    }

    void setSwipeHandler(SwipeHandler handler) {
        mSwipeGestureDetector = new MessageSwipeGestureListener(getContext(), handler);
    }

    void setOnTitleChanged(Runnable runnable) {
        mOnTitleChanged = runnable;
    }

    void enableLargeIcon(boolean enabled) {
        int smallSize = getResources().getDimensionPixelSize(R.dimen.message_icon_size);
        int largeSize = getResources().getDimensionPixelSize(R.dimen.message_icon_size_large);
        LayoutParams params = (LayoutParams) mIconView.getLayoutParams();
        if (enabled) {
            params.height = params.width = largeSize;
        } else {
            params.width = LayoutParams.WRAP_CONTENT;
            params.height = smallSize;
        }
        mIconView.setLayoutParams(params);
    }

    void setPopupMenuShownListener(PopupMenuShownListener popupMenuShownListener) {
        mPopupMenuShownListener = popupMenuShownListener;
    }

    // TODO(crbug.com/1163302): For the M88 experiment we decided to display single item menu in
    // response to the tap on secondary button. The code below implements this logic. Past M88 it
    // will be replaced with modal dialog driven from the feature code.
    void handleSecondaryButtonClick() {
        if (mSecondaryButtonMenuText == null) {
            if (mSecondaryActionCallback != null) {
                mSecondaryActionCallback.run();
            }
            return;
        }

        final PropertyModel menuItemPropertyModel =
                new PropertyModel.Builder(ListMenuItemProperties.ALL_KEYS)
                        .with(ListMenuItemProperties.TITLE, mSecondaryButtonMenuText)
                        .with(ListMenuItemProperties.ENABLED, true)
                        .build();

        MVCListAdapter.ModelList menuItems = new MVCListAdapter.ModelList();
        menuItems.add(new MVCListAdapter.ListItem(
                BasicListMenu.ListMenuItemType.MENU_ITEM, menuItemPropertyModel));

        ListMenu.Delegate listMenuDelegate = (PropertyModel menuItem) -> {
            assert menuItem == menuItemPropertyModel;
            // There is only one menu item in the menu.
            if (mSecondaryActionCallback != null) {
                mSecondaryActionCallback.run();
            }
        };
        BasicListMenu listMenu = new BasicListMenu(getContext(), menuItems, listMenuDelegate);

        ListMenuButtonDelegate delegate = new ListMenuButtonDelegate() {
            @Override
            public ListMenu getListMenu() {
                return listMenu;
            }
        };
        mSecondaryButton.setDelegate(delegate);
        if (mPopupMenuShownListener != null) {
            mSecondaryButton.addPopupListener(mPopupMenuShownListener);
        }
        mSecondaryButton.showMenu();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mSwipeGestureDetector != null) {
            return mSwipeGestureDetector.onTouchEvent(event) || super.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

    private class MessageSwipeGestureListener extends SwipeGestureListener {
        public MessageSwipeGestureListener(Context context, SwipeHandler handler) {
            super(context, handler);
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }
}


text:
/**
 *
 * Emerald (kbi/elude @2015)
 *
 */
#include "test_events.h"
#include "gtest/gtest.h"
#include "shared.h"
#include "system/system_event.h"
#include "system/system_file_monitor.h"
#include "system/system_file_serializer.h"

PRIVATE const char* test_file_name = "Oink";

PRIVATE void _create_test_file()
{
    const char                test_contents[]      = "This is an example sentence.";
    system_hashed_ansi_string test_file_name_has   = system_hashed_ansi_string_create(test_file_name);
    system_file_serializer    test_file_serializer = NULL;

    test_file_serializer = system_file_serializer_create_for_writing(test_file_name_has);

    ASSERT_TRUE(test_file_serializer != NULL);

    system_file_serializer_write(test_file_serializer,
                                 sizeof(test_contents),
                                 test_contents);

    system_file_serializer_release(test_file_serializer);
    test_file_serializer = NULL;
}

PRIVATE void _on_file_contents_changed(system_hashed_ansi_string file_name,
                                       void*                     user_arg)
{
    system_event* event_ptr = (system_event*) user_arg;

    system_event_set(*event_ptr);
}

TEST(FilesTest, NoCallbackFromFileMonitorForReadFilesTest)
{
    system_event              callback_received_event = system_event_create(true); /* manual_reset */
    FILE*                     file_handle             = NULL;
    bool                      has_timed_out           = false;
    char                      temp_buffer[4];
    system_hashed_ansi_string test_file_name_has      = system_hashed_ansi_string_create(test_file_name);
    system_file_serializer    test_file_serializer    = NULL;

    /* Create the test file */
    _create_test_file();

    /* Initialize the file monitor */
    system_file_monitor_monitor_file_changes(test_file_name_has,
                                             true, /* should_enable */
                                            &_on_file_contents_changed,
                                            &callback_received_event);

    /* Open the file and try to read some data from it */
    file_handle = fopen(test_file_name,
                        "r+");

    ASSERT_TRUE(file_handle != NULL);

    fread (temp_buffer,
           sizeof(temp_buffer),
           1,
           file_handle);
    fclose(file_handle);

    /* Wait for a few seconds .. */
    system_event_wait_multiple(&callback_received_event,
                               1, /* n_elements */
                               false, /* wait_on_all_objects */
                               system_time_get_time_for_s(2),
                              &has_timed_out);

    ASSERT_TRUE (has_timed_out);
    ASSERT_FALSE(system_event_wait_single_peek(callback_received_event) );

    /* Clean up */
    system_file_monitor_monitor_file_changes(test_file_name_has,
                                             false, /* should_enable */
                                             NULL,  /* pfn_file_changed_proc */
                                             NULL); /* user_arg */

    system_event_release(callback_received_event);
}

/* Until recently, system_file_serializer used to lock up if you spawned a new instance
 * for a non-existing file in an asynchronous mode, and then attempted to read something
 * from it.
 *
 * This unit test verifies this bug no longer reproduces. */
TEST(FilesTest, NoLockUpForAsyncSerializerInitializedForNonExistingFile)
{
    bool                   result     = true;
    system_file_serializer serializer = system_file_serializer_create_for_reading(system_hashed_ansi_string_create("IAmNotHere"),
                                                                                true); /* async_read */
    char                   temp;

    result = system_file_serializer_read(serializer,
                                         1, /* n_bytes */
                                        &temp);
    ASSERT_FALSE(result);

    system_file_serializer_release(serializer);
}

TEST(FilesTest, SingleFileMonitorTest)
{
    system_event              callback_received_event = system_event_create(true); /* manual_reset */
    FILE*                     file_handle             = NULL;
    const char                test_contents2[]        = "That";
    system_hashed_ansi_string test_file_name_has      = system_hashed_ansi_string_create(test_file_name);

    /* Create the test file */
    _create_test_file();

    /* Initialize the file monitor */
    system_file_monitor_monitor_file_changes(test_file_name_has,
                                             true, /* should_enable */
                                            &_on_file_contents_changed,
                                            &callback_received_event);

    /* Write some more stuff to the file */
    file_handle = fopen(test_file_name,
                        "w+");

    ASSERT_TRUE(file_handle != NULL);

    fwrite(test_contents2,
           sizeof(test_contents2),
           1, /* _Count */
           file_handle);
    fclose(file_handle);

    /* Wait till we hear back. */
    system_event_wait_single(callback_received_event);

    /* Unregister from notifications. This must be done BEFORE
     * we release the 'callback received' event. Otherwise, spurious
     * call-backs may crash the unit test project.. */
    system_file_monitor_monitor_file_changes(test_file_name_has,
                                             false, /* should_enable */
                                             NULL,  /* pfn_file_changed_proc */
                                             NULL); /* user_arg */

    system_event_release(callback_received_event);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<words>
    <word>
        <english>cable car</english>
        <polish>trolejbus</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>chapel</english>
        <polish>kaplica</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>concert hall</english>
        <polish>sala koncertowa</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>cycle lane</english>
        <polish>droga dla rowerów</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>football stadium</english>
        <polish>stadion piłkarski</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>harbour</english>
        <polish>port</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>hill</english>
        <polish>wzgórze</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>law courts</english>
        <polish>sądy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>mosque</english>
        <polish>meczet</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>pedestrian street</english>
        <polish>deptak</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>skyscraper</english>
        <polish>drapacz chmur</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>square</english>
        <polish>plac, skwer</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>statue</english>
        <polish>posąg</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>synagogue</english>
        <polish>synagoga</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>taxi rank</english>
        <polish>postój dla taksówek</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>temple</english>
        <polish>świątynia</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>tower</english>
        <polish>wieża</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>cathedral</english>
        <polish>katedra</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>places of worship</english>
        <polish>miejsca kultu</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>town hall</english>
        <polish>ratusz</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>bridge</english>
        <polish>most</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>underground</english>
        <polish>metro</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>in the city / town centre</english>
        <polish>centrum miasta</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>neighbourhood</english>
        <polish>sąsiedztwo</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>in the suburbs</english>
        <polish>przedmieścia - poza centrum</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>on the outskirts</english>
        <polish>na obrzeżach miasta</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>in the (financial) district</english>
        <polish>w (finansowej) dzielnicy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>in the old town</english>
        <polish>na starówce</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>congestion</english>
        <polish>zagęszczenie, zatłoczenie, przeludnienie</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>slums</english>
        <polish>slamsy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>vandalism</english>
        <polish>wandalizm</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>overcrowding</english>
        <polish>przeludnienie</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>pollution</english>
        <polish>zanieczyszczenie</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>homeless people</english>
        <polish>bezdomni ludzie</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>beggars</english>
        <polish>żebracy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>car fumes</english>
        <polish>spaliny samochodowe</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>poverty (n.)/ poor (adj.)</english>
        <polish>bieda (rz.) / biedny (przym.)</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>cosmopolitan</english>
        <polish>międzynarodowy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>run-down</english>
        <polish>zniszczony, w marnym stanie</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>industrial</english>
        <polish>przemysłowy</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>provincial</english>
        <polish>prowincjonalny</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>vibrant</english>
        <polish>pełny energii, pełny życia, ekscytujący, dynamiczny</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>polluted</english>
        <polish>zanieszczyszczony</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
    <word>
        <english>edge</english>
        <polish>krawędź</polish>
        <part>New English File 4 Upper Intermediate - Unit 6 Town and Cities</part>
        <subpart>A</subpart>
    </word>
</words>


text:
package com.redhat.datamodeler;

import org.jbpm.datamodeler.annotations.Description;
import org.jbpm.datamodeler.annotations.Label;

@Label("FactAnnotations3 label")
@Description(value = "FactAnnotations3 description")
public class FactAnnotations3 {
}


text:
import unittest
from graver import DirectedGraph
from graver import shortest_path

class TestDirectedGraph(unittest.TestCase):
    def test_shortest_path(self):
        g = DirectedGraph()
        a = g.add_vertex('a')
        b = g.add_vertex('b')
        c = g.add_vertex('c')

        g.add_edge('b', 'a', weight=1)
        g.add_edge('c', 'b', weight=2)

        # This edge should NOT be used for c->a
        # because it has opposite direction
        g.add_edge('a', 'c', weight=1)

        route = shortest_path(g, 'c', 'a')

        self.assertEqual([c, b, a], route[0])
        self.assertEqual(3, route[1])

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


text:
package christophedelory.playlist.pla;

import java.io.OutputStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

import christophedelory.content.Content;
import christophedelory.playlist.Media;
import christophedelory.playlist.Playlist;
import christophedelory.playlist.SpecificPlaylist;
import christophedelory.playlist.SpecificPlaylistProvider;

/**
 * iRiver T-series or S-series-compatible playlist.
 * @version $Revision: 91 $
 * @author Christophe Delory
 * @since 0.2.0
 */
public class PLA implements SpecificPlaylist
{
    /**
     * The provider of this specific playlist.
     */
    private transient SpecificPlaylistProvider _provider = null;

    /**
     * The list of song file names.
     */
    private final List<String> _filenames = new ArrayList<String>();

    @Override
    public void setProvider(final SpecificPlaylistProvider provider)
    {
        _provider = provider;
    }

    @Override
    public SpecificPlaylistProvider getProvider()
    {
        return _provider;
    }

    @Override
    public void writeTo(final OutputStream out, final String encoding) throws Exception
    {
        byte[] array = new byte[512];
        Arrays.fill(array, (byte) 0);
        array[4] = 'i';
        array[5] = 'r';
        array[6] = 'i';
        array[7] = 'v';
        array[8] = 'e';
        array[9] = 'r';
        array[10] = ' ';
        array[11] = 'U';
        array[12] = 'M';
        array[13] = 'S';
        array[14] = ' ';
        array[15] = 'P';
        array[16] = 'L';
        array[17] = 'A';

        final int nbSongs = _filenames.size();
        array[3] = (byte)((nbSongs & 0x000000ff) >> 0);
        array[2] = (byte)((nbSongs & 0x0000ff00) >> 8);
        array[1] = (byte)((nbSongs & 0x00ff0000) >> 16);
        array[0] = (byte)((nbSongs & 0xff000000) >> 24);

        out.write(array); // Throws NullPointerException if out is null. May throw IOException.

        for (String filename : _filenames)
        {
            Arrays.fill(array, (byte) 0);

            final int slashIndex = filename.lastIndexOf('/'); // May equal -1.
            final int antislashIndex = filename.lastIndexOf('\\'); // May equal -1.
            int fileIndex = 0; // Default case if none is found.

            if (slashIndex > antislashIndex) // And thus is greater or equal to 0.
            {
                fileIndex = slashIndex + 1;
            }
            else if (antislashIndex > slashIndex) // And thus is greater or equal to 0.
            {
                fileIndex = antislashIndex + 1;
            }

            // File index is one-based.
            fileIndex++;
            array[1] = (byte)((fileIndex & 0x000000ff) >> 0);
            array[0] = (byte)((fileIndex & 0x0000ff00) >> 8);

            final byte[] tmp = filename.getBytes("UTF-16BE"); // Shall not throw UnsupportedEncodingException.
            System.arraycopy(tmp, 0, array, 2, tmp.length); // May throw IndexOutOfBoundsException. Shall not throw ArrayStoreException, NullPointerException.

            out.write(array); // May throw IOException.
        }

        out.flush(); // May throw IOException.
    }

    @Override
    public Playlist toPlaylist()
    {
        final Playlist ret = new Playlist();

        for (String filename : _filenames)
        {
            final Media media = new Media(); // NOPMD Avoid instantiating new objects inside loops
            final Content content = new Content(filename); // NOPMD Avoid instantiating new objects inside loops
            media.setSource(content);

            ret.getRootSequence().addComponent(media);
        }

        ret.normalize();

        return ret;
    }

    /**
     * Returns the list of song file names.
     * @return a list of file names. May be empty but not null.
     */
    public List<String> getFilenames()
    {
        return _filenames;
    }
}


text:
package org.apache.camel.component.dataset;

import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class DataSetEndpointTest extends ContextTestSupport {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testDataSetEndpoint() throws Exception {
        final DataSetEndpoint endpoint = new DataSetEndpoint("dataset://foo", null, new SimpleDataSet(2));
        endpoint.setCamelContext(context);
        endpoint.setInitialDelay(0);

        assertEquals(0, endpoint.getPreloadSize());
        assertEquals(0, endpoint.getConsumeDelay());
        assertEquals(3, endpoint.getProduceDelay());

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(endpoint).to("direct:foo");
                from("direct:foo").to(endpoint);
            }
        });
        context.start();

        endpoint.assertIsSatisfied();
    }

    @Test
    public void testDataSetEndpointCtr() throws Exception {
        final DataSetEndpoint endpoint
                = new DataSetEndpoint("dataset://foo", context.getComponent("dataset"), new SimpleDataSet(2));

        endpoint.setConsumeDelay(2);
        assertEquals(2, endpoint.getConsumeDelay());
        endpoint.setProduceDelay(5);
        assertEquals(5, endpoint.getProduceDelay());
        endpoint.setInitialDelay(1);
        assertEquals(1, endpoint.getInitialDelay());

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(endpoint).to("direct:foo");
                from("direct:foo").to(endpoint);
            }
        });
        context.start();

        endpoint.assertIsSatisfied();
    }

    @Test
    public void testDataSetReporter() throws Exception {
        final DataSetEndpoint endpoint
                = new DataSetEndpoint("dataset://foo", context.getComponent("dataset"), new SimpleDataSet(10));
        endpoint.setInitialDelay(0);

        final AtomicBoolean reported = new AtomicBoolean();
        endpoint.setReporter(new Processor() {
            public void process(Exchange exchange) throws Exception {
                reported.set(true);
            }
        });

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(endpoint).to("direct:foo");
                from("direct:foo").to(endpoint);
            }
        });
        context.start();

        endpoint.assertIsSatisfied();
        assertTrue(reported.get());
    }

    @Test
    public void testSimpleDataSet() throws Exception {
        SimpleDataSet ds = new SimpleDataSet();
        ds.setSize(2);
        ds.setDefaultBody("Hi");
        assertEquals("Hi", ds.getDefaultBody());
    }

    @Test
    public void testDataSetSupport() throws Exception {
        MyDataSet ds = new MyDataSet();
        ds.setSize(4);
        ds.setReportCount(0);
        ds.setOutputTransformer(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String body = "Hi " + exchange.getIn().getBody(String.class);
                exchange.getIn().setBody(body);
            }
        });
        assertNotNull(ds.getOutputTransformer());

        final DataSetEndpoint endpoint = new DataSetEndpoint("dataset://foo", context.getComponent("dataset"), ds);
        endpoint.setInitialDelay(0);
        endpoint.allMessages().body().startsWith("Hi ");

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(endpoint).to("direct:foo");
                from("direct:foo").to(endpoint);
            }
        });
        context.start();

        endpoint.assertIsSatisfied();
    }

    private static class MyDataSet extends DataSetSupport {

        @Override
        protected Object createMessageBody(long messageIndex) {
            return "Message " + messageIndex;
        }
    }

}


text:
package org.ngbw.sdk.tool.validation;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import org.ngbw.sdk.api.tool.ParameterValidator2;
import org.ngbw.sdk.api.tool.FieldError;
import org.ngbw.sdk.common.util.BaseValidator;
import org.ngbw.sdk.database.TaskInputSourceDocument;
import org.ngbw.sdk.common.util.SuperString;
public class blast2Validator implements ParameterValidator2
{
private Set<String> requiredParameters;
private Set<String> requiredInput;
private Set<String> allowedParameters;
private Set<String> allowedInput;
// Map of parameter name to list separator (a single character string) for List parameters.
private Map<String, String> listParameters;
// Maps param name to permitted values for List, Excl, Switch type params
private Map<String, List<String>> listValues;
private Map<String, List<String>> exclValues ;
private Map<String, List<String>> switchValues;
private List<FieldError> errors = new ArrayList<FieldError>();
public blast2Validator() {
requiredParameters = new HashSet<String>();
requiredInput = new HashSet<String>();
allowedParameters = new HashSet<String>();
allowedInput = new HashSet<String>();
listParameters = new HashMap<String, String>();
listValues = new HashMap<String, List<String>>();
exclValues = new HashMap<String, List<String>>();
switchValues = new HashMap<String, List<String>>();
List<String> switchList = new ArrayList<String>(2);
switchList.add("0");
switchList.add("1");
List<String> tmpList;
tmpList = new ArrayList<String>();
tmpList.add("blastn");
tmpList.add("blastp");
tmpList.add("blastx");
tmpList.add("tblastn");
tmpList.add("tblastx");
tmpList.add("psitblastn");
exclValues.put("blast2_", tmpList);
allowedParameters.add("blast2_");
requiredParameters.add("blast2_");
allowedInput.add("query_");
requiredInput.add("query_");
allowedParameters.add("start_region_");
allowedParameters.add("end_region_");
tmpList = new ArrayList<String>();
tmpList.add("UNIPROT");
tmpList.add("SWISSPROT");
tmpList.add("TREMBL");
tmpList.add("PDBSEQ");
tmpList.add("REFSEQ_FUNGI_PROTEIN");
tmpList.add("REFSEQ_INV_PROTEIN");
tmpList.add("REFSEQ_MICRO_PROTEIN");
tmpList.add("REFSEQ_MITO_PROTEIN");
tmpList.add("REFSEQ_PLANT_PROTEIN");
tmpList.add("REFSEQ_PLASM_PROTEIN");
tmpList.add("REFSEQ_PLAST_PROTEIN");
tmpList.add("REFSEQ_PROT_PROTEIN");
tmpList.add("REFSEQ_VERTM_PROTEIN");
tmpList.add("REFSEQ_VERTO_PROTEIN");
tmpList.add("REFSEQ_VIRAL_PROTEIN");
tmpList.add("TPA_PROTEIN");
tmpList.add("UNIMES");
tmpList.add("UNIREF100");
tmpList.add("NCBI_NR");
exclValues.put("protein_db_", tmpList);
allowedParameters.add("protein_db_");
tmpList = new ArrayList<String>();
tmpList.add("NCBI_NT");
tmpList.add("GBMAM");
tmpList.add("GBBCT");
tmpList.add("GBENV");
tmpList.add("GBEST");
tmpList.add("GBGSS");
tmpList.add("GBHTC");
tmpList.add("GBHTG");
tmpList.add("GBPAT");
tmpList.add("GBINV");
tmpList.add("GBPHG");
tmpList.add("GBPLN");
tmpList.add("GBPRI");
tmpList.add("GBROD");
tmpList.add("GBSTS");
tmpList.add("GBSYN");
tmpList.add("GBUNA");
tmpList.add("GBVRL");
tmpList.add("GBVRT");
tmpList.add("REFSEQ_FUNGI_GENOMIC");
tmpList.add("REFSEQ_FUNGI_RNA");
tmpList.add("REFSEQ_INV_GENOMIC");
tmpList.add("REFSEQ_INV_RNA");
tmpList.add("REFSEQ_MICRO_GENOMIC");
tmpList.add("REFSEQ_MITO_GENOMIC");
tmpList.add("REFSEQ_PLANT_GENOMIC");
tmpList.add("REFSEQ_PLANT_RNA");
tmpList.add("REFSEQ_PLASM_GENOMIC");
tmpList.add("REFSEQ_PLASM_RNA");
tmpList.add("REFSEQ_PLAST_GENOMIC");
tmpList.add("REFSEQ_PLAST_RNA");
tmpList.add("REFSEQ_PROT_GENOMIC");
tmpList.add("REFSEQ_PROT_RNA");
tmpList.add("REFSEQ_VERTM_GENOMIC");
tmpList.add("REFSEQ_VERTM_RNA");
tmpList.add("REFSEQ_VERTO_GENOMIC");
tmpList.add("REFSEQ_VERTO_RNA");
tmpList.add("REFSEQ_VIRAL_GENOMIC");
tmpList.add("TPA_NUCLEIC");
tmpList.add("ENSEMBL");
exclValues.put("nucleotid_db_", tmpList);
allowedParameters.add("nucleotid_db_");
allowedParameters.add("filter_");
switchValues.put("filter_", switchList);
tmpList = new ArrayList<String>();
tmpList.add("v1");
tmpList.add("v2");
tmpList.add("v3");
tmpList.add("v4");
tmpList.add("v5");
exclValues.put("other_filters_", tmpList);
allowedParameters.add("other_filters_");
allowedParameters.add("lower_case_");
switchValues.put("lower_case_", switchList);
allowedParameters.add("Expect_");
allowedParameters.add("word_size_");
allowedParameters.add("dist_hits_");
allowedParameters.add("extend_hit_");
allowedParameters.add("dropoff_extent_");
allowedParameters.add("keep_hits_");
allowedParameters.add("gapped_alig_");
switchValues.put("gapped_alig_", switchList);
allowedParameters.add("dropoff_");
allowedParameters.add("dropoff_final_");
allowedParameters.add("mismatch_");
allowedParameters.add("match_");
tmpList = new ArrayList<String>();
tmpList.add("BLOSUM62");
tmpList.add("BLOSUM45");
tmpList.add("BLOSUM80");
tmpList.add("PAM30");
tmpList.add("PAM70");
exclValues.put("matrix_", tmpList);
allowedParameters.add("matrix_");
allowedParameters.add("open_a_gap_");
allowedParameters.add("extend_a_gap_");
tmpList = new ArrayList<String>();
tmpList.add("1");
tmpList.add("2");
tmpList.add("3");
tmpList.add("4");
tmpList.add("5");
tmpList.add("6");
tmpList.add("9");
tmpList.add("10");
tmpList.add("11");
tmpList.add("12");
tmpList.add("13");
tmpList.add("14");
tmpList.add("15");
exclValues.put("gc_query_", tmpList);
allowedParameters.add("gc_query_");
tmpList = new ArrayList<String>();
tmpList.add("1");
tmpList.add("2");
tmpList.add("3");
tmpList.add("4");
tmpList.add("5");
tmpList.add("6");
tmpList.add("9");
tmpList.add("10");
tmpList.add("11");
tmpList.add("12");
tmpList.add("13");
tmpList.add("14");
tmpList.add("15");
exclValues.put("gc_db_", tmpList);
allowedParameters.add("gc_db_");
tmpList = new ArrayList<String>();
tmpList.add("1");
tmpList.add("2");
tmpList.add("3");
exclValues.put("strand_", tmpList);
allowedParameters.add("strand_");
allowedParameters.add("Descriptions_");
allowedParameters.add("Alignments_");
tmpList = new ArrayList<String>();
tmpList.add("0");
tmpList.add("1");
tmpList.add("2");
tmpList.add("3");
tmpList.add("4");
tmpList.add("5");
tmpList.add("6");
tmpList.add("7");
tmpList.add("8");
exclValues.put("view_alignments_", tmpList);
allowedParameters.add("view_alignments_");
allowedParameters.add("show_gi_");
switchValues.put("show_gi_", switchList);
allowedParameters.add("believe_");
switchValues.put("believe_", switchList);
allowedParameters.add("htmloutput_");
switchValues.put("htmloutput_", switchList);
allowedParameters.add("external_links_");
switchValues.put("external_links_", switchList);
allowedParameters.add("one_HSP_per_line_");
switchValues.put("one_HSP_per_line_", switchList);
allowedParameters.add("image_query_");
switchValues.put("image_query_", switchList);
allowedInput.add("restrict_db_");
allowedInput.add("psi_checkpoint_");
}
public List<FieldError> getErrors()
{
return errors;
}
public Map<String, String> preProcessParameters(Map<String, List<String>> parameters)
{
Map<String, String> preProcessed = new HashMap<String, String>();
for (String param : parameters.keySet())
{
String newValue;
List<String> values = parameters.get(param);
// Is param of type List?
if (listValues.keySet().contains(param))
{
for (String value : values)
{
List<String> permittedValues = listValues.get(param);
if (!permittedValues.contains(value))
{
errors.add(new FieldError(param, "'" + value + "' is not a permitted value."));
}
}
// concatenate the multiple choices.
String separator = listParameters.get(param);
if (separator != null)
{
newValue = SuperString.valueOf(parameters.get(param), separator.charAt(0)).toString();
} else
{
newValue = SuperString.valueOf(parameters.get(param), '@').toString();
}
} else
{
newValue = parameters.get(param).get(0);
if (parameters.get(param).size() > 1)
{
errors.add(new FieldError(param, "multiple values are not permitted."));
}
if (exclValues.keySet().contains(param))
{
if (!exclValues.get(param).contains(newValue))
{
errors.add(new FieldError(param, "'" + newValue + "' is not a permitted value."));
}
} else if (switchValues.keySet().contains(param))
{
if (!switchValues.get(param).contains(newValue))
{
// todo: error
errors.add(new FieldError(param, "'" + newValue + "' is not a permitted value, must be 0 or 1."));
}
}
}
preProcessed.put(param, newValue);
}
return preProcessed;
}
public void validateParameters(Map<String, String> parameters) {
Set<String> missingRequired = validateRequiredParameters(parameters);
for (String missing : missingRequired)
{
errors.add(new FieldError(missing, "Parameter is required."));
}
for (String param : parameters.keySet())
{
if (!allowedParameters.contains(param))
{
errors.add(new FieldError(param, "Does not exist."));
continue;
}
String error = validate(param, parameters.get(param));
if (error != null)
{
errors.add(new FieldError(param, error));
}
}
}
public void validateInput(Set<String> input) {
Set<String> missingRequired = validateRequiredInput(input);
for (String missing : missingRequired)
{
errors.add(new FieldError(missing, "Input file parameter is required."));
}
}
String validate(String parameter, Object value) {
if (parameter.equals("blast2_")) {
if (BaseValidator.validateString(value) == false)
return "Parameter is required.";
return null;
}
if (parameter.equals("start_region_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("end_region_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("Expect_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("word_size_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("dist_hits_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("extend_hit_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("dropoff_extent_")) {
if (BaseValidator.validateDouble(value) == false)
return "Must be a Double.";
return null;
}
if (parameter.equals("keep_hits_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("dropoff_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("dropoff_final_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("mismatch_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("match_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("open_a_gap_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("extend_a_gap_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("Descriptions_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
if (parameter.equals("Alignments_")) {
if (BaseValidator.validateInteger(value) == false)
return "Must be an integer.";
return null;
}
return null;
}
private Set<String> validateRequiredParameters(Map<String, String> parameters) {
Set<String> required = new HashSet<String>(requiredParameters.size());
required.addAll(requiredParameters);
for (String parameter : parameters.keySet()) {
if (required.contains(parameter))
required.remove(parameter);
}
return required;
}
private Set<String> validateRequiredInput(Map<String, List<TaskInputSourceDocument>> input) {
Set<String> required = new HashSet<String>(requiredInput.size());
required.addAll(requiredInput);
for (String parameter : input.keySet()) {
if (required.contains(parameter))
required.remove(parameter);
}
return required;
}
private Set<String> validateRequiredInput(Set<String> input) {
Set<String> required = new HashSet<String>(requiredInput.size());
required.addAll(requiredInput);
for (String parameter : input) {
if (required.contains(parameter))
required.remove(parameter);
}
return required;
}
}