text:
"""
The MIT License (MIT)

Copyright (c) 2016 Mervin <mofei2816@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from django.db import models
from mistune import Markdown
from bs4 import BeautifulSoup

from core.utils import BlogContentRenderer
from core.utils import format_publish_time
from .misc import Tag

class Article(models.Model):
    """Article model
    """
    # article id
    id = models.AutoField(
        db_column='id',
        primary_key=True,
        unique=True,
        verbose_name='ID'
    )
    # article title
    title = models.CharField(
        db_column='title',
        max_length=256,
        verbose_name='Title'
    )
    # markdown content
    md_content = models.TextField(
        db_column='md_content',
        null=False,
        blank=False,
        default='',
        verbose_name='Markdown'
    )
    # html content
    html_content = models.TextField(
        db_column='html_content',
        null=False,
        blank=False,
        default='',
        verbose_name='HTML',
        editable=False
    )
    # preview content
    preview_content = models.CharField(
        db_column='preview_content',
        max_length=1024,
        null=False,
        blank=False,
        default='',
        verbose_name='Preview',
        editable=False
    )
    # publish time
    publish_time = models.DateTimeField(
        db_column='publish_time',
        verbose_name='Publish Time'
    )
    # background music id of 163 music service
    bgm_id = models.CharField(
        db_column='bgm_id',
        null=True,
        blank=True,
        max_length=16,
        verbose_name='163 Music ID'
    )
    # tags
    tags = models.ManyToManyField(
        Tag,
        db_table='core_article_tag_relation',
        verbose_name='Tags'
    )

    class Meta(object):
        db_table = 'core_article'
        verbose_name_plural = 'Article'

    def save(self, *args, **kwargs):
        # markdown to html
        markdown = Markdown(renderer=BlogContentRenderer())
        self.html_content = markdown(self.md_content)
        # preview content
        bs = BeautifulSoup(self.html_content, 'html.parser')
        p_list = bs.find_all('p')
        preview = ''
        preview_len = 0
        preview_paragraph = 0
        for p_item in p_list:
            p_item_string_len = len(p_item.get_text().strip()) if isinstance(p_item.get_text(), str) else 0
            if p_item_string_len > 0:
                preview += '<p>%s</p>' % p_item.get_text()
                preview_len += p_item_string_len
                preview_paragraph += 1
            if preview_len > 200 or preview_paragraph >= 5:
                break
        self.preview_content = preview
        super(Article, self).save(*args, **kwargs)
        # process images
        # clear old image data
        article_images = ArticleImage.objects.filter(article=self)
        for article_image in article_images:
            article_image.delete()
        # write new data
        img_list = bs.find_all('img')
        for img_item in img_list:
            src = img_item.get('src')
            if not isinstance(src, str) or len(src.strip()) == 0:
                continue
            article_image = ArticleImage(url=src, publish_time=self.publish_time, article=self)
            article_image.save()

    def __str__(self):
        return self.title

    def to_dict(self, preview_content=True, md_content=True, html_content=True, short_publish_time=False,
                with_images=False, max_images=3):
        preview_content = preview_content if isinstance(preview_content, bool) else False
        md_content = md_content if isinstance(md_content, bool) else False
        html_content = html_content if isinstance(html_content, bool) else False
        with_images = with_images if isinstance(with_images, bool) else False
        max_images = max_images if isinstance(max_images, int) else 3
        data = {
            'content_type': 'article',
            'id': self.id,
            'title': self.title,
            'publish_time': self.publish_time.strftime('%Y-%m-%d %H:%M:%S'),
            'publish_time_display': format_publish_time(self.publish_time, short_publish_time),
            'bgm_id': self.bgm_id,
            'tags': [tag.to_dict() for tag in self.tags.all()]
        }
        if preview_content:
            data['preview_content'] = self.preview_content
        if md_content:
            data['md_content'] = self.md_content
        if html_content:
            data['html_content'] = self.html_content
        if with_images:
            data['images'] = [image.to_dict() for image in list(self.images.all().order_by('id')[0:max_images])]
        return data

    def get_absolute_url(self):
        return '/post/%d' % self.id

class ArticleImage(models.Model):
    # id
    id = models.AutoField(
        db_column='id',
        primary_key=True,
        unique=True
    )
    # article
    article = models.ForeignKey(
        Article,
        db_column='article_id',
        related_name='images'
    )
    # url
    url = models.CharField(
        db_column='url',
        max_length=256
    )
    # publish time
    publish_time = models.DateTimeField(
        db_column='publish_time'
    )

    class Meta:
        db_table = 'core_article_image'
        verbose_name_plural = 'Article Image'

    def to_dict(self):
        return {
            'content_type': 'image',
            'id': self.id,
            'url': self.url
        }


text:
tar xvf .travis/secrets.tar -C .travis

# Setup SSH agent:
eval "$(ssh-agent -s)" #start the ssh agent
chmod 600 .travis/build-key.pem
ssh-add .travis/build-key.pem

# Setup git defaults:
git config --global user.email "lucas@cherifi.info"
git config --global user.name "lucas@cherifi.info"

# Add SSH-based remote to GitHub repo:
git remote add deploy git@github.com:localhook/localhook.git
git fetch deploy

# Get box and build PHAR
wget https://box-project.github.io/box2/manifest.json
BOX_URL=$(php bin/parse-manifest.php manifest.json)
rm manifest.json
wget -O box.phar ${BOX_URL}
chmod 755 box.phar
./box.phar build -vv
# Without the following step, we cannot checkout the gh-pages branch due to
# file conflicts:
mv localhook.phar localhook.phar.tmp

# Checkout gh-pages and add PHAR file and version:
git checkout -b gh-pages deploy/gh-pages
mv localhook.phar.tmp localhook.phar
sha1sum localhook.phar > localhook.phar.version
git add localhook.phar localhook.phar.version

# Commit and push:
git commit -m 'Rebuilt phar'
git push deploy gh-pages:gh-pages

redpajama_set_name: RedPajamaGithub


text:
{{post.title}}

{{post.content}}

					Posted on

					by

		All Posts


text:
package com.intellij.codeInsight.daemon;

import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.ModifiableModel;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.SeverityProvider;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * User: anna
 * Date: Dec 20, 2004
 */
public class InspectionProfileConvertor {
  private final Map<String, HighlightDisplayLevel> myDisplayLevelMap = new HashMap<>();
  @NonNls public static final String OLD_HIGHTLIGHTING_SETTINGS_PROFILE = "EditorHighlightingSettings";
  @NonNls public static final String OLD_DEFAUL_PROFILE = "OldDefaultProfile";

  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettingsConvertor");

  @NonNls private static final String INSPECTIONS_TAG = "inspections";
  @NonNls private static final String NAME_ATT = "name";
  @NonNls private static final String INSP_TOOL_TAG = "inspection_tool";
  @NonNls private static final String CLASS_ATT = "class";
  @NonNls private static final String VERSION_ATT = "version";
  @NonNls private static final String PROFILE_NAME_ATT = "profile_name";
  @NonNls private static final String OPTION_TAG = "option";
  @NonNls private static final String DISPLAY_LEVEL_MAP_OPTION = "DISPLAY_LEVEL_MAP";
  @NonNls protected static final String VALUE_ATT = "value";
  @NonNls private static final String DEFAULT_XML = "Default.xml";
  @NonNls private static final String XML_EXTENSION = ".xml";
  @NonNls public static final String LEVEL_ATT = "level";
  private final SeverityProvider myManager;

  public InspectionProfileConvertor(@NotNull SeverityProvider manager) {
    myManager = manager;
    renameOldDefaultsProfile();
  }

  private boolean retrieveOldSettings(@NotNull Element element) {
    boolean hasOldSettings = false;
    for (Element option : element.getChildren(OPTION_TAG)) {
      final String name = option.getAttributeValue(NAME_ATT);
      if (name != null) {
        hasOldSettings |= processElement(option, name);
      }
    }
    return hasOldSettings;
  }

  protected boolean processElement(final Element option, final String name) {
    if (name.equals(DISPLAY_LEVEL_MAP_OPTION)) {
      for (Element e : option.getChild(VALUE_ATT).getChildren()) {
        String key = e.getName();
        String levelName = e.getAttributeValue(LEVEL_ATT);
        HighlightSeverity severity = myManager.getSeverityRegistrar().getSeverity(levelName);
        HighlightDisplayLevel level = severity == null ? null : HighlightDisplayLevel.find(severity);
        if (level == null) continue;
        myDisplayLevelMap.put(key, level);
      }
      return true;
    }
    return false;
  }

  public void storeEditorHighlightingProfile(@NotNull Element element, @NotNull InspectionProfile editorProfile) {
    if (retrieveOldSettings(element)) {
      ModifiableModel editorProfileModel = editorProfile.getModifiableModel();
      fillErrorLevels(editorProfileModel);
      editorProfileModel.commit();
    }
  }

  public static Element convertToNewFormat(Element profileFile, InspectionProfile profile) {
    Element rootElement = new Element(INSPECTIONS_TAG);
    rootElement.setAttribute(NAME_ATT, profile.getName());
    final InspectionToolWrapper[] tools = profile.getInspectionTools(null);
    for (final Object o : profileFile.getChildren(INSP_TOOL_TAG)) {
      Element toolElement = ((Element)o).clone();
      String toolClassName = toolElement.getAttributeValue(CLASS_ATT);
      final String shortName = convertToShortName(toolClassName, tools);
      if (shortName == null) {
        continue;
      }
      toolElement.setAttribute(CLASS_ATT, shortName);
      rootElement.addContent(toolElement);
    }
    return rootElement;
  }

  private static void renameOldDefaultsProfile() {
    String directoryPath = PathManager.getConfigPath() + File.separator + InspectionProfileManager.INSPECTION_DIR;
    File profileDirectory = new File(directoryPath);
    if (!profileDirectory.exists()) {
      return;
    }

    File[] files = profileDirectory.listFiles(pathname -> pathname.getPath().endsWith(File.separator + DEFAULT_XML));
    if (files == null || files.length != 1 || !files[0].isFile()) {
      return;
    }
    try {
      Document doc = JDOMUtil.loadDocument(files[0]);
      Element root = doc.getRootElement();
      if (root.getAttributeValue(VERSION_ATT) == null){
        root.setAttribute(PROFILE_NAME_ATT, OLD_DEFAUL_PROFILE);
        JDOMUtil.writeDocument(doc, new File(profileDirectory, OLD_DEFAUL_PROFILE + XML_EXTENSION), "\n");
        FileUtil.delete(files[0]);
      }
    }
    catch (IOException e) {
      LOG.error(e);
    }
    catch (JDOMException e) {
      LOG.error(e);
    }
  }

  protected void fillErrorLevels(final ModifiableModel profile) {
    InspectionToolWrapper[] toolWrappers = profile.getInspectionTools(null);
    LOG.assertTrue(toolWrappers != null, "Profile was not correctly init");
    //fill error levels
    for (final String shortName : myDisplayLevelMap.keySet()) {
      //key <-> short name
      HighlightDisplayLevel level = myDisplayLevelMap.get(shortName);

      HighlightDisplayKey key = HighlightDisplayKey.find(shortName);

      if (key == null) continue;

      //set up tools for default profile
      if (level != HighlightDisplayLevel.DO_NOT_SHOW) {
        profile.enableTool(shortName, null, null);
      }

      if (level == null || level == HighlightDisplayLevel.DO_NOT_SHOW) {
        level = HighlightDisplayLevel.WARNING;
      }
      profile.setErrorLevel(key, level, null);
    }
  }

  @Nullable
  private static String convertToShortName(String displayName, InspectionToolWrapper[] tools) {
    if (displayName == null) return null;
    for (InspectionToolWrapper tool : tools) {
      if (displayName.equals(tool.getDisplayName())) {
        return tool.getShortName();
      }
    }
    return null;
  }
}


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

function testInstallButtonHiddenUntilInfoReady() {
  // Polyfill chrome.app.window.current().
  /** @suppress {checkTypes,const} */
  chrome.app = {window: {current: () => null}};

  loadTimeData.data = {};

  let getInfoCallback;
  /** @suppress {checkTypes,const} */
  chrome.fileManagerPrivate = {
    getLinuxPackageInfo: (entry, callback) => {
      getInfoCallback = callback;
    }
  };
  const container =
      assertInstanceof(document.createElement('div'), HTMLElement);

  const info = {name: 'n', version: 'v', info: 'i', summary: 's'};
  const dialog = new cr.filebrowser.InstallLinuxPackageDialog(container);

  // Show dialog and very that install button is disabled.
  dialog.showInstallLinuxPackageDialog(/** @type {!Entry} */ ({}));
  assertTrue(container.querySelector('.cr-dialog-ok').disabled);

  // Button becomes enabled once info is ready.
  getInfoCallback(info);
  assertFalse(container.querySelector('.cr-dialog-ok').disabled);
}


text:
import scrapy

class ToScrapeCSSSpider(scrapy.Spider):
    name = "scrape_know"
    start_urls = [
        'http://www.knowafest.com/college-fests/upcomingfests',
    ]

    def parse(self, response):
        for scrape in response.css("div.blog-thumb"):
            yield {
                'text': scrape.css(".headline.h2::text").extract_first(),
                'Type': scrape.css("dd.fa-fa-calendar::text").extract_first(),
                'Date': scrape.css("dd.fa-fa-calendar::text"),
                'IMG': scrape.css(".pull-right.h4::text").extract(),
            }

        next_page_url = response.css("li.next > a::attr(href)").extract_first()
        if next_page_url is not None:
             yield scrapy.Request(response.urljoin(next_page_url))


text:
package org.osiam.client;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.osiam.client.exception.UnauthorizedException;
import org.osiam.client.oauth.AccessToken;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseOperation;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/context.xml")
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        DbUnitTestExecutionListener.class})
@DatabaseSetup("/database_seed.xml")
@DatabaseTearDown(value = "/database_tear_down.xml", type = DatabaseOperation.DELETE_ALL)
public class LoginClientCredentialsIT {

    protected static final String AUTH_ENDPOINT_ADDRESS = "http://localhost:8180/osiam-auth-server";
    protected static final String RESOURCE_ENDPOINT_ADDRESS = "http://localhost:8180/osiam-resource-server";
    protected String clientId = "example-client";
    protected String clientSecret = "secret";
    protected OsiamConnector oConnector;

	@Test
	public void login_with_client_credentials(){
        OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder().
                setAuthServerEndpoint(AUTH_ENDPOINT_ADDRESS).
                setResourceServerEndpoint(RESOURCE_ENDPOINT_ADDRESS).
                setClientId(clientId).
                setClientSecret(clientSecret);
        oConnector = oConBuilder.build();
        AccessToken at = oConnector.retrieveAccessToken();

        assertThat(at, is(notNullValue()));
	}

	@Test (expected = UnauthorizedException.class)
	public void login_with_wrong_client_credentials(){
        OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder().
                setAuthServerEndpoint(AUTH_ENDPOINT_ADDRESS).
                setResourceServerEndpoint(RESOURCE_ENDPOINT_ADDRESS).
                setClientId(clientId).
                setClientSecret("wrong" + clientSecret);
        oConnector = oConBuilder.build();
        oConnector.retrieveAccessToken();

        fail("Exception expected");
	}

}


text:
import type Printer from "../printer";
import { isIdentifier } from "@babel/types";
import type * as t from "@babel/types";

export function _params(
  this: Printer,
  node: t.Function | t.TSDeclareMethod | t.TSDeclareFunction,
) {
  this.print(node.typeParameters, node);
  this.token("(");
  this._parameters(node.params, node);
  this.token(")");

  const noLineTerminator = node.type === "ArrowFunctionExpression";
  this.print(node.returnType, node, noLineTerminator);

  this._noLineTerminator = noLineTerminator;
}

export function _parameters(
  this: Printer,
  parameters: t.Function["params"],
  parent:
    | t.Function
    | t.TSIndexSignature
    | t.TSDeclareMethod
    | t.TSDeclareFunction
    | t.TSFunctionType
    | t.TSConstructorType,
) {
  const paramLength = parameters.length;
  for (let i = 0; i < paramLength; i++) {
    this._param(parameters[i], parent);

    if (i < parameters.length - 1) {
      this.token(",");
      this.space();
    }
  }
}

export function _param(
  this: Printer,
  parameter: t.Identifier | t.RestElement | t.Pattern | t.TSParameterProperty,
  parent?:
    | t.Function
    | t.TSIndexSignature
    | t.TSDeclareMethod
    | t.TSDeclareFunction
    | t.TSFunctionType
    | t.TSConstructorType,
) {
  this.printJoin(parameter.decorators, parameter);
  this.print(parameter, parent);
  if (
    // @ts-expect-error optional is not in TSParameterProperty
    parameter.optional
  ) {
    this.token("?"); // TS / flow
  }

  this.print(
    // @ts-expect-error typeAnnotation is not in TSParameterProperty
    parameter.typeAnnotation,
    parameter,
  ); // TS / flow
}

export function _methodHead(this: Printer, node: t.Method | t.TSDeclareMethod) {
  const kind = node.kind;
  const key = node.key;

  if (kind === "get" || kind === "set") {
    this.word(kind);
    this.space();
  }

  if (node.async) {
    this.word("async", true);
    this.space();
  }

  if (
    kind === "method" ||
    // @ts-expect-error Fixme: kind: "init" is not defined
    kind === "init"
  ) {
    if (node.generator) {
      this.token("*");
    }
  }

  if (node.computed) {
    this.token("[");
    this.print(key, node);
    this.token("]");
  } else {
    this.print(key, node);
  }

  if (
    // @ts-expect-error optional is not in ObjectMethod
    node.optional
  ) {
    // TS
    this.token("?");
  }

  this._params(node);
}

export function _predicate(
  this: Printer,
  node:
    | t.FunctionDeclaration
    | t.FunctionExpression
    | t.ArrowFunctionExpression,
  noLineTerminatorAfter?: boolean,
) {
  if (node.predicate) {
    if (!node.returnType) {
      this.token(":");
    }
    this.space();
    this.print(node.predicate, node, noLineTerminatorAfter);
  }
}

export function _functionHead(
  this: Printer,
  node: t.FunctionDeclaration | t.FunctionExpression | t.TSDeclareFunction,
) {
  if (node.async) {
    this.word("async");
    // We prevent inner comments from being printed here,
    // so that they are always consistently printed in the
    // same place regardless of the function type.
    this._endsWithInnerRaw = false;
    this.space();
  }
  this.word("function");
  if (node.generator) {
    // We prevent inner comments from being printed here,
    // so that they are always consistently printed in the
    // same place regardless of the function type.
    this._endsWithInnerRaw = false;
    this.token("*");
  }

  this.space();
  if (node.id) {
    this.print(node.id, node);
  }

  this._params(node);
  if (node.type !== "TSDeclareFunction") {
    this._predicate(node);
  }
}

export function FunctionExpression(this: Printer, node: t.FunctionExpression) {
  this._functionHead(node);
  this.space();
  this.print(node.body, node);
}

export { FunctionExpression as FunctionDeclaration };

export function ArrowFunctionExpression(
  this: Printer,
  node: t.ArrowFunctionExpression,
) {
  if (node.async) {
    this.word("async", true);
    this.space();
  }

  // Try to avoid printing parens in simple cases, but only if we're pretty
  // sure that they aren't needed by type annotations or potential newlines.
  let firstParam;
  if (
    !this.format.retainLines &&
    node.params.length === 1 &&
    isIdentifier((firstParam = node.params[0])) &&
    !hasTypesOrComments(node, firstParam)
  ) {
    this.print(firstParam, node, true);
  } else {
    this._params(node);
  }

  this._predicate(node, true);
  this.space();
  // When printing (x)/*1*/=>{}, we remove the parentheses
  // and thus there aren't two contiguous inner tokens.
  // We forcefully print inner comments here.
  this.printInnerComments();
  this.token("=>");

  this.space();

  this.print(node.body, node);
}

function hasTypesOrComments(
  node: t.ArrowFunctionExpression,
  param: t.Identifier,
): boolean {
  return !!(
    node.typeParameters ||
    node.returnType ||
    node.predicate ||
    param.typeAnnotation ||
    param.optional ||
    // Flow does not support `foo /*: string*/ => {};`
    param.leadingComments?.length ||
    param.trailingComments?.length
  );
}


text:
package com.google.cloud.language.v1beta2;

import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.language.v1beta2.stub.LanguageServiceStub;
import com.google.cloud.language.v1beta2.stub.LanguageServiceStubSettings;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * Service Description: Provides text analysis operations such as sentiment analysis and entity
 * recognition.
 *
 *
This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
 *   Document document = Document.newBuilder().build();
 *   AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(document);
 * }
 * }

 *
 *
Note: close() needs to be called on the LanguageServiceClient object to clean up resources
 * such as threads. In the example above, try-with-resources is used, which automatically calls
 * close().
 *
 *
The surface of this class includes several types of Java methods for each of the API's
 * methods:
 *
 *

 *
A "flattened" method. With this type of method, the fields of the request type have been
 *       converted into function parameters. It may be the case that not all fields are available as
 *       parameters, and not every API method will have a flattened method entry point.
 *
A "request object" method. This type of method only takes one parameter, a request object,
 *       which must be constructed before the call. Not every API method will have a request object
 *       method.
 *
A "callable" method. This type of method takes no parameters and returns an immutable API
 *       callable object, which can be used to initiate calls to the service.
 *

 *
 *
See the individual methods for example code.
 *
 *
Many parameters require resource names to be formatted in a particular way. To assist with
 * these names, this class includes a format method for each type of name, and additionally a parse
 * method to extract the individual identifiers contained within names that are returned.
 *
 *
This class can be customized by passing in a custom instance of LanguageServiceSettings to
 * create(). For example:
 *
 *
To customize credentials:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * LanguageServiceSettings languageServiceSettings =
 *     LanguageServiceSettings.newBuilder()
 *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
 *         .build();
 * LanguageServiceClient languageServiceClient =
 *     LanguageServiceClient.create(languageServiceSettings);
 * }

 *
 *
To customize the endpoint:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * LanguageServiceSettings languageServiceSettings =
 *     LanguageServiceSettings.newBuilder().setEndpoint(myEndpoint).build();
 * LanguageServiceClient languageServiceClient =
 *     LanguageServiceClient.create(languageServiceSettings);
 * }

 *
 *
To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over
 * the wire:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * LanguageServiceSettings languageServiceSettings =
 *     LanguageServiceSettings.newHttpJsonBuilder().build();
 * LanguageServiceClient languageServiceClient =
 *     LanguageServiceClient.create(languageServiceSettings);
 * }

 *
 *
Please refer to the GitHub repository's samples for more quickstart code snippets.
 */
@BetaApi
@Generated("by gapic-generator-java")
public class LanguageServiceClient implements BackgroundResource {
  private final LanguageServiceSettings settings;
  private final LanguageServiceStub stub;

  /** Constructs an instance of LanguageServiceClient with default settings. */
  public static final LanguageServiceClient create() throws IOException {
    return create(LanguageServiceSettings.newBuilder().build());
  }

  /**
   * Constructs an instance of LanguageServiceClient, using the given settings. The channels are
   * created based on the settings passed in, or defaults for any settings that are not set.
   */
  public static final LanguageServiceClient create(LanguageServiceSettings settings)
      throws IOException {
    return new LanguageServiceClient(settings);
  }

  /**
   * Constructs an instance of LanguageServiceClient, using the given stub for making calls. This is
   * for advanced usage - prefer using create(LanguageServiceSettings).
   */
  public static final LanguageServiceClient create(LanguageServiceStub stub) {
    return new LanguageServiceClient(stub);
  }

  /**
   * Constructs an instance of LanguageServiceClient, using the given settings. This is protected so
   * that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected LanguageServiceClient(LanguageServiceSettings settings) throws IOException {
    this.settings = settings;
    this.stub = ((LanguageServiceStubSettings) settings.getStubSettings()).createStub();
  }

  protected LanguageServiceClient(LanguageServiceStub stub) {
    this.settings = null;
    this.stub = stub;
  }

  public final LanguageServiceSettings getSettings() {
    return settings;
  }

  public LanguageServiceStub getStub() {
    return stub;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the sentiment of the provided text.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(document);
   * }
   * }

   *
   * @param document Required. Input document.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSentimentResponse analyzeSentiment(Document document) {
    AnalyzeSentimentRequest request =
        AnalyzeSentimentRequest.newBuilder().setDocument(document).build();
    return analyzeSentiment(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the sentiment of the provided text.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   EncodingType encodingType = EncodingType.forNumber(0);
   *   AnalyzeSentimentResponse response =
   *       languageServiceClient.analyzeSentiment(document, encodingType);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param encodingType The encoding type used by the API to calculate sentence offsets for the
   *     sentence sentiment.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSentimentResponse analyzeSentiment(
      Document document, EncodingType encodingType) {
    AnalyzeSentimentRequest request =
        AnalyzeSentimentRequest.newBuilder()
            .setDocument(document)
            .setEncodingType(encodingType)
            .build();
    return analyzeSentiment(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the sentiment of the provided text.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeSentimentRequest request =
   *       AnalyzeSentimentRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSentimentResponse analyzeSentiment(AnalyzeSentimentRequest request) {
    return analyzeSentimentCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the sentiment of the provided text.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeSentimentRequest request =
   *       AnalyzeSentimentRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   ApiFuture<AnalyzeSentimentResponse> future =
   *       languageServiceClient.analyzeSentimentCallable().futureCall(request);
   *   // Do something.
   *   AnalyzeSentimentResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<AnalyzeSentimentRequest, AnalyzeSentimentResponse>
      analyzeSentimentCallable() {
    return stub.analyzeSentimentCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds named entities (currently proper names and common nouns) in the text along with entity
   * types, salience, mentions for each entity, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnalyzeEntitiesResponse response = languageServiceClient.analyzeEntities(document);
   * }
   * }

   *
   * @param document Required. Input document.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitiesResponse analyzeEntities(Document document) {
    AnalyzeEntitiesRequest request =
        AnalyzeEntitiesRequest.newBuilder().setDocument(document).build();
    return analyzeEntities(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds named entities (currently proper names and common nouns) in the text along with entity
   * types, salience, mentions for each entity, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   EncodingType encodingType = EncodingType.forNumber(0);
   *   AnalyzeEntitiesResponse response =
   *       languageServiceClient.analyzeEntities(document, encodingType);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param encodingType The encoding type used by the API to calculate offsets.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitiesResponse analyzeEntities(
      Document document, EncodingType encodingType) {
    AnalyzeEntitiesRequest request =
        AnalyzeEntitiesRequest.newBuilder()
            .setDocument(document)
            .setEncodingType(encodingType)
            .build();
    return analyzeEntities(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds named entities (currently proper names and common nouns) in the text along with entity
   * types, salience, mentions for each entity, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeEntitiesRequest request =
   *       AnalyzeEntitiesRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   AnalyzeEntitiesResponse response = languageServiceClient.analyzeEntities(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest request) {
    return analyzeEntitiesCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds named entities (currently proper names and common nouns) in the text along with entity
   * types, salience, mentions for each entity, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeEntitiesRequest request =
   *       AnalyzeEntitiesRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   ApiFuture<AnalyzeEntitiesResponse> future =
   *       languageServiceClient.analyzeEntitiesCallable().futureCall(request);
   *   // Do something.
   *   AnalyzeEntitiesResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse>
      analyzeEntitiesCallable() {
    return stub.analyzeEntitiesCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds entities, similar to
   * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
   * and analyzes sentiment associated with each entity and its mentions.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnalyzeEntitySentimentResponse response =
   *       languageServiceClient.analyzeEntitySentiment(document);
   * }
   * }

   *
   * @param document Required. Input document.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitySentimentResponse analyzeEntitySentiment(Document document) {
    AnalyzeEntitySentimentRequest request =
        AnalyzeEntitySentimentRequest.newBuilder().setDocument(document).build();
    return analyzeEntitySentiment(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds entities, similar to
   * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
   * and analyzes sentiment associated with each entity and its mentions.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   EncodingType encodingType = EncodingType.forNumber(0);
   *   AnalyzeEntitySentimentResponse response =
   *       languageServiceClient.analyzeEntitySentiment(document, encodingType);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param encodingType The encoding type used by the API to calculate offsets.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitySentimentResponse analyzeEntitySentiment(
      Document document, EncodingType encodingType) {
    AnalyzeEntitySentimentRequest request =
        AnalyzeEntitySentimentRequest.newBuilder()
            .setDocument(document)
            .setEncodingType(encodingType)
            .build();
    return analyzeEntitySentiment(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds entities, similar to
   * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
   * and analyzes sentiment associated with each entity and its mentions.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeEntitySentimentRequest request =
   *       AnalyzeEntitySentimentRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   AnalyzeEntitySentimentResponse response =
   *       languageServiceClient.analyzeEntitySentiment(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeEntitySentimentResponse analyzeEntitySentiment(
      AnalyzeEntitySentimentRequest request) {
    return analyzeEntitySentimentCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Finds entities, similar to
   * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
   * and analyzes sentiment associated with each entity and its mentions.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeEntitySentimentRequest request =
   *       AnalyzeEntitySentimentRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   ApiFuture<AnalyzeEntitySentimentResponse> future =
   *       languageServiceClient.analyzeEntitySentimentCallable().futureCall(request);
   *   // Do something.
   *   AnalyzeEntitySentimentResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<AnalyzeEntitySentimentRequest, AnalyzeEntitySentimentResponse>
      analyzeEntitySentimentCallable() {
    return stub.analyzeEntitySentimentCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
   * part of speech tags, dependency trees, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnalyzeSyntaxResponse response = languageServiceClient.analyzeSyntax(document);
   * }
   * }

   *
   * @param document Required. Input document.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSyntaxResponse analyzeSyntax(Document document) {
    AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder().setDocument(document).build();
    return analyzeSyntax(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
   * part of speech tags, dependency trees, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   EncodingType encodingType = EncodingType.forNumber(0);
   *   AnalyzeSyntaxResponse response = languageServiceClient.analyzeSyntax(document, encodingType);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param encodingType The encoding type used by the API to calculate offsets.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSyntaxResponse analyzeSyntax(Document document, EncodingType encodingType) {
    AnalyzeSyntaxRequest request =
        AnalyzeSyntaxRequest.newBuilder()
            .setDocument(document)
            .setEncodingType(encodingType)
            .build();
    return analyzeSyntax(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
   * part of speech tags, dependency trees, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeSyntaxRequest request =
   *       AnalyzeSyntaxRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   AnalyzeSyntaxResponse response = languageServiceClient.analyzeSyntax(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnalyzeSyntaxResponse analyzeSyntax(AnalyzeSyntaxRequest request) {
    return analyzeSyntaxCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
   * part of speech tags, dependency trees, and other properties.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnalyzeSyntaxRequest request =
   *       AnalyzeSyntaxRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   ApiFuture<AnalyzeSyntaxResponse> future =
   *       languageServiceClient.analyzeSyntaxCallable().futureCall(request);
   *   // Do something.
   *   AnalyzeSyntaxResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse> analyzeSyntaxCallable() {
    return stub.analyzeSyntaxCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Classifies a document into categories.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   ClassifyTextResponse response = languageServiceClient.classifyText(document);
   * }
   * }

   *
   * @param document Required. Input document.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ClassifyTextResponse classifyText(Document document) {
    ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(document).build();
    return classifyText(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Classifies a document into categories.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   ClassifyTextRequest request =
   *       ClassifyTextRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setClassificationModelOptions(ClassificationModelOptions.newBuilder().build())
   *           .build();
   *   ClassifyTextResponse response = languageServiceClient.classifyText(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ClassifyTextResponse classifyText(ClassifyTextRequest request) {
    return classifyTextCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Classifies a document into categories.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   ClassifyTextRequest request =
   *       ClassifyTextRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setClassificationModelOptions(ClassificationModelOptions.newBuilder().build())
   *           .build();
   *   ApiFuture<ClassifyTextResponse> future =
   *       languageServiceClient.classifyTextCallable().futureCall(request);
   *   // Do something.
   *   ClassifyTextResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<ClassifyTextRequest, ClassifyTextResponse> classifyTextCallable() {
    return stub.classifyTextCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * A convenience method that provides all syntax, sentiment, entity, and classification features
   * in one call.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
   *   AnnotateTextResponse response = languageServiceClient.annotateText(document, features);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param features Required. The enabled features.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnnotateTextResponse annotateText(
      Document document, AnnotateTextRequest.Features features) {
    AnnotateTextRequest request =
        AnnotateTextRequest.newBuilder().setDocument(document).setFeatures(features).build();
    return annotateText(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * A convenience method that provides all syntax, sentiment, entity, and classification features
   * in one call.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   Document document = Document.newBuilder().build();
   *   AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
   *   EncodingType encodingType = EncodingType.forNumber(0);
   *   AnnotateTextResponse response =
   *       languageServiceClient.annotateText(document, features, encodingType);
   * }
   * }

   *
   * @param document Required. Input document.
   * @param features Required. The enabled features.
   * @param encodingType The encoding type used by the API to calculate offsets.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnnotateTextResponse annotateText(
      Document document, AnnotateTextRequest.Features features, EncodingType encodingType) {
    AnnotateTextRequest request =
        AnnotateTextRequest.newBuilder()
            .setDocument(document)
            .setFeatures(features)
            .setEncodingType(encodingType)
            .build();
    return annotateText(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * A convenience method that provides all syntax, sentiment, entity, and classification features
   * in one call.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnnotateTextRequest request =
   *       AnnotateTextRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setFeatures(AnnotateTextRequest.Features.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   AnnotateTextResponse response = languageServiceClient.annotateText(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final AnnotateTextResponse annotateText(AnnotateTextRequest request) {
    return annotateTextCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * A convenience method that provides all syntax, sentiment, entity, and classification features
   * in one call.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
   *   AnnotateTextRequest request =
   *       AnnotateTextRequest.newBuilder()
   *           .setDocument(Document.newBuilder().build())
   *           .setFeatures(AnnotateTextRequest.Features.newBuilder().build())
   *           .setEncodingType(EncodingType.forNumber(0))
   *           .build();
   *   ApiFuture<AnnotateTextResponse> future =
   *       languageServiceClient.annotateTextCallable().futureCall(request);
   *   // Do something.
   *   AnnotateTextResponse response = future.get();
   * }
   * }

   */
  public final UnaryCallable<AnnotateTextRequest, AnnotateTextResponse> annotateTextCallable() {
    return stub.annotateTextCallable();
  }

  @Override
  public final void close() {
    stub.close();
  }

  @Override
  public void shutdown() {
    stub.shutdown();
  }

  @Override
  public boolean isShutdown() {
    return stub.isShutdown();
  }

  @Override
  public boolean isTerminated() {
    return stub.isTerminated();
  }

  @Override
  public void shutdownNow() {
    stub.shutdownNow();
  }

  @Override
  public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
    return stub.awaitTermination(duration, unit);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1">
	<Title>
		<v8:item>
			<v8:lang>ru</v8:lang>
			<v8:content>Интернет-поддержка пользователей</v8:content>
		</v8:item>
	</Title>
	<Width>60</Width>
	<WindowOpeningMode>LockOwnerWindow</WindowOpeningMode>
	<AutoTitle>false</AutoTitle>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<Autofill>false</Autofill>
	</AutoCommandBar>
	<Events>
		<Event name="OnOpen">ПриОткрытии</Event>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
		<Event name="OnClose">ПриЗакрытии</Event>
	</Events>
	<ChildItems>
		<UsualGroup name="ГруппаЗаголовка" id="1">
			<Visible>false</Visible>
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа заголовка</v8:content>
				</v8:item>
			</Title>
			<HorizontalStretch>true</HorizontalStretch>
			<Group>Horizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаЗаголовкаExtendedTooltip" id="28"/>
			<ChildItems>
				<PictureDecoration name="КартинкаЗаголовка" id="2">
					<Width>4</Width>
					<Height>2</Height>
					<Title formatted="false">
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Картинка заголовка</v8:content>
						</v8:item>
					</Title>
					<Picture>
						<xr:Ref>CommonPicture.ИнтернетПоддержкаПользователей</xr:Ref>
						<xr:LoadTransparent>false</xr:LoadTransparent>
					</Picture>
					<ContextMenu name="КартинкаЗаголовкаКонтекстноеМеню" id="3"/>
					<ExtendedTooltip name="КартинкаЗаголовкаExtendedTooltip" id="29"/>
				</PictureDecoration>
				<LabelDecoration name="Заголовок" id="4">
					<VerticalStretch>true</VerticalStretch>

					<Title formatted="false">
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Интернет-поддержка пользователей</v8:content>
						</v8:item>
					</Title>
					<ContextMenu name="ЗаголовокКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="ЗаголовокExtendedTooltip" id="30"/>
				</LabelDecoration>
			</ChildItems>
		</UsualGroup>
		<UsualGroup name="ГруппаКонтента" id="6">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа контента</v8:content>
				</v8:item>
			</Title>
			<HorizontalStretch>true</HorizontalStretch>
			<VerticalStretch>false</VerticalStretch>
			<Group>Vertical</Group>
			<Representation>StrongSeparation</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаКонтентаExtendedTooltip" id="31"/>
			<ChildItems>
				<UsualGroup name="ГруппаЗаголовкаКонтента" id="7">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Группа заголовка контента</v8:content>
						</v8:item>
					</Title>
					<HorizontalStretch>true</HorizontalStretch>
					<Group>Horizontal</Group>
					<Representation>None</Representation>
					<ShowTitle>false</ShowTitle>
					<ExtendedTooltip name="ГруппаЗаголовкаКонтентаExtendedTooltip" id="32"/>
					<ChildItems>
						<PictureDecoration name="КартинкаЗаголовкаКонтента" id="8">
							<Width>4</Width>
							<Height>2</Height>
							<Title formatted="false">
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Картинка заголовка контента</v8:content>
								</v8:item>
							</Title>
							<Picture>
								<xr:Ref>CommonPicture.ИнтернетПоддержкаПользователейВнимание</xr:Ref>
								<xr:LoadTransparent>false</xr:LoadTransparent>
							</Picture>
							<ContextMenu name="КартинкаЗаголовкаКонтентаКонтекстноеМеню" id="9"/>
							<ExtendedTooltip name="КартинкаЗаголовкаКонтентаExtendedTooltip" id="33"/>
						</PictureDecoration>
						<LabelDecoration name="ЗаголовокКонтента" id="10">
							<AutoMaxWidth>false</AutoMaxWidth>
							<HorizontalStretch>true</HorizontalStretch>
							<VerticalStretch>true</VerticalStretch>

							<Title formatted="false">
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Интернет-поддержка продукта не оказывается</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="ЗаголовокКонтентаКонтекстноеМеню" id="11"/>
							<ExtendedTooltip name="ЗаголовокКонтентаExtendedTooltip" id="34"/>
						</LabelDecoration>
					</ChildItems>
				</UsualGroup>
				<UsualGroup name="ГруппаСодержанияКонтента" id="12">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Группа содержания контента</v8:content>
						</v8:item>
					</Title>
					<HorizontalStretch>true</HorizontalStretch>
					<Group>Vertical</Group>
					<ShowTitle>false</ShowTitle>
					<ExtendedTooltip name="ГруппаСодержанияКонтентаExtendedTooltip" id="35"/>
					<ChildItems>
						<LabelDecoration name="НадписьСодержанияКонтента" id="13">
							<AutoMaxWidth>false</AutoMaxWidth>
							<Height>2</Height>
							<HorizontalStretch>true</HorizontalStretch>
							<Title formatted="true">
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Интернет-поддержка этого программного продукта не оказывается. Обратитесь к партнеру, у которого вы приобрели эту программу или обратитесь в <link TechSupport>техподдержку</>.</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="НадписьСодержанияКонтентаКонтекстноеМеню" id="14"/>
							<ExtendedTooltip name="НадписьСодержанияКонтентаExtendedTooltip" id="36"/>
							<Events>
								<Event name="URLProcessing">НадписьСодержанияКонтентаОбработкаНавигационнойСсылки</Event>
							</Events>
						</LabelDecoration>
					</ChildItems>
				</UsualGroup>
			</ChildItems>
		</UsualGroup>
		<UsualGroup name="ГруппаЗапускатьПриСтарте" id="44">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа запускать при старте</v8:content>
				</v8:item>
			</Title>
			<Group>Vertical</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаЗапускатьПриСтартеРасширеннаяПодсказка" id="45"/>
			<ChildItems>
				<CheckBoxField name="ЗапускатьПриСтарте" id="41">
					<DataPath>ЗапускатьПриСтарте</DataPath>
					<TitleLocation>Right</TitleLocation>
					<CheckBoxType>Auto</CheckBoxType>
					<ContextMenu name="ЗапускатьПриСтартеКонтекстноеМеню" id="42"/>
					<ExtendedTooltip name="ЗапускатьПриСтартеРасширеннаяПодсказка" id="43"/>
					<Events>
						<Event name="OnChange">ЗапускатьПриСтартеПриИзменении</Event>
					</Events>
				</CheckBoxField>
				<LabelDecoration name="ДекорацияОтступ" id="46">
					<ContextMenu name="ДекорацияОтступКонтекстноеМеню" id="47"/>
					<ExtendedTooltip name="ДекорацияОтступРасширеннаяПодсказка" id="48"/>
				</LabelDecoration>
			</ChildItems>
		</UsualGroup>
		<UsualGroup name="ГруппаКнопок" id="15">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа кнопок</v8:content>
				</v8:item>
			</Title>
			<HorizontalStretch>true</HorizontalStretch>
			<Group>Horizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаКнопокExtendedTooltip" id="37"/>
			<ChildItems>
				<LabelDecoration name="ПустаяСтрокаОдин" id="19">
					<HorizontalStretch>true</HorizontalStretch>
					<ContextMenu name="ПустаяСтрокаОдинКонтекстноеМеню" id="20"/>
					<ExtendedTooltip name="ПустаяСтрокаОдинExtendedTooltip" id="38"/>
				</LabelDecoration>
				<Button name="Закрыть" id="16">
					<Type>UsualButton</Type>
					<DefaultButton>true</DefaultButton>
					<Width>9</Width>
					<CommandName>Form.StandardCommand.Close</CommandName>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>ОК</v8:content>
						</v8:item>
					</Title>
					<ExtendedTooltip name="ЗакрытьExtendedTooltip" id="39"/>
				</Button>
				<LabelDecoration name="ПустаяСтрокаДва" id="17">
					<HorizontalStretch>true</HorizontalStretch>
					<ContextMenu name="ПустаяСтрокаДваКонтекстноеМеню" id="18"/>
					<ExtendedTooltip name="ПустаяСтрокаДваExtendedTooltip" id="40"/>
				</LabelDecoration>
			</ChildItems>
		</UsualGroup>
	</ChildItems>
	<Attributes>
		<Attribute name="Объект" id="1">
			<Type>
				<v8:Type>cfg:DataProcessorObject.БазовыеФункцииИнтернетПоддержки</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
		</Attribute>
		<Attribute name="ПрограммноеЗакрытие" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Программное закрытие</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ЗапускатьПриСтарте" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Запускать Интернет-поддержку при начале работы с программой</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
	<Parameters>
		<Parameter name="ПриНачалеРаботыСистемы">
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Parameter>
	</Parameters>
</Form>


text:
package org.fossasia.phimpme.data.local;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/** Created by saurav on 10/10/17. */
public class FavouriteImagesModel extends RealmObject {

  @PrimaryKey private String path;
  private String description;

  public FavouriteImagesModel() {}

  public void setPath(String path) {
    this.path = path;
  }

  public String getPath() {
    return path;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public String getDescription() {
    return description;
  }
}


text:
import sys

from elements import Elements

try:
    from xml.etree import cElementTree as ET
except ImportError:
    try:
        import cElementTree as ET
    except ImportError:
        from elementtree import ET

xml_string = """
<message>

This is a test

</message>
"""

class Message(Elements):
  _tag = 'message'
  _children = Elements._children.copy()

  _children['body'] = ('body', ET.ElementTree)

  def __init__(self, body=False, text=None):
    self.body = body
    self.text = text

def test_etree():
    global xml_string
    e = Message()
    e.from_string(xml_string)

    root = e.body.getroot()
    assert ET.iselement(root)

    p = root.findtext("{http://www.w3.org/1999/xhtml}p")
    assert p == "This is a test"

    print e.to_string()

if __name__ == '__main__':
    test_etree()


text:
package frames

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"sort"

	"github.com/SlyMarbo/spdy/common"
)

type SETTINGS struct {
	Flags    common.Flags
	Settings common.Settings
}

func (frame *SETTINGS) Add(flags common.Flags, id uint32, value uint32) {
	frame.Settings[id] = &common.Setting{flags, id, value}
}

func (frame *SETTINGS) Compress(comp common.Compressor) error {
	return nil
}

func (frame *SETTINGS) Decompress(decomp common.Decompressor) error {
	return nil
}

func (frame *SETTINGS) Name() string {
	return "SETTINGS"
}

func (frame *SETTINGS) ReadFrom(reader io.Reader) (int64, error) {
	data, err := common.ReadExactly(reader, 12)
	if err != nil {
		return 0, err
	}

	err = controlFrameCommonProcessing(data[:5], _SETTINGS, common.FLAG_SETTINGS_CLEAR_SETTINGS)
	if err != nil {
		return 12, err
	}

	// Get and check length.
	length := int(common.BytesToUint24(data[5:8]))
	if length < 4 {
		return 12, common.IncorrectDataLength(length, 8)
	} else if length > common.MAX_FRAME_SIZE-8 {
		return 12, common.FrameTooLarge
	}

	// Check size.
	numSettings := int(common.BytesToUint32(data[8:12]))
	if length != 4+(8*numSettings) {
		return 12, common.IncorrectDataLength(length, 4+(8*numSettings))
	}

	// Read in data.
	settings, err := common.ReadExactly(reader, 8*numSettings)
	if err != nil {
		return 12, err
	}

	frame.Flags = common.Flags(data[4])
	frame.Settings = make(common.Settings)
	for i := 0; i < numSettings; i++ {
		j := i * 8
		setting := decodeSetting(settings[j:])
		if setting == nil {
			return int64(length), errors.New("Error: Failed to parse settings.")
		}
		frame.Settings[setting.ID] = setting
	}

	return int64(length), nil
}

func (frame *SETTINGS) String() string {
	buf := new(bytes.Buffer)
	flags := ""
	if frame.Flags.CLEAR_SETTINGS() {
		flags += " FLAG_SETTINGS_CLEAR_SETTINGS"
	}
	if flags == "" {
		flags = "[NONE]"
	} else {
		flags = flags[1:]
	}

	buf.WriteString("SETTINGS {\n\t")
	buf.WriteString(fmt.Sprintf("Version:              3\n\t"))
	buf.WriteString(fmt.Sprintf("Flags:                %s\n\t", flags))
	buf.WriteString(fmt.Sprintf("Settings:\n"))
	settings := frame.Settings.Settings()
	for _, setting := range settings {
		buf.WriteString("\t\t" + setting.String() + "\n")
	}
	buf.WriteString("}\n")

	return buf.String()
}

func (frame *SETTINGS) WriteTo(writer io.Writer) (int64, error) {
	settings := encodeSettings(frame.Settings)
	numSettings := uint32(len(frame.Settings))
	length := 4 + len(settings)
	out := make([]byte, 12)

	out[0] = 128                     // Control bit and Version
	out[1] = 3                       // Version
	out[2] = 0                       // Type
	out[3] = 4                       // Type
	out[4] = byte(frame.Flags)       // Flags
	out[5] = byte(length >> 16)      // Length
	out[6] = byte(length >> 8)       // Length
	out[7] = byte(length)            // Length
	out[8] = byte(numSettings >> 24) // Number of Entries
	out[9] = byte(numSettings >> 16) // Number of Entries
	out[10] = byte(numSettings >> 8) // Number of Entries
	out[11] = byte(numSettings)      // Number of Entries

	err := common.WriteExactly(writer, out)
	if err != nil {
		return 0, err
	}

	err = common.WriteExactly(writer, settings)
	if err != nil {
		return 12, err
	}

	return int64(length + 8), nil
}

func decodeSetting(data []byte) *common.Setting {
	if len(data) < 8 {
		return nil
	}

	setting := new(common.Setting)
	setting.Flags = common.Flags(data[0])
	setting.ID = common.BytesToUint24(data[1:])
	setting.Value = common.BytesToUint32(data[4:])

	return setting
}

func encodeSettings(s common.Settings) []byte {
	if len(s) == 0 {
		return []byte{}
	}

	ids := make([]int, 0, len(s))
	for id := range s {
		ids = append(ids, int(id))
	}

	sort.Sort(sort.IntSlice(ids))

	out := make([]byte, 8*len(s))

	offset := 0
	for _, id := range ids {
		setting := s[uint32(id)]
		out[offset] = byte(setting.Flags)
		out[offset+1] = byte(setting.ID >> 16)
		out[offset+2] = byte(setting.ID >> 8)
		out[offset+3] = byte(setting.ID)
		out[offset+4] = byte(setting.Value >> 24)
		out[offset+5] = byte(setting.Value >> 16)
		out[offset+6] = byte(setting.Value >> 8)
		out[offset+7] = byte(setting.Value)
		offset += 8
	}

	return out
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks;

namespace Rikrop.Core.Wpf.Collections
{
    public class ItemLoaderWithConverter<TItem, TModelItem> : IItemLoader<IReadOnlyList<TModelItem>>
    {
        private readonly IItemLoader<IReadOnlyList<TItem>> _itemLoader;
        private readonly Func<TItem, TModelItem> _itemConverterFunc;

        public ItemLoaderWithConverter(IItemLoader<IReadOnlyList<TItem>> itemLoader, Func<TItem, TModelItem> itemConverterFunc)
        {
            Contract.Requires<ArgumentNullException>(itemLoader != null);
            Contract.Requires<ArgumentNullException>(itemConverterFunc != null);

            _itemLoader = itemLoader;
            _itemConverterFunc = itemConverterFunc;
        }

        public async Task<IReadOnlyList<TModelItem>> GetItem()
        {
            var items = await _itemLoader.GetItem();

            return items.Select(o => _itemConverterFunc(o)).ToList();
        }
    }
}


text:
package getter

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/pkg/errors"

	"helm.sh/helm/v3/internal/tlsutil"
	"helm.sh/helm/v3/internal/version"
	"helm.sh/helm/v3/pkg/cli"
)

func TestHTTPGetter(t *testing.T) {
	g, err := NewHTTPGetter(WithURL("http://example.com"))
	if err != nil {
		t.Fatal(err)
	}

	if _, ok := g.(*HTTPGetter); !ok {
		t.Fatal("Expected NewHTTPGetter to produce an *HTTPGetter")
	}

	cd := "../../testdata"
	join := filepath.Join
	ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem")
	insecure := false
	timeout := time.Second * 5

	// Test with options
	g, err = NewHTTPGetter(
		WithBasicAuth("I", "Am"),
		WithUserAgent("Groot"),
		WithTLSClientConfig(pub, priv, ca),
		WithInsecureSkipVerifyTLS(insecure),
		WithTimeout(timeout),
	)
	if err != nil {
		t.Fatal(err)
	}

	hg, ok := g.(*HTTPGetter)
	if !ok {
		t.Fatal("expected NewHTTPGetter to produce an *HTTPGetter")
	}

	if hg.opts.username != "I" {
		t.Errorf("Expected NewHTTPGetter to contain %q as the username, got %q", "I", hg.opts.username)
	}

	if hg.opts.password != "Am" {
		t.Errorf("Expected NewHTTPGetter to contain %q as the password, got %q", "Am", hg.opts.password)
	}

	if hg.opts.userAgent != "Groot" {
		t.Errorf("Expected NewHTTPGetter to contain %q as the user agent, got %q", "Groot", hg.opts.userAgent)
	}

	if hg.opts.certFile != pub {
		t.Errorf("Expected NewHTTPGetter to contain %q as the public key file, got %q", pub, hg.opts.certFile)
	}

	if hg.opts.keyFile != priv {
		t.Errorf("Expected NewHTTPGetter to contain %q as the private key file, got %q", priv, hg.opts.keyFile)
	}

	if hg.opts.caFile != ca {
		t.Errorf("Expected NewHTTPGetter to contain %q as the CA file, got %q", ca, hg.opts.caFile)
	}

	if hg.opts.insecureSkipVerifyTLS != insecure {
		t.Errorf("Expected NewHTTPGetter to contain %t as InsecureSkipVerifyTLs flag, got %t", false, hg.opts.insecureSkipVerifyTLS)
	}

	if hg.opts.timeout != timeout {
		t.Errorf("Expected NewHTTPGetter to contain %s as Timeout flag, got %s", timeout, hg.opts.timeout)
	}

	// Test if setting insecureSkipVerifyTLS is being passed to the ops
	insecure = true

	g, err = NewHTTPGetter(
		WithInsecureSkipVerifyTLS(insecure),
	)
	if err != nil {
		t.Fatal(err)
	}

	hg, ok = g.(*HTTPGetter)
	if !ok {
		t.Fatal("expected NewHTTPGetter to produce an *HTTPGetter")
	}

	if hg.opts.insecureSkipVerifyTLS != insecure {
		t.Errorf("Expected NewHTTPGetter to contain %t as InsecureSkipVerifyTLs flag, got %t", insecure, hg.opts.insecureSkipVerifyTLS)
	}
}

func TestDownload(t *testing.T) {
	expect := "Call me Ishmael"
	expectedUserAgent := "I am Groot"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defaultUserAgent := "Helm/" + strings.TrimPrefix(version.GetVersion(), "v")
		if r.UserAgent() != defaultUserAgent {
			t.Errorf("Expected '%s', got '%s'", defaultUserAgent, r.UserAgent())
		}
		fmt.Fprint(w, expect)
	}))
	defer srv.Close()

	g, err := All(cli.New()).ByScheme("http")
	if err != nil {
		t.Fatal(err)
	}
	got, err := g.Get(srv.URL, WithURL(srv.URL))
	if err != nil {
		t.Fatal(err)
	}

	if got.String() != expect {
		t.Errorf("Expected %q, got %q", expect, got.String())
	}

	// test with http server
	basicAuthSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		username, password, ok := r.BasicAuth()
		if !ok || username != "username" || password != "password" {
			t.Errorf("Expected request to use basic auth and for username == 'username' and password == 'password', got '%v', '%s', '%s'", ok, username, password)
		}
		if r.UserAgent() != expectedUserAgent {
			t.Errorf("Expected '%s', got '%s'", expectedUserAgent, r.UserAgent())
		}
		fmt.Fprint(w, expect)
	}))

	defer basicAuthSrv.Close()

	u, _ := url.ParseRequestURI(basicAuthSrv.URL)
	httpgetter, err := NewHTTPGetter(
		WithURL(u.String()),
		WithBasicAuth("username", "password"),
		WithUserAgent(expectedUserAgent),
	)
	if err != nil {
		t.Fatal(err)
	}
	got, err = httpgetter.Get(u.String())
	if err != nil {
		t.Fatal(err)
	}

	if got.String() != expect {
		t.Errorf("Expected %q, got %q", expect, got.String())
	}
}

func TestDownloadTLS(t *testing.T) {
	cd := "../../testdata"
	ca, pub, priv := filepath.Join(cd, "rootca.crt"), filepath.Join(cd, "crt.pem"), filepath.Join(cd, "key.pem")

	tlsSrv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	tlsConf, err := tlsutil.NewClientTLS(pub, priv, ca)
	if err != nil {
		t.Fatal(errors.Wrap(err, "can't create TLS config for client"))
	}
	tlsConf.BuildNameToCertificate()
	tlsConf.ServerName = "helm.sh"
	tlsSrv.TLS = tlsConf
	tlsSrv.StartTLS()
	defer tlsSrv.Close()

	u, _ := url.ParseRequestURI(tlsSrv.URL)
	g, err := NewHTTPGetter(
		WithURL(u.String()),
		WithTLSClientConfig(pub, priv, ca),
	)
	if err != nil {
		t.Fatal(err)
	}

	if _, err := g.Get(u.String()); err != nil {
		t.Error(err)
	}

	// now test with TLS config being passed along in .Get (see #6635)
	g, err = NewHTTPGetter()
	if err != nil {
		t.Fatal(err)
	}

	if _, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig(pub, priv, ca)); err != nil {
		t.Error(err)
	}

	// test with only the CA file (see also #6635)
	g, err = NewHTTPGetter()
	if err != nil {
		t.Fatal(err)
	}

	if _, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig("", "", ca)); err != nil {
		t.Error(err)
	}
}

func TestDownloadInsecureSkipTLSVerify(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer ts.Close()

	u, _ := url.ParseRequestURI(ts.URL)

	// Ensure the default behaviour did not change
	g, err := NewHTTPGetter(
		WithURL(u.String()),
	)
	if err != nil {
		t.Error(err)
	}

	if _, err := g.Get(u.String()); err == nil {
		t.Errorf("Expected Getter to throw an error, got %s", err)
	}

	// Test certificate check skip
	g, err = NewHTTPGetter(
		WithURL(u.String()),
		WithInsecureSkipVerifyTLS(true),
	)
	if err != nil {
		t.Error(err)
	}
	if _, err = g.Get(u.String()); err != nil {
		t.Error(err)
	}

}

func TestHTTPGetterTarDownload(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f, _ := os.Open("testdata/empty-0.0.1.tgz")
		defer f.Close()

		b := make([]byte, 512)
		f.Read(b)
		//Get the file size
		FileStat, _ := f.Stat()
		FileSize := strconv.FormatInt(FileStat.Size(), 10)

		//Simulating improper header values from bitbucket
		w.Header().Set("Content-Type", "application/x-tar")
		w.Header().Set("Content-Encoding", "gzip")
		w.Header().Set("Content-Length", FileSize)

		f.Seek(0, 0)
		io.Copy(w, f)
	}))

	defer srv.Close()

	g, err := NewHTTPGetter(WithURL(srv.URL))
	if err != nil {
		t.Fatal(err)
	}

	data, _ := g.Get(srv.URL)
	mimeType := http.DetectContentType(data.Bytes())

	expectedMimeType := "application/x-gzip"
	if mimeType != expectedMimeType {
		t.Fatalf("Expected response with MIME type %s, but got %s", expectedMimeType, mimeType)
	}
}


text:
#ifndef alltoall_H
#define alltoall_H

#include <sumi/collective.h>
#include <sumi/collective_actor.h>
#include <sumi/collective_message.h>
#include <sumi/comm_functions.h>

namespace sumi {

class bruck_alltoall_actor :
  public bruck_actor
{
 public:
  std::string to_string() const override {
    return "bruck all-to-all actor";
  }

 protected:
  void finalize() override;

  void finalize_buffers() override;
  void init_buffers(void *dst, void *src) override;
  void init_dag() override;

  void buffer_action(void *dst_buffer, void *msg_buffer, action* ac) override;

  void start_shuffle(action* ac) override;

  void shuffle(action *ac, void* tmpBuf, void* mainBuf, bool copyToTemp);

  int midpoint_;
};

class bruck_alltoall_collective :
  public dag_collective
{
  FactoryRegister("bruck_alltoall", dag_collective, bruck_alltoall_collective)
 public:
  std::string to_string() const override {
    return "all-to-all";
  }

  dag_collective_actor* new_actor() const override {
    return new bruck_alltoall_actor;
  }

  dag_collective* clone() const override {
    return new bruck_alltoall_collective;
  }

};

}

#endif // ALLGATHER_H


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Automated Warehouse Management System</title>
  <meta name="description" content="">

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>


text:
package io.dropwizard.jersey.errors;

import org.glassfish.jersey.server.internal.LocalizationMessages;
import org.junit.jupiter.api.Test;

import javax.ws.rs.NotSupportedException;
import javax.ws.rs.core.Response;

import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static javax.ws.rs.core.Response.Status.UNSUPPORTED_MEDIA_TYPE;
import static org.assertj.core.api.Assertions.assertThat;

public class IllegalStateExceptionMapperTest {

    private final IllegalStateExceptionMapper mapper = new IllegalStateExceptionMapper();

    @Test
    public void delegatesToParentClass() {
        @SuppressWarnings("serial")
        final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {
        });
        assertThat(reponse.getStatusInfo()).isEqualTo(INTERNAL_SERVER_ERROR);
    }

    @Test
    public void handlesFormParamContentTypeError() {
        final Response reponse = mapper
            .toResponse(new IllegalStateException(LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR()));
        assertThat(reponse.getStatusInfo()).isEqualTo(UNSUPPORTED_MEDIA_TYPE);
        assertThat(reponse.getEntity()).isInstanceOf(ErrorMessage.class);
        assertThat(((ErrorMessage) reponse.getEntity()).getMessage())
            .isEqualTo(new NotSupportedException().getLocalizedMessage());
    }
}


text:
#include "mongo/bson/util/bson_extract.h"

#include "mongo/db/jsobj.h"

namespace mongo {

    Status bsonExtractField(const BSONObj& object,
                            const StringData& fieldName,
                            BSONElement* outElement) {
        BSONElement element = object.getField(fieldName);
        if (element.eoo())
            return Status(ErrorCodes::NoSuchKey, fieldName.toString());
        *outElement = element;
        return Status::OK();
    }

    Status bsonExtractTypedField(const BSONObj& object,
                                 const StringData& fieldName,
                                 BSONType type,
                                 BSONElement* outElement) {
        Status status = bsonExtractField(object, fieldName, outElement);
        if (!status.isOK())
            return status;
        if (type != outElement->type()) {
            return Status(ErrorCodes::TypeMismatch,
                          std::string("Expected ") + typeName(type) +
                          " found " + typeName(outElement->type()));
        }
        return Status::OK();
    }

    Status bsonExtractBooleanFieldWithDefault(const BSONObj& object,
                                              const StringData& fieldName,
                                              bool defaultValue,
                                              bool* out) {
        BSONElement value;
        Status status = bsonExtractField(object, fieldName, &value);
        if (status == ErrorCodes::NoSuchKey) {
            *out = defaultValue;
        }
        else if (!status.isOK()) {
            return status;
        }
        else if (!value.isNumber() && !value.isBoolean()) {
            return Status(ErrorCodes::TypeMismatch, "Expected boolean or number type");
        }
        else {
            *out = value.trueValue();
        }
        return Status::OK();
    }

    Status bsonExtractStringField(const BSONObj& object,
                                  const StringData& fieldName,
                                  std::string* out) {
        BSONElement element;
        Status status = bsonExtractTypedField(object, fieldName, String, &element);
        if (!status.isOK())
            return status;
        *out = element.str();
        return Status::OK();
    }

    Status bsonExtractStringFieldWithDefault(const BSONObj& object,
                                             const StringData& fieldName,
                                             const StringData& defaultValue,
                                             std::string* out) {
        Status status = bsonExtractStringField(object, fieldName, out);
        if (status == ErrorCodes::NoSuchKey) {
            *out = defaultValue.toString();
        }
        else if (!status.isOK()) {
            return status;
        }
        return Status::OK();
    }

}  // namespace mongo


text:
typedef struct sk_dcblocker sk_dcblocker;
#endif

typedef struct {
    sk_dcblocker *dcblocker;
} sp_dcblocker;

int sp_dcblocker_create(sp_dcblocker **p);
int sp_dcblocker_destroy(sp_dcblocker **p);
int sp_dcblocker_init(sp_data *sp, sp_dcblocker *p);
int sp_dcblocker_compute(sp_data *sp, sp_dcblocker *p,
                         SPFLOAT *in, SPFLOAT *out);


text:
```js
// Replaces the pattern using "replace", capitalizing the
// first replaced character the same as it was in the source.
// If pattern is not a RegERxp, it is converted to one.
// If it IS a RegExp, the flags must be "gi" - if not, it won't
// work right. If throwIfFlagsDintMatch is true, an exception is thrown.
// UPDATED: 2016/07/20 04:13 PDT
String.prototype.replaceKeepInitialCase = function(pattern, replace, throwIfFlagsDontMatch) {
	var regexp = pattern.toRegExp("gi", throwIfFlagsDontMatch);
	return this.replace(regexp, function(match) {
		return (match.search(/^[a-z]/) === 0 ?
				replace.charAt(0).toLowerCase() :
				replace.charAt(0).toUpperCase()) +
			replace.substring(1);
	});
}
```

Required:
* [String.prototype.toRegExp](String.prototype.toRegExp.md)
* [RegExp.prototype.isRegExp](RegExp.prototype.isRegExp.md)


text:
id: 5900f4451000cf542c50ff57
title: 'Problema 216: Investigação da primalidade dos números da forma 2n2-1'
challengeType: 5
forumTopicId: 301858
dashedName: problem-216-investigating-the-primality-of-numbers-of-the-form-2n2-1
---

# --description--

Considere os números $t(n)$ da forma $t(n) = 2n^2 - 1$, sendo $n > 1$.

Os primeiros desses números são 7, 17, 31, 49, 71, 97, 127 e 161.

Ocorre que apenas $49 = 7 \times 7$ e $161 = 7 \times 23$ dentre esses não são números primos.

Para $n ≤ 10000$, há 2202 números $t(n)$ que são primos.

Quantos números $t(n)$ são primos para $n ≤ 50.000.000$?

# --hints--

`primalityOfNumbers()` deve retornar `5437849`.

```js
assert.strictEqual(primalityOfNumbers(), 5437849);
```

# --seed--

## --seed-contents--

```js
function primalityOfNumbers() {

  return true;
}

primalityOfNumbers();
```

# --solutions--

```js
// solution required
```


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Tabl. analyt. Fung. France (Paris) 1: 107 (1884)

#### Original name
Coprinus patouillardii Quél.

### Remarks
null