text:
// Import docs from a git branch and format them for gh-pages.
// usage: go run _tools/release_docs/main.go _tools/release_docs/api-reference-process.go --branch release-1.0 --output-dir v1.0 --version v1.0
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"strings"
)

var (
	branch       = flag.String("branch", "", "The git branch from which to pull docs. (e.g. release-1.0, master).")
	outputDir    = flag.String("output-dir", "", "The directory in which to save results.")
	version      = flag.String("version", "", "The release version. It should be the same as the version segment in the URL, e.g., when importing docs that will be hosted at k8s.io/v1.0/, the version flag should be \"v1.0\".")
	remote       = flag.String("remote", "upstream", "Optional: The name of the remote repo from which to pull docs.")
	apiReference = flag.Bool("apiReference", true, "Optional: Whether update api reference")

	subdirs = []string{"docs", "examples"}
)

func fileExistsInBranch(path string) bool {
	out, err := exec.Command("git", "ls-tree", fmt.Sprintf("%s/%s", *remote, *branch), path).Output()
	return err == nil && len(out) != 0
}

func fixURL(filename string, u *url.URL) bool {
	if u.Host != "" || u.Path == "" {
		return false
	}

	target := filepath.Join(filepath.Dir(filename), u.Path)
	if fi, err := os.Stat(target); os.IsNotExist(err) {
		// We're linking to something we didn't copy over. Send
		// it through the redirector.
		rel, err := filepath.Rel(*outputDir, target)
		if err != nil {
			return false
		}

		if fileExistsInBranch(rel) {
			u.Path = filepath.Join(*branch, rel)
			u.Host = "releases.k8s.io"
			u.Scheme = "https"
			return true
		}
	} else if fi.IsDir() {
		// If there's no README.md in the directory, redirect to github
		// for the directory view.
		files, err := filepath.Glob(target + "/*")
		if err != nil {
			return false
		}

		hasReadme := false
		for _, f := range files {
			if strings.ToLower(filepath.Base(f)) == "readme.md" {
				hasReadme = true
			}
		}
		if !hasReadme {
			rel, err := filepath.Rel(*outputDir, target)
			if err != nil {
				return false
			}
			u.Path = filepath.Join(*branch, rel)
			u.Host = "releases.k8s.io"
			u.Scheme = "https"
			return true
		}
	} else if strings.HasSuffix(u.Path, ".md") {
		u.Path = u.Path[:len(u.Path)-3] + ".html"
		return true
	}

	return false
}

func processFile(prefix, filename string) error {
	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}

	title := getTitle(fileBytes)
	if len(title) == 0 {
		title = filename[len(prefix)+1 : len(filename)-len(".md")]
	}

	output := rewriteLinks(filename, fileBytes)
	output = rewriteCodeBlocks(output)
	output = rewriteHTMLPreviewLinks(output)
	output = rewriteDownloadLinks(output)

	f, err := os.Create(filename)
	if err != nil {
		return err
	}

	_, err = f.WriteString(fmt.Sprintf("---\nlayout: docwithnav\ntitle: %q\n---\n", title))
	if err != nil {
		return err
	}

	_, err = f.Write(output)
	return err
}

var (
	// Finds markdown links of the form [foo](bar "alt-text").
	linkRE = regexp.MustCompile(`\[([^]]*)\]\(([^)]*)\)`)
	// Finds markdown refence style link definitions
	refRE = regexp.MustCompile(`(?m)^\[([^]]*)\]:\s+(.*)$`)
	// Splits the link target into link target and alt-text.
	altTextRE = regexp.MustCompile(`(.*)( ".*")`)
)

func rewriteLinks(filename string, fileBytes []byte) []byte {
	getParts := func(re *regexp.Regexp, in []byte) (text, link, caption string, changed bool) {
		match := re.FindSubmatch(in)
		text = string(match[1])
		link = strings.TrimSpace(string(match[2]))

		if parts := altTextRE.FindStringSubmatch(link); parts != nil {
			link = parts[1]
			caption = parts[2]
		}

		u, err := url.Parse(link)
		if err != nil || !fixURL(filename, u) {
			return "", "", "", false
		}

		return text, u.String(), caption, true
	}

	for _, conversion := range []struct {
		re     *regexp.Regexp
		format string
	}{
		{linkRE, "[%s](%s)"},
		{refRE, "[%s]: %s"},
	} {

		fileBytes = conversion.re.ReplaceAllFunc(fileBytes, func(in []byte) (out []byte) {
			text, link, caption, changed := getParts(conversion.re, in)
			if !changed {
				return in
			}

			return []byte(fmt.Sprintf(conversion.format, text, link+caption))
		})

	}
	return fileBytes
}

var (
	// Allow more than 3 ticks because people write this stuff.
	ticticticRE    = regexp.MustCompile("^`{3,}\\s*(.*)$")
	notTicticticRE = regexp.MustCompile("^```(.*)```")
	languageFixups = map[string]string{
		"shell":  "sh",
		"golang": "go",
	}
)

func rewriteCodeBlocks(fileBytes []byte) []byte {
	lines := strings.Split(string(fileBytes), "\n")
	inside := false
	highlight := false
	output := []string{}
	for i := range lines {
		trimmed := []byte(strings.TrimLeft(lines[i], " "))
		if !ticticticRE.Match(trimmed) || notTicticticRE.Match(trimmed) {
			output = append(output, lines[i])
			continue
		}
		if !inside {
			out := ticticticRE.FindSubmatch(trimmed)
			lang := strings.ToLower(string(out[1]))
			// Can't syntax highlight unknown language.
			if fixedLang := languageFixups[lang]; fixedLang != "" {
				lang = fixedLang
			}
			if lang != "" {
				// The "redcarpet" markdown renderer will accept ```lang, but
				// "kramdown" will not.  They both accept this, format, and we
				// need a hook to fixup language codes anyway (until we have a
				// munger in master).
				output = append(output, fmt.Sprintf("{%% highlight %s %%}", lang))
				highlight = true
			} else {
				output = append(output, lines[i])
			}
			output = append(output, `{% raw %}`)
		} else {
			output = append(output, `{% endraw %}`)
			if highlight {
				output = append(output, `{% endhighlight %}`)
				highlight = false
			} else {
				output = append(output, lines[i])
			}
		}
		inside = !inside
	}
	return []byte(strings.Join(output, "\n") + "\n")
}

var (
	htmlPreviewRE = regexp.MustCompile(`https://htmlpreview.github.io/\?https://github.com/kubernetes/kubernetes/[^/]*`)
)

// For example, this rewrites
// https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/v1.1.0/docs/api-reference/v1/definitions.html#_v1_pod
// To
// http://kubernetes.io/v1.1/docs/api-reference/v1/definitions.html#_v1_pod
func rewriteHTMLPreviewLinks(fileBytes []byte) []byte {
	return htmlPreviewRE.ReplaceAll(fileBytes, []byte(fmt.Sprintf("http://kubernetes.io/%s", *version)))
}

var (
	downloadLinkRE = regexp.MustCompile("\\[Download example\\]\\((.*\\.)(yaml|json)\\?raw=true\\)")
)

// Drops "?raw=true" from download example links. For example this rewrites
// "[Download example](pod.yaml?raw=true)"
// to
// "[Download example](pod.yaml)"
func rewriteDownloadLinks(fileBytes []byte) []byte {
	return downloadLinkRE.ReplaceAllFunc(fileBytes, func(in []byte) []byte {
		matches := downloadLinkRE.FindSubmatch(in)
		fileName := string(matches[1])
		extension := string(matches[2])
		newLink := "[Download example](" + fileName + extension + ")"
		return []byte(newLink)
	})
}

var (
	// matches "# headers" and "## headers"
	atxTitleRE = regexp.MustCompile(`(?m)^\s*##?\s+(?P<title>.*)$`)
	// matches
	//  Headers
	//  =======
	// and
	//  Headers
	//  --
	setextTitleRE = regexp.MustCompile("(?m)^(?P<title>.+)\n((=+)|(-+))$")
	ignoredRE     = regexp.MustCompile(`[*_\\]`)
)

// removeLinks removes markdown links from the input leaving only the
// display text.
func removeLinks(input []byte) []byte {
	indices := linkRE.FindAllSubmatchIndex(input, -1)
	if len(indices) == 0 {
		return input
	}

	out := make([]byte, 0, len(input))
	cur := 0
	for _, index := range indices {
		linkStart, linkEnd, textStart, textEnd := index[0], index[1], index[2], index[3]
		// append bytes between previous match and this one
		out = append(out, input[cur:linkStart]...)
		// extract and append link text
		out = append(out, input[textStart:textEnd]...)
		// update cur
		cur = linkEnd
	}
	// pick up the remaining and return it
	return append(out, input[cur:len(input)]...)
}

// findTitleMatch returns the start of the match and the "title" subgroup of
// bytes. If the regexp doesn't match, it will return -1 and nil.
func findTitleMatch(titleRE *regexp.Regexp, input []byte) (start int, title []byte) {
	indices := titleRE.FindSubmatchIndex(input)
	if len(indices) == 0 {
		return -1, nil
	}

	for i, name := range titleRE.SubexpNames() {
		if name == "title" {
			start, end := indices[2*i], indices[2*i+1]
			return indices[0], input[start:end]
		}
	}

	// there was no grouped named title
	return -1, nil
}

func getTitle(fileBytes []byte) string {
	atxStart, atxMatch := findTitleMatch(atxTitleRE, fileBytes)
	setextStart, setextMatch := findTitleMatch(setextTitleRE, fileBytes)

	var title []byte

	switch {
	case atxStart == -1 && setextStart == -1:
		return ""
	case atxStart == -1:
		title = setextMatch
	case setextStart == -1:
		title = atxMatch
	case setextStart < atxStart:
		title = setextMatch
	default:
		title = atxMatch
	}

	// Handle the case where there's a link in the header.
	title = removeLinks(title)

	// Take out all markdown stylings.
	return string(ignoredRE.ReplaceAll(title, nil))
}

func runGitUpdate(remote string) error {
	cmd := exec.Command("git", "fetch", remote)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("git fetch failed: %v\n%s", err, out)
	}
	return err
}

func copyFiles(remoteRepo, directory, branch string) error {
	if err := runGitUpdate(remoteRepo); err != nil {
		return err
	}

	if !strings.HasSuffix(directory, "/") {
		directory += "/"
	}
	prefix := fmt.Sprintf("--prefix=%s", directory)
	tagRef := fmt.Sprintf("%s/%s", remoteRepo, branch)
	gitArgs := append([]string{"archive", "--format=tar", prefix, tagRef}, subdirs...)
	gitCmd := exec.Command("git", gitArgs...)
	tarCmd := exec.Command("tar", "-x")

	var err error
	tarCmd.Stdin, err = gitCmd.StdoutPipe()
	if err != nil {
		return err
	}

	gitStderr, err := gitCmd.StderrPipe()
	if err != nil {
		return err
	}
	gitErrs := bytes.Buffer{}

	fmt.Printf("Copying docs and examples from %s to %s\n", tagRef, directory)

	if err = tarCmd.Start(); err != nil {
		return fmt.Errorf("tar command failed: %v", err)
	}

	if err = gitCmd.Run(); err != nil {
		gitErrs.ReadFrom(gitStderr)
		return fmt.Errorf("git command failed: %v\n%s", err, gitErrs.String())
	}

	return tarCmd.Wait()
}

func copySingleFile(src, dst string) (err error) {
	_, err = os.Stat(dst)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}

	defer func() {
		cerr := out.Close()
		if err == nil {
			err = cerr
		}
	}()

	_, err = io.Copy(out, in)
	return
}

func main() {
	flag.Parse()
	if len(*branch) == 0 {
		fmt.Println("You must specify a branch with --branch.")
		os.Exit(1)
	}
	if len(*outputDir) == 0 {
		fmt.Println("You must specify an output dir with --output-dir.")
		os.Exit(1)
	}
	if len(*version) == 0 {
		fmt.Println("You must specify the release version with --version.")
		os.Exit(1)
	}

	if err := checkCWD(); err != nil {
		fmt.Printf("Could not find the kubernetes root: %v\n", err)
		os.Exit(1)
	}

	if err := copyFiles(*remote, *outputDir, *branch); err != nil {
		fmt.Printf("Error copying files: %v\n", err)
		os.Exit(1)
	}

	for _, subDir := range subdirs {
		prefix := path.Join(*outputDir, subDir)
		err := filepath.Walk(prefix, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			if !info.IsDir() && strings.HasSuffix(info.Name(), ".md") {
				fmt.Printf("Processing %s\n", path)
				if err = processFile(prefix, path); err != nil {
					return err
				}

				if strings.ToLower(info.Name()) == "readme.md" {
					newpath := path[0:len(path)-len("readme.md")] + "index.md"
					fmt.Printf("Copying %s to %s\n", path, newpath)
					if err = copySingleFile(path, newpath); err != nil {
						return err
					}
				}
			}

			if *apiReference && !info.IsDir() && (info.Name() == "definitions.html" || info.Name() == "operations.html") {
				fmt.Printf("Processing %s\n", path)
				err := processHTML(path, *version, *outputDir)
				if err != nil {
					return err
				}
			}
			return nil

		})

		if err != nil {
			fmt.Printf("Error while processing markdown and html files: %v\n", err)
			os.Exit(1)
		}
	}
}

func checkCWD() error {
	dir, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
	if err != nil {
		return err
	}
	return os.Chdir(strings.TrimSpace(string(dir)))
}


text:
package org.reactfx;

import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

import javafx.beans.binding.BooleanBinding;
import javafx.beans.value.ObservableBooleanValue;

import org.reactfx.util.Timer;

class ThenAccumulateForStream<T, A> extends EventStreamBase<T> implements AwaitingEventStream<T> {
    private static enum State {
        READY, ACC_NO_EVENT, ACC_HAS_EVENT
    }

    private final EventStream<T> input;
    private final Function<? super T, ? extends A> initial;
    private final BiFunction<? super A, ? super T, ? extends A> reduction;
    private final Function<? super A, List<T>> deconstruction;
    private final Timer timer;

    private State state = State.READY;
    private A acc = null;
    private BooleanBinding pending = null;

    public ThenAccumulateForStream(
            EventStream<T> input,
            Function<? super T, ? extends A> initial,
            BiFunction<? super A, ? super T, ? extends A> reduction,
            Function<? super A, List<T>> deconstruction,
            Function<Runnable, Timer> timerFactory) {

        this.input = input;
        this.initial = initial;
        this.reduction = reduction;
        this.deconstruction = deconstruction;
        this.timer = timerFactory.apply(this::handleTimeout);
    }

    @Override
    public ObservableBooleanValue pendingProperty() {
        if(pending == null) {
            pending = new BooleanBinding() {
                @Override
                protected boolean computeValue() {
                    return state == State.ACC_HAS_EVENT;
                }
            };
        }
        return pending;
    }

    @Override
    public boolean isPending() {
        return pending != null ? pending.get() : state == State.ACC_HAS_EVENT;
    }

    @Override
    protected final Subscription observeInputs() {
        return input.subscribe(this::handleEvent);
    }

    private void handleEvent(T t) {
        switch(state) {
        case READY:
            timer.restart();
            setState(State.ACC_NO_EVENT);
            emit(t);
            break;
        case ACC_NO_EVENT:
            acc = initial.apply(t);
            setState(State.ACC_HAS_EVENT);
            break;
        case ACC_HAS_EVENT:
            acc = reduction.apply(acc, t);
            break;
        }
    }

    private void handleTimeout() {
        List<T> toEmit;
        switch(state) {
        case ACC_HAS_EVENT:
            toEmit = deconstruction.apply(acc);
            acc = null;
            state = State.ACC_NO_EVENT; // so that recursively emitted events start accumulating
            break;
        case ACC_NO_EVENT:
            toEmit = Collections.emptyList();
            break;
        default:
            throw new AssertionError();
        }

        for(T t: toEmit) {
            emit(t);
        }

        if(state == State.ACC_NO_EVENT) { // no recursive emission occurred
            setState(State.READY);
        } else {
            // recursive emission occurred, start the timer to schedule emission
            assert state == State.ACC_HAS_EVENT;
            timer.restart();
        }
    }

    private void setState(State state) {
        this.state = state;
        invalidatePending();
    }

    private void invalidatePending() {
        if(pending != null) {
            pending.invalidate();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.github.ageofwar.telejam.inline;

import com.google.gson.annotations.SerializedName;

import java.util.Objects;

/**
 * This object represents one button of an inline keyboard.
 *
 * @author Michi Palazzo
 */
public class LoginUrlInlineKeyboardButton extends InlineKeyboardButton {

  static final String LOGIN_URL_FIELD = "login_url";

  /**
   * HTTP url to be opened when button is pressed.
   */
  @SerializedName(LOGIN_URL_FIELD)
  private final LoginUrl loginUrl;

  /**
   * Constructs an UrlInlineKeyboardButton.
   *
   * @param text     label text on the button
   * @param loginUrl HTTP url to be opened when button is pressed
   */
  public LoginUrlInlineKeyboardButton(String text, LoginUrl loginUrl) {
    super(text);
    this.loginUrl = Objects.requireNonNull(loginUrl);
  }

  /**
   * Getter for property {@link #loginUrl}.
   *
   * @return value for property {@link #loginUrl}
   */
  public LoginUrl getUrl() {
    return loginUrl;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if (!(obj instanceof LoginUrlInlineKeyboardButton)) {
      return false;
    }
    LoginUrlInlineKeyboardButton button = (LoginUrlInlineKeyboardButton) obj;
    return getText().equals(button.getText()) && loginUrl.equals(button.loginUrl);
  }

  @Override
  public int hashCode() {
    return Objects.hash(getText(), loginUrl);
  }

}


text:
package gov.va.med.lom.javaUtils.file;

import java.io.File;
import java.io.FilenameFilter;

public class DirFilter implements FilenameFilter {
  private String afn;

  DirFilter(String afn) {
    this.afn = afn;
  }

  // strip path information
  public boolean accept(File dir, String name) {
    String f = new File(name).getName();
    return f.indexOf(afn) != -1;
  }

}


text:
module Vultr
  class FirewallResource < Resource
    def list(**params)
      response = get_request("firewalls", params: params)
      Collection.from_response(response, key: "firewall_groups", type: FirewallGroup)
    end

    def create(**attributes)
      FirewallGroup.new post_request("firewalls", body: attributes).body.dig("firewall_group")
    end

    def retrieve(firewall_group_id:)
      FirewallGroup.new get_request("firewalls/#{firewall_group_id}").body.dig("firewall_group")
    end

    def update(firewall_group_id:, **attributes)
      put_request("firewalls/#{firewall_group_id}", body: attributes)
    end

    def delete(firewall_group_id:)
      delete_request("firewalls/#{firewall_group_id}")
    end

    # Firewall Rules
    def list_rules(firewall_group_id:, **params)
      response = get_request("firewalls/#{firewall_group_id}/rules", params: params)
      Collection.from_response(response, key: "firewall_rules", type: Object)
    end

    def create_rule(firewall_group_id:, **attributes)
      Object.new post_request("firewalls/#{firewall_group_id}/rules", body: attributes).body.dig("firewall_rule")
    end

    def retrieve_rule(firewall_group_id:, firewall_rule_id:)
      Object.new get_request("firewalls/#{firewall_group_id}/rules/#{firewall_rule_id}").body.dig("firewall_rule")
    end

    def delete_rule(firewall_group_id:, firewall_rule_id:)
      delete_request("firewalls/#{firewall_group_id}/rules/#{firewall_rule_id}")
    end
  end
end


text:
title: SEO for SSR
desc: (@quasar/app-webpack) Managing the search engine optimizations in a Quasar server-side rendered app.
---

The term SEO refers to Search Engine Optimization. And Quasar covers this aspect too through the [Quasar Meta Plugin](/quasar-plugins/meta).

## Quasar Meta Plugin

The [Quasar Meta Plugin](/quasar-plugins/meta) can dynamically change page title, manage `<meta>` tags, manage `<html>` and `<body>` DOM element attributes, add/remove/change `<style>` and `<script>` tags in the head of your document (useful for CDN stylesheets or for json-ld markup, for example), or manage `<noscript>` tags.

::: tip
This Quasar plugin has the most tight integration with Quasar and so it has the best performance against any other similar solution.
:::


text:
package cn.enjoytoday;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author hfcai
 *
 */
public class Servlet_two extends GenericServlet {

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		/**
		 * handler from service
		 */
		readString(req.getReader());
		getInitParmas();
		response(res.getWriter(), "request success!");

		ServletContext context=getServletContext();

	}

	private void  getInitParmas() {
		 Enumeration<String>names=	getInitParameterNames();
		 while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			System.out.println("initParam name:"+name+",and value is:"+getInitParameter(name));

		}

	}

	private void readString(BufferedReader bufferedReader) throws IOException {

		String line=null;
		StringBuffer stringBuffer=new StringBuffer();
		while( (line=bufferedReader.readLine())!=null) {
			stringBuffer.append(line+"\n");
		}
		System.out.println("get request String:"+stringBuffer.toString());
	}

	private void  response(PrintWriter writer,String content) {
		writer.append(content).flush();
	}

}


text:
/*
 * LMS1xx.cpp
 *
 *  Created on: 09-08-2010
 *  Author: Konrad Banachowicz
 ***************************************************************************
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Lesser General Public            *
 *   License as published by the Free Software Foundation; either          *
 *   version 2.1 of the License, or (at your option) any later version.    *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 59 Temple Place,                                    *
 *   Suite 330, Boston, MA  02111-1307  USA                                *
 *                                                                         *
 ***************************************************************************/

#include <csignal>
#include <cstdio>
#include <LMS1xx/LMS1xx.h>
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include <limits>
#include <string>

#define DEG2RAD M_PI/180.0

int main(int argc, char **argv)
{
  // laser data
  LMS1xx laser;
  scanCfg cfg;
  scanOutputRange outputRange;
  scanDataCfg dataCfg;
  sensor_msgs::LaserScan scan_msg;

  // parameters
  std::string host;
  std::string frame_id;
  bool inf_range;
  int port;

  ros::init(argc, argv, "lms1xx");
  ros::NodeHandle nh;
  ros::NodeHandle n("~");
  ros::Publisher scan_pub = nh.advertise<sensor_msgs::LaserScan>("scan", 1);

  n.param<std::string>("host", host, "192.168.1.2");
  n.param<std::string>("frame_id", frame_id, "laser");
  n.param<bool>("publish_min_range_as_inf", inf_range, false);
  n.param<int>("port", port, 2111);

  while (ros::ok())
  {
    ROS_INFO_STREAM("Connecting to laser at " << host);
    laser.connect(host, port);
    if (!laser.isConnected())
    {
      ROS_WARN("Unable to connect, retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_DEBUG("Logging in to laser.");
    laser.login();
    cfg = laser.getScanCfg();
    outputRange = laser.getScanOutputRange();

    if (cfg.scaningFrequency != 5000)
    {
      laser.disconnect();
      ROS_WARN("Unable to get laser output range. Retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_INFO("Connected to laser.");

    ROS_DEBUG("Laser configuration: scaningFrequency %d, angleResolution %d, startAngle %d, stopAngle %d",
              cfg.scaningFrequency, cfg.angleResolution, cfg.startAngle, cfg.stopAngle);
    ROS_DEBUG("Laser output range:angleResolution %d, startAngle %d, stopAngle %d",
              outputRange.angleResolution, outputRange.startAngle, outputRange.stopAngle);

    scan_msg.header.frame_id = frame_id;
    scan_msg.range_min = 0.01;
    scan_msg.range_max = 20.0;
    scan_msg.scan_time = 100.0 / cfg.scaningFrequency;
    scan_msg.angle_increment = static_cast<double>(outputRange.angleResolution / 10000.0 * DEG2RAD);
    scan_msg.angle_min = static_cast<double>(outputRange.startAngle / 10000.0 * DEG2RAD - M_PI / 2);
    scan_msg.angle_max = static_cast<double>(outputRange.stopAngle / 10000.0 * DEG2RAD - M_PI / 2);

    ROS_DEBUG_STREAM("Device resolution is " << (double)outputRange.angleResolution / 10000.0 << " degrees.");
    ROS_DEBUG_STREAM("Device frequency is " << (double)cfg.scaningFrequency / 100.0 << " Hz");
    outputRange.angleResolution = cfg.scaningFrequency;
    int angle_range = outputRange.stopAngle - outputRange.startAngle;
    int num_values = angle_range / outputRange.angleResolution;
    if (angle_range % outputRange.angleResolution == 0)
    {
      // Include endpoint
      ++num_values;
    }
    scan_msg.ranges.resize(num_values);
    scan_msg.intensities.resize(num_values);

    scan_msg.time_increment =
      (outputRange.angleResolution / 10000.0)
      / 360.0
      / (cfg.scaningFrequency / 100.0);

    ROS_DEBUG_STREAM("Time increment is " << static_cast<int>(scan_msg.time_increment * 1000000) << " microseconds");

    dataCfg.outputChannel = 1;
    dataCfg.remission = true;
    dataCfg.resolution = 1;
    dataCfg.encoder = 0;
    dataCfg.position = false;
    dataCfg.deviceName = false;
    dataCfg.outputInterval = 1;

    ROS_DEBUG("Setting scan data configuration.");
    laser.setScanDataCfg(dataCfg);

    ROS_DEBUG("Starting measurements.");
    laser.startMeas();

    ROS_DEBUG("Waiting for ready status.");
    ros::Time ready_status_timeout = ros::Time::now() + ros::Duration(5);

    // while(1)
    // {
    status_t stat = laser.queryStatus();
    ros::Duration(1.0).sleep();
    if (stat != ready_for_measurement)
    {
      ROS_WARN("Laser not ready. Retrying initialization.");
      laser.disconnect();
      ros::Duration(1).sleep();
      continue;
    }
    /*if (stat == ready_for_measurement)
    {
      ROS_DEBUG("Ready status achieved.");
      break;
    }
      if (ros::Time::now() > ready_status_timeout)
      {
        ROS_WARN("Timed out waiting for ready status. Trying again.");
        laser.disconnect();
        continue;
      }
      if (!ros::ok())
      {
        laser.disconnect();
        return 1;
      }
    }*/

    ROS_DEBUG("Starting device.");
    laser.startDevice();  // Log out to properly re-enable system after config

    ROS_DEBUG("Commanding continuous measurements.");
    laser.scanContinous(1);

    while (ros::ok())
    {
      ros::Time start = ros::Time::now();

      scan_msg.header.stamp = start;
      ++scan_msg.header.seq;

      scanData data;
      ROS_DEBUG("Reading scan data.");
      if (laser.getScanData(&data))
      {
        for (int i = 0; i < data.dist_len1; i++)
        {
          float range_data = data.dist1[i] * 0.001;

          if (inf_range && range_data < scan_msg.range_min)
          {
            scan_msg.ranges[i] = std::numeric_limits<float>::infinity();
          }
          else
          {
            scan_msg.ranges[i] = range_data;
          }
        }

        for (int i = 0; i < data.rssi_len1; i++)
        {
          scan_msg.intensities[i] = data.rssi1[i];
        }

        ROS_DEBUG("Publishing scan data.");
        scan_pub.publish(scan_msg);
      }
      else
      {
        ROS_ERROR("Laser timed out on delivering scan, attempting to reinitialize.");
        //break;
      }

      ros::spinOnce();
    }

    laser.scanContinous(0);
    laser.stopMeas();
    laser.disconnect();
  }

  return 0;
}


text:
using System;
using System.Globalization;
using Txt.Core;

namespace Hls.duration
{
    public class DurationParser : Parser<Duration, TimeSpan>
    {
        protected override TimeSpan ParseImpl(Duration duration)
        {
            return TimeSpan.FromSeconds(
                double.Parse(
                    duration.Text,
                    NumberStyles.AllowDecimalPoint,
                    NumberFormatInfo.InvariantInfo));
        }
    }
}


text:
<!DOCTYPE html>

<wicket:panel>

                [langCode]
                <input wicket:id="title" class="form-control" aria-describedby="langCode-addOn"/>

</wicket:panel>


text:
#include <gflags/gflags.h>
#include <iostream>
#include <memory>
#include <string>

#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc/support/log.h>

#include "src/proto/grpc/testing/echo.grpc.pb.h"

DEFINE_string(address, "", "Address to bind to");

using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;

// In some distros, gflags is in the namespace google, and in some others,
// in gflags. This hack is enabling us to find both.
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;

namespace grpc {
namespace testing {

class ServiceImpl final : public ::grpc::testing::EchoTestService::Service {
  Status BidiStream(
      ServerContext* context,
      ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
    EchoRequest request;
    EchoResponse response;
    while (stream->Read(&request)) {
      gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
      response.set_message(request.message());
      stream->Write(response);
    }
    return Status::OK;
  }
};

void RunServer() {
  ServiceImpl service;

  ServerBuilder builder;
  builder.AddListeningPort(FLAGS_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << FLAGS_address << std::endl;
  server->Wait();
}
}
}

int main(int argc, char** argv) {
  ParseCommandLineFlags(&argc, &argv, true);
  grpc::testing::RunServer();

  return 0;
}


text:
using System;
using System.Diagnostics;

namespace StackingEntities.Desktop.Properties.Annotations
{
	/// <summary>
	/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
	/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>
	/// </summary>
	[AttributeUsage(AttributeTargets.Parameter)]
	[Conditional("JETBRAINS_ANNOTATIONS")]
	public sealed class AspMvcMasterAttribute : Attribute { }
}


text:
#ifndef QPLATFORMINTEGRATION_H
#define QPLATFORMINTEGRATION_H

//
//  W A R N I N G
//  -------------
//
// This file is part of the QPA API and is not meant to be used
// in applications. Usage of this API may make your code
// source and binary incompatible with future versions of Qt.
//

#include <QtGui/qtguiglobal.h>
#include <QtGui/qwindowdefs.h>
#include <qpa/qplatformscreen.h>
#include <QtGui/qsurfaceformat.h>
#include <QtGui/qopenglcontext.h>

QT_BEGIN_NAMESPACE

class QPlatformWindow;
class QWindow;
class QPlatformBackingStore;
class QPlatformFontDatabase;
class QPlatformClipboard;
class QPlatformNativeInterface;
class QPlatformDrag;
class QPlatformOpenGLContext;
class QGuiGLFormat;
class QAbstractEventDispatcher;
class QPlatformInputContext;
class QPlatformAccessibility;
class QPlatformTheme;
class QPlatformDialogHelper;
class QPlatformSharedGraphicsCache;
class QPlatformServices;
class QPlatformSessionManager;
class QKeyEvent;
class QPlatformOffscreenSurface;
class QOffscreenSurface;

class Q_GUI_EXPORT QPlatformIntegration
{
public:
    enum Capability {
        ThreadedPixmaps = 1,
        OpenGL,
        ThreadedOpenGL,
        SharedGraphicsCache,
        BufferQueueingOpenGL,
        WindowMasks,
        MultipleWindows,
        ApplicationState,
        ForeignWindows,
        NonFullScreenWindows,
        NativeWidgets,
        WindowManagement,
        SyncState,
        RasterGLSurface,
        AllGLFunctionsQueryable,
        ApplicationIcon,
        SwitchableWidgetComposition
    };

    virtual ~QPlatformIntegration() { }

    virtual bool hasCapability(Capability cap) const;

    virtual QPlatformPixmap *createPlatformPixmap(QPlatformPixmap::PixelType type) const;
    virtual QPlatformWindow *createPlatformWindow(QWindow *window) const = 0;
    virtual QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const = 0;
#ifndef QT_NO_OPENGL
    virtual QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const;
#endif
    virtual QPlatformSharedGraphicsCache *createPlatformSharedGraphicsCache(const char *cacheId) const;
    virtual QPaintEngine *createImagePaintEngine(QPaintDevice *paintDevice) const;

// Event dispatcher:
    virtual QAbstractEventDispatcher *createEventDispatcher() const = 0;
    virtual void initialize();
    virtual void destroy();

//Deeper window system integrations
    virtual QPlatformFontDatabase *fontDatabase() const;
#ifndef QT_NO_CLIPBOARD
    virtual QPlatformClipboard *clipboard() const;
#endif
#ifndef QT_NO_DRAGANDDROP
    virtual QPlatformDrag *drag() const;
#endif
    virtual QPlatformInputContext *inputContext() const;
#ifndef QT_NO_ACCESSIBILITY
    virtual QPlatformAccessibility *accessibility() const;
#endif

    // Access native handles. The window handle is already available from Wid;
    virtual QPlatformNativeInterface *nativeInterface() const;

    virtual QPlatformServices *services() const;

    enum StyleHint {
        CursorFlashTime,
        KeyboardInputInterval,
        MouseDoubleClickInterval,
        StartDragDistance,
        StartDragTime,
        KeyboardAutoRepeatRate,
        ShowIsFullScreen,
        PasswordMaskDelay,
        FontSmoothingGamma,
        StartDragVelocity,
        UseRtlExtensions,
        PasswordMaskCharacter,
        SetFocusOnTouchRelease,
        ShowIsMaximized,
        MousePressAndHoldInterval,
        TabFocusBehavior,
        ReplayMousePressOutsidePopup,
        ItemViewActivateItemOnSingleClick,
        UiEffects
    };

    virtual QVariant styleHint(StyleHint hint) const;
    virtual Qt::WindowState defaultWindowState(Qt::WindowFlags) const;

    virtual Qt::KeyboardModifiers queryKeyboardModifiers() const;
    virtual QList<int> possibleKeys(const QKeyEvent *) const;

    virtual QStringList themeNames() const;
    virtual QPlatformTheme *createPlatformTheme(const QString &name) const;

    virtual QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const;

#ifndef QT_NO_SESSIONMANAGER
    virtual QPlatformSessionManager *createPlatformSessionManager(const QString &id, const QString &key) const;
#endif

    virtual void sync();

#ifndef QT_NO_OPENGL
    virtual QOpenGLContext::OpenGLModuleType openGLModuleType();
#endif
    virtual void setApplicationIcon(const QIcon &icon) const;

    void removeScreen(QScreen *screen);

    virtual void beep() const;

protected:
    void screenAdded(QPlatformScreen *screen, bool isPrimary = false);
    void destroyScreen(QPlatformScreen *screen);
    void setPrimaryScreen(QPlatformScreen *newPrimary);
};

QT_END_NAMESPACE

#endif // QPLATFORMINTEGRATION_H


text:
package br.com.monitoringDiabeticsApi.controllers;

import javax.validation.Valid;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import br.com.monitoringDiabeticsApi.models.HorarioMedicacao;
import br.com.monitoringDiabeticsApi.services.HorarioMedicacaoService;

@RestController
@RequestMapping("/horario-medicacoes")
public class HorarioMedicacaoController {

	@Autowired
	private HorarioMedicacaoService horarioMedicacaoService;

	@GetMapping
	public ResponseEntity<?> findAll(){
		return ResponseEntity.status(200).body(this.horarioMedicacaoService.findAll());
	}

	@PostMapping
	public ResponseEntity<?> save(@Valid @RequestBody HorarioMedicacao horarioMedicacao) {

		horarioMedicacao = this.horarioMedicacaoService.save(horarioMedicacao);
		return ResponseEntity.ok(horarioMedicacao);
	}

	@PutMapping("/{id}/fim-medicacao")
	public ResponseEntity<?> setFimMedicacao(@PathVariable("id") Integer idHorarioMedicacao){
		try {
			this.horarioMedicacaoService.setFimMedicacao(idHorarioMedicacao);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mensagem", "Pronto, a partir das próximas 24 horas, você não será mais notificado da sua medicação!");
		return ResponseEntity.ok(jsonObject.toString());
		}catch(Exception e) {
			return ResponseEntity.status(500).build();
		}
	}
}


text:
class Vimizer::PostBox
  # ==== Args
  # [pbox] Gtk::TextView
  def initialize(pbox)
    @pbox = pbox
  end

  # ==== Args
  # [to] 移動したい位置
  def go(to)
    pos = @pbox.buffer.cursor_position

    move(:right, to - pos)
  end

  # ==== Args
  # [direction] 移動したい方向。 :up, :down, :right, :left
  # [n] 移動する量
  def move(direction, n)
    step, sign = case direction
      when :up
        [Gtk::MOVEMENT_DISPLAY_LINES, -1]
      when :down
        [Gtk::MOVEMENT_DISPLAY_LINES, 1]
      when :right
        [Gtk::MOVEMENT_VISUAL_POSITIONS, 1]
      when :left
        [Gtk::MOVEMENT_VISUAL_POSITIONS, -1]
      else
        raise ArgumentError, "#{direction} is invalid."
      end

    unless n == 0
      @pbox.move_cursor(step, sign * n, false)
    end
  end

  def delete(position)
    to = case position
      when Integer
        position
      when Range
        position.begin
      else
        raise ArgumentError, "Position should be Integer or Range"
      end

    t = text
    t[position] = ''
    self.text = t

    go(to)
  end

  def text
    return @pbox.buffer.text
  end

  def text=(str)
    @pbox.buffer.text = str
  end

  def cursor_position
    return @pbox.buffer.cursor_position
  end
end


text:
#pragma once

#include "mason/Config.h"
#include "cinder/app/App.h"
#include "cinder/Log.h"

namespace mason {

//! Convenenience routine for common settings that I use with ma::config() within App prepareSettings()
//! - note: I wish I could have placed this method in mason/Config.h alongside the rest of the config stuff,
//!   but well C++ inner classes prevent me from forward declaring App::Settings so we're stuck with this or
//!   other nastier tricks for now
extern void prepareAppSettings( ci::app::App::Settings *settings, const std::vector<ci::fs::path> &configFiles = {} )
{
	if( ! configFiles.empty() ) {
		ma::loadConfig( configFiles );
	}
	else {
		ma::loadConfig();
	}

	auto appConfig = ma::config()->get<ma::Info>( "app" );

	bool fullScreen = appConfig.get( "fullScreen", false );
	bool borderless = appConfig.get( "borderless", false );
	int screenIndex = appConfig.get( "screenIndex", 0 );
	if( screenIndex >= ci::Display::getDisplays().size() ) {
		CI_LOG_W( "config's app.screenIndex out of range (" << screenIndex << ")" );
		screenIndex = 0;
		fullScreen = false;
		borderless = false;
	}

	const auto &display = ci::Display::getDisplays().at( screenIndex );

	CI_LOG_I( "display name: " << display->getName() << ", size: " << display->getSize() );
	settings->setDisplay( display );

	ci::ivec2 windowPos = appConfig.get( "windowPos", ci::ivec2( 8, 50 ) );
	ci::ivec2 windowSize = appConfig.get( "windowSize", ci::ivec2( 1200, 800 ) );

	if( fullScreen && borderless ) {
		// 'fullscreen + borderless' mode, which overcomes some issues with fullscreen on windows
		windowPos = ci::vec2( 0 );
		windowSize = display->getSize() + ci::ivec2( 0, 1 ); // the size is one pixel larger to fully hide the minimized win task bar
	}
	else {
		settings->setFullScreen( fullScreen );
	}

	settings->setBorderless( borderless );

	//settings->setHighDensityDisplayEnabled();

	settings->setWindowPos( windowPos.x, windowPos.y );
	settings->setWindowSize( windowSize.x, windowSize.y );
}

} // namespace mason


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.securityinsights.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.securityinsights.models.Kind;
import com.azure.resourcemanager.securityinsights.models.MetadataAuthor;
import com.azure.resourcemanager.securityinsights.models.MetadataCategories;
import com.azure.resourcemanager.securityinsights.models.MetadataDependencies;
import com.azure.resourcemanager.securityinsights.models.MetadataSource;
import com.azure.resourcemanager.securityinsights.models.MetadataSupport;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
import java.util.List;

/** Metadata property bag. */
@Fluent
public final class MetadataProperties {
    /*
     * Static ID for the content.  Used to identify dependencies and content from solutions or community.
     * Hard-coded/static for out of the box content and solutions. Dynamic for user-created.  This is the resource name
     */
    @JsonProperty(value = "contentId")
    private String contentId;

    /*
     * Full parent resource ID of the content item the metadata is for.  This is the full resource ID including the
     * scope (subscription and resource group)
     */
    @JsonProperty(value = "parentId", required = true)
    private String parentId;

    /*
     * Version of the content.  Default and recommended format is numeric (e.g. 1, 1.0, 1.0.0, 1.0.0.0), following ARM
     * template best practices.  Can also be any string, but then we cannot guarantee any version checks
     */
    @JsonProperty(value = "version")
    private String version;

    /*
     * The kind of content the metadata is for.
     */
    @JsonProperty(value = "kind", required = true)
    private Kind kind;

    /*
     * Source of the content.  This is where/how it was created.
     */
    @JsonProperty(value = "source")
    private MetadataSource source;

    /*
     * The creator of the content item.
     */
    @JsonProperty(value = "author")
    private MetadataAuthor author;

    /*
     * Support information for the metadata - type, name, contact information
     */
    @JsonProperty(value = "support")
    private MetadataSupport support;

    /*
     * Dependencies for the content item, what other content items it requires to work.  Can describe more complex
     * dependencies using a recursive/nested structure. For a single dependency an id/kind/version can be supplied or
     * operator/criteria for complex formats.
     */
    @JsonProperty(value = "dependencies")
    private MetadataDependencies dependencies;

    /*
     * Categories for the solution content item
     */
    @JsonProperty(value = "categories")
    private MetadataCategories categories;

    /*
     * Providers for the solution content item
     */
    @JsonProperty(value = "providers")
    private List<String> providers;

    /*
     * first publish date solution content item
     */
    @JsonProperty(value = "firstPublishDate")
    private LocalDate firstPublishDate;

    /*
     * last publish date for the solution content item
     */
    @JsonProperty(value = "lastPublishDate")
    private LocalDate lastPublishDate;

    /*
     * The custom version of the content. A optional free text
     */
    @JsonProperty(value = "customVersion")
    private String customVersion;

    /*
     * Schema version of the content. Can be used to distinguish between different flow based on the schema version
     */
    @JsonProperty(value = "contentSchemaVersion")
    private String contentSchemaVersion;

    /*
     * the icon identifier. this id can later be fetched from the solution template
     */
    @JsonProperty(value = "icon")
    private String icon;

    /*
     * the tactics the resource covers
     */
    @JsonProperty(value = "threatAnalysisTactics")
    private List<String> threatAnalysisTactics;

    /*
     * the techniques the resource covers, these have to be aligned with the tactics being used
     */
    @JsonProperty(value = "threatAnalysisTechniques")
    private List<String> threatAnalysisTechniques;

    /*
     * preview image file names. These will be taken from the solution artifacts
     */
    @JsonProperty(value = "previewImages")
    private List<String> previewImages;

    /*
     * preview image file names. These will be taken from the solution artifacts. used for dark theme support
     */
    @JsonProperty(value = "previewImagesDark")
    private List<String> previewImagesDark;

    /**
     * Get the contentId property: Static ID for the content. Used to identify dependencies and content from solutions
     * or community. Hard-coded/static for out of the box content and solutions. Dynamic for user-created. This is the
     * resource name.
     *
     * @return the contentId value.
     */
    public String contentId() {
        return this.contentId;
    }

    /**
     * Set the contentId property: Static ID for the content. Used to identify dependencies and content from solutions
     * or community. Hard-coded/static for out of the box content and solutions. Dynamic for user-created. This is the
     * resource name.
     *
     * @param contentId the contentId value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withContentId(String contentId) {
        this.contentId = contentId;
        return this;
    }

    /**
     * Get the parentId property: Full parent resource ID of the content item the metadata is for. This is the full
     * resource ID including the scope (subscription and resource group).
     *
     * @return the parentId value.
     */
    public String parentId() {
        return this.parentId;
    }

    /**
     * Set the parentId property: Full parent resource ID of the content item the metadata is for. This is the full
     * resource ID including the scope (subscription and resource group).
     *
     * @param parentId the parentId value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withParentId(String parentId) {
        this.parentId = parentId;
        return this;
    }

    /**
     * Get the version property: Version of the content. Default and recommended format is numeric (e.g. 1, 1.0, 1.0.0,
     * 1.0.0.0), following ARM template best practices. Can also be any string, but then we cannot guarantee any version
     * checks.
     *
     * @return the version value.
     */
    public String version() {
        return this.version;
    }

    /**
     * Set the version property: Version of the content. Default and recommended format is numeric (e.g. 1, 1.0, 1.0.0,
     * 1.0.0.0), following ARM template best practices. Can also be any string, but then we cannot guarantee any version
     * checks.
     *
     * @param version the version value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withVersion(String version) {
        this.version = version;
        return this;
    }

    /**
     * Get the kind property: The kind of content the metadata is for.
     *
     * @return the kind value.
     */
    public Kind kind() {
        return this.kind;
    }

    /**
     * Set the kind property: The kind of content the metadata is for.
     *
     * @param kind the kind value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withKind(Kind kind) {
        this.kind = kind;
        return this;
    }

    /**
     * Get the source property: Source of the content. This is where/how it was created.
     *
     * @return the source value.
     */
    public MetadataSource source() {
        return this.source;
    }

    /**
     * Set the source property: Source of the content. This is where/how it was created.
     *
     * @param source the source value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withSource(MetadataSource source) {
        this.source = source;
        return this;
    }

    /**
     * Get the author property: The creator of the content item.
     *
     * @return the author value.
     */
    public MetadataAuthor author() {
        return this.author;
    }

    /**
     * Set the author property: The creator of the content item.
     *
     * @param author the author value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withAuthor(MetadataAuthor author) {
        this.author = author;
        return this;
    }

    /**
     * Get the support property: Support information for the metadata - type, name, contact information.
     *
     * @return the support value.
     */
    public MetadataSupport support() {
        return this.support;
    }

    /**
     * Set the support property: Support information for the metadata - type, name, contact information.
     *
     * @param support the support value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withSupport(MetadataSupport support) {
        this.support = support;
        return this;
    }

    /**
     * Get the dependencies property: Dependencies for the content item, what other content items it requires to work.
     * Can describe more complex dependencies using a recursive/nested structure. For a single dependency an
     * id/kind/version can be supplied or operator/criteria for complex formats.
     *
     * @return the dependencies value.
     */
    public MetadataDependencies dependencies() {
        return this.dependencies;
    }

    /**
     * Set the dependencies property: Dependencies for the content item, what other content items it requires to work.
     * Can describe more complex dependencies using a recursive/nested structure. For a single dependency an
     * id/kind/version can be supplied or operator/criteria for complex formats.
     *
     * @param dependencies the dependencies value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withDependencies(MetadataDependencies dependencies) {
        this.dependencies = dependencies;
        return this;
    }

    /**
     * Get the categories property: Categories for the solution content item.
     *
     * @return the categories value.
     */
    public MetadataCategories categories() {
        return this.categories;
    }

    /**
     * Set the categories property: Categories for the solution content item.
     *
     * @param categories the categories value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withCategories(MetadataCategories categories) {
        this.categories = categories;
        return this;
    }

    /**
     * Get the providers property: Providers for the solution content item.
     *
     * @return the providers value.
     */
    public List<String> providers() {
        return this.providers;
    }

    /**
     * Set the providers property: Providers for the solution content item.
     *
     * @param providers the providers value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withProviders(List<String> providers) {
        this.providers = providers;
        return this;
    }

    /**
     * Get the firstPublishDate property: first publish date solution content item.
     *
     * @return the firstPublishDate value.
     */
    public LocalDate firstPublishDate() {
        return this.firstPublishDate;
    }

    /**
     * Set the firstPublishDate property: first publish date solution content item.
     *
     * @param firstPublishDate the firstPublishDate value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withFirstPublishDate(LocalDate firstPublishDate) {
        this.firstPublishDate = firstPublishDate;
        return this;
    }

    /**
     * Get the lastPublishDate property: last publish date for the solution content item.
     *
     * @return the lastPublishDate value.
     */
    public LocalDate lastPublishDate() {
        return this.lastPublishDate;
    }

    /**
     * Set the lastPublishDate property: last publish date for the solution content item.
     *
     * @param lastPublishDate the lastPublishDate value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withLastPublishDate(LocalDate lastPublishDate) {
        this.lastPublishDate = lastPublishDate;
        return this;
    }

    /**
     * Get the customVersion property: The custom version of the content. A optional free text.
     *
     * @return the customVersion value.
     */
    public String customVersion() {
        return this.customVersion;
    }

    /**
     * Set the customVersion property: The custom version of the content. A optional free text.
     *
     * @param customVersion the customVersion value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withCustomVersion(String customVersion) {
        this.customVersion = customVersion;
        return this;
    }

    /**
     * Get the contentSchemaVersion property: Schema version of the content. Can be used to distinguish between
     * different flow based on the schema version.
     *
     * @return the contentSchemaVersion value.
     */
    public String contentSchemaVersion() {
        return this.contentSchemaVersion;
    }

    /**
     * Set the contentSchemaVersion property: Schema version of the content. Can be used to distinguish between
     * different flow based on the schema version.
     *
     * @param contentSchemaVersion the contentSchemaVersion value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withContentSchemaVersion(String contentSchemaVersion) {
        this.contentSchemaVersion = contentSchemaVersion;
        return this;
    }

    /**
     * Get the icon property: the icon identifier. this id can later be fetched from the solution template.
     *
     * @return the icon value.
     */
    public String icon() {
        return this.icon;
    }

    /**
     * Set the icon property: the icon identifier. this id can later be fetched from the solution template.
     *
     * @param icon the icon value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withIcon(String icon) {
        this.icon = icon;
        return this;
    }

    /**
     * Get the threatAnalysisTactics property: the tactics the resource covers.
     *
     * @return the threatAnalysisTactics value.
     */
    public List<String> threatAnalysisTactics() {
        return this.threatAnalysisTactics;
    }

    /**
     * Set the threatAnalysisTactics property: the tactics the resource covers.
     *
     * @param threatAnalysisTactics the threatAnalysisTactics value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withThreatAnalysisTactics(List<String> threatAnalysisTactics) {
        this.threatAnalysisTactics = threatAnalysisTactics;
        return this;
    }

    /**
     * Get the threatAnalysisTechniques property: the techniques the resource covers, these have to be aligned with the
     * tactics being used.
     *
     * @return the threatAnalysisTechniques value.
     */
    public List<String> threatAnalysisTechniques() {
        return this.threatAnalysisTechniques;
    }

    /**
     * Set the threatAnalysisTechniques property: the techniques the resource covers, these have to be aligned with the
     * tactics being used.
     *
     * @param threatAnalysisTechniques the threatAnalysisTechniques value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withThreatAnalysisTechniques(List<String> threatAnalysisTechniques) {
        this.threatAnalysisTechniques = threatAnalysisTechniques;
        return this;
    }

    /**
     * Get the previewImages property: preview image file names. These will be taken from the solution artifacts.
     *
     * @return the previewImages value.
     */
    public List<String> previewImages() {
        return this.previewImages;
    }

    /**
     * Set the previewImages property: preview image file names. These will be taken from the solution artifacts.
     *
     * @param previewImages the previewImages value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withPreviewImages(List<String> previewImages) {
        this.previewImages = previewImages;
        return this;
    }

    /**
     * Get the previewImagesDark property: preview image file names. These will be taken from the solution artifacts.
     * used for dark theme support.
     *
     * @return the previewImagesDark value.
     */
    public List<String> previewImagesDark() {
        return this.previewImagesDark;
    }

    /**
     * Set the previewImagesDark property: preview image file names. These will be taken from the solution artifacts.
     * used for dark theme support.
     *
     * @param previewImagesDark the previewImagesDark value to set.
     * @return the MetadataProperties object itself.
     */
    public MetadataProperties withPreviewImagesDark(List<String> previewImagesDark) {
        this.previewImagesDark = previewImagesDark;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (parentId() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property parentId in model MetadataProperties"));
        }
        if (kind() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property kind in model MetadataProperties"));
        }
        if (source() != null) {
            source().validate();
        }
        if (author() != null) {
            author().validate();
        }
        if (support() != null) {
            support().validate();
        }
        if (dependencies() != null) {
            dependencies().validate();
        }
        if (categories() != null) {
            categories().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(MetadataProperties.class);
}


text:
from __future__ import annotations

import json
from copy import deepcopy
from enum import Enum
from string import Template as pTemplate
from typing import List, Optional, Union

from marshmallow import INCLUDE, Schema, fields, post_dump, post_load

from great_expectations.render.exceptions import InvalidRenderedContentError
from great_expectations.types import DictDot

class RendererPrefix(str, Enum):
    """Available renderer prefixes"""

    LEGACY = "renderer"
    ATOMIC = "atomic"

class AtomicRendererType(str, Enum):
    """Available atomic renderer types"""

    PRESCRIPTIVE = ".".join([RendererPrefix.ATOMIC, "prescriptive"])
    DIAGNOSTIC = ".".join([RendererPrefix.ATOMIC, "diagnostic"])

class AtomicPrescriptiveRendererType(str, Enum):
    """Available atomic prescriptive renderer names"""

    FAILED = ".".join([AtomicRendererType.PRESCRIPTIVE, "failed"])
    SUMMARY = ".".join([AtomicRendererType.PRESCRIPTIVE, "summary"])

    def __str__(self):
        return self.value

class AtomicDiagnosticRendererType(str, Enum):
    """Available atomic diagnostic renderer names"""

    FAILED = ".".join([AtomicRendererType.DIAGNOSTIC, "failed"])
    OBSERVED_VALUE = ".".join([AtomicRendererType.DIAGNOSTIC, "observed_value"])

    def __str__(self):
        return self.value

class LegacyRendererType(str, Enum):
    """Available legacy renderer types"""

    ANSWER = ".".join([RendererPrefix.LEGACY, "answer"])
    DESCRIPTIVE = ".".join([RendererPrefix.LEGACY, "descriptive"])
    DIAGNOSTIC = ".".join([RendererPrefix.LEGACY, "diagnostic"])
    PRESCRIPTIVE = ".".join([RendererPrefix.LEGACY, "prescriptive"])
    QUESTION = ".".join([RendererPrefix.LEGACY, "question"])

class LegacyPrescriptiveRendererType(str, Enum):
    """Available legacy prescriptive renderer names"""

    SUMMARY = ".".join([LegacyRendererType.PRESCRIPTIVE, "summary"])

class LegacyDiagnosticRendererType(str, Enum):
    """Available legacy diagnostic renderer names"""

    META_PROPERTIES = ".".join([LegacyRendererType.DIAGNOSTIC, "meta_properties"])
    OBSERVED_VALUE = ".".join([LegacyRendererType.DIAGNOSTIC, "observed_value"])
    STATUS_ICON = ".".join([LegacyRendererType.DIAGNOSTIC, "status_icon"])
    SUMMARY = ".".join([LegacyRendererType.DIAGNOSTIC, "summary"])
    UNEXPECTED_STATEMENT = ".".join(
        [LegacyRendererType.DIAGNOSTIC, "unexpected_statement"]
    )
    UNEXPECTED_TABLE = ".".join([LegacyRendererType.DIAGNOSTIC, "unexpected_table"])

class LegacyDescriptiveRendererType(str, Enum):
    """Available legacy descriptive renderer names"""

    COLUMN_PROPERTIES_TABLE_DISTINCT_COUNT_ROW = ".".join(
        [
            LegacyRendererType.DESCRIPTIVE,
            "column_properties_table",
            "distinct_count_row",
        ]
    )
    COLUMN_PROPERTIES_TABLE_DISTINCT_PERCENT_ROW = ".".join(
        [
            LegacyRendererType.DESCRIPTIVE,
            "column_properties_table",
            "distinct_percent_row",
        ]
    )
    COLUMN_PROPERTIES_TABLE_MISSING_COUNT_ROW = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "column_properties_table", "missing_count_row"]
    )
    COLUMN_PROPERTIES_TABLE_MISSING_PERCENT_ROW = ".".join(
        [
            LegacyRendererType.DESCRIPTIVE,
            "column_properties_table",
            "missing_percent_row",
        ]
    )
    COLUMN_PROPERTIES_TABLE_REGEX_COUNT_ROW = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "column_properties_table", "regex_count_row"]
    )
    EXAMPLE_VALUES_BLOCK = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "example_values_block"]
    )
    HISTOGRAM = ".".join([LegacyRendererType.DESCRIPTIVE, "histogram"])
    QUANTILE_TABLE = ".".join([LegacyRendererType.DESCRIPTIVE, "quantile_table"])
    STATS_TABLE_MAX_ROW = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "stats_table", "max_row"]
    )
    STATS_TABLE_MEAN_ROW = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "stats_table", "mean_row"]
    )
    STATS_TABLE_MIN_ROW = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "stats_table", "min_row"]
    )
    VALUE_COUNTS_BAR_CHART = ".".join(
        [LegacyRendererType.DESCRIPTIVE, "value_counts_bar_chart"]
    )

class RenderedContent:
    def to_json_dict(self):
        return {}

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            # Delegate comparison to the other instance's __eq__.
            return NotImplemented
        return self.to_json_dict() == other.to_json_dict()

    @classmethod
    def rendered_content_list_to_json(cls, list_, check_dicts=False):
        result_list = []
        for item in list_:
            if isinstance(item, RenderedContent):
                result_list.append(item.to_json_dict())
            elif isinstance(item, list):
                result_list.append(
                    RenderedContent.rendered_content_list_to_json(
                        item, check_dicts=check_dicts
                    )
                )
            elif check_dicts and isinstance(item, dict):
                result_list.append(cls.rendered_content_dict_to_json(item))
            else:
                result_list.append(item)
        return result_list

    @classmethod
    def rendered_content_dict_to_json(cls, dict_, check_list_dicts=True):
        json_dict = deepcopy(dict_)
        for key, val in json_dict.items():
            if not isinstance(val, (RenderedContent, list, dict)):
                continue
            elif isinstance(val, RenderedContent):
                json_dict[key] = val.to_json_dict()
            elif isinstance(val, list):
                json_dict[key] = cls.rendered_content_list_to_json(
                    val, check_list_dicts
                )
            elif isinstance(val, dict):
                json_dict[key] = cls.rendered_content_dict_to_json(
                    val, check_list_dicts
                )
        return json_dict

class RenderedComponentContent(RenderedContent):
    def __init__(self, content_block_type, styling=None) -> None:
        self.content_block_type = content_block_type
        if styling is None:
            styling = {}
        self.styling = styling

    def to_json_dict(self):
        d = super().to_json_dict()
        d["content_block_type"] = self.content_block_type
        if len(self.styling) > 0:
            d["styling"] = self.styling
        return d

class RenderedHeaderContent(RenderedComponentContent):
    def __init__(
        self,
        header,
        subheader=None,
        header_row=None,
        styling=None,
        content_block_type="header",
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.header = header
        self.header_row = header_row
        self.subheader = subheader

    def to_json_dict(self):
        d = super().to_json_dict()
        if isinstance(self.header, RenderedContent):
            d["header"] = self.header.to_json_dict()
        else:
            d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        if self.header_row:
            d["header_row"] = self.header_row
        return d

class RenderedGraphContent(RenderedComponentContent):
    def __init__(
        self,
        graph,
        header=None,
        subheader=None,
        styling=None,
        content_block_type="graph",
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.graph = graph
        self.header = header
        self.subheader = subheader

    def to_json_dict(self):
        d = super().to_json_dict()
        d["graph"] = self.graph
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        return d

class RenderedTableContent(RenderedComponentContent):
    def __init__(
        self,
        table,
        header=None,
        subheader=None,
        header_row=None,
        styling=None,
        content_block_type="table",
        table_options=None,
        header_row_options=None,
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.header = header
        self.subheader = subheader
        self.table = table
        self.table_options = table_options
        self.header_row = header_row
        self.header_row_options = header_row_options

    def to_json_dict(self):
        d = super().to_json_dict()
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        d["table"] = RenderedContent.rendered_content_list_to_json(self.table)
        if self.header_row is not None:
            d["header_row"] = RenderedContent.rendered_content_list_to_json(
                self.header_row
            )
        if self.header_row_options is not None:
            d["header_row_options"] = self.header_row_options
        if self.table_options is not None:
            d["table_options"] = self.table_options
        return d

class RenderedTabsContent(RenderedComponentContent):
    def __init__(
        self, tabs, header=None, subheader=None, styling=None, content_block_type="tabs"
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.tabs = tabs
        self.header = header
        self.subheader = subheader

    def to_json_dict(self):
        d = super().to_json_dict()
        d["tabs"] = RenderedContent.rendered_content_list_to_json(
            self.tabs, check_dicts=True
        )
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        return d

class RenderedBootstrapTableContent(RenderedComponentContent):
    def __init__(
        self,
        table_data,
        table_columns,
        title_row=None,
        table_options=None,
        header=None,
        subheader=None,
        styling=None,
        content_block_type="bootstrap_table",
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.table_data = table_data
        self.table_columns = table_columns
        self.title_row = title_row
        self.table_options = table_options
        self.header = header
        self.subheader = subheader

    def to_json_dict(self):
        d = super().to_json_dict()
        d["table_data"] = RenderedContent.rendered_content_list_to_json(
            self.table_data, check_dicts=True
        )
        d["table_columns"] = RenderedContent.rendered_content_list_to_json(
            self.table_columns, check_dicts=True
        )
        if self.table_options is not None:
            d["table_options"] = self.table_options
        if self.title_row is not None:
            if isinstance(self.title_row, RenderedContent):
                d["title_row"] = self.title_row.to_json_dict()
            else:
                d["title_row"] = self.title_row
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        return d

class RenderedContentBlockContainer(RenderedComponentContent):
    def __init__(
        self, content_blocks, styling=None, content_block_type="content_block_container"
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.content_blocks = content_blocks

    def to_json_dict(self):
        d = super().to_json_dict()
        d["content_blocks"] = RenderedContent.rendered_content_list_to_json(
            self.content_blocks
        )
        return d

class RenderedMarkdownContent(RenderedComponentContent):
    def __init__(self, markdown, styling=None, content_block_type="markdown") -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.markdown = markdown

    def to_json_dict(self):
        d = super().to_json_dict()
        d["markdown"] = self.markdown
        return d

class RenderedStringTemplateContent(RenderedComponentContent):
    def __init__(
        self, string_template, styling=None, content_block_type="string_template"
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.string_template = string_template

    def to_json_dict(self):
        d = super().to_json_dict()
        d["string_template"] = self.string_template
        return d

    def __str__(self):
        string = pTemplate(self.string_template["template"]).safe_substitute(
            self.string_template["params"]
        )
        return string

    def __eq__(self, other):
        return str(self) == str(other)

class RenderedBulletListContent(RenderedComponentContent):
    def __init__(
        self,
        bullet_list,
        header=None,
        subheader=None,
        styling=None,
        content_block_type="bullet_list",
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.header = header
        self.subheader = subheader
        self.bullet_list = bullet_list

    def to_json_dict(self):
        d = super().to_json_dict()
        d["bullet_list"] = RenderedContent.rendered_content_list_to_json(
            self.bullet_list
        )
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        return d

class ValueListContent(RenderedComponentContent):
    def __init__(
        self,
        value_list,
        header=None,
        subheader=None,
        styling=None,
        content_block_type="value_list",
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.header = header
        self.subheader = subheader
        self.value_list = value_list

    def to_json_dict(self):
        d = super().to_json_dict()
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        d["value_list"] = RenderedContent.rendered_content_list_to_json(self.value_list)
        return d

class TextContent(RenderedComponentContent):
    def __init__(
        self, text, header=None, subheader=None, styling=None, content_block_type="text"
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.text = text
        self.header = header
        self.subheader = subheader

    def to_json_dict(self):
        d = super().to_json_dict()
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        d["text"] = RenderedContent.rendered_content_list_to_json(self.text)

        return d

class CollapseContent(RenderedComponentContent):
    def __init__(
        self,
        collapse,
        collapse_toggle_link=None,
        header=None,
        subheader=None,
        styling=None,
        content_block_type="collapse",
        inline_link=False,
    ) -> None:
        super().__init__(content_block_type=content_block_type, styling=styling)
        self.collapse_toggle_link = collapse_toggle_link
        self.header = header
        self.subheader = subheader
        self.collapse = collapse
        self.inline_link = inline_link

    def to_json_dict(self):
        d = super().to_json_dict()
        if self.header is not None:
            if isinstance(self.header, RenderedContent):
                d["header"] = self.header.to_json_dict()
            else:
                d["header"] = self.header
        if self.subheader is not None:
            if isinstance(self.subheader, RenderedContent):
                d["subheader"] = self.subheader.to_json_dict()
            else:
                d["subheader"] = self.subheader
        if self.collapse_toggle_link is not None:
            if isinstance(self.collapse_toggle_link, RenderedContent):
                d["collapse_toggle_link"] = self.collapse_toggle_link.to_json_dict()
            else:
                d["collapse_toggle_link"] = self.collapse_toggle_link
        d["collapse"] = RenderedContent.rendered_content_list_to_json(self.collapse)
        d["inline_link"] = self.inline_link

        return d

class RenderedDocumentContent(RenderedContent):
    # NOTE: JPC 20191028 - review these keys to consolidate and group
    def __init__(
        self,
        sections,
        data_asset_name=None,
        full_data_asset_identifier=None,
        renderer_type=None,
        page_title=None,
        utm_medium=None,
        cta_footer=None,
        expectation_suite_name=None,
        batch_kwargs=None,
        batch_spec=None,
        ge_cloud_id=None,
    ) -> None:
        if not isinstance(sections, list) and all(
            [isinstance(section, RenderedSectionContent) for section in sections]
        ):
            raise InvalidRenderedContentError(
                "RenderedDocumentContent requires a list of RenderedSectionContent for "
                "sections."
            )
        self.sections = sections
        self.data_asset_name = data_asset_name
        self.full_data_asset_identifier = full_data_asset_identifier
        self.renderer_type = renderer_type
        self.page_title = page_title
        self.utm_medium = utm_medium
        self.cta_footer = cta_footer
        self.expectation_suite_name = expectation_suite_name
        self.batch_kwargs = batch_kwargs
        self.batch_spec = batch_spec
        self.ge_cloud_id = ge_cloud_id

    def to_json_dict(self):
        d = super().to_json_dict()
        d["sections"] = RenderedContent.rendered_content_list_to_json(self.sections)
        d["data_asset_name"] = self.data_asset_name
        d["full_data_asset_identifier"] = self.full_data_asset_identifier
        d["renderer_type"] = self.renderer_type
        d["page_title"] = self.page_title
        d["utm_medium"] = self.utm_medium
        d["cta_footer"] = self.cta_footer
        d["expectation_suite_name"] = self.expectation_suite_name
        d["batch_kwargs"] = self.batch_kwargs
        d["batch_spec"] = self.batch_spec
        d["ge_cloud_id"] = self.ge_cloud_id
        return d

class RenderedSectionContent(RenderedContent):
    def __init__(self, content_blocks, section_name=None) -> None:
        if not isinstance(content_blocks, list) and all(
            [
                isinstance(content_block, RenderedComponentContent)
                for content_block in content_blocks
            ]
        ):
            raise InvalidRenderedContentError(
                "Rendered section content requires a list of RenderedComponentContent "
                "for content blocks."
            )
        self.content_blocks = content_blocks
        self.section_name = section_name

    def to_json_dict(self) -> dict:
        d = super().to_json_dict()
        d["content_blocks"] = RenderedContent.rendered_content_list_to_json(
            self.content_blocks
        )
        d["section_name"] = self.section_name
        return d

class RenderedAtomicValue(DictDot):
    def __init__(
        self,
        schema: Optional[dict] = None,
        header: Optional[RenderedAtomicValue] = None,
        template: Optional[str] = None,
        params: Optional[dict] = None,
        header_row: Optional[List[RenderedAtomicValue]] = None,
        table: Optional[List[List[RenderedAtomicValue]]] = None,
        graph: Optional[dict] = None,
    ) -> None:
        self.schema: Optional[dict] = schema
        self.header: Optional[RenderedAtomicValue] = header

        # StringValueType
        self.template: Optional[str] = template
        self.params: Optional[dict] = params

        # TableType
        self.header_row: Optional[List[RenderedAtomicValue]] = header_row
        self.table: Optional[List[List[RenderedAtomicValue]]] = table

        # GraphType
        self.graph = RenderedAtomicValueGraph(graph=graph)

    def __repr__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def __str__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def to_json_dict(self) -> dict:
        """Returns RenderedAtomicValue as a json dictionary."""
        d = renderedAtomicValueSchema.dump(self)
        json_dict: dict = {}
        for key in d:
            if key == "graph":
                json_dict[key] = getattr(self, key).to_json_dict()
            else:
                json_dict[key] = getattr(self, key)
        return json_dict

class RenderedAtomicValueGraph(DictDot):
    def __init__(
        self,
        graph: Optional[dict] = None,
    ):
        self.graph = graph

    def __repr__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def __str__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def to_json_dict(self) -> Optional[dict]:
        """Returns RenderedAtomicValueGraph as a json dictionary."""
        return self.graph

class RenderedAtomicValueSchema(Schema):
    class Meta:
        unknown = INCLUDE

    schema = fields.Dict(required=False, allow_none=True)
    header = fields.Dict(required=False, allow_none=True)

    # for StringValueType
    template = fields.String(required=False, allow_none=True)
    params = fields.Dict(required=False, allow_none=True)

    # for TableType
    header_row = fields.List(fields.Dict, required=False, allow_none=True)
    table = fields.List(fields.List(fields.Dict, required=False, allow_none=True))

    # for GraphType
    graph = fields.Dict(required=False, allow_none=True)

    @post_load
    def create_value_obj(self, data, **kwargs):
        return RenderedAtomicValue(**data)

    REMOVE_KEYS_IF_NONE = [
        "template",
        "table",
        "params",
        "header_row",
        "table",
        "graph",
    ]

    @post_dump
    def clean_null_attrs(self, data: dict, **kwargs: dict) -> dict:
        """Removes the attributes in RenderedAtomicValueSchema.REMOVE_KEYS_IF_NONE during serialization if
        their values are None."""
        data = deepcopy(data)
        for key in RenderedAtomicValueSchema.REMOVE_KEYS_IF_NONE:
            if (
                key == "graph"
                and key in data
                and data.get(key, {}).get("graph") is None
            ):
                data.pop(key)
            elif key in data and data[key] is None:
                data.pop(key)
        return data

class RenderedAtomicContent(RenderedContent):
    def __init__(
        self,
        name: Union[str, AtomicDiagnosticRendererType, AtomicPrescriptiveRendererType],
        value: RenderedAtomicValue,
        value_type: Optional[str] = None,
    ) -> None:
        # str conversion is performed to ensure Enum value is what is serialized
        self.name = str(name)
        self.value = value
        self.value_type = value_type

    def __repr__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def __str__(self) -> str:
        return json.dumps(self.to_json_dict(), indent=2)

    def to_json_dict(self) -> dict:
        """Returns RenderedAtomicContent as a json dictionary."""
        d = super().to_json_dict()
        d["name"] = self.name
        d["value"] = self.value.to_json_dict()
        d["value_type"] = self.value_type
        return d

class RenderedAtomicContentSchema(Schema):
    class Meta:
        unknown: INCLUDE

    name = fields.String(required=False, allow_none=True)
    value = fields.Nested(RenderedAtomicValueSchema(), required=True, allow_none=False)
    value_type = fields.String(required=True, allow_none=False)

    @post_load
    def make_rendered_atomic_content(self, data, **kwargs):
        return RenderedAtomicContent(**data)

renderedAtomicValueSchema = RenderedAtomicValueSchema()


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


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;

using System.Security.Claims;

namespace System.ServiceModel.Security
{
    internal class SecurityTokenAuthenticatorAdapter : SecurityTokenAuthenticator
    {
        SecurityTokenHandler _securityTokenHandler;
        ExceptionMapper _exceptionMapper;

        public SecurityTokenAuthenticatorAdapter(SecurityTokenHandler securityTokenHandler, ExceptionMapper exceptionMapper)
        {
            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _securityTokenHandler = securityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }

        protected override bool CanValidateTokenCore(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            return ((token.GetType() == _securityTokenHandler.TokenType) && (_securityTokenHandler.CanValidateToken));
        }

        protected sealed override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            IEnumerable<ClaimsIdentity> subjectCollection = null;

            try
            {
                subjectCollection = _securityTokenHandler.ValidateToken(token);
            }
            catch (Exception ex)
            {
                if (!_exceptionMapper.HandleSecurityTokenProcessingException(ex))
                {
                    throw;
                }
            }

            List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
            policies.Add(new AuthorizationPolicy(subjectCollection));
            return policies.AsReadOnly();
        }
    }
}


text:
<?php
namespace Transcomics\GoogleTranslation\ServiceProvider;

use Illuminate\Support\ServiceProvider;

class GoogleTranslationServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {
        // Register 'googleTranslation' instance container to our GoogleTranslation object
        $this->app['googleTranslation'] = $this->app->share(function ($app) {

            $translator = new \Transcomics\GoogleTranslation\GoogleTranslation();
            return $translator;
        });
    }
}


text:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from run import app
from app import db

app.config.from_object('app.config')

db.init_app(app)

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#f5f5f5"
    android:paddingLeft="72dp"
    android:paddingRight="72dp"
    android:paddingTop="36dp"
    android:paddingBottom="36dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <org.ayo.view.progress.shape.LoadingView
        android:id="@+id/loadView"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>