text:
<add>
<doc>
<field name="uid">doi:10.1371/journal.pntd.0000835</field>
<field name="doi">10.1371/journal.pntd.0000835</field>
<field name="data_source">PLoS Open Access XML</field>
<field name="authors">Matthew J. Burton, Martin J. Holland, Pateh Makalo, Esther A. N. Aryee, Ansumana Sillah, Sandra Cohuet, Angels Natividad, Neal D. E. Alexander, David C. W. Mabey, Robin L. Bailey</field>
<field name="title">Profound and Sustained Reduction in Chlamydia trachomatis in The Gambia: A Five-Year Longitudinal Study of Trachoma Endemic Communities</field>
<field name="journal">PLoS Neglected Tropical Diseases</field>
<field name="year">2010</field>
<field name="volume">4</field>
<field name="number">10</field>
<field name="pages">e835</field>
<field name="license">Creative Commons Attribution (CC BY)</field>
<field name="license_url">http://creativecommons.org/licenses/by/3.0/</field>
<field name="fulltext">
Abstract

Background

The elimination of blinding trachoma focuses on controlling Chlamydia
trachomatis infection through mass antibiotic treatment and measures to limit
transmission. As the prevalence of disease declines, uncertainty increases
over the most effective strategy for treatment. There are little long-term
data on the effect of treatment on infection, especially in low prevalence
settings, on which to base guidelines.

Methodology/Principal Findings

The population of a cluster of 14 Gambian villages with endemic trachoma was
examined on seven occasions over five years (baseline, 2, 6, 12, 17, 30 and 60
months). Mass antibiotic treatment was given at baseline only. All families
had accessible clean water all year round. New latrines were installed in each
household after 17 months. Conjunctival swab samples were collected and tested
for C. trachomatis by PCR. Before treatment the village-level prevalence of
follicular trachoma in 1 to 9 year olds (TF%1–9) was 15.4% and C. trachomatis
was 9.7%. Antibiotic treatment coverage was 83% of the population. In 12
villages all baseline infection cleared and few sporadic cases were detected
during the following five years. In the other two villages treatment was
followed by increased infection at two months, which was associated with
extensive contact with other untreated communities. The prevalence of
infection subsequently dropped to 0% in these 2 villages and 0.6% for the
whole population by the end of the study in the absence of any further
antibiotic treatment. However, several villages had a TF%1–9 of >10%, the
threshold for initiating or continuing mass antibiotic treatment, in the
absence of any detectable C. trachomatis.

Conclusions/Significance

A single round of mass antibiotic treatment may be sufficient in low
prevalence settings to control C. trachomatis infection when combined with
environmental conditions, which suppress transmission, such as a good water
supply and sanitation.

Author Summary

Trachoma is the most common infectious cause of blindness worldwide. Mass
antibiotic treatment with azithromycin is used to control ocular Chlamydia
trachomatis infection. There is uncertainty over how frequently and for how
long treatment is needed, particularly in low prevalence settings. This study
examines the effect of a single round of treatment on clinical disease and
infection in a cluster of trachoma endemic Gambian villages over a five-year
period. These villages had good water supplies and sanitation improved part
way through the study. We found treatment was followed by a marked decline in
infection prevalence (by PCR) to less than 1%. The decline in prevalence of
active disease in children was less marked. Several villages had a prevalence
of active trachoma in 1 to 9 year old children of greater than 10% during the
follow-up period, mostly in the absence of detectable infection. The
implication of this study is that a single, high coverage mass treatment may
be sufficient to control C. trachomatis infection in a low prevalence setting,
particularly when combined with environmental measures to limit transmission.
However, relying on clinical signs to g</field></doc>
</add>


text:
var fixtures = require('webtorrent-fixtures')
var http = require('http')
var parseTorrent = require('../')
var test = require('tape')

test('http url to a torrent file, string', function (t) {
  t.plan(3)

  var server = http.createServer(function (req, res) {
    t.pass('server got request')
    res.end(fixtures.leaves.torrent)
  })

  server.listen(0, function () {
    var port = server.address().port
    var url = 'http://127.0.0.1:' + port
    parseTorrent.remote(url, function (err, parsedTorrent) {
      t.error(err)
      t.deepEqual(parsedTorrent, fixtures.leaves.parsedTorrent)
      server.close()
    })
  })
})

test('filesystem path to a torrent file, string', function (t) {
  t.plan(2)

  parseTorrent.remote(fixtures.leaves.torrentPath, function (err, parsedTorrent) {
    t.error(err)
    t.deepEqual(parsedTorrent, fixtures.leaves.parsedTorrent)
  })
})

redpajama_set_name: RedPajamaGithub


text:
import json

from oslo_log import log as logging

from congress.api import error_codes
from congress.api import webservice
from congress.dse import deepsix
from congress import exception
from congress.managers import datasource as datasource_manager

LOG = logging.getLogger(__name__)

def d6service(name, keys, inbox, datapath, args):
    return DatasourceModel(name, keys, inbox=inbox, dataPath=datapath, **args)

class DatasourceModel(deepsix.deepSix):
    """Model for handling API requests about Datasources."""
    def __init__(self, name, keys, inbox=None, dataPath=None,
                 policy_engine=None):
        super(DatasourceModel, self).__init__(name, keys, inbox=inbox,
                                              dataPath=dataPath)
        self.engine = policy_engine
        self.datasource_mgr = datasource_manager.DataSourceManager()

    def get_items(self, params, context=None):
        """Get items in model.

        Args:
            params: A dict-like object containing parameters
                    from the request query string and body.
            context: Key-values providing frame of reference of request

        Returns: A dict containing at least a 'results' key whose value is
                 a list of items in the model.  Additional keys set in the
                 dict will also be rendered for the user.
        """
        datasources = self.datasource_mgr.get_datasources(filter_secret=True)
        results = [self.datasource_mgr.make_datasource_dict(datasource)
                   for datasource in datasources]

        return {"results": results}

    def add_item(self, item, params, id_=None, context=None):
        """Add item to model.

         Args:
             item: The item to add to the model
             id_: The ID of the item, or None if an ID should be generated
             context: Key-values providing frame of reference of request

         Returns:
              Tuple of (ID, newly_created_item)

         Raises:
             KeyError: ID already exists.
         """
        try:
            obj = self.datasource_mgr.add_datasource(
                item=item)
        except (datasource_manager.BadConfig,
                datasource_manager.DatasourceNameInUse,
                datasource_manager.DriverNotFound) as e:
            LOG.info(_("Datasource Error: %s") % e.message)
            raise webservice.DataModelException(e.code, e.message,
                                                http_status_code=e.code)

        return (obj['id'], obj)

    def delete_item(self, id_, params, context=None):
        datasource = context.get('ds_id')
        try:
            self.datasource_mgr.delete_datasource(datasource)
        except (datasource_manager.DatasourceNotFound,
                exception.DanglingReference) as e:
            raise webservice.DataModelException(e.code, e.message)

    def request_refresh_action(self, params, context=None, request=None):
        ds_id = context.get('ds_id')
        try:
            self.datasource_mgr.request_refresh(ds_id)
        except (datasource_manager.DatasourceNotFound) as e:
            raise webservice.DataModelException(e.code, e.message)

    def execute_action(self, params, context=None, request=None):
        "Execute the action."
        service = context.get('ds_id')
        body = json.loads(request.body)
        action = body.get('name')
        action_args = body.get('args', {})
        if (not isinstance(action_args, dict)):
            (num, desc) = error_codes.get('execute_action_args_syntax')
            raise webservice.DataModelException(num, desc)

        try:
            self.engine.execute_action(service, action, action_args)
        except exception.PolicyException as e:
            (num, desc) = error_codes.get('execute_error')
            raise webservice.DataModelException(num, desc + "::" + str(e))

        return {}


text:
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Windows.Forms.Design

''' <summary>
''' Editor control for alignment property
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class AlignmentEditorControl

    Private _alignment As AlignmentOption
    Public Property Alignment As AlignmentOption
        Get
            Return _alignment
        End Get
        Set(value As AlignmentOption)
            _alignment = value
            Select Case value
                Case AlignmentOption.TopLeft
                    TopLeft.Checked = True
                Case AlignmentOption.TopCenter
                    TopCenter.Checked = True
                Case AlignmentOption.TopRight
                    TopRight.Checked = True
                Case AlignmentOption.MiddleLeft
                    MiddleLeft.Checked = True
                Case AlignmentOption.MiddleCenter
                    MiddleCenter.Checked = True
                Case AlignmentOption.MiddleRight
                    MiddleRight.Checked = True
                Case AlignmentOption.BottomLeft
                    BottomLeft.Checked = True
                Case AlignmentOption.BottomCenter
                    BottomCenter.Checked = True
                Case AlignmentOption.BottomRight
                    BottomRight.Checked = True
            End Select
        End Set
    End Property

    Private editorService As IWindowsFormsEditorService

    Public Sub New()
        MyBase.New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.Alignment = AlignmentOption.TopLeft

    End Sub

    Public Sub New(alignment As AlignmentOption, service As IWindowsFormsEditorService)
        MyBase.New()

        Me.InitializeComponent()

        Me.editorService = service
        Me.Alignment = alignment

        AddHandler TopLeft.CheckedChanged, AddressOf CheckedChanged
        AddHandler TopCenter.CheckedChanged, AddressOf CheckedChanged
        AddHandler TopRight.CheckedChanged, AddressOf CheckedChanged
        AddHandler MiddleLeft.CheckedChanged, AddressOf CheckedChanged
        AddHandler MiddleCenter.CheckedChanged, AddressOf CheckedChanged
        AddHandler MiddleRight.CheckedChanged, AddressOf CheckedChanged
        AddHandler BottomLeft.CheckedChanged, AddressOf CheckedChanged
        AddHandler BottomCenter.CheckedChanged, AddressOf CheckedChanged
        AddHandler BottomRight.CheckedChanged, AddressOf CheckedChanged

    End Sub

    Private Sub CheckedChanged(sender As Object, e As EventArgs)
        Me._alignment =
            CType([Enum].Parse(GetType(AlignmentOption),
                               CType(sender, RadioButton).Name),
                  AlignmentOption)
        editorService.CloseDropDown()

    End Sub

End Class


text:
package org.kohsuke.stapler.jelly.groovy;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import org.apache.commons.jelly.XMLOutput;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.MetaClassLoader;

import java.io.IOException;
import java.net.URL;

/**
 * @author Kohsuke Kawaguchi
 */
@SuppressFBWarnings(value = "GROOVY_SHELL", justification = "from trusted sources")
public class GroovyClassLoaderTearOff {
    private final MetaClassLoader owner;

    private final GroovyClassLoader gcl;

    private final SimpleTemplateParser parser = new SimpleTemplateParser() {
        /**
         * Sends the output via {@link XMLOutput#write(String)}
         */
        @Override
        protected String printCommand() {
            return "output.write";
        }
    };

    public GroovyClassLoaderTearOff(MetaClassLoader owner) {
        this.owner = owner;
        gcl = createGroovyClassLoader();
    }

    private GroovyClassLoader createGroovyClassLoader() {
        CompilerConfiguration cc = new CompilerConfiguration();
        // use GroovyClosureScript class as the base class of the compiled script,
        // so that we can set a delegate.
        cc.setScriptBaseClass(StaplerClosureScript.class.getName());

        // enable re-compilation support
        cc.setRecompileGroovySource(MetaClass.NO_CACHE);
        return new GroovyClassLoader(owner.loader,cc) {
            /**
             * Groovy calls this method to locate .groovy script files,
             * so during the development it's important to check the
             * resource path before target/classes.
             */
            @Override
            public URL getResource(String name) {
                // allow the resource path to take precedence when loading script
                if(MetaClassLoader.debugLoader!=null) {
                    URL res = MetaClassLoader.debugLoader.loader.getResource(name);
                    if(res!=null)
                        return res;
                }
                return super.getResource(name);
            }
        };
    }

    public GroovierJellyScript parse(URL script) throws IOException {
        // we do the caching on our own, so don't let GroovyClassLoader cache this. Or else
        // dynamic reloading won't work
        GroovyCodeSource gcs = new GroovyCodeSource(script);
        gcs.setCachable(false);

        return new GroovierJellyScript(gcl.parseClass(gcs),script);
    }

    public GroovierJellyScript parseGSP(URL res) throws IOException, ClassNotFoundException {
        GroovyCodeSource gcs = new GroovyCodeSource(parser.parse(res), res.toExternalForm(), res.toExternalForm());
        gcs.setCachable(false);

        return new GroovierJellyScript(gcl.parseClass(gcs),res);
    }
}


text:
"""SVG definitions designed for easy SVG composing

Features:
    * allow for wildcard import
    * defines a mini language for SVG composing
    * short but readable names
    * easy nesting
    * method chaining
    * no boilerplate code (reading files, extracting objects from svg,
                           transversing XML tree)
    * universal methods applicable to all element types
    * don't have to learn python
"""

import os

from svgutils import transform as _transform
from svgutils.common import Unit

CONFIG = {
    "svg.file_path": ".",
    "figure.save_path": ".",
    "image.file_path": ".",
    "text.position": (0, 0),
    "text.size": 8,
    "text.weight": "normal",
    "text.font": "Verdana",
}

class Element(_transform.FigureElement):
    """Base class for new SVG elements."""

    def rotate(self, angle, x=0, y=0):
        """Rotate element by given angle around given pivot.

        Parameters
        ----------
        angle : float
            rotation angle in degrees
        x, y : float
            pivot coordinates in user coordinate system (defaults to top-left
            corner of the figure)
        """
        super(Element, self).rotate(angle, x, y)
        return self

    def move(self, x, y):
        """Move the element by x, y.

        Parameters
        ----------
        x,y : int, str
           amount of horizontal and vertical shift

        Notes
        -----
        The x, y can be given with a unit (for example, "3px",  "5cm"). If no
        unit is given the user unit is assumed ("px"). In SVG all units are
        defined in relation to the user unit [1]_.

        .. [1] W3C SVG specification:
           https://www.w3.org/TR/SVG/coords.html#Units
        """
        self.moveto(x, y)
        return self

    def find_id(self, element_id):
        """Find a single element with the given ID.

        Parameters
        ----------
        element_id : str
            ID of the element to find

        Returns
        -------
        found element
        """
        element = _transform.FigureElement.find_id(self, element_id)
        return Element(element.root)

    def find_ids(self, element_ids):
        """Find elements with given IDs.

        Parameters
        ----------
        element_ids : list of strings
            list of IDs to find

        Returns
        -------
        a new `Panel` object which contains all the found elements.
        """
        elements = [_transform.FigureElement.find_id(self, eid) for eid in element_ids]
        return Panel(*elements)

class SVG(Element):
    """SVG from file.

    Parameters
    ----------
    fname : str
       full path to the file
    fix_mpl : bool
        replace pt units with px units to fix files created with matplotlib
    """

    def __init__(self, fname=None, fix_mpl=False):
        if fname:
            fname = os.path.join(CONFIG["svg.file_path"], fname)
            svg = _transform.fromfile(fname)
            if fix_mpl:
                w, h = svg.get_size()
                svg.set_size((w.replace("pt", ""), h.replace("pt", "")))
            super(SVG, self).__init__(svg.getroot().root)

            # if height/width is in % units, we can't store the absolute values
            if svg.width.endswith("%"):
                self._width = None
            else:
                self._width = Unit(svg.width).to("px")
            if svg.height.endswith("%"):
                self._height = None
            else:
                self._height = Unit(svg.height).to("px")

    @property
    def width(self):
        """Get width of the svg file in px"""
        if self._width:
            return self._width.value

    @property
    def height(self):
        """Get height of the svg file in px"""
        if self._height:
            return self._height.value

class MplFigure(SVG):
    """Matplotlib figure

    Parameters
    ----------
    fig : matplotlib Figure instance
        instance of Figure to be converted
    kws :
        keyword arguments passed to matplotlib's savefig method
    """

    def __init__(self, fig, **kws):
        svg = _transform.from_mpl(fig, savefig_kw=kws)
        self.root = svg.getroot().root

class Image(Element):
    """Raster or vector image

    Parameters
    ----------
    width : float
    height : float
        image dimensions
    fname : str
        full path to the file
    """

    def __init__(self, width, height, fname):
        fname = os.path.join(CONFIG["image.file_path"], fname)
        _, fmt = os.path.splitext(fname)
        fmt = fmt.lower()[1:]
        with open(fname, "rb") as fid:
            img = _transform.ImageElement(fid, width, height, fmt)
        self.root = img.root

class Text(Element):
    """Text element.

    Parameters
    ----------
    text : str
       content
    x, y : float or str
       Text position. If unit is not given it will assume user units (px).
    size : float, optional
       Font size.
    weight : str, optional
       Font weight. It can be one of: normal, bold, bolder or lighter.
    font : str, optional
       Font family.
    """

    def __init__(self, text, x=None, y=None, **kwargs):
        params = {
            "size": CONFIG["text.size"],
            "weight": CONFIG["text.weight"],
            "font": CONFIG["text.font"],
        }
        if x is None or y is None:
            x, y = CONFIG["text.position"]
        params.update(kwargs)
        element = _transform.TextElement(x, y, text, **params)
        Element.__init__(self, element.root)

class Panel(Element):
    """Figure panel.

    Panel is a group of elements that can be transformed together. Usually
    it relates to a labeled figure panel.

    Parameters
    ----------
    svgelements : objects deriving from Element class
        one or more elements that compose the panel

    Notes
    -----
    The grouped elements need to be properly arranged in scale and position.
    """

    def __init__(self, *svgelements):
        element = _transform.GroupElement(svgelements)
        Element.__init__(self, element.root)

    def __iter__(self):
        elements = self.root.getchildren()
        return (Element(el) for el in elements)

class Line(Element):
    """Line element connecting given points.

    Parameters
    ----------
    points : sequence of tuples
        List of point x,y coordinates.
    width : float, optional
        Line width.
    color : str, optional
        Line color. Any of the HTML/CSS color definitions are allowed.
    """

    def __init__(self, points, width=1, color="black"):
        element = _transform.LineElement(points, width=width, color=color)
        Element.__init__(self, element.root)

class Grid(Element):
    """Line grid with coordinate labels to facilitate placement of new
    elements.

    Parameters
    ----------
    dx : float
       Spacing between the vertical lines.
    dy : float
       Spacing between horizontal lines.
    size : float or str
       Font size of the labels.

    Notes
    -----
    This element is mainly useful for manual placement of the elements.
    """

    def __init__(self, dx, dy, size=8):
        self.size = size
        lines = self._gen_grid(dx, dy)
        element = _transform.GroupElement(lines)
        Element.__init__(self, element.root)

    def _gen_grid(self, dx, dy, width=0.5):
        xmax, ymax = 1000, 1000
        x, y = 0, 0
        lines = []
        txt = []
        while x < xmax:
            lines.append(_transform.LineElement([(x, 0), (x, ymax)], width=width))
            txt.append(_transform.TextElement(x, dy / 2, str(x), size=self.size))
            x += dx
        while y < ymax:
            lines.append(_transform.LineElement([(0, y), (xmax, y)], width=width))
            txt.append(_transform.TextElement(0, y, str(y), size=self.size))
            y += dy
        return lines + txt

class Figure(Panel):
    """Main figure class.

    This should be always the top class of all the generated SVG figures.

    Parameters
    ----------
    width, height : float or str
        Figure size. If unit is not given, user units (px) are assumed.
    """

    def __init__(self, width, height, *svgelements):
        Panel.__init__(self, *svgelements)
        self.width = Unit(width)
        self.height = Unit(height)

    def save(self, fname):
        """Save figure to SVG file.

        Parameters
        ----------
        fname : str
            Full path to file.
        """
        element = _transform.SVGFigure(self.width, self.height)
        element.append(self)
        element.save(os.path.join(CONFIG["figure.save_path"], fname))

    def tostr(self):
        """Export SVG as a string"""
        element = _transform.SVGFigure(self.width, self.height)
        element.append(self)
        svgstr = element.to_str()
        return svgstr

    def _repr_svg_(self):
        return self.tostr().decode("ascii")

    def tile(self, ncols, nrows):
        """Automatically tile the panels of the figure.

        This will re-arranged all elements of the figure (first in the
        hierarchy) so that they will uniformly cover the figure area.

        Parameters
        ----------
        ncols, nrows : type
            The number of columns and rows to arrange the elements into.

        Notes
        -----
        ncols * nrows must be larger or equal to number of
        elements, otherwise some elements will go outside the figure borders.
        """
        dx = (self.width / ncols).to("px").value
        dy = (self.height / nrows).to("px").value
        ix, iy = 0, 0
        for el in self:
            el.move(dx * ix, dy * iy)
            ix += 1
            if ix >= ncols:
                ix = 0
                iy += 1
            if iy > nrows:
                break
        return self


text:
package com.espirit.moddev.cli.api.parsing.parser;

import com.espirit.moddev.cli.api.parsing.exceptions.UnknownRootNodeException;
import com.espirit.moddev.cli.api.parsing.identifier.RootNodeIdentifier;
import de.espirit.firstspirit.access.store.IDProvider;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isA;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class RootNodeIdentifierParserTest {

    private RootNodeIdentifierParser testling;

    @BeforeEach
    public void setUp() {
        testling = new RootNodeIdentifierParser();
    }

    @ParameterizedTest
    @ValueSource(strings = {"root:myuid", "ROOT:myuid", "ROOT :myuid", "ROOT : myuid", "contentstore", "globalstore", "templatestore", "pagestore", "sitestore"})
    public void testAppliesTo(@NotNull final String uid) {
        boolean appliesTo = testling.appliesTo(uid);
        assertTrue(appliesTo, "Parser should apply to string " + uid);
    }

    @Test
    public void testParseWithNonExistingStore() {
        assertThrows(UnknownRootNodeException.class, () -> testling.parse(List.of("root:xyz")));
    }

    @Test
    public void testParseWithTemplateStoreRoot() {
        testling.parse(Arrays.asList("root:templatestore"));
    }

    @Test
    public void testParseStoreRootRequestWithExistingStore() {
        final List<RootNodeIdentifier> list = testling.parse(Arrays.asList("root:templatestore"));
        assertThat(list.contains(new RootNodeIdentifier(IDProvider.UidType.TEMPLATESTORE)), equalTo(true));
    }

    @ParameterizedTest
    @ValueSource(strings = {"ROOT : contentstore", "contentstore", "globalstore", "templatestore", "pagestore", "sitestore"})
    public void testParseNakedStoreRoot(@NotNull final String uid) {
        final List<RootNodeIdentifier> list = testling.parse(Collections.singletonList(uid));
        assertThat(list.size(), equalTo(1));
        assertThat(list.get(0), isA(RootNodeIdentifier.class));
    }
}


text:
extern crate discord;

use discord::{Discord, ChannelRef, State};
use discord::voice::AudioReceiver;
use discord::model::{Event, UserId, ChannelType};
use std::env;

struct VoiceTest;

impl AudioReceiver for VoiceTest {
	fn speaking_update(&mut self, ssrc: u32, user_id: UserId, speaking: bool) {
		println!("[{}] is {:?} -> {}", ssrc, user_id, speaking);
	}

	fn voice_packet(&mut self, ssrc: u32, sequence: u16, timestamp: u32, stereo: bool, _data: &[i16]) {
		println!("[{}] ({}, {}) stereo = {}", ssrc, sequence, timestamp, stereo);
	}
}

pub fn main() {
	// Log in to Discord using a bot token from the environment
	let discord = Discord::from_bot_token(
		&env::var("DISCORD_TOKEN").expect("Expected token"),
	).expect("login failed");
	let prefix: &str = "!";

	// Establish and use a websocket connection
	let (mut connection, ready) = discord.connect().expect("connect failed");
	let mut state = State::new(ready);
	let channel_count: usize = state.servers().iter()
		.map(|srv| srv.channels.iter()
			.filter(|chan| chan.kind == ChannelType::Text)
			.count()
		).fold(0, |v, s| v + s);
	println!("[Ready] {} logging {} servers with {} text channels", state.user().username, state.servers().len(), channel_count);

	loop {
		match connection.recv_event() {
			Ok(Event::MessageCreate(message)) => {
				println!("{} says: {}", message.author.name, message.content);
				if message.content == "!test" {
					let _ = discord.send_message(message.channel_id, "This is a reply to the test.", "", false);
				} else if message.content == prefix.to_owned() + "quit" {
					    println!("Quitting.");
					    break
                }
                if message.content == prefix.to_owned() + "help" {
                    let _ = discord.send_message(message.channel_id, "I can't help you. I'm just a bot.", "", false);
                }
                if message.content == prefix.to_owned() + "about" {
                    let _ = discord.send_message(message.channel_id, "I have no clue. All I know is that I was written by Arroz in a language called Rust, and my code is still being developed.", "", false);
                }
                if message.content == prefix.to_owned() + "uber" {
                    let _ = discord.send_message(message.channel_id, "Fuck off m8.", "", false);
                }
                if message.content == prefix.to_owned() + "ask" {
                    let _ = discord.send_message(message.channel_id, "Not just yet, I'll have the answers soon.", "", false);
                }
				if message.content == prefix.to_owned() + "givemeyourcode" {
					let _ = discord.send_message(message.channel_id, "Okay, here you go. https://github.com/aarroz/rice_bot2", "", false);
				}

			}

			Ok(_) => {}
			Err(discord::Error::Closed(code, body)) => {
				println!("Gateway closed on us with code {:?}: {}", code, body);
				break
			}
			Err(err) => println!("Receive error: {:?}", err)
		}
	}
}


text:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from duration.djinni

#pragma once

#include "../../handwritten-src/cpp/optional.hpp"
#include <chrono>
#include <cstdint>
#include <string>

namespace testsuite {

class TestDuration {
public:
    virtual ~TestDuration() {}

    /**
     * Defines the name of the JNI C++ proxy class. Used to convert a
     * C++ implemented object to a Java object when the type of the object being
     * converted is unknown to the JniInterface (see djinni_support.hpp).
     *
     * The proxy class name is only used for converting Djinni interfaces that
     * are implemented in C++. Java implemented interfaces are converted differently.
     * However, the C++ class of an interface implemented in Java must still have a
     * jniProxyClassName method in order for Djinni's JniInterface::fromCpp method to compile.
     *
     * @return The name of the class's associated JNI proxy class.
     *
     * @see JniInterface in djinni_support.hpp
     */
    virtual const std::string jniProxyClassName() { return "com/dropbox/djinni/test/TestDuration$CppProxy"; }

    /**
     * Defines the name of the Objective-C type for the class. Used to convert a
     * C++ object to an Objective-C object when the type of the object being
     * converted is unknown to the C++ wrapper cache (see DJICppWrapperCache+Private.hpp).
     *
     * @return The name of the Objective C type associated with the class.
     *
     * @see get_cpp_proxy function in DJICppWrapperCache+Private.hpp
     */
    virtual const std::string objcProxyClassName() { return "DBTestDuration"; }

    static std::string hoursString(std::chrono::duration<int32_t, std::ratio<3600>> dt);

    static std::string minutesString(std::chrono::duration<int32_t, std::ratio<60>> dt);

    static std::string secondsString(std::chrono::duration<int32_t, std::ratio<1>> dt);

    static std::string millisString(std::chrono::duration<int32_t, std::milli> dt);

    static std::string microsString(std::chrono::duration<int32_t, std::micro> dt);

    static std::string nanosString(std::chrono::duration<int32_t, std::nano> dt);

    static std::chrono::duration<int32_t, std::ratio<3600>> hours(int32_t count);

    static std::chrono::duration<int32_t, std::ratio<60>> minutes(int32_t count);

    static std::chrono::duration<int32_t, std::ratio<1>> seconds(int32_t count);

    static std::chrono::duration<int32_t, std::milli> millis(int32_t count);

    static std::chrono::duration<int32_t, std::micro> micros(int32_t count);

    static std::chrono::duration<int32_t, std::nano> nanos(int32_t count);

    static std::chrono::duration<double, std::ratio<3600>> hoursf(double count);

    static std::chrono::duration<double, std::ratio<60>> minutesf(double count);

    static std::chrono::duration<double, std::ratio<1>> secondsf(double count);

    static std::chrono::duration<double, std::milli> millisf(double count);

    static std::chrono::duration<double, std::micro> microsf(double count);

    static std::chrono::duration<double, std::nano> nanosf(double count);

    static std::experimental::optional<std::chrono::duration<int64_t, std::ratio<1>>> box(int64_t count);

    static int64_t unbox(std::experimental::optional<std::chrono::duration<int64_t, std::ratio<1>>> dt);
};

}  // namespace testsuite


text:
//Generated by the Argon Build System

#ifndef GIM_RADIXSORT_H_INCLUDED
#define GIM_RADIXSORT_H_INCLUDED
/*! \file gim_radixsort.h
\author Francisco Leon Najera.
Based on the work of Michael Herf : "fast floating-point radix sort"
Avaliable on http://www.stereopsis.com/radix.html
*/
/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com

 This library is free software; you can redistribute it and/or
 modify it under the terms of EITHER:
   (1) The GNU Lesser General Public License as published by the Free
       Software Foundation; either version 2.1 of the License, or (at
       your option) any later version. The text of the GNU Lesser
       General Public License is included with this library in the
       file GIMPACT-LICENSE-LGPL.TXT.
   (2) The BSD-style license that is included with this library in
       the file GIMPACT-LICENSE-BSD.TXT.
   (3) The zlib/libpng license that is included with this library in
       the file GIMPACT-LICENSE-ZLIB.TXT.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
 GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details.

-----------------------------------------------------------------------------
*/

#include "gim_memory.h"

///Macros for sorting.
//! Prototype for comparators
class less_comparator
{
	public:

	template<class T,class Z>
	inline int operator() ( const T& a, const Z& b )
	{
		return ( a<b?-1:(a>b?1:0));
	}
};

//! Prototype for comparators
class integer_comparator
{
	public:

	template<class T>
	inline int operator() ( const T& a, const T& b )
	{
		return (int)(a-b);
	}
};

//!Prototype for getting the integer representation of an object
class uint_key_func
{
public:
	template<class T>
	inline GUINT operator()( const T& a)
	{
		return (GUINT)a;
	}
};

//!Prototype for copying elements
class copy_elements_func
{
public:
	template<class T>
	inline void operator()(T& a,T& b)
	{
		a = b;
	}
};

//!Prototype for copying elements
class memcopy_elements_func
{
public:
	template<class T>
	inline void operator()(T& a,T& b)
	{
		gim_simd_memcpy(&a,&b,sizeof(T));
	}
};

//! @{
struct GIM_RSORT_TOKEN
{
    GUINT m_key;
    GUINT m_value;
    GIM_RSORT_TOKEN()
    {
    }
    GIM_RSORT_TOKEN(const GIM_RSORT_TOKEN& rtoken)
    {
    	m_key = rtoken.m_key;
    	m_value = rtoken.m_value;
    }

    inline bool operator <(const GIM_RSORT_TOKEN& other) const
	{
		return (m_key < other.m_key);
	}

	inline bool operator >(const GIM_RSORT_TOKEN& other) const
	{
		return (m_key > other.m_key);
	}
};

//! Prototype for comparators
class GIM_RSORT_TOKEN_COMPARATOR
{
	public:

	inline int operator()( const GIM_RSORT_TOKEN& a, const GIM_RSORT_TOKEN& b )
	{
		return (int)((a.m_key) - (b.m_key));
	}
};

#define kHist 2048
// ---- utils for accessing 11-bit quantities
#define D11_0(x)	(x & 0x7FF)
#define D11_1(x)	(x >> 11 & 0x7FF)
#define D11_2(x)	(x >> 22 )

///Radix sort for unsigned integer keys
inline void gim_radix_sort_rtokens(
				GIM_RSORT_TOKEN * array,
				GIM_RSORT_TOKEN * sorted, GUINT element_count)
{
	GUINT i;
	GUINT b0[kHist * 3];
	GUINT *b1 = b0 + kHist;
	GUINT *b2 = b1 + kHist;
	for (i = 0; i < kHist * 3; ++i)
	{
		b0[i] = 0;
	}
	GUINT fi;
	GUINT pos;
	for (i = 0; i < element_count; ++i)
	{
	    fi = array[i].m_key;
		b0[D11_0(fi)] ++;
		b1[D11_1(fi)] ++;
		b2[D11_2(fi)] ++;
	}
	{
		GUINT sum0 = 0, sum1 = 0, sum2 = 0;
		GUINT tsum;
		for (i = 0; i < kHist; ++i)
		{
			tsum = b0[i] + sum0;
			b0[i] = sum0 - 1;
			sum0 = tsum;
			tsum = b1[i] + sum1;
			b1[i] = sum1 - 1;
			sum1 = tsum;
			tsum = b2[i] + sum2;
			b2[i] = sum2 - 1;
			sum2 = tsum;
		}
	}
	for (i = 0; i < element_count; ++i)
	{
        fi = array[i].m_key;
		pos = D11_0(fi);
		pos = ++b0[pos];
		sorted[pos].m_key = array[i].m_key;
		sorted[pos].m_value = array[i].m_value;
	}
	for (i = 0; i < element_count; ++i)
	{
        fi = sorted[i].m_key;
		pos = D11_1(fi);
		pos = ++b1[pos];
		array[pos].m_key = sorted[i].m_key;
		array[pos].m_value = sorted[i].m_value;
	}
	for (i = 0; i < element_count; ++i)
	{
        fi = array[i].m_key;
		pos = D11_2(fi);
		pos = ++b2[pos];
		sorted[pos].m_key = array[i].m_key;
		sorted[pos].m_value = array[i].m_value;
	}
}

/// Get the sorted tokens from an array. For generic use. Tokens are IRR_RSORT_TOKEN
/*!
*\param array Array of elements to sort
*\param sorted_tokens Tokens of sorted elements
*\param element_count element count
*\param uintkey_macro Functor which retrieves the integer representation of an array element
*/
template<typename T, class GETKEY_CLASS>
void gim_radix_sort_array_tokens(
			T* array ,
			GIM_RSORT_TOKEN * sorted_tokens,
			GUINT element_count,GETKEY_CLASS uintkey_macro)
{
	GIM_RSORT_TOKEN * _unsorted = (GIM_RSORT_TOKEN *) gim_alloc(sizeof(GIM_RSORT_TOKEN)*element_count);
    for (GUINT _i=0;_i<element_count;++_i)
    {
        _unsorted[_i].m_key = uintkey_macro(array[_i]);
        _unsorted[_i].m_value = _i;
    }
    gim_radix_sort_rtokens(_unsorted,sorted_tokens,element_count);
    gim_free(_unsorted);
    gim_free(_unsorted);
}

/// Sorts array in place. For generic use
/*!
\param type Type of the array
\param array
\param element_count
\param get_uintkey_macro Macro for extract the Integer value of the element. Similar to SIMPLE_GET_UINTKEY
\param copy_elements_macro Macro for copy elements, similar to SIMPLE_COPY_ELEMENTS
*/
template<typename T, class GETKEY_CLASS, class COPY_CLASS>
void gim_radix_sort(
	T * array, GUINT element_count,
	GETKEY_CLASS get_uintkey_macro, COPY_CLASS copy_elements_macro)
{
	GIM_RSORT_TOKEN * _sorted = (GIM_RSORT_TOKEN  *) gim_alloc(sizeof(GIM_RSORT_TOKEN)*element_count);
    gim_radix_sort_array_tokens(array,_sorted,element_count,get_uintkey_macro);
    T * _original_array = (T *) gim_alloc(sizeof(T)*element_count);
    gim_simd_memcpy(_original_array,array,sizeof(T)*element_count);
    for (GUINT _i=0;_i<element_count;++_i)
    {
        copy_elements_macro(array[_i],_original_array[_sorted[_i].m_value]);
    }
    gim_free(_original_array);
    gim_free(_sorted);
}

//! Failsafe Iterative binary search,
/*!
If the element is not found, it returns the nearest upper element position, may be the further position after the last element.
\param _array
\param _start_i the beginning of the array
\param _end_i the ending  index of the array
\param _search_key Value to find
\param _comp_macro macro for comparing elements
\param _found If true the value has found. Boolean
\param _result_index the index of the found element, or if not found then it will get the index of the  closest bigger value
*/
template<class T, typename KEYCLASS, typename COMP_CLASS>
bool  gim_binary_search_ex(
		const T* _array, GUINT _start_i,
		GUINT _end_i,GUINT & _result_index,
		const KEYCLASS & _search_key,
		COMP_CLASS _comp_macro)
{
	GUINT _k;
	int _comp_result;
	GUINT _i = _start_i;
	GUINT _j = _end_i+1;
	while (_i < _j)
	{
		_k = (_j+_i-1)/2;
		_comp_result = _comp_macro(_array[_k], _search_key);
		if (_comp_result == 0)
		{
			_result_index = _k;
			return true;
		}
		else if (_comp_result < 0)
		{
			_i = _k+1;
		}
		else
		{
			_j = _k;
		}
	}
	_result_index = _i;
	return false;
}

//! Failsafe Iterative binary search,Template version
/*!
If the element is not found, it returns the nearest upper element position, may be the further position after the last element.
\param _array
\param _start_i the beginning of the array
\param _end_i the ending  index of the array
\param _search_key Value to find
\param _result_index the index of the found element, or if not found then it will get the index of the  closest bigger value
\return true if found, else false
*/
template<class T>
bool gim_binary_search(
	const T*_array,GUINT _start_i,
	GUINT _end_i,const T & _search_key,
	GUINT & _result_index)
{
	GUINT _i = _start_i;
	GUINT _j = _end_i+1;
	GUINT _k;
	while(_i < _j)
	{
		_k = (_j+_i-1)/2;
		if(_array[_k]==_search_key)
		{
			_result_index = _k;
			return true;
		}
		else if (_array[_k]<_search_key)
		{
			_i = _k+1;
		}
		else
		{
			_j = _k;
		}
	}
	_result_index = _i;
	return false;
}

///heap sort from http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Heap/
template <typename T, typename COMP_CLASS>
void gim_down_heap(T *pArr, GUINT k, GUINT n,COMP_CLASS CompareFunc)
{
	/*  PRE: a[k+1..N] is a heap */
	/* POST:  a[k..N]  is a heap */

	T temp = pArr[k - 1];
	/* k has child(s) */
	while (k <= n/2)
	{
		int child = 2*k;

		if ((child < (int)n) && CompareFunc(pArr[child - 1] , pArr[child])<0)
		{
			child++;
		}
		/* pick larger child */
		if (CompareFunc(temp , pArr[child - 1])<0)
		{
			/* move child up */
			pArr[k - 1] = pArr[child - 1];
			k = child;
		}
		else
		{
			break;
		}
	}
	pArr[k - 1] = temp;
} /*downHeap*/

template <typename T, typename COMP_CLASS>
void gim_heap_sort(T *pArr, GUINT element_count, COMP_CLASS CompareFunc)
{
	/* sort a[0..N-1],  N.B. 0 to N-1 */
	GUINT k;
	GUINT n = element_count;
	for (k = n/2; k > 0; k--)
	{
		gim_down_heap(pArr, k, n, CompareFunc);
	}

	/* a[1..N] is now a heap */
	while ( n>=2 )
	{
		gim_swap_elements(pArr,0,n-1); /* largest of a[0..n-1] */
		--n;
		/* restore a[1..i-1] heap */
		gim_down_heap(pArr, 1, n, CompareFunc);
	}
}

#endif // GIM_RADIXSORT_H_INCLUDED


text:
import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {changeBackground} from '../action'
import Nav from './Nav'
import Body from './Body'
import '../stylesheets/waves.scss'
import '../stylesheets/layout.scss'

class Page extends Component {
	render() {
		const {
			color, list, title, activeIndex,
			onSwitch
		} = this.props

		return (
			<div id='app' className={color}>
				<Nav list={list} title={title} activeIndex={activeIndex} onSwitch={onSwitch} />
				<Body />
			</div>
		)
	}
}

Page.propTypes = {
	color: PropTypes.string,
	list: PropTypes.arrayOf(PropTypes.string),
	title: PropTypes.string,
	activeIndex: PropTypes.arrayOf(PropTypes.number),
	onSwitch: PropTypes.func,
}

function mapStateToProps(state) {
	return state
}

function mapDispatchToProps(dispatch) {
	return {
		onSwitch: (color, title) => {dispatch(changeBackground(color, title))},
		switchView: (title, activeIndex) => {dispatch(switchView(title, activeIndex))}
	}
}

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Page)

// {
// 	color: 'red',
// 	list: ['start', 'end'],
// 	title: 'Start',
// 	onSwitch: function(){...}
// }


text:
package com.example.vision.snippets;

// [START vision_batch_annotate_files]
import com.google.cloud.vision.v1.AnnotateFileRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateFilesRequest;
import com.google.cloud.vision.v1.BatchAnnotateFilesResponse;
import com.google.cloud.vision.v1.Block;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.InputConfig;
import com.google.cloud.vision.v1.Page;
import com.google.cloud.vision.v1.Paragraph;
import com.google.cloud.vision.v1.Symbol;
import com.google.cloud.vision.v1.Word;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BatchAnnotateFiles {

  public static void batchAnnotateFiles() throws IOException {
    String filePath = "path/to/your/file.pdf";
    batchAnnotateFiles(filePath);
  }

  public static void batchAnnotateFiles(String filePath) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
      // You can send multiple files to be annotated, this sample demonstrates how to do this with
      // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest`
      // object for each file that you want annotated.
      // First read the files contents
      Path path = Paths.get(filePath);
      byte[] data = Files.readAllBytes(path);
      ByteString content = ByteString.copyFrom(data);

      // Specify the input config with the file's contents and its type.
      // Supported mime_type: application/pdf, image/tiff, image/gif
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig
      InputConfig inputConfig =
          InputConfig.newBuilder().setMimeType("application/pdf").setContent(content).build();

      // Set the type of annotation you want to perform on the file
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
      Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();

      // Build the request object for that one file. Note: for additional file you have to create
      // additional `AnnotateFileRequest` objects and store them in a list to be used below.
      // Since we are sending a file of type `application/pdf`, we can use the `pages` field to
      // specify which pages to process. The service can process up to 5 pages per document file.
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest
      AnnotateFileRequest fileRequest =
          AnnotateFileRequest.newBuilder()
              .setInputConfig(inputConfig)
              .addFeatures(feature)
              .addPages(1) // Process the first page
              .addPages(2) // Process the second page
              .addPages(-1) // Process the last page
              .build();

      // Add each `AnnotateFileRequest` object to the batch request.
      BatchAnnotateFilesRequest request =
          BatchAnnotateFilesRequest.newBuilder().addRequests(fileRequest).build();

      // Make the synchronous batch request.
      BatchAnnotateFilesResponse response = imageAnnotatorClient.batchAnnotateFiles(request);

      // Process the results, just get the first result, since only one file was sent in this
      // sample.
      for (AnnotateImageResponse imageResponse :
          response.getResponsesList().get(0).getResponsesList()) {
        System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText());
        for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) {
          for (Block block : page.getBlocksList()) {
            System.out.format("%nBlock confidence: %s%n", block.getConfidence());
            for (Paragraph par : block.getParagraphsList()) {
              System.out.format("\tParagraph confidence: %s%n", par.getConfidence());
              for (Word word : par.getWordsList()) {
                System.out.format("\t\tWord confidence: %s%n", word.getConfidence());
                for (Symbol symbol : word.getSymbolsList()) {
                  System.out.format(
                      "\t\t\tSymbol: %s, (confidence: %s)%n",
                      symbol.getText(), symbol.getConfidence());
                }
              }
            }
          }
        }
      }
    }
  }
}
// [END vision_batch_annotate_files]


text:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hi, I am a TextView" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="I am an edit text" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="I am a button" />

        <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TOGGLE BUTTON" />

        <CheckBox
            android:id="@+id/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckBox" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:entries="@array/spinner_items" />

        <Switch
            android:id="@+id/switch1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="New Switch" />

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/radioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton" />

            <RadioButton
                android:id="@+id/radioButton2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton2" />
        </RadioGroup>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:src="@mipmap/ic_launcher" />

        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp" />

        <RatingBar
            android:id="@+id/ratingBar2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp" />

    </LinearLayout>
</ScrollView>


text:
package org.ovirt.engine.ui.userportal.place;

import org.ovirt.engine.ui.common.auth.CurrentUser;
import org.ovirt.engine.ui.common.place.ApplicationPlaceManager;
import org.ovirt.engine.ui.common.section.DefaultLoginSectionPlace;
import org.ovirt.engine.ui.common.section.DefaultMainSectionPlace;
import org.ovirt.engine.ui.userportal.auth.CurrentUserRole;
import org.ovirt.engine.ui.userportal.section.DefaultMainSectionExtendedPlace;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.TokenFormatter;

public class UserPortalPlaceManager extends ApplicationPlaceManager {

    private final CurrentUserRole userRole;

    private final PlaceRequest defaultMainSectionRequest;
    private final PlaceRequest defaultMainSectionExtendedRequest;

    @Inject
    public UserPortalPlaceManager(EventBus eventBus, TokenFormatter tokenFormatter,
            CurrentUser user, CurrentUserRole userRole,
            @DefaultLoginSectionPlace String defaultLoginSectionPlace,
            @DefaultMainSectionPlace String defaultMainSectionPlace,
            @DefaultMainSectionExtendedPlace String defaultMainSectionExtendedPlace) {
        super(eventBus, tokenFormatter, user, new PlaceRequest(defaultLoginSectionPlace));
        this.userRole = userRole;
        this.defaultMainSectionRequest = new PlaceRequest(defaultMainSectionPlace);
        this.defaultMainSectionExtendedRequest = new PlaceRequest(defaultMainSectionExtendedPlace);
    }

    @Override
    protected PlaceRequest getDefaultMainSectionPlace() {
        return userRole.isBasicUser() ? defaultMainSectionRequest : defaultMainSectionExtendedRequest;
    }

}


text:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

## Solution

Using stack we can solve it easily.


text:
import os
from urllib.parse import urlparse
from typing import Dict
from studio.util import logs
from studio.credentials.credentials import Credentials
from studio.storage.storage_setup import get_storage_verbose_level
from studio.storage.storage_type import StorageType
from studio.storage.storage_handler import StorageHandler
from studio.storage import storage_util

class HTTPStorageHandler(StorageHandler):
    def __init__(self, remote_path, credentials_dict,
                 timestamp=None,
                 compression=None):

        self.logger = logs.get_logger(self.__class__.__name__)
        self.logger.setLevel(get_storage_verbose_level())

        self.url = remote_path
        self.timestamp = timestamp

        parsed_url = urlparse(self.url)
        self.scheme = parsed_url.scheme
        self.endpoint = parsed_url.netloc
        self.path = parsed_url.path
        self.credentials = Credentials(credentials_dict)

        super().__init__(StorageType.storageHTTP,
            self.logger,
            False,
            compression=compression)

    def upload_file(self, key, local_path):
        storage_util.upload_file(self.url, local_path, self.logger)

    def download_file(self, key, local_path):
        return storage_util.download_file(self.url, local_path, self.logger)

    def download_remote_path(self, remote_path, local_path):
        head, _ = os.path.split(local_path)
        if head is not None:
            os.makedirs(head, exist_ok=True)
        return storage_util.download_file(remote_path, local_path, self.logger)

    @classmethod
    def get_id(cls, config: Dict) -> str:
        endpoint = config.get('endpoint', None)
        if endpoint is None:
            return None
        creds: Credentials = Credentials.get_credentials(config)
        creds_fingerprint = creds.get_fingerprint() if creds else ''
        return '[http]{0}::{1}'.format(endpoint, creds_fingerprint)

    def get_local_destination(self, remote_path: str):
        parsed_url = urlparse(remote_path)
        parts = parsed_url.path.split('/')
        return None, parts[len(parts)-1]

    def delete_file(self, key, shallow=True):
        raise NotImplementedError

    def get_file_url(self, key):
        return self.url

    def get_file_timestamp(self, key):
        return self.timestamp

    def get_qualified_location(self, key):
        return self.url


text:
namespace Microsoft.Azure.Management.Synapse.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Azure Active Directory Only Authentication Info
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class AzureADOnlyAuthentication : ProxyResource
    {
        /// <summary>
        /// Initializes a new instance of the AzureADOnlyAuthentication class.
        /// </summary>
        public AzureADOnlyAuthentication()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AzureADOnlyAuthentication class.
        /// </summary>
        /// <param name="azureADOnlyAuthenticationProperty">Azure Active
        /// Directory only Authentication enabled.</param>
        /// <param name="id">Fully qualified resource ID for the resource. Ex -
        /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}</param>
        /// <param name="name">The name of the resource</param>
        /// <param name="type">The type of the resource. E.g.
        /// "Microsoft.Compute/virtualMachines" or
        /// "Microsoft.Storage/storageAccounts"</param>
        /// <param name="state">property configuration state. Possible values
        /// include: 'Consistent', 'InConsistent', 'Updating'</param>
        /// <param name="creationDate">property configuration date</param>
        public AzureADOnlyAuthentication(bool azureADOnlyAuthenticationProperty, string id = default(string), string name = default(string), string type = default(string), string state = default(string), System.DateTime? creationDate = default(System.DateTime?))
            : base(id, name, type)
        {
            AzureADOnlyAuthenticationProperty = azureADOnlyAuthenticationProperty;
            State = state;
            CreationDate = creationDate;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets azure Active Directory only Authentication enabled.
        /// </summary>
        [JsonProperty(PropertyName = "properties.azureADOnlyAuthentication")]
        public bool AzureADOnlyAuthenticationProperty { get; set; }

        /// <summary>
        /// Gets property configuration state. Possible values include:
        /// 'Consistent', 'InConsistent', 'Updating'
        /// </summary>
        [JsonProperty(PropertyName = "properties.state")]
        public string State { get; private set; }

        /// <summary>
        /// Gets property configuration date
        /// </summary>
        [JsonProperty(PropertyName = "properties.creationDate")]
        public System.DateTime? CreationDate { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
        }
    }
}