text:
/** GenericModel.java
 *
 * @author Sunita Sarawagi
 * @since 1.0
 * @version 1.3
 */
package iitb.Model;
import gnu.trove.list.array.TIntArrayList;
import iitb.CRF.DataSequence;

import java.util.Arrays;
import java.util.BitSet;
import java.util.StringTokenizer;

public class GenericModel extends Model {
    /**
	 *
	 */
	private static final long serialVersionUID = 6363225834538701213L;
	int _numStates;
    Edge _edges[];  // edges have to be sorted by their starting node id.
    int edgeStart[]; // the index in the edges array where edges out of node i start.
    int startStates[];
    int endStates[];
    int myLabel = -1;
    public int label(int s) {return (myLabel == -1)?s:myLabel;}
    public GenericModel(String spec, int thisLabel) throws Exception {
        super(1);
        name = spec;
        myLabel = thisLabel;
        if (spec.equals("naive"))
            spec="1-chain";
        if (spec.endsWith("-chain") || spec.endsWith("-long")) {
            StringTokenizer tok = new StringTokenizer(spec,"-");
            int len = Integer.parseInt(tok.nextToken());
            _numStates = len;
            startStates = new int[1];
            startStates[0] = 0;
            edgeStart = new int[_numStates];
            if (len == 1) {
                _edges = new Edge[1];
                _edges[0] = new Edge(0,0);
                endStates = new int[1];
                endStates[0] = 0;
                edgeStart[0] = 0;
            } else {
                _edges = new Edge[2*(len-1)];
                for (int i = 0; i < len-1; i++) {
                    _edges[2*i] = new Edge(i,i+1);
                    _edges[2*i+1] = new Edge(i,len-1);
                    edgeStart[i] = 2*i;
                }
                _edges[_edges.length-1] = new Edge(len-2,len-2);
                endStates = new int[2];
                endStates[0] = 0; // to allow one word entities.
                endStates[1] = len-1;
            }
        } else if (spec.endsWith("parallel")) {
            StringTokenizer tok = new StringTokenizer(spec,"-");
            int len = Integer.parseInt(tok.nextToken());
            _numStates = len*(len+1)/2;
            _edges = new Edge[len*(len-1)/2 + 1];
            edgeStart = new int[_numStates];
            startStates = new int[len];
            endStates = new int[len];
            int node = 0;
            int e = 0;
            for (int i = 0; i < len; i++) {
                node += i;
                for (int j = 0; j < i; j++) {
                    _edges[e++] = new Edge(node+j,node+j+1);
                    edgeStart[node+j] = e-1;
                }
                startStates[i] = node;
                endStates[i] = node + i;
            }
            node += len;
            _edges[e++] = new Edge(_numStates-2, _numStates-2);
            assert (e == _edges.length);
            assert (node == _numStates);
        } else if (spec.equals("boundary") || (spec.equals("BCEU"))) {
            // this implements a model where each label is either of a
            // Unique word (state 0) or broken into a Start state
            // (state 1) with a single token, Continuation state
            // (state 2) with multiple tokens (only state with
            // self-loop) and end state (state 3) with a single token.
            // The number of states is thus 4, and number of edges 4
            _numStates = 4;
            _edges = new Edge[4];
            _edges[0] = new Edge(1,2);
            _edges[1] = new Edge(1,3);
            _edges[2] = new Edge(2,2);
            _edges[3] = new Edge(2,3);
            startStates = new int[2];
            startStates[0] = 0;
            startStates[1] = 1;
            endStates = new int[2];
            endStates[0] = 0;
            endStates[1] = 3;
            edgeStart = new int[_numStates];
            edgeStart[0] = 4;
            edgeStart[1] = 0;
            edgeStart[2] = 2;
            edgeStart[3] = 4;
        } else if (spec.equals("BCE")) {
            // only "U" state missing, so "B" can also be an ending state.
            _numStates = 3;
            _edges = new Edge[4];
            _edges[0] = new Edge(0,1);
            _edges[1] = new Edge(0,2);
            _edges[2] = new Edge(1,1);
            _edges[3] = new Edge(1,2);
            startStates = new int[1];
            startStates[0] = 0;
            endStates = new int[2];
            endStates[0] = 0;
            endStates[1] = 2;
            edgeStart = new int[_numStates];
            edgeStart[0] = 0;
            edgeStart[1] = 2;
            edgeStart[2] = 4;
        }else if (spec.equals("BI")){
            // there is a start state with a transition to an I state.
            // start state can also be the end state to allow for one token labels.
            _numStates = 2;
            _edges = new Edge[2];
            _edges[0] = new Edge(0,1);
            _edges[1] = new Edge(1,1);
            startStates = new int[1];
            startStates[0] = 0;
            endStates = new int[2];
            endStates[0] = 0;
            endStates[1] = 1;
            edgeStart = new int[_numStates];
            edgeStart[0] = 0;
            edgeStart[1] = 1;
        } else {
            throw new Exception("Unknown graph type: " + spec);
        }
    }
    public void setEdgeStartPointers() {
        // sort the edges in increasing order of start node ids..
        Arrays.sort(_edges);
        edgeStart = new int[_numStates];
        for (int i = 0; i  < edgeStart.length; i++)
            edgeStart[i] = _numStates;
        for (int i = 0; i < _edges.length; i++) {
            if (edgeStart[_edges[i].start] > i)
                edgeStart[_edges[i].start] = i;
        }
    };
    public void fillStartEnd() {
        BitSet isStart = new BitSet(_numStates);
        BitSet isEnd = new BitSet(_numStates);
        isStart.flip(0,_numStates);
        isEnd.flip(0,_numStates);
        for (int i = 0; i < _edges.length; i++) {
            isStart.set(_edges[i].end,false);
            isEnd.set(_edges[i].start,false);
        }
        startStates = new int[isStart.cardinality()];
        int prev = 0;
        for (int i = 0; i < startStates.length; i++) {
            startStates[i] = isStart.nextSetBit(prev);
            prev = startStates[i]+1;
        }
        endStates = new int[isEnd.cardinality()];
        prev = 0;
        for (int i = 0; i < endStates.length; i++) {
            endStates[i] = isEnd.nextSetBit(prev);
            prev = endStates[i]+1;
        }
    }
    public void setEdges(Object[] edges) {
        _edges = new Edge[edges.length];
        for (int i = 0; i < _edges.length; i++)
            _edges[i] = (Edge)(edges[i]);
    }
    public void addEdge(int edgeNum, int st, int end) {
        _edges[edgeNum] = new Edge(st,end);
    }
    public GenericModel(int numNodes, int numEdges) throws Exception {
        super(numNodes);
        _numStates = numNodes;
        _edges = new Edge[numEdges];
    }
    public int numStates() {return _numStates;}
    public int numEdges() {return _edges.length;}
    public int numStartStates() {return startStates.length;}
    public int startState(int i) {return (i < numStartStates())?startStates[i]:-1;}
    public int numEndStates() {
        return endStates.length;
    }
    public int endState(int i) {
        return (i < numEndStates())?endStates[i]:-1;
    }
    public boolean isEndState(int i) {
        // TODO -- convert this to binary search
        for (int k = 0; k < endStates.length; k++)
            if (endStates[k] == i)
                return true;
        return false;
    }
    public boolean isStartState(int i) {
        // TODO -- convert this to binary search
        for (int k = 0; k < startStates.length; k++)
            if (startStates[k] == i)
                return true;
        return false;
    }
    public void stateMappings(DataSequence data) throws Exception {
        return;
    }
    public void stateMappings(DataSequence data, int len, int start) throws Exception {
        for (int i = 0; i < numStartStates(); i++) {
            if (pathToEnd(data,startState(i),len-1,start+1)) {
                data.set_y(start,startState(i));
                return;
            }
        }
        throw new Exception("No path in graph");
    }
    boolean pathToEnd(DataSequence data, int s, int lenLeft, int start) {
        if (lenLeft == 0) {
            return isEndState(s);
        }
        for (int e = edgeStart[s]; (e < numEdges()) && (_edges[e].start == s); e++) {
            int child = _edges[e].end;
            if (pathToEnd(data,child,lenLeft-1,start+1)) {
                data.set_y(start,child);
                return true;
            }
        }
        return false;
    }

    public int stateMappingGivenLength(int label, int len, int posFromStart) throws Exception {
        for (int i = 0; i < numStartStates(); i++) {
            int stateId = pathToEnd(startState(i),len-1,posFromStart-1);
            if (stateId >= 0) {
                if (posFromStart==0)
                    return startState(i);
                return stateId;
            }
        }
        throw new Exception("No path in graph");
    }
    public void stateMappingGivenLength(int label, int len, TIntArrayList stateIds)
    throws Exception {
    	stateIds.clear();
    	for (int i = 0; i < len; i++,stateIds.add(0));
        for (int i = 0; i < numStartStates(); i++) {
            if (pathToEnd(startState(i),len-1,1,stateIds)) {
                stateIds.setQuick(0,startState(i));
                return;
            }
        }
        throw new Exception("No path in graph");
    }
    boolean pathToEnd(int s, int lenLeft, int start, TIntArrayList stateIds) {
        assert (lenLeft >= 0);
        if (lenLeft == 0) {
            return isEndState(s);
        }
        for (int e = edgeStart[s]; (e < numEdges()) && (_edges[e].start == s); e++) {
            int child = _edges[e].end;
            if (pathToEnd(child,lenLeft-1,start+1,stateIds)) {
                stateIds.setQuick(start,child);
                return true;
            }
        }
        return false;
    }

    /**
     * @return
     */
    private int pathToEnd(int s, int lenLeft, int posFromStart) {
        if (lenLeft == 0) {
            return isEndState(s)?s:-1;
        }
        for (int e = edgeStart[s]; (e < numEdges()) && (_edges[e].start == s); e++) {
            int child = _edges[e].end;
            int stateId = pathToEnd(child,lenLeft-1,posFromStart-1);
            if (stateId >= 0) {
                if (posFromStart == 0)
                    return child;
                return stateId;
            }
        }
        return -1;
    }

    public class GenericEdgeIterator implements EdgeIterator {
        int edgeNum;
        Edge edges[];
        GenericEdgeIterator(Edge[] e) {
            edges = e;
            start();
        };
        public void start() {
            edgeNum = 0;
        }
        public boolean hasNext() {
            return (edgeNum < edges.length);
        }
        public Edge next() {
            edgeNum++;
            return edges[edgeNum-1];
        }
        /* (non-Javadoc)
         * @see iitb.Model.EdgeIterator#nextIsOuter()
         */
        public boolean nextIsOuter() {
            return true;
        }
    };
    public EdgeIterator edgeIterator() {
        return new GenericEdgeIterator(_edges);
    }

};


text:
Element::~Element()
{
	if (ns) ns->remove(this);
}

void Element::save(Serializer &s) const
{
	s.string_(nm);
}
void Element::load(Deserializer &s)
{
	s.string_(nm);
}

std::string Element::displayName(PrintingStyle ds) const
{
	auto i = dn.find(ds); if (i != dn.end()) return i->second;
	switch (ds)
	{
		case PS_Debug:
		case PS_Function:
		case PS_Console:  return name();

		case PS_Input:
		case PS_Head:
		case PS_HTML:
		case PS_LaTeX:
		case PS_Mathematica: ds = PS_Console; break; // try again
	}
	i = dn.find(ds); return i != dn.end() ? i->second : name();
}

RootNamespace *Element::root_container() const
{
	for (Namespace *ns = container(); ns; ns = ns->container())
	{
		if (ns->isRoot()) return (RootNamespace*)ns;
	}
	assert(isNamespace() && ((Namespace*)this)->isRoot());
	return NULL;
}

bool Element::rename(const std::string &new_name)
{
	if (nm == new_name) return true;

	if (!ns)
	{
		nm = new_name;
		return true;
	}
	else
	{
		return ns->rename(this, new_name);
	}
}

Element *Element::copy(Namespace &other) const
{
	if (&other == container()) return NULL;

	Element *e = copy(); if (!e) return NULL;

	assert(e->name() == name());

	try
	{
		other.add(e);
	}
	catch(...)
	{
		delete e;
		throw;
	}
	return e;
}

redpajama_set_name: RedPajamaGithub


text:
package de.jonashackt.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.jonashackt.businesslogic.IncredibleLogic;
import de.jonashackt.model.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/weather")
public class WeatherBackendController {

    private static final Logger LOG = LoggerFactory.getLogger(WeatherBackendController.class);

    @Value(value="classpath:responses/forecast.pdf")
    private Resource forecastPdf;

    @RequestMapping(path = "/general/outlook", method=RequestMethod.POST, produces="application/json")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody GeneralOutlook generateGeneralOutlook(@RequestBody Weather weather) throws JsonProcessingException {
        LOG.info("Request for /general/outlook with POST");
        /*
         * Some incredible Businesslogic...
         */
        LOG.info("Called Backend");

        ObjectMapper mapper = new ObjectMapper();
        LOG.info("Object as JSON:" + mapper.writeValueAsString(weather));

        LOG.info("GeneralOutlook as JSON: \n " + mapper.writeValueAsString(IncredibleLogic.generateGeneralOutlook()));

        return IncredibleLogic.generateGeneralOutlook();
    }

    @RequestMapping(path = "/general/outlook", method=RequestMethod.GET, produces="application/json")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String infoAboutGeneralOutlook() throws JsonProcessingException {
        LOG.info("Request for /general/outlook with GET");

        Weather weather = new Weather();
        weather.setFlagColor("blue");
        weather.setPostalCode("99425");
        weather.addUser(new User(55, 5634500, MethodOfPayment.Bitcoin));
        weather.setProduct(Product.ForecastBasic);

        ObjectMapper mapper = new ObjectMapper();
        String weatherJson = mapper.writeValueAsString(weather);

        return "Try a POST also against this URL! Just send some body with it like: '" + weatherJson + "'";
    }

    @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "text/plain")
    public String whatsTheSenseInThat(@PathVariable("name") String name) {
        LOG.info("Request for /{name} with GET");
        return "Hello " + name + "! This is a RESTful HttpService written in Spring. Try to use some other HTTP verbs (don´t say 'methods' :P ) :)";
    }

    @RequestMapping(path = "/general/outlook/{zip}", method=RequestMethod.GET, produces="application/pdf")
    @ResponseStatus(HttpStatus.OK)
    public byte[] getWeatherInformationPdf(@PathVariable("zip") String zip) throws IOException {
        LOG.info("Request for /general/outlook/{zip} with GET");

        return IOUtils.toByteArray(forecastPdf.getInputStream());
    }
}


text:
<?php

namespace Ivory\CKEditorBundle\Form\Type;

use Ivory\CKEditorBundle\Model\ConfigManagerInterface;
use Ivory\CKEditorBundle\Model\PluginManagerInterface;
use Ivory\CKEditorBundle\Model\StylesSetManagerInterface;
use Ivory\CKEditorBundle\Model\TemplateManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\HttpKernel\Kernel;

/**
 * CKEditor type.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class CKEditorType extends AbstractType
{
    /** @var boolean */
    private $enable = true;

    /** @var boolean */
    private $async = false;

    /** @var boolean */
    private $autoload = true;

    /** @var boolean */
    private $autoInline = true;

    /** @var boolean */
    private $inline = false;

    /** @var boolean */
    private $jquery = false;

    /** @var boolean */
    private $requireJs = false;

    /** @var boolean */
    private $inputSync = false;

    /** @var array */
    private $filebrowsers = array();

    /** @var string */
    private $basePath = 'bundles/ivoryckeditor/';

    /** @var string */
    private $jsPath = 'bundles/ivoryckeditor/ckeditor.js';

    /** @var string */
    private $jqueryPath = 'bundles/ivoryckeditor/adapters/jquery.js';

    /** @var \Ivory\CKEditorBundle\Model\ConfigManagerInterface */
    private $configManager;

    /** @var \Ivory\CKEditorBundle\Model\PluginManagerInterface */
    private $pluginManager;

    /** @var \Ivory\CKEditorBundle\Model\StylesSetManagerInterface */
    private $stylesSetManager;

    /** @var \Ivory\CKEditorBundle\Model\TemplateManagerInterface */
    private $templateManager;

    /**
     * Creates a CKEditor type.
     *
     * @param \Ivory\CKEditorBundle\Model\ConfigManagerInterface    $configManager    The config manager.
     * @param \Ivory\CKEditorBundle\Model\PluginManagerInterface    $pluginManager    The plugin manager.
     * @param \Ivory\CKEditorBundle\Model\StylesSetManagerInterface $stylesSetManager The styles set manager.
     * @param \Ivory\CKEditorBundle\Model\TemplateManagerInterface  $templateManager  The template manager.
     */
    public function __construct(
        ConfigManagerInterface $configManager,
        PluginManagerInterface $pluginManager,
        StylesSetManagerInterface $stylesSetManager,
        TemplateManagerInterface $templateManager
    ) {
        $this->setConfigManager($configManager);
        $this->setPluginManager($pluginManager);
        $this->setStylesSetManager($stylesSetManager);
        $this->setTemplateManager($templateManager);
    }

    /**
     * Sets/Checks if the widget is enabled.
     *
     * @param boolean|null $enable TRUE if the widget is enabled else FALSE.
     *
     * @return boolean TRUE if the widget is enabled else FALSE.
     */
    public function isEnable($enable = null)
    {
        if ($enable !== null) {
            $this->enable = (bool) $enable;
        }

        return $this->enable;
    }

    /**
     * Sets/Checks if the widget is async.
     *
     * @param boolean|null $async TRUE if the widget is async else FALSE.
     *
     * @return boolean TRUE if the widget is async else FALSE.
     */
    public function isAsync($async = null)
    {
        if ($async !== null) {
            $this->async = (bool) $async;
        }

        return $this->async;
    }

    /**
     * Sets/Checks if the widget is autoloaded.
     *
     * @param boolean $autoload TRUE if the widget is autoloaded else FALSE.
     *
     * @return boolean TRUE if the widget is autoloaded else FALSE.
     */
    public function isAutoload($autoload = null)
    {
        if ($autoload !== null) {
            $this->autoload = (bool) $autoload;
        }

        return $this->autoload;
    }

    /**
     * Sets/Checks if the widget is auto inlined.
     *
     * @param boolean $autoInline TRUE if the widget is auto inlined else FALSE.
     *
     * @return boolean TRUE if the widget is auto inlined else FALSE.
     */
    public function isAutoInline($autoInline = null)
    {
        if ($autoInline !== null) {
            $this->autoInline = (bool) $autoInline;
        }

        return $this->autoInline;
    }

    /**
     * Sets/Checks if the widget is inlined.
     *
     * @param boolean $inline TRUE if the widget is inlined else FALSE.
     *
     * @return boolean TRUE if the widget is inlined else FALSE.
     */
    public function isInline($inline = null)
    {
        if ($inline !== null) {
            $this->inline = (bool) $inline;
        }

        return $this->inline;
    }

    /**
     * Checks/Sets if the jquery adapter is loaded.
     *
     * @param boolean $jquery TRUE if the jquery adapter is loaded else FALSE.
     *
     * @return boolean TRUE if the jquery adapter is loaded else FALSE.
     */
    public function useJquery($jquery = null)
    {
        if ($jquery !== null) {
            $this->jquery = (bool) $jquery;
        }

        return $this->jquery;
    }

    /**
     * Checks/Sets if require js is used.
     *
     * @param boolean $requireJs TRUE if the requirejs is used else FALSE.
     *
     * @return boolean TRUE if the requirejs is used else FALSE.
     */
    public function useRequireJs($requireJs = null)
    {
        if ($requireJs !== null) {
            $this->requireJs = (bool) $requireJs;
        }

        return $this->requireJs;
    }

    /**
     * Sets/Checks if the input is synchonized with the widget.
     *
     * @param boolean $inputSync TRUE if the input is synchronized with the widget else FALSE.
     *
     * @return boolean TRUE if the input is synchronized with the widget else FALSE.
     */
    public function isInputSync($inputSync = null)
    {
        if ($inputSync !== null) {
            $this->inputSync = (bool) $inputSync;
        }

        return $this->inputSync;
    }

    /**
     * Checks if there are filebrowsers.
     *
     * @return boolean TRUE if there are filebrowsers else FALSE.
     */
    public function hasFilebrowsers()
    {
        return !empty($this->filebrowsers);
    }

    /**
     * Gets the filebrowsers.
     *
     * @return array The filebrowsers.
     */
    public function getFilebrowsers()
    {
        return $this->filebrowsers;
    }

    /**
     * Sets the filebrowsers.
     *
     * @param array $filebrowsers The filebrowsers.
     */
    public function setFilebrowsers(array $filebrowsers)
    {
        foreach ($filebrowsers as $filebrowser) {
            $this->addFilebrowser($filebrowser);
        }
    }

    /**
     * Checks if there is the filebrowser.
     *
     * @param string $filebrowser The filebrowser.
     *
     * @return boolean TRUE if there is the filebrowser else FALSE.
     */
    public function hasFilebrowser($filebrowser)
    {
        return in_array($filebrowser, $this->filebrowsers, true);
    }

    /**
     * Adds a filebrowser.
     *
     * @param string $filebrowser The filebrowser.
     */
    public function addFilebrowser($filebrowser)
    {
        if (!$this->hasFilebrowser($filebrowser)) {
            $this->filebrowsers[] = $filebrowser;
        }
    }

    /**
     * Removes a filebrowser.
     *
     * @param string $filebrowser The filebrowser.
     */
    public function removeFilebrowser($filebrowser)
    {
        unset($this->filebrowsers[array_search($filebrowser, $this->filebrowsers, true)]);
    }

    /**
     * Gets the CKEditor base path.
     *
     * @return string The CKEditor base path.
     */
    public function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * Sets the CKEditor base path.
     *
     * @param string $basePath The CKEditor base path.
     */
    public function setBasePath($basePath)
    {
        $this->basePath = $basePath;
    }

    /**
     * Gets the CKEditor JS path.
     *
     * @return string The CKEditor JS path.
     */
    public function getJsPath()
    {
        return $this->jsPath;
    }

    /**
     * Sets the CKEditor JS path.
     *
     * @param string $jsPath The CKEditor JS path.
     */
    public function setJsPath($jsPath)
    {
        $this->jsPath = $jsPath;
    }

    /**
     * Gets the jquery path.
     *
     * @return string The jquery path.
     */
    public function getJqueryPath()
    {
        return $this->jqueryPath;
    }

    /**
     * Sets the jquery path.
     *
     * @param string $jqueryPath The jquery path.
     */
    public function setJqueryPath($jqueryPath)
    {
        $this->jqueryPath = $jqueryPath;
    }

    /**
     * Gets the CKEditor config manager.
     *
     * @return \Ivory\CKEditorBundle\Model\ConfigManagerInterface The CKEditor config manager.
     */
    public function getConfigManager()
    {
        return $this->configManager;
    }

    /**
     * Sets the CKEditor config manager.
     *
     * @param \Ivory\CKEditorBundle\Model\ConfigManagerInterface $configManager The CKEditor config manager.
     */
    public function setConfigManager(ConfigManagerInterface $configManager)
    {
        $this->configManager = $configManager;
    }

    /**
     * Gets the CKEditor plugin manager.
     *
     * @return \Ivory\CKEditorBundle\Model\PluginManagerInterface The CKEditor plugin manager.
     */
    public function getPluginManager()
    {
        return $this->pluginManager;
    }

    /**
     * Sets the CKEditor plugin manager.
     *
     * @param \Ivory\CKEditorBundle\Model\PluginManagerInterface $pluginManager The CKEditor plugin manager.
     */
    public function setPluginManager(PluginManagerInterface $pluginManager)
    {
        $this->pluginManager = $pluginManager;
    }

    /**
     * Gets the styles set manager.
     *
     * @return \Ivory\CKEditorBundle\Model\StylesSetManagerInterface The styles set manager.
     */
    public function getStylesSetManager()
    {
        return $this->stylesSetManager;
    }

    /**
     * Sets the styles set manager.
     *
     * @param \Ivory\CKEditorBundle\Model\StylesSetManagerInterface $stylesSetManager The styles set manager.
     */
    public function setStylesSetManager(StylesSetManagerInterface $stylesSetManager)
    {
        $this->stylesSetManager = $stylesSetManager;
    }

    /**
     * Gets the CKEditor template manager.
     *
     * @return \Ivory\CKEditorBundle\Model\TemplateManagerInterface The CKEditor template manager.
     */
    public function getTemplateManager()
    {
        return $this->templateManager;
    }

    /**
     * Sets the CKEditor template manager.
     *
     * @param \Ivory\CKEditorBundle\Model\TemplateManagerInterface $templateManager The CKEditor template manager.
     */
    public function setTemplateManager(TemplateManagerInterface $templateManager)
    {
        $this->templateManager = $templateManager;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('enable', $options['enable']);

        if ($builder->getAttribute('enable')) {
            $builder->setAttribute('async', $options['async']);
            $builder->setAttribute('autoload', $options['autoload']);
            $builder->setAttribute('auto_inline', $options['auto_inline']);
            $builder->setAttribute('inline', $options['inline']);
            $builder->setAttribute('jquery', $options['jquery']);
            $builder->setAttribute('require_js', $options['require_js']);
            $builder->setAttribute('input_sync', $options['input_sync']);
            $builder->setAttribute('filebrowsers', $options['filebrowsers']);
            $builder->setAttribute('base_path', $options['base_path']);
            $builder->setAttribute('js_path', $options['js_path']);
            $builder->setAttribute('jquery_path', $options['jquery_path']);

            $configManager = clone $this->configManager;
            $pluginManager = clone $this->pluginManager;
            $stylesSetManager = clone $this->stylesSetManager;
            $templateManager = clone $this->templateManager;

            $config = $options['config'];
            if ($options['config_name'] === null) {
                $options['config_name'] = uniqid('ivory', true);
                $configManager->setConfig($options['config_name'], $config);
            } else {
                $configManager->mergeConfig($options['config_name'], $config);
            }

            $pluginManager->setPlugins($options['plugins']);
            $stylesSetManager->setStylesSets($options['styles']);
            $templateManager->setTemplates($options['templates']);

            $builder->setAttribute('config', $configManager->getConfig($options['config_name']));
            $builder->setAttribute('plugins', $pluginManager->getPlugins());
            $builder->setAttribute('styles', $stylesSetManager->getStylesSets());
            $builder->setAttribute('templates', $templateManager->getTemplates());
        }
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['enable'] = $form->getConfig()->getAttribute('enable');

        if ($form->getConfig()->getAttribute('enable')) {
            $view->vars['async'] = $form->getConfig()->getAttribute('async');
            $view->vars['autoload'] = $form->getConfig()->getAttribute('autoload');
            $view->vars['auto_inline'] = $form->getConfig()->getAttribute('auto_inline');
            $view->vars['inline'] = $form->getConfig()->getAttribute('inline');
            $view->vars['jquery'] = $form->getConfig()->getAttribute('jquery');
            $view->vars['require_js'] = $form->getConfig()->getAttribute('require_js');
            $view->vars['input_sync'] = $form->getConfig()->getAttribute('input_sync');
            $view->vars['filebrowsers'] = $form->getConfig()->getAttribute('filebrowsers');
            $view->vars['base_path'] = $form->getConfig()->getAttribute('base_path');
            $view->vars['js_path'] = $form->getConfig()->getAttribute('js_path');
            $view->vars['jquery_path'] = $form->getConfig()->getAttribute('jquery_path');
            $view->vars['config'] = $form->getConfig()->getAttribute('config');
            $view->vars['plugins'] = $form->getConfig()->getAttribute('plugins');
            $view->vars['styles'] = $form->getConfig()->getAttribute('styles');
            $view->vars['templates'] = $form->getConfig()->getAttribute('templates');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults(array(
                'enable'       => $this->enable,
                'async'        => $this->async,
                'autoload'     => $this->autoload,
                'auto_inline'  => $this->autoInline,
                'inline'       => $this->inline,
                'jquery'       => $this->jquery,
                'require_js'   => $this->requireJs,
                'input_sync'   => $this->inputSync,
                'filebrowsers' => $this->filebrowsers,
                'base_path'    => $this->basePath,
                'js_path'      => $this->jsPath,
                'jquery_path'  => $this->jqueryPath,
                'config_name'  => $this->configManager->getDefaultConfig(),
                'config'       => array(),
                'plugins'      => array(),
                'styles'       => array(),
                'templates'    => array(),
            ));

        $allowedTypesMap = array(
            'enable'       => 'bool',
            'async'        => 'bool',
            'autoload'     => 'bool',
            'auto_inline'  => 'bool',
            'inline'       => 'bool',
            'jquery'       => 'bool',
            'require_js'   => 'bool',
            'input_sync'   => 'bool',
            'filebrowsers' => 'array',
            'config_name'  => array('string', 'null'),
            'base_path'    => 'string',
            'js_path'      => 'string',
            'jquery_path'  => 'string',
            'config'       => 'array',
            'plugins'      => 'array',
            'styles'       => 'array',
            'templates'    => 'array',
        );

        $normalizers = array(
            'base_path' => function (Options $options, $value) {
                if (substr($value, -1) !== '/') {
                    $value .= '/';
                }

                return $value;
            },
        );

        if (Kernel::VERSION_ID >= 20600) {
            foreach ($allowedTypesMap as $option => $allowedTypes) {
                $resolver->addAllowedTypes($option, $allowedTypes);
            }

            foreach ($normalizers as $option => $normalizer) {
                $resolver->setNormalizer($option, $normalizer);
            }
        } else {
            $resolver
                ->addAllowedTypes($allowedTypesMap)
                ->setNormalizers($normalizers);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $this->configureOptions($resolver);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        // Prefer the FQCN if the getBlockPrefix method exists on the parent method
        if (method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')) {
            return 'Symfony\Component\Form\Extension\Core\Type\TextareaType';
        }

        // Return the legacy shortname; drop this when Symfony <2.8 support is removed
        return 'textarea';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'ckeditor';
    }
}


text:
import {fetchChainHeight, clearBlockchain} from './BlockActions'
import {fetchCcSchema, clearResponsePayloads} from './ChaincodeActions'

export const CONFIG_UPDATE_URL_REST_ROOT = 'CONFIG_UPDATE_URL_REST_ROOT'
export const setUrlRestRoot = (url) =>{
  return{
    type: CONFIG_UPDATE_URL_REST_ROOT,
    url
  }
}

export const SET_CONFIG_IOT_CONNECTION = 'SET_CONFIG_IOT_CONNECTION'
export const setConfigIotConnection = (iotDeviceClient) => {
  return{
    type: SET_CONFIG_IOT_CONNECTION,
    iotDeviceClient
  }
}

export const SET_CHAIN_HEIGHT_POLLING_INTERVAL_ID = 'SET_CHAIN_HEIGHT_POLLING_INTERVAL_ID'
export const setChainHeightPollingIntervalId = (intervalId) => {
  return{
    type: SET_CHAIN_HEIGHT_POLLING_INTERVAL_ID,
    intervalId
  }
}

export const SET_OBC_CONFIGURATION = 'SET_OBC_CONFIGURATION'
export const setObcConfiguration = (obcConfigObj) =>{

  //we first need to clear the interval. Subsequently, we need to start
  //a new interval with the new OBC root and update the interval id.
  return{
    type: SET_OBC_CONFIGURATION,
    obcConfigObj
  }
}

export const SET_CONFIG_DIALOG_DISPLAY = 'SET_CONFIG_DIALOG_DISPLAY'
export const setConfigDialogDisplay = (showDialog) =>{
  return{
    type: SET_CONFIG_DIALOG_DISPLAY,
    showDialog
  }
}

export function setConfiguration(obcConfigObj){

  return function(dispatch, getState){
    //let state = getState();

    //update any OBC related configuration
    dispatch(setObcConfiguration(obcConfigObj))

    //get the current state
    let state = getState();

    //clear the existing interval timer
    let intervalId = state.configuration.chainHeightPollingIntervalId
    console.log('Interval to clear: ' + intervalId)
    clearInterval(intervalId);

    //create a new interval and set it in the state
    intervalId = setInterval(() => {dispatch(fetchChainHeight(state.configuration.urlRestRoot))}, state.configuration.chainHeightPollingInterval);

    //set a new chain
    dispatch(clearBlockchain())

    //clear the response payloads when changing configuration
    dispatch(clearResponsePayloads())

    //set the new timeout interval
    dispatch(setChainHeightPollingIntervalId(intervalId));

    //reload form schema
    dispatch(fetchCcSchema());
  }
}


text:
import salt.utils.decorators
import time

def _fallbackfunc():
    return False, 'fallback'

def working_function():
    '''
    CLI Example::
    '''
    return True

@salt.utils.decorators.depends('time')
def depends():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123')
def missing_depends():
    return True

@salt.utils.decorators.depends('time', fallback_funcion=_fallbackfunc)
def depends_will_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123', fallback_funcion=_fallbackfunc)
def missing_depends_will_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret


text:
static const NSString *kvo_WMFSettingsViewController_authManager_loggedInUsername = nil;

NS_ASSUME_NONNULL_BEGIN

static NSString *const WMFSettingsURLZeroFAQ = @"https://foundation.m.wikimedia.org/wiki/Wikipedia_Zero_App_FAQ";
static NSString *const WMFSettingsURLTerms = @"https://foundation.m.wikimedia.org/wiki/Terms_of_Use/en";
static NSString *const WMFSettingsURLRate = @"itms-apps://itunes.apple.com/app/id324715238";
static NSString *const WMFSettingsURLDonation = @"https://donate.wikimedia.org/?utm_medium=WikipediaApp&utm_campaign=iOS&utm_source=<app-version>&uselang=<langcode>";

#if WMF_TWEAKS_ENABLED
@interface WMFSettingsViewController () <UITableViewDelegate, UITableViewDataSource, WMFPreferredLanguagesViewControllerDelegate, WMFAccountViewControllerDelegate, FBTweakViewControllerDelegate>
#else
@interface WMFSettingsViewController () <UITableViewDelegate, UITableViewDataSource, WMFPreferredLanguagesViewControllerDelegate, WMFAccountViewControllerDelegate>
#endif

@property (nonatomic, strong, readwrite) MWKDataStore *dataStore;

@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) IBOutlet UITableView *tableView;

@property (nullable, nonatomic) WMFAuthenticationManager *authManager;

@end

@implementation WMFSettingsViewController

+ (instancetype)settingsViewControllerWithDataStore:(MWKDataStore *)store {
    NSParameterAssert(store);
    WMFSettingsViewController *vc = [WMFSettingsViewController wmf_initialViewControllerFromClassStoryboard];
    vc.dataStore = store;
    return vc;
}

#pragma mark - Setup

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];

    [self.tableView registerNib:[WMFSettingsTableViewCell wmf_classNib] forCellReuseIdentifier:[WMFSettingsTableViewCell identifier]];

    self.tableView.estimatedRowHeight = 52.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.authManager = [WMFAuthenticationManager sharedInstance];

    self.navigationBar.displayType = NavigationBarDisplayTypeLargeTitle;
#if UI_TEST
    if ([[NSUserDefaults standardUserDefaults] wmf_isFastlaneSnapshotInProgress]) {
        self.tableView.decelerationRate = UIScrollViewDecelerationRateFast;
    }
#endif
}

- (void)dealloc {
    self.authManager = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setAuthManager:(nullable WMFAuthenticationManager *)authManager {
    if (_authManager == authManager) {
        return;
    }

    NSString *keyPath = WMF_SAFE_KEYPATH([WMFAuthenticationManager sharedInstance], loggedInUsername);

    [_authManager removeObserver:self forKeyPath:keyPath context:&kvo_WMFSettingsViewController_authManager_loggedInUsername];
    _authManager = authManager;
    [_authManager addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:&kvo_WMFSettingsViewController_authManager_loggedInUsername];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [NSUserActivity wmf_makeActivityActive:[NSUserActivity wmf_settingsViewActivity]];
}

- (UIScrollView *_Nullable)scrollView {
    return self.tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    self.showCloseButton = self.tabBarController == nil;
    [self.navigationController setNavigationBarHidden:YES];
    [super viewWillAppear:animated];
    self.navigationController.toolbarHidden = YES;
    [self loadSections];
}

- (void)configureBackButton {
    if (self.navigationItem.rightBarButtonItem != nil) {
        return;
    }
    UIBarButtonItem *xButton = [UIBarButtonItem wmf_buttonType:WMFButtonTypeX target:self action:@selector(closeButtonPressed)];
    self.navigationItem.rightBarButtonItem = xButton;
}

- (void)setShowCloseButton:(BOOL)showCloseButton {
    if (showCloseButton) {
        [self configureBackButton];
    } else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)closeButtonPressed {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (nullable NSString *)title {
    return [WMFCommonStrings settingsTitle];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    WMFSettingsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:WMFSettingsTableViewCell.identifier forIndexPath:indexPath];

    NSArray *menuItems = [self.sections[indexPath.section] getItems];
    WMFSettingsMenuItem *menuItem = menuItems[indexPath.item];

    cell.tag = menuItem.type;
    cell.title = menuItem.title;
    [cell applyTheme:self.theme];
    if (!self.theme.colors.icon) {
        cell.iconColor = [UIColor whiteColor];
        cell.iconBackgroundColor = menuItem.iconColor;
    }
    cell.iconName = menuItem.iconName;
    cell.disclosureType = menuItem.disclosureType;
    cell.disclosureText = menuItem.disclosureText;
    [cell.disclosureSwitch setOn:menuItem.isSwitchOn];
    cell.selectionStyle = (menuItem.disclosureType == WMFSettingsMenuItemDisclosureType_Switch) ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleDefault;

    if (menuItem.disclosureType != WMFSettingsMenuItemDisclosureType_Switch && menuItem.disclosureType != WMFSettingsMenuItemDisclosureType_None) {
        cell.accessibilityTraits = UIAccessibilityTraitButton;
    } else {
        cell.accessibilityTraits = UIAccessibilityTraitStaticText;
    }

    [cell.disclosureSwitch removeTarget:self action:@selector(disclosureSwitchChanged:) forControlEvents:UIControlEventValueChanged];
    cell.disclosureSwitch.tag = menuItem.type;
    [cell.disclosureSwitch addTarget:self action:@selector(disclosureSwitchChanged:) forControlEvents:UIControlEventValueChanged];

    return cell;
}

- (BOOL)accessibilityPerformEscape {
    [self closeButtonPressed];
    return YES;
}

- (void)disclosureSwitchChanged:(UISwitch *)disclosureSwitch {
    WMFSettingsMenuItemType type = (WMFSettingsMenuItemType)disclosureSwitch.tag;
    [self updateStateForMenuItemType:type isSwitchOnValue:disclosureSwitch.isOn];
    [self loadSections];
}

#pragma mark - Switch tap handling

- (void)updateStateForMenuItemType:(WMFSettingsMenuItemType)type isSwitchOnValue:(BOOL)isOn {
    switch (type) {
        case WMFSettingsMenuItemType_SendUsageReports: {
            WMFEventLoggingService *eventLoggingService = [WMFEventLoggingService sharedInstance];
            eventLoggingService.isEnabled = isOn;
            if (isOn) {
                [eventLoggingService reset];
                [[WMFDailyStatsLoggingFunnel shared] logAppNumberOfDaysSinceInstall];
                [[SessionsFunnel shared] logSessionStart];
                [[UserHistoryFunnel shared] logStartingSnapshot];
            } else {
                [[SessionsFunnel shared] logSessionEnd];
                [[UserHistoryFunnel shared] logSnapshot];
                [eventLoggingService reset];
            }
        } break;
        default:
            break;
    }
}

#pragma mark - Cell tap handling

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    switch (cell.tag) {
        case WMFSettingsMenuItemType_LoginAccount:
            [self showLoginOrAccount];
            break;
        case WMFSettingsMenuItemType_SearchLanguage:
            [self showLanguages];
            break;
        case WMFSettingsMenuItemType_Search:
            [self showSearch];
            break;
        case WMFSettingsMenuItemType_ExploreFeed:
            [self showExploreFeedSettings];
            break;
        case WMFSettingsMenuItemType_Notifications:
            [self showNotifications];
            break;
        case WMFSettingsMenuItemType_Appearance: {
            [self showAppearance];
            break;
        }
        case WMFSettingsMenuItemType_StorageAndSyncing: {
            [self showStorageAndSyncing];
            break;
        }
        case WMFSettingsMenuItemType_StorageAndSyncingDebug: {
            [self showStorageAndSyncingDebug];
            break;
        }
        case WMFSettingsMenuItemType_Support:
            [self wmf_openExternalUrl:[self donationURL] useSafari:YES];
            break;
        case WMFSettingsMenuItemType_PrivacyPolicy:
            [self wmf_openExternalUrl:[NSURL URLWithString:[WMFCommonStrings privacyPolicyURLString]]];
            break;
        case WMFSettingsMenuItemType_Terms:
            [self wmf_openExternalUrl:[NSURL URLWithString:WMFSettingsURLTerms]];
            break;
        case WMFSettingsMenuItemType_ZeroFAQ:
            [self wmf_openExternalUrl:[NSURL URLWithString:WMFSettingsURLZeroFAQ]];
            break;
        case WMFSettingsMenuItemType_RateApp:
            [self wmf_openExternalUrl:[NSURL URLWithString:WMFSettingsURLRate] useSafari:YES];
            break;
        case WMFSettingsMenuItemType_SendFeedback: {
            WMFHelpViewController *vc = [[WMFHelpViewController alloc] initWithDataStore:self.dataStore];
            [vc applyTheme:self.theme];
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case WMFSettingsMenuItemType_About: {
            AboutViewController *vc = [[AboutViewController alloc] initWithTheme:self.theme];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case WMFSettingsMenuItemType_ClearCache:
            [self showClearCacheActionSheet];
            break;
        case WMFSettingsMenuItemType_DevSettings: {
#if WMF_TWEAKS_ENABLED
            FBTweakViewController *tweaksVC = [[FBTweakViewController alloc] initWithStore:[FBTweakStore sharedInstance]];
            tweaksVC.tweaksDelegate = self;
            [self presentViewController:tweaksVC animated:YES completion:nil];
#endif
        }
        default:
            break;
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#if WMF_TWEAKS_ENABLED
- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        DebugReadingListsViewController *vc = [[DebugReadingListsViewController alloc] initWithNibName:@"DebugReadingListsViewController" bundle:nil];
        [self presentViewControllerWrappedInNavigationController:vc];
    }
}
#endif

#pragma mark - Dynamic URLs

- (NSURL *)donationURL {
    NSString *url = WMFSettingsURLDonation;

    NSString *languageCode = [[MWKLanguageLinkController sharedInstance] appLanguage].languageCode;
    languageCode = [languageCode stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSString *appVersion = [[NSBundle mainBundle] wmf_debugVersion];
    appVersion = [appVersion stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    url = [url stringByReplacingOccurrencesOfString:@"<langcode>" withString:languageCode];
    url = [url stringByReplacingOccurrencesOfString:@"<app-version>" withString:appVersion];

    return [NSURL URLWithString:url];
}

#pragma mark - Presentation

- (void)presentViewControllerWrappedInNavigationController:(UIViewController<WMFThemeable> *)viewController {
    WMFThemeableNavigationController *themeableNavController = [[WMFThemeableNavigationController alloc] initWithRootViewController:viewController theme:self.theme];
    [self presentViewController:themeableNavController animated:YES completion:nil];
}

#pragma mark - Log in and out

- (void)showLoginOrAccount {
    NSString *userName = [WMFAuthenticationManager sharedInstance].loggedInUsername;
    if (userName) {
        WMFAccountViewController *accountVC = [[WMFAccountViewController alloc] init];
        accountVC.dataStore = self.dataStore;
        accountVC.delegate = self;
        [accountVC applyTheme:self.theme];
        [self.navigationController pushViewController:accountVC animated:YES];
    } else {
        WMFLoginViewController *loginVC = [WMFLoginViewController wmf_initialViewControllerFromClassStoryboard];
        [loginVC applyTheme:self.theme];
        [self presentViewControllerWrappedInNavigationController:loginVC];
        [[LoginFunnel shared] logLoginStartInSettings];
    }
}

#pragma mark - Clear Cache

- (void)showClearCacheActionSheet {
    NSString *message = WMFLocalizedStringWithDefaultValue(@"settings-clear-cache-are-you-sure-message", nil, nil, @"Clearing cached data will free up about %1$@ of space. It will not delete your saved pages.", @"Message for the confirmation presented to the user to verify they are sure they want to clear clear cached data. %1$@ is replaced with the approximate file size in bytes that will be made available. Also explains that the action will not delete their saved pages.");
    NSString *bytesString = [NSByteCountFormatter stringFromByteCount:[NSURLCache sharedURLCache].currentDiskUsage countStyle:NSByteCountFormatterCountStyleFile];
    message = [NSString localizedStringWithFormat:message, bytesString];

    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:WMFLocalizedStringWithDefaultValue(@"settings-clear-cache-are-you-sure-title", nil, nil, @"Clear cached data?", @"Title for the confirmation presented to the user to verify they are sure they want to clear clear cached data.") message:message preferredStyle:UIAlertControllerStyleAlert];
    [sheet addAction:[UIAlertAction actionWithTitle:WMFLocalizedStringWithDefaultValue(@"settings-clear-cache-ok", nil, nil, @"Clear cache", @"Confirm action to clear cached data")
                                              style:UIAlertActionStyleDestructive
                                            handler:^(UIAlertAction *_Nonnull action) {
                                                [self.dataStore clearCachesForUnsavedArticles];
                                            }]];
    [sheet addAction:[UIAlertAction actionWithTitle:WMFLocalizedStringWithDefaultValue(@"settings-clear-cache-cancel", nil, nil, @"Cancel", @"Cancel action to clear cached data\n{{Identical|Cancel}}") style:UIAlertActionStyleCancel handler:NULL]];

    [self presentViewController:sheet animated:YES completion:NULL];
}

- (void)logout {
    [self wmf_showKeepSavedArticlesOnDevicePanelIfNeededTriggeredBy:KeepSavedArticlesTriggerLogout
                                                                     theme:self.theme
                                                                completion:^{
                                                                    [[WMFAuthenticationManager sharedInstance] logoutInitiatedBy:LogoutInitiatorUser completion:^{
                                                                        [[LoginFunnel shared] logLogoutInSettings];
                                                                    }];
                                                                }];
}

#pragma mark - Languages

- (void)showLanguages {
    WMFPreferredLanguagesViewController *languagesVC = [WMFPreferredLanguagesViewController preferredLanguagesViewController];
    languagesVC.showExploreFeedCustomizationSettings = YES;
    languagesVC.delegate = self;
    [languagesVC applyTheme:self.theme];
    [self presentViewControllerWrappedInNavigationController:languagesVC];
}

- (void)languagesController:(WMFPreferredLanguagesViewController *)controller didUpdatePreferredLanguages:(NSArray<MWKLanguageLink *> *)languages {
    if ([languages count] > 1) {
        [[NSUserDefaults wmf] wmf_setShowSearchLanguageBar:YES];
    } else {
        [[NSUserDefaults wmf] wmf_setShowSearchLanguageBar:NO];
    }

    [self loadSections];
}

#pragma mark - Search

- (void)showSearch {
    WMFSearchSettingsViewController *searchSettingsViewController = [[WMFSearchSettingsViewController alloc] init];
    [searchSettingsViewController applyTheme:self.theme];
    [self.navigationController pushViewController:searchSettingsViewController animated:YES];
}

#pragma mark - Feed

- (void)showExploreFeedSettings {
    WMFExploreFeedSettingsViewController *feedSettingsVC = [[WMFExploreFeedSettingsViewController alloc] init];
    feedSettingsVC.dataStore = self.dataStore;
    [feedSettingsVC applyTheme:self.theme];
    [self.navigationController pushViewController:feedSettingsVC animated:YES];
}

#pragma mark - Notifications

- (void)showNotifications {
    WMFNotificationSettingsViewController *notificationSettingsVC = [[WMFNotificationSettingsViewController alloc] init];
    [notificationSettingsVC applyTheme:self.theme];
    [self.navigationController pushViewController:notificationSettingsVC animated:YES];
}

#pragma mark - Appearance

- (void)showAppearance {
    WMFAppearanceSettingsViewController *appearanceSettingsVC = [[WMFAppearanceSettingsViewController alloc] init];
    [appearanceSettingsVC applyTheme:self.theme];
    [self.navigationController pushViewController:appearanceSettingsVC animated:YES];
}

#pragma mark - Storage and syncing

- (void)showStorageAndSyncing {
    WMFStorageAndSyncingSettingsViewController *storageAndSyncingSettingsVC = [[WMFStorageAndSyncingSettingsViewController alloc] init];
    storageAndSyncingSettingsVC.dataStore = self.dataStore;
    [storageAndSyncingSettingsVC applyTheme:self.theme];
    [self.navigationController pushViewController:storageAndSyncingSettingsVC animated:YES];
}

- (void)showStorageAndSyncingDebug {
#if DEBUG
    DebugReadingListsViewController *vc = [[DebugReadingListsViewController alloc] initWithNibName:@"DebugReadingListsViewController" bundle:nil];
    [self presentViewControllerWrappedInNavigationController:vc];
#endif
}

#if WMF_TWEAKS_ENABLED
- (void)tweakViewControllerPressedDone:(FBTweakViewController *)tweakViewController {
    [[NSNotificationCenter defaultCenter] postNotificationName:FBTweakShakeViewControllerDidDismissNotification object:tweakViewController];
    [tweakViewController dismissViewControllerAnimated:YES completion:nil];
}
#endif

#pragma mark - Cell reloading

- (nullable NSIndexPath *)indexPathForVisibleCellOfType:(WMFSettingsMenuItemType)type {
    return [self.tableView.indexPathsForVisibleRows wmf_match:^BOOL(NSIndexPath *indexPath) {
        return ([self.tableView cellForRowAtIndexPath:indexPath].tag == type);
    }];
}

#pragma mark - Sections structure

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section {
    NSArray *items = [self.sections[section] getItems];
    return items.count;
}

- (nullable NSString *)tableView:(UITableView *)tableView
         titleForHeaderInSection:(NSInteger)section {
    NSString *header = [self.sections[section] getHeaderTitle];
    if (header != nil) {
        return header;
    }
    return nil;
}

- (void)loadSections {
    self.sections = [[NSMutableArray alloc] init];

    [self.sections addObject:[self section_1]];
    [self.sections addObject:[self section_2]];
    [self.sections addObject:[self section_3]];
    [self.sections addObject:[self section_4]];
    WMFSettingsTableViewSection *section5 = [self section_5];
    if (section5) {
        [self.sections addObject:section5];
    }

    [self.tableView reloadData];
}

#pragma mark - Section structure

- (WMFSettingsTableViewSection *)section_1 {
    NSArray *items = @[[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_LoginAccount],
                       [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_Support]];
    WMFSettingsTableViewSection *section = [[WMFSettingsTableViewSection alloc] initWithItems:items
                                                                                headerTitle:nil
                                                                                footerText:nil];
    return section;
}

- (WMFSettingsTableViewSection *)section_2 {
    NSArray *commonItems = @[[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_SearchLanguage],
                             [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_Search]];
    NSMutableArray *items = [NSMutableArray arrayWithArray:commonItems];
    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_ExploreFeed]];

    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_Notifications]];

    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_Appearance]];
    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_StorageAndSyncing]];
#if DEBUG
    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_StorageAndSyncingDebug]];
#endif
    [items addObject:[WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_ClearCache]];
    WMFSettingsTableViewSection *section = [[WMFSettingsTableViewSection alloc] initWithItems:items headerTitle:nil footerText:nil];
    return section;
}

- (WMFSettingsTableViewSection *)section_3 {
    WMFSettingsTableViewSection *section = [[WMFSettingsTableViewSection alloc] initWithItems:@[
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_PrivacyPolicy],
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_Terms],
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_SendUsageReports]
    ]
                                                                                headerTitle:WMFLocalizedStringWithDefaultValue(@"main-menu-heading-legal", nil, nil, @"Privacy and Terms", @"Header text for the legal section of the menu. Consider using something informal, but feel free to use a more literal translation of \"Legal info\" if it seems more appropriate.")
                                                                                footerText:WMFLocalizedStringWithDefaultValue(@"preference-summary-eventlogging-opt-in", nil, nil, @"Allow Wikimedia Foundation to collect information about how you use the app to make the app better", @"Description of preference that when checked enables data collection of user behavior.")];

    return section;
}

- (WMFSettingsTableViewSection *)section_4 {
    WMFSettingsTableViewSection *section = [[WMFSettingsTableViewSection alloc] initWithItems:@[
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_RateApp],
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_SendFeedback],
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_About]
    ]
                                                                                headerTitle:nil
                                                                                footerText:nil];
    return section;
}

- (nullable WMFSettingsTableViewSection *)section_5 {
#if WMF_TWEAKS_ENABLED
    WMFSettingsTableViewSection *section = [[WMFSettingsTableViewSection alloc] initWithItems:@[
        [WMFSettingsMenuItem itemForType:WMFSettingsMenuItemType_DevSettings]
    ]
                                                                                headerTitle:WMFLocalizedStringWithDefaultValue(@"main-menu-heading-debug", nil, nil, @"Debug", @"Header text for the debug section of the menu. The debug menu is conditionally shown if in Xcode debug mode.\n{{Identical|Debug}}")
                                                                                footerText:nil];
    return section;
#else
    return nil;
#endif
}

#pragma mark - Scroll view

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewDidScroll:scrollView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewWillBeginDragging:scrollView];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self.navigationBarHider scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewDidEndScrollingAnimation:scrollView];
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewWillScrollToTop:scrollView];
    return YES;
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [self.navigationBarHider scrollViewDidScrollToTop:scrollView];
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context {
    if (context == &kvo_WMFSettingsViewController_authManager_loggedInUsername) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadSections];
        });
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WMFThemeable

- (void)applyTheme:(WMFTheme *)theme {
    [super applyTheme:theme];
    if (self.viewIfLoaded == nil) {
        return;
    }
    self.tableView.backgroundColor = theme.colors.baseBackground;
    self.tableView.indicatorStyle = theme.scrollIndicatorStyle;
    self.view.backgroundColor = theme.colors.baseBackground;
    [self loadSections];
}

#pragma Mark WMFAccountViewControllerDelegate

- (void)accountViewControllerDidTapLogout:(WMFAccountViewController * _Nonnull)accountViewController {
    [self logout];
    [self loadSections];
}

@end

NS_ASSUME_NONNULL_END


text:
import urllib2
import cookielib
import requests
import re
import json
import codecs
import os
import datetime
import random
import time
import mysql.connector
import variable
import facebook_variable

class User(object):
    def __init__(self):
        super(User, self).__init__()
        self.data = {
            'profile': {},
            'following': [],
            'followers': [],
            'latest': [],
            'recommends': [],
            'highlights': {},
            'responses': [],
        }

    def getstr(self):
        result = json.dumps(self.data, indent=4)
        return result

class Story(object):
    def __init__(self):
        super(Story, self).__init__()
        self.data = {
            'story_id': "",
            'author': "",
            'timestamp': 0,
            'published_date': "",
            'collection': {},
            'tags': [],
            'recommends': 0,
            'responses': 0,
            'response_to': "",
            'success': 1,
        }

    def getstr(self):
        result = json.dumps(self.data, indent=4)
        return result

class FBUser(object):
    def __init__(self):
        super(FBUser, self).__init__()
        self.data = {
            'user_id': '',
            'URL': '',
            'Name': '',
            'Friends': None,
            'Current City': '',
            'Hometown': '',
            'Birthday': '',
            'Gender': '',
            'Languages': '',
        }

    def getstr(self):
        result = json.dumps(self.data, indent=4)
        return result

def mark_failed_post(post):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "UPDATE posts SET failed=1 WHERE post_id='%s'" % post
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def get_story(post_id):
    url = 'https://medium.com/posts/' + post_id
    story = Story()
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    try:
        response = opener.open(req, timeout=10)
    except urllib2.URLError:
        story.data['success'] = 0
        print('----------timeout')
        mark_failed_post(post_id)
        return story
    data = response.read()

    story_id = re.findall('data-post-id="(.*?)" data-is-icon', data)
    if not story_id:
        story.data['success'] = 0
        print('----------fail to get story_id')
        mark_failed_post(post_id)
        return story
    else:
        story.data['story_id'] = story_id[0]

    author = re.findall('"username":"(.*?)","createdAt"', data)
    if not author:
        story.data['success'] = 0
        print('----------fail to get author')
        mark_failed_post(post_id)
        return story
    else:
        story.data['author'] = author[0]

    timestamp = re.findall('"firstPublishedAt":(.*?),"latestPublishedAt"', data)
    if not timestamp:
        story.data['success'] = 0
        print('----------fail to get timestamp')
        mark_failed_post(post_id)
        return story
    else:
        story.data['timestamp'] = float(timestamp[0])
        story.data['published_date'] = datetime.date.fromtimestamp(story.data['timestamp']/1000.0).isoformat()

    collection = re.findall('"approvedHomeCollection":(.*?),"newsletterId"', data)
    if not collection:
        story.data['collection'] = {}
    else:
        story.data['collection'] = json.loads(collection[0])
        story.data['collection'].pop("sections", None)
        story.data['collection'].pop("virtuals", None)
        story.data['collection'].pop("colorPalette", None)
        story.data['collection'].pop("highlightSpectrum", None)
        story.data['collection'].pop("defaultBackgroundSpectrum", None)
        story.data['collection'].pop("navItems", None)
        story.data['collection'].pop("ampLogo", None)

    tags = re.findall('false,"tags":(.*?),"socialRecommendsCount"', data)
    if not tags:
        story.data['success'] = 0
        print('----------fail to get tags')
        mark_failed_post(post_id)
        return story
    else:
        story.data['tags'] = json.loads(tags[0])

    recommends = re.findall('"recommends":(.*?),"socialRecommends"', data)
    if not recommends:
        story.data['success'] = 0
        print('----------fail to get recommends')
        mark_failed_post(post_id)
        return story
    else:
        story.data['recommends'] = eval(recommends[0])

    responses = re.findall('"responsesCreatedCount":(.*?),"links"', data)
    if not responses:
        story.data['success'] = 0
        print('----------fail to get responses')
        mark_failed_post(post_id)
        return story
    else:
        story.data['responses'] = eval(responses[0])

    response_to = re.findall('"inResponseToPostId":"(.*?)","inResponseToPost"', data)
    if not response_to:
        story.data['response_to'] = ''
    else:
        story.data['response_to'] = response_to[0]

    return story

def get_following(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/following'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    following = re.findall('"username":"(.*?)","createdAt"', data)
    following_set = set(following)
    to = re.findall('"to":"(.*?)"}}},"v"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/following?to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        following = re.findall('"username":"(.*?)","createdAt"', data)
        following_set.update(following)
        to = re.findall('"to":"(.*?)"}}},"v"', data)
    return list(following_set)

def get_followers(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/followers'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    followers = re.findall('"username":"(.*?)","createdAt"', data)
    followers_set = set(followers)
    to = re.findall('"to":"(.*?)"}}},"v"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/followers?to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        followers = re.findall('"username":"(.*?)","createdAt"', data)
        followers_set.update(followers)
        to = re.findall('"to":"(.*?)"}}},"v"', data)
    return list(followers_set)

def get_latest(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=latest'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    latest = re.findall('"postId":"(.*?)"},"randomId"', data)
    latest_set = set(latest)
    to = re.findall('"to":"(.*?)","source":"latest"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=latest&to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        latest = re.findall('"postId":"(.*?)"},"randomId"', data)
        latest_set.update(latest)
        to = re.findall('"to":"(.*?)","source":"latest"', data)
    return list(latest_set)

def get_recommends(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=has-recommended'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    recommends = re.findall('w":{"postId":"(.*?)"},"randomId"', data)
    recommends_set = set(recommends)
    to = re.findall('"to":"(.*?)","source":"has-recommended"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=has-recommended&to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        recommends = re.findall('w":{"postId":"(.*?)"},"randomId"', data)
        recommends_set.update(recommends)
        to = re.findall('"to":"(.*?)","source":"has-recommended"', data)
    return list(recommends_set)

def get_highlights(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=quotes'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    highlights = re.findall('","postId":"(.*?)","userId":"', data)
    highlights_set = set(highlights)
    to = re.findall('"to":"(.*?)","source":"quotes"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=quotes&to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        highlights = re.findall('","postId":"(.*?)","userId":"', data)
        highlights_set.update(highlights)
        to = re.findall('"to":"(.*?)","source":"quotes"', data)
    return list(highlights_set)

def get_responses(user_id):
    url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=responses'
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    responses = re.findall('w":{"postId":"(.*?)"},"randomId"', data)
    responses_set = set(responses)
    to = re.findall('"to":"(.*?)","source":"responses"', data)
    while to:
        url = 'https://medium.com/_/api/users/' + user_id + '/profile/stream?source=responses&to=' + to[0]
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        req = urllib2.Request(url)
        req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                        Chrome/50.0.2661.102 Safari/537.36')
        response = opener.open(req, timeout=10)
        data = response.read()
        responses = re.findall('w":{"postId":"(.*?)"},"randomId"', data)
        responses_set.update(responses)
        to = re.findall('"to":"(.*?)","source":"responses"', data)
    return list(responses_set)

def mark_visited(username):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "UPDATE users SET visited=1 WHERE username='%s'" % username
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def mark_failed(username):
    print('-----mark failed')
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "UPDATE users SET failed=1 WHERE username='%s'" % username
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def post_exist(post):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    try:
        sql = "INSERT INTO posts VALUE('%s', %s, %s)" % (post, 1, 0)
        cur.execute(sql)
        cur.close()
        conn.commit()
        conn.close()
        return False
    except:
        cur.close()
        conn.close()
        return True

def get_posts(user):
    post_list = user.data['latest'] + user.data['recommends'] + user.data['highlights'] + user.data['responses']
    post_list = list(set(post_list))
    for post in post_list:
        if not post_exist(post):
            out = codecs.open("./Posts/%s.json" % post, 'w', 'utf-8')
            out.write(get_story(post).getstr())
            out.close()
    for post in user.data['responses']:
        post = get_story(post).data['response_to']
        if post and (not post_exist(post)):
            out = codecs.open("./Posts/%s.json" % post, 'w', 'utf-8')
            out.write(get_story(post).getstr())
            out.close()

def get_twitter_profile(username, twitter_id):
    url = "https://twitter.com/" + str(twitter_id) + "?lang=en"
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    response = opener.open(req, timeout=10)
    data = response.read()
    profile_data = re.findall('class="json-data" value="(.*?)">', data)
    profile = json.loads(profile_data[0].replace('"', '"'))
    profile.pop("promptbirdData", None)
    profile.pop("wtfOptions", None)
    profile.pop("typeaheadData", None)
    profile.pop("dm", None)
    profile.pop("initialState", None)
    profile.pop("activeHashflags", None)
    profile.pop("keyboardShortcuts", None)
    profile.pop("deciders", None)
    out = codecs.open("./Twitter/%s_t.json" % username, 'w', 'utf-8')
    out.write(json.dumps(profile, indent=4))
    out.close()

def mark_visited_twitter(username, twitter_id):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "INSERT INTO twitter VALUE('%s', '%s', %s, %s)" % (username, twitter_id, 1, 0)
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def mark_failed_twitter(username, twitter_id):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "UPDATE twitter SET failed=1 WHERE username='%s' and twitter_id='%s'" % (username, twitter_id)
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def get_facebook_profile(username, user_id):
    print(user_id)
    user = FBUser()

    user.data['user_id'] = user_id

    login_url = 'https://m.facebook.com/login'
    s = requests.session()
    login_data = {
        'email': facebook_variable.username,
        'pass': facebook_variable.password
    }
    s.post(login_url, login_data)

    time.sleep(1)
    url = 'https://facebook.com/' + user_id
    response = s.get(url)
    data = response.content

    URL = re.findall('URL=/(.*?)\?_fb_noscript=1', data)
    if URL:
        user.data['URL'] = URL[0]
    else:
        user.data['URL'] = user_id
    print(user.data['URL'])

    time.sleep(1)
    url = 'https://m.facebook.com/' + user.data['URL']
    response = s.get(url)
    data = response.content

    name = re.findall('<title>(.*?)</title>', data)
    if name:
        user.data['Name'] = name[0]
    else:
        print('-----no Name to show')

    if user.data['Name'] == 'Page Not Found':
        print('-----blocked')
        mark_failed_facebook(username, user_id)
        return

    friends = re.findall('See All Friends \((.*?)\)', data)
    if friends:
        user.data['Friends'] = int(friends[0])
    else:
        print('-----no Friends to show')

    current_city = re.findall('Current City<(.*?)a>', data)
    if current_city:
        current_city = re.findall('(.*?)<', current_city[0])
    if current_city:
        user.data['Current City'] = current_city[0]
    else:
        print('-----no Current City to show')

    hometown = re.findall('Hometown<(.*?)a>', data)
    if hometown:
        hometown = re.findall('(.*?)<', hometown[0])
    if hometown:
        user.data['Hometown'] = hometown[0]
    else:
        print('-----no Hometown to show')

    birthday = re.findall('Birthday
	', data)
    if birthday:
        birthday = re.findall('><(.*?)/', birthday[0])
        if birthday:
            birthday = re.findall('>(.*?)<', birthday[0])
    if birthday:
        user.data['Birthday'] = birthday[0]
    else:
        birthday = re.findall('Birth Year
	', data)
        if birthday:
            birthday = re.findall('><(.*?)/', birthday[0])
            if birthday:
                birthday = re.findall('>(.*?)<', birthday[0])
        if birthday:
            user.data['Birthday'] = birthday[0]
        else:
            print('-----no Birthday to show')

    gender = re.findall('Gender
	', data)
    if gender:
        gender = re.findall('><(.*?)/', gender[0])
        if gender:
            gender = re.findall('>(.*?)<', gender[0])
    if gender:
        user.data['Gender'] = gender[0]
    else:
        print('-----no Gender to show')

    languages = re.findall('Languages
	', data)
    if languages:
        languages = re.findall('><(.*?)/', languages[0])
        if languages:
            languages = re.findall('>(.*?)<', languages[0])
    if languages:
        user.data['Languages'] = languages[0]
    else:
        print('-----no Languages to show')

    out = codecs.open("./Facebook/%s_fb.json" % username, 'w', 'utf-8')
    out.write(user.getstr())
    out.close()

def mark_visited_facebook(username, facebook_id):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "INSERT INTO facebook VALUE('%s', '%s', %s, %s)" % (username, facebook_id, 1, 0)
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def mark_failed_facebook(username, facebook_id):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "UPDATE facebook SET failed=1 WHERE username='%s' and facebook_id='%s'" % (username, facebook_id)
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

def get_user(username):
    if not os.path.exists('./Users'):
        os.mkdir('./Users')
    if not os.path.exists('./Posts'):
        os.mkdir('./Posts')
    if not os.path.exists('./Twitter'):
        os.mkdir('./Twitter')
    if not os.path.exists('./Facebook'):
        os.mkdir('./Facebook')

    print(username)

    user = User()

    url = 'https://medium.com/@' + username
    cj = cookielib.MozillaCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    req = urllib2.Request(url)
    req.add_header("User-agent", 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
                    Chrome/50.0.2661.102 Safari/537.36')
    try:
        response = opener.open(req, timeout=10)
    except:
        print('-----fail to get data')
        mark_failed(username)
        return
    data = response.read()

    profile = re.findall('"userMeta":(.*?)"UserMeta"}', data)
    if not profile:
        print('-----fail to get profile')
        mark_failed(username)
        return
    else:
        user.data['profile'] = json.loads(profile[0]+'"UserMeta"}')
        print('-----profile')

    user_id = user.data['profile']['user']['userId']

    try:
        user.data['following'] = get_following(user_id)
        print('-----following')
    except:
        print('-----fail to get following')
        mark_failed(username)
        return

    try:
        user.data['followers'] = get_followers(user_id)
        print('-----followers')
    except:
        print('-----fail to get followers')
        mark_failed(username)
        return

    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password,
                                   database='Medium', charset='utf8')
    cur = conn.cursor()
    for following in user.data['following']:
        try:
            sql = "INSERT INTO users VALUE('%s', %s, %s, '%s')" % (following, 0, 0, variable.ip)
            cur.execute(sql)
            conn.commit()
            variable.queue.append(following)
        except:
            continue
    for follower in user.data['followers']:
        try:
            sql = "INSERT INTO users VALUE('%s', %s, %s, '%s')" % (follower, 0, 0, variable.ip)
            cur.execute(sql)
            conn.commit()
            variable.queue.append(follower)
        except:
            continue
    cur.close()
    conn.close()

    try:
        user.data['latest'] = get_latest(user_id)
        print('-----latest')
    except:
        print('-----fail to get latest')
        mark_failed(username)
        return

    try:
        user.data['recommends'] = get_recommends(user_id)
        print('-----recommends')
    except:
        print('-----fail to get recommends')
        mark_failed(username)
        return

    try:
        user.data['highlights'] = get_highlights(user_id)
        print('-----highlights')
    except:
        print('-----fail to get highlights')
        mark_failed(username)
        return

    try:
        user.data['responses'] = get_responses(user_id)
        print('-----responses')
    except:
        print('-----fail to get responses')
        mark_failed(username)
        return

    out = codecs.open("./Users/%s.json" % username, 'w', 'utf-8')
    out.write(user.getstr())
    out.close()

    try:
        get_posts(user)
        print('-----posts')
    except:
        print('-----fail to get posts')

    twitter_id = user.data['profile']['user']['twitterScreenName']
    print('-----twitter: ' + twitter_id)
    if twitter_id:
        try:
            mark_visited_twitter(username, twitter_id)
            get_twitter_profile(username, twitter_id)
            print('-----twitter')
        except:
            mark_failed_twitter(username, twitter_id)
            print('-----fail to get Twitter')

    facebook_id = user.data['profile']['user']['facebookAccountId']
    print('-----facebook: ' + facebook_id)
    if facebook_id:
        try:
            mark_visited_facebook(username, facebook_id)
            get_facebook_profile(username, facebook_id)
            print('-----facebook')
        except:
            mark_failed_facebook(username, facebook_id)
            print('-----fail to get Facebook')

    print("-----%s obtained" % username)

def get_queue(ip):
    conn = mysql.connector.connect(host=variable.host, port=3306, user=variable.username, password=variable.password, database='Medium', charset='utf8')
    cur = conn.cursor()
    sql = "SELECT username FROM users WHERE visited=0 and failed=0 and ip='%s'" % ip
    cur.execute(sql)
    result = cur.fetchall()
    cur.close()
    conn.commit()
    conn.close()
    queue = []
    for user in result:
        queue.append(user[0])
    for i in range(5):
        random.shuffle(queue)
    return queue

def bfs():
    while variable.queue:
        username = variable.queue.pop(0)
        mark_visited(username)
        try:
            get_user(username)
        except:
            print('fail to get user')

if __name__ == '__main__':
    variable.queue = get_queue(variable.ip)
    bfs()


text:
<?php

/*******************************************************************************

 *  Marketplace Web Service PHP5 Library
 *  Generated: Thu May 07 13:07:36 PDT 2009
 *
 */

/**
 *  @see MarketplaceWebService_Model
 */
require_once (dirname(__FILE__) . '/../Model.php');

/**
 * MarketplaceWebService_Model_CancelFeedSubmissionsResult
 *
 * Properties:
 *

 *
 *
Count: int

 *
FeedSubmissionInfo: MarketplaceWebService_Model_FeedSubmissionInfo

 *
 *

 */
class MarketplaceWebService_Model_CancelFeedSubmissionsResult extends MarketplaceWebService_Model
{

    /**
     * Construct new MarketplaceWebService_Model_CancelFeedSubmissionsResult
     *
     * @param mixed $data DOMElement or Associative Array to construct from.
     *
     * Valid properties:
     *

     *
     *
Count: int

     *
FeedSubmissionInfo: MarketplaceWebService_Model_FeedSubmissionInfo

     *
     *

     */
    public function __construct($data = null)
    {
        $this->fields = array (
        'Count' => array('FieldValue' => null, 'FieldType' => 'int'),
        'FeedSubmissionInfo' => array('FieldValue' => array(), 'FieldType' => array('MarketplaceWebService_Model_FeedSubmissionInfo')),
        );
        parent::__construct($data);
    }

        /**
     * Gets the value of the Count property.
     *
     * @return int Count
     */
    public function getCount()
    {
        return $this->fields['Count']['FieldValue'];
    }

    /**
     * Sets the value of the Count property.
     *
     * @param int Count
     * @return this instance
     */
    public function setCount($value)
    {
        $this->fields['Count']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the Count and returns this instance
     *
     * @param int $value Count
     * @return MarketplaceWebService_Model_CancelFeedSubmissionsResult instance
     */
    public function withCount($value)
    {
        $this->setCount($value);
        return $this;
    }

    /**
     * Checks if Count is set
     *
     * @return bool true if Count  is set
     */
    public function isSetCount()
    {
        return !is_null($this->fields['Count']['FieldValue']);
    }

    /**
     * Gets the value of the FeedSubmissionInfo.
     *
     * @return array of FeedSubmissionInfo FeedSubmissionInfo
     */
    public function getFeedSubmissionInfoList()
    {
        return $this->fields['FeedSubmissionInfo']['FieldValue'];
    }

    /**
     * Sets the value of the FeedSubmissionInfo.
     *
     * @param mixed FeedSubmissionInfo or an array of FeedSubmissionInfo FeedSubmissionInfo
     * @return this instance
     */
    public function setFeedSubmissionInfoList($feedSubmissionInfo)
    {
        if (!$this->_isNumericArray($feedSubmissionInfo)) {
            $feedSubmissionInfo =  array ($feedSubmissionInfo);
        }
        $this->fields['FeedSubmissionInfo']['FieldValue'] = $feedSubmissionInfo;
        return $this;
    }

    /**
     * Sets single or multiple values of FeedSubmissionInfo list via variable number of arguments.
     * For example, to set the list with two elements, simply pass two values as arguments to this function
     * withFeedSubmissionInfo($feedSubmissionInfo1, $feedSubmissionInfo2)
     *
     * @param FeedSubmissionInfo  $feedSubmissionInfoArgs one or more FeedSubmissionInfo
     * @return MarketplaceWebService_Model_CancelFeedSubmissionsResult  instance
     */
    public function withFeedSubmissionInfo($feedSubmissionInfoArgs)
    {
        foreach (func_get_args() as $feedSubmissionInfo) {
            $this->fields['FeedSubmissionInfo']['FieldValue'][] = $feedSubmissionInfo;
        }
        return $this;
    }

    /**
     * Checks if FeedSubmissionInfo list is non-empty
     *
     * @return bool true if FeedSubmissionInfo list is non-empty
     */
    public function isSetFeedSubmissionInfo()
    {
        return count ($this->fields['FeedSubmissionInfo']['FieldValue']) > 0;
    }

}


text:
maintainer       'Peter Donald'
maintainer_email 'peter@realityforge.org'
license          'Apache 2.0'
description      'Installs/Configures Geoserver application'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.4.0'

supports 'ubuntu'

suggests 'glassfish'
suggests 'tomcat'


text:
import Ember from 'ember';
import layout from 'ember-data-table-light/templates/components/data-table/empty';

/**
 * @class Empty
 * @extends Ember.Component
 */
export default Ember.Component.extend({
  layout,

  message: 'No data to display'
});


text:
package com.github.mateuszwenus.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "satellites")
public class Satellite {

	@Id
	private Long id;
	@ManyToOne
	@JoinColumn(name = "planet_id")
	private Planet planet;
	private String name;

	public Satellite() {
	}

	public Satellite(String name) {
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Planet getPlanet() {
		return planet;
	}

	public void setPlanet(Planet planet) {
		this.planet = planet;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Satellite other = (Satellite) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Satellite [name=" + name + "]";
	}
}


text:
if ! [ -x "$(command -v docker-compose)" ]; then
  echo 'Error: docker-compose is not installed.' >&2
  exit 1
fi

domains=(ruslanskorb.com www.ruslanskorb.com)
rsa_key_size=4096
data_path="./data/certbot"
email="ruslan.skorb@gmail.com" # Adding a valid address is strongly recommended
staging=0 # Set to 1 if you're testing your setup to avoid hitting request limits

if [ -d "$data_path" ]; then
  read -p "Existing data found for $domains. Continue and replace existing certificate? (y/N) " decision
  if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then
    exit
  fi
fi

if [ ! -e "$data_path/conf/options-ssl-nginx.conf" ] || [ ! -e "$data_path/conf/ssl-dhparams.pem" ]; then
  echo "### Downloading recommended TLS parameters ..."
  mkdir -p "$data_path/conf"
  curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf"
  curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem"
  echo
fi

echo "### Creating dummy certificate for $domains ..."
path="/etc/letsencrypt/live/$domains"
mkdir -p "$data_path/conf/live/$domains"
docker-compose -f docker-compose.prod.yml run --rm --entrypoint "\
  openssl req -x509 -nodes -newkey rsa:1024 -days 1\
    -keyout '$path/privkey.pem' \
    -out '$path/fullchain.pem' \
    -subj '/CN=localhost'" certbot
echo

echo "### Starting nginx ..."
docker-compose -f docker-compose.prod.yml up --force-recreate -d nginx
echo

echo "### Deleting dummy certificate for $domains ..."
docker-compose -f docker-compose.prod.yml run --rm --entrypoint "\
  rm -Rf /etc/letsencrypt/live/$domains && \
  rm -Rf /etc/letsencrypt/archive/$domains && \
  rm -Rf /etc/letsencrypt/renewal/$domains.conf" certbot
echo

echo "### Requesting Let's Encrypt certificate for $domains ..."
#Join $domains to -d args
domain_args=""
for domain in "${domains[@]}"; do
  domain_args="$domain_args -d $domain"
done

# Select appropriate email arg
case "$email" in
  "") email_arg="--register-unsafely-without-email" ;;
  *) email_arg="--email $email" ;;
esac

# Enable staging mode if needed
if [ $staging != "0" ]; then staging_arg="--staging"; fi

docker-compose -f docker-compose.prod.yml run --rm --entrypoint "\
  certbot certonly --webroot -w /var/www/certbot \
    $staging_arg \
    $email_arg \
    $domain_args \
    --rsa-key-size $rsa_key_size \
    --agree-tos \
    --force-renewal" certbot
echo

echo "### Reloading nginx ..."
docker-compose -f docker-compose.prod.yml exec nginx nginx -s reload