text:
package org.tap4j.model;

/**
 * TAP Plan. The TAP Plan gives details about the execution of the tests such as
 * initial test number, last test number, flag to skip all tests and a reason
 * for this.
 *
 * @since 1.0
 */
public class Plan extends TapElement {

    /**
     * Serial Version UID.
     */
    private static final long serialVersionUID = 8517740981464132024L;

    /**
     * Default initial test step.
     */
    private static final Integer INITIAL_TEST_STEP = 1;

    /**
     * TAP Plan initial test number.
     */
    private final Integer initialTestNumber;

    /**
     * TAP Plan last test number.
     */

    private final Integer lastTestNumber;

    /**
     * TAP Plan skip. If present the tests should not be executed.
     */
    private SkipPlan skip;

    /**
     * Child subtest.
     */
    private TestSet subtest;

    /**
     * Constructor with parameters.
     *
     * @param initialTestNumber Initial test number (usually is 1).
     * @param lastTestNumber Last test number (may be 0 if to skip all tests).
     */
    public Plan(Integer initialTestNumber, Integer lastTestNumber) {
        super();
        this.initialTestNumber = initialTestNumber;
        this.lastTestNumber = lastTestNumber;
        this.subtest = null;
    }

    /**
     * Constructor with parameters.
     *
     * @param amountOfTests How many tests we have in the plan.
     */
    public Plan(Integer amountOfTests) {
        super();
        this.initialTestNumber = INITIAL_TEST_STEP;
        this.lastTestNumber = amountOfTests;
    }

    /**
     * Constructor with parameters.
     *
     * @param amountOfTests How many tests we have in the plan.
     * @param skip Plan skip with a reason.
     */
    public Plan(Integer amountOfTests, SkipPlan skip) {
        super();
        this.initialTestNumber = INITIAL_TEST_STEP;
        this.lastTestNumber = amountOfTests;
        this.skip = skip;
    }

    /**
     * Constructor with parameters.
     *
     * @param initialTestNumber Initial test number (usually is 1).
     * @param lastTestNumber Last test number (may be 0 if to skip all tests).
     * @param skip Plan skip with a reason.
     */
    public Plan(Integer initialTestNumber, Integer lastTestNumber, SkipPlan skip) {
        super();
        this.initialTestNumber = initialTestNumber;
        this.lastTestNumber = lastTestNumber;
        this.skip = skip;
    }

    /**
     * @return Initial test number.
     */
    public Integer getInitialTestNumber() {
        return this.initialTestNumber;
    }

    /**
     * @return Last test number.
     */
    public Integer getLastTestNumber() {
        return this.lastTestNumber;
    }

    /**
     * @return Flag used to indicate whether skip all tests or not.
     */
    public Boolean isSkip() {
        return this.skip != null;
    }

    /**
     * @return Plan Skip with reason.
     */
    public SkipPlan getSkip() {
        return this.skip;
    }

    /**
     * Defines whether we should skip all tests or not.
     *
     * @param skip Plan Skip.
     */
    public void setSkip(SkipPlan skip) {
        this.skip = skip;
    }

    /**
     * @return the subtest
     */
    public TestSet getSubtest() {
        return subtest;
    }

    /**
     * @param subtest the subtest to set
     */
    public void setSubtest(TestSet subtest) {
        this.subtest = subtest;
    }
}


text: /*Add custom css here*/

redpajama_set_name: RedPajamaGithub


text:
We follow the preference in metadata files. If it doesn't state in the metadata, default is not to sign the SAML Request.

In IdP's metadata, there is an attribute called `WantAuthnRequestsSigned`. Default value is `false`.

```xml
<IDPSSODescriptor
    WantAuthnRequestsSigned="true"
    ID="SM14a93e72cb19411b4fc4eec882c98b12dbf55cea68e"
    protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
```
In SP's metadata, there is an attribute called `AuthnRequestsSigned`. Default value is `false`.

```xml
<SPSSODescriptor
    AuthnRequestsSigned="true"
    protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
```

and include the X.509 certificate in SP's metadata.

```xml
<SPSSODescriptor
    AuthnRequestsSigned="true"
    WantAssertionsSigned="true"
    protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">

    <KeyDescriptor use="signing">
        <KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <X509Data>
                <X509Certificate>MIIDozCCAougAwIBAgIJAKN...</X509Certificate>
            </X509Data>
        </KeyInfo>
    </KeyDescriptor>
...
```

If both two attributes are not matched, an error will be thrown out during run-time. Developers can easily locate the error.

If IdP doesn't provide the metadata for you, 1) you may ask them 2) import an object setting, see advanced topics [here]().

Metadata stores the preferences only. To sign a XML document, we still need our **private key** and **signature algorithm**. We can configure our SP here:

```javascript
const saml = require('samlify');
// Define the setting
const setting = {
	privateKey: fs.readFileSync('./key/sp_key.pem'),
	privateKeyPass: 'KCkGOSjrcAuXFwU1pVH5RUiBcrsNA8px',
	requestSignatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512',
	metadata: fs.readFileSync('./metadata_sp.xml')
};
// Construct our service provider
const sp = saml.ServiceProvider(setting);
```

The property `privateKeyPass` is optional in case you have set a passphrase when the private key is created. Also the default value of `requestSignatureAlgorithm` is RSA-SHA1.

All support signature algorithms:
```javascript
'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'
```
Once you have configured the SP correctly, all you need to send a signed SAML Request is to do as follow:

```javascript
router.get('/spinitsso-redirect', (req, res) => {
  const { id, context } = sp.createLoginRequest(idp, 'redirect');
  return res.redirect(context);
});
```

Yes, it's the same method we used to send a SAML Request without signature.

**How to generate a signature**

For those who are not interested in how the signature generates, you can skip this section. The signature is generated by two different formats.

In **Redirect-Binding**, the URL-encoded message should be assigned as follow:

+ Octet string is a concatenation of SAMLRequest, RelayState and SigAlg.`SAMLRequest=xxx&RelayState=yyy&SigAlg=zzz`
+ Signature MUST be encoded by base64 encoding.
+ RelayState is an optional parameter. If there is no RelayState value, this parameter should be ignored from computing signature. e.g. `SAMLRequest=xxx&SigAlg=zzz`

In **Post-Binding**, XML digital signature is used and embedded inside the Request XML.

```xml
<samlp:AuthnRequest
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="_809707f0030a5d00620c9d9df97f627afe9dcc24"
    Version="2.0"
    ProviderName="SP test"
    IssueInstant="2014-07-16T23:52:45Z"
    Destination="https://idp.example.org/SSOService"
    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    AssertionConsumerServiceURL="https://sp.example.org/sso/acs">

    <saml:Issuer ID="_0">https://sp.example.org/metadata</saml:Issuer>
    <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" AllowCreate="true"/>
        <samlp:RequestedAuthnContext Comparison="exact">
            <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
        </samlp:RequestedAuthnContext>

        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
                <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                <Reference URI="#_0">
                    <Transforms>
                        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    </Transforms>
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                    <DigestValue>tQDisBXKTQ+9OXJO5r7KuJga+KI=</DigestValue>
                </Reference>
            </SignedInfo>
            <SignatureValue>oxRkvau7UvYgFEZ7YNAUNf3067V7Tn5C9XSIiet1aZw2FYevNW5bUy/0mxp3aj6AvfFjnmpzAb88BjdwAz2BErDTomRcuZB7Lb0fYTf31N2oZOX0MiPiQOH54I63qJW4Xo3VqdF7GBuFZZHyllfSBv7gfCtjJDwFSCzWK70B9r3cFMRJZLhCJ9oPen+4U9scSYO6g+szBZLl6AiJ06PHc8jzEKGwfQrcZk8kDKUlvNfJMULyq8dpx2VvUAx4p5ewfMOwB9W3Hl3PPa0dO77zZif3CglpcN06f+m6UYG/wnoTQEyKW9hOe+2vGM80W77eWu0dmiaPuqT1ok8LXPuq1A==</SignatureValue>
        </Signature>
</samlp:AuthnRequest>
```


text:
{replace_label}
<input type="file" id="{replace_id}" name="{replace_name}" value="{replace_value}" {extra_attributes} />


text:
<?php

namespace Nuwira\Bandrek\Notification;

class ResetPassword extends BandrekNotification
{
}


text:
package uk.ac.ebi.biosamples.model.facet.content;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FacetContentDeserializer extends JsonDeserializer<FacetContent> {

  @Override
  public FacetContent deserialize(JsonParser p, DeserializationContext ctxt)
      throws IOException, JsonParseException {
    JsonNode root = p.readValueAsTree();
    if (root.isArray()) {
      // If the json is an array, I'm assuming it to be a LabelCountListContent facet content
      return parseLabelCountListContent(root);
    }
    throw new JsonParseException(p, "Unable to parse facet content");
  }

  /**
   * Deserialize the Json to a LabelCountListContent
   *
   * @param jsonArray the Json Array representing LabelCountListContent
   * @return LabelCountListContent
   */
  private LabelCountListContent parseLabelCountListContent(JsonNode jsonArray) {
    List<LabelCountEntry> labelCountList = new ArrayList<>();
    for (JsonNode labelCountJsonEntry : jsonArray) {
      String label = labelCountJsonEntry.get("label").asText();
      Long count = labelCountJsonEntry.get("count").asLong();
      labelCountList.add(LabelCountEntry.build(label, count));
    }
    return new LabelCountListContent(labelCountList);
  }
}


text:
namespace PythonSharp.Tests.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using PythonSharp.Commands;
    using PythonSharp.Expressions;
    using PythonSharp.Language;
    using PythonSharp.Tests.Classes;

    [TestClass]
    public class SetAttributeCommandTests
    {
        [TestMethod]
        public void SetAttributeInDynamicObject()
        {
            BindingEnvironment environment = new BindingEnvironment();
            DefinedClass klass = new DefinedClass("Spam");
            DynamicObject dynobj = new DynamicObject(klass);
            environment.SetValue("foo", dynobj);

            SetAttributeCommand command = new SetAttributeCommand(new NameExpression("foo"), "one", new ConstantExpression(1));

            command.Execute(environment);

            Assert.IsTrue(dynobj.HasValue("one"));
            Assert.AreEqual(1, dynobj.GetValue("one"));
        }

        [TestMethod]
        public void SetAttributeInNativeObject()
        {
            BindingEnvironment environment = new BindingEnvironment();
            Person adam = new Person();
            environment.SetValue("adam", adam);

            SetAttributeCommand command = new SetAttributeCommand(new NameExpression("adam"), "FirstName", new ConstantExpression("Adam"));

            command.Execute(environment);

            Assert.AreEqual("Adam", adam.FirstName);
        }
    }
}


text:
/* This is script-generated code (for the most part).  */
/* See dataObjCreate.h for a description of this API call.*/

#include "dataObjCreate.h"
#include "dataObjCreateAndStat.h"
#include "rodsLog.h"
#include "rsGlobalExtern.hpp"
#include "rcGlobalExtern.h"
#include "reGlobalsExtern.hpp"

int
rsDataObjCreateAndStat( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                        openStat_t **openStat ) {
    int status;

    status = rsDataObjCreate( rsComm, dataObjInp );

    if ( status >= 0 ) {
        *openStat = ( openStat_t* )malloc( sizeof( openStat_t ) );
        ( *openStat )->dataSize = L1desc[status].dataObjInfo->dataSize;
        rstrcpy( ( *openStat )->dataMode, L1desc[status].dataObjInfo->dataMode,
                 SHORT_STR_LEN );
        rstrcpy( ( *openStat )->dataType, L1desc[status].dataObjInfo->dataType,
                 NAME_LEN );
        ( *openStat )->l3descInx = L1desc[status].l3descInx;
        ( *openStat )->replStatus = L1desc[status].replStatus;
        ( *openStat )->replNum = L1desc[status].dataObjInfo->replNum;
    }
    else {
        *openStat = NULL;
    }

    return status;
}


text:
<!DOCTYPE html>

    <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }} – {{ site.description }}</title>

    {% include meta.html %}

    <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/style.css" />
    <link rel="alternate" type="application/rss+xml" title="{{ site.name }} - {{ site.description }}" href="{{ site.baseurl }}/feed.xml" />

{{ site.name }}

{{ site.description }}

            Blog
            About

      {{ content }}

          {% include svg-icons.html %}

    {% include analytics.html %}


text:
<?php

namespace App\MainBundle\Controller;

use App\MainBundle\Entity\Trauma;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Trauma controller.
 *
 */
class TraumaController extends BaseController
{
    public function indexAction()
    {
        return $this->redirect($this->generateUrl('trauma_list'));
    }

    public function listAction()
    {
        $builder = $this->createFormBuilder(null, [
            'csrf_protection' => false,
            'method' => 'get'
        ]);

        $this->buildFilterForm($builder);
        $form = $builder->getForm();
        $request = $this->get('request');
        $form->submit($request);

        $query = $this->createFilterQuery($form);
        $pagination = $this->paginate($query, 10);

        return $this->render('MainBundle:Trauma:list.html.twig', [
            'pagination' => $pagination,
            'filterForm' => $form->createView()
        ]);
    }

    public function editAction($id = null)
    {
        $isNew = null === $id;

        if ($isNew) {
            $entity = new Trauma();
        } else {
            $entity = $this->findTrauma($id);
        }

        $builder = $this->createFormBuilder($entity)
            ->add('datetrauma', 'date', array(
                'widget' => 'single_text',
                'format' => 'dd.MM.yyyy',
                'attr' => array('class' => 'date-input')
            ))
            ->add('traumareport')
            ->add('hoursstart')
            ->add('employee', 'entity', array(
                'class' => 'MainBundle:Employee',
                'empty_value' => false,
//                'choices' => $options['OTparams']['aEmployee'],
            ))
            ->add('traumacause')
            ->add('traumakind')
        ;

        $editForm = $builder->getForm();
        $editForm->handleRequest($this->getRequest());

        if ($editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            if ($isNew) {
                $this->addFlashMessage('success', 'Случай травматизма создан');
            } else {
                $this->addFlashMessage('success', 'Случай травматизма сохранен');
            }

            return $this->redirect($this->generateUrl('trauma_edit', [
                'id' => $entity->getId()
            ]));
        }

        return $this->render('MainBundle:Trauma:edit.html.twig', [
            'isNew' => $isNew,
            'entity' => $entity,
            'form'   => $editForm->createView(),
            'isNew' => $isNew
        ]);
    }

    protected function buildFilterForm(FormBuilderInterface $builder)
    {
        $builder
            ->add('name', 'text', [
                'required' => false
            ])
            ->add('submit', 'submit', [
                'label' => 'Применить'
            ])
        ;
    }

    protected function createFilterQuery(Form $form)
    {
        $qb = $this->getTraumaRepository()->createQueryBuilder('t')
            ->select('t', 'e', 'enterp')
            ->leftJoin('t.employee', 'e')
            ->leftJoin('e.enterprise', 'enterp');

        if ($form->get('name')->getNormData()) {
            $qb->andWhere('t.name LIKE :name');
            $qb->setParameter('name', '%' . $form->get('name')->getNormData() . '%');
        }

        if ($form->has('sort_field') && $form->get('sort_field')->getNormData()) {
            $qb->orderBy('t.' . $form->get('sort_field')->getNormData(), $form->get('sort_order')->getNormData());
        } else {
            $qb->orderBy('t.id', 'ASC');
        }

        return $qb->getQuery();
    }

    /**
     * @param $id
     * @return null|Trauma
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    protected function findTrauma($id)
    {
        $entity = $this->getTraumaRepository()->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Случай травматизма не найден');
        }

        return $entity;
    }

    public function showAction()
    {
        return new Response();
    }

    public function removeAction($id)
    {
        $entity = $this->findTrauma($id);

        if(!$entity) {
            new NotFoundHttpException();
        }

        $em = $this->getEntityManager();
        $em->remove($entity);
        $em->flush();

        $this->addFlashMessage('success', 'Случай травматизма удален');

        return $this->redirect($this->generateUrl('trauma_list'));
    }
}


text:
<?php

namespace Sunlight;

use Sunlight\Post\Post;
use Sunlight\Database\Database as DB;
use Sunlight\Page\Page;
use Sunlight\Util\Arr;
use Sunlight\Util\Html;

abstract class Router
{
    /**
     * Sestavit adresu k libovolne ceste
     *
     * Cesta bude relativni k zakladni adrese systemu.
     *
     * @param string $path cesta v URL, muze obsahovat query string a fragment
     * @param bool   $absolute
     * @return string
     */
    static function generate(string $path, bool $absolute = false): string
    {
        $url = ($absolute ? Core::getBaseUrl()->build() : Core::getBaseUrl()->getPath()) . '/' . $path;

        Extend::call('link', [
            'path' => $path,
            'absolute' => $absolute,
            'output' => &$url,
        ]);

        return $url;
    }

    /**
     * Sestavit webovou cestu k existujicimu souboru
     *
     * Soubor musi byt umisten v korenovem adresari systemu nebo v jeho podadresarich.
     *
     * @param string $filePath
     * @param bool   $absolute
     * @return string
     */
    static function file(string $filePath, bool $absolute = false): string
    {
        static $realRootPath = null, $realRootPathLength = null;

        if ($realRootPath === null) {
            $realRootPath = realpath(SL_ROOT) . DIRECTORY_SEPARATOR;
            $realRootPathLength = strlen($realRootPath);
        }

        if (($queryParamPos = strpos($filePath, '?')) !== false) {
            $filePath = substr($filePath, 0, $queryParamPos);
            $params = substr($filePath, $queryParamPos);
        } else {
            $params = '';
        }

        $realFilePath = realpath($filePath);

        if ($realFilePath !== false && substr($realFilePath, 0, $realRootPathLength) === $realRootPath) {
            $path = str_replace('\\', '/', substr($realFilePath, $realRootPathLength));
        } else {
            return '#';
        }

        return self::generate($path, $absolute) . $params;
    }

    /**
     * Sestavit adresu clanku
     *
     * @param int|null    $id            ID clanku
     * @param string|null $slug          jiz nacteny identifikator clanku nebo null
     * @param string|null $category_slug jiz nacteny identifikator kategorie nebo null
     * @param bool        $absolute      sestavit absolutni adresu 1/0
     * @return string
     */
    static function article(?int $id, ?string $slug = null, ?string $category_slug = null, bool $absolute = false): string
    {
        if ($id !== null) {
            if ($slug === null || $category_slug === null) {
                $slug = DB::queryRow("SELECT art.slug AS art_ts, cat.slug AS cat_ts FROM " . DB::table('article') . " AS art JOIN " . DB::table('page') . " AS cat ON(cat.id=art.home1) WHERE art.id=" . $id);
                if ($slug === false) {
                    $slug = ['---', '---'];
                } else {
                    $slug = [$slug['art_ts'], $slug['cat_ts']];
                }
            } else {
                $slug = [$slug, $category_slug];
            }
        } else {
            $slug = [$slug, $category_slug];
        }

        return self::page(null, $slug[1], $slug[0], $absolute);
    }

    /**
     * Sestavit cestu ke strance
     *
     * @param string $slug     cely identifikator stranky (prazdny pro hlavni stranu)
     * @param bool   $absolute sestavit absolutni adresu 1/0
     * @return string
     */
    static function path(string $slug, bool $absolute = false): string
    {
        if (Settings::get('pretty_urls')) {
            $path = $slug;
        } elseif ($slug !== '') {
            $path = 'index.php?p=' . $slug;
        } else {
            $path = '';
        }

        return self::generate($path, $absolute);
    }

    /**
     * Sestavit adresu stranky existujici v databazi
     *
     * @param int|null    $id       ID stranky
     * @param string|null $slug     jiz nacteny identifikator nebo null
     * @param string|null $segment  segment nebo null
     * @param bool        $absolute sestavit absolutni adresu 1/0
     * @return string
     */
    static function page(?int $id, ?string $slug = null, ?string $segment = null, bool $absolute = false): string
    {
        if ($id !== null && $slug === null) {
            $slug = DB::queryRow("SELECT slug FROM " . DB::table('page') . " WHERE id=" . DB::val($id));
            $slug = ($slug !== false ? $slug['slug'] : '---');
        }

        if ($segment !== null) {
            $slug .= '/' . $segment;
        } elseif ($id == Settings::get('index_page_id')) {
            $slug = '';
        }

        return self::path($slug, $absolute);
    }

    /**
     * Sestavit adresu a titulek komentare
     *
     * @param array $post     data komentare (potreba sloupce z {@see Post::createFilter()}
     * @param bool  $absolute sestavit absolutni adresu 1/0
     * @return array adresa, titulek
     */
    static function post(array $post, bool $absolute = false): array
    {
        switch ($post['type']) {
            case Post::SECTION_COMMENT:
            case Post::BOOK_ENTRY:
                return [
                    self::page($post['home'], $post['page_slug'], null, $absolute),
                    $post['page_title'],
                ];
            case Post::ARTICLE_COMMENT:
                return [
                    self::article(null, $post['art_slug'], $post['cat_slug'], $absolute),
                    $post['art_title'],
                ];
            case Post::FORUM_TOPIC:
            case Post::PRIVATE_MSG:
                if ($post['xhome'] == -1) {
                    $topicId = $post[$post['type'] == Post::PRIVATE_MSG ? 'home' : 'id'];
                } else {
                    $topicId = $post['xhome'];
                }
                if ($post['type'] == Post::FORUM_TOPIC) {
                    $url = self::topic($topicId, $post['page_slug'], $absolute);
                } else {
                    $url = self::module('messages', "a=list&read={$topicId}", $absolute);
                }

                return [
                    $url,
                    ($post['xhome'] == -1)
                        ? $post['subject']
                        : $post['xhome_subject']
                ,
                ];
            case Post::PLUGIN:
                $url = '';
                $title = '';

                Extend::call("posts.{$post['flag']}.link", [
                    'post' => $post,
                    'url' => &$url,
                    'title' => &$title,
                    'absolute' => $absolute,
                ]);

                return [$url, $title];
            default:
                return ['', ''];
        }
    }

    /**
     * Sestavit adresu tematu
     *
     * @param int         $topic_id   ID tematu
     * @param string|null $forum_slug jiz nacteny identifikator domovskeho fora nebo null
     * @param bool        $absolute   sestavit absolutni adresu 1/0
     * @return string
     */
    static function topic(int $topic_id, ?string $forum_slug = null, bool $absolute = false): string
    {
        if ($forum_slug === null) {
            $forum_slug = DB::queryRow('SELECT r.slug FROM ' . DB::table('page') . ' r WHERE type=' . Page::FORUM . ' AND id=(SELECT p.home FROM ' . DB::table('post') . ' p WHERE p.id=' . DB::val($topic_id) . ')');
            if ($forum_slug !== false) {
                $forum_slug = $forum_slug['slug'];
            } else {
                $forum_slug = '---';
            }
        }

        return self::page(null, $forum_slug, $topic_id, $absolute);
    }

    /**
     * Sestavit adresu modulu
     *
     * @param string      $module   jmeno modulu
     * @param string|null $params   standartni querystring
     * @param bool        $absolute sestavit absolutni adresu 1/0
     * @return string
     */
    static function module(string $module, ?string $params = null, bool $absolute = false): string
    {
        if (Settings::get('pretty_urls')) {
            $path = 'm/' . $module;
        } else {
            $path = 'index.php?m=' . $module;
        }

        if (!empty($params)) {
            $path .= (Settings::get('pretty_urls') ? '?' : '&') . $params;
        }

        return self::generate($path, $absolute);
    }

    /**
     * Sestaveni kodu odkazu na uzivatele
     *
     * Mozne klice v $options
     * ----------------------
     * plain (0)        vratit pouze jmeno uzivatele 1/0
     * link (1)         odkazovat na profil uzivatele 1/0
     * color (1)        obarvit podle skupiny 1/0
     * icon (1)         zobrazit ikonu skupiny 1/0
     * publicname (1)   vykreslit publicname, ma-li jej uzivatel vyplneno 1/0
     * new_window (0)   odkazovat do noveho okna 1/0 (v prostredi administrace je vychozi 1)
     * max_len (-)      maximalni delka vykresleneho jmena
     * class (-)        vlastni CSS trida
     * title (-)        titulek
     *
     * @param array $data    samostatna data uzivatele viz {@see User::createQuery()}
     * @param array $options moznosti vykresleni, viz popis funkce
     * @return string HTML kod
     */
    static function user(array $data, array $options = []): string
    {
        // vychozi nastaveni
        $options += [
            'plain' => false,
            'link' => true,
            'color' => true,
            'icon' => true,
            'publicname' => true,
            'new_window' => Core::$env === Core::ENV_ADMIN,
            'max_len' => null,
            'class' => null,
            'title' => null,
        ];

        // extend
        $extendOutput = Extend::buffer('user.link', array('user' => $data, 'options' => &$options));
        if ($extendOutput !== '') {
            return $extendOutput;
        }

        $tag = ($options['link'] ? 'a' : 'span');
        $name = $data[$options['publicname'] && $data['publicname'] !== null ? 'publicname' : 'username'];
        $nameIsTooLong = ($options['max_len'] !== null && mb_strlen($name) > $options['max_len']);

        // pouze jmeno?
        if ($options['plain']) {
            if ($nameIsTooLong) {
                return Html::cut($name, $options['max_len']);
            }

            return $name;
        }

        // titulek
        $title = $options['title'];
        if ($nameIsTooLong) {
            if ($title === null) {
                $title = $name;
            } else {
                $title = "{$name}, {$title}";
            }
        }

        // oteviraci tag
        $out = "<{$tag}"
            . ($options['link'] ? ' href="' . _e(self::module('profile', 'id=' .  $data['username'])) . '"' : '')
            . ($options['link'] && $options['new_window'] ? ' target="_blank"' : '')
            . " class=\"user-link user-link-{$data['id']} user-link-group-{$data['group_id']}" . ($options['class'] !== null ? " {$options['class']}" : '') . "\""
            . ($options['color'] && $data['group_color'] !== '' ? " style=\"color:{$data['group_color']}\"" : '')
            . ($title !== null ? " title=\"{$title}\"" : '')
            . '>';

        // ikona skupiny
        if ($options['icon'] && $data['group_icon'] !== '') {
            $out .= "<img src=\"" . self::generate('images/groupicons/' . $data['group_icon']) . "\" title=\"{$data['group_title']}\" alt=\"{$data['group_title']}\" class=\"icon\">";
        }

        // jmeno uzivatele
        if ($nameIsTooLong) {
            $out .= Html::cut($name, $options['max_len']) . '...';
        } else {
            $out .= $name;
        }

        // uzaviraci tag
        $out .= "</{$tag}>";

        return $out;
    }

    /**
     * Sestaveni kodu odkazu na uzivatele na zaklade dat z funkce {@see User::createQuery()}
     *
     * @param array $userQuery vystup z {@see User::createQuery()}
     * @param array $row       radek z vysledku dotazu
     * @param array $options   nastaveni vykresleni, viz {@see Router::user()}
     * @return string
     */
    static function userFromQuery(array $userQuery, array $row, array $options = []): string
    {
        $userData = Arr::getSubset($row, $userQuery['columns'], strlen($userQuery['prefix']));

        if ($userData['id'] === null) {
            return '?';
        }

        return self::user($userData, $options);
    }
}


text:
set -o errexit
set -o nounset
set -o pipefail

. "$(dirname "${BASH_SOURCE[0]}")/common.sh"

cd "${KOPS_ROOT}"

# Accept an optional argument overriding the package to update
PKG="${1:-./...}"

# Don't override variables that are commonly used in dev, but shouldn't be in our tests
unset KOPS_BASE_URL DNSCONTROLLER_IMAGE KOPSCONTROLLER_IMAGE KUBE_APISERVER_HEALTHCHECK_IMAGE KOPS_FEATURE_FLAGS KOPS_ARCH
unset AWS_ACCESS_KEY_ID AWS_REGION AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN CNI_VERSION_URL DNS_IGNORE_NS_CHECK DO_ACCESS_TOKEN GOOGLE_APPLICATION_CREDENTIALS HCLOUD_TOKEN
unset KOPS_CLUSTER_NAME KOPS_RUN_OBSOLETE_VERSION KOPS_STATE_STORE KOPS_STATE_S3_ACL KUBE_API_VERSIONS NODEUP_URL OPENSTACK_CREDENTIAL_FILE PROTOKUBE_IMAGE SKIP_PACKAGE_UPDATE
unset SKIP_REGION_CHECK S3_ACCESS_KEY_ID S3_ENDPOINT S3_REGION S3_SECRET_ACCESS_KEY
unset SCW_ACCESS_KEY SCW_SECRET_KEY SCW_DEFAULT_PROJECT_ID SCW_DEFAULT_REGION SCW_DEFAULT_ZONE
unset AZURE_CLIENT_ID AZURE_CLIENT_SECRET AZURE_STORAGE_ACCOUNT AZURE_STORAGE_KEY AZURE_SUBSCRIPTION_ID AZURE_TENANT_ID

# Run the tests in "autofix mode"
HACK_UPDATE_EXPECTED_IN_PLACE=1 go test "${PKG}" -count=1


text:
using SharpDX;

namespace PersistentPlanet.Transform
{
    public class PositionChangedEvent
    {
        public Vector3 Position { get; set; }
    }
}


text:
package wh1spr.olympians;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Invite;
import net.dv8tion.jda.core.entities.User;

/**
 * This class takes care of the timed events from tempbans/kicks/mutes/deafens and perm bans and kicks.
 *
 * @author Robbe
 */
public class UserControl {

	private static Timer timer;
	private static final List<TimerTask> scheduledTasks = new ArrayList<TimerTask>();

	public void shutdown() {
		Iterator<TimerTask> it = scheduledTasks.iterator();
		while (it.hasNext()) {
			TimerTask next = (TimerTask) it.next();
			if (next instanceof unBanTask) {
				unBanTask task = (unBanTask) next;
				if (!task.hasRun) {
					task.run();
				}
			} else if (next instanceof Object) {
				//this is for other tasks.
			}

		}
	}

	public UserControl() {
		guild = BotControl.getZeus().getJDA().getGuildById("319896741233033216");
		timer = new Timer();
	}

	private static Guild guild;

	public void permban(User user, int days, String reason) {
		if (BotControl.usage.isImmune(user)) return;
		if (BotControl.usage.isAdmin(user)) return;
		guild.getController().ban(user, days, "BAN issued by Leader").queue();
		Tools.addLineToFile("data/bans.txt", String.format("%s - %s with ID [%s] - %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd kk:mm:ss")),user.getName(), user.getId(), reason));
	}

	public void kick(User user, String reason) {
		if (BotControl.usage.isImmune(user)) return;
		if (BotControl.usage.isAdmin(user)) return;
		guild.getController().kick(user.getId(), "KICK issued by Leader").queue();
		Tools.addLineToFile("data/kicks.txt", String.format("%s - %s with ID [%s] - %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd kk:mm:ss")),user.getName(), user.getId(), reason));
	}

	/**
	 * @param time The duration in milliseconds until ban has ended.
	 */
	public void tempban(User user, String reason, long time, int daysToDelete) {
		if (BotControl.usage.isImmune(user)) return;
		if (BotControl.usage.isAdmin(user)) return;
		guild.getController().ban(user, daysToDelete, "TEMPBAN issued by Leader").queue();
		Tools.addLineToFile("data/tempbans.txt", String.format("%s - %s with ID [%s] - %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd kk:mm:ss")),user.getName(), user.getId(), reason));
		timer.schedule(new unBanTask(user), time);
	}
	/**
	 * @param time The date at which to lift the ban.
	 */
	public void tempban(User user, String reason, Date time, int daysToDelete) {
		if (BotControl.usage.isImmune(user)) return;
		if (BotControl.usage.isAdmin(user)) return;
		guild.getController().ban(user, daysToDelete, "TEMPBAN issued by Leader").queue();
		Tools.addLineToFile("data/tempbans.txt", String.format("%s - %s with ID [%s] - %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd kk:mm:ss")),user.getName(), user.getId(), reason));
		timer.schedule(new unBanTask(user), time);
	}
	private static class unBanTask extends TimerTask {

		private final User user;
		private boolean hasRun = false;

		public boolean hasRun() {return hasRun;}

		public User getUser() {
			return this.user;
		}

		public unBanTask(User user) {
			this.user = user;
			scheduledTasks.add(this);
		}

		@Override
		public void run() {
			hasRun = true;
			guild = BotControl.getZeus().getJDA().getGuildById("319896741233033216");
			Invite invite = guild.getPublicChannel().createInvite().setMaxUses(1).complete();
			guild.getController().unban(this.user).queue();
			Tools.addLineToFile("data/tempbans.txt", String.format("%s - %s with ID [%s] - %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd kk:mm:ss")),user.getName(), user.getId(), "Unban event"));
			user.openPrivateChannel().complete().sendMessage("Your tempban has been lifted. Here is your invite: discord.gg/" + invite.getCode()).queue();
		}

	}

}


text:
{exp:member:login_form return="{path='profile'}/index"}

Username

<input type="text" name="username" value="" maxlength="32" size="25">

Password

<input type="password" name="password" value="" maxlength="32" size="25">

{if auto_login}

<input type="checkbox" name="auto_login" value="1"> Auto-login on future visits

{/if}

<input type="checkbox" name="anon" value="1" checked="checked"> Show my name in the online users list

<input type="submit" name="submit" value="Submit">

{/exp:member:login_form}


text:
package org.foxlabs.validation.constraint;

import java.util.Comparator;

/**
 * This class provides java.util.Comparator implementation for
 * objects that implement java.lang.Comparable interface.
 *
 * @author Fox Mulder
 * @see RangeConstraint
 * @see PropertyComparisonConstraint
 */
public final class DefaultComparator implements Comparator<Comparable<Object>> {

    /**
     * DefaultComparator single instance.
     */
    public static final DefaultComparator INSTANCE = new DefaultComparator();

    /**
     * Constructs default DefaultComparator.
     */
    private DefaultComparator() {}

    /**
     * Compares two java.lang.Comparable objects.
     *
     * @param o1 The first object to be compared.
     * @param o2 The second object to be compared.
     * @return A negative integer, zero, or a positive integer as the first
     *         object is less than, equal to, or greater than the second.
     */
    @Override
    public int compare(Comparable<Object> o1, Comparable<Object> o2) {
        return o1.compareTo(o2);
    }

    /**
     * Returns comparator for the specified object type and comparator type.
     *
     * @param <V> The value type.
     * @param type Type of the objects to be compared.
     * @param comparatorType Type of the comparator.
     * @return Comparator instance.
     * @throws UnsupportedOperationException if the specified comparator is not
     *         applicable to the specified object type.
     * @throws IllegalArgumentException if comparator instantiation fails.
     */
    @SuppressWarnings("unchecked")
    public static <V> Comparator<V> getInstance(Class<V> type, Class<? extends Comparator<?>> comparatorType) {
        if (comparatorType == DefaultComparator.class) {
            if (Comparable.class.isAssignableFrom(type) || type.isPrimitive())
                return (Comparator<V>) INSTANCE;
            throw new UnsupportedOperationException();
        }
        try {
            return (Comparator<V>) comparatorType.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="default_options">
        <item>Yes</item>
        <item>No</item>
        <item>Abstain</item>
    </string-array>
</resources>


text:
<?php

/**
 * Handles `<atom:source>`
 *
 * Used by {@see SimplePie_Item::get_source()}
 *
 * This class can be overloaded with {@see SimplePie::set_source_class()}
 *
 * @package SimplePie
 * @subpackage API
 */
class SimplePie_Source
{
	var $item;
	var $data = array();
	protected $registry;

	public function __construct($item, $data)
	{
		$this->item = $item;
		$this->data = $data;
	}

	public function set_registry(SimplePie_Registry $registry)
	{
		$this->registry = $registry;
	}

	public function __toString()
	{
		return md5(serialize($this->data));
	}

	public function get_source_tags($namespace, $tag)
	{
		if (isset($this->data['child'][$namespace][$tag]))
		{
			return $this->data['child'][$namespace][$tag];
		}
		else
		{
			return null;
		}
	}

	public function get_base($element = array())
	{
		return $this->item->get_base($element);
	}

	public function sanitize($data, $type, $base = '')
	{
		return $this->item->sanitize($data, $type, $base);
	}

	public function get_item()
	{
		return $this->item;
	}

	public function get_title()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		else
		{
			return null;
		}
	}

	public function get_category($key = 0)
	{
		$categories = $this->get_categories();
		if (isset($categories[$key]))
		{
			return $categories[$key];
		}
		else
		{
			return null;
		}
	}

	public function get_categories()
	{
		$categories = array();

		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category)
		{
			$term = null;
			$scheme = null;
			$label = null;
			if (isset($category['attribs']['']['term']))
			{
				$term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($category['attribs']['']['scheme']))
			{
				$scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($category['attribs']['']['label']))
			{
				$label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			$categories[] = $this->registry->create('Category', array($term, $scheme, $label));
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'category') as $category)
		{
			// This is really the label, but keep this as the term also for BC.
			// Label will also work on retrieving because that falls back to term.
			$term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			if (isset($category['attribs']['']['domain']))
			{
				$scheme = $this->sanitize($category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			else
			{
				$scheme = null;
			}
			$categories[] = $this->registry->create('Category', array($term, $scheme, null));
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category)
		{
			$categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category)
		{
			$categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
		}

		if (!empty($categories))
		{
			return array_unique($categories);
		}
		else
		{
			return null;
		}
	}

	public function get_author($key = 0)
	{
		$authors = $this->get_authors();
		if (isset($authors[$key]))
		{
			return $authors[$key];
		}
		else
		{
			return null;
		}
	}

	public function get_authors()
	{
		$authors = array();
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author)
		{
			$name = null;
			$uri = null;
			$email = null;
			if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']))
			{
				$name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']))
			{
				$uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]));
			}
			if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data']))
			{
				$email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if ($name !== null || $email !== null || $uri !== null)
			{
				$authors[] = $this->registry->create('Author', array($name, $uri, $email));
			}
		}
		if ($author = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author'))
		{
			$name = null;
			$url = null;
			$email = null;
			if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data']))
			{
				$name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data']))
			{
				$url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]));
			}
			if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data']))
			{
				$email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if ($name !== null || $email !== null || $url !== null)
			{
				$authors[] = $this->registry->create('Author', array($name, $url, $email));
			}
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author)
		{
			$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author)
		{
			$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author)
		{
			$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
		}

		if (!empty($authors))
		{
			return array_unique($authors);
		}
		else
		{
			return null;
		}
	}

	public function get_contributor($key = 0)
	{
		$contributors = $this->get_contributors();
		if (isset($contributors[$key]))
		{
			return $contributors[$key];
		}
		else
		{
			return null;
		}
	}

	public function get_contributors()
	{
		$contributors = array();
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor)
		{
			$name = null;
			$uri = null;
			$email = null;
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']))
			{
				$name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']))
			{
				$uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]));
			}
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data']))
			{
				$email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if ($name !== null || $email !== null || $uri !== null)
			{
				$contributors[] = $this->registry->create('Author', array($name, $uri, $email));
			}
		}
		foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor)
		{
			$name = null;
			$url = null;
			$email = null;
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data']))
			{
				$name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data']))
			{
				$url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]));
			}
			if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data']))
			{
				$email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
			}
			if ($name !== null || $email !== null || $url !== null)
			{
				$contributors[] = $this->registry->create('Author', array($name, $url, $email));
			}
		}

		if (!empty($contributors))
		{
			return array_unique($contributors);
		}
		else
		{
			return null;
		}
	}

	public function get_link($key = 0, $rel = 'alternate')
	{
		$links = $this->get_links($rel);
		if (isset($links[$key]))
		{
			return $links[$key];
		}
		else
		{
			return null;
		}
	}

	/**
	 * Added for parity between the parent-level and the item/entry-level.
	 */
	public function get_permalink()
	{
		return $this->get_link(0);
	}

	public function get_links($rel = 'alternate')
	{
		if (!isset($this->data['links']))
		{
			$this->data['links'] = array();
			if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link'))
			{
				foreach ($links as $link)
				{
					if (isset($link['attribs']['']['href']))
					{
						$link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
						$this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link));
					}
				}
			}
			if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link'))
			{
				foreach ($links as $link)
				{
					if (isset($link['attribs']['']['href']))
					{
						$link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
						$this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link));

					}
				}
			}
			if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link'))
			{
				$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
			}
			if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link'))
			{
				$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
			}
			if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link'))
			{
				$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
			}

			$keys = array_keys($this->data['links']);
			foreach ($keys as $key)
			{
				if ($this->registry->call('Misc', 'is_isegment_nz_nc', array($key)))
				{
					if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]))
					{
						$this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]);
						$this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key];
					}
					else
					{
						$this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key];
					}
				}
				elseif (substr($key, 0, 41) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY)
				{
					$this->data['links'][substr($key, 41)] =& $this->data['links'][$key];
				}
				$this->data['links'][$key] = array_unique($this->data['links'][$key]);
			}
		}

		if (isset($this->data['links'][$rel]))
		{
			return $this->data['links'][$rel];
		}
		else
		{
			return null;
		}
	}

	public function get_description()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0]));
		}
		else
		{
			return null;
		}
	}

	public function get_copyright()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright'))
		{
			return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'copyright'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		else
		{
			return null;
		}
	}

	public function get_language()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'language'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		elseif (isset($this->data['xml_lang']))
		{
			return $this->sanitize($this->data['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT);
		}
		else
		{
			return null;
		}
	}

	public function get_latitude()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat'))
		{
			return (float) $return[0]['data'];
		}
		elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match))
		{
			return (float) $match[1];
		}
		else
		{
			return null;
		}
	}

	public function get_longitude()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long'))
		{
			return (float) $return[0]['data'];
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon'))
		{
			return (float) $return[0]['data'];
		}
		elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match))
		{
			return (float) $match[2];
		}
		else
		{
			return null;
		}
	}

	public function get_image_url()
	{
		if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image'))
		{
			return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI);
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
		}
		elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon'))
		{
			return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
		}
		else
		{
			return null;
		}
	}
}


text:
package com.leonardofischer.jmautic;

import com.leonardofischer.jmautic.MauticException;
import com.leonardofischer.jmautic.oauth.OAuthService;
import com.leonardofischer.jmautic.oauth.Request;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;

public class MockedOauthService implements OAuthService {

    String json;

    public void loadJsonFromResource(String resource) throws IOException {
        json = IOUtils.toString(this.getClass().getResourceAsStream(resource),"UTF-8");
    }

    public InputStream executeRequest(Request request) throws MauticException {
        try {
            return new ByteArrayInputStream(json.getBytes("UTF-8"));
        }
        catch(Exception e) {
            throw new MauticException(e);
        }
    }
}


text:
#ifndef DO_PRINTSTAT
# define DO_PRINTSTAT do_printstat
#endif

#ifndef STRUCT_STAT
# define STRUCT_STAT struct stat
#endif

#ifndef STAT_MAJOR
# define STAT_MAJOR(x) major(x)
#endif

#ifndef STAT_MINOR
# define STAT_MINOR(x) minor(x)
#endif

static void
DO_PRINTSTAT(struct tcb *tcp, const STRUCT_STAT *statbuf)
{
	if (!abbrev(tcp)) {
		tprintf("{st_dev=makedev(%u, %u), st_ino=%llu, st_mode=%s, ",
			(unsigned int) STAT_MAJOR(statbuf->st_dev),
			(unsigned int) STAT_MINOR(statbuf->st_dev),
			(unsigned long long) statbuf->st_ino,
			sprintmode(statbuf->st_mode));
		tprintf("st_nlink=%u, st_uid=%u, st_gid=%u, ",
			(unsigned int) statbuf->st_nlink,
			(unsigned int) statbuf->st_uid,
			(unsigned int) statbuf->st_gid);
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
		tprintf("st_blksize=%u, ", (unsigned int) statbuf->st_blksize);
#endif
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
		tprintf("st_blocks=%llu, ",
			(unsigned long long) statbuf->st_blocks);
#endif
	} else {
		tprintf("{st_mode=%s, ", sprintmode(statbuf->st_mode));
	}

	switch (statbuf->st_mode & S_IFMT) {
	case S_IFCHR: case S_IFBLK:
#ifdef HAVE_STRUCT_STAT_ST_RDEV
		tprintf("st_rdev=makedev(%u, %u), ",
			(unsigned int) STAT_MAJOR(statbuf->st_rdev),
			(unsigned int) STAT_MINOR(statbuf->st_rdev));
#else /* !HAVE_STRUCT_STAT_ST_RDEV */
		tprintf("st_size=makedev(%u, %u), ",
			(unsigned int) STAT_MAJOR(statbuf->st_size),
			(unsigned int) STAT_MINOR(statbuf->st_size));
#endif /* !HAVE_STRUCT_STAT_ST_RDEV */
		break;
	default:
		tprintf("st_size=%llu, ",
			(unsigned long long) statbuf->st_size);
		break;
	}

	if (!abbrev(tcp)) {
		const bool cast = sizeof(statbuf->st_atime) == sizeof(int);

		tprintf("st_atime=%s, ",
			sprinttime(cast ? (time_t) (int) statbuf->st_atime:
					  (time_t) statbuf->st_atime));
		tprintf("st_mtime=%s, ",
			sprinttime(cast ? (time_t) (int) statbuf->st_mtime:
					  (time_t) statbuf->st_mtime));
		tprintf("st_ctime=%s",
			sprinttime(cast ? (time_t) (int) statbuf->st_ctime:
					  (time_t) statbuf->st_ctime));
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
		tprintf(", st_flags=%u", (unsigned int) statbuf->st_flags);
#endif
#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
		tprintf(", st_fstype=%.*s",
			(int) sizeof statbuf->st_fstype, statbuf->st_fstype);
#endif
#ifdef HAVE_STRUCT_STAT_ST_GEN
		tprintf(", st_gen=%u", (unsigned int) statbuf->st_gen);
#endif
		tprints("}");
	} else {
		tprints("...}");
	}
}

#undef STAT_MINOR
#undef STAT_MAJOR
#undef STRUCT_STAT
#undef DO_PRINTSTAT


text:
package de.gigagagagigo.sagma.client.ui.test;

import java.io.IOException;

import de.gigagagagigo.sagma.net.LocalNetworkFactory;
import de.gigagagagigo.sagma.net.NetworkFactories;

public class Main {

	private static final boolean SERVER_GUI = true;
	private static final boolean JAVA_FX = true;
	private static final int CLIENTS = 2;

	public static void main(String[] args) {
		NetworkFactories.set(new LocalNetworkFactory());
		startServer();
		startClients();
	}

	private static void startServer() {
		if (SERVER_GUI) {
			de.gigagagagigo.sagma.server.ui.swing.Main.main(new String[0]);
		} else {
			new Thread(() -> {
				try {
					de.gigagagagigo.server.cli.Main.main(new String[0]);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}).start();
		}
	}

	private static void startClients() {
		int clients = 0;
		if (JAVA_FX) {
			new Thread(() -> {
				de.gigagagagigo.sagma.client.ui.fxml.Main.main(new String[0]);
			}).start();
			clients++;
		}
		for (; clients < CLIENTS; clients++) {
			de.gigagagagigo.sagma.client.ui.swing.Main.main(new String[0]);
		}
	}

}


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace ImageMagick
{
    /// <summary>
    /// Class that contains information about an image format.
    /// </summary>
    public sealed partial class MagickFormatInfo : IMagickFormatInfo
    {
        private static readonly Dictionary<MagickFormat, IMagickFormatInfo> _all = LoadFormats();

        private MagickFormatInfo()
        {
        }

        /// <summary>
        /// Gets a value indicating whether the format can be read multithreaded.
        /// </summary>
        public bool CanReadMultithreaded { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the format can be written multithreaded.
        /// </summary>
        public bool CanWriteMultithreaded { get; private set; }

        /// <summary>
        /// Gets the description of the format.
        /// </summary>
        public string? Description { get; private set; }

        /// <summary>
        /// Gets the format.
        /// </summary>
        public MagickFormat Format { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the format supports multiple frames.
        /// </summary>
        public bool IsMultiFrame { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the format is readable.
        /// </summary>
        public bool IsReadable { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the format is writable.
        /// </summary>
        public bool IsWritable { get; private set; }

        /// <summary>
        /// Gets the mime type.
        /// </summary>
        public string? MimeType { get; private set; }

        /// <summary>
        /// Gets the module.
        /// </summary>
        public MagickFormat ModuleFormat { get; private set; }

        internal static IReadOnlyCollection<IMagickFormatInfo> All
            => _all.Values;

        /// <summary>
        /// Returns the format information. The extension of the supplied file is used to determine
        /// the format.
        /// </summary>
        /// <param name="file">The file to check.</param>
        /// <returns>The format information.</returns>
        public static IMagickFormatInfo? Create(FileInfo file)
        {
            Throw.IfNull(nameof(file), file);

            var format = EnumHelper.ParseMagickFormatFromExtension(file);

            if (format == MagickFormat.Unknown)
                return null;

            return Create(format);
        }

        /// <summary>
        /// Returns the format information of the specified format.
        /// </summary>
        /// <param name="format">The image format.</param>
        /// <returns>The format information.</returns>
        public static IMagickFormatInfo? Create(MagickFormat format)
        {
            if (!_all.ContainsKey(format))
                return null;

            return _all[format];
        }

        /// <summary>
        /// Returns the format information. The header of the image in the array of bytes is used to
        /// determine the format.
        /// </summary>
        /// <param name="data">The array of bytes to read the image header from.</param>
        /// <returns>The format information.</returns>
        public static IMagickFormatInfo? Create(byte[] data)
        {
            Throw.IfNullOrEmpty(nameof(data), data);

            var instance = new NativeMagickFormatInfo();
            instance.GetInfoWithBlob(data, data.Length);

            return Create(instance);
        }

        /// <summary>
        /// Returns the format information. The extension of the supplied file name is used to
        /// determine the format.
        /// </summary>
        /// <param name="fileName">The name of the file to check.</param>
        /// <returns>The format information.</returns>
        public static IMagickFormatInfo? Create(string fileName)
        {
            var filePath = FileHelper.CheckForBaseDirectory(fileName);
            Throw.IfNullOrEmpty(nameof(fileName), filePath);

            return Create(new FileInfo(filePath));
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current <see cref="MagickFormatInfo"/>.
        /// </summary>
        /// <param name="obj">The object to compare this <see cref="MagickFormatInfo"/> with.</param>
        /// <returns>True when the specified object is equal to the current <see cref="MagickFormatInfo"/>.</returns>
        public override bool Equals(object? obj)
            => Equals(obj as MagickFormatInfo);

        /// <summary>
        /// Determines whether the specified <see cref="IMagickFormatInfo"/> is equal to the current <see cref="MagickFormatInfo"/>.
        /// </summary>
        /// <param name="other">The <see cref="IMagickFormatInfo"/> to compare this <see cref="MagickFormatInfo"/> with.</param>
        /// <returns>True when the specified <see cref="IMagickFormatInfo"/> is equal to the current <see cref="MagickFormatInfo"/>.</returns>
        public bool Equals(IMagickFormatInfo? other)
        {
            if (other is null)
                return false;

            if (ReferenceEquals(this, other))
                return true;

            return Format == other.Format;
        }

        /// <summary>
        /// Serves as a hash of this type.
        /// </summary>
        /// <returns>A hash code for the current instance.</returns>
        public override int GetHashCode()
            => ModuleFormat.GetHashCode();

        /// <summary>
        /// Returns a string that represents the current format.
        /// </summary>
        /// <returns>A string that represents the current format.</returns>
        public override string ToString()
            => string.Format(CultureInfo.InvariantCulture, "{0}: {1} ({2}R{3}W{4}M)", Format, Description, IsReadable ? "+" : "-", IsWritable ? "+" : "-", IsMultiFrame ? "+" : "-");

        /// <summary>
        /// Unregisters this format.
        /// </summary>
        /// <returns>True when the format was found and unregistered.</returns>
        public bool Unregister()
            => NativeMagickFormatInfo.Unregister(Enum.GetName(Format.GetType(), Format));

        private static MagickFormatInfo? Create(NativeMagickFormatInfo instance)
        {
            if (!instance.HasInstance)
                return null;

            return new MagickFormatInfo
            {
                Format = GetFormat(instance.Format),
                Description = instance.Description,
                CanReadMultithreaded = instance.CanReadMultithreaded,
                CanWriteMultithreaded = instance.CanWriteMultithreaded,
                IsMultiFrame = instance.IsMultiFrame,
                IsReadable = instance.IsReadable,
                IsWritable = instance.IsWritable,
                MimeType = instance.MimeType,
                ModuleFormat = GetFormat(instance.Module),
            };
        }

        private static MagickFormatInfo? Create(NativeMagickFormatInfo instance, string name)
        {
            instance.GetInfoByName(name);
            return Create(instance);
        }

        private static MagickFormat GetFormat(string? format)
        {
            if (format is null)
                return MagickFormat.Unknown;

            format = format.Replace("-", string.Empty);
            if (format == "3FR")
                format = "ThreeFr";
            else if (format == "3G2")
                format = "ThreeG2";
            else if (format == "3GP")
                format = "ThreeGp";

            return EnumHelper.Parse(format, MagickFormat.Unknown);
        }

        private static Dictionary<MagickFormat, IMagickFormatInfo> LoadFormats()
        {
            var formats = new Dictionary<MagickFormat, IMagickFormatInfo>();

            var list = IntPtr.Zero;
            var length = (UIntPtr)0;
            var instance = new NativeMagickFormatInfo();

            try
            {
                list = instance.CreateList(out length);

                var ptr = list;
                for (var i = 0; i < (int)length; i++)
                {
                    instance.GetInfo(list, i);

                    var formatInfo = Create(instance);
                    if (formatInfo is not null)
                        formats[formatInfo.Format] = formatInfo;

                    ptr = new IntPtr(ptr.ToInt64() + i);
                }

                AddStealthCoders(instance, formats);
            }
            finally
            {
                if (list != IntPtr.Zero)
                    NativeMagickFormatInfo.DisposeList(list, (int)length);
            }

            return formats;
        }

        private static void AddStealthCoders(NativeMagickFormatInfo instance, Dictionary<MagickFormat, IMagickFormatInfo> formats)
        {
            var formatInfo = Create(instance, "DIB");
            if (formatInfo is not null)
                formats[formatInfo.Format] = formatInfo;

            formatInfo = Create(instance, "TIF");
            if (formatInfo is not null)
                formats[formatInfo.Format] = formatInfo;
        }
    }
}


text:
using System;
using Newtonsoft.Json;

#endregion

namespace NineGag.Serialization
{
    /// <summary>
    /// Represents a JSON converter, which parses UNIX timestamps in seconds to <see cref="DateTime"/> objects.
    /// </summary>
    internal class TimestampToDateTimeConverter : JsonConverter
    {
        #region Private Static Fields

        /// <summary>
        /// Contains the UNIX epoch as a <see cref="DateTime"/> object.
        /// </summary>
        private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        #endregion

        #region JsonConverter Implementation

        /// <summary>
        /// Determines whether this converter can convert the specified type.
        /// </summary>
        /// <param name="objectType">The type for which is to be checked whether it can be converted by this converter.</param>
        /// <returns>Returns <c>true</c> if the object type is <see cref="DateTime"/> and <c>false</c> otherwise.</returns>
        public override bool CanConvert(Type objectType) => objectType == typeof(DateTime);

        /// <summary>
        /// Reads the JSON value. Converts the UNIX timestamp in seconds to a <see cref="DateTime"/> objects.
        /// </summary>
        /// <param name="reader">The reader that is used to read the value.</param>
        /// <param name="objectType">The type of the property into which the value is to be converted.</param>
        /// <param name="existingValue">The already existing value of the property into which the value is to be deserialized.</param>
        /// <param name="serializer">The serializer that is used.</param>
        /// <returns>
        /// Returns the local date and time represented by the UNIX timestamp. If the timestamp is <c>null</c>, then the default value for
        /// <see cref="DateTime"/> is returned.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // If the timestamp is null, then an "empty" date time is returned
            if (reader.Value == null)
                return default(DateTime);

            // Reads the timestamp
            long timestamp = Convert.ToInt64(reader.Value);

            // Converts the UNIX timestamp to a local date time and returned it
            return TimestampToDateTimeConverter.epoch
                .AddSeconds(timestamp)
                .ToLocalTime();
        }

        /// <summary>
        /// Is not implemented.
        /// </summary>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

        /// <summary>
        /// Gets a value that determines whether this converter can write values. Returns <c>false</c>, because this is a read-only
        /// converter.
        /// </summary>
        public override bool CanWrite { get => false; }

        #endregion
    }
}


text:
id: 587d7b8b367417b2b2512b50
title: Escrever funções declarativas concisas com ES6
challengeType: 1
forumTopicId: 301224
dashedName: write-concise-declarative-functions-with-es6
---

# --description--

Ao definir funções dentro de objetos em ES5, nós temos de usar a palavra-chave `function` como se segue:

```js
const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};
```

Com ES6, você pode remover a palavra-chave `function` e dois pontos ao definir funções em objetos. Aqui está um exemplo dessa sintaxe:

```js
const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};
```

# --instructions--

Refatore a função `setGear` dentro do objeto `bicycle` para usar a sintaxe curta descrita acima.

# --hints--

Expressão tradicional de função não deve ser usado.

```js
(getUserInput) => assert(!code.match(/function/));
```

`setGear` deve ser uma função declarativa.

```js
assert(
  typeof bicycle.setGear === 'function' && code.match(/setGear\s*\(.+\)\s*\{/)
);
```

`bicycle.setGear(48)` deve alterar o valor de `gear` para 48.

```js
assert(new bicycle.setGear(48).gear === 48);
```

# --seed--

## --seed-contents--

```js
// Only change code below this line
const bicycle = {
  gear: 2,
  setGear: function(newGear) {
    this.gear = newGear;
  }
};
// Only change code above this line
bicycle.setGear(3);
console.log(bicycle.gear);
```

# --solutions--

```js
const bicycle = {
  gear: 2,
  setGear(newGear) {
    this.gear = newGear;
  }
};
bicycle.setGear(3);
```


text:
import $ from 'jquery';
import Cookies from 'cookies-js';
import { Instance as Editors } from '../forms/fields/editor';

let Data = JSON.parse(Cookies.get('grav-tabs-state') || '{}');

$('body').on('touchstart click', '[data-tabid]', (event) => {
    event && event.stopPropagation();
    let target = $(event.currentTarget);

    Data[target.data('tabkey')] = target.data('scope');
    Cookies.set('grav-tabs-state', JSON.stringify(Data), { expires: Infinity });

    const panel = $(`[id="${target.data('tabid')}"]`);

    target.siblings('[data-tabid]').removeClass('active');
    target.addClass('active');

    panel.siblings('[id]').removeClass('active');
    panel.addClass('active');

    Editors.editors.each((index, editor) => {
        let codemirror = $(editor).data('codemirror');
        if (!codemirror) { return; }
        if (codemirror.display.lastWrapWidth === 0) {
            codemirror.refresh();
        }
    });
});


text:
package kubectl

import (
	"fmt"
	"io"
	"sort"
	"strconv"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apis/extensions"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_2"
	"k8s.io/kubernetes/pkg/runtime"
	deploymentutil "k8s.io/kubernetes/pkg/util/deployment"
	"k8s.io/kubernetes/pkg/util/errors"
)

const (
	ChangeCauseAnnotation = "kubernetes.io/change-cause"
)

// HistoryViewer provides an interface for resources that can be rolled back.
type HistoryViewer interface {
	History(namespace, name string) (HistoryInfo, error)
}

func HistoryViewerFor(kind unversioned.GroupKind, c clientset.Interface) (HistoryViewer, error) {
	switch kind {
	case extensions.Kind("Deployment"):
		return &DeploymentHistoryViewer{c}, nil
	}
	return nil, fmt.Errorf("no history viewer has been implemented for %q", kind)
}

// HistoryInfo stores the mapping from revision to podTemplate;
// note that change-cause annotation should be copied to podTemplate
type HistoryInfo struct {
	RevisionToTemplate map[int64]*api.PodTemplateSpec
}

type DeploymentHistoryViewer struct {
	c clientset.Interface
}

// History returns a revision-to-RC map as the revision history of a deployment
func (h *DeploymentHistoryViewer) History(namespace, name string) (HistoryInfo, error) {
	historyInfo := HistoryInfo{
		RevisionToTemplate: make(map[int64]*api.PodTemplateSpec),
	}
	deployment, err := h.c.Extensions().Deployments(namespace).Get(name)
	if err != nil {
		return historyInfo, fmt.Errorf("failed to retrieve deployment %s: %v", name, err)
	}
	_, allOldRCs, err := deploymentutil.GetOldRCs(*deployment, h.c)
	if err != nil {
		return historyInfo, fmt.Errorf("failed to retrieve old RCs from deployment %s: %v", name, err)
	}
	newRC, err := deploymentutil.GetNewRC(*deployment, h.c)
	if err != nil {
		return historyInfo, fmt.Errorf("failed to retrieve new RC from deployment %s: %v", name, err)
	}
	allRCs := append(allOldRCs, newRC)
	for _, rc := range allRCs {
		v, err := deploymentutil.Revision(rc)
		if err != nil {
			continue
		}
		historyInfo.RevisionToTemplate[v] = rc.Spec.Template
		changeCause := getChangeCause(rc)
		if historyInfo.RevisionToTemplate[v].Annotations == nil {
			historyInfo.RevisionToTemplate[v].Annotations = make(map[string]string)
		}
		historyInfo.RevisionToTemplate[v].Annotations[ChangeCauseAnnotation] = changeCause
	}
	return historyInfo, nil
}

// PrintRolloutHistory prints a formatted table of the input revision history of the deployment
func PrintRolloutHistory(historyInfo HistoryInfo, resource, name string) (string, error) {
	if len(historyInfo.RevisionToTemplate) == 0 {
		return fmt.Sprintf("No rollout history found in %s %q", resource, name), nil
	}
	// Sort the revisionToChangeCause map by revision
	var revisions []string
	for k := range historyInfo.RevisionToTemplate {
		revisions = append(revisions, strconv.FormatInt(k, 10))
	}
	sort.Strings(revisions)

	return tabbedString(func(out io.Writer) error {
		fmt.Fprintf(out, "%s %q:\n", resource, name)
		fmt.Fprintf(out, "REVISION\tCHANGE-CAUSE\n")
		errs := []error{}
		for _, r := range revisions {
			// Find the change-cause of revision r
			r64, err := strconv.ParseInt(r, 10, 64)
			if err != nil {
				errs = append(errs, err)
				continue
			}
			changeCause := historyInfo.RevisionToTemplate[r64].Annotations[ChangeCauseAnnotation]
			if len(changeCause) == 0 {
				changeCause = "<none>"
			}
			fmt.Fprintf(out, "%s\t%s\n", r, changeCause)
		}
		return errors.NewAggregate(errs)
	})
}

// getChangeCause returns the change-cause annotation of the input object
func getChangeCause(obj runtime.Object) string {
	meta, err := api.ObjectMetaFor(obj)
	if err != nil {
		return ""
	}
	return meta.Annotations[ChangeCauseAnnotation]
}


text:
package org.apache.cassandra.utils.memory;

import java.nio.ByteBuffer;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.utils.concurrent.OpOrder;

public abstract class MemtableBufferAllocator extends MemtableAllocator
{

    protected MemtableBufferAllocator(SubAllocator onHeap, SubAllocator offHeap)
    {
        super(onHeap, offHeap);
    }

    public MemtableRowData.ReusableRow newReusableRow()
    {
        return MemtableRowData.BufferRowData.createReusableRow();
    }

    public RowAllocator newRowAllocator(CFMetaData cfm, OpOrder.Group writeOp)
    {
        return new RowBufferAllocator(allocator(writeOp), cfm.isCounter());
    }

    public DecoratedKey clone(DecoratedKey key, OpOrder.Group writeOp)
    {
        return new BufferDecoratedKey(key.getToken(), allocator(writeOp).clone(key.getKey()));
    }

    public abstract ByteBuffer allocate(int size, OpOrder.Group opGroup);

    protected AbstractAllocator allocator(OpOrder.Group writeOp)
    {
        return new ContextAllocator(writeOp, this);
    }

    private static class RowBufferAllocator extends RowDataBlock.Writer implements RowAllocator
    {
        private final AbstractAllocator allocator;
        private final boolean isCounter;

        private MemtableRowData.BufferClustering clustering;
        private int clusteringIdx;
        private LivenessInfo info;
        private DeletionTime deletion;
        private RowDataBlock data;

        private RowBufferAllocator(AbstractAllocator allocator, boolean isCounter)
        {
            super(true);
            this.allocator = allocator;
            this.isCounter = isCounter;
        }

        public void allocateNewRow(int clusteringSize, Columns columns, boolean isStatic)
        {
            data = new RowDataBlock(columns, 1, false, isCounter);
            clustering = isStatic ? null : new MemtableRowData.BufferClustering(clusteringSize);
            clusteringIdx = 0;
            updateWriter(data);
        }

        public MemtableRowData allocatedRowData()
        {
            MemtableRowData row = new MemtableRowData.BufferRowData(clustering == null ? Clustering.STATIC_CLUSTERING : clustering,
                                                                    info,
                                                                    deletion,
                                                                    data);

            clustering = null;
            info = LivenessInfo.NONE;
            deletion = DeletionTime.LIVE;
            data = null;

            return row;
        }

        public void writeClusteringValue(ByteBuffer value)
        {
            clustering.setClusteringValue(clusteringIdx++, value == null ? null : allocator.clone(value));
        }

        public void writePartitionKeyLivenessInfo(LivenessInfo info)
        {
            this.info = info;
        }

        public void writeRowDeletion(DeletionTime deletion)
        {
            this.deletion = deletion;
        }

        @Override
        public void writeCell(ColumnDefinition column, boolean isCounter, ByteBuffer value, LivenessInfo info, CellPath path)
        {
            ByteBuffer v = allocator.clone(value);
            if (column.isComplex())
                complexWriter.addCell(column, v, info, MemtableRowData.BufferCellPath.clone(path, allocator));
            else
                simpleWriter.addCell(column, v, info);
        }
    }
}


text:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from accounts.models import Account,BiffyUser
# Register your models here.

#class B1ifAdmin(admin.ModelAdmin):

#admin.site.register(B1if, B1ifAdmin)
admin.site.register(Account)

class BiffyUserInline(admin.StackedInline):
    model = BiffyUser
    can_delete = False
    verbose_name_plural = 'biffy user'

# Define a new User admin
class UserAdmin(UserAdmin):
    inlines = (BiffyUserInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)