text:
#pragma once

#include <rj_param_utils/param.hpp>

namespace params {
/**
 * The base for parameter providers using ROS parameters.
 *
 * Provides useful helper methods.
 */
class BaseROS2ParamProvider : public ::params::ParamProvider {
protected:
    BaseROS2ParamProvider(const std::string& module) : ParamProvider{module} {}

    /**
     * Update the parameters provided by this object with a key/value list.
     * @param params the parameters to set. All parameters not included in this vector will be left
     * unchanged.
     * @return a success/fail result. If any parameter fails the whole operation is assumed to have
     * failed.
     */
    rcl_interfaces::msg::SetParametersResult UpdateParameters(
        const std::vector<rclcpp::Parameter>& params);

    /**
     * @brief Converts the full_name of a parameter from using double colons (::) as the namespace
     * separator to using periods (.).
     * @param full_name The full_name to convert.
     * @return The full name of the parameter in ROS2 parameter convention.
     */
    static std::string ConvertFullNameToROS2(const std::string& full_name);

    /**
     * @brief Converts the full name of a parameter from using periods (.) as the namespace separator to using double colons (::). Inverts @ref ConvertFullNameToROS2.
     * @param ros2_name The ros2 name to convert.
     * @return The full name of the parameter in ROS2 parameter convention.
     */
    static std::string ConvertFullNameFromROS2(const std::string& ros2_name);
};

}  // namespace params


text:
/* eslint-disable max-len */
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const __PWA_ENV__ = process.env.PWA_ENV;
const __PWA_PUBLIC_PATH__ = process.env.PWA_PUBLIC_PATH;
const isProd = process.env.NODE_ENV === 'production';

module.exports = {
  entry: './server/index.js',

  target: 'node',

  externals: [
    nodeExternals({ whitelist: [/\.css$/] }),
    /assetsManifest.json/,
  ],

  output: {
    path: path.resolve('./build/server'),
    publicPath: __PWA_PUBLIC_PATH__,
    filename: 'index.js',
    chunkFilename: '[name].js',
    libraryTarget: 'commonjs2',
  },

  resolve: {
    alias: {
      react: 'preact-compat',
      'react-dom': 'preact-compat',
    },
  },

  module: {
    rules: isProd ? [
      { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] },
      { test: /\.css$/, use: ['css-loader/locals', 'postcss-loader'] },
      { test: /\.(gif|png|jpe?g|svg|ico)$/i, use: [{ loader: 'file-loader', options: { name: 'images/[name].[hash:8].[ext]' } }] },
      { test: /\.(woff(2)?|ttf|otf|eot)(\?[a-z0-9=&.]+)?$/, use: [{ loader: 'url-loader', options: { limit: 1000, name: 'fonts/[name].[hash:8].[ext]' } }] },
    ] : [
      { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] },
      { test: /\.css$/, use: ['css-loader/locals', 'postcss-loader'] },
      { test: /\.(gif|png|jpe?g|svg|ico)$/i, use: [{ loader: 'file-loader', options: { name: 'images/[name].[ext]' } }] },
      { test: /\.(woff(2)?|ttf|otf|eot)(\?[a-z0-9=&.]+)?$/, use: [{ loader: 'url-loader', options: { limit: 1000, name: 'fonts/[name].[ext]' } }] },
    ],
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new CleanWebpackPlugin(['./build/server']),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isProd ? '"production"' : '"development"',
      __BROWSER__: false,
      __PWA_ENV__: JSON.stringify(__PWA_ENV__),
      __LOCAL__: __PWA_ENV__ === 'local',
    }),
    new webpack.optimize.CommonsChunkPlugin({
      children: true,
      minChunks: 2,
    }),
    ...(isProd ? [
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false,
      }),
      new webpack.HashedModuleIdsPlugin(),
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true,
          warnings: false,
        },
        mangle: {
          screw_ie8: true,
        },
        output: {
          comments: false,
          screw_ie8: true,
        },
      }),
    ] : [
      new webpack.NamedModulesPlugin(),
    ]),
  ],

  devtool: 'source-map',
};

redpajama_set_name: RedPajamaGithub


text:
package helmeili;

import aha.util.Logger;
import com.google.inject.*;
import de.grobmeier.postmark.PostmarkClient;
import helmeili.di.DevelopmentModule;
import helmeili.di.HelmeiliModule;
import helmeili.di.HerokuModule;
import helmeili.di.PostmarkModule;
import helmeili.web.SparkConfiguration;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.logging.LogManager;

import static java.util.Arrays.asList;

public class RunSpark {
    private static final Logger log = Logger.getInstance(RunSpark.class);

    public static final Collection<Module> MODULES = asList(
            new HelmeiliModule(),
            new HerokuModule(),
            new PostmarkModule()
    );

    public static final Collection<Module> DEV_MODULES = asList(
            new DevelopmentModule()
    );

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("Server shutdown")));

        setupLogging();

        final Injector injector = Guice.createInjector(selectModules());
        getSparkConfigurations(injector).forEach(SparkConfiguration::configure);

        log.info("Server launched");
    }

    private static void setupLogging() {
        removeNastyStaticLogConfigurationDoneByPostmarkClient();
        SLF4JBridgeHandler.install();
    }

    private static void removeNastyStaticLogConfigurationDoneByPostmarkClient() {
        new PostmarkClient("");
        LogManager.getLogManager().reset();
    }

    private static Collection<Module> selectModules() {
        List<Module> modules = new ArrayList<>(MODULES);
        if (isDevelopmentEnv()) {
            modules.addAll(DEV_MODULES);
        }
        return modules;
    }

    public static boolean isDevelopmentEnv() {
        return System.getenv("DEVELOPMENT") != null;
    }

    private static Collection<SparkConfiguration> getSparkConfigurations(Injector injector) {
        return injector.getInstance(Key.get(new TypeLiteral<Set<SparkConfiguration>>() {}));
    }

}


text:
package io.logmatic.android;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.util.Log;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Logger {

    public static final String TAG = "logmatic";
    private final String name;
    private final LogmaticAppender appender;
    private ArrayMap<String, JsonElement> extraFields = new ArrayMap<>();
    private boolean timestamping;
    private boolean legacyLogging;

    /* formatter and tools */
    private static final String ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    private final static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_8601, Locale.US);
    private static final Gson gson = new GsonBuilder()
            .serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    /**
     * Default constructor
     *
     * @param name          Application withName
     * @param appender      The appender
     * @param timestamping  True to enable event timestamping
     * @param legacyLogging True to add legacy (logcat) logging
     * @param extraFields   Global fields added to all events
     */
    public Logger(final @NonNull String name,
                  final @NonNull LogmaticAppender appender,
                  final boolean timestamping,
                  final boolean legacyLogging,
                  final @NonNull ArrayMap<String, JsonElement> extraFields) {

        this.name = name;
        this.appender = appender;
        this.timestamping = timestamping;
        this.legacyLogging = legacyLogging;
        this.extraFields = extraFields;
    }

    public void v(String message) {
        internalLog(Log.VERBOSE, message);
    }

    public void v(String message, Object context) {
        internalLog(Log.VERBOSE, message, context);
    }

    public void d(String message) {
        internalLog(Log.DEBUG, message);
    }

    public void d(String message, Object context) {
        internalLog(Log.DEBUG, message, context);
    }

    public void i(String message) {
        internalLog(Log.INFO, message);
    }

    public void i(String message, Object context) {
        internalLog(Log.INFO, message, context);
    }

    public void w(String message) {
        internalLog(Log.DEBUG, message);
    }

    public void w(String message, Object context) {
        internalLog(Log.DEBUG, message, context);
    }

    public void e(String message) {
        internalLog(Log.ERROR, message);
    }

    public void e(String message, Object context) {
        internalLog(Log.ERROR, message, context);
    }

    public void wtf(String message) {
        internalLog(Log.ERROR, message);
    }

    public void wtf(String message, Object context) {
        internalLog(Log.ERROR, message, context);
    }

    public Logger addField(final @NonNull String key, final @Nullable String value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Long value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Integer value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Float value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Double value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Boolean value) {
        extraFields.put(key, gson.toJsonTree(value));
        return this;
    }

    public Logger addField(final @NonNull String key, final @Nullable Date value) {
        extraFields.put(key, gson.toJsonTree(value != null ? value.getTime() : null));
        return this;
    }

    public Logger removeField(final @NonNull String key) {
        extraFields.remove(key);
        return this;
    }

    // Private methods
    private void internalLog(int level, String message) {
        internalLog(level, message, null);
    }

    private void internalLog(int level, String message, Object context) {

        // if it's enabled, log with Logcat as usual
        if (legacyLogging) {
            Log.println(level, name, message);
        }

        // instantiate a new Json object from the context
        JsonObject event = new JsonObject();

        try {
            if (context != null) {
                JsonElement root = gson.toJsonTree(context);
                if (root.isJsonObject()) event = root.getAsJsonObject();
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }

        // add extra and global fields
        final int extraFieldsCount = extraFields.size();
        for (int i = 0; i < extraFieldsCount; i++) {
            event.add(extraFields.keyAt(i), extraFields.valueAt(i));

        }

        // add mandatory fields
        event.addProperty("message", message);
        event.addProperty("severity", getLevelAsString(level));
        event.addProperty("appname", name);

        // add datetime field if it's enabled
        if (timestamping) {
            event.addProperty("date", simpleDateFormat.format(new Date()));
        }

        // send the event to the appender as string
        appender.append(gson.toJson(event));
    }

    /**
     * Simple matcher fro Logcat levels and default syslog levels
     */
    private String getLevelAsString(int level) {

        switch (level) {
            case Log.ERROR:
                return "ERROR";
            case Log.WARN:
                return "WARN";
            case Log.INFO:
                return "INFO";
            case Log.DEBUG:
                return "DEBUG";
            case Log.VERBOSE:
                return "TRACE";
            default:
                return "DEBUG";
        }
    }

    public LogmaticAppender getAppender() {
        return appender;
    }
}


text:
package com.flurry.sdk;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.os.Build.VERSION;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Display;
import android.view.WindowManager;

public class fg
{
  public static int a(int paramInt)
  {
    DisplayMetrics localDisplayMetrics = b();
    return Math.round(paramInt / localDisplayMetrics.density);
  }

  @SuppressLint({"NewApi"})
  public static Point a()
  {
    Display localDisplay = ((WindowManager)eg.a().b().getSystemService("window")).getDefaultDisplay();
    Point localPoint = new Point();
    if (Build.VERSION.SDK_INT >= 13)
    {
      localDisplay.getSize(localPoint);
      return localPoint;
    }
    localPoint.x = localDisplay.getWidth();
    localPoint.y = localDisplay.getHeight();
    return localPoint;
  }

  public static int b(int paramInt)
  {
    DisplayMetrics localDisplayMetrics = b();
    return Math.round(paramInt * localDisplayMetrics.density);
  }

  public static DisplayMetrics b()
  {
    Display localDisplay = ((WindowManager)eg.a().b().getSystemService("window")).getDefaultDisplay();
    DisplayMetrics localDisplayMetrics = new DisplayMetrics();
    localDisplay.getMetrics(localDisplayMetrics);
    return localDisplayMetrics;
  }

  public static float c()
  {
    return b().density;
  }

  public static Pair<Integer, Integer> c(int paramInt)
  {
    int i = f();
    int j = g();
    switch (paramInt)
    {
    default:
      break;
    case 2:
      return Pair.create(Integer.valueOf(j), Integer.valueOf(i));
    }
    return Pair.create(Integer.valueOf(i), Integer.valueOf(j));
  }

  public static int d()
  {
    return a().x;
  }

  public static int e()
  {
    return a().y;
  }

  public static int f()
  {
    return a(d());
  }

  public static int g()
  {
    return a(e());
  }

  public static int h()
  {
    Point localPoint = a();
    if (localPoint.x == localPoint.y)
      return 3;
    if (localPoint.x < localPoint.y)
      return 1;
    return 2;
  }

  public static Pair<Integer, Integer> i()
  {
    return Pair.create(Integer.valueOf(f()), Integer.valueOf(g()));
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.flurry.sdk.fg
 * JD-Core Version:    0.6.2
 */


text:
$(document).ready(function() {
    hideError();
    addHighscores();
    markScoresLoading();
    updateScores();
    markDevicesLoading();
    updateDevices();
    updateScores();
    setInterval(updateDevices, 30000);
    setInterval(updateScores, 180000);
});

function updateDevices() {
    $.getJSON("jeepingben.json")
    .done (function(result) {
          hideError();
        loadNewData(result);
    })
    .fail (showError);
}

function markAndUpdateDevices()
{
    markDevicesLoading();
    updateDevices();
}

function loadNewData(powerData) {
    $.each(powerData.dvcs, function() {
        if ($("#" + this.s).length === 0) {
            addDevice(this.s, this.t);
        }
        overrideStatus(this);
        $("#" + this.s + "inverterStatus").text(this.st);
        switch( this.sc)
        {
            case "Good":
                $("#" + this.s + "inverterStatus").css('color', '#588D43');
                break;
            case "Neutral":
                $("#" + this.s + "inverterStatus").css('color', 'grey');
                break;
            case "Bad":
                $("#" + this.s + "inverterStatus").css('color', '#68372B');
                break;
        }
        $("#" + this.s + "powerNow").html( "" + this.p + "W");
    if (this.t.indexOf("Inverter") !== -1) {
    if (this.x) {
        $("#" + this.s + "importExport").html("&#x21C4");
        if (this.x > 0) {
            $("#" + this.s + "importExport a").css('color', '#588D43');
        } else {
            $("#" + this.s + "importExport a").css('color', '#68372B');
        }
    }
        $("#" + this.s + "inverterTotal").html("" + (this.et / 1000.0).toFixed(1) + "Kwh");
        $("#" + this.s + "powerToday").html("" + (this.ed / 1000.0).toFixed(1) + "Kwh");
        } else {
             $("#" + this.s + "inverterTotal").html("" + (this.et / 1000.0).toFixed(1) + "Kwh");
    }
          $("#" + this.s).removeClass("loading");
    });
}

function overrideStatus(device)
{
    // If data is stale, tell the user the device is offline
    var lastupdate = new Date(Date(device.up));
    var now = new Date();
    var diff = now.getTime() - lastupdate.getTime();
    if (now.getTime() - lastupdate.getTime() > 600 * 1000) //10 minutes
    {
        device.st = "Offline";
        device.sc = "Bad";
    }
}

function updateScores() {

    $.getJSON("high-scores.json")
    .done (function(result) {
          hideError();
        loadHighScores(result);
    })
    .fail (showError);
}

function showError()
{
    $("#errormessage").show();
}
function hideError()
{
    $("#errormessage").hide();
}

function markDevicesLoading()
{
    $.each($(".rebusitem"), function(){
        $(this).addClass("loading");});
}
function markScoresLoading()
{
    $("#maxPower").addClass("loading");
    $("#topDays").addClass("loading");
}

function loadHighScores(scores) {

    $("#maxPower").empty();
    $.each(scores.best_output, function() {
        $("
" + this[0] + " " + this[1] + "W
").appendTo("#maxPower");
    });
     $("#maxPower").removeClass("loading");
    $("#topDays").empty();
    $.each(scores.best_days, function() {
        $("
" + this[0] + " " + (this[1] / 1000.0).toFixed(1) + "Kwh
").appendTo("#topDays");
    });
    $("#topDays").removeClass("loading");
}

function addDevice(serial, deviceType) {

    $("

" + deviceType + " " + serial + "" +
        "
" +
        "" +
        "Status:

" +
        "
Power:
" +
        "
Total Energy Captured:
" +
    "

" +
        "
").appendTo("#devices");

    if (deviceType.indexOf("Inverter") !== -1) {
        $("#" + serial).addClass("card-info");
        $("#" + serial + "Icon").attr('src', 'inverter.png');
        $("
Energy Captured Today:
").appendTo("#" + serial + "deviceBody");
    } else {
        $("#" + serial).addClass("card-success");
        $("#" + serial + "Icon").attr('src', 'panels.png');
    }
}

function addHighscores() {

    $("

Highest Production Days" +
        "

" +
        "Highest Power Output" +
        "

" +
        "
").appendTo("#highscores");

}


text: Hello this is my first blog


text:
layout: home
title: About
tags: [about, open science, research]
modified:
comments: true
image:
  feature: Papas_Desk.jpg
  credit: Guillaume Dumas

---

**Click ! and go directly to the french or the english version**

1. [Français](#français)
2. [English](#english)

### Français

### Ce qui me définit aujourd'hui ?

#### Un parcours interdisciplinaire à la croisée entre sciences sociales et sciences cognitives

- Chercheuse associée au ([Costech](http://www.utc.fr/costech/)/UTC)
- Docteure en sciences sociales (STS/SIC) spécialisée sur les questions d'_open access/science_ et sur l'impact du numérique sur les relations sciences/société (data science, éthique, transformations économiques et sociales).
- Diplômée de l'École Normale Supérieure et d'un Master en Neurosciences cognitives et comportementales (UPMC)

#### Un engagement dans des projets associatifs et entreprenariaux pour des sociétés numériques durables

- Consultante (praticienne-chercheuse) chez [Inno^3](https://inno3.fr/), cabinet de conseil spécialisé en _open data_, _open source_ et _open science_

- Co-fondatrice de [HackYourPhD](http://www.hackyourphd.org) désormais [HackYourResearch](http://www.hyr.science/): groupe de réflexion sur la science ouverte/ _open science_ et la prise en considération des connaissances comme communs.

#### Une approche intégrative de la production de savoirs (perspective _mind/body_)

- Co-fondatrice de l'association [Ancre des Savoirs] pour questionner la place des pratiques « bien-être» par le biais des sciences sociales et scienes cognitives

- Professeure de Yoga Sivananda avec une spécialisation en yoga pré-natal et en yoga nidra.

----

Pour en savoir plus sur mon parcours : mon CV est en ligne et tenu à jour sur Linkedin [Linkedin](https://www.linkedin.com/in/celyagrusondaniel)

## Que trouverez-vous sur ce site ?

Vous y trouverez :

- Mes activités de recherche (publications, présentations et projets en cours) ==> [ici](http://celyagd.github.io/research/)
- Mes activités associatives en lien avec l'*open science*, l'enseignement supérieur, la recherche et le numérique (évènements, présentations, etc.) ==> [là](http://celyagd.github.io/openscience/)
- Mes activités d'enseignements (MOOC, Master, etc.) [ici](http://celyagd.github.io/teaching/)
- Quelques articles de blog écrits pour différents sites (MyScienWork, HackYourPhD, Centre Virchow-Villermé) ==> par [là](http://celyagd.github.io/blog/)

### English

### What defines me today? ##

#### An interdisciplinary curriculum at the crossroads between social and cognitive sciences

- Associate Researcher at ([Costech](http://www.utc.fr/costech/)/UTC)
- Doctor of Social Sciences (STS/SIC) specializing in _open access/science_ issues and the impact of digital technology on science/society relations (data science, ethics, economic and social transformations).
- Graduate of the École Normale Supérieure and a Master's degree in Cognitive and Behavioural Neurosciences (UPMC).

#### A commitment to associative and entrepreneurial projects for sustainable digital societies

- Consultant (practitioner-researcher) at [Inno^3](https://inno3.fr/), a consulting company specialized in _open data_, _open source_ and _open science_.

- Co-founder of [HackYourPhD](http://www.hackyourphd.org) now [HackYourResearch](http://www.hyr.science/): think tank on open science and the acknowledgement of knowledge as common.

#### An integrative approach to knowledge production (mind/body perspective)

- Co-founder of the association [Ancre des Savoirs] to question the place of "well-being" practices through the social sciences and cognitive sciences.

- Sivananda Yoga teacher with a specialization in prenatal yoga and nidra yoga.

Translated with www.DeepL.com/Translator (free version)

To know more about my background : my CV is on [Linkedin](https://www.linkedin.com/in/celyagrusondaniel)

----

## What would you find on this website ?

Informations about :

- My research activities (Publications, Academic Presentation, Open Notebook...) ==> [here](http://celyagd.github.io/research/)
- My Open Science activities mainly with HackYourResearch (Events, Presentations...) ==> [there](http://celyagd.github.io/openscience/)
- My teaching coordination activities (MOOC, Master, etc.)
 ==> [here](http://celyagd.github.io/teaching/)
- A few blog articles written first for different websites (MyScienceWork, HackYourPhD, Centre Virchow-Villermé) ==> [there](http://celyagd.github.io/blog/)


text:
@interface STLocation : NSObject<STHTTPNetTaskRequestObject>

@property (nonatomic, strong) NSString *lat;
@property (nonatomic, strong) NSString *lon;
@property (nonatomic, assign) int ignoredValue;
@property (nonatomic, assign, readonly) BOOL readOnlyProperty; // Read only property will not be packed into parameters

@end


text:
import json
import logging
import os
import os.path

def load_config(config=None):
    """Loads the configuration file for rpi_twitter.

    Args:
        config (str): The location of the configuration json file. If none, it
            looks at the $RPI_TWITTER_CONFIG variable, and then
            ${XDG_CONFIG_HOME}/rpi-twitter/config, and finally
            ${HOME}/.rpitwitterrc.
    """
    logging.info("Loading config file")
    conf_file = None
    if config is not None:
        txt = "Config file passed in as a parameter: '{config}'".format(config=config)
        logging.debug(txt)
        conf_file = config

    # Try the file at $RPI_TWITTER_CONFIG
    if conf_file is None:
        logging.info("Checking $RPI_TWITTER_CONFIG")
        conf = os.getenv("RPI_TWITTER_CONFIG")
        if conf is not None and os.path.isfile(conf):
            txt = "Config file found at $RPI_TWITTER_CONFIG: '{conf}'".format(conf=conf)
            logging.debug(txt)
            conf_file = conf

    # Try ${XDG_CONFIG_HOME}/rpi-twitter/config
    if conf_file is None:
        logging.info("Checking $XDG_CONFIG_HOME")
        backup_conf = os.path.join(os.getenv("HOME"), ".config")
        txt = "Backup XDG location: '{loc}'".format(loc=backup_conf)
        logging.debug(txt)

        conf_dir = os.getenv("XDG_CONFIG_HOME", backup_conf)
        txt = "Final XDG location: '{loc}'".format(loc=conf_dir)
        logging.debug(txt)

        conf = os.path.join(conf_dir, "rpi-twitter", "config")
        txt = "Total XDG location: '{loc}'".format(loc=conf)
        logging.debug(txt)

        if os.path.isfile(conf):
            txt = "Config file found at $XDG_CONFIG_HOME/rpi-twitter/config: '{conf}'".format(conf=conf)
            logging.debug(txt)
            conf_file = conf

    # Try ${HOME}/.rpitwitterrc
    if conf_file is None:
        logging.info("Checking $HOME/.rpitwitterrc")
        conf = os.path.join(os.getenv("HOME"), ".rpitwitterrc")
        if os.path.isfile(conf):
            txt = "Config file found at $HOME/.rpitwitterrc: '{conf}'".format(conf=conf)
            logging.debug(txt)
            conf_file = conf

    # If we have failed to find the configuration file, raise an
    # IOError. Otherwise read_json() will fail with a less helpful
    # TypeError.
    if conf_file is None:
        txt = "Configuration file not found!"
        logging.error(txt)
        raise IOError(txt)

    # Return the config dictionary
    logging.info("Returning loaded config")
    return read_json(conf_file)

def read_json(file):
    """Read a JSON file and return the contents.

    Args:
        file (str): Location of the file to open.
    """
    logging.info("Opening JSON file: '{file}'".format(file=file))
    with open(file) as f:
        cont = json.load(f)

    return cont


text:
/*************************************************************************/
/*  test_basis.h                                                         */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef TEST_BASIS_H
#define TEST_BASIS_H

#include "core/math/basis.h"
#include "core/math/random_number_generator.h"

#include "tests/test_macros.h"

namespace TestBasis {

Vector3 deg_to_rad(const Vector3 &p_rotation) {
	return p_rotation / 180.0 * Math_PI;
}

Vector3 rad2deg(const Vector3 &p_rotation) {
	return p_rotation / Math_PI * 180.0;
}

String get_rot_order_name(EulerOrder ro) {
	switch (ro) {
		case EulerOrder::XYZ:
			return "XYZ";
		case EulerOrder::XZY:
			return "XZY";
		case EulerOrder::YZX:
			return "YZX";
		case EulerOrder::YXZ:
			return "YXZ";
		case EulerOrder::ZXY:
			return "ZXY";
		case EulerOrder::ZYX:
			return "ZYX";
		default:
			return "[Not supported]";
	}
}

void test_rotation(Vector3 deg_original_euler, EulerOrder rot_order) {
	// This test:
	// 1. Converts the rotation vector from deg to rad.
	// 2. Converts euler to basis.
	// 3. Converts the above basis back into euler.
	// 4. Converts the above euler into basis again.
	// 5. Compares the basis obtained in step 2 with the basis of step 4
	//
	// The conversion "basis to euler", done in the step 3, may be different from
	// the original euler, even if the final rotation are the same.
	// This happens because there are more ways to represents the same rotation,
	// both valid, using eulers.
	// For this reason is necessary to convert that euler back to basis and finally
	// compares it.
	//
	// In this way we can assert that both functions: basis to euler / euler to basis
	// are correct.

	// Euler to rotation
	const Vector3 original_euler = deg_to_rad(deg_original_euler);
	const Basis to_rotation = Basis::from_euler(original_euler, rot_order);

	// Euler from rotation
	const Vector3 euler_from_rotation = to_rotation.get_euler(rot_order);
	const Basis rotation_from_computed_euler = Basis::from_euler(euler_from_rotation, rot_order);

	Basis res = to_rotation.inverse() * rotation_from_computed_euler;

	CHECK_MESSAGE((res.get_column(0) - Vector3(1.0, 0.0, 0.0)).length() <= 0.1, vformat("Fail due to X %s\n", String(res.get_column(0))).utf8().ptr());
	CHECK_MESSAGE((res.get_column(1) - Vector3(0.0, 1.0, 0.0)).length() <= 0.1, vformat("Fail due to Y %s\n", String(res.get_column(1))).utf8().ptr());
	CHECK_MESSAGE((res.get_column(2) - Vector3(0.0, 0.0, 1.0)).length() <= 0.1, vformat("Fail due to Z %s\n", String(res.get_column(2))).utf8().ptr());

	// Double check `to_rotation` decomposing with XYZ rotation order.
	const Vector3 euler_xyz_from_rotation = to_rotation.get_euler(EulerOrder::XYZ);
	Basis rotation_from_xyz_computed_euler = Basis::from_euler(euler_xyz_from_rotation, EulerOrder::XYZ);

	res = to_rotation.inverse() * rotation_from_xyz_computed_euler;

	CHECK_MESSAGE((res.get_column(0) - Vector3(1.0, 0.0, 0.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to X %s\n", String(res.get_column(0))).utf8().ptr());
	CHECK_MESSAGE((res.get_column(1) - Vector3(0.0, 1.0, 0.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to Y %s\n", String(res.get_column(1))).utf8().ptr());
	CHECK_MESSAGE((res.get_column(2) - Vector3(0.0, 0.0, 1.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to Z %s\n", String(res.get_column(2))).utf8().ptr());

	INFO(vformat("Rotation order: %s\n.", get_rot_order_name(rot_order)).utf8().ptr());
	INFO(vformat("Original Rotation: %s\n", String(deg_original_euler)).utf8().ptr());
	INFO(vformat("Quaternion to rotation order: %s\n", String(rad2deg(euler_from_rotation))).utf8().ptr());
}

TEST_CASE("[Basis] Euler conversions") {
	Vector<EulerOrder> euler_order_to_test;
	euler_order_to_test.push_back(EulerOrder::XYZ);
	euler_order_to_test.push_back(EulerOrder::XZY);
	euler_order_to_test.push_back(EulerOrder::YZX);
	euler_order_to_test.push_back(EulerOrder::YXZ);
	euler_order_to_test.push_back(EulerOrder::ZXY);
	euler_order_to_test.push_back(EulerOrder::ZYX);

	Vector<Vector3> vectors_to_test;

	// Test the special cases.
	vectors_to_test.push_back(Vector3(0.0, 0.0, 0.0));
	vectors_to_test.push_back(Vector3(0.5, 0.5, 0.5));
	vectors_to_test.push_back(Vector3(-0.5, -0.5, -0.5));
	vectors_to_test.push_back(Vector3(40.0, 40.0, 40.0));
	vectors_to_test.push_back(Vector3(-40.0, -40.0, -40.0));
	vectors_to_test.push_back(Vector3(0.0, 0.0, -90.0));
	vectors_to_test.push_back(Vector3(0.0, -90.0, 0.0));
	vectors_to_test.push_back(Vector3(-90.0, 0.0, 0.0));
	vectors_to_test.push_back(Vector3(0.0, 0.0, 90.0));
	vectors_to_test.push_back(Vector3(0.0, 90.0, 0.0));
	vectors_to_test.push_back(Vector3(90.0, 0.0, 0.0));
	vectors_to_test.push_back(Vector3(0.0, 0.0, -30.0));
	vectors_to_test.push_back(Vector3(0.0, -30.0, 0.0));
	vectors_to_test.push_back(Vector3(-30.0, 0.0, 0.0));
	vectors_to_test.push_back(Vector3(0.0, 0.0, 30.0));
	vectors_to_test.push_back(Vector3(0.0, 30.0, 0.0));
	vectors_to_test.push_back(Vector3(30.0, 0.0, 0.0));
	vectors_to_test.push_back(Vector3(0.5, 50.0, 20.0));
	vectors_to_test.push_back(Vector3(-0.5, -50.0, -20.0));
	vectors_to_test.push_back(Vector3(0.5, 0.0, 90.0));
	vectors_to_test.push_back(Vector3(0.5, 0.0, -90.0));
	vectors_to_test.push_back(Vector3(360.0, 360.0, 360.0));
	vectors_to_test.push_back(Vector3(-360.0, -360.0, -360.0));
	vectors_to_test.push_back(Vector3(-90.0, 60.0, -90.0));
	vectors_to_test.push_back(Vector3(90.0, 60.0, -90.0));
	vectors_to_test.push_back(Vector3(90.0, -60.0, -90.0));
	vectors_to_test.push_back(Vector3(-90.0, -60.0, -90.0));
	vectors_to_test.push_back(Vector3(-90.0, 60.0, 90.0));
	vectors_to_test.push_back(Vector3(90.0, 60.0, 90.0));
	vectors_to_test.push_back(Vector3(90.0, -60.0, 90.0));
	vectors_to_test.push_back(Vector3(-90.0, -60.0, 90.0));
	vectors_to_test.push_back(Vector3(60.0, 90.0, -40.0));
	vectors_to_test.push_back(Vector3(60.0, -90.0, -40.0));
	vectors_to_test.push_back(Vector3(-60.0, -90.0, -40.0));
	vectors_to_test.push_back(Vector3(-60.0, 90.0, 40.0));
	vectors_to_test.push_back(Vector3(60.0, 90.0, 40.0));
	vectors_to_test.push_back(Vector3(60.0, -90.0, 40.0));
	vectors_to_test.push_back(Vector3(-60.0, -90.0, 40.0));
	vectors_to_test.push_back(Vector3(-90.0, 90.0, -90.0));
	vectors_to_test.push_back(Vector3(90.0, 90.0, -90.0));
	vectors_to_test.push_back(Vector3(90.0, -90.0, -90.0));
	vectors_to_test.push_back(Vector3(-90.0, -90.0, -90.0));
	vectors_to_test.push_back(Vector3(-90.0, 90.0, 90.0));
	vectors_to_test.push_back(Vector3(90.0, 90.0, 90.0));
	vectors_to_test.push_back(Vector3(90.0, -90.0, 90.0));
	vectors_to_test.push_back(Vector3(20.0, 150.0, 30.0));
	vectors_to_test.push_back(Vector3(20.0, -150.0, 30.0));
	vectors_to_test.push_back(Vector3(-120.0, -150.0, 30.0));
	vectors_to_test.push_back(Vector3(-120.0, -150.0, -130.0));
	vectors_to_test.push_back(Vector3(120.0, -150.0, -130.0));
	vectors_to_test.push_back(Vector3(120.0, 150.0, -130.0));
	vectors_to_test.push_back(Vector3(120.0, 150.0, 130.0));

	for (int h = 0; h < euler_order_to_test.size(); h += 1) {
		for (int i = 0; i < vectors_to_test.size(); i += 1) {
			test_rotation(vectors_to_test[i], euler_order_to_test[h]);
		}
	}
}

TEST_CASE("[Stress][Basis] Euler conversions") {
	Vector<EulerOrder> euler_order_to_test;
	euler_order_to_test.push_back(EulerOrder::XYZ);
	euler_order_to_test.push_back(EulerOrder::XZY);
	euler_order_to_test.push_back(EulerOrder::YZX);
	euler_order_to_test.push_back(EulerOrder::YXZ);
	euler_order_to_test.push_back(EulerOrder::ZXY);
	euler_order_to_test.push_back(EulerOrder::ZYX);

	Vector<Vector3> vectors_to_test;
	// Add 1000 random vectors with weirds numbers.
	RandomNumberGenerator rng;
	for (int _ = 0; _ < 1000; _ += 1) {
		vectors_to_test.push_back(Vector3(
				rng.randf_range(-1800, 1800),
				rng.randf_range(-1800, 1800),
				rng.randf_range(-1800, 1800)));
	}

	for (int h = 0; h < euler_order_to_test.size(); h += 1) {
		for (int i = 0; i < vectors_to_test.size(); i += 1) {
			test_rotation(vectors_to_test[i], euler_order_to_test[h]);
		}
	}
}

TEST_CASE("[Basis] Set axis angle") {
	Vector3 axis;
	real_t angle;
	real_t pi = (real_t)Math_PI;

	// Testing the singularity when the angle is 0°.
	Basis identity(1, 0, 0, 0, 1, 0, 0, 0, 1);
	identity.get_axis_angle(axis, angle);
	CHECK(angle == 0);

	// Testing the singularity when the angle is 180°.
	Basis singularityPi(-1, 0, 0, 0, 1, 0, 0, 0, -1);
	singularityPi.get_axis_angle(axis, angle);
	CHECK(angle == doctest::Approx(pi));

	// Testing reversing the an axis (of an 30° angle).
	float cos30deg = Math::cos(Math::deg_to_rad((real_t)30.0));
	Basis z_positive(cos30deg, -0.5, 0, 0.5, cos30deg, 0, 0, 0, 1);
	Basis z_negative(cos30deg, 0.5, 0, -0.5, cos30deg, 0, 0, 0, 1);

	z_positive.get_axis_angle(axis, angle);
	CHECK(angle == doctest::Approx(Math::deg_to_rad((real_t)30.0)));
	CHECK(axis == Vector3(0, 0, 1));

	z_negative.get_axis_angle(axis, angle);
	CHECK(angle == doctest::Approx(Math::deg_to_rad((real_t)30.0)));
	CHECK(axis == Vector3(0, 0, -1));

	// Testing a rotation of 90° on x-y-z.
	Basis x90deg(1, 0, 0, 0, 0, -1, 0, 1, 0);
	x90deg.get_axis_angle(axis, angle);
	CHECK(angle == doctest::Approx(pi / (real_t)2));
	CHECK(axis == Vector3(1, 0, 0));

	Basis y90deg(0, 0, 1, 0, 1, 0, -1, 0, 0);
	y90deg.get_axis_angle(axis, angle);
	CHECK(axis == Vector3(0, 1, 0));

	Basis z90deg(0, -1, 0, 1, 0, 0, 0, 0, 1);
	z90deg.get_axis_angle(axis, angle);
	CHECK(axis == Vector3(0, 0, 1));

	// Regression test: checks that the method returns a small angle (not 0).
	Basis tiny(1, 0, 0, 0, 0.9999995, -0.001, 0, 001, 0.9999995); // The min angle possible with float is 0.001rad.
	tiny.get_axis_angle(axis, angle);
	CHECK(angle == doctest::Approx(0.001).epsilon(0.0001));

	// Regression test: checks that the method returns an angle which is a number (not NaN)
	Basis bugNan(1.00000024, 0, 0.000100001693, 0, 1, 0, -0.000100009143, 0, 1.00000024);
	bugNan.get_axis_angle(axis, angle);
	CHECK(!Math::is_nan(angle));
}

TEST_CASE("[Basis] Finite number checks") {
	const Vector3 x(0, 1, 2);
	const Vector3 infinite(NAN, NAN, NAN);

	CHECK_MESSAGE(
			Basis(x, x, x).is_finite(),
			"Basis with all components finite should be finite");

	CHECK_FALSE_MESSAGE(
			Basis(infinite, x, x).is_finite(),
			"Basis with one component infinite should not be finite.");
	CHECK_FALSE_MESSAGE(
			Basis(x, infinite, x).is_finite(),
			"Basis with one component infinite should not be finite.");
	CHECK_FALSE_MESSAGE(
			Basis(x, x, infinite).is_finite(),
			"Basis with one component infinite should not be finite.");

	CHECK_FALSE_MESSAGE(
			Basis(infinite, infinite, x).is_finite(),
			"Basis with two components infinite should not be finite.");
	CHECK_FALSE_MESSAGE(
			Basis(infinite, x, infinite).is_finite(),
			"Basis with two components infinite should not be finite.");
	CHECK_FALSE_MESSAGE(
			Basis(x, infinite, infinite).is_finite(),
			"Basis with two components infinite should not be finite.");

	CHECK_FALSE_MESSAGE(
			Basis(infinite, infinite, infinite).is_finite(),
			"Basis with three components infinite should not be finite.");
}

} // namespace TestBasis

#endif // TEST_BASIS_H


text:
using node::SocketAddress;

TEST(SocketAddress, SocketAddress) {
  CHECK(SocketAddress::is_numeric_host("123.123.123.123"));
  CHECK(!SocketAddress::is_numeric_host("localhost"));

  sockaddr_storage storage;
  sockaddr_storage storage2;
  SocketAddress::ToSockAddr(AF_INET, "123.123.123.123", 443, &storage);
  SocketAddress::ToSockAddr(AF_INET, "1.1.1.1", 80, &storage2);

  SocketAddress addr(reinterpret_cast<const sockaddr*>(&storage));
  SocketAddress addr2(reinterpret_cast<const sockaddr*>(&storage2));

  CHECK_EQ(addr.length(), sizeof(sockaddr_in));
  CHECK_EQ(addr.family(), AF_INET);
  CHECK_EQ(addr.address(), "123.123.123.123");
  CHECK_EQ(addr.port(), 443);

  addr.set_flow_label(12345);
  CHECK_EQ(addr.flow_label(), 0);

  CHECK_NE(addr, addr2);
  CHECK_EQ(addr, addr);

  CHECK_EQ(SocketAddress::Hash()(addr), SocketAddress::Hash()(addr));
  CHECK_NE(SocketAddress::Hash()(addr), SocketAddress::Hash()(addr2));

  addr.Update(reinterpret_cast<uint8_t*>(&storage2), sizeof(sockaddr_in));
  CHECK_EQ(addr.length(), sizeof(sockaddr_in));
  CHECK_EQ(addr.family(), AF_INET);
  CHECK_EQ(addr.address(), "1.1.1.1");
  CHECK_EQ(addr.port(), 80);

  SocketAddress::Map<size_t> map;
  map[addr]++;
  map[addr]++;
  CHECK_EQ(map[addr], 2);
}

TEST(SocketAddress, SocketAddressIPv6) {
  sockaddr_storage storage;
  SocketAddress::ToSockAddr(AF_INET6, "::1", 443, &storage);

  SocketAddress addr(reinterpret_cast<const sockaddr*>(&storage));

  CHECK_EQ(addr.length(), sizeof(sockaddr_in6));
  CHECK_EQ(addr.family(), AF_INET6);
  CHECK_EQ(addr.address(), "::1");
  CHECK_EQ(addr.port(), 443);

  addr.set_flow_label(12345);
  CHECK_EQ(addr.flow_label(), 12345);
}


text:
stage: Plan
group: Project Management
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#designated-technical-writers
---

# Issue Boards API

Every API call to boards must be authenticated.

If a user is not a member of a project and the project is private, a `GET`
request on that project will result to a `404` status code.

## Project Board

Lists Issue Boards in the given project.

```plaintext
GET /projects/:id/boards
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |

```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards"
```

Example response:

```json
[
  {
    "id" : 1,
    "project": {
      "id": 5,
      "name": "Diaspora Project Site",
      "name_with_namespace": "Diaspora / Diaspora Project Site",
      "path": "diaspora-project-site",
      "path_with_namespace": "diaspora/diaspora-project-site",
      "http_url_to_repo": "http://example.com/diaspora/diaspora-project-site.git",
      "web_url": "http://example.com/diaspora/diaspora-project-site"
    },
    "milestone":   {
      "id": 12,
      "title": "10.0"
    },
    "lists" : [
      {
        "id" : 1,
        "label" : {
          "name" : "Testing",
          "color" : "#F0AD4E",
          "description" : null
        },
        "position" : 1,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric": null
      },
      {
        "id" : 2,
        "label" : {
          "name" : "Ready",
          "color" : "#FF0000",
          "description" : null
        },
        "position" : 2,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      },
      {
        "id" : 3,
        "label" : {
          "name" : "Production",
          "color" : "#FF5F00",
          "description" : null
        },
        "position" : 3,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      }
    ]
  }
]
```

## Single board

Get a single board.

```plaintext
GET /projects/:id/boards/:board_id
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |

```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1"
```

Example response:

```json
  {
    "id": 1,
    "name": "project issue board",
    "project": {
      "id": 5,
      "name": "Diaspora Project Site",
      "name_with_namespace": "Diaspora / Diaspora Project Site",
      "path": "diaspora-project-site",
      "path_with_namespace": "diaspora/diaspora-project-site",
      "http_url_to_repo": "http://example.com/diaspora/diaspora-project-site.git",
      "web_url": "http://example.com/diaspora/diaspora-project-site"
    },
    "milestone":   {
      "id": 12,
      "title": "10.0"
    },
    "lists" : [
      {
        "id" : 1,
        "label" : {
          "name" : "Testing",
          "color" : "#F0AD4E",
          "description" : null
        },
        "position" : 1,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      },
      {
        "id" : 2,
        "label" : {
          "name" : "Ready",
          "color" : "#FF0000",
          "description" : null
        },
        "position" : 2,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      },
      {
        "id" : 3,
        "label" : {
          "name" : "Production",
          "color" : "#FF5F00",
          "description" : null
        },
        "position" : 3,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      }
    ]
  }
```

## Create a board **(STARTER)**

Creates a board.

```plaintext
POST /projects/:id/boards
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `name` | string | yes | The name of the new board |

```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards?name=newboard"
```

Example response:

```json
  {
    "id": 1,
    "project": {
      "id": 5,
      "name": "Diaspora Project Site",
      "name_with_namespace": "Diaspora / Diaspora Project Site",
      "path": "diaspora-project-site",
      "path_with_namespace": "diaspora/diaspora-project-site",
      "http_url_to_repo": "http://example.com/diaspora/diaspora-project-site.git",
      "web_url": "http://example.com/diaspora/diaspora-project-site"
    },
    "name": "newboard",
    "milestone":   {
      "id": 12
      "title": "10.0"
    },
    "lists" : [
      {
        "id" : 1,
        "label" : {
          "name" : "Testing",
          "color" : "#F0AD4E",
          "description" : null
        },
        "position" : 1,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      },
      {
        "id" : 2,
        "label" : {
          "name" : "Ready",
          "color" : "#FF0000",
          "description" : null
        },
        "position" : 2,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      },
      {
        "id" : 3,
        "label" : {
          "name" : "Production",
          "color" : "#FF5F00",
          "description" : null
        },
        "position" : 3,
        "max_issue_count": 0,
        "max_issue_weight": 0,
        "limit_metric":  null
      }
    ]
  }
```

## Update a board **(STARTER)**

> [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/5954) in [GitLab Starter](https://about.gitlab.com/pricing/) 11.1.

Updates a board.

```plaintext
PUT /projects/:id/boards/:board_id
```

| Attribute           | Type           | Required | Description |
| ------------------- | -------------- | -------- | ----------- |
| `id`                | integer/string | yes      | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id`          | integer        | yes      | The ID of a board |
| `name`              | string         | no       | The new name of the board |
| `assignee_id`       | integer        | no       | The assignee the board should be scoped to |
| `milestone_id`      | integer        | no       | The milestone the board should be scoped to |
| `labels`            | string         | no       | Comma-separated list of label names which the board should be scoped to |
| `weight`            | integer        | no       | The weight range from 0 to 9, to which the board should be scoped to |

```shell
curl --request PUT --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1?name=new_name&milestone_id=43&assignee_id=1&labels=Doing&weight=4"
```

Example response:

```json
  {
    "id": 1,
    "project": {
      "id": 5,
      "name": "Diaspora Project Site",
      "name_with_namespace": "Diaspora / Diaspora Project Site",
      "path": "diaspora-project-site",
      "path_with_namespace": "diaspora/diaspora-project-site",
      "created_at": "2018-07-03T05:48:49.982Z",
      "default_branch": null,
      "tag_list": [],
      "ssh_url_to_repo": "ssh://user@example.com/diaspora/diaspora-project-site.git",
      "http_url_to_repo": "http://example.com/diaspora/diaspora-project-site.git",
      "web_url": "http://example.com/diaspora/diaspora-project-site",
      "readme_url": null,
      "avatar_url": null,
      "star_count": 0,
      "forks_count": 0,
      "last_activity_at": "2018-07-03T05:48:49.982Z"
    },
    "lists": [],
    "name": "new_name",
    "group": null,
    "milestone": {
      "id": 43,
      "iid": 1,
      "project_id": 15,
      "title": "Milestone 1",
      "description": "Milestone 1 desc",
      "state": "active",
      "created_at": "2018-07-03T06:36:42.618Z",
      "updated_at": "2018-07-03T06:36:42.618Z",
      "due_date": null,
      "start_date": null,
      "web_url": "http://example.com/root/board1/milestones/1"
    },
    "assignee": {
      "id": 1,
      "name": "Administrator",
      "username": "root",
      "state": "active",
      "avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
      "web_url": "http://example.com/root"
    },
    "labels": [{
      "id": 10,
      "name": "Doing",
      "color": "#5CB85C",
      "description": null
    }],
    "weight": 4
  }
```

## Delete a board **(STARTER)**

Deletes a board.

```plaintext
DELETE /projects/:id/boards/:board_id
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |

```shell
curl --request DELETE --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1"
```

## List board lists

Get a list of the board's lists.
Does not include `open` and `closed` lists

```plaintext
GET /projects/:id/boards/:board_id/lists
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |

```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1/lists"
```

Example response:

```json
[
  {
    "id" : 1,
    "label" : {
      "name" : "Testing",
      "color" : "#F0AD4E",
      "description" : null
    },
    "position" : 1,
    "max_issue_count": 0,
    "max_issue_weight": 0,
    "limit_metric":  null
  },
  {
    "id" : 2,
    "label" : {
      "name" : "Ready",
      "color" : "#FF0000",
      "description" : null
    },
    "position" : 2,
    "max_issue_count": 0,
    "max_issue_weight": 0,
    "limit_metric":  null
  },
  {
    "id" : 3,
    "label" : {
      "name" : "Production",
      "color" : "#FF5F00",
      "description" : null
    },
    "position" : 3,
    "max_issue_count": 0,
    "max_issue_weight": 0,
    "limit_metric":  null
  }
]
```

## Single board list

Get a single board list.

```plaintext
GET /projects/:id/boards/:board_id/lists/:list_id
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |
| `list_id`| integer | yes | The ID of a board's list |

```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1/lists/1"
```

Example response:

```json
{
  "id" : 1,
  "label" : {
    "name" : "Testing",
    "color" : "#F0AD4E",
    "description" : null
  },
  "position" : 1,
  "max_issue_count": 0,
  "max_issue_weight": 0,
  "limit_metric":  null
}
```

## New board list

Creates a new Issue Board list.

```plaintext
POST /projects/:id/boards/:board_id/lists
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |
| `label_id` | integer | no | The ID of a label |
| `assignee_id` **(PREMIUM)** | integer | no | The ID of a user |
| `milestone_id` **(PREMIUM)** | integer | no | The ID of a milestone |

NOTE: **Note:**
Label, assignee and milestone arguments are mutually exclusive,
that is, only one of them are accepted in a request.
Check the [Issue Board docs](../user/project/issue_board.md#summary-of-features-per-tier)
for more information regarding the required license for each list type.

```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1/lists?label_id=5"
```

Example response:

```json
{
  "id" : 1,
  "label" : {
    "name" : "Testing",
    "color" : "#F0AD4E",
    "description" : null
  },
  "position" : 1,
  "max_issue_count": 0,
  "max_issue_weight": 0,
  "limit_metric":  null
}
```

## Edit board list

Updates an existing Issue Board list. This call is used to change list position.

```plaintext
PUT /projects/:id/boards/:board_id/lists/:list_id
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |
| `list_id` | integer | yes | The ID of a board's list |
| `position` | integer | yes | The position of the list |

```shell
curl --request PUT --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1/lists/1?position=2"
```

Example response:

```json
{
  "id" : 1,
  "label" : {
    "name" : "Testing",
    "color" : "#F0AD4E",
    "description" : null
  },
  "position" : 1,
  "max_issue_count": 0,
  "max_issue_weight": 0,
  "limit_metric":  null
}
```

## Delete a board list

Only for admins and project owners. Deletes the board list in question.

```plaintext
DELETE /projects/:id/boards/:board_id/lists/:list_id
```

| Attribute | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `board_id` | integer | yes | The ID of a board |
| `list_id` | integer | yes | The ID of a board's list |

```shell
curl --request DELETE --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/boards/1/lists/1"
```


text:
use iron::{Iron, IronResult, Listening, status};
use iron::error::HttpResult;
use iron::response::Response;
#[cfg(feature = "gzip")]
use iron::response::WriteBody;
use iron::request::Request;
use iron::middleware::Handler;
use iron::mime::Mime;

use sysinfo::{System, SystemExt};

#[cfg(feature = "gzip")]
use flate2::Compression;
#[cfg(feature = "gzip")]
use flate2::write::GzEncoder;

use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::{Duration, SystemTime};
#[cfg(feature = "gzip")]
use std::io::{self, Write};

use SysinfoExt;
use serde_json;

const INDEX_HTML: &'static [u8] = include_bytes!("index.html");
const FAVICON: &'static [u8] = include_bytes!("../resources/favicon.ico");
const REFRESH_DELAY: u64 = 60 * 10; // 10 minutes

/// Simple wrapper to get gzip compressed output on string types.
#[cfg(feature = "gzip")]
struct GzipContent(Box<WriteBody>);

#[cfg(feature = "gzip")]
impl WriteBody for GzipContent {
    fn write_body(&mut self, w: &mut Write) -> io::Result<()> {
        let mut w = GzEncoder::new(w, Compression::default());
        self.0.write_body(&mut w)?;
        w.finish().map(|_| ())
    }
}

struct SysinfoIronHandler(Arc<DataHandler>);

struct DataHandler {
    system: RwLock<System>,
    last_connection: Mutex<SystemTime>,
    json_output: RwLock<String>,
}

impl DataHandler {
    fn can_update_system_info(&self) -> bool {
        SystemTime::now().duration_since(*self.last_connection.lock().unwrap())
                         .unwrap()
                         .as_secs() < REFRESH_DELAY
    }

    fn update_last_connection(&self) {
        *self.last_connection.lock().unwrap() = SystemTime::now();
    }
}

#[cfg(feature = "gzip")]
macro_rules! return_gzip_or_not {
    ($req:expr, $content:expr, $typ:expr) => {{
        let mut use_gzip = false;

        if let Some(raw_accept_encoding) = $req.headers.get_raw("accept-encoding") {
            for accept_encoding in raw_accept_encoding {
                match ::std::str::from_utf8(accept_encoding).map(|s| s.to_lowercase()) {
                    Ok(ref s) if s.contains("gzip") => {
                        use_gzip = true;
                        break;
                    }
                    _ => continue,
                }
            }
        }
        if !use_gzip {
            Ok(Response::with((status::Ok, $typ.parse::<Mime>().unwrap(), $content)))
        } else {
            use iron::headers::{ContentType, ContentEncoding, Encoding};
            let mut res = Response::new();
            res.status = Some(status::Ok);
            res.body = Some(Box::new(GzipContent(Box::new($content))));
            res.headers.set(ContentType($typ.parse::<Mime>().unwrap()));
            res.headers.set(ContentEncoding(vec![Encoding::Gzip]));
            Ok(res)
        }
    }}
}

#[cfg(not(feature = "gzip"))]
macro_rules! return_gzip_or_not {
    ($req:expr, $content:expr, $typ:expr) => {{
        Ok(Response::with((status::Ok, $typ.parse::<Mime>().unwrap(), $content)))
    }}
}

impl Handler for SysinfoIronHandler {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        match match req.url.path().last() {
            Some(path) => {
                if *path == "" {
                    1
                } else if *path == "favicon.ico" {
                    2
                } else {
                    3
                }
            }
            None => 0,
        } {
            1 => return_gzip_or_not!(req, INDEX_HTML, "text/html"),
            2 => return_gzip_or_not!(req, FAVICON, "image/x-icon"),
            3 => {
                self.0.update_last_connection();
                return_gzip_or_not!(req,
                                    self.0.json_output.read().unwrap().clone(),
                                    "application/json")
            }
            _ => Ok(Response::with((status::NotFound, "Not found"))),
        }
    }
}

pub fn start_web_server(sock_addr: Option<String>) -> HttpResult<Listening> {
    let data_handler = Arc::new(DataHandler {
        system: RwLock::new(System::new()),
        last_connection: Mutex::new(SystemTime::now()),
        json_output: RwLock::new(String::from("[]")),
    });
    let data_handler_clone = data_handler.clone();
    thread::spawn(move || {
        let mut sleeping = false;
        loop {
            if data_handler_clone.can_update_system_info() {
                {
                    let mut system = data_handler_clone.system.write().unwrap();
                    system.refresh_all();
                    // refresh it twice to provide accurate information after wake up
                    if sleeping {
                        system.refresh_all();
                        sleeping = false;
                    }
                    let sysinfo = SysinfoExt::new(&system);
                    let mut json_output = data_handler_clone.json_output.write().unwrap();
                    json_output.clear();
                    use std::fmt::Write;
                    json_output.write_str(&serde_json::to_string(&sysinfo)
                                          .unwrap_or(String::from("[]"))).unwrap();
                }
                thread::sleep(Duration::new(5, 0));
            } else {
                // If we don't need to refresh the system information, we can sleep a lot less.
                thread::sleep(Duration::from_millis(500));
                sleeping = true;
            }
        }
    });
    let mut iron = Iron::new(SysinfoIronHandler(data_handler));
    iron.threads = 4;
    let ret = iron.http(sock_addr.unwrap_or("localhost:3000".to_owned()));
    if ret.is_ok() {
        println!("Started server on port 3000");
    }
    ret
}


text:
import time
import unittest

import config
import node

LEADER = 1
ROUTER = 2

class Cert_5_8_2_KeyIncrement(unittest.TestCase):
    def setUp(self):
        self.simulator = config.create_default_simulator()

        self.nodes = {}
        for i in range(1,3):
            self.nodes[i] = node.Node(i, simulator=self.simulator)

        self.nodes[LEADER].set_panid(0xface)
        self.nodes[LEADER].set_mode('rsdn')
        self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64())
        self.nodes[LEADER].set_key_switch_guardtime(0)
        self.nodes[LEADER].enable_whitelist()

        self.nodes[ROUTER].set_panid(0xface)
        self.nodes[ROUTER].set_mode('rsdn')
        self.nodes[ROUTER].add_whitelist(self.nodes[LEADER].get_addr64())
        self.nodes[ROUTER].enable_whitelist()
        self.nodes[ROUTER].set_key_switch_guardtime(0)
        self.nodes[ROUTER].set_router_selection_jitter(1)

    def tearDown(self):
        for node in list(self.nodes.values()):
            node.stop()
        del self.nodes
        del self.simulator

    def test(self):
        self.nodes[LEADER].start()
        self.simulator.go(4)
        self.assertEqual(self.nodes[LEADER].get_state(), "leader")

        self.nodes[ROUTER].start()
        self.simulator.go(5)
        self.assertEqual(self.nodes[ROUTER].get_state(), "router")

        addrs = self.nodes[ROUTER].get_addrs()
        for addr in addrs:
            self.assertTrue(self.nodes[LEADER].ping(addr))

        key_sequence_counter = self.nodes[LEADER].get_key_sequence_counter()
        self.nodes[LEADER].set_key_sequence_counter(key_sequence_counter + 1)

        addrs = self.nodes[ROUTER].get_addrs()
        for addr in addrs:
            self.assertTrue(self.nodes[LEADER].ping(addr))

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


text:
int
main(int argc, char** argv) {
  if (argc < 4) {
    fprintf(stderr, "Usage: %s <auth-secret> <receiver-private> <message>",
            argv[0]);
    return 2;
  }

  int err = 0;
  uint8_t* payload = NULL;
  uint8_t* plaintext = NULL;

  uint8_t authSecret[ECE_WEBPUSH_AUTH_SECRET_LENGTH];
  if (!ece_base64url_decode(argv[1], strlen(argv[1]),
                            ECE_BASE64URL_REJECT_PADDING, authSecret,
                            ECE_WEBPUSH_AUTH_SECRET_LENGTH)) {
    fprintf(stderr, "Error: Failed to Base64url-decode auth secret\n");
    goto error;
  }
  uint8_t rawRecvPrivKey[ECE_WEBPUSH_PRIVATE_KEY_LENGTH];
  if (!ece_base64url_decode(argv[2], strlen(argv[2]),
                            ECE_BASE64URL_REJECT_PADDING, rawRecvPrivKey,
                            ECE_WEBPUSH_PRIVATE_KEY_LENGTH)) {
    fprintf(stderr, "Error: Failed to Base64url-decode private key\n");
    goto error;
  }
  size_t payloadBase64Len = strlen(argv[3]);
  size_t payloadLen = ece_base64url_decode(
    argv[3], payloadBase64Len, ECE_BASE64URL_REJECT_PADDING, NULL, 0);
  if (!payloadLen) {
    fprintf(stderr, "Error: Empty or invalid Base64url-encoded message\n");
    goto error;
  }
  payload = calloc(payloadLen, sizeof(uint8_t));
  if (!payload) {
    fprintf(
      stderr,
      "Error: Failed to allocate %zu bytes for Base64url-decoded message\n",
      payloadLen);
    goto error;
  }
  payloadLen =
    ece_base64url_decode(argv[3], payloadBase64Len,
                         ECE_BASE64URL_REJECT_PADDING, payload, payloadLen);
  if (!payloadLen) {
    fprintf(stderr, "Error: Failed to Base64url-decode message\n");
    goto error;
  }

  size_t plaintextLen = ece_aes128gcm_plaintext_max_length(payload, payloadLen);
  if (!plaintextLen) {
    fprintf(stderr, "Error: Encrypted message too short\n");
    goto error;
  }
  plaintextLen++;
  plaintext = calloc(plaintextLen, sizeof(uint8_t));
  if (!plaintext) {
    fprintf(stderr,
            "Error: Failed to allocate %zu bytes for decrypted message\n",
            plaintextLen);
    goto error;
  }
  err = ece_webpush_aes128gcm_decrypt(
    rawRecvPrivKey, ECE_WEBPUSH_PRIVATE_KEY_LENGTH, authSecret,
    ECE_WEBPUSH_AUTH_SECRET_LENGTH, payload, payloadLen, plaintext,
    &plaintextLen);
  if (err) {
    fprintf(stderr, "Error: Failed to decrypt message: %d\n", err);
    goto error;
  }
  plaintext[plaintextLen] = '\0';
  printf("Decrypted message: %s\n", plaintext);
  goto end;

error:
  err = 1;

end:
  free(payload);
  free(plaintext);
  return err;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AssemblyPropertiesViewer.Services.Interfaces
{
    internal interface IFileSystemService
    {
        IEnumerable<string> GetAssembliesInDirectory(string directoryPath, bool getRecursivelyFromSubdirectories);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Abre la app en tu reloj</string>
    <string name="description">Activa \"Aerlink\" desde tu reloj. Aparecerá una tarjeta con ayuda en la pantalla principal de tu reloj.</string>
</resources>


text:
TXC
===

* **TXC Corporation**
* http://txccrystal.com


text:
<?php

// include and configure Composer autoloader
include(__DIR__ . '/../vendor/autoload.php');


text:
<?php
/**
 *
 *
 * PHP version 5
 *
 * @package
 * @author  Andrey Filippov <afi.work@gmail.com>
 */

namespace Solo\Logger;

abstract class Level
{
	/**
	 * Detailed debug information
	 */
	const DEBUG = 100;

	/**
	 * Interesting events
	 *
	 * Examples: User logs in, SQL logs.
	 */
	const INFO = 200;

	/**
	 * Uncommon events
	 */
	const NOTICE = 250;

	/**
	 * Exceptional occurrences that are not errors
	 *
	 * Examples: Use of deprecated APIs, poor use of an API,
	 * undesirable things that are not necessarily wrong.
	 */
	const WARNING = 300;

	/**
	 * Runtime errors
	 */
	const ERROR = 400;

	/**
	 * Critical conditions
	 *
	 * Example: Application component unavailable, unexpected exception.
	 */
	const CRITICAL = 500;

	/**
	 * Action must be taken immediately
	 *
	 * Example: Entire website down, database unavailable, etc.
	 * This should trigger the SMS alerts and wake you up.
	 */
	const ALERT = 550;

	/**
	 * Urgent alert.
	 */
	const EMERGENCY = 600;
}


text:
package tools

import (
	"fmt"
	"testing"

	"github.com/coreos/go-etcd/etcd"
)

type EtcdResponseWithError struct {
	R *etcd.Response
	E error
}

type FakeEtcdClient struct {
	watchCompletedChan chan bool

	Data        map[string]EtcdResponseWithError
	DeletedKeys []string
	Err         error
	t           *testing.T
	Ix          int

	// Will become valid after Watch is called; tester may write to it. Tester may
	// also read from it to verify that it's closed after injecting an error.
	WatchResponse chan *etcd.Response
	// Write to this to prematurely stop a Watch that is running in a goroutine.
	WatchInjectError chan<- error
	WatchStop        chan<- bool
}

func MakeFakeEtcdClient(t *testing.T) *FakeEtcdClient {
	ret := &FakeEtcdClient{
		t:    t,
		Data: map[string]EtcdResponseWithError{},
	}
	// There are three publicly accessible channels in FakeEtcdClient:
	//  - WatchResponse
	//  - WatchInjectError
	//  - WatchStop
	// They are only available when Watch() is called.  If users of
	// FakeEtcdClient want to use any of these channels, they have to call
	// WaitForWatchCompletion before any operation on these channels.
	// Internally, FakeEtcdClient use watchCompletedChan to indicate if the
	// Watch() method has been called. WaitForWatchCompletion() will wait
	// on this channel. WaitForWatchCompletion() will return only when
	// WatchResponse, WatchInjectError and WatchStop are ready to read/write.
	ret.watchCompletedChan = make(chan bool)
	return ret
}

func (f *FakeEtcdClient) AddChild(key, data string, ttl uint64) (*etcd.Response, error) {
	f.Ix = f.Ix + 1
	return f.Set(fmt.Sprintf("%s/%d", key, f.Ix), data, ttl)
}

func (f *FakeEtcdClient) Get(key string, sort, recursive bool) (*etcd.Response, error) {
	result := f.Data[key]
	if result.R == nil {
		f.t.Errorf("Unexpected get for %s", key)
		return &etcd.Response{}, EtcdErrorNotFound
	}
	f.t.Logf("returning %v: %v %#v", key, result.R, result.E)
	return result.R, result.E
}

func (f *FakeEtcdClient) Set(key, value string, ttl uint64) (*etcd.Response, error) {
	result := EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Value: value,
			},
		},
	}
	f.Data[key] = result
	return result.R, f.Err
}

func (f *FakeEtcdClient) CompareAndSwap(key, value string, ttl uint64, prevValue string, prevIndex uint64) (*etcd.Response, error) {
	// TODO: Maybe actually implement compare and swap here?
	return f.Set(key, value, ttl)
}

func (f *FakeEtcdClient) Create(key, value string, ttl uint64) (*etcd.Response, error) {
	return f.Set(key, value, ttl)
}
func (f *FakeEtcdClient) Delete(key string, recursive bool) (*etcd.Response, error) {
	f.Data[key] = EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: EtcdErrorNotFound,
	}

	f.DeletedKeys = append(f.DeletedKeys, key)
	return &etcd.Response{}, f.Err
}

func (f *FakeEtcdClient) WaitForWatchCompletion() {
	<-f.watchCompletedChan
}

func (f *FakeEtcdClient) Watch(prefix string, waitIndex uint64, recursive bool, receiver chan *etcd.Response, stop chan bool) (*etcd.Response, error) {
	f.WatchResponse = receiver
	f.WatchStop = stop
	injectedError := make(chan error)

	defer close(injectedError)
	f.WatchInjectError = injectedError

	f.watchCompletedChan <- true
	select {
	case <-stop:
		return nil, etcd.ErrWatchStoppedByUser
	case err := <-injectedError:
		// Emulate etcd's behavior.
		close(receiver)
		return nil, err
	}
	// Never get here.
	return nil, nil
}


text:
import os
import sys
import webapp2
import jinja2
import codecs
import re

from google.appengine.ext import ndb

from jinja2 import Environment, meta
from bigrig.models import Project
from bigrig.models import User
from bigrig.usermanager import UserManager

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        os.path.join(
          os.path.dirname(__file__), '..'
        )
      ),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class UsersCreateHandler(webapp2.RequestHandler):

  def post (self):

    if UserManager.get_current_user() == None:
      self.redirect('/user-not-found')
      return

    save_message = 'ok'
    user_email = self.request.get('user-email')

    if (user_email == '' or user_email == None):
      save_message = 'No email address provided.'
    elif (UserManager.get_user_by_email_address(user_email) != None):
      save_message = 'User already exists.'
    else:
      user = User(email=user_email)
      user.put()

    template = JINJA_ENVIRONMENT.get_template('templates/_endpoints/action-update.json')
    self.response.write(template.render({
      "message": save_message
    }))

class UsersDeleteHandler(webapp2.RequestHandler):

  def post (self):

    if UserManager.get_current_user() == None:
      self.redirect('/user-not-found')
      return

    save_message = 'ok'

    user_email = self.request.get('user-email')

    if (user_email == '' or user_email == None):
      save_message = 'No email address provided.'
    elif (UserManager.get_user_by_email_address(user_email) == None):
      save_message = 'User does not exist.'
    else:

      projects_to_reassign = Project.query().filter(Project.owner==user_email)
      to_update = []

      for project in projects_to_reassign:
        project.owner = UserManager.get_email()
        to_update.append(project)

      if len(to_update) > 0:
        ndb.put_multi(to_update)

      user = UserManager.get_user_by_email_address(user_email)
      user.key.delete()

    template = JINJA_ENVIRONMENT.get_template('templates/_endpoints/action-update.json')
    self.response.write(template.render({
      "message": save_message
    }))

class UsersHandler(webapp2.RequestHandler):

  def get (self):

    if UserManager.get_current_user() == None:
      self.redirect('/user-not-found')
      return

    if not UserManager.is_admin():
      self.redirect('/')
      return

    template = JINJA_ENVIRONMENT.get_template('templates/users/users.html')

    def is_user_admin(user):

      values = sorted(values, key=lambda r: r.value, reverse=True)
      remapped_values = itertools.groupby(values, key=lambda v: v.type)

      return remapped_values

    JINJA_ENVIRONMENT.filters['is_user_admin'] = is_user_admin

    self.response.write(template.render({
      'users': User.query(),
      'sign_out_url': UserManager.get_signout_url(),
      'gravatar_url': UserManager.get_gravatar_url(),
      'user_email': UserManager.get_email(),
      'user_is_admin': UserManager.is_admin(),
      'sections': [{
        "name": "Users"
      }]
    }))

app = webapp2.WSGIApplication([
    ('/users/', UsersHandler),
    ('/users/create', UsersCreateHandler),
    ('/users/delete', UsersDeleteHandler)
], debug=True)


text:
********************************************************************************
	Project owner:		RageQuit community
	Project name: 		GTW-RPG
	Developers:   		Mr_Moose

	Source code:		https://github.com/404rq/GTW-RPG/
	Bugtracker: 		https://discuss.404rq.com/t/issues
	Suggestions:		https://discuss.404rq.com/t/development

	Version:    		Open source
	License:    		BSD 2-Clause
	Status:     		Stable release
********************************************************************************
]]--

members_in_turf 		= {{ }}						-- Counts the amount of players in each group in each turf
capturing 				= { }						-- Boolean to check whenever someone is trying to capture a specific turf
cooldown 				= { }						-- Cooldown timer to prevent spam kills for stats farming
time_syncer 			= { }						-- Timers to update the client status text with information about how much time is left to capture a turf

-- Database connection setup, MySQL or fallback SQLite
local mysql_host    	= exports.GTWcore:getMySQLHost() or nil
local mysql_database 	= exports.GTWcore:getMySQLDatabase() or nil
local mysql_user    	= exports.GTWcore:getMySQLUser() or nil
local mysql_pass    	= exports.GTWcore:getMySQLPass() or nil
db = dbConnect("mysql", "dbname="..mysql_database..";host="..mysql_host, mysql_user, mysql_pass, "autoreconnect=1")
if not db then db = dbConnect("sqlite", "/turfs.db") end

payout_time_interval		= 600						-- Time interval between payments for owned turfs (seconds).
lowest_amount_to_display 	= 50						-- Specify the lowest amount of money which is worth to notice the players about during payouts.

team_criminals			= "Criminals"					-- Specify teams that are allowed to turf
team_gangsters			= "Gangsters"					-- (See above)

money_pickpocket_max	= 500						-- Specify how much (or less) money the gangmembers will pickpocket from their enemies during a kill inside a turf
money_pickpocket_min	= 50						-- (See above)
armor_max				= 35						-- The maximum amount of armor the killer will get after killing an enemy
armor_min				= 25						-- The minimum amount of armor the killer will get after killing an enemy
weapon_stats_max		= 15						-- The maximum amount of stats for the current weapon the killer will gain after killing an enemy
weapon_stats_min		= 5							-- The minimum amount of stats for the current weapon the killer will gain after killing an enemy

time_reduce_factor		= 0.05						-- A value to be multiplied with sizex * sizey of a turf entered to decide how much time it takes to capture it
turf_alpha				= 140						-- The global turf color alpha value


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Angular Data Mapping</title>
    <link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.css">
</head>
<body ng-app="application" ng-controller="Application as application">
<pre>{{application.jsonData}}</pre>
</body>
<!-- core libraries -->
<script type="text/javascript" src="../../bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="../../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="../../bower_components/angular/angular.js"></script>
<!-- angular components api -->
<script type="text/javascript" src="../../dist/datamapping.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="service.js"></script>
<script type="text/javascript" src="controller.js"></script>
<!-- custom scripts, components, stuff -->
</html>


text:
package com.coreoz.plume.file.gallery.services.gallery.data;

public interface FileGalleryPosition {

	Long getIdFile();
	Integer getPosition();

}


text:
package mesosphere.marathon.core.launcher.impl

import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.base.{ Clock, ConstantClock }
import mesosphere.marathon.core.launcher.{ OfferProcessor, OfferProcessorConfig, TaskLauncher }
import mesosphere.marathon.core.matcher.base.OfferMatcher
import OfferMatcher.{ MatchedTasks, TaskLaunchSource, TaskWithSource }
import mesosphere.marathon.core.matcher.base.OfferMatcher
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.Timestamp
import mesosphere.marathon.{ MarathonSpec, MarathonTestHelper }
import org.apache.mesos.Protos.TaskInfo
import org.mockito.Mockito.{ verify, when }

import scala.concurrent.duration._
import scala.concurrent.{ Await, Future }

class OfferProcessorImplTest extends MarathonSpec {
  private[this] val offer = MarathonTestHelper.makeBasicOffer().build()
  private[this] val offerId = offer.getId
  private[this] val taskInfo1 = MarathonTestHelper.makeOneCPUTask("taskid1").build()
  private[this] val taskInfo2 = MarathonTestHelper.makeOneCPUTask("taskid2").build()
  private[this] val tasks = Seq(taskInfo1, taskInfo2)

  test("match successful, launch tasks successful") {
    val dummySource = new DummySource
    val tasksWithSource = tasks.map(TaskWithSource(dummySource, _))

    val offerProcessor = createProcessor()

    val deadline: Timestamp = clock.now() + 1.second
    when(offerMatcher.matchOffer(deadline, offer)).thenReturn(
      Future.successful(MatchedTasks(offerId, tasksWithSource))
    )
    when(taskLauncher.launchTasks(offerId, tasks)).thenReturn(true)

    Await.result(offerProcessor.processOffer(offer), 1.second)

    verify(offerMatcher).matchOffer(deadline, offer)
    verify(taskLauncher).launchTasks(offerId, tasks)

    assert(dummySource.rejected.isEmpty)
    assert(dummySource.accepted.toSeq == tasks)
  }

  test("match successful, launch tasks unsuccessful") {
    val dummySource = new DummySource
    val tasksWithSource = tasks.map(TaskWithSource(dummySource, _))

    val offerProcessor = createProcessor()

    val deadline: Timestamp = clock.now() + 1.second
    when(offerMatcher.matchOffer(deadline, offer)).thenReturn(
      Future.successful(MatchedTasks(offerId, tasksWithSource))
    )
    when(taskLauncher.launchTasks(offerId, tasks)).thenReturn(false)

    Await.result(offerProcessor.processOffer(offer), 1.second)

    verify(offerMatcher).matchOffer(deadline, offer)
    verify(taskLauncher).launchTasks(offerId, tasks)

    assert(dummySource.accepted.isEmpty)
    assert(dummySource.rejected.toSeq.map(_._1) == tasks)
  }

  test("match empty => decline") {
    val offerProcessor = createProcessor()

    val deadline: Timestamp = clock.now() + 1.second
    when(offerMatcher.matchOffer(deadline, offer)).thenReturn(
      Future.successful(MatchedTasks(offerId, Seq.empty))
    )

    Await.result(offerProcessor.processOffer(offer), 1.second)

    verify(offerMatcher).matchOffer(deadline, offer)
    verify(taskLauncher).declineOffer(offerId, refuseMilliseconds = Some(conf.declineOfferDuration()))
  }

  test("match crashed => decline") {
    val offerProcessor = createProcessor()

    val deadline: Timestamp = clock.now() + 1.second
    when(offerMatcher.matchOffer(deadline, offer)).thenReturn(
      Future.failed(new RuntimeException("failed matching"))
    )

    Await.result(offerProcessor.processOffer(offer), 1.second)

    verify(offerMatcher).matchOffer(deadline, offer)
    verify(taskLauncher).declineOffer(offerId, refuseMilliseconds = None)
  }

  private[this] var clock: Clock = _
  private[this] var offerMatcher: OfferMatcher = _
  private[this] var taskLauncher: TaskLauncher = _
  private[this] var conf: OfferProcessorConfig = _

  private[this] def createProcessor(): OfferProcessor = {
    conf = new OfferProcessorConfig {}
    conf.afterInit()

    clock = ConstantClock()
    offerMatcher = mock[OfferMatcher]
    taskLauncher = mock[TaskLauncher]

    new OfferProcessorImpl(conf, clock, new Metrics(new MetricRegistry), offerMatcher, taskLauncher)
  }

  class DummySource extends TaskLaunchSource {
    var rejected = Vector.empty[(TaskInfo, String)]
    var accepted = Vector.empty[TaskInfo]

    override def taskLaunchRejected(taskInfo: TaskInfo, reason: String): Unit = rejected :+= taskInfo -> reason
    override def taskLaunchAccepted(taskInfo: TaskInfo): Unit = accepted :+= taskInfo
  }
}


text:
Dropwizard Playground
=====================

Java Dropwizard playground for testing and training purpose.

Includes:
- Dropwizard 0.6.2
- Swagger 1.2

## Setup

1. Install MongoDB: todo
2. Clone repository: git clone git@github.com:leeprovoost/dropwizard-playground.git
3. Build using Maven: mvn package

## How to run

Terminal:
- Start MongoDB: mongod
- Start REST service: java -jar target/dropwizard-playground-0.0.1-SNAPSHOT.jar server configuration.yml

Browser:
- View API listing: http://localhost:3000/api-docs (drill down: http://localhost:3000/api-docs/registration)
- View Swagger UI: http://localhost:3000/swagger-ui/index.html


text:
package ops2015.holyspider.spi;

import ops2015.holyspider.domain.DomainFetchEngine;

import org.apache.http.client.HttpClient;

public interface IFetcher {
	public void fetch();

	public void setDomainHttpClient(HttpClient httpClient);

	public void setEngine(DomainFetchEngine engine);
}


text:
import web
from modules.json_controller import JSONController
from modules.json_form import (JSONForm, NotFoundError,
                               BooleanInput, StringInput)

class Todos(JSONController):

    Form = JSONForm(
        BooleanInput('is_done'),
        StringInput(
            'content',
            web.form.Validator('Content length must be greater than 7',
                               lambda s: len(s) > 7)
        ),
    )

    def list(self):
        '''Select todos from database'''
        return web.ctx.db.select('todos').list()

    def get(self, todo_id):
        '''Select todo by id'''
        todo = web.ctx.db.select('todos', where="id = $todo_id",
                                 vars=locals()).list()
        if todo:
            return todo[0]
        else:
            raise NotFoundError()

    def create(self):
        '''Create new todo'''
        form = self.Form()
        if form.validates():
            todo_id = web.ctx.db.insert('todos', **form.d)
            return self.get(todo_id)

    def update(self, todo_id):
        '''Update todo by id and return it'''
        form = self.Form()
        if form.validates():
            todo = self.get(todo_id)
            web.ctx.db.update('todos', where='id = $todo_id',
                              vars=locals(), **form.d)
            todo.update(**form.d)
            return todo

    def delete(self, todo_id):
        '''Delete todo by id and return deleted todo'''
        todo = self.get(todo_id)
        web.ctx.db.delete('todos', where='id = $todo_id', vars=locals())
        return todo


text:
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('promotion/tweets', { user: req.user, layout: 'layout' });
};

exports.login = function(req, res) {
	res.render('login', { layout: null });
}
exports.notadmin = function(req, res) {
	res.render('notadmin', { layout: null });
}


text:
require 'rails_helper'

describe 'LanguagesRequests', type: :request do
  subject { page }

  describe 'viewing information by language' do

    before do
      6.times { create :project, main_language: 'Haskell' }
      1.times { create :project, inactive: true, main_language: 'Haskell' }
      3.times { create :skill, language: 'Haskell' }
      9.times { create :contribution, language: 'Haskell' }

      visit language_path('haskell')
    end

    it { is_expected.to have_content '3 Contributors' }
    it { is_expected.to have_content '6 Haskell Projects' }
    it { is_expected.to have_content 'Latest Haskell Contributions (9 total)' }

    describe 'view all' do
      it '#projects' do
        within('#projects') { click_on 'View All' }

        is_expected.to have_content '6 Projects are using Haskell'
      end

      it '#users' do
        within('#users') { click_on 'View All' }

        is_expected.to have_content '3 Contributors using Haskell'
      end

      it '#contributions' do
        within('#contributions') { click_on 'View All' }

        is_expected.to have_content '9 contributions already made in Haskell!'
      end
    end
  end

  describe 'viewing a non existing language' do

    it 'should raise an error' do
      expect { visit language_path('Pugs') }
        .to raise_error(ActionController::RoutingError, 'Pugs is not a valid language')
    end
  end
end


text:
.select-select {
  display: none;
  /* For when we are on a small touch device and want to use native controls */
  -webkit-pointer-events: none;
  -moz-pointer-events: none;
  pointer-events: none;
  position: absolute;
  opacity: 0; }

.select-element, .select-element:after, .select-element:before, .select-element *, .select-element *:after, .select-element *:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box; }

.select-element {
  position: absolute;
  display: none; }
  .select-element.select-open {
    display: block; }

.select-theme-default, .select-theme-default *, .select-theme-default *:after, .select-theme-default *:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box; }

.select.select-theme-default .select-content {
  -webkit-border-radius: 0.25em;
  -moz-border-radius: 0.25em;
  -ms-border-radius: 0.25em;
  -o-border-radius: 0.25em;
  border-radius: 0.25em;
  -webkit-box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  background: white;
  font-family: inherit;
  color: inherit;
  overflow: auto;
  max-width: 18rem;
  max-height: 18rem;
  -webkit-overflow-scrolling: touch; }
  @media (max-width: 27rem), (max-height: 27rem) {
    .select.select-theme-default .select-content {
      max-width: 11.25rem;
      max-height: 11.25rem; } }
.select.select-theme-default .select-options {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-touch-callout: none;
  margin: 0;
  padding: 0; }
  .select.select-theme-default .select-options .select-option {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    -webkit-touch-callout: none;
    position: relative;
    list-style: none;
    margin: 0;
    line-height: 1.25rem;
    padding: 0.5rem 1em 0.5rem 2.5em;
    display: block;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; }
    .select.select-theme-default .select-options .select-option.select-option-selected:before {
      content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='#444444' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='#444444' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>");
      position: absolute;
      left: 1em;
      top: 0;
      bottom: 0.2em;
      height: 1em;
      width: 1em;
      margin: auto; }
    .select.select-theme-default .select-options .select-option:hover, .select.select-theme-default .select-options .select-option.select-option-highlight {
      background: #63a2f1;
      color: white; }
      .select.select-theme-default .select-options .select-option:hover.select-option-selected:before, .select.select-theme-default .select-options .select-option.select-option-highlight.select-option-selected:before {
        content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='white' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='white' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>"); }
    .select.select-theme-default .select-options .select-option:first-child {
      -webkit-border-radius: 0.25em 0.25em 0 0;
      -moz-border-radius: 0.25em 0.25em 0 0;
      -ms-border-radius: 0.25em 0.25em 0 0;
      -o-border-radius: 0.25em 0.25em 0 0;
      border-radius: 0.25em 0.25em 0 0; }
    .select.select-theme-default .select-options .select-option:last-child {
      -webkit-border-radius: 0 0 0.25em 0.25em;
      -moz-border-radius: 0 0 0.25em 0.25em;
      -ms-border-radius: 0 0 0.25em 0.25em;
      -o-border-radius: 0 0 0.25em 0.25em;
      border-radius: 0 0 0.25em 0.25em; }

.select-target.select-theme-default {
  display: -moz-inline-stack;
  display: inline-block;
  vertical-align: middle;
  *vertical-align: auto;
  zoom: 1;
  *display: inline;
  -webkit-border-radius: 0.25em;
  -moz-border-radius: 0.25em;
  -ms-border-radius: 0.25em;
  -o-border-radius: 0.25em;
  border-radius: 0.25em;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-touch-callout: none;
  position: relative;
  padding: 0.5rem 3em 0.5rem 1em;
  background: #f6f6f6;
  border: 0.18em solid #dddddd;
  cursor: pointer;
  color: #444444;
  text-decoration: none;
  white-space: nowrap;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis; }
  .select-target.select-theme-default:hover {
    border-color: #aaaaaa;
    color: black; }
  .select-target.select-theme-default.select-target-focused, .select-target.select-theme-default.select-target-focused:focus {
    border-color: #63a2f1;
    outline: none; }
  .select-target.select-theme-default b {
    position: absolute;
    right: 1em;
    top: 0;
    bottom: 0;
    margin: auto;
    height: 1.25rem;
    width: 2em; }
    .select-target.select-theme-default b:before, .select-target.select-theme-default b:after {
      content: "";
      display: block;
      position: absolute;
      margin: auto;
      right: 0;
      height: 0;
      width: 0;
      border: 0.263em solid transparent; }
    .select-target.select-theme-default b:before {
      top: 0;
      border-bottom-color: inherit; }
    .select-target.select-theme-default b:after {
      bottom: 0;
      border-top-color: inherit; }


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="false" >
    <solid android:color="@color/colorLine" />
    <padding
        android:left="2dp"
        android:top="1dp"
        android:right="2dp"
        android:bottom="1dp" />
    <solid
        android:color="@color/colorLine" />
    <stroke
        android:width="1dp"
        android:color="@android:color/white" />
    <!--<size android:width="25dp"-->
        <!--android:height="25dp" />-->
</shape>


text:
<?php

namespace Application\View\HelperFactory;

use Application\View\Helper\GetSites;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

use Interop\Container\ContainerInterface;

class GetSitesFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $viewHelperServiceLocator)
    {
        return $this($viewHelperServiceLocator, GetSites::class);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $sl = $container->getServiceLocator();
        $manager = $sl->get('LoggedInUserManager');

        $helper = new GetSites($manager);

        return $helper;
    }
}


text:
set -o nounset
set -o errexit

workdir=$(mktemp -d)
origdir=$(pwd)

cd ${workdir}
git clone https://github.com/katcipis/st.git
cd st
make
sudo make install
cd ${origdir}
rm -rf ${workdir}


text:
package org.basex.util;

import java.net.*;

import javax.xml.catalog.*;
import javax.xml.transform.*;

import org.basex.core.*;
import org.basex.io.*;
import org.w3c.dom.ls.*;
import org.xml.sax.*;

/**
 * Catalog resolver: Convenience methods for retrieving resolver instances of the standard
 * JDK 11 implementation or Norman Walsh's enhanced XML resolver.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class Resolver {
  /** Path to enhanced XML resolver. */
  private static final String RESOLVER = "org.xmlresolver.Resolver";
  /** Path to enhanced XML resolver configuration. */
  private static final String CONFIGURATION = "org.xmlresolver.XMLResolverConfiguration";

  /** Private Constructor. */
  private Resolver() { }

  /**
   * Returns an entity resolver.
   * @param mopts main options
   * @return entity resolver (can be {@code null})
   */
  public static EntityResolver entities(final MainOptions mopts) {
    return (EntityResolver) resolver(mopts);
  }

  /**
   * Returns a URI resolver.
   * @param mopts main options
   * @return URI resolver (can be {@code null})
   */
  public static URIResolver uris(final MainOptions mopts) {
    return (URIResolver) resolver(mopts);
  }

  /**
   * Returns a resource resolver.
   * @param mopts main options
   * @return resource resolver (can be {@code null})
   */
  public static LSResourceResolver resources(final MainOptions mopts) {
    return (LSResourceResolver) resolver(mopts);
  }

  /**
   * Returns a catalog resolver.
   * @param mopts main options
   * @return catalog resolver (can be {@code null})
   */
  private static Object resolver(final MainOptions mopts) {
    final String catalog = mopts.get(MainOptions.CATALOG);
    if(!catalog.isEmpty()) {
      if(Reflect.available(RESOLVER)) {
        // return enhanced XML resolver
        final Class<?> resolver = Reflect.find(RESOLVER);
        final Class<?> configuration = Reflect.find(CONFIGURATION);
        final Object conf = Reflect.get(Reflect.find(configuration, String.class), catalog);
        return Reflect.get(Reflect.find(resolver, configuration), conf);
      }
      // return JDK 11 resolver
      final URI uri = URI.create(IO.get(catalog).url());
      final CatalogFeatures cf = CatalogFeatures.defaults();
      return CatalogManager.catalogResolver(CatalogManager.catalog(cf, uri));
    }
    return null;
  }
}