text:
package org.copperengine.monitoring.client.ui.logs.result;

import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import javafx.util.converter.DateStringConverter;

import org.copperengine.monitoring.client.adapter.GuiCopperDataProvider;
import org.copperengine.monitoring.client.form.filter.FilterResultControllerBase;
import org.copperengine.monitoring.client.ui.logs.filter.LogsFilterModel;
import org.copperengine.monitoring.client.ui.logs.result.LogsResultModel.LogsRowModel;
import org.copperengine.monitoring.client.util.CSSHelper;
import org.copperengine.monitoring.client.util.TableColumnHelper;

public class LogsResultController extends FilterResultControllerBase<LogsFilterModel, LogsResultModel> implements Initializable {
    private final GuiCopperDataProvider copperDataProvider;

    public LogsResultController(GuiCopperDataProvider copperDataProvider) {
        super();
        this.copperDataProvider = copperDataProvider;
    }

    @FXML
    // fx:id="copyButton"
    private Button copyButton; // Value injected by FXMLLoader

    @FXML
    // fx:id="detailstackPane"
    private StackPane detailstackPane; // Value injected by FXMLLoader

    @FXML
    // fx:id="idColumn"
    private TableColumn<LogsRowModel, Date> timeColumn; // Value injected by FXMLLoader

    @FXML
    // fx:id="logConfig"
    private TextArea logConfig; // Value injected by FXMLLoader

    @FXML
    // fx:id="loglevelColumn"
    private TableColumn<LogsRowModel, String> loglevelColumn; // Value injected by FXMLLoader

    @FXML
    // fx:id="occurrenceColumn"
    private TableColumn<LogsRowModel, String> messageColumn; // Value injected by FXMLLoader

    @FXML
    // fx:id="resultTable"
    private TableView<LogsRowModel> resultTable; // Value injected by FXMLLoader

    @FXML
    // fx:id="resultTextarea"
    private TextArea resultTextarea; // Value injected by FXMLLoader

    @FXML
    // fx:id="searchField"
    private TextField searchField; // Value injected by FXMLLoader

    @FXML
    private BorderPane tableBorderPane;

    @FXML
    private Button updateConfig;

    @FXML
    private TableColumn<LogsRowModel, String> locationColumn;

    @Override
    // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
        assert copyButton != null : "fx:id=\"copyButton\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert detailstackPane != null : "fx:id=\"detailstackPane\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert timeColumn != null : "fx:id=\"timeColumn\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert logConfig != null : "fx:id=\"logConfig\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert loglevelColumn != null : "fx:id=\"loglevelColumn\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert messageColumn != null : "fx:id=\"occurrenceColumn\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert resultTable != null : "fx:id=\"resultTable\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert resultTextarea != null : "fx:id=\"resultTextarea\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert searchField != null : "fx:id=\"searchField\" was not injected: check your FXML file 'LogsResult.fxml'.";
        assert tableBorderPane != null;
        assert updateConfig != null;
        assert locationColumn != null;

        resultTable.setRowFactory(new Callback<TableView<LogsRowModel>, TableRow<LogsRowModel>>() {
            @Override
            public TableRow<LogsRowModel> call(TableView<LogsRowModel> param) {
                return new TableRow<LogsRowModel>() {
                    @Override
                    protected void updateItem(LogsRowModel item, boolean empty) {
                        if (item != null) {
                            if ("ERROR".equals(item.level.get())) {
                                this.setStyle("-fx-control-inner-background: " + CSSHelper.toCssColor(Color.rgb(255, 128, 128)) + ";");
                            } else {
                                this.setStyle("");
                            }

                        }
                        super.updateItem(item, empty);
                    }
                };
            }
        });

        loglevelColumn.setCellValueFactory(new Callback<CellDataFeatures<LogsRowModel, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(
                    CellDataFeatures<LogsRowModel, String> p) {
                return p.getValue().level;
            }
        });

        tableBorderPane.setBottom(createTableControls(resultTable));

        timeColumn.setCellValueFactory(new Callback<CellDataFeatures<LogsRowModel, Date>, ObservableValue<Date>>() {
            @Override
            public ObservableValue<Date> call(
                    CellDataFeatures<LogsRowModel, Date> p) {
                return p.getValue().time;
            }
        });
        TableColumnHelper.setConverterCellFactory(timeColumn, new DateStringConverter("dd.MM.yyyy HH:mm:ss,SSS"));

        locationColumn.setCellValueFactory(new Callback<CellDataFeatures<LogsRowModel, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(
                    CellDataFeatures<LogsRowModel, String> p) {
                return p.getValue().locationInformation;
            }
        });
        TableColumnHelper.setTextOverrunCellFactory(locationColumn, OverrunStyle.LEADING_ELLIPSIS);

        messageColumn.setCellValueFactory(new Callback<CellDataFeatures<LogsRowModel, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(
                    CellDataFeatures<LogsRowModel, String> p) {
                return p.getValue().message;
            }
        });
        messageColumn.setCellFactory(new Callback<TableColumn<LogsRowModel, String>, TableCell<LogsRowModel, String>>() {
            @Override
            public TableCell<LogsRowModel, String> call(TableColumn<LogsRowModel, String> param) {
                final TextFieldTableCell<LogsRowModel, String> textFieldTableCell = new TextFieldTableCell<LogsRowModel, String>();
                textFieldTableCell.getStyleClass().add("consoleFont");
                return textFieldTableCell;
            }
        });

        searchField.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (resultTextarea.getText() != null && searchField.getText() != null) {
                    int from = resultTextarea.getText().indexOf(searchField.getText(), resultTextarea.getSelection().getEnd());
                    resultTextarea.selectRange(from, from + searchField.getText().length());

                }
            }
        });

        copyButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Clipboard clipboard = Clipboard.getSystemClipboard();
                final ClipboardContent content = new ClipboardContent();
                content.putString(resultTextarea.getText());
                clipboard.setContent(content);
            }
        });

        timeColumn.prefWidthProperty().bind(resultTable.widthProperty().subtract(3).multiply(0.15));
        loglevelColumn.prefWidthProperty().bind(resultTable.widthProperty().subtract(3).multiply(0.05));
        locationColumn.prefWidthProperty().bind(resultTable.widthProperty().subtract(3).multiply(0.05));
        messageColumn.prefWidthProperty().bind(resultTable.widthProperty().subtract(3).multiply(0.73));

        updateConfig.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                copperDataProvider.updateLogConfig(logConfig.getText());
            }
        });
        logConfig.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                updateConfig.setDisable(false);
            }
        });

        resultTextarea.getStyleClass().add("consoleFont");
        resultTextarea.setWrapText(false);
    }

    @Override
    public URL getFxmlResource() {
        return getClass().getResource("LogsResult.fxml");
    }

    @Override
    public void showFilteredResult(List<LogsResultModel> filteredResult, LogsFilterModel usedFilter) {
        LogsResultModel resultModel = filteredResult.get(0);

        resultTable.getItems().clear();
        setOriginalItems(resultTable, resultModel.logs);

        StringBuilder textresult = new StringBuilder();
        textresult.append("Time");
        textresult.append("\t");
        textresult.append("Level");
        textresult.append("\t");
        textresult.append("message");
        textresult.append("\t");
        textresult.append("Location");
        textresult.append("\n");

        for (LogsRowModel row : resultModel.logs) {
            row.fillString(textresult);
        }
        resultTextarea.setText(textresult.toString());

        logConfig.setText(resultModel.config.get());
        updateConfig.setDisable(true);
    }

    @Override
    public List<LogsResultModel> applyFilterInBackgroundThread(LogsFilterModel filter) {
        return Arrays.asList(copperDataProvider.getLogData(filter.fromToFilterModel.from.get(), filter.fromToFilterModel.to.get(), filter.maxCountFilterModel.getMaxCount()));
    }

    @Override
    public boolean supportsClear() {
        return true;
    }

    @Override
    public void clear() {
        resultTable.getItems().clear();
        resultTextarea.clear();
        logConfig.clear();
    }

}


text:
package io.agora.contract.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.util.Log;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.update.BmobUpdateAgent;
import io.agora.contract.LoginActivity;
import io.agora.openlive.R;
import io.agora.openlive.ui.BaseActivity;
import io.agora.openlive.ui.HomeActivity;

/**
 * File Name:
 * Author:      ruan
 * Write Dates: 2017/7/7
 * Description:
 */

public class SplaseActivity extends BaseActivity {

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splase);
    }

    @Override
    protected void initUIandEvent() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //两秒后才执行到这里
                //执行在主线程中
                Intent intent;
                BmobUser bmobUser = BmobUser.getCurrentUser();
                if(bmobUser != null){
                    // 允许用户使用应用
                    intent = new Intent(SplaseActivity.this, HomeActivity.class);
                    startActivity(intent);
                }else{
                    //缓存用户对象为空时, 可打开用户注册界面…
                    intent = new Intent(SplaseActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

                finish();
                Log.e("Spalse", "当前线程名称==" + Thread.currentThread().getName());
            }
        }, 2000);

    }

    @Override
    protected void deInitUIandEvent() {

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests\Feature\Account;

use App\Models\Sys\Notification;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class DashboardTest extends TestCase
{
    use DatabaseTransactions;

    public function testItRedirectsToDashboard()
    {
        Notification::query()->delete();

        $this->actingAs($this->user)
            ->get(route('dashboard'))
            ->assertRedirect(route('mship.manage.dashboard'));
    }
}


text:
require 'spec_helper'

describe Issuu::IssuuExceptionManager do

  describe "Invalid field exception" do
    it "should raise an exception with the invalid field" do
      manager = Issuu::IssuuExceptionManager.new({'code'=>'201', 'message' => 'Invalid field format', 'field' => 'apiKey'})
      expect {manager.raise_error}.should raise_error(Issuu::IssuuException, '#201 Invalid field format: \'apiKey\'')
    end
  end

  describe "Authentication exception" do
    it "should raise an exception with the invalid field" do
      manager = Issuu::IssuuExceptionManager.new({'code'=>'009', 'message' => 'Authentication required'})
      expect {manager.raise_error}.should raise_error(Issuu::IssuuException, '#009 Authentication required')
    end
  end
end


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * AddressRdvRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AddressRdvRepository extends EntityRepository
{

    public function findAllNotChecked(){
        $query = $this->createQueryBuilder('a')
                    ->where('a.name IS NOT NULL')
                    ->andWhere('a.checkedForSuggestion IS NULL');

        return $query->getQuery()->getResult();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ValidationUnits
{
    public class ValidatorSettings
    {
        /// <summary>
        /// Each property's default value is true
        /// </summary>
        public ValidatorSettings()
        {
            UseDataAnnotationValidator = true;
            IncludeChildrenInDataAnnotationValidation = true;
            StopValidatingAtFirstError = true;
        }

        public static ValidatorSettings CreateDefaultValidatorSettings()
        {
            return new ValidatorSettings();
        }

        /// <summary>
        /// Default value is true
        /// </summary>
        public bool UseDataAnnotationValidator { get; set; }

        /// <summary>
        /// Default value is true
        /// </summary>
        public bool IncludeChildrenInDataAnnotationValidation { get; set; }

        /// <summary>
        /// Default value is true
        /// </summary>
        public bool StopValidatingAtFirstError { get; set; }
    }
}


text:
<!DOCTYPE html>

	<title>vue-outside-events v-click-outside</title>

	<link href="style.css" type="text/css" rel="stylesheet" />
	<link href="theme.css" type="text/css" rel="stylesheet" />

v-click-outside, passing an object

Click around... see the colors change and labels pop. See the data value "{{static}}" get passed with the directive.

            Note: Vue Directives can have data bound to them once, at run-time when they are created. If you bind a variable to the directive and then change the variable, the directive will maintain the old value when it calls the handler.

		  test

			  a

				  b

			  c
			  d
			  e

			  f

				  g
				  h
				  i

v-click-outside example

		<template>

		</template>


text:
from commonTools.ui.Qt import QtCore, QtGui, QtWidgets

import pipeCore.common as pcCommon
import pipeCore.folderPaths as folderPaths
import pipeCore.dbTableNumbers as dbTableNums
from pipeCore.ui.browseBaseWidget import BrowseBaseWidget
import pipeCore.ui.dbQtModels as dbQtModels

class BrowseShotsWidget(BrowseBaseWidget):
	""" A widget displaying the shots in the database for a particular sequence
	Kwargs:
		parent (QWidget- default None): Optional parent widget
		client (str- default None): Optional initial client to browse to
		project (str- default None): Optional initial project to browse to
		sequence (str- default None): Optional initial sequence to browse to
	"""
	def __init__(self, parent=None, client=None, project=None, sequence=None, workInShot=True, adjustSelectedRowWidth=True):
		self.__adjustSelectedRowWidth = adjustSelectedRowWidth
		super(BrowseShotsWidget, self).__init__(parent=parent, client=client, project=project, clientInfoVisible=False)
		self.sequence = sequence or ''
		self._workInShot = workInShot
		self._keyColumnNames = ['SeqCode', 'ShotCode']
		self._displayGifs = True
		self.__connectSignals()

	def _getBrowseQueryModel(self):
		""" Return the SqlQueryModel to use to fill the browse table
		Returns:
			SqlQuereyModel: The model to use to fill the browse table
		"""
		if not self._workInShot:
			model = dbQtModels.getShotsModel(self.client, self.project, adjustColumns=True, onlyGeneral=True)
		if self.sequence == pcCommon.ALL_SEQUENCES:
			model = dbQtModels.getShotsModel(self.client, self.project, adjustColumns=True)
		else:
			model = dbQtModels.getShotsModel(self.client, self.project, sequenceName=self.sequence, adjustColumns=True)
		if model is not None:
			model.setDisplayGifs(self._displayGifs)
		return model

	def setSequence(self, sequence):
		""" Set the sequence to browse shots under
		Args:
			sequence (str): The sequence
		"""
		self.sequence = sequence

	def setWorkInShot(self, workInShot):
		""" Set whether to browse the non shot work
		Args:
			workInShot (bool): The value
		"""
		self._workInShot = workInShot

	def setDisplayGifs(self, displayGifs):
		""" Sets a parameter to say if the thumbnails column should display GIFs of the shots when available
		Args:
			displayGifs (bool): True if they should be displayed
		"""
		self._displayGifs = displayGifs
		if self.browseTable.model() is not None:
			self.browseTable.model().setDisplayGifs(self._displayGifs)
			self.updateData()

	def __connectSignals(self):
		""" Connect any signals for UI widgets
		"""
		self.selectionChange.connect(self._shotSelectionChanged)
		self.clicked.connect(self._shotClicked)
		self.doubleClicked.connect(self._shotDoubleClicked)

	def _shotSelectionChanged(self):
		""" Event that fires when the selection changes
		"""
		if not self._initialised:
			return
		if self.__adjustSelectedRowWidth and self.browseTable.model() is not None:
			self.browseTable.model().setRowHeights(self)

	def _shotClicked(self, index):
		""" Event that fires when a cell is clicked
		"""
		if index.column() == self.browseTable.model().getThumbnailColumn() and self._displayGifs:
			shotId = self.browseTable.model().data(self.browseTable.model().createIndex(index.row(), dbTableNums.SH_shot_id), adjustIndex=False)
			shotName = self.browseTable.model()._database._getOneStrFieldFromAnother('shot', 'shot_id', shotId, dbTableNums.SH_ShotCode)
			sequenceId = self.browseTable.model().data(self.browseTable.model().createIndex(index.row(), dbTableNums.SH_sequence_id), adjustIndex=False)
			sequenceName = self.browseTable.model()._database._getOneStrFieldFromAnother('sequence', 'sequence_id', sequenceId, dbTableNums.SE_SequenceCode)
			if self.browseTable.model()._database.getShotThumbnail(self.client, self.project, sequenceName, shotName):
				# Play the GIF which is displaying for this cell
				self.browseTable.edit(index)

	def _shotDoubleClicked(self, index):
		""" Event that fires when a cell is double clicked
		"""
		if index.column() == self.browseTable.model().getThumbnailColumn():
			if self._displayGifs:
				shotId = self.browseTable.model().data(self.browseTable.model().createIndex(index.row(), dbTableNums.SH_shot_id), adjustIndex=False)
				shotName = self.browseTable.model()._database._getOneStrFieldFromAnother('shot', 'shot_id', shotId, dbTableNums.SH_ShotCode)
				sequenceId = self.browseTable.model().data(self.browseTable.model().createIndex(index.row(), dbTableNums.SH_sequence_id), adjustIndex=False)
				sequenceName = self.browseTable.model()._database._getOneStrFieldFromAnother('sequence', 'sequence_id', sequenceId, dbTableNums.SE_SequenceCode)
				if self.browseTable.model()._database.getShotThumbnail(self.client, self.project, sequenceName, shotName):
					# The thumbnail GIF is displaying for this cell
					return
			# The storyboard image is displaying for this cell
			storyboardPath = folderPaths.getStoryboardDir(self.client, self.project)
			fileSelected = QtWidgets.QFileDialog.getOpenFileName(None, "Select Image", "%s/Thumbnails" % storyboardPath, "Image Files (*.png *.jpg *.jpeg *.bmp)")[0]
			if fileSelected:
				index.model().setData(index, fileSelected, QtCore.Qt.EditRole)

	def __getSequencesAndShots(self, keys):
		""" Get the list of sequences and shots for the rows that are selected
		Args:
			keys (list of str): The keys of the rows to return the sequence and shot for
		Returns:
			list of str: The selected sequences
			list of str: The selected shots
		"""
		sequences = []
		shots = []
		for rowName in keys:
			parts = rowName.split(':')
			if len(parts) == 2:
				sequences.append(parts[0])
				shots.append(parts[1])
		return sequences, shots

	def allSequencesAndShots(self):
		""" Get the list of sequences and shots for all rows
		Returns:
			list of str: The selected sequences
			list of str: The selected shots
		"""
		return self.__getSequencesAndShots(self.rowKeys)

	def selectedSequencesAndShots(self):
		""" Get the list of sequences and shots for the rows that are selected
		Returns:
			list of str: The selected sequences
			list of str: The selected shots
		"""
		return self.__getSequencesAndShots(self._selectedKeys())

	def selectedShots(self):
		""" Gets the name of the shot(s) currently selected in the table
		Returns:
			str: The name of the selected shot(s)
		"""
		_, shots = self.selectedSequencesAndShots()
		return shots

	def selectRowFromSequenceAndShotName(self, sequenceName, shotName):
		""" Select the row of the shot with the given name
		Args:
			sequenceName (str): The name of the sequenceName
			shotName (str): The name of the shotName
		"""
		rowName = '%s:%s' % (sequenceName, shotName)
		if rowName in self.rowKeys:
			self.selectRows([self.rowKeys.index(rowName)])


text:
package org.elasticsearch.test.client.transport;

import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse;
import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.ConnectionProfile;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.TransportStats;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

abstract class FailAndRetryMockTransport<Response extends TransportResponse> implements Transport {

    private final Random random;
    private final ClusterName clusterName;

    private boolean connectMode = true;

    private TransportService transportService;

    private final AtomicInteger connectTransportExceptions = new AtomicInteger();
    private final AtomicInteger failures = new AtomicInteger();
    private final AtomicInteger successes = new AtomicInteger();
    private final Set<DiscoveryNode> triedNodes = new CopyOnWriteArraySet<>();
    private final AtomicLong requestId = new AtomicLong();

    FailAndRetryMockTransport(Random random, ClusterName clusterName) {
        this.random = new Random(random.nextLong());
        this.clusterName = clusterName;
    }

    protected abstract ClusterState getMockClusterState(DiscoveryNode node);

    @Override
    public Connection getConnection(DiscoveryNode node) {
        return new Connection() {
            @Override
            public DiscoveryNode getNode() {
                return node;
            }

            @Override
            public void sendRequest(long requestId, String action, TransportRequest request, TransportRequestOptions options)
                throws IOException, TransportException {

                //we make sure that nodes get added to the connected ones when calling addTransportAddress, by returning proper nodes info
                if (connectMode) {
                    if (TransportLivenessAction.NAME.equals(action)) {
                        TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
                        transportResponseHandler.handleResponse(new LivenessResponse(ClusterName.CLUSTER_NAME_SETTING.
                            getDefault(Settings.EMPTY),
                            node));
                    } else if (ClusterStateAction.NAME.equals(action)) {
                        TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
                        ClusterState clusterState = getMockClusterState(node);
                        transportResponseHandler.handleResponse(new ClusterStateResponse(clusterName, clusterState, 0L));
                    } else {
                        throw new UnsupportedOperationException("Mock transport does not understand action " + action);
                    }
                    return;
                }

                //once nodes are connected we'll just return errors for each sendRequest call
                triedNodes.add(node);

                if (random.nextInt(100) > 10) {
                    connectTransportExceptions.incrementAndGet();
                    throw new ConnectTransportException(node, "node not available");
                } else {
                    if (random.nextBoolean()) {
                        failures.incrementAndGet();
                        //throw whatever exception that is not a subclass of ConnectTransportException
                        throw new IllegalStateException();
                    } else {
                        TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
                        if (random.nextBoolean()) {
                            successes.incrementAndGet();
                            transportResponseHandler.handleResponse(newResponse());
                        } else {
                            failures.incrementAndGet();
                            transportResponseHandler.handleException(new TransportException("transport exception"));
                        }
                    }
                }
            }

            @Override
            public void close() throws IOException {

            }
        };
    }

    @Override
    public Connection openConnection(DiscoveryNode node, ConnectionProfile profile) throws IOException {
        return getConnection(node);
    }

    protected abstract Response newResponse();

    public void endConnectMode() {
        this.connectMode = false;
    }

    public int connectTransportExceptions() {
        return connectTransportExceptions.get();
    }

    public int failures() {
        return failures.get();
    }

    public int successes() {
        return successes.get();
    }

    public Set<DiscoveryNode> triedNodes() {
        return triedNodes;
    }

    @Override
    public void setTransportService(TransportService transportServiceAdapter) {
        this.transportService = transportServiceAdapter;
    }

    @Override
    public BoundTransportAddress boundAddress() {
        return null;
    }

    @Override
    public TransportAddress[] addressesFromString(String address, int perAddressLimit) throws UnknownHostException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean nodeConnected(DiscoveryNode node) {
        return false;
    }

    @Override
    public void connectToNode(DiscoveryNode node, ConnectionProfile connectionProfile,
                              CheckedBiConsumer<Connection, ConnectionProfile, IOException> connectionValidator)
        throws ConnectTransportException {

    }

    @Override
    public void disconnectFromNode(DiscoveryNode node) {

    }

    @Override
    public Lifecycle.State lifecycleState() {
        return null;
    }

    @Override
    public void addLifecycleListener(LifecycleListener listener) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void start() {}

    @Override
    public void stop() {}

    @Override
    public void close() {}

    @Override
    public Map<String, BoundTransportAddress> profileBoundAddresses() {
        return Collections.emptyMap();
    }

    @Override
    public long newRequestId() {
        return requestId.incrementAndGet();
    }

    @Override
    public TransportStats getStats() {
        throw new UnsupportedOperationException();
    }
}


text:
if defined?(::H) && ::H != Hexp::Node
  $stderr.puts "WARN: H is already defined, Hexp H[] shorthand not available"
else
  module H
    def self.[](*args)
      if args.first.is_a? Symbol
        Hexp::Node[*args]
      else
        Hexp::List[*args]
      end
    end
  end
end


text:
"""
Remove formatting from abstract
"""

from panflute import *

format_element = (Emph, Strong, Strikeout, Subscript, Superscript, SmallCaps)

def remove_format(e, doc):
    if isinstance(e, format_element):
        return Span(*e.content)

def remove_all(e, doc):
    # This filters removes formatting from all of metadata
    # Not used; kept here as a comparison
    if isinstance(e, MetaValue):
        return e.walk(remove_format, doc)

def remove_abstract(e, doc) :
    if isinstance(e, MetaMap) and 'abstract' in e.content:
        # Note that even if we don't <return e>, it has already been modified
        e.content['abstract'].walk(remove_format, doc)

if __name__ == '__main__':
    toJSONFilter(remove_abstract)


text:
<?php

namespace Starmind\Pygments\Formatter\Test;

use Starmind\Pygments\Exception\CommandException;
use Starmind\Pygments\Formatter\Html;

class HtmlTest extends \PHPUnit_Framework_TestCase
{
    public function testGetDefaultCliParameters()
    {
        $formatter = new Html();

        $this->assertEquals(
            '-f html -P style=default -P cssclass=highlight -P linenos=1',
            $formatter->getCliParameters()
        );
    }

    public function testGetFormat()
    {
        $formatter = new Html();

        $this->assertEquals(
            'html',
            $formatter->getFormat()
        );
    }

    public function testGenerateStyles()
    {
        $pygmentizeMock = $this->getMockBuilder('Starmind\Pygments\Pygmentize')
            ->disableOriginalConstructor()
            ->getMock();

        $pygmentizeMock->expects($this->any())
            ->method('executeCommand')
            ->will($this->returnValue('body { display: none; }'));

        $formatter = new Html();

        $this->assertEquals(
            'body { display: none; }',
            $formatter->generateStyles($pygmentizeMock)
        );
    }

    public function testGenerateStylesIncludeStyleTag()
    {
        $pygmentizeMock = $this->getMockBuilder('Starmind\Pygments\Pygmentize')
            ->disableOriginalConstructor()
            ->getMock();

        $pygmentizeMock->expects($this->any())
            ->method('executeCommand')
            ->will($this->returnValue('body { display: none; }'));

        $formatter = new Html();

        $this->assertEquals(
            "<style>\nbody { display: none; }\n</style>",
            $formatter->generateStyles($pygmentizeMock, true)
        );
    }

    public function testGenerateStylesError()
    {
        $pygmentizeMock = $this->getMockBuilder('Starmind\Pygments\Pygmentize')
            ->disableOriginalConstructor()
            ->getMock();

        $pygmentizeMock->expects($this->any())
            ->method('executeCommand')
            ->will($this->throwException(new CommandException()));

        $formatter = new Html();

        $this->assertEquals(
            '/* Could not generate Styles */',
            $formatter->generateStyles($pygmentizeMock, true)
        );
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Open SCAP Library: _sexp-output.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Open SCAP Library

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

src

OVAL

probes

SEAP

_sexp-output.h

    1

   22

   23 #pragma once

   24 #ifndef _SEXP_OUTPUT_H

   25 #define _SEXP_OUTPUT_H

   26

   27 #include <stddef.h>

   28 #include <stdint.h>

   29 #include "public/sexp-types.h"

   30 #include "public/sexp-output.h"

   31 #include "_sexp-manip.h"

   32 #include "../../../common/util.h"

   33

   34 OSCAP_HIDDEN_START;

   35

   36 struct SEXP_ostate {

   37         SEXP_t        *s_exp;   /* ref to the S-exp that we are writing */

   38         SEXP_lstack_t *l_stack; /* list stack */

   39         uint32_t      *p_stack; /* list position stack */

   40         uint8_t       *s_part;  /* S-exp part */

   41         size_t        *s_pos;   /* S-exp position */

   42 };

   43

   44 OSCAP_HIDDEN_END;

   45

   46 #endif /* _SEXP_OUTPUT_H */

SEXP_lstack_t

Definition: _sexp-manip.h:36

SEXP_ostate

Definition: _sexp-output.h:36

SEXP

Definition: sexp-types.h:82

<address class="footer">
Generated by

 1.8.6
</address>


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class Boss : MonoBehaviour {

    [Header("Boss Requirements")]
    public EnemyHP EnemyHPScript;
    public GameObject BossGUI;
    public GameObject Projecttilespawn;
    public Image Healthbar;
    public Image FadeOutScreen;
    public GameObject Player;
    public AudioClip[] BossFxs;
    public AudioClip[] BossThemes;
    public AudioSource PlayerMusic;
    private AudioSource AudioSource;
    public float AudioVolume = 0.5f;

    [Header("Boss Objects")]
    public GameObject ShieldObject;
    private Transform HomeLocation;
    public Transform BossMissle;
    public Transform RangeSkeleton;
    public Transform MeleeSkeleton;
    public Transform Slime;

    private int Fase = 1;
    private int AttackSelector = 0;
    private int PreviousAttack = 0;
    private float NextAttackDelay = 0;
    private float NextAttackTime = 0;
    private float AttackTimeWait = 0;
    private float AttackTime = 0;
    private bool CanAttack = true;

    [Header("Boss Stats")]
    public float BossHP = 1000;
    private float OldBossHP = 0;
    private float BossCurrentHP = 0;
    private float Switch1HP = 1200;
    private float Switch2HP = 600;

    private float AttackSpeed = 1;

    public bool Active = false;
    private bool setgui = false;
    public bool Beaten = false;
    private bool Invincible = false;
    private int SpawnedEnemiesActive = 0;

    public float TimeSlowValue = 1;
    private float FadeOutValue = 0;
    public bool FadeOut = false;

    private bool GoToFinishScreen = false;
    private int SoundSelector = 0;

    private int CurrentRadius = 0;
    private int CurrentIndex = 0;
    private float SpawnRadius = 2.0f;
    private int RadiusDistance = 0;
    private int SpawnAmount = 0;

    // Use this for initialization
    void Start () {
        BossCurrentHP = BossHP;
        OldBossHP = BossHP;

        if (AudioSource == null) { AudioSource = GetComponent<AudioSource>(); }
    }

	// Update is called once per frame
	void Update () {
        if (Active && !Beaten)
        {
            if (setgui)
            {
                setgui = false;
                BossGUI.SetActive(true);
                LookAt();
            }
            CheckHealth();
            Attack();
        }
        if (Active && Beaten)
        {
            Defeaten();
        }

    }

    void CheckHealth()
    {
        if (OldBossHP != BossHP) { OldBossHP = BossHP; BossCurrentHP = BossHP; }
        BossCurrentHP = EnemyHPScript.GetHP();
        switch (Fase)
        {
            case 1:
                if (BossCurrentHP < Switch1HP)
                {
                    BossCurrentHP = Switch1HP;
                    Fase++;
                    AttackSpeed = 0.65f;
                    SoundSelector = 1;
                    PlayerMusic.Stop();
                    PlayerMusic.clip = BossThemes[SoundSelector];
                    PlayerMusic.Play();
                    Debug.Log("[BOSS] Fase 1 beaten.");
                }
                break;
            case 2:
                if (BossCurrentHP < Switch2HP)
                {
                    BossCurrentHP = Switch2HP;
                    Fase++;
                    AttackSpeed = 0.35f;
                    SoundSelector = 2;
                    PlayerMusic.Stop();
                    PlayerMusic.clip = BossThemes[SoundSelector];
                    PlayerMusic.Play();
                    Debug.Log("[BOSS] Fase 2 beaten.");
                }
                break;
            case 3:
                if (BossCurrentHP <= 0)
                {
                    Beaten = true;
                    BossCurrentHP = 0;
                    Fase++;
                    FadeOut = true;
                    BossGUI.SetActive(false);

                    PlayerMusic.Stop();
                    SoundSelector = 4;
                    AudioSource.PlayOneShot(BossFxs[SoundSelector], AudioVolume);
                    Debug.Log("[BOSS] Fase 3 beaten.");
                }
                break;
        }

        Healthbar.fillAmount = BossCurrentHP / BossHP;
    }

    void Defeaten()
    {
        // Animation

        // Slowdown
        if (TimeSlowValue > 0.25)
        {
            Time.fixedDeltaTime = TimeSlowValue;
            Time.timeScale = TimeSlowValue;
            TimeSlowValue -= 0.01f;
            if (TimeSlowValue < 0.25) { TimeSlowValue = 0.25f; SceneManager.LoadScene(0); }
        }
        if (FadeOut)
        {
            if (FadeOutValue < 1)
            {
                FadeOutValue -= 0.15f * Time.deltaTime;
                Color ne = FadeOutScreen.color;
                ne.a = FadeOutValue;
                FadeOutScreen.color = ne;
            }
            if (FadeOutValue >= 1) { GoToFinishScreen = true; }
        }
        if (GoToFinishScreen)
        {
            SceneManager.LoadScene(0);
        }
    }

    void LookAt()
    {
        Vector3 direction = (Player.transform.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(direction);
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation,  10);
        transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0);
    }

    void Attack()
    {
        if (CanAttack)
        {
            Debug.Log("[BOSS] Rolling for new attack");
            CanAttack = false;
            switch (Fase)
            {
                case 1:
                    do { AttackSelector = Random.Range(1, 3); } while (AttackSelector == PreviousAttack);
                    break;
                case 2:
                    do { AttackSelector = Random.Range(1, 4); } while (AttackSelector == PreviousAttack);
                    break;
                case 3:
                    do { AttackSelector = Random.Range(1, 5); } while (AttackSelector == PreviousAttack);
                    break;
            }
            PreviousAttack = AttackSelector;
            if (BossFxs.Length > 0 && AudioSource && !AudioSource.isPlaying)
            {
                SoundSelector = Random.Range(1, 4);
                AudioSource.PlayOneShot(BossFxs[SoundSelector], AudioVolume);
            }
            switch (AttackSelector)
            {
                case 1:
                    AttackTime = 3.0f * AttackSpeed;
                    NextAttackTime = 2.5f;
                    StartCoroutine(MagicSpell(AttackTime));
                    break;
                case 2:
                    AttackTime = 2.0f * AttackSpeed;
                    NextAttackTime = 2.5f;
                    StartCoroutine(QuickShield(AttackTime));
                    break;
                case 3:
                    AttackTime = 2.5f * AttackSpeed;
                    NextAttackTime = 1;
                    StartCoroutine(CircleMissleAttack(AttackTime));
                    break;
                case 4:
                    AttackTime = 5 * AttackSpeed;
                    NextAttackTime = 5;
                    StartCoroutine(MultipleCircleMissle(AttackTime));

                    break;
                case 5:
                    break;
                case 6:
                    //AttackTime = 5;
                    //NextAttackTime = 5;
                    //StartCoroutine(SpawnRangeSkeletons(AttackTime));
                    break;
                case 7:
                    break;
                case 8:
                    break;
                default:
                    Debug.LogError("[BOSS] Got an invalid AttackSelector number:" + AttackSelector);
                    CanAttack = true;
                    break;
            }
            AttackTimeWait = Time.time + AttackTime;
            NextAttackDelay = NextAttackTime + AttackTimeWait;
            //Debug.Log("Got Attack: " + AttackSelector + " with AT: " + AttackTime + "ATW: " + AttackTimeWait + " NAT: " + NextAttackTime + " NAD: " + NextAttackDelay);
        }
        else
        {
            if (Time.time > NextAttackDelay)
            {
                CanAttack = true;
            }
            SoundSelector = Random.Range(1, 101);
            if (SoundSelector < 5 && !AudioSource.isPlaying)
            {
                if (BossFxs.Length > 0 && AudioSource)
                {
                    SoundSelector = Random.Range(1, 4);
                    AudioSource.PlayOneShot(BossFxs[SoundSelector], AudioVolume);
                }
            }

        }
    }

    Vector3 CalcCircle(Vector3 center, float radius, int angle)
    {
        float ang = angle;
        Vector3 pos;
        pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
        pos.y = center.y;
        pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
        return pos;
    }

    int CalcDistance(int input)
    {
        int am = input;
        int calc = 360 / am;
        return calc;
    }

    IEnumerator MagicSpell(float attacktime)
    {
        Debug.Log("[BOSSATTACK] Cast MagicSpell with attacktime " + attacktime);
        for (int i = 0; i < 3; i++)
        {
            for (int o = 0; o < 10; o++)
            {
                LookAt();
                yield return new WaitForSeconds(0.1f);
            }
            Transform Ball = (Transform)Instantiate(BossMissle, Projecttilespawn.transform.position + Projecttilespawn.transform.forward , transform.rotation);
            Ball.GetComponent<HitRegistrator>().SetSettings(
                4,
                1,
                10,
                5,
                true);
        }
        Debug.Log("Finished");
        yield return new WaitForSeconds(attacktime);
    }

    IEnumerator QuickShield(float attacktime)
    {
        if (ShieldObject.activeSelf == false) {
            ShieldObject.SetActive(true);
            EnemyHPScript.SetIsInvincible(true);
        }
        LookAt();
        Debug.Log("[BOSSATTACK] Cast QuickShield with attacktime " + attacktime);
        yield return new WaitForSeconds(attacktime);
        ShieldObject.SetActive(false);
        EnemyHPScript.SetIsInvincible(false);
        yield return new WaitForSeconds(0);
    }

    IEnumerator SpawnRangeSkeletons(float attacktime)
    {
        SpawnAmount = 6;
        CurrentIndex = 1;
        CurrentRadius = 0;
        SpawnRadius = 8;
        RadiusDistance = CalcDistance(SpawnAmount);
        for (int i = 0; i < SpawnAmount; i++)
        {
            Vector3 Calcpos = CalcCircle(transform.position, SpawnRadius, CurrentRadius);

            Transform Skeleton = (Transform)Instantiate(RangeSkeleton, Calcpos, Quaternion.identity);
            Skeleton.Rotate(0, CurrentRadius, 0, Space.World);

            if (CurrentRadius != 360)
            {
                CurrentRadius = CurrentIndex * RadiusDistance;
                CurrentIndex++;
            }
        }

        Debug.Log("[BOSSATTACK] Cast SpawnRangeSkeletons with attacktime " + attacktime);
        yield return new WaitForSeconds(attacktime);
    }

    IEnumerator CircleMissleAttack(float attacktime)
    {

        SpawnAmount = 6;
        CurrentIndex = 1;
        CurrentRadius = 0;
        SpawnRadius = 2;
        RadiusDistance = CalcDistance(SpawnAmount);
        for (int i = 0; i < SpawnAmount;i++)
        {
            Vector3 Calcpos = CalcCircle(transform.position, SpawnRadius, CurrentRadius);

            Transform Ball = (Transform)Instantiate(BossMissle, Calcpos, transform.rotation);
            Ball.Rotate(0, CurrentRadius, 0, Space.World);
            Ball.GetComponent<HitRegistrator>().SetSettings(4,
                1,
                10,
                5,
                true);

            if (CurrentRadius != 360)
            {
                CurrentRadius = CurrentIndex * RadiusDistance;
                CurrentIndex++;
            }
        }
        Debug.Log("[BOSSATTACK] Cast CircleMissleAttack with attacktime " + attacktime + " and SpawnAmount: " + SpawnAmount);
        yield return new WaitForSeconds(attacktime);
    }

    IEnumerator MultipleCircleMissle(float attacktime)
    {
        for (int o = 0; o < 5; o++)
        {
            SpawnAmount = 6;
            CurrentIndex = 1;
            CurrentRadius = 0;
            SpawnRadius = 2;
            RadiusDistance = CalcDistance(SpawnAmount);
            for (int i = 0; i < SpawnAmount; i++)
            {
                Vector3 Calcpos = CalcCircle(transform.position, SpawnRadius, CurrentRadius);

                Transform Ball = (Transform)Instantiate(BossMissle, Calcpos, Quaternion.identity);
                Ball.Rotate(0, CurrentRadius, 0, Space.World);
                Ball.GetComponent<HitRegistrator>().SetSettings(
                4,
                1,
                10,
                5,
                true);

                if (CurrentRadius != 360)
                {
                    CurrentRadius = CurrentIndex * RadiusDistance;
                    CurrentIndex++;
                }
                LookAt();
            }
            yield return new WaitForSeconds(0.5f);
        }

        Debug.Log("[BOSSATTACK] Cast CircleMissleAttack with attacktime " + attacktime + " and SpawnAmount: " + SpawnAmount);
        yield return new WaitForSeconds(attacktime);

    }

    IEnumerator MultipleCircleMisslebroken(float attacktime)
    {
        int rings = 5;// Random.Range(2, 6);
        int ringsdis = CalcDistance(rings);
        int ringindex = 1;
        SpawnRadius = 2;
        for (int s = 0; s < rings; s++)
        {
            SpawnAmount = 6;
            CurrentIndex = 1;

            if (ringindex != 1)
            {
                int curin = ringindex - 1;
                int added = curin * ringsdis;
                CurrentRadius += added;
                if (CurrentRadius > 360) { CurrentRadius = CurrentRadius - 360; }
            } else
            {
                CurrentRadius = 0;
            }

            RadiusDistance = CalcDistance(SpawnAmount);
            for (int i = 0; i < SpawnAmount; i++)
            {
                Vector3 Calcpos = CalcCircle(transform.position, SpawnRadius, CurrentRadius);

                Transform Ball = (Transform)Instantiate(BossMissle, Calcpos, Quaternion.identity);
                Ball.Rotate(0, CurrentRadius, 0, Space.World);
                Ball.GetComponent<HitRegistrator>().SetSettings(4, 5, 25, Vector3.zero, true);

                if (ringindex < 2)
                {
                    if (CurrentRadius != 360)
                    {
                        CurrentRadius = CurrentIndex * RadiusDistance;
                        CurrentIndex++;
                    }
                }
            }
            transform.Rotate(0, ringsdis, 0, Space.World);
            ringindex++;
            yield return new WaitForSeconds(0.33f);
        }

        Debug.Log("[BOSSATTACK] Cast CircleMissleAttack with attacktime " + attacktime + " and SpawnAmount: " + SpawnAmount);
        yield return new WaitForSeconds(attacktime);

    }

    public void SetBossActive()
    {
        setgui = true;
        Active = true;
        if (EnemyHPScript && BossGUI && Healthbar && Player)
        {
            EnemyHPScript.SetHP(BossHP);
            EnemyHPScript.SetIsBoss(true);

            Healthbar.fillAmount = 1;
            HomeLocation = transform;
            if (Active)
            {
                BossGUI.SetActive(true);
                LookAt();
            }

        }
        else
        {
            Active = false;
            Debug.LogWarning("BossFight couldn't start, assign objects!");
        }
    }
}


text:
package ru.shutoff.cgstarter;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

import java.io.IOException;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public abstract class HttpTask {

    final static String userAgent = System.getProperty("http.agent");
    public static final OkHttpClient client = createClient();
    AsyncTask<Object, Void, String> bgTask;
    String error_text;
    boolean canceled;

    static OkHttpClient createClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request requestWithUserAgent = originalRequest.newBuilder()
                                .removeHeader("User-Agent")
                                .addHeader("User-Agent", userAgent)
                                .build();
                        return chain.proceed(requestWithUserAgent);
                    }
                }).build();
        return client;
    }

    static String request(Object... params) throws Exception {
        String url = params[0].toString();
        String data = "";
        int last_param = 1;
        for (; ; last_param++) {
            if (!url.contains("$" + last_param))
                break;
        }
        for (int i = 1; i < last_param; i++) {
            url = url.replace("$" + i, URLEncoder.encode(params[i].toString(), "UTF-8"));
        }
        for (; last_param + 1 < params.length; last_param += 2) {
            if (params[last_param + 1] == null)
                continue;
            url += "&" + params[last_param].toString();
            url += "=" + URLEncoder.encode(params[last_param + 1].toString(), "UTF-8");
        }

        Request.Builder builder = new Request.Builder().url(url);

        Request request = builder.build();
        Response response = client.newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            Log.v("http", url);
            if (data != null)
                Log.v("data", data);
            throw new Exception(response.message());
        }
        Reader reader = response.body().charStream();
        char[] arr = new char[8 * 1024];
        StringBuilder buffer = new StringBuilder();
        int numCharsRead;
        while ((numCharsRead = reader.read(arr, 0, arr.length)) != -1) {
            buffer.append(arr, 0, numCharsRead);
        }
        return buffer.toString();
    }

    abstract void result(String res);

    abstract void error(String error);

    void execute(Object... params) {
        if (bgTask != null)
            return;
        bgTask = new AsyncTask<Object, Void, String>() {
            @Override
            protected String doInBackground(Object... params) {
                try {
                    return request(params);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    error_text = ex.getLocalizedMessage();
                    if (error_text != null) {
                        int pos = error_text.indexOf(":");
                        if (pos > 0)
                            error_text = error_text.substring(0, pos);
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(String res) {
                bgTask = null;
                if (canceled) {
                    canceled = false;
                    return;
                }
                if (res != null) {
                    try {
                        result(res);
                        return;
                    } catch (Exception ex) {
                        if (error_text == null) {
                            String msg = ex.getLocalizedMessage();
                            if (msg == null)
                                msg = ex.getMessage();
                            if (msg == null)
                                msg = ex.toString();
                            error_text = msg;
                        }
                        ex.printStackTrace();
                    }
                }
                error(error_text);
            }
        };
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                bgTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
            } else {
                bgTask.execute(params);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            error(ex.getLocalizedMessage());
        }
    }

    void cancel() {
        canceled = true;
    }

}


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

namespace NuGet
{
    public class PackageSorter : PackageWalker
    {
        private IPackageRepository _repository;
        private IList<IPackage> _sortedPackages;

        protected override bool RaiseErrorOnCycle
        {
            get
            {
                return false;
            }
        }

        protected override bool IgnoreWalkInfo
        {
            get
            {
                return true;
            }
        }

        protected override bool SkipDependencyResolveError
        {
            get
            {
                return true;
            }
        }

        protected override void OnAfterPackageWalk(IPackage package)
        {
            base.OnAfterPackageWalk(package);

            _sortedPackages.Add(package);
        }

        protected override IPackage ResolveDependency(PackageDependency dependency)
        {
            return _repository.ResolveDependency(dependency, allowPrereleaseVersions: true, preferListedPackages: false);
        }

        protected override void OnDependencyResolveError(PackageDependency dependency)
        {
            // ignore dependency error
        }

        /// <summary>
        /// Get all packages from the specified repository in the dependency order,
        /// e.g. if A -> B, then B will come before A.
        /// </summary>
        public IEnumerable<IPackage> GetPackagesByDependencyOrder(IPackageRepository repository)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }
            Marker.Clear();

            _repository = repository;
            _sortedPackages = new List<IPackage>();

            foreach (var package in _repository.GetPackages())
            {
                Walk(package);
            }

            return _sortedPackages;
        }
    }
}


text:
package grails.plugins.orm.auditable;

import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.transform.GroovyASTTransformation;

@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class StampASTTransformation extends AbstractASTTransformation{
	@Override
	public void transformGeneral(AnnotationNode annotationNode, ClassNode node) {
		addStaticField(node, "stampable", Boolean.class, Boolean.TRUE);
		for(MethodNode value:annotationNode.getClassNode().getMethods()){
			String fieldName = value.getName();

			Object stampInfo = getAnnotationValue(annotationNode, fieldName,true);

			boolean shouldExclude = getStampInfoValue(stampInfo,"exclude",false);
			if(!shouldExclude){
				Class<?> fieldType = getStampInfoValue(stampInfo, "type",String.class);

				FieldNode fieldNode = addFieldNode(node, fieldName, fieldType);

				boolean nullable = getStampInfoValue(stampInfo, "nullable",true);
				if(nullable){
					addNullableConstraint(node, fieldNode);
				}
			}
		}
	}

	private <T> T getStampInfoValue(Object stampInfo,String field,T defaultValue){
		T result = (T) InvokerHelper.invokeMethod(stampInfo, field, new Object[]{});
		return result!=null ? result:defaultValue;
	}
}


text:
import wheel.install
import hashlib
try:
    from StringIO import StringIO
except ImportError:
    from io import BytesIO as StringIO
import zipfile
import pytest

def test_verifying_zipfile():
    if not hasattr(zipfile.ZipExtFile, '_update_crc'):
        pytest.skip('No ZIP verification. Missing ZipExtFile._update_crc.')

    sio = StringIO()
    zf = zipfile.ZipFile(sio, 'w')
    zf.writestr("one", b"first file")
    zf.writestr("two", b"second file")
    zf.writestr("three", b"third file")
    zf.close()

    # In default mode, VerifyingZipFile checks the hash of any read file
    # mentioned with set_expected_hash(). Files not mentioned with
    # set_expected_hash() are not checked.
    vzf = wheel.install.VerifyingZipFile(sio, 'r')
    vzf.set_expected_hash("one", hashlib.sha256(b"first file").digest())
    vzf.set_expected_hash("three", "blurble")
    vzf.open("one").read()
    vzf.open("two").read()
    try:
        vzf.open("three").read()
    except wheel.install.BadWheelFile:
        pass
    else:
        raise Exception("expected exception 'BadWheelFile()'")

    # In strict mode, VerifyingZipFile requires every read file to be
    # mentioned with set_expected_hash().
    vzf.strict = True
    try:
        vzf.open("two").read()
    except wheel.install.BadWheelFile:
        pass
    else:
        raise Exception("expected exception 'BadWheelFile()'")

    vzf.set_expected_hash("two", None)
    vzf.open("two").read()

def test_pop_zipfile():
    sio = StringIO()
    zf = wheel.install.VerifyingZipFile(sio, 'w')
    zf.writestr("one", b"first file")
    zf.writestr("two", b"second file")
    zf.close()

    try:
        zf.pop()
    except RuntimeError:
        pass # already closed
    else:
        raise Exception("expected RuntimeError")

    zf = wheel.install.VerifyingZipFile(sio, 'a')
    zf.pop()
    zf.close()

    zf = wheel.install.VerifyingZipFile(sio, 'r')
    assert len(zf.infolist()) == 1


text:
[![Build Status](https://travis-ci.org/BinPy/BinPy.png?branch=develop)](https://travis-ci.org/BinPy/BinPy) [![Version](https://pypip.in/v/BinPy/badge.png)](https://pypi.python.org/pypi/BinPy/0.3) [![Downloads](https://pypip.in/d/BinPy/badge.png)](https://pypi.python.org/pypi/BinPy/0.3)

 * [About](#about)
 * [Installation](#installation)
 * [Documentation](#documentation)
 * [Contribute](#contribute)

What is BinPy?
---------------
It is a library which will serve as a base to develop circuit based applications and educational software on top of it. BinPy is a clear representation of fundamentals. Everything has been written from scratch such as gates, logical operations, etc. This package does not depend on any external library other than pure Python. It aims to extend the hardware programming concepts to Python.

How to use
----------

Here's an example of SR latch constructed from a pair of cross-coupled NOR gates
![SR latch | Source: Wikipedia](https://upload.wikimedia.org/wikipedia/commons/c/c6/R-S_mk2.gif)

```python

from BinPy import *

NOR1 = Nor('NOR1')  #First NOR gate
NOR2 = Nor('NOR2')  #Second NOR gate

#Connecting output of second NOR with input of first NOR
NOR2.C.connect(NOR1.B)
#Connecting output of first NOR with input of second NOR
NOR1.C.connect(NOR2.A)

NOR1.A.set(1);NOR2.B.set(0) #Set state
print 'Q: ',NOR2.C.getState(), '\t','Q\': ',NOR1.C.getState()

NOR1.A.set(0);NOR2.B.set(1) #Reset state
print 'Q: ',NOR2.C.getState(), '\t','Q\': ',NOR1.C.getState()

NOR1.A.set(0);NOR2.B.set(0) #Hold state
print 'Q: ',NOR2.C.getState(), '\t','Q\': ',NOR1.C.getState()

NOR1.A.set(1);NOR2.B.set(1) #Invalid state
print 'Q: ',NOR2.C.getState(), '\t','Q\': ',NOR1.C.getState()

```
Output
```python
Q:  True 	Q':  False
Q:  False 	Q':  True
Q:  False 	Q':  True
Q:  False 	Q':  False	#Invalid State
```

Operations, Combinatonal Logic and Algorithms

```python
from BinPy import *

# Operations
operator = Operations()
operator.ADD(1011,11)
operator.SUB(1011,11)
operator.COMP('0011',1) #Second argument chooses betweem 1's or 2's Compliment

# Combinational Logic
m = MUX(1,1,0,1)
m.selectLines(0,1)
print "MUX Out: ", m.output()

d = DEMUX()
d.selectLines(0,1)
print "DEMUX Out: ", d.output()

d = Decoder(0,1)
print "Decoder Out: ", d.output()

e = Encoder(0,1,0,0)
print "Encoder Out: ", e.output()

# Sequential Circuits
a = DFlipFlop(1,0)
print "DFlipFlop Out: ", a.output()

# IC
myIC = IC_7400()
p = {1:1,2:0,4:0,5:0,7:0,10:1,9:1,13:0,12:0,14:1}
myIC.setIC(p)
print "IC_7400 Out: ", myIC.run()

myIC1 = IC_7401()
p = {2:0,3:1,5:0,6:0,7:0,8:1,9:1,11:0,12:0,14:1}
myIC1.setIC(p)
print "IC_7401 Out: ", myIC1.run()

# Algorithms
# Includes the Quine-McCluskey algorithm for solving K-Maps
FinalEquation = QM(['A','B'])
print "Minimized Boolean Equation : " , FinalEquation.get_function(qm.solve([0,1,2],[])[1])
```

Output

```python
{'carry': 0, 'sum': [1, 1, 1, 0]}
{'carry': 1, 'difference': [1, 0, 0, 0]}
MUX Out: 1
DEMUX Out: [0, 0, 0, 0]
Decoder Out:  [0, 1, 0, 0]
Encoder Out: [0, 1]
DFlipFlop Out: [1,0]
IC_7400 Out:  {8: 0, 11: 1, 3: 1, 6: 1}
IC_7401 Out:  {1: 1, 10: 0, 4: 1, 13: 1}
Minimized Boolean Equation : ((NOT B) OR (NOT A))
```
BinPy also comes with a console that is a simple  wrapper around the classic python console from which you can directly use the BinPy Resources.

To start it, simply issue ```$ binpy``` if BinPy is installed in your path.

Documentation
-------------
Auto-generated documentation is available for reference at [BinPy docs](http://docs.binpy.org)

Wiki
----
Check out the BinPy [Wiki page](http://github.com/BinPy/BinPy/wiki) for a complete summary of BinPy, [The Development workflow](https://github.com/BinPy/BinPy/wiki/Development-workflow), [Downloading and Installation guide](https://github.com/BinPy/BinPy/wiki/Download-Installation), [Tutorials](https://github.com/BinPy/BinPy/wiki/tutorial), [Technical References](https://github.com/BinPy/BinPy/wiki/Technical-References) and Much more.

Installation
------------

## Linux

###Install with pip

#####Python2

######PIP and setuptools

```sh
sudo apt-get install python-pip
sudo pip install --upgrade setuptools
```

######BinPy

```sh
sudo pip install https://github.com/BinPy/BinPy/zipball/master
```

######IPython Notebook

```sh
sudo pip install --upgrade ipython[all]
```

#####Python3

######PIP and setuptools

```sh
sudo apt-get install python3-pip
sudo pip3 install --upgrade setuptools
```

######BinPy

```sh
sudo pip3 install https://github.com/BinPy/BinPy/zipball/master
```

######IPython Notebook

```sh
sudo pip3 install --upgrade ipython[all]
```

#####Install `autopep8` Tool to ensure your contributions pass the `pep8` test.

```sh
sudo pip install --upgrade autopep8
```

###Install BinPy using git

#####Python2

```sh
sudo apt-get install git setuptools
git clone https://github.com/BinPy/BinPy.git
cd BinPy/
sudo python setup.py install
```

#####Python3

```sh
sudo apt-get install git python3-pip
sudo pip3 install --upgrade setuptools
git clone https://github.com/BinPy/BinPy.git
cd BinPy/
sudo python3 setup.py install
```

####

Future Work
------------

* Introduction of all ICs
* Introduction of problem solving algorithms
* Addition of Microprocessors and Analog Devices
* Graphical representation of the circuit

Visit our [roadmap](https://github.com/BinPy/BinPy/wiki/roadmap) and [ideas page](https://github.com/BinPy/BinPy/wiki/ideas) in [Wiki](http://github.com/BinPy/BinPy/wiki) to know more.

How To Contribute
-----------------

For a detailed summary of all the coding guidelines and [development workflow](https://github.com/BinPy/BinPy/wiki/Development-workflow), visit our [Wiki page](http://github.com/BinPy/BinPy/wiki).

 - [Report Bugs and Issues](https://github.com/BinPy/BinPy/issues)
 - [Solve Bugs and Issues](https://github.com/BinPy/BinPy/issues?page=1&state=open)
 - Write Tutorials, Examples and Documentation

__DEV NOTE:__

 - It is expected that your code must follow [pep8](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCkQFjAA&url=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0008&ei=4SxIU4LWJ4mzrAfEyoHgBg&usg=AFQjCNGUTp-Bavhz439Hr22L2HoxWDeNGg&sig2=dep_DZ8B918mWzzvX8KUYQ) standards. To conform to the same please install `autopep8` tool following the instructions in the [installation section](#installation).

 - After installation is complete. Make the necessary changes and commit your changes. After Committing your changes, `cd` to the BinPy root directory and issue the following command

   `autopep8 -r -i -a -a -v .`

   To learn more about the `autopep8` tool visit [here](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCkQFjAA&url=https%3A%2F%2Fpypi.python.org%2Fpypi%2Fautopep8%2F&ei=SjFIU7jkIcWKrQfE5oDgBQ&usg=AFQjCNGP0o38e1Ia6S7_TfsDIJrvgdGAug&sig2=Yp4VZe9UepdYtoCF_mcBFg).

 - Ensure that all the tests pass by running `nosetests; nosetests3` in `BinPy\BinPy\tests` directory.

 - To check for the pep8 indentation status issue the following command

   `pep8 ./ --ignore=E501`

If all the tests pass successfully push your repo to the origin/branch and send us a Pull Request. We'll be happy to review the same and merge it with our codebase.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mrsud/binpy/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
angular.module('hyq.controllers', [
    'hyq.services'
])

    .controller('FeedCtrl', ['$scope', '$timeout', function($scope, $timeout) {
        $scope.doRefresh = function() {
            $timeout(function() {
                $scope.$broadcast('scroll.refreshComplete');
            }, 2000);
        };
    }])

    .controller('FriendCtrl', ['$scope', 'Friends', 'collectionService', 'toolService',
        function($scope, Friends, collectionService, toolService) {

            // 预处理
            // $scope.friends = dividerService.doDivide(Friends.all());
            var friends = Friends.all();

            var sortKeyFunction = function(item) {
                var key = toolService.toPinyin(item.name.slice(0, 1));
                return key.toString().toUpperCase();
            };
            $scope.friends = collectionService.sort(friends, sortKeyFunction);

            $scope.remove = function(friend) {
                Friends.remove(friend);
            };
    }])

    .controller('ApplicationCtrl', function($scope, $stateParams, Friends) {
        $scope.friend = Friends.get($stateParams.friendId);
    })

    .controller('UserCtrl', function($scope) {
        $scope.settings = {
          enableFriends: true
        };
    })

    .controller('UserSettingCtrl', function($scope) {

    });


text:
package com.palmelf.eoffice.dao.system;

import com.palmelf.core.dao.BaseDao;
import com.palmelf.eoffice.model.system.AppRole;

import java.util.HashMap;
import java.util.Set;

public abstract interface AppRoleDao extends BaseDao<AppRole> {
	public abstract AppRole getByRoleName(String paramString);

	public abstract HashMap<String, Set<String>> getSecurityDataSource();
}


text:
namespace base {
class RefCountedMemory;
}

// The Web UI handler for about:flash.
class FlashUI : public content::WebUIController {
 public:
  explicit FlashUI(content::WebUI* web_ui);

  static base::RefCountedMemory* GetFaviconResourceBytes();

 private:
  DISALLOW_COPY_AND_ASSIGN(FlashUI);
};

#endif  // CHROME_BROWSER_UI_WEBUI_FLASH_UI_H_


text:
<?php

interface Bare_Acl_SubjectInterface
{
    public function getRoles();
}


text:
package gocardless.connect;

import static gocardless.http.HttpClient.basicAuth;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import gocardless.AccountDetails;
import gocardless.exception.SignatureException;
import gocardless.http.HttpClient;
import gocardless.utils.Utils;

import java.math.BigDecimal;
import java.net.URI;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Utils.class})
@PowerMockIgnore({"javax.crypto.*"}) // See http://code.google.com/p/powermock/issues/detail?id=274
public class ConnectTest {

  private AccountDetails accountDetails = new AccountDetails.Builder()
    .appId("id01").appSecret("sec01").accessToken("tok01").merchantId("mer01").build();

  private Connect connect = new Connect(accountDetails);

  @Mock private HttpClient mockHttpClient;

  @Before
  public void setup() throws Exception {
    initMocks(this);
    PowerMockito.spy(Utils.class);
    PowerMockito.when(Utils.class, "nonce").thenReturn("Q9gMPVBZixfRiQ9VnRdDyrrMiskqT0ox8IT+HO3ReWMxavlco0Fw8rva+ZcI");
    PowerMockito.when(Utils.class, "utc").thenReturn("2012-03-21T08:55:56Z");
    connect.setHttpClient(mockHttpClient);
  }

  @Test
  public void testNewBillUrl() {
    Bill bill = new Bill(accountDetails.getMerchantId(), new BigDecimal("1000.0"));
    assertEquals(Fixtures.NEW_BILL_URL, connect.newBillUrl(bill, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewBillUrlInEuros() {
    Bill bill = new Bill(accountDetails.getMerchantId(), new BigDecimal("1000.0"));
    bill.setCurrency("EUR");
    assertEquals(Fixtures.NEW_BILL_URL_EUR, connect.newBillUrl(bill, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewSubscriptionUrl() {
    Subscription subscription = new Subscription(accountDetails.getMerchantId(), new BigDecimal("15.0"), 1, "month");
    assertEquals(Fixtures.NEW_SUBSCRIPTION_URL, connect.newSubscriptionUrl(subscription, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewSubscriptionUrlInEuros() {
    Subscription subscription = new Subscription(accountDetails.getMerchantId(), new BigDecimal("15.0"), 1, "month");
    subscription.setCurrency("EUR");
    assertEquals(Fixtures.NEW_SUBSCRIPTION_URL_EUR, connect.newSubscriptionUrl(subscription, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewSubscriptionUrlWithSetupFee() {
    Subscription subscription = new Subscription(accountDetails.getMerchantId(), new BigDecimal("15.0"), 1, "month");
    subscription.setSetupFee(new BigDecimal(20));
    assertEquals(Fixtures.NEW_SUB_URL_WITH_SETUP_FEE, connect.newSubscriptionUrl(subscription, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewPreAuthorizationUrl() {
    PreAuthorization preAuthorization = new PreAuthorization(accountDetails.getMerchantId(), new BigDecimal("15.0"), 1, "month");
    assertEquals(Fixtures.NEW_PRE_AUTHORIZATION_URL, connect.newPreAuthorizationUrl(preAuthorization, (URI) null, (URI) null, null));
  }

  @Test
  public void testNewPreAuthorizationUrlInEuros() {
    PreAuthorization preAuthorization = new PreAuthorization(accountDetails.getMerchantId(), new BigDecimal("15.0"), 1, "month");
    preAuthorization.setCurrency("EUR");
    assertEquals(Fixtures.NEW_PRE_AUTHORIZATION_URL_EUR, connect.newPreAuthorizationUrl(preAuthorization, (URI) null, (URI) null, null));
  }

  @Test
  public void testConfirmResource() throws SignatureException {
    Map<String, String> headers = basicAuth(accountDetails.getAppId(), accountDetails.getAppSecret());
    connect.confirm(Fixtures.RESOURCE);
    String expectedPath = "https://gocardless.com/api/v1/confirm";
    verify(mockHttpClient, times(1)).post(expectedPath, headers, Fixtures.CONFIRM_POST);
  }

}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.ServiceBus.Models;
using Microsoft.Azure.Management.ServiceBus.Models;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.ServiceBus.Commands.Topic
{
    /// <summary>
    /// 'Set-AzureRmServiceBusTopic' Cmdlet updates the specified ServiceBus Topic
    /// </summary>
    [Cmdlet(VerbsCommon.Set, ServicebusTopicVerb, SupportsShouldProcess = true), OutputType(typeof(TopicAttributes))]
    public class SetAzureRmServiceBusTopic : AzureServiceBusCmdletBase
    {
        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 0,
            HelpMessage = "The name of the resource group")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasResourceGroup)]
        public string ResourceGroupName { get; set; }

        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 1,
            HelpMessage = "Namespace Name.")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasNamespaceName)]
        public string Namespace { get; set; }

        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 1,
            HelpMessage = "Topic Name.")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasTopicName)]
        public string Name { get; set; }

        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 3,
            HelpMessage = "ServiceBus Topic definition.")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasTopicObj)]
        public TopicAttributes InputObject { get; set; }

        public override void ExecuteCmdlet()
        {
            TopicAttributes topicAttributes = new TopicAttributes();
            if (InputObject != null)
            {
                topicAttributes = InputObject;
            }
            else
            {
                //topicAttributes = TopicObj;
            }

            if (ShouldProcess(target: Name, action: string.Format(Resources.UpdateTopic, Name, Namespace)))
            {
                WriteObject(Client.CreateUpdateTopic(ResourceGroupName, Namespace, topicAttributes.Name, topicAttributes));
            }
        }
    }
}


text:
/*
 * ┌──┐
 * │  │
 * │Eh│ony
 * └──┘
 */
package org.ehony.dsl.api;

import java.beans.Introspector;

/**
 * Interface that DSL tags must implement in order to support context
 * resolution strategies and tag tree traversing mechanisms.
 *
 * @param <Parent> type of parent container tag.
 */
public interface Tag<Parent extends ContainerTag>
{

    /**
     * Get human-readable name of this tag.
     *
Default implementation does not introspect annotations and rely only on class name.

     *
     * @return Tag name in bean identifier flavour.
     */
    default String getTagName() {
        return Introspector.decapitalize(getClass().getSimpleName());
    }

    /**
     * Get parent container tag.
     * @return Parent tag object.
     */
    Parent getParentTag();

    /**
     * Set parent container for this tag.
     *
Recommended implementation: this tag is first detached from its current parent container
     * and then added as a child to provided parent.

     *
     * @param parent container to attach this tag to as a child.
     * @return Replaced parent container, equals to parent argument if not changes were made.
     * @exception IllegalArgumentException cyclic dependency in tag tree.
     */
    Parent setParentTag(Parent parent);

    /**
     * Get tag context.
     * @return Context this tag is attached to.
     */
    TagContext getContext();

    /**
     * Set tag context.
     * @param context context to attach tag to.
     */
    void setContext(TagContext context);

    /**
     * Tag consistency validation strategy.
     *
Throws exceptions indicating that tag does not conform required rules.

     */
    default void validate() throws ValidationException {
        // noop
    }

    // <editor-fold desc="Default Fluent API">

    /**
     * Element finishing strategy.
     *
By default returns parent of this element and tries to implicitly adopt returned type.

     *
     * @return Original parent builder instance.
     */
    default Parent end() {
        return getParentTag();
    }

    /**
     * Element finishing strategy which explicitly casts parent to given type.
     * @param type type instance to cast to.
     * @return Original parent builder instance.
     */
    default <T extends Parent> T end(Class<T> type) {
        return type.cast(end());
    }

    // </editor-fold>
}


text:
<?php
/**
 * Laravel 4 Core
 *
 * @author   Andreas Lutro <anlutro@gmail.com>
 * @license  http://opensource.org/licenses/MIT
 * @package  l4-core
 */

namespace anlutro\Core\Auth\Users\Traits;

use InvalidArgumentException;

trait UserLevelModelTrait
{
	protected static $accessLevels = [
		'user' => 1,
		'mod' => 10,
		'admin' => 100,
		'superadmin' => 255,
	];

	/**
	 * Get the list of access levels.
	 *
	 * @return array
	 */
	public function getAccessLevels()
	{
		return static::$accessLevels;
	}

	/**
	 * Check if a user has access to a certain level of actions.
	 *
	 * @param  string  $access
	 *
	 * @return boolean
	 */
	public function hasAccess($access)
	{
		if ($access === '*') {
			$access = 'superadmin';
		}

		return $this->user_level >= $this->getUserLevelValue($access);
	}

	/**
	 * Make sure the user_level attribute is cast to an int.
	 *
	 * @param  string $value
	 *
	 * @return int
	 */
	public function getUserLevelAttribute($value)
	{
		return (int) $value;
	}

	/**
	 * Set the user_level attribute.
	 *
	 * @param string|int $value
	 */
	public function setUserLevelAttribute($value)
	{
		$this->attributes['user_level'] = $this->getUserLevelValue($value);
	}

	/**
	 * Getter for user_type.
	 *
	 * @return string
	 */
	public function getUserTypeAttribute()
	{
		$types = array_reverse(static::$accessLevels);
		$level = $this->user_level;

		foreach ($types as $name => $min) {
			if ($level >= $min) {
				return $name;
			}
		}
	}

	/**
	 * Setter for user_type.
	 *
	 * @param string $value
	 */
	public function setUserTypeAttribute($value)
	{
		$this->setUserLevelAttribute($value);
	}

	/**
	 * Get the real user level value from a string or integer. Throws an
	 * exception if the value is invalid.
	 *
	 * @param  mixed $value
	 *
	 * @return int
	 */
	public function getUserLevelValue($value)
	{
		if (is_int($value)) {
			if ($value < 0 || $value > 255) {
				throw new InvalidArgumentException("Invalid access level: $value");
			}
		} else {
			if (!array_key_exists($value, static::$accessLevels)) {
				throw new InvalidArgumentException("Invalid access level: $value");
			}

			$value = static::$accessLevels[$value];
		}

		return $value;
	}
}


text:
import { compose, createStore, applyMiddleware, combineReducers } from 'redux';
import thunkMiddleware from 'redux-thunk';
import loggerMiddleware from '../../../libs/middlewares/loggerMiddleware';
import reducers, { initialStates } from '../reducers';

export default (props, railsContext) => {
  const initialComments = props.comments;
  const { $$commentsState } = initialStates;
  const initialState = {
    $$commentsStore: $$commentsState.merge({
      $$comments: initialComments,
    }),
    railsContext,
  };

  const reducer = combineReducers(reducers);
  const composedStore = compose(applyMiddleware(thunkMiddleware, loggerMiddleware));

  return composedStore(createStore)(reducer, initialState);
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>citrus-validation</artifactId>
    <groupId>com.consol.citrus</groupId>
    <version>3.3.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>citrus-validation-text</artifactId>
  <name>Citrus :: Validation :: Plaintext</name>

  <dependencies>
    <dependency>
      <groupId>com.consol.citrus</groupId>
      <artifactId>citrus-base</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- Test scoped dependencies -->
    <dependency>
      <groupId>com.consol.citrus</groupId>
      <artifactId>citrus-test-support</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.consol.citrus</groupId>
      <artifactId>citrus-spring</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.consol.citrus</groupId>
      <artifactId>citrus-testng</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>