text:
<!doctype html>

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

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

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

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

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

<link href="css/font-awesome.min.css" rel="stylesheet" type="text/css">

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

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

<link href="css/audioplayer.css" rel="stylesheet">

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

<link href="css/yamm-menu.css" rel="stylesheet" type="text/css">

<link rel="icon" href="images/favicon.ico" type="image/x-icon">

<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,500,700,900' rel='stylesheet' type='text/css'>

Log in /

 Sign up

Home

Explore

 Connect us on

            Gramventures © 2016 All Rights Reserved

Log in /

 Sign up

            <button type="button" data-toggle="collapse" data-target="#navbar-collapse-1" class="navbar-toggle"></button>

Explore

Gramventure Theme

Home

Explore

Apply

 Creative Brief

Created: June 13, 2016

What We're Looking For:

Ensure that new Gramventures photographers are discovered by voting on the top photos. Even if you're not a new photographer, vote so the best new members get recognized!

The Gramventures Editorial Team will pick their favorite photo and the winner will be featured on our Instagram @gramventures

Rules:

You can only enter if you joined Gramventures within 7 days of this challenge opening.

No watermarks

No thick borders

No screenshots

 #gramventures

 Prize: 100

 2,509 Entries

 Time to Enter: 5 days

              Apply

Title

            Name

47

Title

            Name

47

Title

            Name

47

Title

            Name

47

Title

            Name

47

Title

            Name

47

Title

            Name

47

Title

            Name

47

 Connect us on

Gramventures © 2016 All Rights Reserved

redpajama_set_name: RedPajamaGithub


text:
package gnu.java.awt.color;

/**
 * ColorSpaceConverter - used by java.awt.color.ICC_ColorSpace
 *
 * Color space conversion can occur in several ways:
 *
 * -Directly (for the built in spaces sRGB, linear RGB, gray, CIE XYZ and PYCC
 * -ICC_ProfileRGB works through TRC curves and a matrix
 * -ICC_ProfileGray works through a single TRC
 * -Everything else is done through Color lookup tables.
 *
 * The different conversion methods are implemented through
 * an interface. The built-in colorspaces are implemented directly
 * with the relevant conversion equations.
 *
 * In this way, we hopefully will always use the fastest and most
 * accurate method available.
 *
 * @author Sven de Marothy
 */
public interface ColorSpaceConverter
{
  float[] toCIEXYZ(float[] in);

  float[] fromCIEXYZ(float[] in);

  float[] toRGB(float[] in);

  float[] fromRGB(float[] in);
}


text:
package org.ros.internal.message.field;

import org.jboss.netty.buffer.ChannelBuffer;

/**
 * @author damonkohler@google.com (Damon Kohler)
 */
public abstract class Field {

  protected final FieldType type;
  protected final String name;
  protected final boolean isConstant;

  protected Field(FieldType type, String name, boolean isConstant) {
    this.name = name;
    this.type = type;
    this.isConstant = isConstant;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @return the type
   */
  public FieldType getType() {
    return type;
  }

  /**
   * @return true if this {@link ListField} represents a constant
   */
  public boolean isConstant() {
    return isConstant;
  }

  /**
   * @return the textual representation of this field used for computing the MD5
   *         of a message definition
   */
  public String getMd5String() {
    if (isConstant()) {
      return String.format("%s %s=%s\n", getType().getMd5String(), getName(), getValue());
    }
    return String.format("%s %s\n", getType().getMd5String(), getName());
  }

  public abstract void serialize(ChannelBuffer buffer);

  public abstract void deserialize(ChannelBuffer buffer);

  public abstract <T> T getValue();

  // TODO(damonkohler): Why not make Field generic?
  public abstract void setValue(Object value);

  public abstract String getJavaTypeName();

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

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


text:
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace AdmissionControl {

using GrpcStatus = Grpc::Status::GrpcStatus;

static constexpr double defaultAggression = 2.0;

AdmissionControlFilterConfig::AdmissionControlFilterConfig(
    const AdmissionControlProto& proto_config, Runtime::Loader& runtime,
    Random::RandomGenerator& random, Stats::Scope& scope, ThreadLocal::SlotPtr&& tls,
    std::shared_ptr<ResponseEvaluator> response_evaluator)
    : random_(random), scope_(scope), tls_(std::move(tls)),
      admission_control_feature_(proto_config.enabled(), runtime),
      aggression_(
          proto_config.has_aggression_coefficient()
              ? std::make_unique<Runtime::Double>(proto_config.aggression_coefficient(), runtime)
              : nullptr),
      response_evaluator_(std::move(response_evaluator)) {}

double AdmissionControlFilterConfig::aggression() const {
  return std::max<double>(1.0, aggression_ ? aggression_->value() : defaultAggression);
}

AdmissionControlFilter::AdmissionControlFilter(AdmissionControlFilterConfigSharedPtr config,
                                               const std::string& stats_prefix)
    : config_(std::move(config)), stats_(generateStats(config_->scope(), stats_prefix)),
      expect_grpc_status_in_trailer_(false), record_request_(true) {}

Http::FilterHeadersStatus AdmissionControlFilter::decodeHeaders(Http::RequestHeaderMap&, bool) {
  // TODO(tonya11en): Ensure we document the fact that healthchecks are ignored.
  if (!config_->filterEnabled() || decoder_callbacks_->streamInfo().healthCheck()) {
    // We must forego recording the success/failure of this request during encoding.
    record_request_ = false;
    return Http::FilterHeadersStatus::Continue;
  }

  if (shouldRejectRequest()) {
    decoder_callbacks_->sendLocalReply(Http::Code::ServiceUnavailable, "", nullptr, absl::nullopt,
                                       "denied by admission control");
    stats_.rq_rejected_.inc();
    return Http::FilterHeadersStatus::StopIteration;
  }

  return Http::FilterHeadersStatus::Continue;
}

Http::FilterHeadersStatus AdmissionControlFilter::encodeHeaders(Http::ResponseHeaderMap& headers,
                                                                bool end_stream) {
  // TODO(tonya11en): It's not possible for an HTTP filter to understand why a stream is reset, so
  // we are not currently accounting for resets when recording requests.

  if (!record_request_) {
    return Http::FilterHeadersStatus::Continue;
  }

  bool successful_response = false;
  if (Grpc::Common::isGrpcResponseHeaders(headers, end_stream)) {
    absl::optional<GrpcStatus> grpc_status = Grpc::Common::getGrpcStatus(headers);

    // If the GRPC status isn't found in the headers, it must be found in the trailers.
    expect_grpc_status_in_trailer_ = !grpc_status.has_value();
    if (expect_grpc_status_in_trailer_) {
      return Http::FilterHeadersStatus::Continue;
    }

    const uint32_t status = enumToInt(grpc_status.value());
    successful_response = config_->responseEvaluator().isGrpcSuccess(status);
  } else {
    // HTTP response.
    const uint64_t http_status = Http::Utility::getResponseStatus(headers);
    successful_response = config_->responseEvaluator().isHttpSuccess(http_status);
  }

  if (successful_response) {
    recordSuccess();
  } else {
    recordFailure();
  }

  return Http::FilterHeadersStatus::Continue;
}

Http::FilterTrailersStatus
AdmissionControlFilter::encodeTrailers(Http::ResponseTrailerMap& trailers) {
  if (expect_grpc_status_in_trailer_) {
    absl::optional<GrpcStatus> grpc_status = Grpc::Common::getGrpcStatus(trailers, false);

    if (grpc_status.has_value() &&
        config_->responseEvaluator().isGrpcSuccess(grpc_status.value())) {
      recordSuccess();
    } else {
      recordFailure();
    }
  }

  return Http::FilterTrailersStatus::Continue;
}

bool AdmissionControlFilter::shouldRejectRequest() const {
  const auto request_counts = config_->getController().requestCounts();
  const double total = request_counts.requests;
  const double success = request_counts.successes;
  const double probability = (total - config_->aggression() * success) / (total + 1);

  // Choosing an accuracy of 4 significant figures for the probability.
  static constexpr uint64_t accuracy = 1e4;
  auto r = config_->random().random();
  return (accuracy * std::max(probability, 0.0)) > (r % accuracy);
}

} // namespace AdmissionControl
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy


text:
#define dotnet_connector_VERSION 1,1
#define dotnet_connector_VERSIONINFO_VERSION "1.1"
#define dotnet_connector_VERSIONINFO_COMPANY "///"
#define dotnet_connector_VERSIONINFO_TITLE "helper library to connect unmangend and managed code"
#define dotnet_connector_VERSIONINFO_PACKAGE "dotnet connector"
#define dotnet_connector_VERSIONINFO_COPYRIGHT "Copyright \xA9 2010-2011 Eric Karge"


text: <!DOCTYPE html><meta charset=UTF-8><meta name=viewport content="initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv=X-UA-Compatible content="ie=edge"><title>写给100天后的你</title><link href=/static/css/app.6c150fa62fe152fcb34819b780ca8dd6.css rel=stylesheet>


text:
using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace tour_of_heroes_1.Controllers.Helpers
{
    public class ConflictResult : StatusCodeResult
    {
        public ConflictResult() : base((int)HttpStatusCode.Conflict)
        {
        }
    }
}


text:
Template Meta Programming (TMP) is a programming methodology that makes
it possible to shift program logic from runtime to compile time, using
solely types and templates. This can be a lot more memory efficient, can
have better performance and allows for earlier error detection based on
types.

"Template metaprogramming can shift work from runtime to compile-time,
thus enabling earlier error detection and higher runtime performance."

Factorial using Template Meta Programming:

template<std::size_t n>
struct Factorial
 {
     enum { value = n * Factorial<n-1>::value };
template<>
struct Factorial<0>
 {
     enum { value = 1 };

};

Output:

>>>  std::cout << Factorial<4>::value;

>>> 24

Loop using Template Meta Programming:

template<std::size_t i, std::size_t n>
class Loop
 {
public:

     static void notaloophehe()
     {
         std::cout << i << std::endl;

        Print<i+1, n>::notaloophehe();

    }

};
template<std::size_t i>
class Loop<i, i>
 {

 public:

     static void notaloophehe()
     {
         std::cout << i << std::endl;
     }

};


text:
/*
 * buildSearchParts
 * Inverted Index Toolkit  <http://code.google.com/p/inverted-index/>
 * Apache License 2.0, blah blah blah.
 *
 * This constructs the various clauses for the search query, returning
 * them in the INOUT parameters.
 *
 * It is not intended to be used directly, but by the "search" procedure.
 *
 * Parameters:
 *
 * _classId:   the class ID to be searched.  eg. classID('doc')
 *
 * _sentence:  the sentence to be searched.  eg. "best of times"
 *
 * _type:      'and', 'ordered' or 'phrase', to determine search type.
 *
 * _froms:     the resulting FROM clause.  Should start with the initial
 *             data table or i0 (see search procedure).  Set to NULL if
 *             no words will be found.
 *
 * _wheres:    the resulting WHERE clause.
 *
 */

DROP PROCEDURE IF EXISTS buildSearchParts;
DELIMITER ;;

CREATE PROCEDURE `buildSearchParts`(_classId INT UNSIGNED,
                                    _sentence TEXT,
                                    _type ENUM('and', 'ordered', 'phrase'),
                                    INOUT _froms TEXT,
                                    INOUT _wheres TEXT)
    DETERMINISTIC -- is this true?  Hrmm...
    READS SQL DATA
thisproc:BEGIN

-- Iterator counter for word loop
DECLARE _i INT UNSIGNED DEFAULT 0;

-- Found word
DECLARE _word TEXT;

-- ID for found word
DECLARE _wordId INT UNSIGNED;

-- Find the first word in the sentence
CALL nextWord(_sentence, _word);

-- Okay.  For each word...
WHILE (_word IS NOT NULL) DO

    -- Get the ID for this word
    SET _wordId = wordID(sanitizeWord(_word));

    -- If no word was found, this whole thing's a waste of time
    -- anyway, as no rows will be returned.
    IF (_wordId IS NULL) THEN
        SET _froms = NULL;
        SET _wheres = _word;
        LEAVE thisproc;
    END IF;

    -- Assemble an inner join from one copy of the index table to the
    -- previous one.
    IF (_i=0) THEN
        -- This is the first word, so we just establish the conditions for
        -- i0.  i0 has already nbeen specified in the original query
        -- string initialisation.
        SET _wheres = CONCAT(_wheres,
                             'i0.search_class_id=',_classId,
                             ' AND i0.word_id=',_wordId);
    ELSE
        -- This is a subsequent word, so we join against i0.
        SET _froms = CONCAT(_froms,
                            ' INNER JOIN search_index AS i',_i,
                            ' ON i0.id=i',_i,'.id');
        SET _wheres = CONCAT(_wheres,
                             ' AND i',_i,'.search_class_id=',_classId,
                             ' AND i',_i,'.word_id=',_wordId);

        IF (_type = 'phrase') THEN
            -- This is a phrase search, so we need to specify word position.
            SET _wheres = CONCAT(_wheres,
                                 ' AND i',_i,'.position=',
                                 'i0.position+',_i);
        ELSEIF (_type = 'ordered') THEN
            -- This is an ordered search, so we need to specify word position.
            SET _wheres = CONCAT(_wheres,
                                 ' AND i',_i,'.position>i',(_i-1),'.position');
        END IF;
    END IF;

    SET _i=_i+1;

    -- Get the next word
    CALL nextWord(_sentence, _word);

END WHILE;

END;;
DELIMITER ;


text:
/**
*
* ToolListItem
*
*/

import React from 'react';
import styled from 'styled-components';
import Isvg from 'react-inlinesvg';

import { injectIntl } from 'react-intl';

import ToolTypeAll from 'containers/ToolTypeAll';

import SearchField from 'containers/SearchField';
import ToolsViewOptions from 'containers/ToolsViewOptions';
import ToolsSortOptions from 'containers/ToolsSortOptions';
import TranslatableStaticText from 'containers/TranslatableStaticText';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import {TextButton} from 'components/CommonComponents';
import IconButton from 'components/IconButton';
import MobileSectionHeader from 'components/HomePage/MobileSectionHeader';
import ArrowIcon from 'assets/images/icons/arrow.svg';

import TypeDetails from 'containers/TypeDetails';
import Link from 'components/Link';
import Modal from 'react-modal';

import TagArea from './TagArea';
import staticText from './staticText';

const MobileHeaderContainer = styled.div`
  width: 100%;
  margin-top: 10px;

  padding-right: 15px;
  padding-left: 15px;

  &::before {
    position: absolute;
    content: ' ';
    width: 240px;
    height: 4px;
    background-color: white;
    ${props=>props.theme.lang==='ar' ? (props.showTools?'right: 326px':'right: 96px') : (props.showTools?'left: 325px':'left: 95px')};
    transition: left 0.3s ease, right 0.3s ease;
  }
`;

const FilterSection = styled.ul`
  width: 100%;
  padding-bottom: 5px;
  border-bottom: 2px solid black;
  padding-${p=>p.theme.isArabic?'right':'left'}: 0px;
  display: flex;
  list-style: none;
  margin: 0;

  @media(max-width: 1320px) {
  }
  @media(max-width: 970px) {
    flex-wrap: wrap;

    &::after {
      content: ' ';
      border: 1px solid white;
      position: absolute;
      right: 0;
      top: 0;
      height: 68px;
    }

    &:first-child {
      border-bottom: 0;
    }
  }
`;

const SingleFilterSection = styled(FilterSection)`
  padding-top: 12px;
  padding-bottom: 12px;
  border-bottom: 0;
`;

const FilterItem = styled.li`
  display: inline-block;
  list-style: none;
  position: relative;
  padding-left: ${p=>p.sidePadding || 0};
  padding-right: ${p=>p.sidePadding || 0};
  position: relative;
  text-align: ${p=>p.theme.isArabic?'right': 'left'};

  ${p=>{
      if (p.last) {
          return p.theme.isArabic?'padding-left:0;':'padding-right:0';
      } else { return null; }
  }}

  &::after {
    content: ' ';
    border-${p=>p.theme.isArabic?'left':'right'}: 2px solid;
    position: absolute;
    height: 12px;
    ${p=>p.theme.isArabic?'left':'right'}: 0px;
    top: 7px;
  }

  &:first-child {
    flex-grow: 1;
  }
  &:last-child {
    padding-${p=>p.theme.isArabic?'left':'right'}: 0;
    width: 110px;
    text-align: center;
    &::after { border-${p=>p.theme.isArabic?'left':'right'}: none; }
  }
`;

const TagShownIcon = styled.div`
  display: inline-block;
  ${p=>{
    if(p.theme.isArabic) {
      return `transform: ${p.selected?'rotate(270deg)':'rotate(360deg)'};`
    } else {
      return `transform: ${p.selected?'rotate(270deg)':'rotate(180deg)'};`;
    }
  }}
  margin-${p=>p.theme.isArabic?'right':'left'}: 12px;
  margin-top: -5px;
  transition: transform 0.5s ease;

  svg { width: 10px !important; }
  svg * {
    fill: ${p=>p.selected?'black':'#ACACAC'};
    transition: fill 0.5s ease;
  }
`;

//For modalIsOpen
const customStyles = {
  overlay: {
    backgroundColor: 'rgba(149, 149, 149, 0.75)',
    zIndex: 900
  },
  content : {
    position: 'absolute',
    right: 'auto',
    left: 'auto',
    bottom: 'auto',
    border: '0px none',
    background: 'rgb(255, 255, 255)',
    overflow: 'visible',
    outline: 'none',
    padding: '15px',
    width: '100%',
    height: 'calc(100% - 115px)',
    zIndex: '600',
    top: '115px'
  }
};

const ApplyButton = styled.button`
  outline: none;
  display: none;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  font-size: 15px;
  padding: 18px;
  text-transform: uppercase;
  font-weight: 800;
  border: 2px solid black;
  @media(max-width: 1320px) {
  }
  @media(max-width: 970px) {
    display: block;
  }
`;

class MobileHeader extends React.PureComponent {

  constructor() {
    super();

    this.state = {
      isTagsAreaShown: false,
      isTypeAreaShown: false
    }
  }

  toggleTagArea() {
    this.setState({isTagsAreaShown: !this.state.isTagsAreaShown });
  }

  hideTagArea() {
    this.setState({isTagsAreaShown: false });
  }

  showTagArea(){
    this.setState({isTagsAreaShown: true });
  }

  toggleTypeArea() {
    this.setState({isTypeAreaShown: !this.state.isTypeAreaShown });
  }

  hideTypeArea() {
    this.setState({isTypeAreaShown: false });
  }

  showTypeArea(){
    this.setState({isTypeAreaShown: true });
  }

  componentWillReceiveProps(nextProps) {
  }

  renderMobileTags() {
    const lang = this.props.intl.locale;
    return (
      <IconButton width="auto" onClick={this.toggleTagArea.bind(this)}>
        <TextButton ar={lang==='ar'} selected={false}>
          <TranslatableStaticText {...staticText.tags} />
        </TextButton>
      </IconButton>
    )
  }
  renderTypeButton() {
    const lang = this.props.intl.locale;
    return (
      <IconButton width="auto" onClick={this.toggleTypeArea.bind(this)}>
        <TextButton ar={lang==='ar'} selected={false}>
          <TranslatableStaticText {...staticText.toolTypeButton} />
        </TextButton>
      </IconButton>
    )
  }
  render() {
    const lang = this.props.intl.locale;
    const showTypeDetails=this.props.params&&this.props.params.filter==="type";
    return (
      <LanguageThemeProvider>
        <MobileHeaderContainer {...this.props}>
          <FilterSection>
            <FilterItem style={{ flexGrow: 1 }}>
              <SearchField {...this.props.params}/>
            </FilterItem>
            <FilterItem>
              { this.renderMobileTags() }
            </FilterItem>
          </FilterSection>
          <FilterSection>
            <FilterItem>
              <ToolsSortOptions />
            </FilterItem>
            <FilterItem last={true}>
              <ToolsViewOptions />
            </FilterItem>
          </FilterSection>
          <SingleFilterSection>
            <FilterItem>
              {this.renderTypeButton() }
            </FilterItem>
          </SingleFilterSection>
          <TypeDetails show={showTypeDetails} {...this.props.params} />
        </MobileHeaderContainer>

        {/* MODAL FOR TAGS */}
        <Modal
          isOpen={this.state.isTagsAreaShown}
          style={{content: {...customStyles.content}, overlay: {...customStyles.overlay, backgroundColor: 'rgba(0,0,0,0)'} }}
          contentLabel="TagsModal"
          overlayClassName="TagsModalOverlay"
        >
          <MobileSectionHeader>
            <TranslatableStaticText {...staticText.tags} />
          </MobileSectionHeader>
          <TagArea show={true} {...this.props} hideTagArea={()=>{}}/>
          <ApplyButton onClick={this.hideTagArea.bind(this)}>
            <TranslatableStaticText {...staticText.apply} />
          </ApplyButton>
        </Modal>

        {/* MODAL FOR TYPES */}
        <Modal
          isOpen={this.state.isTypeAreaShown}
          style={{...customStyles, content: {...customStyles.content}, overlay: {...customStyles.overlay, backgroundColor: 'rgba(0,0,0,0)'}}}
          contentLabel="TypeFilterModal"
          overlayClassName="TypeFilterOverlay"
        >
          <MobileSectionHeader>
            <TranslatableStaticText {...staticText.toolTypeButton} />
          </MobileSectionHeader>
          <ToolTypeAll lang={this.props.lang} show={true} {...this.props} />
          <ApplyButton onClick={this.hideTypeArea.bind(this)}>
            <TranslatableStaticText {...staticText.apply} />
          </ApplyButton>
        </Modal>
      </LanguageThemeProvider>
    );
  }

}

MobileHeader.propTypes = {

};

export default injectIntl(MobileHeader);


text:
use std::net::SocketAddr;
use std::io;
use std::result;
use std::sync::Arc;
use time::Duration;
use log;

use delix::logger;
use delix::metric::{self, Metric};
use delix::node::{self, Node};
use delix::discovery::{self, Discovery};
use delix::relay::{self, Relay};
use delix::transport::{self, Transport};
use delix::transport::cipher::{self, Cipher};
use delix::transport::direct::balancer;
use delix::util::resolve;
use configuration::Configuration;

#[derive(Debug)]
pub struct Loader {
    configuration: Configuration,
}

pub type Result<T> = result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    MissingField(&'static str),
    InvalidValue(&'static str, String, Vec<&'static str>),
    NodeError(node::Error),
    Cipher(cipher::Error),
    Relay(relay::Error),
    Resolve(io::Error),
}

impl Loader {
    pub fn new(configuration: Configuration) -> Loader {
        Loader { configuration: configuration }
    }

    pub fn load_metric(&self) -> Result<Arc<metric::Metric>> {
        let metric_type = try!(self.configuration
                                   .string_at("metric.type")
                                   .ok_or(Error::MissingField("metric.type")));

        match metric_type.as_ref() {
            "console" => {
                info!("loaded console metric");
                Ok(Arc::new(metric::Memory::new()))
            }
            "terminal" => {
                info!("loaded terminal metric");
                let refresh_interval_ms = self.configuration
                                              .i64_at("metric.refresh_interval_ms")
                                              .unwrap_or(100);
                Ok(Arc::new(metric::Terminal::new(refresh_interval_ms as u64)))
            }
            _ => {
                Err(Error::InvalidValue("metric.type",
                                        metric_type.to_string(),
                                        vec!["console", "terminal"]))
            }
        }
    }

    pub fn load_log(&self, metric: &Arc<Metric>) -> Result<()> {
        let log_type = try!(self.configuration
                                .string_at("log.type")
                                .ok_or(Error::MissingField("log.type")));

        let log_level_filter = match self.configuration
                                         .string_at("log.level")
                                         .unwrap_or("off".to_string())
                                         .as_ref() {
            "off" => log::LogLevelFilter::Off,
            "error" => log::LogLevelFilter::Error,
            "warn" => log::LogLevelFilter::Warn,
            "info" => log::LogLevelFilter::Info,
            "debug" => log::LogLevelFilter::Debug,
            "trace" => log::LogLevelFilter::Trace,
            _ => log::LogLevelFilter::Off,
        };

        match log_type.as_ref() {
            "console" => {
                logger::Console::init(log_level_filter, "delix", metric).unwrap();
                info!("loaded console log");
                Ok(())
            }
            _ => Err(Error::InvalidValue("log.type", log_type.to_string(), vec!["console"])),
        }
    }

    pub fn load_node(&self, metric: &Arc<metric::Metric>) -> Result<Arc<Node>> {
        let cipher = try!(self.load_cipher());
        let transport = try!(self.load_transport(cipher, metric.clone()));
        let discovery = try!(self.load_discovery(transport.public_address()));

        Ok(Arc::new(try!(Node::new(discovery, transport, metric.clone()))))
    }

    fn load_cipher(&self) -> Result<Box<Cipher>> {
        let cipher_type = try!(self.configuration
                                   .string_at("cipher.type")
                                   .ok_or(Error::MissingField("cipher.type")));

        match cipher_type.as_ref() {
            "symmetric" => {
                let key = try!(self.configuration
                                   .bytes_at("cipher.key")
                                   .ok_or(Error::MissingField("cipher.key")));
                let cipher = try!(cipher::Symmetric::new(&key, None));
                info!("loaded symmetric cipher");
                Ok(Box::new(cipher))
            }
            _ => {
                Err(Error::InvalidValue("cipher.type", cipher_type.to_string(), vec!["symmetric"]))
            }
        }
    }

    fn load_discovery(&self, public_address: SocketAddr) -> Result<Box<Discovery>> {
        let discovery_type = try!(self.configuration
                                      .string_at("discovery.type")
                                      .ok_or(Error::MissingField("discovery.type")));

        match discovery_type.as_ref() {
            "constant" => {
                let addresses = try!(self.configuration
                                         .strings_at("discovery.addresses")
                                         .ok_or(Error::MissingField("discovery.addresses")));
                let addresses = try!(resolve::socket_addresses(&addresses));
                let discovery = discovery::Constant::new(addresses);
                info!("loaded constant discovery");
                Ok(Box::new(discovery))
            }
            "multicast" => {
                let interface_address = try!(self.configuration
                                                 .string_at("discovery.interface_address")
                                                 .ok_or(Error::MissingField("discovery.\
                                                                             interface_address")));
                let interface_address = try!(resolve::socket_address(&interface_address));
                let multicast_address = try!(self.configuration
                                                 .string_at("discovery.multicast_address")
                                                 .ok_or(Error::MissingField("discovery.\
                                                                             multicast_address")));
                let multicast_address = try!(resolve::socket_address(&multicast_address));

                let reply_timeout = Duration::milliseconds(self.configuration
                                                               .i64_at("transport.\
                                                                        reply_timeout_ms")
                                                               .unwrap_or(500));

                let discovery = try!(discovery::Multicast::new(interface_address,
                                                               multicast_address,
                                                               public_address,
                                                               reply_timeout));
                info!("loaded multicast discovery");
                Ok(Box::new(discovery))

            }
            _ => {
                Err(Error::InvalidValue("discovery.type",
                                        discovery_type.to_string(),
                                        vec!["constant"]))
            }
        }
    }

    fn load_transport(&self, cipher: Box<Cipher>, metric: Arc<Metric>) -> Result<Box<Transport>> {
        let transport_type = try!(self.configuration
                                      .string_at("transport.type")
                                      .ok_or(Error::MissingField("transport.type")));

        match transport_type.as_ref() {
            "direct" => {
                let local_address = try!(self.configuration
                                             .string_at("transport.local_address")
                                             .ok_or(Error::MissingField("transport.\
                                                                         local_address")));
                let local_address = try!(resolve::socket_address(&local_address));

                let public_address = match self.configuration
                                               .string_at("transport.public_address") {
                    Some(ref value) => Some(try!(resolve::socket_address(value))),
                    None => None,
                };

                let request_timeout = self.configuration
                                          .i64_at("transport.request_timeout_ms")
                                          .map(|value| Duration::milliseconds(value));

                let balancer_type = try!(self.configuration
                                             .string_at("transport.balancer.type")
                                             .ok_or(Error::MissingField("transport.balancer.\
                                                                         type")));

                let balancer_factory = match balancer_type.as_ref() {
                    "dynamic_round_robin" => Box::new(balancer::DynamicRoundRobinFactory::new()),
                    _ => {
                        return Err(Error::InvalidValue("transport.balancer.type",
                                                       balancer_type.to_string(),
                                                       vec!["dynamic_round_robin"]))
                    }
                };

                info!("loaded direct transport - listening at {}", local_address);

                Ok(Box::new(transport::Direct::new(cipher,
                                                   balancer_factory,
                                                   metric,
                                                   local_address,
                                                   public_address,
                                                   request_timeout)))
            }
            _ => {
                Err(Error::InvalidValue("transport.type",
                                        transport_type.to_string(),
                                        vec!["direct"]))
            }
        }
    }

    pub fn load_relays(&self, node: &Arc<Node>) -> Result<Vec<Box<Relay>>> {
        let mut relays = Vec::new();
        if let Some(configurations) = self.configuration.configurations_at("relay") {
            for configuration in configurations {
                relays.push(try!(load_relay(&configuration, node)));
            }
        }
        Ok(relays)
    }
}

impl From<node::Error> for Error {
    fn from(error: node::Error) -> Self {
        Error::NodeError(error)
    }
}

impl From<cipher::Error> for Error {
    fn from(error: cipher::Error) -> Self {
        Error::Cipher(error)
    }
}

impl From<relay::Error> for Error {
    fn from(error: relay::Error) -> Self {
        Error::Relay(error)
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Error::Resolve(error)
    }
}

fn load_relay(configuration: &Configuration, node: &Arc<Node>) -> Result<Box<Relay>> {
    let relay_type = try!(configuration.string_at("type")
                                       .ok_or(Error::MissingField("relay.type")));

    match relay_type.as_ref() {
        "http" => {
            let address = match configuration.string_at("address") {
                Some(address) => Some(try!(resolve::socket_address(&address))),
                None => None,
            };
            let header_field = configuration.string_at("header_field")
                                            .unwrap_or("X-Delix-Service".to_string());
            let read_timeout = configuration.i64_at("read_timeout_ms")
                                            .map(|value| Duration::milliseconds(value));
            let write_timeout = configuration.i64_at("write_timeout_ms")
                                             .map(|value| Duration::milliseconds(value));
            let services_path = configuration.string_at("services_path");

            let api_address = match configuration.string_at("api.address") {
                Some(address) => Some(try!(resolve::socket_address(&address))),
                None => None,
            };

            let http = try!(relay::Http::bind(node.clone(),
                                              address,
                                              api_address,
                                              &header_field,
                                              read_timeout,
                                              write_timeout,
                                              services_path));

            try!(http.load());

            info!("loaded http relay");

            Ok(Box::new(http))
        }
        _ => Err(Error::InvalidValue("relay.type", relay_type.to_string(), vec!["http"])),
    }
}


text:
import classNames from 'classnames';
import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';

import PreviewPage from '../../pages/PreviewPage';
import styles from './style.scss';

const App = () => (

      <Switch>
        <Route exact path="/" component={PreviewPage} />
        <Redirect to="/" />
      </Switch>

);

export default App;


text:
package ru.org.linux.search

import java.nio.file.Files

import com.sksamuel.elastic4s.ElasticsearchClientUri
import com.sksamuel.elastic4s.http.ElasticClient
import com.sksamuel.elastic4s.http.ElasticDsl._
import org.mockito.Mockito
import org.specs2.mutable.SpecificationWithJUnit
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation._
import org.springframework.stereotype.{Repository, Service}
import org.springframework.test.context.{ContextConfiguration, TestContextManager}
import play.api.libs.ws.StandaloneWSClient
import ru.org.linux.auth.FloodProtector
import ru.org.linux.search.ElasticsearchIndexService.MessageIndex

@ContextConfiguration(classes = Array(classOf[SearchIntegrationTestConfiguration]))
class ElasticsearchIndexServiceIntegrationSpec extends SpecificationWithJUnit {
  new TestContextManager(this.getClass).prepareTestInstance(this)

  @Autowired
  var indexService: ElasticsearchIndexService = _

  @Autowired
  var elastic: ElasticClient = _

  "ElasticsearchIndexService" should {
    "create index" in {
      indexService.createIndexIfNeeded()

      val exists = elastic execute { indexExists(MessageIndex) } await

      exists.result.isExists must beTrue
    }
  }
}

@Configuration
@ImportResource(Array("classpath:common.xml", "classpath:database.xml"))
@ComponentScan(
  basePackages = Array("ru.org.linux"),
  lazyInit = true,
  useDefaultFilters = false,
  includeFilters = Array(
    new ComponentScan.Filter(
      `type` = FilterType.ANNOTATION,
      value = Array(classOf[Service], classOf[Repository])))
)
class SearchIntegrationTestConfiguration {
  class LocalNodeProvider {
    val node = ElasticsearchConfiguration.createEmbedded("test-elastic", Files.createTempDirectory("test-elastic").toFile.getAbsolutePath)

    def close(): Unit = node.stop(true)
  }

  @Bean(destroyMethod="close")
  def elasticNode: LocalNodeProvider = new LocalNodeProvider()

  @Bean
  def elasticClient(node: LocalNodeProvider): ElasticClient = {
    ElasticClient(ElasticsearchClientUri("localhost", 9200))
  }

  @Bean
  def floodProtector: FloodProtector = Mockito.mock(classOf[FloodProtector])

  @Bean
  def httpClient: StandaloneWSClient = Mockito.mock(classOf[StandaloneWSClient])
}


text:
layout: post
title:  Angular Factories
date:   2016-03-11 23:45:41 -0800
---

Angular has a lot of services available that may be confusing at first especially for new devs. One of which is the Factory service. the [Angular documentation](https://docs.angularjs.org/guide/services) provides the following definition
for what a service is:

> The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service.

What does this mean? Lets break it down!

A factory in angular:

* generates an object or a function
* this object or function can be used throughout the app
* access to this object or function is done via injection into any component

So, basically, a factory in Angular allows code (whether it be an object that you need to pass throughout the app or functions relavent to particular components) to be made into components to be reused rather than hardcoding the same logic into controllers. Inject is a scary word, but think of it as just that: you're injecting (or inserting) your code that you created in your factory into a controller, a service, or a directive.

One instance of a factory i've encountered is to use it to pass data along an app. Say you have a form and your client wants you to create multiple pages to help make the flow of the form better and more dynamic. You can use a factory to create an object that contains all of the information the user has filled out and submit the data in one go at the very end.

in a seperate script file (factory.js)
{% highlight javascript %}
  var myModule = angular.module('myModule', []);
  myModule.factory('userAnswers', function() {
    var userAnswers = {
      Q1: "",
      Q2: "",
      Q3: "",
      ...
    };

    return userAnswers;
  });
{% endhighlight %}

Then, in your controller, you just have to insert this factory, the one we name 'userAnswers' into the controller. Every controller we inject this factory too will be able to have access to userAnswers to read, write, and edit the data.

in a controller file(controller.js)
{% highlight javascript %}
  var myApp = angular.module('myApp',[]);

  myApp.controller('FirstFormCtrl', ['$scope', 'userAnswers',  function($scope, userAnswers) {
    // do something here
  }])
  .controller('SecondFormCtrl', ['$scope', 'userAnswers', function($scope, userAnswers){
    //do something else
  }])
  ...
{% endhighlight %}

The reason we must write the variables within the brackets and outside of the function declaration is to help the browser understand the variables once code is minimized. Feel free to read more about [inline injection annotation](https://docs.angularjs.org/guide/di) for the docs. As you can see, we now have access to our object within both controllers (and more if we needed it)! This is a handy trick and is applicable in many ways.

I know I referenced the Angular docs a lot here but I'm getting in the habit of reading and understanding the docs more thoroughly. It's a great habit for any developer to do!


text:
`gitaur-publish` [_PKGBUILD_] [_VERSION_]

`gitaur-publish` `-h`|`--help`

## DESCRIPTION
`gitaur-publish` runs `gitaur-pkgbuild` to populate the `PKGBUILD` if it is
incomplete, creates a source package, and publishes it to the AUR.

If the path to a `PKGBUILD` is not provided, `gitaur-publish` will look in the
current working directory for a `PKGBUILD`.

If a `VERSION` is provided, `gitaur-publish` will create a Git tag, push it to
GitHub and release from that tag. Otherwise, it assumes that a tag has already
been created and pushed. `VERSION` must start with a `v`, followed by a version
number consisting of digits separated by `.`, followed by a '-', followed by a
release number. For example, a valid `VERSION` would be `v1.2.3-4`.

`namcap` is used to check the generated `PKGBUILD` for any problems.

`mksrcinfo` (from the `pkgbuild-introspection` package) is used to build the
source package.

Note that the generated package will be published via Git to
`ssh://aur@aur4.archlinux.org/package`. `gitaur-publish` assumes that the SSH
key is in place to enable this action.

## OPTIONS
* -h, --help:
  Show help text and exit.

## COPYRIGHT
`gitaur` is Copyright (c) 2016 Vinson Chuong under The MIT License.

## SEE ALSO
gitaur-pkgbuild(1), namcap(1)


text:
package net.apnic.rdapd.intervaltree.avl;

import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.generator.GeneratorConfiguration;
import com.pholser.junit.quickcheck.generator.InRange;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;
import net.apnic.rdapd.types.IP;
import net.apnic.rdapd.types.IpInterval;
import net.apnic.rdapd.types.Parsing;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Ipv4IntervalGenerator extends Generator<IpInterval> {

    int lowerBound = low(Parsing.parseCIDRInterval("0.0.0.0"));
    int upperBound = low(Parsing.parseCIDRInterval("255.255.255.255"));
    IpInterval encompassed = Parsing.parseCIDRInterval("10.0.127.0/24");

    public Ipv4IntervalGenerator() {
        super(IpInterval.class);
    }

    @Override
    public IpInterval generate(SourceOfRandomness sourceOfRandomness, GenerationStatus generationStatus) {

        //to encompass encompassed, this must be equal to or lower than the lowest address of the encompassed range
        int generatedAddress = sourceOfRandomness.nextInt(lowerBound, low(encompassed));

        List<Integer> prefixes = IntStream.range(0, 32)
                .filter(prefix -> {
                    int netmask = networkMask(prefix);
                    int addressMask = ~netmask;

                    int minRange = high(this.encompassed) - (generatedAddress & netmask);
                    int maxRange = upperBound - (generatedAddress & netmask);

                    return addressMask >= minRange && addressMask <= maxRange && (generatedAddress & netmask) >= lowerBound;
                }).boxed().collect(Collectors.toList());

        int prefix = sourceOfRandomness.choose(prefixes);

        try {
            return new IpInterval(
                    new IP(Inet4Address.getByAddress(intToByteArray(generatedAddress & networkMask(prefix))))
                    , prefix
            );
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    public void configure(InRange range) {
        lowerBound = low(Parsing.parseCIDRInterval(range.min()));
        upperBound = high(Parsing.parseCIDRInterval(range.max()));
    }

    public void configure(Encompassed encompassed) {
        this.encompassed = Parsing.parseCIDRInterval(encompassed.value());
    }

    private static int byteArrayToInt(byte[] b) {
        final ByteBuffer bb = ByteBuffer.wrap(b);
        return bb.getInt();
    }

    private static byte[] intToByteArray(int i) {
        final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
        bb.putInt(i);
        return bb.array();
    }

    private static int networkMask(int prefix) {
        return 0xFFFFFFFF << 32 - prefix;
    }

    private static int high(IpInterval ipInterval) {
        return byteArrayToInt(ipInterval.high().getAddress().getAddress());
    }

    private static int low(IpInterval ipInterval) {
        return byteArrayToInt(ipInterval.low().getAddress().getAddress());
    }

    @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @GeneratorConfiguration
    public @interface Encompassed {
        String value();
    }
}


text:
import os
import sys
import warnings
import setuptools
import versioneer
from setuptools import setup, Extension

versioneer.VCS = 'git'
versioneer.versionfile_source = 'trackpy/_version.py'
versioneer.versionfile_build = 'trackpy/_version.py'
versioneer.tag_prefix = 'v'
versioneer.parentdir_prefix = '.'

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

# In some cases, the numpy include path is not present by default.
# Let's try to obtain it.
try:
    import numpy
except ImportError:
    ext_include_dirs = []
else:
    ext_include_dirs = [numpy.get_include(),]

setup_parameters = dict(
    name = "trackpy",
    version = versioneer.get_version(),
    cmdclass = versioneer.get_cmdclass(),
    description = "particle-tracking toolkit",
    author = "Trackpy Contributors",
    author_email = "daniel.b.allan@gmail.com",
    url = "https://github.com/soft-matter/trackpy",
    install_requires = ['numpy', 'scipy', 'six', 'pandas',
                        'pyyaml', 'matplotlib', 'pims'],
    packages = ['trackpy'],
    long_description = read('README.md'),
)

setup(**setup_parameters)


text:
Ti.UI.backgroundColor = '#dddddd';

var uie = require('lib/UiElements');
var indicator = uie.createIndicatorWindow();

indicator.openIndicator();

var url = "https://raw.github.com/andi2/01_singleWindow/master/Resources/data/json.txt";
var win = Ti.UI.createWindow();
//win.layout = 'vertical';
win.orientationModes = [Titanium.UI.PORTRAIT];

var scrollView = Titanium.UI.createScrollView({
        contentWidth:'auto',
        contentHeight:'auto',
        //top:0,
        showVerticalScrollIndicator:true,
        showHorizontalScrollIndicator:true,
        layout: 'vertical'
    });

//var table = Ti.UI.createTableView();
var json, fighters, fighter, i, j, rowIndex, rowLength, row, nameLabel, nickLabel,Lista,nodCerut;

var nodIdCurent="1";

var xhr = Ti.Network.createHTTPClient({
    onload: function() {

    json = JSON.parse(this.responseText);
    for (rowIndex = 0 , rowLength = json.customLayoutRow.length; rowIndex < rowLength; rowIndex+=1)
{
            if(json.customLayoutRow[rowIndex].uiElementType==='Label')
            {
            nameLabel = Ti.UI.createLabel({
                text:json.customLayoutRow[rowIndex].labelText,
                font:{
                    fontSize:'24dp',
                    fontWeight:'bold'
                },
                height:'auto',
                left:'10dp',
                top:'5dp',
                color:'#000',
                touchEnabled:false
            });
            scrollView.add(nameLabel);
            }

            if(json.customLayoutRow[rowIndex].uiElementType==='Button')
            {
            simpleButton = Titanium.UI.createButton({
            title:json.customLayoutRow[rowIndex].buttonTitle,
            width: "auto",
            height: "auto"
            });

            var window=win;
                simpleButton.addEventListener("click", function(e){
                    window.refresh();
                });

            scrollView.add(simpleButton);
            //row.add(simpleButton);
            }

            if(json.customLayoutRow[rowIndex].uiElementType==='Slider')
            {
            var simpleSlider = Titanium.UI.createSlider({
            height:"auto",
            width:"auto",
            min:json.customLayoutRow[rowIndex].min, //Minimum value for the slider (needed for Android)
            max:json.customLayoutRow[rowIndex].max //Maximum value for the slider (needed for Android)
            });
            scrollView.add(simpleSlider);
            }

            if(json.customLayoutRow[rowIndex].uiElementType==='Switch')
            {
            var basicSwitch = Titanium.UI.createSwitch({
            value:json.customLayoutRow[rowIndex].value
            });
            scrollView.add(basicSwitch);
            }

            if(json.customLayoutRow[rowIndex].uiElementType==='Picker')
            {
            var picker = Ti.UI.createPicker();
            var data = [];

            var pickerLenght = json.customLayoutRow[rowIndex].PickerRow.length;//aici PickerRow.lenght
            //var pickerLenght = 20;

            for (var pickerIndex = 0 ; pickerIndex < pickerLenght; pickerIndex += 1) {
                data[pickerIndex]=Ti.UI.createPickerRow({
                    title:json.customLayoutRow[rowIndex].PickerRow[pickerIndex]
                    });
            }
            picker.add(data);

            scrollView.add(picker);
            }

            if(json.customLayoutRow[rowIndex].uiElementType==='tableView')
            {

            var tableData=[];
            var tableView = Ti.UI.createTableView();
            var tableViewRow = json.customLayoutRow[rowIndex].tableViewRow;

            for (var tableIndex = 0 , tableLength = tableViewRow.length; tableIndex < tableLength; tableIndex +=1){

                var row = Ti.UI.createTableViewRow({
                        height:'60dp'
                        });

                if(tableViewRow[tableIndex].uiElementType==='Label'){

                    nameLabel = Ti.UI.createLabel({
                        text:tableViewRow[tableIndex].labelText,
                        font:{
                            fontSize:'24dp',
                            fontWeight:'bold'
                        },
                        height:'auto',
                        left:'10dp',
                        top:'5dp',
                        color:'#000',
                        touchEnabled:false
                        });
                        row.add(nameLabel);
                    }
                    tableData.push(row);
                    }
                    tableView.setData(tableData);
                    scrollView.add(tableView);
            }

}// for loop end

    //table.setData(tableData);

    indicator.closeIndicator();

    win.add(scrollView);
    },
    onerror: function(e) {
    Ti.API.debug("STATUS: " + this.status);
    Ti.API.debug("TEXT:   " + this.responseText);
    Ti.API.debug("ERROR:  " + e.error);
    alert('Connection error \nThere was an error retrieving the remote data. Try again.');
    },
    timeout:5000
});

xhr.open("GET", url);
xhr.send();

    function refresh() {

        win.remove(scrollView);
        indicator.openIndicator();

        var i,j;

        // perfect view clear
        if (scrollView && scrollView.children != undefined)
        {
            // Save childrens
            var removeData = [];
            for (i = scrollView.children.length; i > 0; i--){
                removeData.push(scrollView.children[i - 1]);
            };

            // Remove childrens
            for (i = 0, j = removeData.length; i < j; i++){
                scrollView.remove(removeData[i]);
            }
            removeData = null;
        };

        xhr.send();
    };

    win.refresh = refresh;

win.open();


text:
'use strict';

//Setting up route
angular.module('mean').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise(function ($injector, $location) {
        $injector.invoke(['$state', function ($state) {
            $state.go('404');
        }]);
    });

    $stateProvider
        .state('home', {
            url: '/',
            controller: 'IndexController',
            templateUrl: 'views/index.html'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'views/users/login.html'
        })
        .state('register', {
            url: '/register',
            templateUrl: 'views/users/register.html'
        })
        .state('forgetpassword', {
            url: '/forgetpassword',
            controller: 'ForgetPasswordController',
            templateUrl: 'views/users/forgetPassword.html'
        })
        .state('resetpassword', {
            url: '/resetpassword/token={token}/verify',
            controller: 'ResetPasswordController',
            templateUrl: 'views/users/resetPassword.html'
        })
        .state('aboutus', {
            url: '/aboutus',
            templateUrl: 'views/aboutus.html'
        })
        .state('faq', {
            url: '/faq',
            templateUrl: 'views/faq.html'
        })
        .state('contactus', {
            url: '/contactus',
            templateUrl: 'views/contactUs.html'
        })
        .state('articles', {
            url: '/article',
            controller: 'ArticlesController',
            templateUrl: 'views/articles/list.html'
        })
        .state('createarticle', {
            url: '/article/create',
            controller: 'ArticlesController',
            templateUrl: 'views/articles/create.html'
        })
        .state('editarticles', {
            url: '/article/{articleId}/edit',
            controller: 'ArticlesController',
            templateUrl: 'views/articles/edit.html'
        })
        .state('viewarticle', {
            url: '/article/{articleId}',
            controller: 'ArticlesController',
            templateUrl: 'views/articles/view.html'
        })
        .state('productdetails', {
            url: '/productdetails',
            params: {
                prodTravel: null
            },
            controller: 'ProductDetailsController',
            templateUrl: 'views/productDetails.html'
        })
        .state('userprofile', {
            url: '/userprofile',
            params: {
                profileId: '',
            },
            controller: 'UserProfileController',
            templateUrl: 'views/users/userProfile.html'
        })
        .state('address', {
            url: '/address',
            params: {
                profileId: '',
                profile: ''
            },
            controller: 'AddressController',
            templateUrl: 'views/users/address.html'
        })
        .state('order', {
            url: '/order',
            params: {
                profile: ''
            },
            controller: 'OrderController',
            templateUrl: 'views/users/order.html'
        })
        .state('post', {
            url: '/post',
            params: {
                profile: ''
            },
            controller: 'PostController',
            templateUrl: 'views/users/post.html'
        })
        .state('request', {
            url: '/request',
            params: {
                profile: ''
            },
            controller: 'RequestController',
            templateUrl: 'views/users/request.html'
        })
        // .state('uploadimage', {
        //     url: '/uploadimage',
        //     controller: 'UploadImageController',
        //     templateUrl: 'views/uploadImage.html'
        // })
        .state('404', {
            templateUrl: 'views/404.html'
        })
        .state('500', {
            templateUrl: 'views/500.html'
        })
        .state('profileIcon', {
            url: '/profileIcon',
            templateUrl: 'views/users/account-orders.html'
        })
        .state('searchResult', {
            url: '/searchresult',
            params: {
                prodTravel: null,
                prodRequest: null
            },
            controller: 'SearchResultController',
            templateUrl: 'views/searchResult.html'
        })
        .state('searchCountry', {
            url: '/searchcountry',
            params: {
                productDetailID: null
            },
            controller: 'SearchCountryController',
            templateUrl: 'views/searchCountry.html'
        })
        .state('postProductDetail', {
            url: '/postproductdetail',
            params: {
                productID: null
            },
            controller: 'PostProductDetailController',
            templateUrl: 'views/postProductDetail.html'
        })
        .state('editProductDetail', {
            url: '/editproductdetail',
            params: {
                productDet: null
            },
            controller: 'EditProductDetailController',
            templateUrl: 'views/editProductDetail.html'
        })
        .state('userprofilemain', {
            url: '/userprofilemain',
            controller: 'UserProfileMainController',
            templateUrl: 'views/users/userprofilemain.html'
        })
        .state('chat', {
            url: '/chat',
            params: {
                sellerInfo: '',
                prodTravel: null
            },
            controller: 'ChatController',
            templateUrl: 'views/chat/chat.html'
        })
        .state('travel', {
            url: '/travel',
            params: {
                //productObj: null,
                buyer: false
            },
            controller: 'TravelController',
            templateUrl: 'views/travel/postTravel.html'
        })
        .state('postproduct', {
            url: '/postproduct',
            params: {
                travelObj: null
            },
            controller: 'ProductController',
            templateUrl: 'views/travel/postProduct.html'
        })
        .state('postreview', {
            url: '/postreview',
            params: {
                productObj: null
            },
            controller: 'ReviewController',
            templateUrl: 'views/travel/postReview.html'
        });
}]);

//Setting HTML5 Location Mode
angular.module('mean').config(['$locationProvider', function ($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

angular.module('mean').run(function ($rootScope, $location, $state, CheckLoggedIn, $window) {
    $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
        var isLogin = toState.name === "login";
        if (isLogin) {
            return;
        }

        CheckLoggedIn.get(function (response) {
            if (response.status === '0' && toState.name === 'travel') {
                e.preventDefault();
                $state.go('login');
            }else{
                $rootScope.currentUser = response;
                $window.sessionStorage.setItem("id", response.id);
            }
        });
    });
});


text:
var child_process = require('child_process');
var map = require('map-stream');
var gutil = require('gulp-util');
var cssxTranspiler = require('cssx-transpiler');
var browserify = require('browserify');
var cssxTransform = require('browserify-cssx');
var intoStream = require('into-stream');
var cssx = require('cssx');
var path = require('path');

cssx.domChanges(false);
cssx.minify(false);

module.exports = function(options) {
   var ops = {
      execute: options && options.execute ? options.execute : false
   };

   return map(function(file, cb) {
      var error = null, transpiled;

      // execute to css
      if (ops.execute) {
        var b = browserify(intoStream(file.contents), {
          transform: [ cssxTransform ],
          basedir: path.dirname(file.path),
          cssx: options
        });
        b.bundle(function (err, buff) {
          var codeToRun = buff.toString('utf8'), func, generatedCSS, css;

          try {
            func = new Function('cssx', codeToRun);
            func(cssx);
            generatedCSS = cssx.getStylesheets().map(function (stylesheet) {
              return stylesheet.compileImmediate().getCSS();
            });
            css = generatedCSS.join('');
          } catch (err) {
            cb(err); return;
          }
          file.contents = new Buffer(css);
          cb(error, file);
        });
      // transpile
      } else {
         try {
            transpiled = cssxTranspiler(file.contents.toString('utf8'), options);
         } catch (err) {
            cb(err);
            return;
         }
         file.contents = new Buffer(transpiled);
         cb(error, file);
      }

   });
};

module.exports.transpiler = cssxTranspiler;


text:
package intellij.haskell.testIntegration

import java.util

import com.intellij.psi.PsiElement
import com.intellij.psi.search.{FilenameIndex, GlobalSearchScope}
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testIntegration.TestFinder
import intellij.haskell.HaskellFile

import scala.jdk.CollectionConverters._

/**
  * Triggered when the user uses the "Navigation / Test"  action (= jump to test shortcut)
  */
class HaskellTestFinder extends TestFinder {

  /**
    * Return the parent PsiFile of the PsiElement where the cursor was when the test finder was invoked, to handle some magic stuff, like the name displayed in "Choose Test for {file name}".
    */
  override def findSourceElement(psiElement: PsiElement): PsiElement = {
    PsiTreeUtil.getParentOfType(psiElement, classOf[HaskellFile])
  }

  /**
    * Given a source PSI element, find all test files this element could be a source of.
    */
  override def findTestsForClass(psiElement: PsiElement): util.Collection[PsiElement] = {
    val testFileName = psiElement.getContainingFile.getName.replace(".hs", "Spec.hs")
    val testFiles: Seq[PsiElement] = FilenameIndex.getFilesByName(psiElement.getProject, testFileName, GlobalSearchScope.projectScope(psiElement.getProject)).toIndexedSeq
    testFiles.asJavaCollection
  }

  /**
    * Given a test PSI element, find all source files this element could be a test of.
    */
  override def findClassesForTest(psiElement: PsiElement): util.Collection[PsiElement] = {
    val sourceFileName = psiElement.getContainingFile.getName.replace("Spec.hs", ".hs")
    val sourceFiles: Seq[PsiElement] = FilenameIndex.getFilesByName(psiElement.getProject, sourceFileName, GlobalSearchScope.projectScope(psiElement.getProject)).toIndexedSeq
    sourceFiles.asJavaCollection
  }

  override def isTest(psiElement: PsiElement): Boolean = {
    psiElement.getContainingFile.getName.endsWith("Spec.hs")
  }
}


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	/**
	 * Copyright (c) 2015-present, Facebook, Inc.
	 * All rights reserved.
	 *
	 * This source code is licensed under the BSD-style license found in the
	 * LICENSE file in the root directory of this source tree. An additional grant
	 * of patent rights can be found in the PATENTS file in the same directory.
	 *
	 *
	 */
	'use strict';

	/* global chrome */

	var ports = {};

	chrome.runtime.onConnect.addListener(function (port) {
	  var tab = null;
	  var name = null;
	  if (isNumeric(port.name)) {
	    tab = port.name;
	    name = 'devtools';
	    installContentScript(+port.name);
	  } else {
	    tab = port.sender.tab.id;
	    name = 'content-script';
	  }

	  if (!ports[tab]) {
	    ports[tab] = {
	      devtools: null,
	      'content-script': null
	    };
	  }
	  ports[tab][name] = port;

	  if (ports[tab].devtools && ports[tab]['content-script']) {
	    doublePipe(ports[tab].devtools, ports[tab]['content-script']);
	  }
	});

	function isNumeric(str) {
	  return +str + '' === str;
	}

	function installContentScript(tabId) {
	  chrome.tabs.executeScript(tabId, { file: '/build/contentScript.js' }, function () {});
	}

	function doublePipe(one, two) {
	  one.onMessage.addListener(lOne);
	  function lOne(message) {
	    // console.log('dv -> rep', message);
	    two.postMessage(message);
	  }
	  two.onMessage.addListener(lTwo);
	  function lTwo(message) {
	    // console.log('rep -> dv', message);
	    one.postMessage(message);
	  }
	  function shutdown() {
	    one.onMessage.removeListener(lOne);
	    two.onMessage.removeListener(lTwo);
	    one.disconnect();
	    two.disconnect();
	  }
	  one.onDisconnect.addListener(shutdown);
	  two.onDisconnect.addListener(shutdown);
	}

/***/ }
/******/ ]);


text:
package com.mynotes;

import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class AtyVideoViewer extends Activity {

    private VideoView vv;
    public static final String EXTRA_PATH="path";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        vv=new VideoView(this);
        vv.setMediaController(new MediaController(this));
        setContentView(vv);

        String path=getIntent().getStringExtra(EXTRA_PATH);
        if (path!=null){
            vv.setVideoPath(path);
        }else{
            finish();
        }
    }
}


text:
#ifndef _ASM_IA64_BITOPS_H
#define _ASM_IA64_BITOPS_H

#ifndef _LINUX_BITOPS_H
#error only <linux/bitops.h> can be included directly
#endif

#include <linux/compiler.h>
#include <linux/types.h>
#include <asm/intrinsics.h>
#include <asm/barrier.h>

/**
 * set_bit - Atomically set a bit in memory
 * @nr: the bit to set
 * @addr: the address to start counting from
 *
 * This function is atomic and may not be reordered.  See __set_bit()
 * if you do not require the atomic guarantees.
 * Note that @nr may be almost arbitrarily large; this function is not
 * restricted to acting on a single-word quantity.
 *
 * The address must be (at least) "long" aligned.
 * Note that there are driver (e.g., eepro100) which use these operations to
 * operate on hw-defined data-structures, so we can't easily change these
 * operations to force a bigger alignment.
 *
 * bit 0 is the LSB of addr; bit 32 is the LSB of (addr+1).
 */
static __inline__ void
set_bit (int nr, volatile void *addr)
{
	__u32 bit, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	bit = 1 << (nr & 31);
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old | bit;
	} while (cmpxchg_acq(m, old, new) != old);
}

/**
 * __set_bit - Set a bit in memory
 * @nr: the bit to set
 * @addr: the address to start counting from
 *
 * Unlike set_bit(), this function is non-atomic and may be reordered.
 * If it's called on the same region of memory simultaneously, the effect
 * may be that only one operation succeeds.
 */
static __inline__ void
__set_bit (int nr, volatile void *addr)
{
	*((__u32 *) addr + (nr >> 5)) |= (1 << (nr & 31));
}

/**
 * clear_bit - Clears a bit in memory
 * @nr: Bit to clear
 * @addr: Address to start counting from
 *
 * clear_bit() is atomic and may not be reordered.  However, it does
 * not contain a memory barrier, so if it is used for locking purposes,
 * you should call smp_mb__before_atomic() and/or smp_mb__after_atomic()
 * in order to ensure changes are visible on other processors.
 */
static __inline__ void
clear_bit (int nr, volatile void *addr)
{
	__u32 mask, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	mask = ~(1 << (nr & 31));
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old & mask;
	} while (cmpxchg_acq(m, old, new) != old);
}

/**
 * clear_bit_unlock - Clears a bit in memory with release
 * @nr: Bit to clear
 * @addr: Address to start counting from
 *
 * clear_bit_unlock() is atomic and may not be reordered.  It does
 * contain a memory barrier suitable for unlock type operations.
 */
static __inline__ void
clear_bit_unlock (int nr, volatile void *addr)
{
	__u32 mask, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	mask = ~(1 << (nr & 31));
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old & mask;
	} while (cmpxchg_rel(m, old, new) != old);
}

/**
 * __clear_bit_unlock - Non-atomically clears a bit in memory with release
 * @nr: Bit to clear
 * @addr: Address to start counting from
 *
 * Similarly to clear_bit_unlock, the implementation uses a store
 * with release semantics. See also arch_spin_unlock().
 */
static __inline__ void
__clear_bit_unlock(int nr, void *addr)
{
	__u32 * const m = (__u32 *) addr + (nr >> 5);
	__u32 const new = *m & ~(1 << (nr & 31));

	ia64_st4_rel_nta(m, new);
}

/**
 * __clear_bit - Clears a bit in memory (non-atomic version)
 * @nr: the bit to clear
 * @addr: the address to start counting from
 *
 * Unlike clear_bit(), this function is non-atomic and may be reordered.
 * If it's called on the same region of memory simultaneously, the effect
 * may be that only one operation succeeds.
 */
static __inline__ void
__clear_bit (int nr, volatile void *addr)
{
	*((__u32 *) addr + (nr >> 5)) &= ~(1 << (nr & 31));
}

/**
 * change_bit - Toggle a bit in memory
 * @nr: Bit to toggle
 * @addr: Address to start counting from
 *
 * change_bit() is atomic and may not be reordered.
 * Note that @nr may be almost arbitrarily large; this function is not
 * restricted to acting on a single-word quantity.
 */
static __inline__ void
change_bit (int nr, volatile void *addr)
{
	__u32 bit, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	bit = (1 << (nr & 31));
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old ^ bit;
	} while (cmpxchg_acq(m, old, new) != old);
}

/**
 * __change_bit - Toggle a bit in memory
 * @nr: the bit to toggle
 * @addr: the address to start counting from
 *
 * Unlike change_bit(), this function is non-atomic and may be reordered.
 * If it's called on the same region of memory simultaneously, the effect
 * may be that only one operation succeeds.
 */
static __inline__ void
__change_bit (int nr, volatile void *addr)
{
	*((__u32 *) addr + (nr >> 5)) ^= (1 << (nr & 31));
}

/**
 * test_and_set_bit - Set a bit and return its old value
 * @nr: Bit to set
 * @addr: Address to count from
 *
 * This operation is atomic and cannot be reordered.
 * It also implies the acquisition side of the memory barrier.
 */
static __inline__ int
test_and_set_bit (int nr, volatile void *addr)
{
	__u32 bit, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	bit = 1 << (nr & 31);
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old | bit;
	} while (cmpxchg_acq(m, old, new) != old);
	return (old & bit) != 0;
}

/**
 * test_and_set_bit_lock - Set a bit and return its old value for lock
 * @nr: Bit to set
 * @addr: Address to count from
 *
 * This is the same as test_and_set_bit on ia64
 */
#define test_and_set_bit_lock test_and_set_bit

/**
 * __test_and_set_bit - Set a bit and return its old value
 * @nr: Bit to set
 * @addr: Address to count from
 *
 * This operation is non-atomic and can be reordered.
 * If two examples of this operation race, one can appear to succeed
 * but actually fail.  You must protect multiple accesses with a lock.
 */
static __inline__ int
__test_and_set_bit (int nr, volatile void *addr)
{
	__u32 *p = (__u32 *) addr + (nr >> 5);
	__u32 m = 1 << (nr & 31);
	int oldbitset = (*p & m) != 0;

	*p |= m;
	return oldbitset;
}

/**
 * test_and_clear_bit - Clear a bit and return its old value
 * @nr: Bit to clear
 * @addr: Address to count from
 *
 * This operation is atomic and cannot be reordered.
 * It also implies the acquisition side of the memory barrier.
 */
static __inline__ int
test_and_clear_bit (int nr, volatile void *addr)
{
	__u32 mask, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	mask = ~(1 << (nr & 31));
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old & mask;
	} while (cmpxchg_acq(m, old, new) != old);
	return (old & ~mask) != 0;
}

/**
 * __test_and_clear_bit - Clear a bit and return its old value
 * @nr: Bit to clear
 * @addr: Address to count from
 *
 * This operation is non-atomic and can be reordered.
 * If two examples of this operation race, one can appear to succeed
 * but actually fail.  You must protect multiple accesses with a lock.
 */
static __inline__ int
__test_and_clear_bit(int nr, volatile void * addr)
{
	__u32 *p = (__u32 *) addr + (nr >> 5);
	__u32 m = 1 << (nr & 31);
	int oldbitset = (*p & m) != 0;

	*p &= ~m;
	return oldbitset;
}

/**
 * test_and_change_bit - Change a bit and return its old value
 * @nr: Bit to change
 * @addr: Address to count from
 *
 * This operation is atomic and cannot be reordered.
 * It also implies the acquisition side of the memory barrier.
 */
static __inline__ int
test_and_change_bit (int nr, volatile void *addr)
{
	__u32 bit, old, new;
	volatile __u32 *m;
	CMPXCHG_BUGCHECK_DECL

	m = (volatile __u32 *) addr + (nr >> 5);
	bit = (1 << (nr & 31));
	do {
		CMPXCHG_BUGCHECK(m);
		old = *m;
		new = old ^ bit;
	} while (cmpxchg_acq(m, old, new) != old);
	return (old & bit) != 0;
}

/**
 * __test_and_change_bit - Change a bit and return its old value
 * @nr: Bit to change
 * @addr: Address to count from
 *
 * This operation is non-atomic and can be reordered.
 */
static __inline__ int
__test_and_change_bit (int nr, void *addr)
{
	__u32 old, bit = (1 << (nr & 31));
	__u32 *m = (__u32 *) addr + (nr >> 5);

	old = *m;
	*m = old ^ bit;
	return (old & bit) != 0;
}

static __inline__ int
test_bit (int nr, const volatile void *addr)
{
	return 1 & (((const volatile __u32 *) addr)[nr >> 5] >> (nr & 31));
}

/**
 * ffz - find the first zero bit in a long word
 * @x: The long word to find the bit in
 *
 * Returns the bit-number (0..63) of the first (least significant) zero bit.
 * Undefined if no zero exists, so code should check against ~0UL first...
 */
static inline unsigned long
ffz (unsigned long x)
{
	unsigned long result;

	result = ia64_popcnt(x & (~x - 1));
	return result;
}

/**
 * __ffs - find first bit in word.
 * @x: The word to search
 *
 * Undefined if no bit exists, so code should check against 0 first.
 */
static __inline__ unsigned long
__ffs (unsigned long x)
{
	unsigned long result;

	result = ia64_popcnt((x-1) & ~x);
	return result;
}

#ifdef __KERNEL__

/*
 * Return bit number of last (most-significant) bit set.  Undefined
 * for x==0.  Bits are numbered from 0..63 (e.g., ia64_fls(9) == 3).
 */
static inline unsigned long
ia64_fls (unsigned long x)
{
	long double d = x;
	long exp;

	exp = ia64_getf_exp(d);
	return exp - 0xffff;
}

/*
 * Find the last (most significant) bit set.  Returns 0 for x==0 and
 * bits are numbered from 1..32 (e.g., fls(9) == 4).
 */
static inline int
fls (int t)
{
	unsigned long x = t & 0xffffffffu;

	if (!x)
		return 0;
	x |= x >> 1;
	x |= x >> 2;
	x |= x >> 4;
	x |= x >> 8;
	x |= x >> 16;
	return ia64_popcnt(x);
}

/*
 * Find the last (most significant) bit set.  Undefined for x==0.
 * Bits are numbered from 0..63 (e.g., __fls(9) == 3).
 */
static inline unsigned long
__fls (unsigned long x)
{
	x |= x >> 1;
	x |= x >> 2;
	x |= x >> 4;
	x |= x >> 8;
	x |= x >> 16;
	x |= x >> 32;
	return ia64_popcnt(x) - 1;
}

#include <asm-generic/bitops/fls64.h>

#include <asm-generic/bitops/builtin-ffs.h>

/*
 * hweightN: returns the hamming weight (i.e. the number
 * of bits set) of a N-bit word
 */
static __inline__ unsigned long __arch_hweight64(unsigned long x)
{
	unsigned long result;
	result = ia64_popcnt(x);
	return result;
}

#define __arch_hweight32(x) ((unsigned int) __arch_hweight64((x) & 0xfffffffful))
#define __arch_hweight16(x) ((unsigned int) __arch_hweight64((x) & 0xfffful))
#define __arch_hweight8(x)  ((unsigned int) __arch_hweight64((x) & 0xfful))

#include <asm-generic/bitops/const_hweight.h>

#endif /* __KERNEL__ */

#include <asm-generic/bitops/find.h>

#ifdef __KERNEL__

#include <asm-generic/bitops/le.h>

#include <asm-generic/bitops/ext2-atomic-setbit.h>

#include <asm-generic/bitops/sched.h>

#endif /* __KERNEL__ */

#endif /* _ASM_IA64_BITOPS_H */


text:
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.node as node
import logging

logging.basicConfig(level=logging.DEBUG)

AUTOSYNTH_MULTIPLE_COMMITS = True

common_templates = gcp.CommonTemplates()
templates = common_templates.node_library()
s.copy(templates, excludes=['.eslintignore'])

node.install()
node.fix()


text:
set -e

config_path=/data/conf/zabbix_agentd.conf
update_config_var() {
    local var_name=$1
    local var_value=$2
    local is_multiple=$3

    # Remove configuration parameter definition in case of unset parameter value
    if [ -z "$var_value" ]; then
        sed -i -e "/$var_name=/d" "$config_path"
        echo "Bootstrap: removed $var_name"
        return
    fi

    # Escaping "/" character in parameter value
    var_value=${var_value//\//\\/}

    if [ "$(grep -E "^$var_name=" $config_path)" ] && [ "$is_multiple" != "true" ]; then
        sed -i -e "/^$var_name=/s/=.*/=$var_value/" "$config_path"
        echo "Bootstrap: updated $var_name to $var_value"
    elif [ "$(grep -Ec "^# $var_name=" $config_path)" -gt 1 ]; then
        sed -i -e  "/^[#;] $var_name=$/i\\$var_name=$var_value" "$config_path"
        echo "Bootstrap: added first occurrence of $var_name to $var_value"
    else
        sed -i -e "/^[#;] $var_name=/s/.*/&\n$var_name=$var_value/" "$config_path"
        echo "Bootstrap: added $var_name=$var_value"
    fi

}

if [ -d "/conf" ]; then
  echo "Bootstrap: found configuration folder, copying contents to /data"
  cp -R /conf /data/
fi

update_config_var "Server" "${ZBX_Server}"

# add the required user parameters to the configuration if it is missing
if ! grep -q "UserParameter=docker.containers.discovery" "$config_path"; then
  echo "Initializing UserParameter for Docker monitoring..."
  echo "UserParameter=docker.containers.discovery,/data/discover.py" >> "$config_path"
  echo "UserParameter=docker.containers[*],/data/discover.py \$1 \$2" >>  "$config_path"
fi

chown -R zabbix /data/conf /data/discover.py /var/run/docker.sock
echo "Bootstrap: starting agent..."
sudo -u zabbix zabbix_agentd -f -c "$config_path"


text:
'use strict';

import RuleOfHooks from './RulesOfHooks';
import ExhaustiveDeps from './ExhaustiveDeps';

export const rules = {
  'rules-of-hooks': RuleOfHooks,
  'exhaustive-deps': ExhaustiveDeps,
};


text:
echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"

# Build the project.
hugo -t casper

# Add changes to git.
git add -A

# Commit changes.
msg="rebuilding site `date`"
if [ $# -eq 1 ]
    then msg="$1"
    fi
    git commit -m "$msg"

    # Push source and build repos.
    git push origin master
    git subtree push --prefix=public https://github.com/ashyadav/ashtech.git gh-pages


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _sparkPlugin = require('../lib/spark-plugin');

var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);

var _sparkCore = require('../spark-core');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var precedence = {
  error: ['log'],
  warn: ['error', 'log'],
  info: ['log'],
  debug: ['info', 'log'],
  trace: ['debug', 'info', 'log']
};

/**
 * Assigns the specified console method to Logger; uses `precedence` to fallback
 * to other console methods if the current environment doesn't provide the
 * specified level.
 * @param {string} level
 * @returns {Function}
 */
function wrapConsoleMethod(level) {
  /* eslint no-console: [0] */
  var impls = precedence[level];
  if (impls) {
    impls = impls.slice();
    while (!console[level]) {
      level = impls.pop();
    }
  }

  return console[level].bind(console);
}

var Logger = _sparkPlugin2.default.extend({
  namespace: 'Logger',
  error: wrapConsoleMethod('error'),
  warn: wrapConsoleMethod('warn'),
  log: wrapConsoleMethod('log'),
  info: wrapConsoleMethod('info'),
  debug: wrapConsoleMethod('debug'),
  trace: wrapConsoleMethod('trace')
});

(0, _sparkCore.registerPlugin)('logger', Logger);

exports.default = Logger;
//# sourceMappingURL=logger.js.map


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('lingcod.loadshp.views',
    url(r'^single/$', 'load_single_shp', name='loadshp-single'),
)


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

</body>
<footer>
        <script src="/parser.min.js"></script>
        <script>
        </script>
</footer>
</html>


text:
Roster Item Exchange
====================

This extension is used to send rosters, roster groups and roster entries from
one XMPP Entity to another. It also provides an easy way to hook up custom
logic when entries are received from other XMPP clients.

Follow these links to learn how to send and receive roster items:

  * Send a complete roster
  * Send a roster's group
  * Send a roster's entry
  * Receive roster entries

**XEP related:** [XEP-93](http://www.xmpp.org/extensions/xep-0093.html)

Send a entire roster
-------------------

**Description**

Sometimes it is useful to send a whole roster to another user. Smack provides
a very easy way to send a complete roster to another XMPP client.

**Usage**

Create an instance of _**RosterExchangeManager**_ and use the **#send(Roster,
String)** message to send a roster to a given user. The first parameter is the
roster to send and the second parameter is the id of the user that will
receive the roster entries.

**Example**

In this example we can see how user1 sends his roster to user2.

```
XMPPConnection conn1 = …

// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send user1's roster to user2
rosterExchangeManager.send(conn1.getRoster(), user2);
```

Send a roster group
-------------------

**Description**

It is also possible to send a roster group to another XMPP client. A roster
group groups a set of roster entries under a name.

**Usage**

Create an instance of _**RosterExchangeManager**_ and use the
**#send(RosterGroup, String)** message to send a roster group to a given user.
The first parameter is the roster group to send and the second parameter is
the id of the user that will receive the roster entries.

**Example**

In this example we can see how user1 sends his roster groups to user2.

```
XMPPConnection conn1 = …

// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send user1's RosterGroups to user2
for (Iterator it = conn1.getRoster().getGroups(); it.hasNext(); )
rosterExchangeManager.send((RosterGroup)it.next(), user2);
```

Send a roster entry
-------------------

**Description**

Sometimes you may need to send a single roster entry to another XMPP client.
Smack also lets you send items at this granularity level.

**Usage**

Create an instance of _**RosterExchangeManager**_ and use the
**#send(RosterEntry, String)** message to send a roster entry to a given user.
The first parameter is the roster entry to send and the second parameter is
the id of the user that will receive the roster entries.

**Example**

In this example we can see how user1 sends a roster entry to user2.

```
XMPPConnection conn1 = …

// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send a roster entry (any) to user2
rosterExchangeManager1.send((RosterEntry)conn1.getRoster().getEntries().next(), user2);
```

Receive roster entries
----------------------

**Description**

Since roster items are sent between XMPP clients, it is necessary to listen to
possible roster entries receptions. Smack provides a mechanism that you can
use to execute custom logic when roster entries are received.

**Usage**

  1. Create a class that implements the _**RosterExchangeListener**_ interface.
  2. Implement the method **entriesReceived(String, Iterator)** that will be called when new entries are received with custom logic.
  3. Add the listener to the _RosterExchangeManager_ that works on the desired _XMPPConnection_.

**Example**

In this example we can see how user1 sends a roster entry to user2 and user2
adds the received entries to his roster.

```
// Connect to the server and log in the users
XMPPConnection conn1 = …
XMPPConnection conn2 = …

final Roster user2_roster = conn2.getRoster();

// Create a RosterExchangeManager that will help user2 to listen and accept
the entries received
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(conn2);
// Create a RosterExchangeListener that will iterate over the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator remoteRosterEntries) {
while (remoteRosterEntries.hasNext()) {
try {
// Get the received entry
RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) remoteRosterEntries.next();
// Display the remote entry on the console
System.out.println(remoteRosterEntry);
// Add the entry to the user2's roster
user2_roster.createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
}
catch (XMPPException e) {
e.printStackTrace();
}
}
}
};
// Add the RosterExchangeListener to the RosterExchangeManager that user2 is using
rosterExchangeManager2.addRosterListener(rosterExchangeListener);

// Create a RosterExchangeManager that will help user1 to send his roster
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(conn1);
// Send user1's roster to user2
rosterExchangeManager1.send(conn1.getRoster(), user2);
```


text:
package org.tomighty.log;

import org.tomighty.ioc.Provider;

public class LogProvider implements Provider<Log> {

	@Override
	public Log createFor(Object needer) {
		return new Log(needer.getClass());
	}

}


text:
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkLSMImageIO_h
#define itkLSMImageIO_h
#include "ITKIOLSMExport.h"

#include "itkTIFFImageIO.h"
#include <fstream>

namespace itk
{
/** \class LSMImageIO
 *
 *  \brief ImageIO class for reading LSM (Zeiss) images
 * LSM is a line of confocal laser scanning microscopes produced by the Zeiss company
 * LSM files are essentially extensions of the TIFF multiple image stack file format.
 *
 * \ingroup IOFilters
 *
 * \ingroup ITKIOLSM
 */
class ITKIOLSM_EXPORT LSMImageIO:public TIFFImageIO
{
public:
  /** Standard class typedefs. */
  typedef LSMImageIO           Self;
  typedef ImageIOBase          Superclass;
  typedef SmartPointer< Self > Pointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(LSMImageIO, Superclass);

  /*-------- This part of the interface deals with reading data. ------ */

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanReadFile(const char *) ITK_OVERRIDE;

  /** Set the spacing and dimesion information for the current filename. */
  virtual void ReadImageInformation() ITK_OVERRIDE;

  /** Reads the data from disk into the memory buffer provided. */
  virtual void Read(void *buffer) ITK_OVERRIDE;

  /*-------- This part of the interfaces deals with writing data. ----- */

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanWriteFile(const char *) ITK_OVERRIDE;

  /** Writes the spacing and dimensions of the image.
   * Assumes SetFileName has been called with a valid file name. */
  virtual void WriteImageInformation() ITK_OVERRIDE {}

  /** Writes the data to disk from the memory buffer provided. Make sure
   * that the IORegion has been set properly. */
  virtual void Write(const void *buffer) ITK_OVERRIDE;

protected:
  LSMImageIO();
  ~LSMImageIO();
  virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

private:
  LSMImageIO(const Self &);     //purposely not implemented
  void operator=(const Self &); //purposely not implemented

  void FillZeissStruct(char *z);
};
} // end namespace itk

#endif // itkLSMImageIO_h


text:
.normal {
    font-size: 14;
    horizontal-align: center;
    margin: 10;
}

.copyright {
    font-size: 14;
    margin: 10;
}

.Lobster {
    font-family:Lobster-Regular;
}

.IndieFlower {
    font-family:IndieFlower;
}

.JosefinSans {
    font-family:JosefinSans-Regular,Josefin Sans;
}

.Material {
    font-family: MaterialIcons-Regular, Material Icons;
}

.FontAwesome {
    font-family: FontAwesome;
}

.MaterialIconic {
    font-family: Material-Design-Iconic-Font;
}

.larger {
    font-size: 24;
    horizontal-align: center;
    margin: 10;

}


text:
using log4net;
using System;

namespace Log4NetAppender
{
    public static class Logger
    {
        private static ILog _activity = LogManager.GetLogger("Activity");
        private static ILog _exception = LogManager.GetLogger("Exception");
        public static void Activity(string message)
        {
            _activity.Info(message);
        }
        public static void Exception(string message, Exception ex)
        {
            _exception.Error(message, ex);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Interactivity;

using Kbtter3.ViewModels;
using Newtonsoft.Json;

using Livet;
using Livet.EventListeners;
using Livet.EventListeners.WeakEvents;
using System.ComponentModel;

namespace Kbtter3.Views
{

    /// <summary>
    /// StatusPage.xaml の相互作用ロジック
    /// </summary>
    internal partial class StatusPage : Page
    {
        LivetCompositeDisposable composite;
        PropertyChangedWeakEventListener ctxlistener;

        Storyboard sb;
        bool showed = false;
        IList<StatusViewModel.StatusElement> elm;
        string stsn;
        StatusViewModel statvm;

        static Kbtter3Setting setting;

        static StatusPage()
        {
            setting = Kbtter3Extension.LoadJson<Kbtter3Setting>(App.ConfigurationFileName);
        }

        public StatusPage(StatusViewModel vm)
        {
            statvm = vm;
            DataContext = vm;
            InitializeComponent();
            elm = vm.TextElements;
            stsn = vm.ScreenName;

            if (vm.Via == "") StackPanelBlockVia.Visibility = Visibility.Collapsed;
            SetMainText();

            composite = new LivetCompositeDisposable();
            ctxlistener = new PropertyChangedWeakEventListener((INotifyPropertyChanged)DataContext);
            ctxlistener.Add("Delete", DeleteContent);
        }

        ~StatusPage()
        {
            Debug.WriteLine("Statuspage has been deleted!");
        }

        private void DeleteContent(object s, PropertyChangedEventArgs e)
        {
            DispatcherHelper.UIDispatcher.InvokeAsync(() => Content = new Label { Content = "このツイートは削除されました" });
        }

        private void SetMainText()
        {
            foreach (var i in elm)
            {
                switch (i.Type)
                {
                    case "None":
                        TextBlockMainText.Inlines.Add(i.Text);
                        break;

                    case "Url":
                    case "Media":
                    case "Mention":
                    case "Hashtag":
                        var hl = new Hyperlink();
                        hl.Inlines.Add(i.Text);
                        hl.Tag = i;
                        hl.Click += (s, e2) =>
                        {
                            var t = ((s as Hyperlink).Tag as StatusViewModel.StatusElement);
                            RequestHyperlinkAction(t.Type, t.Infomation);
                            e2.Handled = true;
                        };
                        var bh = new HyperlinkMouseOverColorChangeBehavior();
                        bh.MouseEnteredForeground = Brushes.Red;
                        bh.MouseLeftForeground = Brushes.DodgerBlue;
                        Interaction.GetBehaviors(hl).Add(bh);
                        TextBlockMainText.Inlines.Add(hl);
                        break;
                    default:
                        throw new InvalidOperationException("予期しないテキスト要素です");
                }
            }

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (showed) return;
            showed = true;
            if (!setting.StatusPage.AnimationNewStatus) return;

            var cdu = new Duration(TimeSpan.FromMilliseconds(500));
            //たかさ
            var dah = new DoubleAnimation { From = 0.0, To = this.ActualHeight, Duration = cdu, EasingFunction = new SineEase() };
            Storyboard.SetTargetProperty(dah, new PropertyPath("Height"));
            Storyboard.SetTarget(dah, this);
            //透明度
            var dao = new DoubleAnimation { From = 0, To = 1, Duration = cdu };
            Storyboard.SetTargetProperty(dao, new PropertyPath("Opacity"));
            Storyboard.SetTarget(dao, this);

            sb = new Storyboard();
            sb.Children.Add(dah);
            sb.Children.Add(dao);
            this.Height = 0;
            sb.Begin();

        }

        private void RequestHyperlinkAction(string type, string info)
        {
            statvm.main.RequestStatusAction(type, info);
        }

        //Via用とか
        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            RequestHyperlinkAction("Url", e.Uri.ToString());
            e.Handled = true;
        }

        private void HyperlinkScreenName_Click(object sender, RoutedEventArgs e)
        {
            RequestHyperlinkAction("Mention", stsn);
            e.Handled = true;
        }

    }
}


text: Alaska banner service


text:
define(function(require) {
  var angular = require('angular');
  require('angular-route');
  return angular.module('rtp', ['ngRoute']);
});


text:
package org.primefaces.adamantium.view.input;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class MaskView {

    private String date;
	private String phone;
	private String phoneExt;
	private String taxId;
	private String ssn;
	private String productKey;

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getPhoneExt() {
		return phoneExt;
	}

	public void setPhoneExt(String phoneExt) {
		this.phoneExt = phoneExt;
	}

	public String getTaxId() {
		return taxId;
	}

	public void setTaxId(String taxId) {
		this.taxId = taxId;
	}

	public String getSsn() {
		return ssn;
	}

	public void setSsn(String ssn) {
		this.ssn = ssn;
	}

	public String getProductKey() {
		return productKey;
	}

	public void setProductKey(String productKey) {
		this.productKey = productKey;
	}
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Topics.Radical.ComponentModel.ChangeTracking;
using SharpTestsEx;

namespace Test.Radical
{
    [TestClass()]
    public class RejectedEventArgsTests
    {
        [TestMethod]
        public void rejectedEventArgs_ctor_normal_should_set_values()
        {
            var expected = RejectReason.RejectChanges;
            RejectedEventArgs target = new RejectedEventArgs( expected );

            target.Reason.Should().Be.EqualTo( expected );
        }
    }
}