text:
package io.github.thatsmusic99.headsplus;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;

/**
 * bStats collects some data for plugin authors.
 *

 * Check out https://bStats.org/ to learn more about bStats!
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {

    static {
        // You can use the property to disable the check in your test environment
        if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals(
                "false")) {
            // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
            final String defaultPackage = new String(
                    new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
            final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g'
                    , 'e'});
            // We want to make sure nobody just copy & pastes the example and use the wrong package names
            if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
                throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
            }
        }
    }

    // The version of this bStats class
    public static final int B_STATS_VERSION = 1;

    // The url to which the data is sent
    private static final String URL = "https://bStats.org/submitData/bukkit";

    // Is bStats enabled on this server?
    private boolean enabled;

    // Should failed requests be logged?
    private static boolean logFailedRequests;

    // Should the sent data be logged?
    private static boolean logSentData;

    // Should the response text be logged?
    private static boolean logResponseStatusText;

    // The uuid of the server
    private static String serverUUID;

    // The plugin
    private final Plugin plugin;

    // The plugin id
    private final int pluginId;

    // A list with all custom charts
    private final List<CustomChart> charts = new ArrayList<>();

    /**
     * Class constructor.
     *
     * @param plugin   The plugin which stats should be submitted.
     * @param pluginId The id of the plugin.
     *                 It can be found at What is my plugin id?
     */
    public Metrics(Plugin plugin, int pluginId) {
        if (plugin == null) {
            throw new IllegalArgumentException("Plugin cannot be null!");
        }
        this.plugin = plugin;
        this.pluginId = pluginId;

        // Get the config file
        File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
        File configFile = new File(bStatsFolder, "config.yml");
        YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);

        // Check if the config file exists
        if (!config.isSet("serverUuid")) {

            // Add default values
            config.addDefault("enabled", true);
            // Every server gets it's unique random id.
            config.addDefault("serverUuid", UUID.randomUUID().toString());
            // Should failed request be logged?
            config.addDefault("logFailedRequests", false);
            // Should the sent data be logged?
            config.addDefault("logSentData", false);
            // Should the response text be logged?
            config.addDefault("logResponseStatusText", false);

            // Inform the server owners about bStats
            config.options().header(
                    "bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
                            "To honor their work, you should not disable it.\n" +
                            "This has nearly no effect on the server performance!\n" +
                            "Check out https://bStats.org/ to learn more :)"
            ).copyDefaults(true);
            try {
                config.save(configFile);
            } catch (IOException ignored) {
            }
        }

        // Load the data
        enabled = config.getBoolean("enabled", true);
        serverUUID = config.getString("serverUuid");
        logFailedRequests = config.getBoolean("logFailedRequests", false);
        logSentData = config.getBoolean("logSentData", false);
        logResponseStatusText = config.getBoolean("logResponseStatusText", false);

        if (enabled) {
            boolean found = false;
            // Search for all other bStats Metrics classes to see if we are the first one
            for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
                try {
                    service.getField("B_STATS_VERSION"); // Our identifier :)
                    found = true; // We aren't the first
                    break;
                } catch (NoSuchFieldException ignored) {
                }
            }
            // Register our service
            Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
            if (!found) {
                // We are the first!
                startSubmitting();
            }
        }
    }

    /**
     * Checks if bStats is enabled.
     *
     * @return Whether bStats is enabled or not.
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Adds a custom chart.
     *
     * @param chart The chart to add.
     */
    public void addCustomChart(CustomChart chart) {
        if (chart == null) {
            throw new IllegalArgumentException("Chart cannot be null!");
        }
        charts.add(chart);
    }

    /**
     * Starts the Scheduler which submits our data every 30 minutes.
     */
    private void startSubmitting() {
        final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (!plugin.isEnabled()) { // Plugin was disabled
                    timer.cancel();
                    return;
                }
                // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit
                // scheduler
                // Don't be afraid! The connection to the bStats server is still async, only the stats collection is
                // sync ;)
                Bukkit.getScheduler().runTask(plugin, () -> submitData());
            }
        }, 1000 * 60 * 5, 1000 * 60 * 30);
        // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
        // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
        // WARNING: Just don't do it!
    }

    /**
     * Gets the plugin specific data.
     * This method is called using Reflection.
     *
     * @return The plugin specific data.
     */
    public JsonObject getPluginData() {
        JsonObject data = new JsonObject();

        String pluginName = plugin.getDescription().getName();
        String pluginVersion = plugin.getDescription().getVersion();

        data.addProperty("pluginName", pluginName); // Append the name of the plugin
        data.addProperty("id", pluginId); // Append the id of the plugin
        data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
        JsonArray customCharts = new JsonArray();
        for (CustomChart customChart : charts) {
            // Add the data of the custom charts
            JsonObject chart = customChart.getRequestJsonObject();
            if (chart == null) { // If the chart is null, we skip it
                continue;
            }
            customCharts.add(chart);
        }
        data.add("customCharts", customCharts);

        return data;
    }

    /**
     * Gets the server specific data.
     *
     * @return The server specific data.
     */
    private JsonObject getServerData() {
        // Minecraft specific data
        int playerAmount;
        try {
            // Around MC 1.8 the return type was changed to a collection from an array,
            // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
            Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
            playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
                    ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
                    : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
        } catch (Exception e) {
            playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
        }
        int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
        String bukkitVersion = Bukkit.getVersion();
        String bukkitName = Bukkit.getName();

        // OS/Java specific data
        String javaVersion = System.getProperty("java.version");
        String osName = System.getProperty("os.name");
        String osArch = System.getProperty("os.arch");
        String osVersion = System.getProperty("os.version");
        int coreCount = Runtime.getRuntime().availableProcessors();

        JsonObject data = new JsonObject();

        data.addProperty("serverUUID", serverUUID);

        data.addProperty("playerAmount", playerAmount);
        data.addProperty("onlineMode", onlineMode);
        data.addProperty("bukkitVersion", bukkitVersion);
        data.addProperty("bukkitName", bukkitName);

        data.addProperty("javaVersion", javaVersion);
        data.addProperty("osName", osName);
        data.addProperty("osArch", osArch);
        data.addProperty("osVersion", osVersion);
        data.addProperty("coreCount", coreCount);

        return data;
    }

    /**
     * Collects the data and sends it afterwards.
     */
    private void submitData() {
        final JsonObject data = getServerData();

        JsonArray pluginData = new JsonArray();
        // Search for all other bStats Metrics classes to get their plugin data
        for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
            try {
                service.getField("B_STATS_VERSION"); // Our identifier :)

                for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
                    try {
                        Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
                        if (plugin instanceof JsonObject) {
                            pluginData.add((JsonObject) plugin);
                        } else { // old bstats version compatibility
                            try {
                                Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
                                if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
                                    Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
                                    jsonStringGetter.setAccessible(true);
                                    String jsonString = (String) jsonStringGetter.invoke(plugin);
                                    JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
                                    pluginData.add(object);
                                }
                            } catch (ClassNotFoundException e) {
                                // minecraft version 1.14+
                                if (logFailedRequests) {
                                    this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
                                }
                            }
                        }
                    } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
                    }
                }
            } catch (NoSuchFieldException ignored) {
            }
        }

        data.add("plugins", pluginData);

        // Create a new thread for the connection to the bStats server
        new Thread(() -> {
            try {
                // Send the data
                sendData(plugin, data);
            } catch (Exception e) {
                // Something went wrong! :(
                if (logFailedRequests) {
                    plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
                }
            }
        }).start();
    }

    /**
     * Sends the data to the bStats server.
     *
     * @param plugin Any plugin. It's just used to get a logger instance.
     * @param data   The data to send.
     * @throws Exception If the request failed.
     */
    private static void sendData(Plugin plugin, JsonObject data) throws Exception {
        if (data == null) {
            throw new IllegalArgumentException("Data cannot be null!");
        }
        if (Bukkit.isPrimaryThread()) {
            throw new IllegalAccessException("This method must not be called from the main thread!");
        }
        if (logSentData) {
            plugin.getLogger().info("Sending data to bStats: " + data);
        }
        HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

        // Compress the data to save bandwidth
        byte[] compressedData = compress(data.toString());

        // Add headers
        connection.setRequestMethod("POST");
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("Connection", "close");
        connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
        connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
        connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
        connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

        // Send data
        connection.setDoOutput(true);
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            outputStream.write(compressedData);
        }

        StringBuilder builder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        }

        if (logResponseStatusText) {
            plugin.getLogger().info("Sent data to bStats and received response: " + builder);
        }
    }

    /**
     * Gzips the given String.
     *
     * @param str The string to gzip.
     * @return The gzipped String.
     * @throws IOException If the compression failed.
     */
    private static byte[] compress(final String str) throws IOException {
        if (str == null) {
            return null;
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
            gzip.write(str.getBytes(StandardCharsets.UTF_8));
        }
        return outputStream.toByteArray();
    }

    /**
     * Represents a custom chart.
     */
    public static abstract class CustomChart {

        // The id of the chart
        final String chartId;

        /**
         * Class constructor.
         *
         * @param chartId The id of the chart.
         */
        CustomChart(String chartId) {
            if (chartId == null || chartId.isEmpty()) {
                throw new IllegalArgumentException("ChartId cannot be null or empty!");
            }
            this.chartId = chartId;
        }

        private JsonObject getRequestJsonObject() {
            JsonObject chart = new JsonObject();
            chart.addProperty("chartId", chartId);
            try {
                JsonObject data = getChartData();
                if (data == null) {
                    // If the data is null we don't send the chart.
                    return null;
                }
                chart.add("data", data);
            } catch (Throwable t) {
                if (logFailedRequests) {
                    Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
                }
                return null;
            }
            return chart;
        }

        protected abstract JsonObject getChartData() throws Exception;

    }

    /**
     * Represents a custom simple pie.
     */
    public static class SimplePie extends CustomChart {

        private final Callable<String> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public SimplePie(String chartId, Callable<String> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            String value = callable.call();
            if (value == null || value.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            data.addProperty("value", value);
            return data;
        }
    }

    /**
     * Represents a custom advanced pie.
     */
    public static class AdvancedPie extends CustomChart {

        private final Callable<Map<String, Integer>> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            JsonObject values = new JsonObject();
            Map<String, Integer> map = callable.call();
            if (map == null || map.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            boolean allSkipped = true;
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 0) {
                    continue; // Skip this invalid
                }
                allSkipped = false;
                values.addProperty(entry.getKey(), entry.getValue());
            }
            if (allSkipped) {
                // Null = skip the chart
                return null;
            }
            data.add("values", values);
            return data;
        }
    }

    /**
     * Represents a custom drilldown pie.
     */
    public static class DrilldownPie extends CustomChart {

        private final Callable<Map<String, Map<String, Integer>>> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        public JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            JsonObject values = new JsonObject();
            Map<String, Map<String, Integer>> map = callable.call();
            if (map == null || map.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            boolean reallyAllSkipped = true;
            for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
                JsonObject value = new JsonObject();
                boolean allSkipped = true;
                for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
                    value.addProperty(valueEntry.getKey(), valueEntry.getValue());
                    allSkipped = false;
                }
                if (!allSkipped) {
                    reallyAllSkipped = false;
                    values.add(entryValues.getKey(), value);
                }
            }
            if (reallyAllSkipped) {
                // Null = skip the chart
                return null;
            }
            data.add("values", values);
            return data;
        }
    }

    /**
     * Represents a custom single line chart.
     */
    public static class SingleLineChart extends CustomChart {

        private final Callable<Integer> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public SingleLineChart(String chartId, Callable<Integer> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            int value = callable.call();
            if (value == 0) {
                // Null = skip the chart
                return null;
            }
            data.addProperty("value", value);
            return data;
        }

    }

    /**
     * Represents a custom multi line chart.
     */
    public static class MultiLineChart extends CustomChart {

        private final Callable<Map<String, Integer>> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            JsonObject values = new JsonObject();
            Map<String, Integer> map = callable.call();
            if (map == null || map.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            boolean allSkipped = true;
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 0) {
                    continue; // Skip this invalid
                }
                allSkipped = false;
                values.addProperty(entry.getKey(), entry.getValue());
            }
            if (allSkipped) {
                // Null = skip the chart
                return null;
            }
            data.add("values", values);
            return data;
        }

    }

    /**
     * Represents a custom simple bar chart.
     */
    public static class SimpleBarChart extends CustomChart {

        private final Callable<Map<String, Integer>> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            JsonObject values = new JsonObject();
            Map<String, Integer> map = callable.call();
            if (map == null || map.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                JsonArray categoryValues = new JsonArray();
                categoryValues.add(new JsonPrimitive(entry.getValue()));
                values.add(entry.getKey(), categoryValues);
            }
            data.add("values", values);
            return data;
        }

    }

    /**
     * Represents a custom advanced bar chart.
     */
    public static class AdvancedBarChart extends CustomChart {

        private final Callable<Map<String, int[]>> callable;

        /**
         * Class constructor.
         *
         * @param chartId  The id of the chart.
         * @param callable The callable which is used to request the chart data.
         */
        public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
            super(chartId);
            this.callable = callable;
        }

        @Override
        protected JsonObject getChartData() throws Exception {
            JsonObject data = new JsonObject();
            JsonObject values = new JsonObject();
            Map<String, int[]> map = callable.call();
            if (map == null || map.isEmpty()) {
                // Null = skip the chart
                return null;
            }
            boolean allSkipped = true;
            for (Map.Entry<String, int[]> entry : map.entrySet()) {
                if (entry.getValue().length == 0) {
                    continue; // Skip this invalid
                }
                allSkipped = false;
                JsonArray categoryValues = new JsonArray();
                for (int categoryValue : entry.getValue()) {
                    categoryValues.add(new JsonPrimitive(categoryValue));
                }
                values.add(entry.getKey(), categoryValues);
            }
            if (allSkipped) {
                // Null = skip the chart
                return null;
            }
            data.add("values", values);
            return data;
        }
    }

}


text:
1) Prepare for release `./gradlew prepareRelease`
1) Update Version Number: remove -SNAPSHOT and commit the change
1) Run release task `./gradlew release`
1) Update Version Number in build.gradle and README.adoc

redpajama_set_name: RedPajamaGithub


text:
<?php
    $username = "root";
    $password = "";
    $host = "localhost";
    $database="ktph";

    $conn = mysqli_connect($host, $username, $password, $database);
    //$connection = mysql_select_db($database, $conn);

    $myquery = "
SELECT DISTINCT(`scnZone`) AS name FROM `ktphalldata`
UNION
SELECT DISTINCT(`BMIGrp`) AS name FROM `ktphalldata`
UNION
SELECT DISTINCT(CONCAT(BMIGrp,'-F')) AS name FROM `ktphalldata`
UNION
SELECT DISTINCT(`action`) AS name FROM `ktphalldata`
GROUP BY name
";
    $query = mysqli_query($conn,$myquery);

    if ( ! $myquery ) {
        ////echo mysql_error();
        echo "mySQL Error";
        die("Connection failed: ");
    }

    $nodes = array();

    for ($x = 0; $x < mysqli_num_rows($query); $x++) {
        $nodes[] = mysqli_fetch_assoc($query);
    }

    $myquery = "
SELECT `scnZone` AS source, `BMIGrp` AS target,
COUNT(*) as value
FROM `ktphalldata`
WHERE `revisit` = 'TRUE' AND `visitFY` = 'FY2013'
GROUP BY source, target
UNION
SELECT `BMIGrp` AS source, `action` AS target,
COUNT(*) as value
FROM `ktphalldata`
WHERE `revisit` = 'TRUE' AND `visitFY` = 'FY2013'
GROUP BY source, target
UNION
SELECT `action` AS source, CONCAT(BMIGrp,'-F') AS target,
COUNT(*) as value
FROM `ktphalldata`
WHERE `revisit` = 'TRUE' AND `visitFY` = 'FY2014'
GROUP BY source, target
";
    $query = mysqli_query($conn,$myquery);

    if ( ! $myquery ) {
        ////echo mysql_error();
        echo "mySQL Error";
        die("Connection failed: ");
    }

    $links = array();

    for ($x = 0; $x < mysqli_num_rows($query); $x++) {
        $links[] = mysqli_fetch_assoc($query);
    }

echo "{";
echo '"links": ', json_encode($links), "\n";
echo ',"nodes": ', json_encode($nodes), "\n";
echo "}";

    mysqli_close($conn);
?>


text:
$category@: media
formats:
  - websites
teaser:
  text: Displays an embedded Hulu video.
---

# amp-hulu

## Usage

Displays an embedded Hulu video.

```html
<amp-hulu
  width="412"
  height="213"
  layout="responsive"
  data-eid="4Dk5F2PYTtrgciuvloH3UA"
>
</amp-hulu>
```

## Attributes

### data-eid

The id of the video. For example, `4Dk5F2PYTtrgciuvloH3UA` is the eid in the following URL: `https://player.hulu.com/site/dash/mobile_embed.html?eid=4Dk5F2PYTtrgciuvloH3UA`.

### Common attributes

This element includes [common attributes](https://amp.dev/documentation/guides-and-tutorials/learn/common_attributes) extended to AMP components.

## Validation

See [amp-hulu rules](validator-amp-hulu.protoascii) in the AMP validator specification.


text:
/**
 * iOS Notifications
 */
declare var interop: any;

export class EZNotificationObserver extends NSObject {
  private _onReceiveCallback: (notification: NSNotification) => void;

  static new(): EZNotificationObserver {
    return <EZNotificationObserver>super.new();
  }

  public initWithCallback(onReceiveCallback: (notification: NSNotification) => void): EZNotificationObserver {
    this._onReceiveCallback = onReceiveCallback;
    return this;
  }

  public onReceive(notification: NSNotification): void {
    this._onReceiveCallback(notification);
  }

  public static ObjCExposedMethods = {
    "onReceive": { returns: interop.types.void, params: [NSNotification] }
  };
}


text:
.class final Lo/ᴴ$2;
.super Ljava/lang/Object;
.source ""

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lo/ᴴ;
.end annotation

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

# instance fields
.field private synthetic ˊ:Lo/ᴴ;

# direct methods
.method constructor <init>(Lo/ᴴ;)V
    .locals 0

    .line 76
    iput-object p1, p0, Lo/ᴴ$2;->ˊ:Lo/ᴴ;

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

    return-void
.end method

# virtual methods
.method public final onClick(Landroid/content/DialogInterface;I)V
    .locals 1

    .line 81
    iget-object v0, p0, Lo/ᴴ$2;->ˊ:Lo/ᴴ;

    invoke-virtual {v0}, Lo/ᴴ;->ˋ()V

    .line 82
    return-void
.end method


text:
#include "modules/prediction/scenario/prioritization/obstacles_prioritizer.h"

#include <algorithm>
#include <limits>
#include <memory>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>

#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacle_clusters.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

using apollo::perception::PerceptionObstacle;
using common::adapter::AdapterConfig;
using common::math::Box2d;
using common::math::Vec2d;
using hdmap::LaneInfo;
using hdmap::OverlapInfo;
using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>;

namespace {

bool IsLaneSequenceInReferenceLine(
    const LaneSequence& lane_sequence,
    const ADCTrajectoryContainer* ego_trajectory_container) {
  for (const auto& lane_segment : lane_sequence.lane_segment()) {
    std::string lane_id = lane_segment.lane_id();
    if (ego_trajectory_container->IsLaneIdInReferenceLine(lane_id)) {
      return true;
    }
  }
  return false;
}

int NearestFrontObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) {
  int nearest_front_obstacle_id = std::numeric_limits<int>::min();
  double smallest_relative_s = std::numeric_limits<double>::max();
  for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) {
    if (nearby_obs.s() < 0.0) {
      continue;
    }
    if (nearby_obs.s() < smallest_relative_s) {
      smallest_relative_s = nearby_obs.s();
      nearest_front_obstacle_id = nearby_obs.id();
    }
  }
  return nearest_front_obstacle_id;
}

int NearestBackwardObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) {
  int nearest_backward_obstacle_id = std::numeric_limits<int>::min();
  double smallest_relative_s = std::numeric_limits<double>::max();
  for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) {
    if (nearby_obs.s() > 0.0) {
      continue;
    }
    if (-nearby_obs.s() < smallest_relative_s) {
      smallest_relative_s = -nearby_obs.s();
      nearest_backward_obstacle_id = nearby_obs.id();
    }
  }
  return nearest_backward_obstacle_id;
}

}  // namespace

void ObstaclesPrioritizer::PrioritizeObstacles(
    const EnvironmentFeatures& environment_features,
    const std::shared_ptr<ScenarioFeatures> scenario_features) {
  AssignIgnoreLevel(environment_features, scenario_features);
  AssignCautionLevel(scenario_features);
}

void ObstaclesPrioritizer::AssignCautionLevel(
    const std::shared_ptr<ScenarioFeatures> scenario_features) {
  AssignCautionLevelInCruise(scenario_features);
}

void ObstaclesPrioritizer::AssignIgnoreLevel(
    const EnvironmentFeatures& environment_features,
    const std::shared_ptr<ScenarioFeatures> ptr_scenario_features) {
  auto obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);

  if (obstacles_container == nullptr) {
    AERROR << "Obstacles container pointer is a null pointer.";
    return;
  }

  auto pose_container =
      ContainerManager::Instance()->GetContainer<PoseContainer>(
          AdapterConfig::LOCALIZATION);
  if (pose_container == nullptr) {
    AERROR << "Pose container pointer is a null pointer.";
    return;
  }

  const PerceptionObstacle* pose_obstacle_ptr =
      pose_container->ToPerceptionObstacle();
  if (pose_obstacle_ptr == nullptr) {
    AERROR << "Pose obstacle pointer is a null pointer.";
    return;
  }

  double pose_theta = pose_obstacle_ptr->theta();
  double pose_x = pose_obstacle_ptr->position().x();
  double pose_y = pose_obstacle_ptr->position().y();

  ADEBUG << "Get pose (" << pose_x << ", " << pose_y << ", " << pose_theta
         << ")";

  // Build rectangular scan_area
  Box2d scan_box({pose_x + FLAGS_scan_length / 2.0 * std::cos(pose_theta),
                  pose_y + FLAGS_scan_length / 2.0 * std::sin(pose_theta)},
                 pose_theta, FLAGS_scan_length, FLAGS_scan_width);

  const auto& obstacle_ids =
      obstacles_container->curr_frame_predictable_obstacle_ids();

  for (const int& obstacle_id : obstacle_ids) {
    Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
    if (obstacle_ptr->history_size() == 0) {
      AERROR << "Obstacle [" << obstacle_ptr->id() << "] has no feature.";
      continue;
    }
    Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
    double obstacle_x = latest_feature_ptr->position().x();
    double obstacle_y = latest_feature_ptr->position().y();
    Vec2d ego_to_obstacle_vec(obstacle_x - pose_x, obstacle_y - pose_y);
    Vec2d ego_vec = Vec2d::CreateUnitVec2d(pose_theta);
    double s = ego_to_obstacle_vec.InnerProd(ego_vec);

    double pedestrian_like_nearby_lane_radius =
        FLAGS_pedestrian_nearby_lane_search_radius;
    bool is_near_lane = PredictionMap::HasNearbyLane(
        obstacle_x, obstacle_y, pedestrian_like_nearby_lane_radius);

    // Decide if we need consider this obstacle
    bool is_in_scan_area = scan_box.IsPointIn({obstacle_x, obstacle_y});
    bool is_on_lane = obstacle_ptr->IsOnLane();
    bool is_pedestrian_like_in_front_near_lanes =
        s > FLAGS_back_dist_ignore_ped &&
        (latest_feature_ptr->type() == PerceptionObstacle::PEDESTRIAN ||
         latest_feature_ptr->type() == PerceptionObstacle::BICYCLE ||
         latest_feature_ptr->type() == PerceptionObstacle::UNKNOWN ||
         latest_feature_ptr->type() == PerceptionObstacle::UNKNOWN_MOVABLE) &&
        is_near_lane;
    bool is_near_junction = obstacle_ptr->IsNearJunction();

    bool need_consider = is_in_scan_area || is_on_lane || is_near_junction ||
                         is_pedestrian_like_in_front_near_lanes;

    if (!need_consider) {
      latest_feature_ptr->mutable_priority()->set_priority(
          ObstaclePriority::IGNORE);
    } else {
      latest_feature_ptr->mutable_priority()->set_priority(
          ObstaclePriority::NORMAL);
    }
  }
}

void ObstaclesPrioritizer::AssignCautionLevelInCruise(
    const std::shared_ptr<ScenarioFeatures> scenario_features) {
  // TODO(kechxu) integrate change lane when ready to check change lane
  AssignCautionLevelCruiseKeepLane();
  AssignCautionLevelByEgoReferenceLine();
}

void ObstaclesPrioritizer::AssignCautionLevelCruiseKeepLane() {
  ObstaclesContainer* obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);
  if (obstacles_container == nullptr) {
    AERROR << "Null obstacles container found";
    return;
  }
  Obstacle* ego_vehicle =
      obstacles_container->GetObstacle(FLAGS_ego_vehicle_id);
  if (ego_vehicle == nullptr) {
    AERROR << "Ego vehicle not found";
    return;
  }
  if (ego_vehicle->history_size() < 2) {
    AERROR << "Ego vehicle has no history";
    return;
  }
  const Feature& ego_latest_feature = ego_vehicle->feature(1);
  for (const LaneSequence& lane_sequence :
       ego_latest_feature.lane().lane_graph().lane_sequence()) {
    int nearest_front_obstacle_id =
        NearestFrontObstacleIdOnLaneSequence(lane_sequence);
    if (nearest_front_obstacle_id < 0) {
      continue;
    }
    Obstacle* obstacle_ptr =
        obstacles_container->GetObstacle(nearest_front_obstacle_id);
    if (obstacle_ptr == nullptr) {
      AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found";
      continue;
    }
    obstacle_ptr->SetCaution();
  }
}

void ObstaclesPrioritizer::AssignCautionLevelCruiseChangeLane() {
  ObstaclesContainer* obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);
  if (obstacles_container == nullptr) {
    AERROR << "Null obstacles container found";
    return;
  }
  ADCTrajectoryContainer* ego_trajectory_container =
      ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
          AdapterConfig::PLANNING_TRAJECTORY);
  Obstacle* ego_vehicle =
      obstacles_container->GetObstacle(FLAGS_ego_vehicle_id);
  if (ego_vehicle == nullptr) {
    AERROR << "Ego vehicle not found";
    return;
  }
  if (ego_vehicle->history_size() == 0) {
    AERROR << "Ego vehicle has no history";
    return;
  }
  const Feature& ego_latest_feature = ego_vehicle->latest_feature();
  for (const LaneSequence& lane_sequence :
       ego_latest_feature.lane().lane_graph().lane_sequence()) {
    if (lane_sequence.vehicle_on_lane()) {
      int nearest_front_obstacle_id =
          NearestFrontObstacleIdOnLaneSequence(lane_sequence);
      if (nearest_front_obstacle_id < 0) {
        continue;
      }
      Obstacle* obstacle_ptr =
          obstacles_container->GetObstacle(nearest_front_obstacle_id);
      if (obstacle_ptr == nullptr) {
        AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found";
        continue;
      }
      obstacle_ptr->SetCaution();
    } else if (IsLaneSequenceInReferenceLine(lane_sequence,
                                             ego_trajectory_container)) {
      int nearest_front_obstacle_id =
          NearestFrontObstacleIdOnLaneSequence(lane_sequence);
      int nearest_backward_obstacle_id =
          NearestBackwardObstacleIdOnLaneSequence(lane_sequence);
      if (nearest_front_obstacle_id >= 0) {
        Obstacle* front_obstacle_ptr =
            obstacles_container->GetObstacle(nearest_front_obstacle_id);
        if (front_obstacle_ptr != nullptr) {
          front_obstacle_ptr->SetCaution();
        }
      }
      if (nearest_backward_obstacle_id >= 0) {
        Obstacle* backward_obstacle_ptr =
            obstacles_container->GetObstacle(nearest_backward_obstacle_id);
        if (backward_obstacle_ptr != nullptr) {
          backward_obstacle_ptr->SetCaution();
        }
      }
    }
  }
}

void ObstaclesPrioritizer::AssignCautionLevelInJunction(
    const std::shared_ptr<ScenarioFeatures> scenario_features) {
  if (scenario_features->scenario().type() != Scenario::JUNCTION) {
    ADEBUG << "Not in Junction Scenario";
    return;
  }
  std::string junction_id = scenario_features->scenario().junction_id();
  ObstaclesContainer* obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);
  if (obstacles_container == nullptr) {
    AERROR << "Null obstacles container found";
    return;
  }
  Obstacle* ego_vehicle =
      obstacles_container->GetObstacle(FLAGS_ego_vehicle_id);
  if (ego_vehicle == nullptr) {
    AERROR << "Ego vehicle not found";
    return;
  }
  for (const int id :
       obstacles_container->curr_frame_predictable_obstacle_ids()) {
    Obstacle* obstacle_ptr = obstacles_container->GetObstacle(id);
    if (obstacle_ptr != nullptr && obstacle_ptr->IsInJunction(junction_id)) {
      obstacle_ptr->SetCaution();
      ADEBUG << "SetCaution for obstacle [" << obstacle_ptr->id() << "]";
    }
  }
  AssignCautionLevelByEgoReferenceLine();
}

void ObstaclesPrioritizer::AssignCautionLevelByEgoReferenceLine() {
  ObstaclesContainer* obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);
  if (obstacles_container == nullptr) {
    AERROR << "Null obstacles container found";
    return;
  }
  ADCTrajectoryContainer* adc_trajectory_container =
      ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
          AdapterConfig::PLANNING_TRAJECTORY);
  if (adc_trajectory_container == nullptr) {
    AERROR << "adc_trajectory_container is nullptr";
    return;
  }
  const std::vector<std::string>& lane_ids =
      adc_trajectory_container->GetADCLaneIDSequence();
  if (lane_ids.empty()) {
    return;
  }

  auto pose_container =
      ContainerManager::Instance()->GetContainer<PoseContainer>(
          AdapterConfig::LOCALIZATION);
  if (pose_container == nullptr) {
    AERROR << "Pose container pointer is a null pointer.";
    return;
  }
  const PerceptionObstacle* pose_obstacle_ptr =
      pose_container->ToPerceptionObstacle();
  if (pose_obstacle_ptr == nullptr) {
    AERROR << "Pose obstacle pointer is a null pointer.";
    return;
  }
  double pose_x = pose_obstacle_ptr->position().x();
  double pose_y = pose_obstacle_ptr->position().y();
  double ego_vehicle_s = std::numeric_limits<double>::max();
  double ego_vehicle_l = std::numeric_limits<double>::max();
  double accumulated_s = 0.0;
  // first loop of lane_ids to findout ego_vehicle_s
  for (const std::string& lane_id : lane_ids) {
    std::shared_ptr<const LaneInfo> lane_info_ptr =
        PredictionMap::LaneById(lane_id);
    if (lane_info_ptr == nullptr) {
      AERROR << "Null lane info pointer found.";
      continue;
    }
    double s = 0.0;
    double l = 0.0;
    if (PredictionMap::GetProjection({pose_x, pose_y}, lane_info_ptr, &s, &l)) {
      if (std::fabs(l) < std::fabs(ego_vehicle_l)) {
        ego_vehicle_s = accumulated_s + s;
        ego_vehicle_l = l;
      }
    }
    accumulated_s += lane_info_ptr->total_length();
  }

  // then loop through lane_ids to AssignCaution for obstacle vehicles
  accumulated_s = 0.0;
  for (const std::string& lane_id : lane_ids) {
    std::shared_ptr<const LaneInfo> lane_info_ptr =
        PredictionMap::LaneById(lane_id);
    if (lane_info_ptr == nullptr) {
      AERROR << "Null lane info pointer found.";
      continue;
    }
    accumulated_s += lane_info_ptr->total_length();
    AssignCautionByMerge(lane_info_ptr);
    AssignCautionByOverlap(lane_info_ptr);
    if (accumulated_s > FLAGS_caution_search_distance_ahead + ego_vehicle_s) {
      break;
    }
  }

  // finally loop through all pedestrian to AssignCaution
  for (const int obstacle_id :
       obstacles_container->curr_frame_predictable_obstacle_ids()) {
    Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
    if (obstacle_ptr->history_size() == 0) {
      AERROR << "Obstacle [" << obstacle_ptr->id() << "] has no feature.";
      continue;
    }
    Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
    if (latest_feature_ptr->type() != PerceptionObstacle::PEDESTRIAN) {
      continue;
    }
    double start_x = latest_feature_ptr->position().x();
    double start_y = latest_feature_ptr->position().y();
    double end_x = start_x + FLAGS_caution_pedestrian_approach_time *
                                 latest_feature_ptr->raw_velocity().x();
    double end_y = start_y + FLAGS_caution_pedestrian_approach_time *
                                 latest_feature_ptr->raw_velocity().y();
    std::vector<std::string> nearby_lane_ids = PredictionMap::NearbyLaneIds(
        {start_x, start_y}, FLAGS_pedestrian_nearby_lane_search_radius);
    if (nearby_lane_ids.empty()) {
      continue;
    }
    for (const std::string& lane_id : nearby_lane_ids) {
      if (!adc_trajectory_container->IsLaneIdInReferenceLine(lane_id)) {
        continue;
      }
      std::shared_ptr<const LaneInfo> lane_info_ptr =
          PredictionMap::LaneById(lane_id);
      if (lane_info_ptr == nullptr) {
        AERROR << "Null lane info pointer found.";
        continue;
      }
      double start_s = 0.0;
      double start_l = 0.0;
      double end_s = 0.0;
      double end_l = 0.0;
      if (PredictionMap::GetProjection({start_x, start_y}, lane_info_ptr,
                                       &start_s, &start_l) &&
          PredictionMap::GetProjection({end_x, end_y}, lane_info_ptr, &end_s,
                                       &end_l)) {
        if (std::fabs(start_l) < FLAGS_pedestrian_nearby_lane_search_radius ||
            std::fabs(end_l) < FLAGS_pedestrian_nearby_lane_search_radius ||
            start_l * end_l < 0.0) {
          obstacle_ptr->SetCaution();
        }
      }
    }
  }
}

void ObstaclesPrioritizer::AssignCautionByMerge(
    std::shared_ptr<const LaneInfo> lane_info_ptr) {
  SetCautionBackward(lane_info_ptr,
                     FLAGS_caution_search_distance_backward_for_merge);
}

void ObstaclesPrioritizer::AssignCautionByOverlap(
    std::shared_ptr<const LaneInfo> lane_info_ptr) {
  std::string lane_id = lane_info_ptr->id().id();
  const std::vector<std::shared_ptr<const OverlapInfo>> cross_lanes_ =
      lane_info_ptr->cross_lanes();
  for (const auto overlap_ptr : cross_lanes_) {
    for (const auto& object : overlap_ptr->overlap().object()) {
      const auto& object_id = object.id().id();
      if (object_id == lane_info_ptr->id().id()) {
        continue;
      } else {
        std::shared_ptr<const LaneInfo> overlap_lane_ptr =
            PredictionMap::LaneById(object_id);
        SetCautionBackward(overlap_lane_ptr,
                           FLAGS_caution_search_distance_backward_for_overlap);
      }
    }
  }
}

void ObstaclesPrioritizer::SetCautionBackward(
    std::shared_ptr<const LaneInfo> start_lane_info_ptr,
    const double max_distance) {
  ObstaclesContainer* obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);
  std::unordered_map<std::string, std::vector<LaneObstacle>> lane_obstacles =
      ObstacleClusters::GetLaneObstacles();
  std::queue<std::pair<ConstLaneInfoPtr, double>> lane_info_queue;
  lane_info_queue.emplace(start_lane_info_ptr,
                          start_lane_info_ptr->total_length());
  while (!lane_info_queue.empty()) {
    ConstLaneInfoPtr curr_lane = lane_info_queue.front().first;
    double cumu_distance = lane_info_queue.front().second;
    lane_info_queue.pop();
    const std::string& lane_id = curr_lane->id().id();
    std::unordered_set<std::string> visited_lanes;
    if (visited_lanes.find(lane_id) == visited_lanes.end() &&
        lane_obstacles.find(lane_id) != lane_obstacles.end() &&
        !lane_obstacles[lane_id].empty()) {
      visited_lanes.insert(lane_id);
      // find the obstacle with largest lane_s on the lane
      int obstacle_id = lane_obstacles[lane_id].front().obstacle_id();
      double obstacle_s = lane_obstacles[lane_id].front().lane_s();
      for (const LaneObstacle& lane_obstacle : lane_obstacles[lane_id]) {
        if (lane_obstacle.lane_s() > obstacle_s) {
          obstacle_id = lane_obstacle.obstacle_id();
          obstacle_s = lane_obstacle.lane_s();
        }
      }
      Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
      if (obstacle_ptr == nullptr) {
        AERROR << "Obstacle [" << obstacle_id << "] Not found";
        continue;
      }
      obstacle_ptr->SetCaution();
      continue;
    }
    if (cumu_distance > max_distance) {
      continue;
    }
    for (const auto& pre_lane_id : curr_lane->lane().predecessor_id()) {
      ConstLaneInfoPtr pre_lane_ptr = PredictionMap::LaneById(pre_lane_id.id());
      lane_info_queue.emplace(pre_lane_ptr,
                              cumu_distance + pre_lane_ptr->total_length());
    }
  }
}

}  // namespace prediction
}  // namespace apollo


text:
title: Meinungen
layout: splash
permalink: /meinungen
header:
  overlay_image: /assets/images/splash/scoobac-landingpage.jpg
  overlay_filter: rgba(54, 251, 88, 0.4)
  cta_label: "Intro"
  cta_url: "/intro"
excerpt: "**Das sagen Andere zu Scoobac.**"
---

# Sylvia Löhrmann, Bildungsministerin NRW

Wir haben Frau Löhrmann folgendes gefragt:

Sehr geehrte Frau Löhrmann,
wir von Scoobac planen die Entwicklung einer App zur verbesserten Organisation des Schullaltags
für Schülerinnen und Schüler. Wir möchten vor Allem die Kommunikation zwischen Lehrer und Schüler vereinfachen
und wichtige Informationen wie Stunden- und Vertretungspläne bequem zugänglich machen.

Hierzu würde uns interessieren, wie sie generell den Mega-Trend der Digitalisierung im Zusammenhang mit dem Schulsystem bewerten und ob Sie grundsätzlich Potential in der App-Idee sehen.

Freundlicherweise erhielten wir folgende Antwort:

>Digitale Kompetenzen sind unverzichtbar, auch um Prozesse zu verstehen und hinterfragen zu können. Daher arbeiten wir in Nordrhein-Westfalen an einer Bildungsoffensive für das Lernen in der digitalen Welt. Im Mittelpunkt stehen die Kinder und Jugendlichen.
>Die Herausforderungen und Chancen der Digitalisierung wollen wir auch in der Bildung als Querschnittsaufgabe fassen und in allen Schulfächern abbilden. Hierbei spielt die einzelne Schule als zentraler Ort des gemeinsamen Lernens im Kollegium und zwischen Lehrenden und Lernenden eine zentrale Rolle.
>In diesem Sinne stehen wir der Entwicklung und dem Einsatz von Apps zur Kommunikation zwischen Lehrer*innen und Schüler*innen aufgeschlossen gegenüber.
>-- Email vom 8. März 2017 (via Vera Küpper, Kommunikation Frau Löhrmann)


text:
import React from "react";
import Book from "@material-ui/icons/BookOutlined";
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Avatar from '@material-ui/core/Avatar';

export default () => {
  return (
    <ListItem>
      <Avatar>
        <Book color={"default"} />
      </Avatar>
      <ListItemText primary="GIT BOOKs" style={{ color: 'white' }}></ListItemText>
    </ListItem>
  );
};


text:
package org.hisp.dhis.security.oidc.provider;

import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_GOOGLE_REDIRECT_URI;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_CLIENT_ID;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_CLIENT_SECRET;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_DISPLAY_ALIAS;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_ENABLE_LOGOUT;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_MAPPING_CLAIM;
import static org.hisp.dhis.external.conf.ConfigurationKey.OIDC_PROVIDER_WSO2_SERVER_URL;

import java.util.Objects;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.hisp.dhis.security.oidc.DhisOidcClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;

/**
 * @author Morten Svanæs <msvanaes@dhis2.org>
 */
public class Wso2Provider extends AbstractOidcProvider
{
    public static final String REGISTRATION_ID = "wso2";

    private Wso2Provider()
    {
        throw new IllegalStateException( "Utility class" );
    }

    public static DhisOidcClientRegistration parse( Properties config )
    {
        Objects.requireNonNull( config, "DhisConfigurationProvider is missing!" );

        String wso2ClientId = config.getProperty( OIDC_PROVIDER_WSO2_CLIENT_ID.getKey() );
        String wso2ClientSecret = config.getProperty( OIDC_PROVIDER_WSO2_CLIENT_SECRET.getKey() );

        if ( Strings.isNullOrEmpty( wso2ClientId ) )
        {
            return null;
        }

        if ( Strings.isNullOrEmpty( wso2ClientSecret ) )
        {
            throw new IllegalArgumentException( "WSO2 client secret is missing!" );
        }

        ClientRegistration clientRegistration = buildClientRegistration( config,
            wso2ClientId, wso2ClientSecret, config.getProperty( OIDC_PROVIDER_WSO2_SERVER_URL.getKey() ) );

        return DhisOidcClientRegistration.builder()
            .clientRegistration( clientRegistration )
            .mappingClaimKey( config.getProperty( OIDC_PROVIDER_WSO2_MAPPING_CLAIM.getKey() ) )
            .loginIcon( "../oidc/wso2-logo.svg" )
            .loginIconPadding( "0px 1px" )
            .loginText( config.getProperty( OIDC_PROVIDER_WSO2_DISPLAY_ALIAS.getKey() ) )
            .build();
    }

    private static ClientRegistration buildClientRegistration( Properties config, String wso2ClientId,
        String wso2ClientSecret, String providerBaseUrl )
    {
        ClientRegistration.Builder builder = ClientRegistration.withRegistrationId( Wso2Provider.REGISTRATION_ID );
        builder.clientName( wso2ClientId );
        builder.clientId( wso2ClientId );
        builder.clientSecret( wso2ClientSecret );
        builder.clientAuthenticationMethod( ClientAuthenticationMethod.BASIC );
        builder.authorizationGrantType( AuthorizationGrantType.AUTHORIZATION_CODE );
        builder.scope( "openid", "profile", DEFAULT_MAPPING_CLAIM );
        builder.authorizationUri( providerBaseUrl + "/oauth2/authorize" );
        builder.tokenUri( providerBaseUrl + "/oauth2/token" );
        builder.jwkSetUri( providerBaseUrl + "/oauth2/jwks" );
        builder.userInfoUri( providerBaseUrl + "/oauth2/userinfo" );
        builder.redirectUri( StringUtils.firstNonBlank(
            config.getProperty( OIDC_PROVIDER_GOOGLE_REDIRECT_URI.getKey() ),
            DEFAULT_REDIRECT_TEMPLATE_URL ) );
        builder.userInfoAuthenticationMethod( AuthenticationMethod.HEADER );
        builder.userNameAttributeName( IdTokenClaimNames.SUB );

        if ( DhisConfigurationProvider.isOn( config.getProperty( OIDC_PROVIDER_WSO2_ENABLE_LOGOUT.getKey() ) ) )
        {
            builder.providerConfigurationMetadata( ImmutableMap
                .of( "end_session_endpoint", providerBaseUrl + "/oidc/logout" ) );
        }

        return builder.build();
    }
}


text:
static unsigned long *crc32 = NULL;

// TRX magic (HDR0)
#define TRX_MAGIC 0x30524448

// Structures
struct TRXHeader {
    unsigned int magic;
    unsigned int len;
    unsigned int crc;
    unsigned int flags_vers;
    unsigned int offsets[3];
};

int readFile(const char *filename, char **result) {
    *result = NULL;
	FILE *f = fopen(filename, "rb");
	if (f == NULL) return -1;
	fseek(f, 0, SEEK_END);
    int size = ftell(f);
	fseek(f, 0, SEEK_SET);
	*result = (char *)malloc(size+1);
	if (size != fread(*result, sizeof(char), size, f)) {
		free(*result);
		return -1;
	}
	fclose(f);
	(*result)[size] = 0x00;
	return size;
}

int writeFile(const char *filename, char *data, int size) {
    FILE *f = fopen(filename, "wb");
    int written = fwrite(data, sizeof(char), size, f);
    fclose(f);
    return written;
}

unsigned int calcCRC(char *data, unsigned int length) {
    unsigned int crc = 0xFFFFFFFF;
    if (!crc32) {
        unsigned long crc, poly = 0xEDB88320L;
        int n, bit;
        if (crc32) return 0;
        crc32 = (unsigned long *)malloc(256 * sizeof(unsigned long));
        if (crc32 == NULL) return 0;

        for (n = 0; n < 256; n++) {
            crc = (unsigned long)n;
            for (bit = 0; bit < 8; bit++) {
                crc = (crc & 1) ? (poly ^ (crc >> 1)) : (crc >> 1);
            }
            crc32[n] = crc;
        }
    }
    for (; length; length--, data++) {
        crc = crc32[(crc ^ *data) & 0xff] ^ (crc >> 8);
    }
    return crc;
}

void writeTRX(int newHeader, char *filename, struct TRXHeader *expectedHeader, struct TRXHeader **currentHeaderPointer, int linksys) {
    struct TRXHeader *currentHeader = *currentHeaderPointer;
    unsigned int newlen = expectedHeader->len;
    int headerLength = sizeof(struct TRXHeader);
    if (newHeader) {
        // Write new header
        expectedHeader->len += headerLength;
        char *newData = malloc(expectedHeader->len+headerLength);
        memcpy(newData, expectedHeader, headerLength);
        memcpy(newData+headerLength, *currentHeaderPointer, expectedHeader->len);
        *currentHeaderPointer = (struct TRXHeader *)newData;
        currentHeader = *currentHeaderPointer;
    } else {
        // Overwrite existing header
        memcpy(currentHeader, expectedHeader, headerLength);
        if (linksys) {
            currentHeader->len -= 978;
            expectedHeader->len -= 978;
        }
    }

    // Recalculate checksum
    currentHeader->crc = calcCRC((char *)(&currentHeader->flags_vers), currentHeader->len-3*sizeof(int));
    expectedHeader->crc = currentHeader->crc;

    // Write out revised file
    printf("Writing revised binary with TRX header to %s... ", filename);
    writeFile(filename, (char *)currentHeader, newlen);
    printf("done!\n");
}

int validateTRX(int size, char *data, char *filename, int linksys) {
    int retVal = 1;

    // Append .trx to filename in case we write a new one
    char *outFilename = malloc(strlen(filename)+5);
    sprintf(outFilename, "%s.trx", filename);

    // Cast the beginning of the file as a TRX header, and fill in expected header values
    struct TRXHeader *expectedHeader = malloc(sizeof(struct TRXHeader));
    struct TRXHeader *currentHeader = (struct TRXHeader *)data;
    expectedHeader->magic = TRX_MAGIC;
    expectedHeader->len = size;
    if (size > sizeof(struct TRXHeader)) expectedHeader->crc = calcCRC((char *)(&currentHeader->flags_vers), expectedHeader->len-3*sizeof(int));
    expectedHeader->flags_vers = currentHeader->flags_vers;
    expectedHeader->offsets[0] = currentHeader->offsets[0];
    expectedHeader->offsets[1] = currentHeader->offsets[1];
    expectedHeader->offsets[2] = currentHeader->offsets[2];

    // Validate magic number
    if (currentHeader->magic == expectedHeader->magic) {
        printf("TRX header found: %08X\n", currentHeader->magic);
    } else {
        printf("TRX header not found.\n");
        printf("\tMagic expected: %08X\t Magic found: %08X\n", expectedHeader->magic, currentHeader->magic);

        // Firmware doesn't actually have a TRX header, so populate its other fields
        expectedHeader->flags_vers = 0x10000; // Why? I don't know.
        expectedHeader->offsets[0] = 0x1C; // Again, no idea.
        expectedHeader->offsets[1] = 0x0930;
        expectedHeader->offsets[2] = 0x1DDD0C;

        writeTRX(1, outFilename, expectedHeader, &currentHeader, linksys);
        retVal = -1;
    }

   // Validate file size is more than TRX header
    if (currentHeader->len < sizeof(struct TRXHeader)) {
        printf("Error: TRX file size is too small\n");
        printf("\tFile size is smaller than TRX header size (28 bytes)\n");
        writeTRX(0, outFilename, expectedHeader, &currentHeader, linksys);
        retVal = -2;
    }

    // Validate file length
    if (currentHeader->len == expectedHeader->len) {
        printf("TRX file length: %d\n", currentHeader->len);
    } else {
        printf("Error: Expected and actual file length do not match\n");
        printf("\tLength expected: %d\tLength found: %d\n", expectedHeader->len, currentHeader->len);
        writeTRX(0, outFilename, expectedHeader, &currentHeader, linksys);
        retVal = -2;
    }

    // Validate checksum
    if (retVal) {
        if (currentHeader->crc == expectedHeader->crc) {
            printf("TRX checksum is correct: %08X\n", expectedHeader->crc);
        } else {
            printf("Error: Bad TRX checksum\n");
            printf("\tExpected: %08X\tFound: %08X\n", expectedHeader->crc, currentHeader->crc);
            writeTRX(0, outFilename, expectedHeader, &currentHeader, linksys);
            retVal = -2;
        }
    }

    free(outFilename);
    free(data);
    if (retVal == -1) free(currentHeader); // If we created a brand new header (because there was none before), free it
    if (retVal != -2) free(expectedHeader); // If we re-used the original header (because there was one before, but it had an issue), don't double-free it
    return retVal;
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        int linksys = 0;
        if (argc > 2 && strcmp(argv[2], "-l") == 0)
            linksys = 1;

        char *data, *filename = argv[1];
        int size = readFile(filename, &data);
        int result = validateTRX(size, data, filename, linksys);
        if (result == 1) printf("TRX header is valid!\n");
	} else {
        printf("TRXUtil verifies the TRX header of a binary file. If it is incorrect or missing, a new file will be written to <oldfilename>.trx with a complete TRX header. Passing -l (for Linksys mode) will write out a header with a 932-byte smaller file size, which some Linksys web GUIs require for some reason. Written by Ari Weinstein on 6/26/12.\nUsage: %s <file> [-l]\n\nExample:\n%s WR1043ND_firmware.bin\n", argv[0], argv[0]);
	}
	return 0;
}


text:
"""
h2/exceptions
~~~~~~~~~~~~~

Exceptions for the HTTP/2 module.
"""

class H2Error(Exception):
    """
    The base class for all exceptions for the HTTP/2 module.
    """

class ProtocolError(H2Error):
    """
    An action was attempted in violation of the HTTP/2 protocol.
    """
    pass

class NoSuchStreamError(H2Error):
    """
    A stream-specific action referenced a stream that does not exist.
    """
    def __init__(self, stream_id):
        self.stream_id = stream_id

class FlowControlError(H2Error):
    """
    An attempted action violates flow control constraints.
    """
    pass


text:
package com.yahoo.pulsar.client.admin;

import javax.ws.rs.ClientErrorException;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;

import com.yahoo.pulsar.common.policies.data.ErrorData;

@SuppressWarnings("serial")
public class PulsarAdminException extends Exception {
    private static final int DEFAULT_STATUS_CODE = 500;

    private final String httpError;
    private final int statusCode;

    private static String getReasonFromServer(WebApplicationException e) {
        if (MediaType.APPLICATION_JSON.equals(e.getResponse().getHeaderString("Content-Type"))) {
            try {
                return e.getResponse().readEntity(ErrorData.class).reason;
            } catch (Exception ex) {
                // could not parse output to ErrorData class
                return e.getMessage();
            }
        }
        return e.getMessage();
    }

    public PulsarAdminException(ClientErrorException e) {
        super(getReasonFromServer(e), e);
        this.httpError = e.getMessage();
        this.statusCode = e.getResponse().getStatus();
    }

    public PulsarAdminException(ClientErrorException e, String message) {
        super(message, e);
        this.httpError = e.getMessage();
        this.statusCode = e.getResponse().getStatus();
    }

    public PulsarAdminException(ServerErrorException e) {
        super(getReasonFromServer(e), e);
        this.httpError = e.getMessage();
        this.statusCode = e.getResponse().getStatus();
    }

    public PulsarAdminException(ServerErrorException e, String message) {
        super(message, e);
        this.httpError = e.getMessage();
        this.statusCode = e.getResponse().getStatus();
    }

    public PulsarAdminException(Throwable t) {
        super(t);
        httpError = null;
        statusCode = DEFAULT_STATUS_CODE;
    }

    public PulsarAdminException(String message, Throwable t) {
        super(message, t);
        httpError = null;
        statusCode = DEFAULT_STATUS_CODE;
    }

    public PulsarAdminException(String message) {
        super(message);
        httpError = null;
        statusCode = DEFAULT_STATUS_CODE;
    }

    public String getHttpError() {
        return httpError;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public static class NotAuthorizedException extends PulsarAdminException {
        public NotAuthorizedException(ClientErrorException e) {
            super(e);
        }
    }

    public static class NotFoundException extends PulsarAdminException {
        public NotFoundException(ClientErrorException e) {
            super(e);
        }
    }

    public static class NotAllowedException extends PulsarAdminException {
        public NotAllowedException(ClientErrorException e) { super(e); }
    }

    public static class ConflictException extends PulsarAdminException {
        public ConflictException(ClientErrorException e) {
            super(e);
        }
    }

    public static class PreconditionFailedException extends PulsarAdminException {
        public PreconditionFailedException(ClientErrorException e) {
            super(e);
        }
    }

    public static class ServerSideErrorException extends PulsarAdminException {
        public ServerSideErrorException(ServerErrorException e) {
            super(e, "Some error occourred on the server");
        }
    }

    public static class HttpErrorException extends PulsarAdminException {
        public HttpErrorException(Exception e) {
            super(e);
        }

        public HttpErrorException(Throwable t) {
            super(t);
        }
    }

    public static class ConnectException extends PulsarAdminException {
        public ConnectException(Throwable t) {
            super(t);
        }

        public ConnectException(String message, Throwable t) {
            super(message, t);
        }
    }

    public static class GettingAuthenticationDataException extends PulsarAdminException {
        public GettingAuthenticationDataException(Throwable t) {
            super(t);
        }

        public GettingAuthenticationDataException(String msg) {
            super(msg);
        }
    }
}


text:
import DIALOG from 'mobile/dialog';
import MODEL from 'mobile/model';
import KEYBOARD from 'mobile/keyboard';

var backgroundSkin = new Skin({ fill: '#eee' });
var buttonSkin = new Skin({ fill: '#ccf' });

var buttonStyle = new Style({ color: 'blue', font: 'bold 24px', horizontal: 'center', vertical: 'middle' });
var headerStyle = new Style({ color: '#444', font: 'bold 18px', horizontal: 'center', vertical: 'middle' });

class DialogHandlerBehavior extends MODEL.DialogBehavior{
	onDescribe(query) {
		return {
            Dialog: DIALOG.Box,
            title: "What is your name?",
            action: "/traceResult",
            items: [
                {
                    Item: DIALOG.Field,
                    id: "first_name",
                    label: "First",
                },
                {
                    Item: DIALOG.Field,
                    id: "last_name",
                    label: "Last",
                },
                {
                    id: "secret",
                },
                {
                    Item: DIALOG.Caption,
                    string: query.greeting
                },
            ],
            ok: "OK",
            cancel: "Cancel",
		};
	}
}
Handler.bind("/dialog", new DialogHandlerBehavior);

Handler.bind("/traceResult", {
	onInvoke(handler, message) {
		data = parseQuery(message.query);
		for (var key in data) {
			trace(key + ": " + data[key] + "\n");
		}
	}
});

var MainScreen = Container.template($ => ({
	left: 0, right: 0, top: 0, bottom: 0, skin: backgroundSkin,
	contents: [
		Label($, { left: 0, right: 0, top: 4, style: headerStyle, string: 'Basic Dialog Sample' }),
		Label($, { height: 35, left: 25, right: 25, active: true, string: 'Show Simple Dialog', skin: buttonSkin, style: buttonStyle,
			behavior: Behavior({
				onTouchEnded(label, x, y, id, ticks) {
					var dialogData = {first_name: 'Will', greeting: 'Welcome to KinomaJS', secret: '42'};
					label.invoke(new Message("/dialog?" + serializeQuery(dialogData)));
				}
			})
		})
 	]
}));

application.behavior = new MODEL.ApplicationBehavior( application );
application.add(new MainScreen({}));


text:
package com.fsck.k9.preferences;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.fsck.k9.EmailAddressValidator;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import com.fsck.k9.preferences.Settings.BooleanSetting;
import com.fsck.k9.preferences.Settings.InvalidSettingValueException;
import com.fsck.k9.preferences.Settings.SettingsDescription;
import com.fsck.k9.preferences.Settings.SettingsUpgrader;
import com.fsck.k9.preferences.Settings.V;

class IdentitySettings {
    static final Map<String, TreeMap<Integer, SettingsDescription>> SETTINGS;
    private static final Map<Integer, SettingsUpgrader> UPGRADERS;

    static {
        Map<String, TreeMap<Integer, SettingsDescription>> s = new LinkedHashMap<>();

        /*
         * When adding new settings here, be sure to increment {@link Settings.VERSION}
         * and use that for whatever you add here.
         */

        s.put("signature", Settings.versions(
                new V(1, new SignatureSetting())
        ));
        s.put("signatureUse", Settings.versions(
                new V(1, new BooleanSetting(true))
        ));
        s.put("replyTo", Settings.versions(
                new V(1, new OptionalEmailAddressSetting())
        ));

        SETTINGS = Collections.unmodifiableMap(s);

        // noinspection MismatchedQueryAndUpdateOfCollection, this map intentionally left blank
        Map<Integer, SettingsUpgrader> u = new HashMap<>();
        UPGRADERS = Collections.unmodifiableMap(u);
    }

    static Map<String, Object> validate(int version, Map<String, String> importedSettings, boolean useDefaultValues) {
        return Settings.validate(version, SETTINGS, importedSettings, useDefaultValues);
    }

    public static Set<String> upgrade(int version, Map<String, Object> validatedSettings) {
        return Settings.upgrade(version, UPGRADERS, SETTINGS, validatedSettings);
    }

    public static Map<String, String> convert(Map<String, Object> settings) {
        return Settings.convert(settings, SETTINGS);
    }

    static Map<String, String> getIdentitySettings(Storage storage, String uuid, int identityIndex) {
        Map<String, String> result = new HashMap<>();
        String prefix = uuid + ".";
        String suffix = "." + Integer.toString(identityIndex);
        for (String key : SETTINGS.keySet()) {
            String value = storage.getString(prefix + key + suffix, null);
            if (value != null) {
                result.put(key, value);
            }
        }
        return result;
    }

    static boolean isEmailAddressValid(String email) {
        return new EmailAddressValidator().isValidAddressOnly(email);
    }

    private static class SignatureSetting extends SettingsDescription<String> {
        SignatureSetting() {
            super(null);
        }

        @Override
        public String getDefaultValue() {
            return K9.app.getResources().getString(R.string.default_signature);
        }

        @Override
        public String fromString(String value) throws InvalidSettingValueException {
            return value;
        }
    }

    private static class OptionalEmailAddressSetting extends SettingsDescription<String> {
        private EmailAddressValidator validator;

        OptionalEmailAddressSetting() {
            super(null);
            validator = new EmailAddressValidator();
        }

        @Override
        public String fromString(String value) throws InvalidSettingValueException {
            if (value != null && !validator.isValidAddressOnly(value)) {
                throw new InvalidSettingValueException();
            }
            return value;
        }

        @Override
        public String toString(String value) {
            return value;
        }

        @Override
        public String toPrettyString(String value) {
            return (value == null) ? "" : value;
        }

        @Override
        public String fromPrettyString(String value) throws InvalidSettingValueException {
            return "".equals(value) ? null : fromString(value);
        }
    }
}


text:
import Ember from 'ember';
import Analytics from '../../mixins/analytics';

function arrayEquals(arr1, arr2) {
    return arr1.length === arr2.length && arr1.reduce((acc, val, i) => acc && val === arr2[i], true);
}

function arrayStartsWith(arr, prefix) {
    return prefix.reduce((acc, val, i) => acc && val && arr[i] && val.id === arr[i].id, true);
}
/**
 * @module ember-preprints
 * @submodule components
 */

/**
 * Add discipline when creating a preprint.
 *
 * Sample usage:
 * ```handlebars
 * {{subject-picker
 *      editMode=editMode
 *      selected=subjectsList
 *      disciplineModifiedToggle=disciplineModifiedToggle
 *      save=(action 'setSubjects')
 *}}
 * ```
 * @class subject-picker
 */
export default Ember.Component.extend(Analytics, {
    store: Ember.inject.service(),
    theme: Ember.inject.service(),

    // Store the lists of subjects
    _tier1: null,
    _tier2: null,
    _tier3: null,

    // Filter the list of subjects if appropriate
    tier1FilterText: '',
    tier2FilterText: '',
    tier3FilterText: '',

    tierSorting: ['text:asc'],
    tier1Filtered: Ember.computed('tier1FilterText', '_tier1.[]', function() {
        let items = this.get('_tier1') || [];
        let filterText = this.get('tier1FilterText').toLowerCase();
        if (filterText) {
            return items.filter(item => item.get('text').toLowerCase().includes(filterText));
        }
        return items;
    }),
    tier1Sorted: Ember.computed.sort('tier1Filtered', 'tierSorting'),

    tier2Filtered: Ember.computed('tier2FilterText', '_tier2.[]', function() {
        let items = this.get('_tier2') || [];
        let filterText = this.get('tier2FilterText').toLowerCase();
        if (filterText) {
            return items.filter(item => item.get('text').toLowerCase().includes(filterText));
        }
        return items;
    }),
    tier2Sorted: Ember.computed.sort('tier2Filtered', 'tierSorting'),

    tier3Filtered: Ember.computed('tier3FilterText', '_tier3.[]', function() {
        let items = this.get('_tier3') || [];
        let filterText = this.get('tier3FilterText').toLowerCase();
        if (filterText) {
            return items.filter(item => item.get('text').toLowerCase().includes(filterText));
        }
        return items;
    }),
    tier3Sorted: Ember.computed.sort('tier3Filtered', 'tierSorting'),

    // Currently selected subjects
    selection1: null,
    selection2: null,
    selection3: null,

    querySubjects(parents = 'null', tier = 0) {
        this.get('theme.provider')
            .then(provider => provider
                .query('taxonomies', {
                    filter: {
                        parents
                    },
                    page: {
                        size: 100
                    }
                })
            )
            .then(results => this
                .set(`_tier${tier + 1}`, results.toArray())
            );
    },

    init() {
        this._super(...arguments);
        this.set('selected', []);
        this.querySubjects();
    },

    actions: {
        deselect(subject) {
            Ember.get(this, 'metrics')
                .trackEvent({
                    category: 'button',
                    action: 'click',
                    label: `Preprints - ${this.get('editMode') ? 'Edit' : 'Submit'} - Discipline Remove`
                });
            let index;
            if (subject.length === 1) {
                index = 0;
            } else {
                let parent = subject.slice(0, -1);
                index = this.get('selected').findIndex(item => item !== subject && arrayStartsWith(item, parent));
            }

            let wipe = 4; // Tiers to clear
            if (index === -1) {
                if (this.get(`selection${subject.length}`) === subject[subject.length - 1])
                    wipe = subject.length + 1;
                subject.removeAt(subject.length - 1);
            } else {
                this.get('selected').removeAt(this.get('selected').indexOf(subject));
                for (let i = 2; i < 4; i++) {
                    if (this.get(`selection${i}`) !== subject[i - 1]) continue;
                    wipe = i;
                    break;
                }
            }

            for (let i = wipe; i < 4; i++) {
                this.set(`_tier${i}`, null);
                this.set(`selection${i}`, null);
            }
            this.sendAction('save', this.get('selected'));
        },
        select(selected, tier) {
            Ember.get(this, 'metrics')
                .trackEvent({
                    category: 'button',
                    action: 'click',
                    label: `Preprints - ${this.get('editMode') ? 'Edit' : 'Submit'} - Discipline Add`
                });
            tier = parseInt(tier);
            if (this.get(`selection${tier}`) === selected) return;

            this.set(`selection${tier}`, selected);

            // Inserting the subject lol
            let index = -1;
            let selection = [...Array(tier).keys()].map(index => this.get(`selection${index + 1}`));

            // An existing tag has this prefix, and this is the lowest level of the taxonomy, so no need to fetch child results
            if (!(tier !== 3 && this.get('selected').findIndex(item => arrayStartsWith(item, selection)) !== -1)) {
                for (let i = 0; i < selection.length; i++) {
                    let sub = selection.slice(0, i + 1);
                    // "deep" equals
                    index = this.get('selected').findIndex(item => arrayEquals(item, sub));  // jshint ignore:line

                    if (index === -1) continue;

                    this.get('selected')[index].pushObjects(selection.slice(i + 1));
                    break;
                }

                if (index === -1)
                    this.get('selected').pushObject(selection);
            }

            this.sendAction('save', this.get('selected'));

            if (tier === 3) return;

            for (let i = tier + 1; i < 4; i++)
                this.set(`_tier${i}`, null);

            // TODO: Fires a network request every time clicking here, instead of only when needed?
            this.querySubjects(selected.id, tier);
        },
    }
});


text:
using Famoser.MassPass.Data.Entities.Communications.Response.Base;

namespace Famoser.MassPass.Data.Entities.Communications.Response.Authorization
{
    public class AuthorizationResponse : ApiResponse
    {
        public string Message { get; set; }
        public string Content { get; set; }
    }
}


text:
package com.lokalized;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Collections;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;

import static java.util.Objects.requireNonNull;

/**
 * Collection of utility methods for working with Maps.
 *
 * @author Mark Allen
 */
@ThreadSafe
final class Maps {
  private Maps() {
    // Non-instantiable
  }

  /**
   * Creates an immutable sorted map with the given values.
   *
   * @param mapEntries the entries for the map, may be null
   * @param <K>        the type of keys in the map
   * @param <V>        type type of values in the map
   * @return an immutable sorted map, not null
   */
  @Nonnull
  static <K, V> SortedMap<K, V> sortedMap(@Nullable MapEntry<K, V>... mapEntries) {
    if (mapEntries == null || mapEntries.length == 0)
      return Collections.emptySortedMap();

    SortedMap<K, V> sortedMap = new TreeMap<>();

    for (MapEntry<K, V> mapEntry : mapEntries)
      sortedMap.put(mapEntry.getKey(), mapEntry.getValue());

    return Collections.unmodifiableSortedMap(sortedMap);
  }

  /**
   * A representation of a map entry (key-value pair).
   *
   * @param <K> the type of key in the map entry
   * @param <V> the type of value in the map entry
   */
  @Immutable
  static class MapEntry<K, V> {
    @Nonnull
    private final K key;
    @Nonnull
    private final V value;

    /**
     * Provides a map entry with the given key and value.
     *
     * @param key   the key for the map entry, not null
     * @param value the value for the map entry, not null
     * @param <K>
     * @param <V>
     * @return a map entry, not null
     */
    @Nonnull
    public static <K, V> MapEntry<K, V> of(@Nonnull K key, @Nonnull V value) {
      requireNonNull(key);
      requireNonNull(value);

      return new MapEntry<>(key, value);
    }

    /**
     * Creates a map entry with the given key and value.
     *
     * @param key   the key for this map entry, not null
     * @param value the value for this map entry, not null
     */
    private MapEntry(@Nonnull K key, @Nonnull V value) {
      requireNonNull(key);
      requireNonNull(value);

      this.key = key;
      this.value = value;
    }

    /**
     * Generates a {@code String} representation of this object.
     *
     * @return a string representation of this object, not null
     */
    @Override
    @Nonnull
    public String toString() {
      return String.format("%s{key=%s, value=%s}", getClass().getSimpleName(), getKey(), getValue());
    }

    /**
     * Checks if this object is equal to another one.
     *
     * @param other the object to check, null returns false
     * @return true if this is equal to the other object, false otherwise
     */
    @Override
    public boolean equals(@Nullable Object other) {
      if (this == other)
        return true;

      if (other == null || !getClass().equals(other.getClass()))
        return false;

      MapEntry mapEntry = (MapEntry) other;

      return Objects.equals(getKey(), mapEntry.getKey())
          && Objects.equals(getValue(), mapEntry.getValue());
    }

    /**
     * A hash code for this object.
     *
     * @return a suitable hash code
     */
    @Override
    public int hashCode() {
      return Objects.hash(getKey(), getValue());
    }

    /**
     * The key for this map entry.
     *
     * @return the key, not null
     */
    @Nonnull
    public K getKey() {
      return key;
    }

    /**
     * The value for this map entry.
     *
     * @return the value, not null
     */
    @Nonnull
    public V getValue() {
      return value;
    }
  }
}


text:
<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2018
 */

namespace Praxigento\Downline\Observer\CustomerSaveAfterDataObject\A;

use Praxigento\Downline\Api\Service\Customer\Downline\SwitchUp\Request as ASwitchUpRequest;
use Praxigento\Downline\Repo\Data\Change\Group as EChangeGroup;
use Praxigento\Downline\Service\Customer\Downline\StickUp\Request as AStickUpRequest;

/**
 * Analyze customer group change, restructure downline tree and registry group change event.
 */
class GroupSwitch
{
    /** @var \Praxigento\Downline\Repo\Dao\Change\Group */
    private $daoChangeGroup;
    /** @var \Praxigento\Core\Api\Helper\Date */
    private $hlpDate;
    /** @var \Praxigento\Downline\Api\Helper\Group\Transition */
    private $hlpGroupTrans;
    /** @var \Praxigento\Downline\Service\Customer\Downline\StickUp */
    private $servStickUp;
    /** @var \Praxigento\Downline\Api\Service\Customer\Downline\SwitchUp */
    private $servSwitchUp;

    public function __construct(
        \Praxigento\Downline\Repo\Dao\Change\Group $daoChangeGroup,
        \Praxigento\Core\Api\Helper\Date $hlpDate,
        \Praxigento\Downline\Api\Helper\Group\Transition $hlpGroupTrans,
        \Praxigento\Downline\Api\Service\Customer\Downline\SwitchUp $servSwitchUp,
        \Praxigento\Downline\Service\Customer\Downline\StickUp $servStickUp
    ) {
        $this->daoChangeGroup = $daoChangeGroup;
        $this->hlpDate = $hlpDate;
        $this->hlpGroupTrans = $hlpGroupTrans;
        $this->servSwitchUp = $servSwitchUp;
        $this->servStickUp = $servStickUp;
    }

    /**
     * @param int $groupIdBefore
     * @param \Magento\Customer\Model\Data\Customer $customer
     * @throws \Exception
     */
    public function exec($groupIdBefore, $customer)
    {
        $groupIdAfter = $customer->getGroupId();
        if ($groupIdBefore != $groupIdAfter) {
            $custId = $customer->getId();
            $this->switchDownline($custId, $groupIdBefore, $groupIdAfter);
            $this->registerGroupChange($custId, $groupIdBefore, $groupIdAfter);
        }
    }

    /**
     * Save group change event into registry.
     *
     * @param int $custId
     * @param int $groupIdOld
     * @param int $groupIdNew
     */
    private function registerGroupChange($custId, $groupIdOld, $groupIdNew)
    {
        $data = new EChangeGroup();
        $data->setCustomerRef($custId);
        $data->setGroupOld($groupIdOld);
        $data->setGroupNew($groupIdNew);
        $dateChanged = $this->hlpDate->getUtcNowForDb();
        $data->setDateChanged($dateChanged);
        $this->daoChangeGroup->create($data);
    }

    /**
     * Change downline on group upgrade/downgrade event.
     *
     * @param int $custId
     * @param int $groupIdBefore
     * @param int $groupIdAfter
     * @throws \Exception
     */
    private function switchDownline($custId, $groupIdBefore, $groupIdAfter)
    {
        $isDowngrade = $this->hlpGroupTrans->isDowngrade($groupIdBefore, $groupIdAfter);
        if ($isDowngrade) {
            /* we need to switch all customer's children to the customer's parent */
            $req = new ASwitchUpRequest();
            $req->setCustomerId($custId);
            $this->servSwitchUp->exec($req);
        } else {
            $isUpgrade = $this->hlpGroupTrans->isUpgrade($groupIdBefore, $groupIdAfter);
            if ($isUpgrade) {
                /* we need to place customer under the first distributor in upline */
                $req = new AStickUpRequest();
                $req->setCustomerId($custId);
                $this->servStickUp->exec($req);
            }
        }
    }
}


text:
/*
 * helpers.js: Helper functions for the pinpoint web service.
 *
 * (C) 2011 Charlie Robbins
 * MIT LICENSE
 *
 */

/**
 * randomString returns a pseude-random ASCII string which contains at least the specified number of bits of entropy
 * the return value is a string of length ⌈bits/6⌉ of characters from the base64 alphabet
 * @param {int} bits: Number of bits to use for the randomString
 *
 */
var randomString = exports.randomString = function (bits) {
  var chars, rand, i, ret;

  chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  ret = '';

  // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
  while (bits > 0) {
    // 32-bit integer
    rand = Math.floor(Math.random() * 0x100000000);
    // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
    for (i = 26; i > 0 && bits > 0; i -= 6, bits -= 6) {
      ret += chars[0x3F & rand >>> i];
    }
  }

  return ret;
};


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Messages;
using DotNetCore.CAP.Serialization;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace DotNetCore.CAP.Test
{
    public class SubscribeInvokerTest
    {
        private readonly IServiceProvider _serviceProvider;

        public SubscribeInvokerTest()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging();
            serviceCollection.AddSingleton<ISerializer, JsonUtf8Serializer>();
            serviceCollection.AddSingleton<ISubscribeInvoker, SubscribeInvoker>();
            _serviceProvider = serviceCollection.BuildServiceProvider();
        }

        private ISubscribeInvoker SubscribeInvoker => _serviceProvider.GetService<ISubscribeInvoker>();

        [Fact]
        public async Task InvokeTest()
        {
            var descriptor = new ConsumerExecutorDescriptor()
            {
                Attribute = new CandidatesTopic("fake.output.integer"),
                ServiceTypeInfo = typeof(FakeSubscriber).GetTypeInfo(),
                ImplTypeInfo = typeof(FakeSubscriber).GetTypeInfo(),
                MethodInfo = typeof(FakeSubscriber).GetMethod(nameof(FakeSubscriber.OutputIntegerSub)),
                Parameters = new List<ParameterDescriptor>()
            };

            var header = new Dictionary<string, string>()
            {
                [Headers.MessageId] = SnowflakeId.Default().NextId().ToString(),
                [Headers.MessageName] = "fake.output.integer"
            };
            var message = new Message(header, null);
            var context = new ConsumerContext(descriptor, message);

            var ret = await SubscribeInvoker.InvokeAsync(context);
            Assert.Equal(int.MaxValue, ret.Result);
        }
    }

    public class FakeSubscriber : ICapSubscribe
    {
        [CapSubscribe("fake.output.integer")]
        public int OutputIntegerSub()
        {
            return int.MaxValue;
        }
    }
}


text:
package com.example.sakydpozrux.githubusers.model;

/**
 * Created by sakydpozrux on 07/08/2017.
 */

public class Repository {
    public final String name;

    public Repository(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
using System;
using System.Timers;

namespace NginxTray
{
    public class ProcessMonitor
    {
        public string ProcessName
        {
            get;
            set;
        }
        public delegate void EventHandler(object sender, EventArgs e);
        public event EventHandler OnProcessStarted;
        public event EventHandler OnProcessExited;

        private Timer timer;
        private bool processExist = false;

        public ProcessMonitor()
        {
            this.timer = new Timer();
            this.timer.Interval = 1000;
            this.timer.Elapsed += timer_Elapsed;

        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            int flag = 0;
            // 获取系统的所有进程
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
            for (int i = 0; i < processes.Length; i++)
            {
                if (String.Compare(processes[i].ProcessName, ProcessName, true) == 0)
                {
                    flag++;
                    break;
                }
            }
            if (flag > 0 && !this.processExist)
            {
                this.processExist = true;
                OnProcessStarted(this, new EventArgs());
            }
            if (flag == 0 && this.processExist)
            {
                this.processExist = false;
                OnProcessExited(this, new EventArgs());
            }
        }

        public void Start()
        {
            this.timer.Start();
        }

        public void Stop()
        {
            this.timer.Stop();
        }
    }
}