text:
__all__ = [
    'OAuthToken',
]

class OAuthToken(object):
    """OAuth credentials base-class. Several implementations are available:

    this class:
      provides crawler what is require to authenticate against sources
      via OAuth.
    """
    def __init__(self, access_token, refresh_token=None,
                 token_secret=None, consumer_key=None, expires=None):
        self.__access_token = access_token
        self.__refresh_token = refresh_token
        self.__token_secret = token_secret
        self.__consumer_key = consumer_key
        self.__expires = expires

    access_token = property(
        fget=lambda slf: slf.__access_token,
        doc='''Read-only property accessor over the
        OAuth granted access token used by Docido to gain access
        to the protected resources on behalf of the user, instead
        of using the user's service provider credentials.

        :rtype: string
        '''
    )

    refresh_token = property(
        fget=lambda slf: slf.__refresh_token,
        doc='''Read-only property accessor over the
        OAuth refresh token used to recreate the access token.

        :rtype: string
        '''
    )

    token_secret = property(
        fget=lambda slf: slf.__token_secret,
        doc='''Read-only property accessor over the
        secret token provided by a service when retrieving an OAuth token.
        This property is set only when required provided by the authentication
        mechanism of the crawled service and required by crawler to fetch data.

        :rtype: string
        '''
    )

    consumer_key = property(
        fget=lambda slf: slf.__consumer_key,
        doc='''Read-only property accessor over the
        Docido consumer key. This property is set when required by
        the crawler to fetch data.

        :rtype: string
        '''
    )

    expires = property(
        fget=lambda slf: slf.__expires,
        doc='''Read-only property accessor over the expires field provided
        by authentication mechanism of the crawled service when token was
        acquired.

        :rtype: string
        '''
    )


text:
using testing::Eq;
using testing::StartsWith;

class PromoServiceTest : public testing::Test {
 public:
  PromoServiceTest()
      : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP),
        test_shared_loader_factory_(
            base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
                &test_url_loader_factory_)) {}

  void SetUp() override {
    testing::Test::SetUp();

    service_ =
        std::make_unique<PromoService>(test_shared_loader_factory_, &profile_);
  }

  void SetUpResponseWithData(const GURL& load_url,
                             const std::string& response) {
    test_url_loader_factory_.SetInterceptor(base::BindLambdaForTesting(
        [&](const network::ResourceRequest& request) {}));
    test_url_loader_factory_.AddResponse(load_url.spec(), response);
  }

  void SetUpResponseWithNetworkError(const GURL& load_url) {
    test_url_loader_factory_.AddResponse(
        load_url, network::mojom::URLResponseHead::New(), std::string(),
        network::URLLoaderCompletionStatus(net::HTTP_NOT_FOUND));
  }

  PromoService* service() { return service_.get(); }
  PrefService* prefs() { return profile_.GetPrefs(); }
  network::TestURLLoaderFactory& test_url_loader_factory() {
    return test_url_loader_factory_;
  }

 private:
  // Required to run tests from UI and threads.
  content::BrowserTaskEnvironment task_environment_;

  data_decoder::test::InProcessDataDecoder in_process_data_decoder_;

  network::TestURLLoaderFactory test_url_loader_factory_;
  scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;

  std::unique_ptr<PromoService> service_;

  TestingProfile profile_;
};

TEST_F(PromoServiceTest, PromoDataNetworkError) {
  SetUpResponseWithNetworkError(service()->GetLoadURLForTesting());

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::TRANSIENT_ERROR);
}

TEST_F(PromoServiceTest, BadPromoResponse) {
  SetUpResponseWithData(service()->GetLoadURLForTesting(),
                        "{\"update\":{\"promotions\":{}}}");

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::FATAL_ERROR);
}

TEST_F(PromoServiceTest, PromoResponseMissingData) {
  SetUpResponseWithData(service()->GetLoadURLForTesting(),
                        "{\"update\":{\"promos\":{}}}");

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(service()->promo_data(), PromoData());
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITHOUT_PROMO);
}

TEST_F(PromoServiceTest, GoodPromoResponse) {
  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);
}

TEST_F(PromoServiceTest, GoodPromoResponseCanDismiss) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);
}

TEST_F(PromoServiceTest, GoodPromoResponseNoIdField) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);
}

TEST_F(PromoServiceTest, GoodPromoResponseNoIdFieldNorLogUrl) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);
}

TEST_F(PromoServiceTest, GoodPromoWithBlockedID) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  {
    DictionaryPrefUpdate update(prefs(), prefs::kNtpPromoBlocklist);
    base::Time recent = base::Time::Now() - base::Hours(2);
    update->SetDoubleKey("42", recent.ToDeltaSinceWindowsEpoch().InSecondsF());
  }

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(service()->promo_data(), PromoData());
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_BUT_BLOCKED);
}

TEST_F(PromoServiceTest, BlocklistPromo) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);

  ASSERT_EQ(0u, prefs()->GetDict(prefs::kNtpPromoBlocklist).size());

  service()->BlocklistPromo("42");

  EXPECT_EQ(service()->promo_data(), PromoData());
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_BUT_BLOCKED);

  const auto& blocklist = prefs()->GetDict(prefs::kNtpPromoBlocklist);
  ASSERT_EQ(1u, blocklist.size());
  ASSERT_TRUE(blocklist.Find("42"));
}

TEST_F(PromoServiceTest, BlocklistExpiration) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  {
    DictionaryPrefUpdate update(prefs(), prefs::kNtpPromoBlocklist);
    ASSERT_EQ(0u, update->DictSize());
    base::Time past = base::Time::Now() - base::Days(365);
    update->SetDoubleKey("42", past.ToDeltaSinceWindowsEpoch().InSecondsF());
  }

  ASSERT_EQ(1u, prefs()->GetDict(prefs::kNtpPromoBlocklist).size());

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  // The year-old entry of {promo_id: "42", time: <1y ago>} should be gone.
  ASSERT_EQ(0u, prefs()->GetDict(prefs::kNtpPromoBlocklist).size());

  // The promo should've still been shown, as expiration should take precedence.
  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  EXPECT_EQ(service()->promo_data(), promo);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::OK_WITH_PROMO);
}

TEST_F(PromoServiceTest, BlocklistWrongExpiryType) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  {
    DictionaryPrefUpdate update(prefs(), prefs::kNtpPromoBlocklist);
    ASSERT_EQ(0u, update->DictSize());
    update->SetDoubleKey("42", 5);
    update->SetStringKey("84", "wrong type");
  }

  ASSERT_GT(prefs()->GetDict(prefs::kNtpPromoBlocklist).size(), 0u);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  // All the invalid formats should've been removed from the pref.
  ASSERT_EQ(0u, prefs()->GetDict(prefs::kNtpPromoBlocklist).size());
}

TEST_F(PromoServiceTest, UndoBlocklistPromo) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(ntp_features::kNtpMiddleSlotPromoDismissal);

  std::string response_string =
      "{\"update\":{\"promos\":{\"middle_announce_payload\":"
      "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]},"
      "\"log_url\":\"/log_url?id=42\",\"id\":\"42\"}}}";
  SetUpResponseWithData(service()->GetLoadURLForTesting(), response_string);

  ASSERT_EQ(service()->promo_data(), absl::nullopt);
  EXPECT_EQ(service()->promo_status(), PromoService::Status::NOT_UPDATED);

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  PromoData promo;
  promo.middle_slot_json = "{\"part\":[{\"text\":{\"text\":\"Foo\"}}]}";
  promo.promo_log_url = GURL("https://www.google.com/log_url?id=42");
  promo.promo_id = "42";

  ASSERT_TRUE(prefs()->GetDict(prefs::kNtpPromoBlocklist).empty());

  service()->BlocklistPromo("42");

  const auto& blocklist = prefs()->GetDict(prefs::kNtpPromoBlocklist);
  ASSERT_EQ(1u, blocklist.size());
  ASSERT_TRUE(blocklist.contains("42"));

  service()->UndoBlocklistPromo("42");

  ASSERT_TRUE(prefs()->GetDict(prefs::kNtpPromoBlocklist).empty());
}

TEST_F(PromoServiceTest, ReturnFakeData) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      ntp_features::kNtpMiddleSlotPromoDismissal,
      {{ntp_features::kNtpMiddleSlotPromoDismissalParam, "fake"}});

  service()->Refresh();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(0, test_url_loader_factory().NumPending());
  ASSERT_TRUE(service()->promo_data().has_value());
  EXPECT_EQ("test" + base::NumberToString(static_cast<int>(
                         browser_command::mojom::Command::kNoOpCommand)),
            service()->promo_data()->promo_id);
}

redpajama_set_name: RedPajamaGithub


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

namespace DotNetNuclear.Modules.LogAnalyzer.Components
{
    public interface IAnalyzerNotifyer
    {
        long ProgressTotalCount { get; set; }
        long ProgressIncrement { get; set; }
        string CurrentHubTaskId { get; set; }
        void UpdateProgress();
        void IncrementCurrentProgress();
    }
}


text:
import React from 'react'
import classes from './Login.scss'
import Logo from './assets/hackduke-logo.svg'
import { AuthenticationStatus } from 'routes/Login/modules/authentication'

class Login extends React.Component {

  constructor () {
    super()
    this.state = {sendPassword: false, showMessage: false, firstValue: '', secondValue: ''}
    this.handlePasswordClick = this.handlePasswordClick.bind(this)
    this.handleButtonClick = this.handleButtonClick.bind(this)
    this.handleFirstChange = this.handleFirstChange.bind(this)
    this.handleSecondChange = this.handleSecondChange.bind(this)
    this.handleEnter = this.handleEnter.bind(this)
    const that = this
    window.addEventListener('popstate', function (event) {
      that.props.authenticate(localStorage.getItem('email'), 'password')
    })
  }

  static propTypes = {
    authStatus: React.PropTypes.string.isRequired,
    message: React.PropTypes.string.isRequired,
    authenticate: React.PropTypes.func.isRequired,
    setPassword: React.PropTypes.func.isRequired,
    resetPassword: React.PropTypes.func.isRequired,
    updateAuthStatus: React.PropTypes.func.isRequired,
    updateMessage: React.PropTypes.func.isRequired,
    login: React.PropTypes.func.isRequired,
    fetching: React.PropTypes.bool.isRequired
  }

  handleEnter (event) {
    if (event.keyCode === 13) {
      this.handleButtonClick()
    }
  }

  componentWillMount () {
    document.addEventListener('keydown', this.handleEnter, false)
  }

  componentWillUnmount () {
    document.removeEventListener('keydown', this.handleEnter, false)
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.authStatus === AuthenticationStatus.TEMPORARY) {
      this.setState({firstValue: '', secondValue: ''})
    } else if (nextProps.authStatus === AuthenticationStatus.PERMANENT) {
      this.props.updateMessage('')
      this.props.login()
    }
  }

  handleButtonClick () {
    this.setState({showMessage: true})
    const first = this.state.firstValue
    if (this.state.sendPassword) {
      this.props.resetPassword(first)
    } else if (this.props.authStatus === AuthenticationStatus.TEMPORARY) {
      const second = this.state.secondValue
      if (first !== second) {
        this.props.updateMessage('The passwords must match!')
      } else {
        this.props.setPassword(localStorage.getItem('email'), first)
      }
    } else {
      const second = this.state.secondValue
      this.props.authenticate(first, second)
    }
  }

  handlePasswordClick () {
    if (this.props.authStatus === AuthenticationStatus.TEMPORARY) {
      this.props.updateAuthStatus('')
    } else {
      this.setState({sendPassword: !this.state.sendPassword})
    }
    this.setState({showMessage: false})
    this.props.updateMessage('')
  }

  loginBoxHeight () {
    return this.state.sendPassword ? '400px' : '480px'
  }

  handleMessageVisibility () {
    return this.state.showMessage ? 'visible' : 'hidden'
  }

  handleMessagePadding () {
    return this.state.showMessage ? '15px 0px 15px 0px' : '0'
  }

  handleButtonText () {
    if (this.state.sendPassword) {
      return 'Send password'
    } else {
      return this.props.authStatus === AuthenticationStatus.TEMPORARY ? 'Set password' : 'Login'
    }
  }

  handleFirstPlaceholder () {
    return this.props.authStatus === AuthenticationStatus.TEMPORARY ? 'New Password' : 'Email'
  }

  handleSecondPlaceholder () {
    return this.props.authStatus === AuthenticationStatus.TEMPORARY ? 'Confirm Password' : 'Password'
  }

  handlePasswordText () {
    const needsBackToLogin = this.state.sendPassword || this.props.authStatus === AuthenticationStatus.TEMPORARY
    return needsBackToLogin ? 'Back to log in' : 'Forgot or reset password?'
  }

  handleSecondType () {
    return this.props.authStatus === AuthenticationStatus.TEMPORARY ? 'password' : 'text'
  }

  handleFirstChange (event) {
    this.setState({firstValue: event.target.value})
  }

  handleSecondChange (event) {
    this.setState({secondValue: event.target.value})
  }

  render () {
    return (

        <div className={classes.loginBox} style={{'height': `${this.loginBoxHeight()}`}}>

          <div className={classes.message}
            style={{'visibility': `${this.handleMessageVisibility()}`}}>
            {this.state.showMessage ? this.props.message : ''}

          <input id='first'
            className={classes.input}
            value={this.state.firstValue}
            type={this.handleSecondType()}
            onChange={this.handleFirstChange}
            placeholder={this.handleFirstPlaceholder()} />
          {this.state.sendPassword ? null
            : (<input id='second'
              className={classes.input}
              type='password'
              value={this.state.secondValue}
              onChange={this.handleSecondChange}
              placeholder={this.handleSecondPlaceholder()} />)
          }
          <button id='action' className={classes.loginButton} onClick={this.handleButtonClick}>
            {this.handleButtonText()}
          </button>
          {this.state.sendPassword || this.props.authStatus === AuthenticationStatus.TEMPORARY ? null : (

              <button id='action' className={classes.registerButton}>
                Main Site
              </button>

          )
          }
          <button className={classes.textButton} onClick={this.handlePasswordClick}> {this.state.bottomText}
            {this.handlePasswordText()}
          </button>

    )
  }
}

export default Login


text:
"""
generate design result image

@author: Bowen
"""

from PIL import Image, ImageDraw, ImageFont
import os.path
import time
import datetime

BASE = os.path.dirname(os.path.abspath(__file__))

from design.models import parts, chain

icon_width_small = 40
icon_height_small = 40
icon_width_large = 80
icon_height_large = 80
icon_text_space = 10
icon_space_small = 30
icon_space_large = 30

def createFolder(contentType):
    """
    create the folders with time steamp

    @param contentType: file type in the folder
    @type contentType: str
    @return: created path
    @rtype: str
    """
    basePath = BASE+'/../downloads/'
    year     = str(time.localtime().tm_year)
    month    = str(time.localtime().tm_mon)
    day      = str(time.localtime().tm_mday)
    if not os.path.exists(basePath + year + '/'):
        os.makedirs(basePath + year + '/')
    basePath += year + '/'
    if not os.path.exists(basePath + month + '/'):
        os.makedirs(basePath + month + '/')
    basePath += month + '/'
    if not os.path.exists(basePath + day + '/'):
        os.makedirs(basePath + day + '/')
    basePath += day + '/'
    if not os.path.exists(basePath + contentType + '/'):
        os.makedirs(basePath + contentType + '/')
    basePath += contentType + '/'
    return basePath

def geneFileName(name, surfix):
    """
    generate file name with time and given name

    @param name: name for the file
    @type name: str
    @param surfix: file extension
    @type surfix:str
    @return : filename
    @rtype: str
    """
    now = datetime.datetime.now()
    name = name.replace(' ', '')
    fileNameFormat = '%(year)i-%(month)i-%(day)i-%(hour)i-%(minute)i-%(second)i-%(name)s.%(extension)s'
    fileNameValue = {
                     'year' : now.year,
                     'month' : now.month,
                     'day' : now.day,
                     'hour' : now.hour,
                     'minute' : now.minute,
                     'second' : now.second,
                     'name' : name,
                     'extension' : surfix
                     }
    return fileNameFormat % fileNameValue

def drawOnePart(name, position, drawer, isSmall, icon_im):
    #draw the line
    if isSmall:
        w = icon_width_small
        h = icon_height_small
        s = icon_space_small
    else:
        w = icon_width_large
        h = icon_height_large
        s = icon_space_large
    lineStartX = position[0]
    lineStartY = position[1] + h/2 + 2.5
    lineEndX = position[0] + w + s
    lineEndY = position[1] + h/2 + 2.5
    drawer.line([(lineStartX, lineStartY), (lineEndX, lineEndY)], fill='#800000', width=5)
    #draw the icon
    icon_data = icon_im.getdata()
    for x in range(0, icon_im.size[0]):
        for y in range(0, icon_im.size[1]):
            if icon_data[y*icon_im.size[0]+x][3] != 0:
                drawer.point((position[0] + x, position[1] + y), fill=icon_data[y*icon_im.size[0]+x])
    #draw text
    font = ImageFont.truetype(BASE+'/../static/fonts/HelveticaNeueDeskInterface.ttc', 10)
    drawer.text((position[0], position[1] + h + icon_text_space), name, fill='black', font=font)

def drawCurve(drawer, cbox, isForward):
    if isForward:
        drawer.line([cbox[0], cbox[1], cbox[2], (cbox[1] + cbox[3])/2], fill=(128,0,0,255), width=5)
        drawer.line([cbox[2], (cbox[1] + cbox[3])/2, cbox[0], cbox[3]], fill=(128,0,0,255), width=5)
    else:
        drawer.line([cbox[2], cbox[1], cbox[0], (cbox[1] + cbox[3])/2], fill=(128,0,0,255), width=5)
        drawer.line([cbox[0], (cbox[1] + cbox[3])/2, cbox[2], cbox[3]], fill=(128,0,0,255), width=5)

def drawSequence(sequenceInfo, width, height, file_path):
    newImage = Image.new('RGBA', (width, height), (255,255,255,255))
    drawer = ImageDraw.Draw(newImage)
    initX = 10
    initY = 10
    isForward = True
    index = 0
    while index < len(sequenceInfo):
        item = sequenceInfo[index]
        if isForward:
            if initX + icon_width_small + icon_space_small > width - 10:
                drawCurve(drawer, [initX, initY+ icon_height_small/2 + 2.5, initX + 10, initY + icon_height_small/2 + 2.5 + icon_height_small*2], isForward)
                initY = initY + icon_height_small*2
                isForward = not isForward
                initX -= icon_width_small + icon_space_small
            else:
                icon_im = Image.open(item['icon_file_name'])
                drawOnePart(item['name'], (initX, initY), drawer, True, icon_im)
                initX += icon_width_small + icon_space_small
                index+=1
        else:
            if initX < 10:
                initX += icon_width_small + icon_space_small
                drawCurve(drawer, [initX-10, initY+ icon_height_small/2 + 2.5, initX, initY + icon_height_small/2 + 2.5 + icon_height_small*2], isForward)
                initY = initY + icon_height_small*2
                isForward = not isForward

            else:
                icon_im = Image.open(item['icon_reverse_file_name'])
                drawOnePart(item['name'], (initX, initY), drawer, True, icon_im)
                initX -= icon_width_small + icon_space_small
                index+=1
    newImage.save(file_path)

def getSequenceResultImage(sequence, width, height, name):
    """
    get a part sequence image

    @param sequence: part sequence
    @type sequence: str
    @param width: image width
    @type width: int
    @param height: image height
    @param name: name for that image
    @type name:str
    @return : image file path
    @rtype: str
    """
    if sequence.startswith('_'):
        sequence = sequence[1:]
    sequenceList = sequence.split('_')
    sequenceInfo = list()
    for partid in sequenceList:
        partObj = parts.objects.get(part_id=partid)
        infoDict = {
            'name': partObj.part_name,
            'icon_file_name' : BASE + '/../static/img/%s.png' % partObj.part_type,
            'icon_reverse_file_name': BASE + '/../static/img/%s_reverse.png' % partObj.part_type,
        }
        sequenceInfo.append(infoDict)
    filename = createFolder('image') + geneFileName(name, 'png')
    drawSequence(sequenceInfo, width, height, filename)
    return '/' + filename.replace(BASE+'/../','')


text:
module Gitlab
  module HookData
    class IssueBuilder < BaseBuilder
      SAFE_HOOK_RELATIONS = %i[
        assignees
        labels
        total_time_spent
      ].freeze

      def self.safe_hook_attributes
        %i[
          assignee_id
          author_id
          closed_at
          confidential
          created_at
          description
          due_date
          id
          iid
          last_edited_at
          last_edited_by_id
          milestone_id
          moved_to_id
          project_id
          relative_position
          state
          time_estimate
          title
          updated_at
          updated_by_id
        ].freeze
      end

      alias_method :issue, :object

      def build
        attrs = {
            description: absolute_image_urls(issue.description),
            url: Gitlab::UrlBuilder.build(issue),
            total_time_spent: issue.total_time_spent,
            human_total_time_spent: issue.human_total_time_spent,
            human_time_estimate: issue.human_time_estimate,
            assignee_ids: issue.assignee_ids,
            assignee_id: issue.assignee_ids.first # This key is deprecated
        }

        issue.attributes.with_indifferent_access.slice(*self.class.safe_hook_attributes)
            .merge!(attrs)
      end
    end
  end
end


text:
package com.siyeh.ipp.interfacetoclass;

import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.testFramework.LightProjectDescriptor;
import com.siyeh.IntentionPowerPackBundle;
import com.siyeh.ipp.IPPTestCase;
import org.jetbrains.annotations.NotNull;

public class ConvertInterfaceToClassTest extends IPPTestCase {
  public void testBasic() { doTest(); }
  public void testExtensionMethods() { doTest(); }
  public void testInnerInterface() { doTest(); }
  public void testStaticMethods() { doTest(); }
  public void testInterfaceExtendsClass() { doTest(); }
  public void testLocalInterface() { doTest(); }

  public void testFunctionalExpressions() {
    try {
      doTest();
      fail("Conflict not detected");
    }
    catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
      assertEquals("() -> {...} in Test will not compile after converting interface FunctionalExpressions to a class",
                   e.getMessage());
    }
  }

  public void testExtendsConflict() {
    try {
      doTest();
      fail("Conflict not detected");
    }
    catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
      assertEquals("class AaaImpl implementing interface Aaa already extends class " +
                   "Bbb and will not compile after converting interface Aaa to a class",
                   e.getMessage());
    }
  }

  public void testFunctionalInterface() {
    assertIntentionNotAvailable();
  }

  @Override
  protected String getRelativePath() {
    return "interfaceToClass";
  }

  @Override
  protected String getIntentionName() {
    return IntentionPowerPackBundle.message("convert.interface.to.class.intention.name");
  }

  @NotNull
  @Override
  protected LightProjectDescriptor getProjectDescriptor() {
    return JAVA_15;
  }
}


text:
namespace System.Threading
{
    [System.Runtime.InteropServices.ComVisibleAttribute(false)]
    public delegate void ParameterizedThreadStart(object obj);
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public sealed partial class Thread
    {
        public Thread(System.Threading.ParameterizedThreadStart start) { }
        public Thread(System.Threading.ThreadStart start) { }
        public static System.Threading.Thread CurrentThread { get { return default(System.Threading.Thread); } }
        public bool IsAlive { get { return default(bool); } }
        public bool IsBackground { get { return default(bool); } set { } }
        public int ManagedThreadId { get { return default(int); } }
        public string Name { get { return default(string); } set { } }
        public System.Threading.ThreadState ThreadState { get { return default(System.Threading.ThreadState); } }
        public void Join() { }
        public bool Join(int millisecondsTimeout) { return default(bool); }
        public static void Sleep(int millisecondsTimeout) { }
        public static void Sleep(System.TimeSpan timeout) { }
        public void Start() { }
        public void Start(object parameter) { }
    }
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public delegate void ThreadStart();
    public sealed partial class ThreadStartException : System.Exception
    {
        internal ThreadStartException() { }
    }
    [System.FlagsAttribute]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public enum ThreadState
    {
        Aborted = 256,
        AbortRequested = 128,
        Background = 4,
        Running = 0,
        Stopped = 16,
        StopRequested = 1,
        Suspended = 64,
        SuspendRequested = 2,
        Unstarted = 8,
        WaitSleepJoin = 32,
    }
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class ThreadStateException : System.Exception
    {
        public ThreadStateException() { }
        public ThreadStateException(string message) { }
        public ThreadStateException(string message, System.Exception innerException) { }
    }
}


text:
package com.viadee.acceptancetests.roo.addon;

import java.util.ArrayList;
import java.util.List;

import org.springframework.roo.classpath.PhysicalTypeCategory;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.ConstructorMetadata;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.MutableClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;

class GeneralStoriesPhysicalTypeDetails implements
		MutableClassOrInterfaceTypeDetails {
	public PhysicalTypeCategory getPhysicalTypeCategory() {
		return PhysicalTypeCategory.CLASS;
	}

	public JavaType getName() {
		return new JavaType("de.viadee.bibliothek1.acceptancetests.GeneralStories");
	}

	public List<? extends MethodMetadata> getDeclaredMethods() {
		List<MethodMetadata> result = new ArrayList<MethodMetadata>();
		result.add(new MethodMetadata() {

			public int getModifier() { return 0; }

			public String getDeclaredByMetadataId() { return null; }

			public List<AnnotatedJavaType> getParameterTypes() { return null; }

			public List<JavaSymbolName> getParameterNames() { return null; }

			public String getBody() { return null; }

			public List<AnnotationMetadata> getAnnotations() { return null; }

			public List<JavaType> getThrowsTypes() { return null; }

			public JavaType getReturnType() { return null; }

			public JavaSymbolName getMethodName() {
				return new JavaSymbolName("thisIsAnExistingStory");
			}
		});
		return result;
	}

	public List<JavaType> getImplementsTypes() { return null; }

	public List<JavaType> getExtendsTypes() { return null; }

	public List<? extends FieldMetadata> getDeclaredFields() { return null; }

	public List<? extends ConstructorMetadata> getDeclaredConstructors() { return null; }

	public ClassOrInterfaceTypeDetails getSuperclass() { return null; }

	public int getModifier() { return 0; }

	public List<JavaSymbolName> getEnumConstants() { return null; }

	public String getDeclaredByMetadataId() { return null; }

	public void removeTypeAnnotation(JavaType annotationType) { }

	public void removeField(JavaSymbolName fieldName) { }

	public List<? extends AnnotationMetadata> getTypeAnnotations() { return null; }

	public void addTypeAnnotation(AnnotationMetadata annotation) { }

	public void addMethod(MethodMetadata methodMetadata) { }

	public void addField(FieldMetadata fieldMetadata) { }

	public void addEnumConstant(JavaSymbolName name) { }
}


text:
.main_frame {
    text-align: center;
    color: grey;
}

.d1 {
    font-family: Arial, Helvetica, sans-serif;
    display: inline-block;
}


text:
/// <reference path="../../../typings/tsd.d.ts" />
import { Component, OnInit} from '@angular/core';
import { RouteParams, Router, RouteConfig, RouterLink, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { Http, Response, HTTP_PROVIDERS, HTTP_BINDINGS, Headers, RequestOptions } from '@angular/http';
import { FormBuilder, Validators, CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle} from '@angular/common';
import { FILE_UPLOAD_DIRECTIVES, FileSelectDirective, FileDropDirective, FileUploader} from 'ng2-file-upload';
import { Observable } from 'rxjs/Observable';
import { CONFIG } from '../../config';

import { ValidationService } from '../../services/validation.service';
import { ArticleService } from '../../services/article.service';
import { CategoryService } from '../../services/category.service';
import { LoggerService } from '../../services/logger.service';
import { ProcessMessageService } from '../../services/processmessage.service';
import { PageTitleService } from '../../services/pagetitle.service';

import { ControlMessages } from '../controls/control-messages.component';
import { Article, Attachement, Category ,PageTitle , UserSession, UserIdentity, Authentication, Guid} from '../../helpers/classes';

let uploadsUrl = CONFIG.baseUrls.uploads;
let uploadsAttachUrl = CONFIG.baseUrls.uploadsattach;
let uploadPhysical = CONFIG.baseUrls.uploadsphysical;

@Component({
  selector: 'article-view',
  templateUrl: './app/views/articles/add-article.component.html',
  directives: [ROUTER_DIRECTIVES, ControlMessages, FILE_UPLOAD_DIRECTIVES, NgClass, NgStyle, CORE_DIRECTIVES, FORM_DIRECTIVES],
  providers: [Http, HTTP_BINDINGS, ArticleService, CategoryService]
})

export class AddArticleComponent {

  private articleId: string;
  private articleForm: any;
  private newArticle: Article = new Article();
  private returnedArticle: Article = new Article();
  private returnedAttachements: Attachement[] =[];
  private categories: Category[] = [];
  private isSubmitted: boolean = false;
  private isRequesting: boolean = false;
  private isVisible: boolean =  false;
  private isMessageVisible: boolean = false;
  private isFileAllowed: boolean = false;

  private fileErrorMessage: string = "";

  private uploader: FileUploader = new FileUploader({
    url: uploadsUrl,
    queueLimit: 2,
    maxFileSize: 1024 * 1024, //max 10 MB
    allowedFileType: ['csv', 'xls', 'xlsx', 'xml', 'txt', 'doc', 'docx', 'cs', 'vb', 'sql', 'json']
    // MAKE SURE THAT ALL EXTENSIONS ARE INTRODUCED IN THE file-type.class.js of the ng2-file-upload
  });
  private hasBaseDropZoneOver: boolean = true;
  private hasAnotherDropZoneOver: boolean = false;

  constructor(private _http: Http,
        private _articleService: ArticleService,
        private _categoryService:CategoryService,
        private _pmService: ProcessMessageService,
        private _pageTitleService: PageTitleService,
        private _loggerService: LoggerService,
        private _formBuilder: FormBuilder) {

        this.articleForm = this._formBuilder.group({
          'Title': ['', Validators.compose([Validators.required])],
          'Flash': ['', Validators.compose([Validators.required,])],
          'Content': ['', Validators.required],
          'Category': ['', Validators.required],
        });
  };

  ngOnInit() {
    // generate the article id which will need to be passed as part of the file attached
    this.articleId = Guid.newGuid();
    this._pageTitleService.emitPageTitle(new PageTitle("Add Article"));
    this._pmService.emitRoute("nill");

    this.isRequesting = false;
    this.isFileAllowed = false;
    this.getCategories();
  }

  private fileOverBase(e: any) {
    this.hasBaseDropZoneOver = e;

  }

  private fileOverAnother(e: any) {
    this.hasAnotherDropZoneOver = e;
  }

 //*******************************************
 // GET CATEGORIES
 //*******************************************
  private getCategories() {
    this._categoryService.getCategories()
          .subscribe((returnedCategories: Category[]) => {
                  if (returnedCategories.length == 0) { this._pmService.emitProcessMessage("PMNOCs"); }
                  this.categories = returnedCategories,
                  this.isRequesting = false
              }, (res: Response) => this.onError(res, "GetCategories"));
  }

 //*************************************
 // ADD ARTICLE
 //*************************************
  private onChange(event: any) {
    this.isFileAllowed = false;
    this.isMessageVisible = false;
    let i: number = 0;

    // get the files from the event which controll has passed
    let files: File[] = event.srcElement.files;

     // MULTIPLE FILES POSSIBLE
     // check the number of files selected
     if ((this.uploader.queue.length + files.length) > 2 ) {
            this.isMessageVisible = true;
            this.fileErrorMessage = "Warning: Maximum of 2 files can be attached with maximum size of 10MB each!";
      }

     for (i = 0; i < files.length; i++) {
          // check the sizeof the file
          if (files[i].size > this.uploader.options.maxFileSize) {
                this.isMessageVisible = true;
                this.fileErrorMessage = "Warning: The selected file '" + files[i].name + "' is too big!";
          }
          // check the type of the file
          this.uploader.options.allowedFileType.forEach(type => {
                let filename = files[i].name.split(".");
                if (type === filename[filename.length - 1]) {
                  this.isFileAllowed = true;
              }
          });

          if (!this.isFileAllowed) {
            this.isMessageVisible = true;
                let filename = files[i].name.split(".");
                this.fileErrorMessage = "Warning: The  file extension '" + filename[filename.length - 1] + "' is not allowed!";
          }
      }

    // SINGLE FILE AT THE TIME
    //if (this.uploader.queue.length == 2) {
    //    this.isMessageVisible = true;
    //    this.fileErrorMessage = "Warning: Maximum of 2 files can be attached and with maximum size of 10MB each!";
    //    return;
    //}

    //// check the size of the file selected
    //if (files[0].size > this.uploader.options.maxFileSize) {
    //      this.isMessageVisible = true;
    //      this.fileErrorMessage = "Warning: The file selected " + files[0].name  + " is too big!";
    //}
    //// check the selected file type
    //this.uploader.options.allowedFileType.forEach(type => {
    //      let filename = files[0].name.split(".");
    //      if (type === filename[filename.length-1]) {
    //            this.isFileAllowed = true;
    //      }
    //});
    //if (!this.isFileAllowed) {
    //  this.isMessageVisible = true;
    //    this.fileErrorMessage = "Warning: The file extension not allowed!";
    //}

  }

  // called when remove file button is clicked
  private removeFile(item: any) {
       this.isMessageVisible = false;
       item.remove();

  }

  // called when remove all files button is clicked
  private removeAllFiles() {
    this.isMessageVisible = false;
    this.uploader.clearQueue();
  }

  private saveArticle() {
    if (this.articleForm.dirty && this.articleForm.valid) {

              this.isMessageVisible = false;
              this.isRequesting = true;
              this.newArticle.ArticleId = this.articleId;

              // upload files if any and get result first
              if (this.uploader.queue.length > 0) {
                    this.uploader.queue.forEach(x => this.uploadSingleFile(x))
              }
              this.addArticle(this.newArticle);
        }
  }

  private uploadSingleFile(item: any) {
      let originalFileName: string = item.file.name;
      item.withCredentials = false;
      // we are making the name unique evenif the file is the same
      // and does exist on the server upload side
      item.file.name = this.articleId + "_" + item.file.name;
      item.upload();

      // set the attachement array here
      let attachement = new Attachement();
      // date and the authorid of the article are added in the artcile service
      // the service has an access to the session and user identity
      attachement.ArticleId = this.articleId;
      attachement.Name = item.file.name;
      attachement.PhysicalPath = uploadPhysical + "/" + item.file.name;
      this.newArticle.Attachements.push(attachement);
 }

  private addArticle(article: Article) {
        if (!article) { return; }
        // call the article service to post the articles
        this._articleService.addArticle(article)
              .subscribe((addedArticle: any) => this.onSuccessAddArticle(addedArticle),
              (err => this.onError(err, "AddArticle")));
  }

  //*****************************************************
  // PRIVATE METHODS ARTICLES
  //*****************************************************
  private onSuccessAddArticle(article: Article) {
          this.isSubmitted = true;
          this.returnedArticle = article;
          this.returnedAttachements = article.Attachements;
          if (this.returnedAttachements.length > 0) { this.isVisible = true; }
          this.isRequesting = false;
          this._pmService.emitProcessMessage("PMAAS");

  }

  // an error has occured
  private onError(err: any, type: string) {

    let message: string = "";
    // stop the spinner
    this.isRequesting = false;

    // we will log the error in the server side by calling the logger, or that is already
    // done on the server side if the error has been caught
    this._loggerService.logErrors(err, "add article page");

    // we will display a fiendly process message using the process message service
    this._pmService.emitProcessMessage("PMAA");
    // we will display a fiendly process message using the process message service
    if (err.status !== 200 || err.status !== 300) {
      let data = err.json();

      if (data.ModelState) {
        for (var key in data.ModelState) {
          for (var i = 0; i < data.ModelState[key].length; i++) {
            //errors.push(data.modelState[key][i]);
            if (message == null) { message = data.ModelState[key][i]; }
            else { message = message + data.ModelState[key][i]; } // end if else
          }// end for
        } // end for
        this._pmService.emitProcessMessage("PME", message);
      } // end if
      else {
        // we will display a fiendly process message using the process message service
        switch (type) {
          case "AddArticle":
            this._pmService.emitProcessMessage("PMAA");
            break;
          case "GetCategories":
            this._pmService.emitProcessMessage("PMGCs");
            break;
          default:
            this._pmService.emitProcessMessage("PMG");
        }
      }
    }
  }
}

//// check the number of files selected
//if (files.length > 2) {
//  this.isMessageVisible = true;
//  this.fileErrorMessage = "Warning: Maximum of 2 files can be attached and with maximum size of 10MB each!";
//  return;
//}

//for (i = 0; i < files.length; i++) {

//  if (files[i].size > this.uploader.options.maxFileSize) {
//    this.isMessageVisible = true;
//    this.fileErrorMessage = "Warning: The file " + files[i].name + " selected is too big!";
//  }
//  // check the type of each file
//  this.uploader.options.allowedFileType.forEach(type => {
//    let filename = files[i].name.split(".");
//    if (type === filename[filename.length - 1]) {
//      this.isFileAllowed = true;
//    }
//  });

//  if (!this.isFileAllowed) {
//    this.isMessageVisible = true;
//    this.fileErrorMessage = "Warning: The file extension " + " not allowed!";
//    return;
//  }

//}
//this.uploader.addToQueue(files);


text:
@implementation Person

-(instancetype)initWithFirstName:(NSString *)fname andLastName:(NSString *)lname{
    self = [super init];
    if(self){
        self.firstName = fname;
        self.lastName = lname;
    }
    return self;
}

+(Person *)personWithFirstName:(NSString *)fname andLastName:(NSString *)lname{
    Person *person = [[Person alloc] initWithFirstName:fname
                                           andLastName:lname]
}

-(void)sayHello{
    NSLog(@"Hello!");
}

@end


text:
package org.apache.samoa.topology.impl;

import static org.junit.Assert.*;
import mockit.Mocked;
import mockit.StrictExpectations;
import mockit.Tested;
import mockit.Verifications;

import org.apache.samoa.core.ContentEvent;
import org.apache.samoa.core.EntranceProcessor;
import org.apache.samoa.topology.Stream;
import org.apache.samoa.topology.impl.ThreadsEntranceProcessingItem;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Anh Thu Vu
 *
 */
public class ThreadsEntranceProcessingItemTest {

  @Tested
  private ThreadsEntranceProcessingItem entrancePi;

  @Mocked
  private EntranceProcessor entranceProcessor;
  @Mocked
  private Stream outputStream, anotherStream;
  @Mocked
  private ContentEvent event;

  @Mocked
  private Thread unused;

  /**
   * @throws java.lang.Exception
   */
  @Before
  public void setUp() throws Exception {
    entrancePi = new ThreadsEntranceProcessingItem(entranceProcessor);
  }

  @Test
  public void testContructor() {
    assertSame("EntranceProcessor is not set correctly.", entranceProcessor, entrancePi.getProcessor());
  }

  @Test
  public void testSetOutputStream() {
    entrancePi.setOutputStream(outputStream);
    assertSame("OutoutStream is not set correctly.", outputStream, entrancePi.getOutputStream());
  }

  @Test
  public void testSetOutputStreamRepeate() {
    entrancePi.setOutputStream(outputStream);
    entrancePi.setOutputStream(outputStream);
    assertSame("OutoutStream is not set correctly.", outputStream, entrancePi.getOutputStream());
  }

  @Test(expected = IllegalStateException.class)
  public void testSetOutputStreamError() {
    entrancePi.setOutputStream(outputStream);
    entrancePi.setOutputStream(anotherStream);
  }

  @Test
  public void testStartSendingEvents() {
    entrancePi.setOutputStream(outputStream);
    new StrictExpectations() {
      {
        for (int i = 0; i < 1; i++) {
          entranceProcessor.isFinished();
          result = false;
          entranceProcessor.hasNext();
          result = false;
        }

        for (int i = 0; i < 5; i++) {
          entranceProcessor.isFinished();
          result = false;
          entranceProcessor.hasNext();
          result = true;
          entranceProcessor.nextEvent();
          result = event;
          outputStream.put(event);
        }

        for (int i = 0; i < 2; i++) {
          entranceProcessor.isFinished();
          result = false;
          entranceProcessor.hasNext();
          result = false;
        }

        for (int i = 0; i < 5; i++) {
          entranceProcessor.isFinished();
          result = false;
          entranceProcessor.hasNext();
          result = true;
          entranceProcessor.nextEvent();
          result = event;
          outputStream.put(event);
        }

        entranceProcessor.isFinished();
        result = true;
        times = 1;
        entranceProcessor.hasNext();
        times = 0;

      }
    };
    entrancePi.startSendingEvents();
    new Verifications() {
      {
        try {
          Thread.sleep(anyInt);
          times = 3;
        } catch (InterruptedException e) {

        }
      }
    };
  }

  @Test(expected = IllegalStateException.class)
  public void testStartSendingEventsError() {
    entrancePi.startSendingEvents();
  }

}


text:
<?php

namespace Cma\CmaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Cma\CmaBundle\Entity\Apropos;
use Cma\CmaBundle\Form\AproposType;

/**
 * Apropos controller.
 *
 * @Route("/apropos")
 */
class AproposController extends Controller
{

    /**
     * Lists all Apropos entities.
     *
     * @Route("/", name="apropos")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('CmaBundle:Apropos')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Apropos entity.
     *
     * @Route("/", name="apropos_create")
     * @Method("POST")
     * @Template("CmaBundle:Apropos:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Apropos();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

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

            return $this->redirect($this->generateUrl('apropos_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Apropos entity.
     *
     * @param Apropos $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Apropos $entity)
    {
        $form = $this->createForm(new AproposType(), $entity, array(
            'action' => $this->generateUrl('apropos_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Apropos entity.
     *
     * @Route("/new", name="apropos_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Apropos();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Apropos entity.
     *
     * @Route("/{id}", name="apropos_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CmaBundle:Apropos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Apropos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Apropos entity.
     *
     * @Route("/{id}/edit", name="apropos_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CmaBundle:Apropos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Apropos entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Apropos entity.
    *
    * @param Apropos $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Apropos $entity)
    {
        $form = $this->createForm(new AproposType(), $entity, array(
            'action' => $this->generateUrl('apropos_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Apropos entity.
     *
     * @Route("/{id}", name="apropos_update")
     * @Method("PUT")
     * @Template("CmaBundle:Apropos:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CmaBundle:Apropos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Apropos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('apropos_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Apropos entity.
     *
     * @Route("/{id}", name="apropos_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('CmaBundle:Apropos')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Apropos entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

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

    /**
     * Creates a form to delete a Apropos entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('apropos_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php

namespace Supervisorg\Workers;

use Puzzle\AMQP\Workers\Worker;
use Puzzle\AMQP\ReadableMessage;
use Supervisorg\Services\AsynchronousRunner;
use Psr\Log\LoggerAwareTrait;

class ProcessControlAll implements Worker
{
    use LoggerAwareTrait;

    private
        $runner;

    public function __construct(AsynchronousRunner $runner)
    {
        $this->runner = $runner;
    }

    public function process(ReadableMessage $message)
    {
        $payload = $message->getDecodedBody();

        $this->ensurePayloadIsValid($payload);

        $serverName = $payload['server'];
        $action = $payload['action'];

        foreach($payload['processes'] as $processName)
        {
            $this->runner->startStop($serverName, $processName, $action);
        }
    }

    private function ensurePayloadIsValid(array $payload)
    {
        foreach(['server', 'processes', 'action'] as $requiredEntry)
        {
            if(! isset($payload[$requiredEntry]))
            {
                throw new \InvalidArgumentException("Payload need a entry called $requiredEntry");
            }
        }
    }
}


text:
<?php

namespace Chrisyue\Mala\Manager;

use Chrisyue\Mala\Model\ChannelInterface;

interface VideoManagerInterface
{
    public function findByChannel(ChannelInterface $channel);
}


text:
#include <aws/mediapackage-vod/model/ScteMarkersSource.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace MediaPackageVod
  {
    namespace Model
    {
      namespace ScteMarkersSourceMapper
      {

        static const int SEGMENTS_HASH = HashingUtils::HashString("SEGMENTS");
        static const int MANIFEST_HASH = HashingUtils::HashString("MANIFEST");

        ScteMarkersSource GetScteMarkersSourceForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == SEGMENTS_HASH)
          {
            return ScteMarkersSource::SEGMENTS;
          }
          else if (hashCode == MANIFEST_HASH)
          {
            return ScteMarkersSource::MANIFEST;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ScteMarkersSource>(hashCode);
          }

          return ScteMarkersSource::NOT_SET;
        }

        Aws::String GetNameForScteMarkersSource(ScteMarkersSource enumValue)
        {
          switch(enumValue)
          {
          case ScteMarkersSource::SEGMENTS:
            return "SEGMENTS";
          case ScteMarkersSource::MANIFEST:
            return "MANIFEST";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ScteMarkersSourceMapper
    } // namespace Model
  } // namespace MediaPackageVod
} // namespace Aws


text: The resource allows specifying a power plan to activate.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal unsafe partial class Sys
    {
        [RuntimeImport("SystemNative_GetErrNo")]
        internal static extern int GetErrNo();

        [RuntimeImport("SystemNative_ClearErrNo")]
        internal static extern void ClearErrNo();
    }
}


text:
Plataforma de empleabilidad para ninis

## 1) Introducción

Es una plataforma web creada para conectar jóvenes que no están ni estudiando ni trabajando (NINIs) con trabajos eventuales (o con proyección en el tiempo) de manera ágil, sencilla y segura. Ayudando a los NINIs a exhibir sus talentos y lograr ocupación laboral, y de otro lado, a personas naturales y empresas, simplificando su selección de capital humano.

A nivel laboral y fiscal nuestra propuesta de innovación rompe con las altas tasas de informalidad en el trabajo, porque integrará todos sus usuarios con el sistema tributario nacional (SUNAT), siendo esta un prototipo digital nunca antes visto, pero requerido por los ODS, el Plan Bicentenario y diversos compromisos internacionales.

## 2) Funcionalidad

### FRONTED (Sin Accesos).-

a) Al iniciar la aplicación ésta deberá mostrar una lista de categorias por ejemplo: Petlovers, Creativos, MilOficios; las cuales no deberían sobrepasar el máximo de tres.

>NOTA: Si el usuario ha iniciado sesión las categorías se muestran en base a sus anteriores preferencias, de lo contrario se mostrarán las categorias más usadas.

b) Cuando el usuario elige una categoría deberá mostrarse una siguiente pantalla con dos opciones: ¿Quieres ganar dinero? (1) ¿Quiero contratar? (2)

>NOTA: Para las tres categorías se muestran las mismas opciones descritas arriba.

c) Al elegir la opción 1, el usuario podrá visualizar los trabajos en base a la categoría anterior, ejemplo: Petlovers. Adicionalmente tendrá un botón para crear un perfil (En caso no haya creado uno aún)

d) Al elegir la opción 2, el usuario podrá visualizar la lista de perfiles de cachueleros (personas que están buscando tener un trabajo temporal). Adicionalmente tendrá un botón para agregar un trabajo.

### BACKED (Con Login):

#### DEL REGISTRO E INGRESO

a) Si el usuario no ha iniciado sesión lo redirigirá al formulario de ingreso, en el cual deberá ingresar su correo y contraseña.

b) Si el usuario no se ha registrado lo redirigirá al formulario de registro, el cual contará con las siguientes opciones: Correo, Clave, Nombres, DNI, Foto de DNI, Enlace a su cuenta de Facebook, Dirección, Etiquetas, Foto de algún recibo de servicio.

#### DE LA CREACIÓN DE TRABAJO:

a) El contratante podrá tener acceso al formulario de registro de empleo que contará con las siguientes opciones: Titulo, Descripción, Remunareción, Horas, Categoría (), Etiquetas.

#### DE LA CREACIÓN DEL PERFIL:

El NINI podrá tener acceso al registro del perfil que contará con las siguientes opciones: Titulo, Descripción, Experiencia (ej: Imágenes de carta de recomendacion o trabajos realizados), Rango de precios.

## 3) Alcance


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight;

import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandlerBase;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PythonLanguage;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.Nullable;

/**
 * Provides reaction on ctrl+click for {@code break} and {@code continue} statements.
 * @author dcheryasov
 */
public class PyBreakContinueGotoProvider extends GotoDeclarationHandlerBase {
  @Override
  public PsiElement getGotoDeclarationTarget(@Nullable PsiElement source, Editor editor) {
    if (source != null && source.getLanguage() instanceof PythonLanguage) {
      final PsiElement breakOrContinue = source.getParent();
      final PyLoopStatement loop = PyUtil.getCorrespondingLoop(breakOrContinue);
      if (loop != null) {
        if (breakOrContinue instanceof PyContinueStatement) {
          return loop;
        }
        else {
          PsiElement outer_element = loop;
          PsiElement after_cycle;
          while (true) {
            after_cycle = outer_element.getNextSibling();
            if (after_cycle != null) {
              if (after_cycle instanceof PsiWhiteSpace) {
                after_cycle = after_cycle.getNextSibling();
              }
              if (after_cycle instanceof PyStatement) return after_cycle;
            }
            outer_element = outer_element.getParent();
            if (PsiTreeUtil.instanceOf(outer_element, PsiFile.class, PyFunction.class, PyClass.class)) {
              break;
            }
          }
          // cycle is the last statement in the flow of execution. its last element is our best bet.
          return PsiTreeUtil.getDeepestLast(loop);
        }
      }
    }

    return null;
  }
}


text:
package com.intellij.refactoring.makeStatic;

import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.refactoring.util.VariableData;
import java.util.HashMap;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public final class Settings {
  private final boolean myMakeClassParameter;
  private final String myClassParameterName;
  private final boolean myMakeFieldParameters;
  private final HashMap<PsiField,String> myFieldToNameMapping;
  private final ArrayList<FieldParameter> myFieldToNameList;
  private final boolean myReplaceUsages;
  private final boolean myDelegate;

  public static final class FieldParameter {
    public FieldParameter(PsiField field, String name, PsiType type) {
      this.field = field;
      this.name = name;
      this.type = type;
    }

    public final PsiField field;
    public final String name;
    public final PsiType type;
  }

  public Settings(boolean replaceUsages, @Nullable String classParameterName, @Nullable VariableData[] variableDatum) {
    this(replaceUsages, classParameterName, variableDatum, false);
  }

  public Settings(boolean replaceUsages,
                  @Nullable String classParameterName,
                  @Nullable VariableData[] variableDatum,
                  boolean delegate) {
    myReplaceUsages = replaceUsages;
    myDelegate = delegate;
    myMakeClassParameter = classParameterName != null;
    myClassParameterName = classParameterName;
    myMakeFieldParameters = variableDatum != null;
    myFieldToNameList = new ArrayList<>();
    if(myMakeFieldParameters) {
      myFieldToNameMapping = new HashMap<>();
      for (VariableData data : variableDatum) {
        if (data.passAsParameter) {
          myFieldToNameMapping.put((PsiField)data.variable, data.name);
          myFieldToNameList.add(new FieldParameter((PsiField)data.variable, data.name, data.type));
        }
      }
    }
    else {
      myFieldToNameMapping = null;
    }
  }

  public Settings(boolean replaceUsages, String classParameterName,
                  PsiField[] fields, String[] names) {
    myReplaceUsages = replaceUsages;
    myMakeClassParameter = classParameterName != null;
    myClassParameterName = classParameterName;
    myMakeFieldParameters = fields.length > 0;
    myFieldToNameList = new ArrayList<>();
    if (myMakeFieldParameters) {
      myFieldToNameMapping = new HashMap<>();
      for (int i = 0; i < fields.length; i++) {
        final PsiField field = fields[i];
        final String name = names[i];
        myFieldToNameMapping.put(field, name);
        myFieldToNameList.add(new FieldParameter(field, name, field.getType()));
      }
    }
    else {
      myFieldToNameMapping = null;
    }
    myDelegate = false;
  }

  public boolean isReplaceUsages() {
    return myReplaceUsages;
  }

  public boolean isMakeClassParameter() {
    return myMakeClassParameter;
  }

  public String getClassParameterName() {
    return myClassParameterName;
  }

  public boolean isMakeFieldParameters() {
    return myMakeFieldParameters;
  }

  public boolean isDelegate() {
    return myDelegate;
  }

  @Nullable
  public String getNameForField(PsiField field) {
    if (myFieldToNameMapping != null) {
      return myFieldToNameMapping.get(field);
    }
    return null;
  }

  public List<FieldParameter> getParameterOrderList() {
    return myFieldToNameList;
  }

  public boolean isChangeSignature() {
    return isMakeClassParameter() || isMakeFieldParameters();
  }

  public int getNewParametersNumber() {
    final int result = isMakeFieldParameters() ? myFieldToNameList.size() : 0;
    return result + (isMakeClassParameter() ? 1 : 0);
  }
}


text:
using UnityEngine;

namespace Dungeon
{
    public struct RoomTransitionRelationship
    {
        internal readonly Room from;
        internal readonly Room to;
        internal readonly Vector3 via;

        public RoomTransitionRelationship(Room from, Room to, Vector3 via)
        {
            this.from = from;
            this.to = to;
            this.via = via;
        }
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/**
 * @codeCoverageIgnore
 */
class CreateEvents extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->dateTime('start_date');
            $table->dateTime('end_date');
            $table->integer('calendar_id')->unsigned();
            $table->timestamps();
        });

        Schema::create('event_extras', function (Blueprint $table) {
            $table->string('slug');
            $table->text('value');
            $table->integer('event_id')->unsigned();
            $table->timestamps();

            $table->primary(['slug', 'event_id']);
        });

        Schema::table('event_extras', function (Blueprint $table) {
            $table->foreign('event_id')
                ->references('id')->on('events');
        });

        Schema::table('events', function (Blueprint $table) {
            $table->foreign('calendar_id')
                ->references('id')->on('calendars');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('event_extras');
        Schema::drop('events');
    }
}


text:
function alternate(URL) {
  if (URL.indexOf("#") !== -1) {
    var URL = URL.substr(0, URL.indexOf('#'));
  }

  var newURL = null;
  if (URL.endsWith(".h")) {
    newURL = URL.replaceLast("m");
  } else if (URL.endsWith(".m")) {
    newURL = URL.replaceLast("h");
  } else if (URL.endsWith(".c")) {
    newURL = URL.replaceLast("h");
  }

  if (newURL) {
    window.location.href = newURL;
  }
}

function commits(oldURL) {
  window.location.href = oldURL + "/commits";
}

String.prototype.replaceLast = function(character) {
  return this.substr(0, this.length - 1) + character;
};

$(document).keypress(function(e) {
  // Exit early if we're in an input field
  // This wasn't needed in Chrome but is in Safari
  if (document.activeElement.nodeName === "INPUT" || document.activeElement.nodeName === "TEXTAREA") {
    return;
  }

  // If you're in a file editing box it's not technically an input field.
  if (document.activeElement.isContentEditable) {
    return;
  }

  switch (e.which) {
    case 97: // 'a'
      alternate(window.location.href);
      break;
    case 99: // 'c'
      commits(window.location.href);
      break;
    default:
      break;
  }
});

// Actions on pageload

$(document).ready(function() {
  removeDislikedElements();
  addHideDiffButton();
});

// Remove some buttons GitHub adds that I don't want to click
function removeDislikedElements() {
  $(".js-new-blob-submit").remove();
  $(".signup-prompt-bg").remove();
  $(".toolbar-help").remove();
  $("a[href^=github-mac]").remove();
}

// Add a button to 'fold' a file in diff mode (super nice for storyboards!)
function addHideDiffButton() {
  $(".file-actions").each(function() {
    var diff = $(this).parent().parent();
    var link = $("Hide");
    $(this).prepend(link);
    link.click(function() {
      var codeArea = $(diff).find('[class$="wrapper"]');
      $(this).html() == 'Hide' ? codeArea.hide() : codeArea.show()
      $(this).html($(this).html() == 'Show' ? 'Hide' : 'Show');
      return false;
    });
  });
}


text:
<?php echo modal_header($article->title . ' ' . lang('documents') . ' ' . (count($documents) ? '(' . count($documents) . ')' : '') . '') ?>
<?php $imgs = get_icons() ?>

	<?php echo form_open_multipart('', array('id' => 'form-document'));?>

		 <?php echo lang('upload_documents') ?>
		<input type="file" name="document[]" multiple="multiple" id="document" size="20">

	<?php if (count($documents)) : ?>

		<?php echo button_default(lang('edit'), 'btn-edit-files', 'glyphicon-edit', 'UPDATE') ?>

			<?php echo button_default(lang('cancel'), 'btn-cancel-files', 'glyphicon-ban-circle', 'UPDATE') ?>
			<?php echo button_primary(lang('save_data'), 'btn-save-files', 'glyphicon-ok', 'UPDATE') ?>

	<?php endif ?>
	<?php echo form_close(); ?>
	<form id="form-documents" onsubmit="return validate_data(this, '<?php echo base_url() ?>cms/article/save_descriptions/', 'btn-save-files', null, save_textareas)">

			<?php $pks = '' ?>
			<?php foreach ($documents as $document): ?>
				<?php $pks .= $document->id_file . ',' ?>

					<div class="thumbnail" data-toggle="tooltip" data-placement="bottom" title="<?php echo $document->filename ?>">

							<?php $extension = explode('.', $document->filename) ?>
							<img  src="<?php echo base_url() . 'assets/img/docs/' . $imgs[$extension[count($extension)-1]] ?>">

							<a target="_blank" href="http://docs.google.com/viewer?url=<?php echo urlencode(base_url() . 'assets/files/articles/documents/'. $document->filename) ?>" type="button" class="preview btn btn-default btn-xs" title="Vista previa" data-toggle="tooltip" data-placement="bottom">
							<a href="<?php echo base_url() . 'assets/files/articles/documents/'. $document->filename ?>" class="btn btn-default btn-xs" title="Descargar" data-toggle="tooltip" data-placement="bottom">
							<button type="button" class="delete btn btn-danger btn-xs" data-role="<?php echo $document->id_file ?>" title="Eliminar documento" data-toggle="tooltip" data-placement="bottom"></button>

<?php echo strlen($document->description) ? $document->description : 'Sin descripción' ?>

						<textarea name="description-<?php echo $document->id_file ?>" placeholder="Escribir descripción..."><?php echo $document->description ?></textarea>

			<?php endforeach ?>
			<input type="hidden" name="pks" value="<?php echo rtrim($pks, ',') ?>">

	</form>


text:
@echo off

@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR

set GLFW_URL=http://github.com/glfw/glfw/releases/download/3.1.1/glfw-3.1.1.zip

cd "%~dp0"

bin\curl -L %GLFW_URL% > glfw.zip
bin\7z  x -r -y -o. glfw.zip
del glfw.zip

set glfwdir="empty"
for /D %%A IN ("glfw-*") DO set glfwdir=%%A

mkdir glfwbuild
cd glfwbuild
cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 11" "..\%glfwdir%"

MSBuild.exe GLFW.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64

mkdir ..\lib
mkdir ..\bin
mkdir ..\include
mkdir ..\include\GLFW

copy src\Release\*.lib ..\lib\
copy ..\%glfwdir%\include\GLFW\*.h ..\include\GLFW\

cd ..

rmdir /s /q %glfwdir%
rmdir /s /q glfwbuild

@exit /B 0

:error_no_VSINSTALLDIR
@echo ERROR: You should run this bat file from your Developer Command Prompt for VS2012
pause


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
CGWorks::Application.initialize!


text:
package org.apache.roller.webservices.adminapi;

import java.io.IOException;
import java.io.Reader;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.roller.config.RollerConfig;
import org.apache.roller.model.Roller;
import org.apache.roller.model.RollerFactory;
import org.apache.roller.ui.core.RollerContext;
import org.apache.roller.webservices.adminapi.sdk.EntrySet;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.apache.roller.config.RollerRuntimeConfig;
import org.apache.roller.webservices.adminapi.sdk.MissingElementException;
import org.apache.roller.webservices.adminapi.sdk.UnexpectedRootElementException;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * This class is the abstract notion of an AAPP request handler.
 * It processes HTTP requests for each of the four HTTP verbs:
 * GET, POST, PUT, DELETE, for a given weblog resource.
 */
abstract class Handler {
    protected static final String ENDPOINT = "/aapp";

    static class URI {
        private static Pattern PATHINFO_PATTERN = Pattern.compile("^/(users|weblogs|members)(?:/(.*))?$");

        private String type;
        private String entryId;

        public URI(HttpServletRequest request) throws BadRequestException {
            String pi = request.getPathInfo();

            if (pi == null || pi.length() == 0) {
                type = null;
                entryId = null;
            } else {
                Matcher m = PATHINFO_PATTERN.matcher(pi);
                if (!m.matches()) {
                    throw new BadRequestException("ERROR: Invalid path info: " + pi);
                }

                type = m.group(1);
                entryId = m.group(2);
            }
        }

        public String getType() {
            return type;
        }

        public String getEntryId() {
            return entryId;
        }

        public boolean isIntrospection() {
            return getEntryId() == null && type == null;
        }

        public boolean isCollection() {
            return getEntryId() == null && type != null;
        }

        public boolean isEntry() {
            return getEntryId() != null && type != null;
        }
    }

    protected static final Log logger = LogFactory.getFactory().getInstance(Handler.class);

    private HttpServletRequest request;
    private Roller roller;
    private RollerContext rollerContext;
    private String userName;
    private URI uri;
    private String urlPrefix;

    /** Get a Handler object implementation based on the given request. */
    public static Handler getHandler(HttpServletRequest req) throws HandlerException {
        boolean enabled = RollerConfig.getBooleanProperty("webservices.adminprotocol.enabled");
        if (!enabled) {
            throw new NotAllowedException("ERROR: Admin protocol not enabled");
        }

        URI uri = new URI(req);
        Handler handler;

        if (uri.isIntrospection()) {
            handler = new IntrospectionHandler(req);
        } else if (uri.isCollection() || uri.isEntry()) {
            String type = uri.getType();
            if (type.equals(EntrySet.Types.WEBLOGS)) {
                handler = new RollerWeblogHandler(req);
            } else if (type.equals(EntrySet.Types.USERS)) {
                handler = new RollerUserHandler(req);
            } else if (type.equals(EntrySet.Types.MEMBERS)) {
                handler = new RollerMemberHandler(req);
            } else {
                throw new BadRequestException("ERROR: Unknown type: " + uri.getType());
            }
        } else {
            throw new BadRequestException("ERROR: Unknown URI type");
        }

        return handler;
    }

    public Handler(HttpServletRequest request) throws HandlerException {
        this.request = request;
        this.uri = new URI(request);
        this.rollerContext = RollerContext.getRollerContext();
        this.roller = RollerFactory.getRoller();
        //TODO: is this the right thing to do? hardcode roller-services?
        this.urlPrefix = RollerRuntimeConfig.getAbsoluteContextURL() + "/roller-services" + ENDPOINT;

        // TODO: decide what to do about authentication, is WSSE going to fly?
        //Authenticator auth = new WSSEAuthenticator(request);
        Authenticator auth = new BasicAuthenticator(request);
        auth.authenticate();
        setUserName(auth.getUserName());
    }

    /**
     * Get the authenticated user name.
     * If this method returns null, then authentication has failed.
     */
    public String getUserName() {
        return userName;
    }

    private void setUserName(String userName) {
        this.userName = userName;
    }

    /** Process an HTTP GET request. */
    public abstract EntrySet processGet() throws HandlerException;
    /** Process an HTTP POST request. */
    public abstract EntrySet processPost(Reader r) throws HandlerException;
    /** Process an HTTP PUT request. */
    public abstract EntrySet processPut(Reader r) throws HandlerException;
    /** Process an HTTP DELETE request. */
    public abstract EntrySet processDelete() throws HandlerException;

    protected URI getUri() {
        return uri;
    }

    protected HttpServletRequest getRequest() {
        return request;
    }

    protected RollerContext getRollerContext() {
        return rollerContext;
    }

    protected Roller getRoller() {
        return roller;
    }

    protected String getUrlPrefix() {
        return urlPrefix;
    }

    protected abstract EntrySet getEntrySet(Document d) throws MissingElementException, UnexpectedRootElementException;

    protected EntrySet getEntrySet(Reader r) throws HandlerException {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document d = builder.build(r);
            EntrySet c = getEntrySet(d);

            return c;
        } catch (UnexpectedRootElementException ure) {
            throw new BadRequestException("ERROR: Failed to parse content", ure);
        } catch (MissingElementException mee) {
            throw new BadRequestException("ERROR: Failed to parse content", mee);
        } catch (JDOMException jde) {
            throw new BadRequestException("ERROR: Failed to parse content", jde);
        } catch (IOException ioe) {
            throw new InternalException("ERROR: Failed to parse content", ioe);
        }
    }
}


text:
import inflect
import json
import random
import re

infl = inflect.engine()

class MadLibber():
    def make(self, template = None):
        if(template is None):
            template = self.actions["template"]()

        tokens = template.split(" ")
        result = ""
        for token in tokens:
            action = re.match("(.*)\{\{(.+?)\}\}(.*)", token)
            if(action):
                if(action[2] in self.actions):
                    result += action[1] + self.actions[action[2]]() + action[3]
                else:
                    result += action[0]
            else:
                result += token

            result += " "

        if (re.search("\{\{(.+?)\}\}", result)):
            # Recursion with no base case -
            # I'm going to regret this some day aren't I...
            return self.make(result)

        return result.strip()

class Complimenter(MadLibber):
    def __init__(self):
        with open("./data/madlib/adjectives.json") as adf:
            self.adjectives = json.load(adf)
        with open("./data/madlib/amounts.json") as amf:
            self.amounts = json.load(amf)
        with open("./data/madlib/parts.json") as parf:
            self.parts = json.load(parf)
        with open("./data/madlib/persons.json") as perf:
            self.persons = json.load(perf)
        with open("./data/madlib/templates.json") as temf:
            self.templates = json.load(temf)
        with open("./data/madlib/things.json") as thinf:
            self.things = json.load(thinf)

        self.actions = {
            "adjective" : lambda : random.choice(self.adjectives["adjectives"]),
            "an_adjective" : lambda : infl.an(self.actions["adjective"]()),
            "amount" : lambda : random.choice(self.amounts),
            "an_amount" : lambda : infl.an(self.actions["amount"]()),
            "parts" : lambda : random.choice(self.parts),
            "person" : lambda : random.choice(self.persons),
            "thing" : lambda : random.choice(self.things),
            "template" : lambda : random.choice(self.templates["respect"])
        }

class Horoscoper(MadLibber):
    def __init__(self):
        with open("./data/madlib/adjectives.json") as adf:
            self.adjectives = json.load(adf)
        with open("./data/madlib/amounts.json") as amf:
            self.amounts = json.load(amf)
        with open("./data/madlib/assets.json") as parf:
            self.assets = json.load(parf)
        with open("./data/madlib/persons.json") as perf:
            self.persons = json.load(perf)
        with open("./data/madlib/templates.json") as temf:
            self.templates = json.load(temf)
        with open("./data/madlib/nouns.json") as thinf:
            self.nouns = json.load(thinf)
        with open("./data/madlib/ing_verbs.json") as ing:
            self.ing_verbs = json.load(ing)
        with open("./data/madlib/present_verbs.json") as pres:
            self.present_verbs = json.load(pres)
        with open("./data/madlib/planets.json") as pla:
            self.planets = json.load(pla)

        self.actions = {
            "adjective" : lambda : random.choice(self.adjectives["adjectives"]),
            "an_adjective" : lambda : infl.an(self.actions["adjective"]()),
            "adverb" : lambda : random.choice(self.adjectives["adverbs"]),
            "amount" : lambda : random.choice(self.amounts),
            "an_amount" : lambda : infl.an(self.actions["amount"]()),
            "asset" : lambda : random.choice(self.assets),
            "person" : lambda : random.choice(self.persons),
            "present_verb" : lambda : random.choice(self.present_verbs),
            "noun" : lambda : random.choice(self.nouns),
            "nouns" : lambda : infl.plural_noun(random.choice(self.nouns)),
            "ing_verb" : lambda : random.choice(self.ing_verbs),
            "planet" : lambda : random.choice(self.planets)
        }

    def get_variants(self):
        return self.templates["horoscope"].keys()

    def make_horoscope(self, variant):
        return self.make(random.choice(self.templates["horoscope"][variant]))

class Prompter(MadLibber):
    def __init__(self):
        with open("./data/prompt/adjectives.json") as adf:
            self.adjectives = json.load(adf)
        with open("./data/prompt/nouns.json") as nf:
            self.nouns = json.load(nf)

        self.actions = {
            "adjective" : lambda : random.choice(self.adjectives),
            "noun" : lambda : random.choice(self.nouns),
            "template" : lambda : r"{{adjective}} {{noun}}"
        }

    def addNoun(self, noun):
        self.nouns.append(noun)
        with open("./data/prompt/nouns.json", "w") as nf:
            json.dump(self.nouns, nf)

    def remNoun(self, noun):
        if(noun in self.nouns):
            self.nouns.remove(noun)
            with open("./data/prompt/nouns.json", "w") as nf:
                json.dump(self.nouns, nf)

    def addAdjective(self, adjective):
        self.adjectives.append(adjective)
        with open("./data/prompt/adjectives.json", "w") as adf:
            json.dump(self.adjectives, adf)

    def remAdjective(self, adjective):
        if(adjective in self.adjectives):
            self.adjectives.remove(adjective)
            with open("./data/prompt/adjectives.json", "w") as adf:
                json.dump(self.adjectives, adf)

class Thinger(MadLibber):
    def __init__(self) -> None:
        with open("./data/madlib/adjectives.json") as adf:
            self.adjectives = json.load(adf)
        with open("./data/madlib/amounts.json") as amf:
            self.amounts = json.load(amf)
        with open("./data/madlib/assets.json") as parf:
            self.assets = json.load(parf)
        with open("./data/madlib/templates.json") as temf:
            self.templates = json.load(temf)
        with open("./data/madlib/nouns.json") as nounf:
            self.nouns = json.load(nounf)
        with open("./data/madlib/ing_verbs.json") as ing_verbsf:
            self.ing_verbs = json.load(ing_verbsf)
        with open("./data/madlib/itemtypes.json") as typef:
            self.types = json.load(typef)

        self.actions = {
            "adjective" : lambda : random.choice(self.adjectives["adjectives"]),
            "an_adjective" : lambda : infl.an(self.actions["adjective"]()),
            "adverb" : lambda : random.choice(self.adjectives["adverbs"]),
            "amount" : lambda : random.choice(self.amounts),
            "an_amount" : lambda : infl.an(self.actions["amount"]()),
            "asset" : lambda : random.choice(self.assets),
            "noun" : lambda : random.choice(self.nouns),
            "ing_verb" : lambda : random.choice(self.ing_verbs),
            "template" : lambda : random.choice(self.templates["thing"]),
            "type": lambda : random.choice(self.types)
        }

    def typeThing(self, thing):
        return "(" + self.actions["type"]() + ") " + thing

class User(MadLibber):
    def __init__(self) -> None:
        with open("./data/madlib/adjectives.json") as adf:
            self.adjectives = json.load(adf)
        with open("./data/madlib/amounts.json") as amf:
            self.amounts = json.load(amf)
        with open("./data/madlib/assets.json") as parf:
            self.assets = json.load(parf)
        with open("./data/madlib/templates.json") as temf:
            self.templates = json.load(temf)
        with open("./data/madlib/nouns.json") as nounf:
            self.nouns = json.load(nounf)
        with open("./data/madlib/present_verbs.json") as present_verbsf:
            self.present_verbs = json.load(present_verbsf)
        with open("./data/madlib/ing_verbs.json") as ing_verbsf:
            self.ing_verbs = json.load(ing_verbsf)
        with open("./data/madlib/planets.json") as planetsf:
            self.planets = json.load(planetsf)

        self.actions = {
            "adjective" : lambda : random.choice(self.adjectives["adjectives"]),
            "an_adjective" : lambda : infl.an(self.actions["adjective"]()),
            "adverb" : lambda : random.choice(self.adjectives["adverbs"]),
            "asset" : lambda : random.choice(self.assets),
            "a_noun": lambda : infl.a(self.actions["noun"]()),
            "noun" : lambda : random.choice(self.nouns),
            "planet" : lambda : random.choice(self.planets),
            "present_verb" : lambda : random.choice(self.present_verbs),
            "ing_verb": lambda : random.choice(self.ing_verbs),
            "template" : lambda : random.choice(self.templates["use"])
        }


text:
@interface NSString (sandBox)
//获取沙盒的cache目录
- (instancetype)ay_appdendCache;
//document
- (instancetype)ay_appdendDocument;
//temp
- (instancetype)ay_appdendTemp;
@end


text:
<?php

$locale['urg_shop_100'] = "Shopping Mall";
$locale['urg_shop_101'] = "Welcome to the shopping area.
Here you are able to do a few little things with your gold that may improve your account or maybe make it worse
Please select from the list
";
$locale['urg_shop_101a'] = "Welcome to the shopping area!";
$locale['urg_shop_101b'] = "Here you are able to do a few little things with your gold that may improve your account or maybe make it worse.";
$locale['urg_shop_101c'] = "Please select from the list bellow:
";
$locale['urg_shop_102'] = "Shop";
$locale['urg_shop_103'] = "Ribbon Shop";
$locale['urg_shop_104'] = "Buy Steal";
$locale['urg_shop_105'] = "Buy Forum Posts";
$locale['urg_shop_106'] = "Buy New Signup Date";
$locale['urg_shop_107'] = "Buy Karma";
$locale['urg_shop_108'] = "Sort by:";
$locale['urg_shop_109'] = "Price";
$locale['urg_shop_110'] = "Description";
$locale['urg_shop_111'] = "Stock";
$locale['urg_shop_112'] = "ASC";
$locale['urg_shop_113'] = "DESC";
$locale['urg_shop_114'] = "Go";
$locale['urg_shop_115'] = "Image";
$locale['urg_shop_116'] = "Price/Stock";
$locale['urg_shop_117'] = "Stock:";
$locale['urg_shop_118'] = "Owned";
$locale['urg_shop_119'] = "Buy Now";
$locale['urg_shop_120'] = "Sorry, nothing here. Please come back later!";
$locale['urg_shop_121'] = "You need";
$locale['urg_shop_122'] = "Nothing available";
$locale['urg_shop_123'] = "Shop Inventory List";
$locale['urg_shop_124'] = "ERROR: This item is sold out!";
$locale['urg_shop_125'] = "You successfully bought a";
$locale['urg_shop_126'] = "You will be sent back shortly.";
$locale['urg_shop_127'] = "Ribbon Shop";
$locale['urg_shop_128'] = "Amount: ";
$locale['urg_shop_129'] = "Welcome to the ribbon shop.
Here, you can buy a ribbon or more if you do not want to donate to get one!
All ribbons cost %s";
$locale['urg_shop_130'] = "Buy";
$locale['urg_shop_131'] = "You must enter an amount!";
$locale['urg_shop_132'] = "You must enter an amount above 0!";
$locale['urg_shop_133'] = "You dont have that much gold in your account!";
$locale['urg_shop_134'] = "You have successfully bought the %s of ribbon(s) at the cost of %s";
$locale['urg_shop_135'] = "You have purchased the right to steal once from one person";
$locale['urg_shop_136'] = "You cant afford this";
$locale['urg_shop_137'] = "It is";
$locale['urg_shop_138'] = "to buy a chance to steal from a user.
It is very dangerous to steal from someone as you may lose all of your money.
This is why it's very wise to keep your money in the bank.
Try not to lose it all if you buy this.
You just may get caught.";
$locale['urg_shop_139'] = "Successfully added ";
$locale['urg_shop_140'] = " forum posts to your post count!";
$locale['urg_shop_141'] = "Your maximum amount to raise you post by is %s , this is based on a percentage (%s) of your current posts %s, this action has a set cost of %s %s!";
$locale['urg_shop_142'] = "Successfully altered Signup date to %s from %s at a cost of %s !";
$locale['urg_shop_143'] = "The Randomiser will alter your join time from ";
$locale['urg_shop_144'] = " to a date between this time in 2004 and today.
";
$locale['urg_shop_145'] = "I Agree:";
$locale['urg_shop_146'] = "Continue";
$locale['urg_shop_147'] = "Finalizing";
$locale['urg_shop_148'] = "5 Most Bought";
$locale['urg_shop_149'] = "Sorry, no items bought.";
$locale['urg_shop_150'] = "Sorry, you don't have access to requested item.";
$locale['urg_shop_151'] = "Sorry, the item requested could not be found in the database.";
$locale['urg_shop_152'] = "Users Also Bought";
$locale['urg_shop_153'] = "Be the first.";
$locale['urg_shop_154'] = "Sorry, no item defined.";
$locale['urg_shop_155'] = "Not created yet!";
$locale['urg_shop_156'] = "";
$locale['urg_shop_157'] = "";
?>