text:
import React, {Component} from 'react'

import BreadcrumbsNav from '../../components/BreadcrumbsNav'
import HierarchicalListSearch from '../../components/HierarchicalListSearch'
import ChordComponent from '../../components/ChordComponent'
import TreeComponent from '../../components/TreeComponent'
import {CHORD_VIEW, TREE_VIEW} from '../../reducers/'
import graphProvider from '../../components/graph/'

class XocesWidget extends Component {

  constructor(props) {
    super(props);

    this.w;
    this.h;
  }

  render() {
    let graph = graphProvider(this.props.relationship)

    // console.log('props in XocesWidget', this.props)

    let component;
    if (this.props.view === CHORD_VIEW) {
      component = (<ChordComponent {...this.props} />)
    } else {
      // we want the tree component to show ALL prerequsities
      let prereqsOfSelectedEntities = _.flatMap(this.props.selectedEntities, e => graph.getOutgoingEntitiesAll(e.id, this.props.data.entities, this.props.data.relationships));
      let nodes = _.uniq(_.concat(this.props.selectedEntities, prereqsOfSelectedEntities));
      // console.log(nodes)
      component = (<TreeComponent {...this.props} nodes={nodes} />)
    }

    return (

          <BreadcrumbsNav breadcrumbs={this.props.breadcrumbs}
                        schemeName={this.props.colorScheme}
                        entityLabelKey={this.props.entityLabelKey}
                        hierarchy={this.props.hierarchy}
                        view={this.props.view}
                        onClickBreadcrumb={this.props.onClickBreadcrumb}
                        onChangeView={this.props.onChangeView}
                      />

              {component}

              <HierarchicalListSearch schemeName={this.props.colorScheme}
                                      height={this.props.height}
                                      hierarchy={this.props.hierarchy}
                                      currentLevelEntity={this.props.currentLevelEntity}
                                      data={this.props.data}
                                      entityLabelKey={this.props.entityLabelKey}
                                      graph={graph}
                                      selectedEntities={this.props.selectedEntities}
                                      onToggleEntity={this.props.onToggleEntity}
                                    />

    )
  }

}

export default XocesWidget


text:
var oauth = ShanbayOauth.initPage();

function logout() {
    oauth.clearToken();
}

chrome.runtime.onMessage.addListener(function (request, sender, sendReponse) {
    if (request.action == 'authorize') {
        oauth.authorize(sendReponse);
    }
})

redpajama_set_name: RedPajamaGithub


text:
/**
 * www.bplow.com
 */
package com.bplow.deep.bpm;

/**
 * @desc
 * @author wangxiaolei
 * @date 2016年7月10日 下午5:06:39
 */
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.ActivitiRule;
import org.activiti.engine.test.Deployment;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.*;

public class MyUnitTest {

	@Rule
	public ActivitiRule activitiRule = new ActivitiRule();

	@Test
	@Deployment(resources = {"org/activiti/test/my-process.bpmn20.xml"})
	public void test() {
		ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
		assertNotNull(processInstance);

		Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
		assertEquals("Activiti is awesome!", task.getName());
	}

}


text:
@interface CCBannerView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSArray <CCBannerViewModel *> *banners;

@end

@implementation CCBannerView

@synthesize viewAction;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self collectionViewSetup];
        [self pageControlSetup];
    }
    return self;
}

- (void)didMoveToSuperview {
    [self.viewAction bannerViewDidSet:self];
}

#pragma mark - UI Setup

- (void)collectionViewSetup {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.backgroundColor = [[UIColor cc_themeColor] colorWithAlphaComponent:0.5];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.layer.cornerRadius = 6.f;
    self.collectionView.layer.masksToBounds = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[CCBannerCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([CCBannerCollectionViewCell class])];

    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).with.insets(UIEdgeInsetsMake(6, 6, 6, 6));
    }];
}

- (void)pageControlSetup {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    self.pageControl.currentPageIndicatorTintColor = [UIColor cc_themeColor];
    self.pageControl.numberOfPages = 0;

    [self addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.equalTo(@30);
    }];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.banners.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CCBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CCBannerCollectionViewCell class])
                                                                                forIndexPath:indexPath];
    cell.banner = self.banners[indexPath.row];
    return cell;
}

#pragma mark -UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.viewAction bannerView:self didSelectBannerAtIndex:indexPath.row];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.collectionView.bounds.size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.pageControl.currentPage = self.collectionView.contentOffset.x / self.collectionView.bounds.size.width;
}

#pragma mark - CCBannerViewProtocol

- (void)showBanners:(NSArray <CCBannerViewModel *> *)banners {
    self.banners = banners;
    self.pageControl.numberOfPages = banners.count;
    [self.collectionView reloadData];
}

- (void)updateBannerHeight:(CGFloat)height {
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(height));
    }];

    [UIView animateWithDuration:0.4 animations:^{
        [self layoutIfNeeded];
    }];
}

#pragma mark - CCSpinerViewProtocol

- (void)showSpiner {
    [self cc_showSpiner];
}

- (void)hideSpiner {
    [self cc_hideSpiner];
}

@end


text:
Spring Boot and ReactJS
-----------------------

Dette er selve programmet bygd med Spring Boot som controller og ReactJS som frontend.

## Hvordan kjøre programmet

### Lokalt

Kjør kommandoen `mvn package && java -jar target/gs-spring-boot-docker-0.1.0.jar` og gå til `http://localhost:8080/`.

### Lokalt med Docker
```
mvn package docker:build
sudo docker run -p 8080:8080 -t ciberacademy/ciber-mangekamp
```

## Mer informasjon
* [Spring Boot with Docker](https://spring.io/guides/gs/spring-boot-docker/)
* [React.js and Spring Data REST](https://spring.io/guides/tutorials/react-and-spring-data-rest/)


text:
      Hello {{ account.name }},
      ●You have {{ account.numOfNewVendors }}disfunctioning vendors.
      Encourage them by mail

Powered by

INTRODUCTION MAIL

VAT RECOVERY PROGRAM

TO

        {{ account.numOfNewVendors }} Vendors

Edit Vendors List

            <md-checkbox fxFlex="0 0 35px" [checked]="isVendorListChecked(categoryIndex)" (change)="selectVendorList($event, categoryIndex)"></md-checkbox>
            {{ config.categoryById(category.typeCode).name }} ({{ getCheckedVendorsListCount(category.typeCode) }} / {{category.vendors.length}})

Vendor Name

Vendor Vat Ressiue Rate

Country

              <md-checkbox fxFlex="0 0 35px" [checked]="isVendorChecked(vendor)" (change)="selectVendor($event, vendor, categoryIndex)"></md-checkbox>
              {{vendor.name}}

                <span *ngFor="let star of stars; let index = index" [class.active]="index < vendor.rate">☆

              {{ config.countryByCode(vendor.countryCode).name }}

SUBJECT

      <md-input-container fxFlex="0 0 876px">
        <input mdInput placeholder="" [disabled]="isSubjectDisabled" value="Amazon Introduce Recovery VAT Program">
      </md-input-container>

        <md-icon color="primary" (click)="toogleDisable('subject',isSubjectDisabled)">create</md-icon>

        <md-icon color="primary" (click)="toogleDisable('subject',isSubjectDisabled)">save</md-icon>

      <text-editor *ngIf="!isContentDisabled" [content]='mailText'></text-editor>

        <md-icon color="primary" (click)="toogleDisable('content',isContentDisabled)">create</md-icon>

        <md-icon color="primary" (click)="saveTextEditor()">save</md-icon>
        <md-icon color="primary" (click)="closeTextEditor()">close</md-icon>

          <md-button-toggle value="bold" (change)="setTextFormat($event)"><md-icon color="primary">format_bold</md-icon></md-button-toggle>
          <md-button-toggle value="italic" (change)="setTextFormat($event)"><md-icon color="primary">format_italic</md-icon></md-button-toggle>

FROM

      <md-input-container fxFlex="0 0 876px">
        <input mdInput placeholder="" [disabled]="isFromtDisabled" [value]="account.fromEmail">
      </md-input-container>

        <md-icon color="primary" (click)="toogleDisable('from',isFromtDisabled)">create</md-icon>

        <md-icon color="primary" (click)="toogleDisable('from',isFromtDisabled)">save</md-icon>

CC

      <md-input-container fxFlex="0 0 876px">
        <input mdInput placeholder="" disabled [value]="account.ccEmail">
      </md-input-container>

<button [disabled]="!(checkedVendorList.length > 0)" (click)="sendEmail()" md-raised-button color="primary">Send Email</button>

<ng-template #noData>

      <md-spinner></md-spinner>

</ng-template>


text:
package javax.util;

import static javax.util.Map.*;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

@SuppressWarnings("serial")
public class Timestamp extends java.sql.Timestamp {

	public static TimeZone GMT = TimeZone.getTimeZone("GMT");
	public static TimeZone TIMEZONE = TimeZone.getDefault();

	private static String FORMAT = "YYYY-MM-dd HH:mm:ss";
	private static Map<String, SimpleDateFormat> formatters = map();

	public Timestamp(long time) {
		super(time);
	}

	public String format() {
		return Timestamp.format(this.getTime());
	}

	public String format(String format) {
		return Timestamp.format(this.getTime(), format);
	}

	public String format(TimeZone timezone) {
		return Timestamp.format(this.getTime(), timezone);
	}

	public String format(String format, TimeZone timezone) {
		return Timestamp.format(this.getTime(), format, timezone);
	}

	public String toString() {
		return format();
	}

	public static Timestamp now() {
		return new Timestamp(System.currentTimeMillis());
	}

	public static String format(long timestamp) {
		return format(timestamp, FORMAT);
	}

	public static String format(long timestamp, String format) {
		return format(timestamp, format, TIMEZONE);
	}

	public static String format(long timestamp, TimeZone timezone) {
		return format(timestamp, FORMAT, timezone);
	}

	public static String format(long timestamp, String format, TimeZone timezone) {
		return formatters.get(timezone.getID(), () -> formatter(format, timezone)).format(timestamp);
	}

	public static SimpleDateFormat formatter() {
		return formatter(FORMAT);
	}

	public static SimpleDateFormat formatter(String format) {
		return formatter(format, TIMEZONE);
	}

	public static SimpleDateFormat formatter(TimeZone timezone) {
		return formatter(FORMAT, timezone);
	}

	public static SimpleDateFormat formatter(String format, TimeZone timezone) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		formatter.setTimeZone(timezone);
		return formatter;
	}
}


text:
import React, { Component } from 'react';
import {
  ScrollView,
  TextInput,
  StyleSheet,
  Image,
  Text,
  View,
  Alert,
  Platform,
  ActivityIndicator
} from 'react-native';

import { Navigation } from 'react-native-navigation';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Parse from 'parse/react-native';

import Auth from '../../helpers/Auth';

class SpotDetail extends Component {
  static navigatorStyle = {
    drawUnderNavBar: true,
    navBarTranslucent: true,
    navBarTransparent: true
  };

  constructor(props) {
    super(props);
    this.state = {
      isSigningUp: false
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <View style={styles.header}>
            <Icon name="rocket" size={160} color="#FFF" />
            <Text style={styles.title}>{"Let's Sign Up!"}</Text>
          </View>
          <View style={styles.inputs}>
            <SignUpInput
                placeholder="Your Name"
                autoCapitalize="words"
                returnKeyType="next"
                onChangeText={(name) => this.setState({name})}
                onSubmitEditing={this._focusField.bind(this, 'emailInput')}/>
            <SignUpInput
                ref='emailInput'
                placeholder="Email"
                keyboardType="email-address"
                autoCapitalize="none"
                returnKeyType="next"
                onChangeText={(email) => this.setState({email})}
                onSubmitEditing={this._focusField.bind(this, 'pwdInput')}/>
            <SignUpInput
                ref='pwdInput'
                placeholder="Password"
                autoCapitalize="none"
                returnKeyType="next"
                secureTextEntry={true}
                onChangeText={(password) => this.setState({password})}
                onSubmitEditing={this._focusField.bind(this, 'confirmPwdInput')}/>
            <SignUpInput
                ref='confirmPwdInput'
                placeholder="Password Confirmation"
                autoCapitalize="none"
                returnKeyType="go"
                secureTextEntry={true}
                onChangeText={(password_confirmation) => this.setState({password_confirmation})}
                onSubmitEditing={this._doSignUp.bind(this)} />
          </View>
          <View style={styles.buttons}>
            {this.state.isSigningUp
                ? <ActivityIndicator animating={this.state.isSigningUp} style={styles.progress} size={'large'} />
                : <Icon.Button name="check" backgroundColor="#FFF"  color="#E11D32" onPress={this._doSignUp.bind(this)}>Sign Up</Icon.Button> }
            <View style={styles.loginButton}>
              <Icon.Button name="login" color="#FFF" backgroundColor="#E11D32" onPress={this._goToLogin.bind(this)}>Have an account? Log in</Icon.Button>
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }

  _focusField(nextField) {
    // Fixme: issue trying to set focus to the TextInput custom component
    //this.refs[nextField].focus();
  }

  _doSignUp() {
    if (this.state.isSigningUp || !this._validateData()) {
      return;
    }
    this.state.isSigningUp = true;
    let user = new Parse.User();
    user.set("name", this.state.name);
    user.set("username", this.state.email);
    user.set("email", this.state.email);
    user.set("password", this.state.password);

    let instance = this;
    user.signUp(null, {
      success: function(user) {
        instance.state.isSigningUp = false;
        instance.props.navigator.showModal({
          screen: "ppg-spots.auth.welcome",
          animationType: 'slide-up',
          passProps: {
            from: 'signUp'
          }
        });
      },
      error: function(user, error) {
        Alert.alert('Sign Up error', (error.code == 202 ? "Email already in use." : error.message), [{text: "Try again"}]);
        console.log("SignUp error", error);
        instance.state.isSigningUp = false;
        }
    });
  }

  _goToLogin() {
    this.props.navigator.showModal({
      screen: "ppg-spots.auth.login",
      animationType: 'slide-up'
    });
  }

  _validateData() {
    let error;
    if (this.state.name) {
      this.state.name = this.state.name.trim();
    }
    if (this.state.email) {
      this.state.email = this.state.email.trim();
    }
    if (!this.state.name || this.state.name.length < 3 || this.state.name.length > 30) {
      error = "Your name must be between 3 and 30 characters long.";
    } else if (!Auth.isEmailValid(this.state.email)) {
      error = "This email is invalid";
    } else if (!this.state.password || this.state.password.length < 6) {
      error = "Your password needs to be at least 6 characters long."
    } else if (this.state.password !== this.state.password_confirmation) {
      error = "Your password confirmation needs to match."
    }
    if (error) {
      Alert.alert('Oops', error, [{text: 'Got it'}]);
    }
    return !error;
  }
}

class SignUpInput extends Component {
  render() {
    return (
      <TextInput
        style={styles.input}
        placeholderTextColor="#F5F5F5"
        keyboardAppearance="dark"
        underlineColorAndroid="#FFFFFF"
        editable = {true}
        multiline = {false}
        spellCheck = {false}
        numberOfLines = {1}
        maxLength = {70}
        {...this.props}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: "#E11D32"
  },
  header: {
    flex: 1,
    marginTop: 40,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  inputs: {
    flex: 1,
    marginTop: 8,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttons: {
    flex: 1,
    marginTop: 8,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    color: '#fff',
    fontWeight: '300',
    fontSize: 24
  },
  loginButton: {
    marginTop: 32
  },
  input: {
    flex: 1,
    width: 250,
    height: 40,
    color: "#FFF",
  },
});

export default SpotDetail;


text:
TorpedoTask::TorpedoTask()
    : m_nodeHandle(),
      m_redBuoySubcriber(),
      m_redBuoyLocation(),
      m_taskStateSubscriber(),
      m_highLevelMotorPublisher(),
      m_centerOnPointPublisher(),
      m_isEnabled(false)
{
    m_redBuoyLocation.height = 0;
    m_redBuoyLocation.width = 0;
    m_redBuoyLocation.center_x = 0;
    m_redBuoyLocation.center_y = 0;
    m_redBuoyLocation.confidence = 0;

    // Subscribe to image recognition of red buoy
    m_redBuoySubcriber = m_nodeHandle.subscribe("image_recognition/buoys/red", 10, &TorpedoTask::redBuoyCallback, this);

    // Subscribe to task state message
    m_taskStateSubscriber = m_nodeHandle.subscribe("Module_Enable", 10, &TorpedoTask::moduleEnableCallback, this);

   // Setup publisher for center on point
    m_centerOnPointPublisher = m_nodeHandle.advertise<Robosub::Point>("Center_On_Point", 10);

   // Setup publisher for high level motor control
    m_highLevelMotorPublisher = m_nodeHandle.advertise<Robosub::HighLevelControl>("High_Level_Motor_Control", 10);

    // Setup publisher to fire torpedoes
    m_torpedoLaunchPublisher = m_nodeHandle.advertise<std_msgs::UInt8>("Torpedo_Launch", 10);

   // @todo Setup publisher for center on line
}

TorpedoTask::~TorpedoTask()
{

}

void TorpedoTask::moduleEnableCallback(const Robosub::ModuleEnableMsg& msg)
{
    if (msg.Module == "TorpedoTask")
    {
        if (msg.State == true)
        {
            bool status = false;
            printf("TorpedoTask: Enabled\n");
            m_isEnabled = true;

            status = performTask();

            // @todo Signal task complete on topic with task finish status
        }
        else
        {
            printf("TorpedoTask: Disabled\n");
            m_isEnabled = false;
        }
    }
}

void TorpedoTask::redBuoyCallback(const SubImageRecognition::ImgRecObject& msg)
{
    if (m_isEnabled)
    {
        printf("TorpedoTask: Got red buoy msg x: %i y: %i height: %i width: %i\n", msg.center_x, msg.center_y, msg.height, msg.width);

        //@todo Throw out message below some confidence level?

        m_redBuoyLocation.center_x = msg.center_x;
        m_redBuoyLocation.center_y = msg.center_y;
        m_redBuoyLocation.stamp = msg.stamp;
        m_redBuoyLocation.height = msg.height;
        m_redBuoyLocation.width = msg.width;
        m_redBuoyLocation.confidence = msg.confidence;
    }
}

bool TorpedoTask::performTask(void)
{
    Robosub::HighLevelControl highLevelControlMsg;
    int retries = 0;

    printf("TorpedoTask: Driving Forward to find red buoy...\n");

    // 1. Find the red bouy - keep driving forward
    highLevelControlMsg.Direction = "Forward";
    highLevelControlMsg.MotionType = "Manual";
    highLevelControlMsg.Value = 75.0f;
    m_highLevelMotorPublisher.publish(highLevelControlMsg);

    // Get at least 10 samples of the red buoy (easiest to spot) before looking for desired buoy
    retries = 150;  // 15 seconds-ish timeout
    while ((m_redBuoyLocation.height == 0) && (retries > 0))
    {
        usleep(100000);
        retries--;
    }

    if (retries == 0)
    {
        printf("TorpedoTask: Could not identiy red buoy\n");
        return false;
    }

    printf("TorpedoTask: Red buoy identified, attempting to center on buoy\n");
    m_highLevelMotorPublisher.publish(highLevelControlMsg);

    // Get close to red buoy
    retries = 150;  // 15 seconds-ish timeout
    while ((m_redBuoyLocation.height < 75) && (retries > 0))
    {
        centerOnRedBuoy();
        usleep(100000);
        retries--;
    }

    // Stop moving
    highLevelControlMsg.Direction = "Forward";
    highLevelControlMsg.MotionType = "Manual";
    highLevelControlMsg.Value = 0.0f;
    m_highLevelMotorPublisher.publish(highLevelControlMsg);

    // Re-center on buoy
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();

    // Fire red torpedo
    fireTorpedo(RED);

    // Re-center on buoy
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();
    centerOnRedBuoy();

    // Fire blue torpedo
    fireTorpedo(BLUE);

    return true;
}

bool TorpedoTask::centerOnRedBuoy(void)
{
    Robosub::Point pointMsg;
    bool isCentered = false;

    while (!isCentered)
    {
        pointMsg.x = m_redBuoyLocation.center_x;
        pointMsg.y = m_redBuoyLocation.center_y;

        m_centerOnPointPublisher.publish(pointMsg);

        if ((pointMsg.x <= 20) && (pointMsg.x >= -20) && (pointMsg.y <= 20) && (pointMsg.y >= -20))
        {
            isCentered = true;
        }

        usleep(100000);
    }

    return isCentered;
}

void TorpedoTask::fireTorpedo(TorpedoColors toShoot)
{
    std_msgs::UInt8 torpedoMessage;
    torpedoMessage.data = toShoot;

    m_torpedoLaunchPublisher.publish(torpedoMessage);
}


text:
package com.amazonaws.services.inspector.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 */
public class ListAssessmentRunAgentsRequest extends AmazonWebServiceRequest
        implements Serializable, Cloneable {

    /**
     *

     * The ARN that specifies the assessment run whose agents you want to list.
     *

     */
    private String assessmentRunArn;
    /**
     *

     * You can use this parameter to specify a subset of data to be included in
     * the action's response.
     *

     *

     * For a record to match a filter, all specified filter attributes must
     * match. When multiple values are specified for a filter attribute, any of
     * the values can match.
     *

     */
    private AgentFilter filter;
    /**
     *

     * You can use this parameter when paginating results. Set the value of this
     * parameter to null on your first call to the
     * ListAssessmentRunAgents action. Subsequent calls to the action
     * fill nextToken in the request with the value of NextToken
     * from the previous response to continue listing data.
     *

     */
    private String nextToken;
    /**
     *

     * You can use this parameter to indicate the maximum number of items that
     * you want in the response. The default value is 10. The maximum value is
     * 500.
     *

     */
    private Integer maxResults;

    /**
     *

     * The ARN that specifies the assessment run whose agents you want to list.
     *

     *
     * @param assessmentRunArn
     *        The ARN that specifies the assessment run whose agents you want to
     *        list.
     */

    public void setAssessmentRunArn(String assessmentRunArn) {
        this.assessmentRunArn = assessmentRunArn;
    }

    /**
     *

     * The ARN that specifies the assessment run whose agents you want to list.
     *

     *
     * @return The ARN that specifies the assessment run whose agents you want
     *         to list.
     */

    public String getAssessmentRunArn() {
        return this.assessmentRunArn;
    }

    /**
     *

     * The ARN that specifies the assessment run whose agents you want to list.
     *

     *
     * @param assessmentRunArn
     *        The ARN that specifies the assessment run whose agents you want to
     *        list.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListAssessmentRunAgentsRequest withAssessmentRunArn(
            String assessmentRunArn) {
        setAssessmentRunArn(assessmentRunArn);
        return this;
    }

    /**
     *

     * You can use this parameter to specify a subset of data to be included in
     * the action's response.
     *

     *

     * For a record to match a filter, all specified filter attributes must
     * match. When multiple values are specified for a filter attribute, any of
     * the values can match.
     *

     *
     * @param filter
     *        You can use this parameter to specify a subset of data to be
     *        included in the action's response.

     *

     *        For a record to match a filter, all specified filter attributes
     *        must match. When multiple values are specified for a filter
     *        attribute, any of the values can match.
     */

    public void setFilter(AgentFilter filter) {
        this.filter = filter;
    }

    /**
     *

     * You can use this parameter to specify a subset of data to be included in
     * the action's response.
     *

     *

     * For a record to match a filter, all specified filter attributes must
     * match. When multiple values are specified for a filter attribute, any of
     * the values can match.
     *

     *
     * @return You can use this parameter to specify a subset of data to be
     *         included in the action's response.

     *

     *         For a record to match a filter, all specified filter attributes
     *         must match. When multiple values are specified for a filter
     *         attribute, any of the values can match.
     */

    public AgentFilter getFilter() {
        return this.filter;
    }

    /**
     *

     * You can use this parameter to specify a subset of data to be included in
     * the action's response.
     *

     *

     * For a record to match a filter, all specified filter attributes must
     * match. When multiple values are specified for a filter attribute, any of
     * the values can match.
     *

     *
     * @param filter
     *        You can use this parameter to specify a subset of data to be
     *        included in the action's response.

     *

     *        For a record to match a filter, all specified filter attributes
     *        must match. When multiple values are specified for a filter
     *        attribute, any of the values can match.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListAssessmentRunAgentsRequest withFilter(AgentFilter filter) {
        setFilter(filter);
        return this;
    }

    /**
     *

     * You can use this parameter when paginating results. Set the value of this
     * parameter to null on your first call to the
     * ListAssessmentRunAgents action. Subsequent calls to the action
     * fill nextToken in the request with the value of NextToken
     * from the previous response to continue listing data.
     *

     *
     * @param nextToken
     *        You can use this parameter when paginating results. Set the value
     *        of this parameter to null on your first call to the
     *        ListAssessmentRunAgents action. Subsequent calls to the
     *        action fill nextToken in the request with the value of
     *        NextToken from the previous response to continue listing
     *        data.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * You can use this parameter when paginating results. Set the value of this
     * parameter to null on your first call to the
     * ListAssessmentRunAgents action. Subsequent calls to the action
     * fill nextToken in the request with the value of NextToken
     * from the previous response to continue listing data.
     *

     *
     * @return You can use this parameter when paginating results. Set the value
     *         of this parameter to null on your first call to the
     *         ListAssessmentRunAgents action. Subsequent calls to the
     *         action fill nextToken in the request with the value of
     *         NextToken from the previous response to continue listing
     *         data.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * You can use this parameter when paginating results. Set the value of this
     * parameter to null on your first call to the
     * ListAssessmentRunAgents action. Subsequent calls to the action
     * fill nextToken in the request with the value of NextToken
     * from the previous response to continue listing data.
     *

     *
     * @param nextToken
     *        You can use this parameter when paginating results. Set the value
     *        of this parameter to null on your first call to the
     *        ListAssessmentRunAgents action. Subsequent calls to the
     *        action fill nextToken in the request with the value of
     *        NextToken from the previous response to continue listing
     *        data.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListAssessmentRunAgentsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * You can use this parameter to indicate the maximum number of items that
     * you want in the response. The default value is 10. The maximum value is
     * 500.
     *

     *
     * @param maxResults
     *        You can use this parameter to indicate the maximum number of items
     *        that you want in the response. The default value is 10. The
     *        maximum value is 500.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * You can use this parameter to indicate the maximum number of items that
     * you want in the response. The default value is 10. The maximum value is
     * 500.
     *

     *
     * @return You can use this parameter to indicate the maximum number of
     *         items that you want in the response. The default value is 10. The
     *         maximum value is 500.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * You can use this parameter to indicate the maximum number of items that
     * you want in the response. The default value is 10. The maximum value is
     * 500.
     *

     *
     * @param maxResults
     *        You can use this parameter to indicate the maximum number of items
     *        that you want in the response. The default value is 10. The
     *        maximum value is 500.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListAssessmentRunAgentsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAssessmentRunArn() != null)
            sb.append("AssessmentRunArn: " + getAssessmentRunArn() + ",");
        if (getFilter() != null)
            sb.append("Filter: " + getFilter() + ",");
        if (getNextToken() != null)
            sb.append("NextToken: " + getNextToken() + ",");
        if (getMaxResults() != null)
            sb.append("MaxResults: " + getMaxResults());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListAssessmentRunAgentsRequest == false)
            return false;
        ListAssessmentRunAgentsRequest other = (ListAssessmentRunAgentsRequest) obj;
        if (other.getAssessmentRunArn() == null
                ^ this.getAssessmentRunArn() == null)
            return false;
        if (other.getAssessmentRunArn() != null
                && other.getAssessmentRunArn().equals(
                        this.getAssessmentRunArn()) == false)
            return false;
        if (other.getFilter() == null ^ this.getFilter() == null)
            return false;
        if (other.getFilter() != null
                && other.getFilter().equals(this.getFilter()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null
                && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null
                && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getAssessmentRunArn() == null) ? 0 : getAssessmentRunArn()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getFilter() == null) ? 0 : getFilter().hashCode());
        hashCode = prime * hashCode
                + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode
                + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        return hashCode;
    }

    @Override
    public ListAssessmentRunAgentsRequest clone() {
        return (ListAssessmentRunAgentsRequest) super.clone();
    }
}


text:
'''
Created on 17.10.2012

@author: Teemu Pääkkönen
'''
from qsdl.simulator import defaultOutputFormatter
from qsdl.simulator import csvOutputFormatter

def get_output_formatters():

    return {
            'default':  defaultOutputFormatter.get_output_formatter,
            'python': defaultOutputFormatter.get_output_formatter,
            'csv': csvOutputFormatter.get_output_formatter }

def get_cross_session_output_formatters():

    return {
            'default':  csvOutputFormatter.get_cross_session_output_formatter,
            'csv': csvOutputFormatter.get_cross_session_output_formatter }


text:
package com.lmax.angler.monitoring.network.monitor.system.softnet;

import com.lmax.angler.monitoring.network.monitor.util.FileLoader;
import com.lmax.angler.monitoring.network.monitor.util.TokenHandler;
import org.agrona.collections.Int2ObjectHashMap;

import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser;
import static java.lang.Runtime.getRuntime;

/**
 * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread
 * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate.
 */
public final class SoftnetStatsMonitor
{
    private static final int ESTIMATED_LINE_LENGTH = 120;

    private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>();
    private final TokenHandler lineParser = rowColumnParser(new SoftnetStatColumnHandler(this::handleEntry));
    private final FileLoader fileLoader;

    private SoftnetStatsHandler softnetStatsHandler;
    private int cpuId;

    public SoftnetStatsMonitor()
    {
        this(Paths.get("/proc/net/softnet_stat"));
    }

    SoftnetStatsMonitor(final Path pathToProcNetSoftnetStat)
    {
        fileLoader = new FileLoader(pathToProcNetSoftnetStat, ESTIMATED_LINE_LENGTH * getRuntime().availableProcessors());
    }

    /**
     * Read from monitored file, report any changed values to the supplied handler.
     *
     * Not thread-safe, only call from a single thread.
     *
     * @param softnetStatsHandler the handler for changed statistics
     */
    public void poll(final SoftnetStatsHandler softnetStatsHandler)
    {
        this.softnetStatsHandler = softnetStatsHandler;
        try
        {
            fileLoader.load();
            final ByteBuffer buffer = fileLoader.getBuffer();

            cpuId = 0;
            lineParser.reset();
            lineParser.handleToken(buffer, buffer.position(), buffer.limit());
        }
        finally
        {
            this.softnetStatsHandler = null;
        }
    }

    private void handleEntry(final CpuSoftIrqData cpuSoftIrqData)
    {
        final int currentCpuId = this.cpuId++;
        if(!cpuSoftIrqDataMap.containsKey(currentCpuId))
        {
            cpuSoftIrqDataMap.put(currentCpuId, new CpuSoftIrqData(currentCpuId));
        }

        final CpuSoftIrqData existing = cpuSoftIrqDataMap.get(currentCpuId);
        existing.copyFrom(cpuSoftIrqData);
        if(existing.isChanged())
        {
            softnetStatsHandler.perCpuStatistics(
                    existing.getCpuId(), existing.getTotalPackets(),
                    existing.getTimeSqueeze(), existing.getDroppedPackets());
        }

    }
}


text:
/*
 * linux/arch/arm/plat-omap/devices.c
 *
 * Common platform device setup/initialization for OMAP1 and OMAP2
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/io.h>

#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/map.h>

#include <mach/tc.h>
#include <mach/control.h>
#include <mach/board.h>
#include <mach/mmc.h>
#include <mach/mux.h>
#include <mach/gpio.h>
#include <mach/menelaus.h>
#include <mach/mcbsp.h>
#include <mach/dsp_common.h>

#if	defined(CONFIG_OMAP_DSP) || defined(CONFIG_OMAP_DSP_MODULE)

static struct dsp_platform_data dsp_pdata = {
	.kdev_list = LIST_HEAD_INIT(dsp_pdata.kdev_list),
};

static struct resource omap_dsp_resources[] = {
	{
		.name	= "dsp_mmu",
		.start	= -1,
		.flags	= IORESOURCE_IRQ,
	},
};

static struct platform_device omap_dsp_device = {
	.name		= "dsp",
	.id		= -1,
	.num_resources	= ARRAY_SIZE(omap_dsp_resources),
	.resource	= omap_dsp_resources,
	.dev = {
		.platform_data = &dsp_pdata,
	},
};

static inline void omap_init_dsp(void)
{
	struct resource *res;
	int irq;

	if (cpu_is_omap15xx())
		irq = INT_1510_DSP_MMU;
	else if (cpu_is_omap16xx())
		irq = INT_1610_DSP_MMU;
	else if (cpu_is_omap24xx())
		irq = INT_24XX_DSP_MMU;

	res = platform_get_resource_byname(&omap_dsp_device,
					   IORESOURCE_IRQ, "dsp_mmu");
	res->start = irq;

	platform_device_register(&omap_dsp_device);
}

int dsp_kfunc_device_register(struct dsp_kfunc_device *kdev)
{
	static DEFINE_MUTEX(dsp_pdata_lock);

	spin_lock_init(&kdev->lock);

	mutex_lock(&dsp_pdata_lock);
	list_add_tail(&kdev->entry, &dsp_pdata.kdev_list);
	mutex_unlock(&dsp_pdata_lock);

	return 0;
}
EXPORT_SYMBOL(dsp_kfunc_device_register);

#else
static inline void omap_init_dsp(void) { }
#endif	/* CONFIG_OMAP_DSP */

/*-------------------------------------------------------------------------*/
#if	defined(CONFIG_KEYBOARD_OMAP) || defined(CONFIG_KEYBOARD_OMAP_MODULE)

static void omap_init_kp(void)
{
	/* 2430 and 34xx keypad is on TWL4030 */
	if (cpu_is_omap2430() || cpu_is_omap34xx())
		return;

	if (machine_is_omap_h2() || machine_is_omap_h3()) {
		omap_cfg_reg(F18_1610_KBC0);
		omap_cfg_reg(D20_1610_KBC1);
		omap_cfg_reg(D19_1610_KBC2);
		omap_cfg_reg(E18_1610_KBC3);
		omap_cfg_reg(C21_1610_KBC4);

		omap_cfg_reg(G18_1610_KBR0);
		omap_cfg_reg(F19_1610_KBR1);
		omap_cfg_reg(H14_1610_KBR2);
		omap_cfg_reg(E20_1610_KBR3);
		omap_cfg_reg(E19_1610_KBR4);
		omap_cfg_reg(N19_1610_KBR5);
	} else if (machine_is_omap_perseus2() || machine_is_omap_fsample()) {
		omap_cfg_reg(E2_730_KBR0);
		omap_cfg_reg(J7_730_KBR1);
		omap_cfg_reg(E1_730_KBR2);
		omap_cfg_reg(F3_730_KBR3);
		omap_cfg_reg(D2_730_KBR4);

		omap_cfg_reg(C2_730_KBC0);
		omap_cfg_reg(D3_730_KBC1);
		omap_cfg_reg(E4_730_KBC2);
		omap_cfg_reg(F4_730_KBC3);
		omap_cfg_reg(E3_730_KBC4);
	} else if (machine_is_omap_h4()) {
		omap_cfg_reg(T19_24XX_KBR0);
		omap_cfg_reg(R19_24XX_KBR1);
		omap_cfg_reg(V18_24XX_KBR2);
		omap_cfg_reg(M21_24XX_KBR3);
		omap_cfg_reg(E5__24XX_KBR4);
		if (omap_has_menelaus()) {
			omap_cfg_reg(B3__24XX_KBR5);
			omap_cfg_reg(AA4_24XX_KBC2);
			omap_cfg_reg(B13_24XX_KBC6);
		} else {
			omap_cfg_reg(M18_24XX_KBR5);
			omap_cfg_reg(H19_24XX_KBC2);
			omap_cfg_reg(N19_24XX_KBC6);
		}
		omap_cfg_reg(R20_24XX_KBC0);
		omap_cfg_reg(M14_24XX_KBC1);
		omap_cfg_reg(V17_24XX_KBC3);
		omap_cfg_reg(P21_24XX_KBC4);
		omap_cfg_reg(L14_24XX_KBC5);
	}
}
#else
static inline void omap_init_kp(void) {}
#endif

/*-------------------------------------------------------------------------*/
#if defined(CONFIG_OMAP_MCBSP) || defined(CONFIG_OMAP_MCBSP_MODULE)

static struct platform_device **omap_mcbsp_devices;

void omap_mcbsp_register_board_cfg(struct omap_mcbsp_platform_data *config,
					int size)
{
	int i;

	omap_mcbsp_devices = kzalloc(size * sizeof(struct platform_device *),
				     GFP_KERNEL);
	if (!omap_mcbsp_devices) {
		printk(KERN_ERR "Could not register McBSP devices\n");
		return;
	}

	for (i = 0; i < size; i++) {
		struct platform_device *new_mcbsp;
		int ret;

		new_mcbsp = platform_device_alloc("omap-mcbsp", i + 1);
		if (!new_mcbsp)
			continue;
		new_mcbsp->dev.platform_data = &config[i];
		ret = platform_device_add(new_mcbsp);
		if (ret) {
			platform_device_put(new_mcbsp);
			continue;
		}
		omap_mcbsp_devices[i] = new_mcbsp;
	}
}

#else
void omap_mcbsp_register_board_cfg(struct omap_mcbsp_platform_data *config,
					int size)
{  }
#endif

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

#if defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE) || \
	defined(CONFIG_MMC_OMAP_HS) || defined(CONFIG_MMC_OMAP_HS_MODULE)

#define OMAP_MMC_NR_RES		2

/*
 * Register MMC devices. Called from mach-omap1 and mach-omap2 device init.
 */
int __init omap_mmc_add(const char *name, int id, unsigned long base,
				unsigned long size, unsigned int irq,
				struct omap_mmc_platform_data *data)
{
	struct platform_device *pdev;
	struct resource res[OMAP_MMC_NR_RES];
	int ret;

	pdev = platform_device_alloc(name, id);
	if (!pdev)
		return -ENOMEM;

	memset(res, 0, OMAP_MMC_NR_RES * sizeof(struct resource));
	res[0].start = base;
	res[0].end = base + size - 1;
	res[0].flags = IORESOURCE_MEM;
	res[1].start = res[1].end = irq;
	res[1].flags = IORESOURCE_IRQ;

	ret = platform_device_add_resources(pdev, res, ARRAY_SIZE(res));
	if (ret == 0)
		ret = platform_device_add_data(pdev, data, sizeof(*data));
	if (ret)
		goto fail;

	ret = platform_device_add(pdev);
	if (ret)
		goto fail;

	/* return device handle to board setup code */
	data->dev = &pdev->dev;
	return 0;

fail:
	platform_device_put(pdev);
	return ret;
}

#endif

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

/* Numbering for the SPI-capable controllers when used for SPI:
 * spi		= 1
 * uwire	= 2
 * mmc1..2	= 3..4
 * mcbsp1..3	= 5..7
 */

#if defined(CONFIG_SPI_OMAP_UWIRE) || defined(CONFIG_SPI_OMAP_UWIRE_MODULE)

#define	OMAP_UWIRE_BASE		0xfffb3000

static struct resource uwire_resources[] = {
	{
		.start		= OMAP_UWIRE_BASE,
		.end		= OMAP_UWIRE_BASE + 0x20,
		.flags		= IORESOURCE_MEM,
	},
};

static struct platform_device omap_uwire_device = {
	.name	   = "omap_uwire",
	.id	     = -1,
	.num_resources	= ARRAY_SIZE(uwire_resources),
	.resource	= uwire_resources,
};

static void omap_init_uwire(void)
{
	/* FIXME define and use a boot tag; not all boards will be hooking
	 * up devices to the microwire controller, and multi-board configs
	 * mean that CONFIG_SPI_OMAP_UWIRE may be configured anyway...
	 */

	/* board-specific code must configure chipselects (only a few
	 * are normally used) and SCLK/SDI/SDO (each has two choices).
	 */
	(void) platform_device_register(&omap_uwire_device);
}
#else
static inline void omap_init_uwire(void) {}
#endif

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

#if	defined(CONFIG_OMAP_WATCHDOG) || defined(CONFIG_OMAP_WATCHDOG_MODULE)

static struct resource wdt_resources[] = {
	{
		.flags		= IORESOURCE_MEM,
	},
};

static struct platform_device omap_wdt_device = {
	.name	   = "omap_wdt",
	.id	     = -1,
	.num_resources	= ARRAY_SIZE(wdt_resources),
	.resource	= wdt_resources,
};

static void omap_init_wdt(void)
{
	if (cpu_is_omap16xx())
		wdt_resources[0].start = 0xfffeb000;
	else if (cpu_is_omap2420())
		wdt_resources[0].start = 0x48022000; /* WDT2 */
	else if (cpu_is_omap2430())
		wdt_resources[0].start = 0x49016000; /* WDT2 */
	else if (cpu_is_omap343x())
		wdt_resources[0].start = 0x48314000; /* WDT2 */
	else if (cpu_is_omap44xx())
		wdt_resources[0].start = 0x4a314000;
	else
		return;

	wdt_resources[0].end = wdt_resources[0].start + 0x4f;

	(void) platform_device_register(&omap_wdt_device);
}
#else
static inline void omap_init_wdt(void) {}
#endif

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

#if defined(CONFIG_HW_RANDOM_OMAP) || defined(CONFIG_HW_RANDOM_OMAP_MODULE)

#ifdef CONFIG_ARCH_OMAP24XX
#define	OMAP_RNG_BASE		0x480A0000
#else
#define	OMAP_RNG_BASE		0xfffe5000
#endif

static struct resource rng_resources[] = {
	{
		.start		= OMAP_RNG_BASE,
		.end		= OMAP_RNG_BASE + 0x4f,
		.flags		= IORESOURCE_MEM,
	},
};

static struct platform_device omap_rng_device = {
	.name	   = "omap_rng",
	.id	     = -1,
	.num_resources	= ARRAY_SIZE(rng_resources),
	.resource	= rng_resources,
};

static void omap_init_rng(void)
{
	(void) platform_device_register(&omap_rng_device);
}
#else
static inline void omap_init_rng(void) {}
#endif

/*
 * This gets called after board-specific INIT_MACHINE, and initializes most
 * on-chip peripherals accessible on this board (except for few like USB):
 *
 *  (a) Does any "standard config" pin muxing needed.  Board-specific
 *	code will have muxed GPIO pins and done "nonstandard" setup;
 *	that code could live in the boot loader.
 *  (b) Populating board-specific platform_data with the data drivers
 *	rely on to handle wiring variations.
 *  (c) Creating platform devices as meaningful on this board and
 *	with this kernel configuration.
 *
 * Claiming GPIOs, and setting their direction and initial values, is the
 * responsibility of the device drivers.  So is responding to probe().
 *
 * Board-specific knowlege like creating devices or pin setup is to be
 * kept out of drivers as much as possible.  In particular, pin setup
 * may be handled by the boot loader, and drivers should expect it will
 * normally have been done by the time they're probed.
 */
static int __init omap_init_devices(void)
{
	/* please keep these calls, and their implementations above,
	 * in alphabetical order so they're easier to sort through.
	 */
	omap_init_dsp();
	omap_init_kp();
	omap_init_uwire();
	omap_init_wdt();
	omap_init_rng();
	return 0;
}
arch_initcall(omap_init_devices);


text:
from openturns import *

TESTPREAMBLE()
RandomGenerator.SetSeed(0)

try:

    # We create a numerical math function
    myFunction = NumericalMathFunction(
        ('E', 'F', 'L', 'I'), ('d',), ('-F*L^3/(3.*E*I)',))

    dim = myFunction.getInputDimension()
    # We create a normal distribution point of dimension 1
    mean = NumericalPoint(dim, 0.0)
    # E
    mean[0] = 50.0
    # F
    mean[1] = 1.0
    # L
    mean[2] = 10.0
    # I
    mean[3] = 5.0
    sigma = NumericalPoint(dim, 1.0)
    R = IdentityMatrix(dim)
    myDistribution = Normal(mean, sigma, R)

    # We create a 'usual' RandomVector from the Distribution
    vect = RandomVector(myDistribution)

    # We create a composite random vector */
    output = RandomVector(myFunction, vect)

    # We create an Event from this RandomVector */
    myEvent = Event(output, Less(), -3)

# TEST ONE : directional sampling from an event (slow and safe strategy by default)
    # We create a Directional Sampling algorithm */
    myAlgo = DirectionalSampling(myEvent)
    myAlgo.setMaximumOuterSampling(250)
    myAlgo.setBlockSize(4)
    myAlgo.setMaximumCoefficientOfVariation(0.1)

    print "DirectionalSampling=", myAlgo

    # Perform the simulation */
    myAlgo.run()

    # Stream out the result */
    print "DirectionalSampling result=", myAlgo.getResult()

# TEST TWO : diectional sampling from an event and a root strategy : Risky And Fast, and a directional sampling strategy :
    # We create a Directional Sampling algorithm */
    myAlgo2 = DirectionalSampling(myEvent, MediumSafe(), OrthogonalDirection())
    myAlgo2.setMaximumOuterSampling(250)
    myAlgo2.setBlockSize(4)
    myAlgo2.setMaximumCoefficientOfVariation(0.1)

    print "DirectionalSampling=", myAlgo2

    # Perform the simulation */
    myAlgo2.run()

    # Stream out the result */
    print "DirectionalSampling result=", myAlgo2.getResult()

except:
    import sys
    print "t_DirectionalSampling.py", sys.exc_type, sys.exc_value


text:
module Opinio
  module Controllers
    module Extensions

      def self.included(base)
        base.extend ClassMethods
        base.send :include, InstanceMethods

        base.class_eval do
          (class << self; self; end).instance_eval do
            define_method "#{Opinio.model_name.underscore}_destroy_conditions" do |&block|
              Opinio.set_destroy_conditions( &block )
            end
          end
        end
      end

      module ClassMethods
        def opinio_identifier(&block)
          Opinio.opinio_identifier(block)
        end
      end

      module InstanceMethods
        def can_destroy_opinio?(opinio)
          self.instance_exec(opinio, &Opinio.destroy_conditions)
        end

        def opinio_after_create_path(resource)
          resource.is_a?(Opinio.model_name.constantize) ? resource.commentable : resource
        end

        def opinio_after_destroy_path(comment)
          comment.commentable
        end
      end
    end
  end
end


text:
module C80MapFloors

  #==========================================================
  #
  #   Это Площадь (которая привязывается к полигону на карте)
  #
  #==========================================================

  module AreaRepresentator

    # noinspection RubyResolve
    extend ActiveSupport::Concern

    #  ERROR: Cannot define multiple 'included' blocks for a Concern
    # included do
    #
    # end

    def self.included(klass)
      klass.extend ClassMethods
      klass.send(:include, InstanceMethods)
    end

    module ClassMethods

      # noinspection RubyResolve
      def acts_as_map_area_representator
        class_eval do

          has_one :area, :as => :area_representator, :class_name => 'C80MapFloors::Area', :dependent => :nullify

          after_save :update_json

          # выдать название привязанного к Площади полигона
          def apolygon_title
            res = '-'
            if self.area.present?
              res = "id=#{self.area.id}"
            end
            res
          end

          def update_json
            # MapJson.update_json # NOTE-json:: возможно, временно отключён
          end

        end
      end
    end

    module InstanceMethods

=begin
# legacy от с80_map
      def to_hash_a
        res = {
            id: id,
            title: title,
            props: {
                square: square,
                floor_height: floor_height,
                gate_type: gate_type,
                desc: desc,
                column_step: column_step,
                communications: communications,
                price: price_string
            }
        }
        res
      end
=end

      # Выдать json Площади, которая привязана к полигону на карте
      # noinspection RubyResolve
      def my_as_json2
        result = {
            id:             self.id,
            title:          self.title,
            square:         self.square,
            desc:           self.desc,
            price_string:   self.price_string,
            communications: self.communications,
            is_free:        self.is_free?,
            shop:           self.shop_as_json
        }
        result.as_json
      end

    end

  end
end

ActiveRecord::Base.send :include, C80MapFloors::AreaRepresentator


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_TRACE_EVENT_TRACE_LOG_H_
#define BASE_TRACE_EVENT_TRACE_LOG_H_

#include <stddef.h>
#include <stdint.h>

#include <string>
#include <vector>

#include "base/atomicops.h"
#include "base/containers/hash_tables.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/trace_config.h"
#include "base/trace_event/trace_event_impl.h"
#include "build/build_config.h"

namespace base {

template <typename Type>
struct DefaultSingletonTraits;
class RefCountedString;

namespace trace_event {

class TraceBuffer;
class TraceBufferChunk;
class TraceEvent;
class TraceEventMemoryOverhead;
class TraceSamplingThread;

struct BASE_EXPORT TraceLogStatus {
  TraceLogStatus();
  ~TraceLogStatus();
  uint32_t event_capacity;
  uint32_t event_count;
};

class BASE_EXPORT TraceLog : public MemoryDumpProvider {
 public:
  enum Mode {
    DISABLED = 0,
    RECORDING_MODE
  };

  // The pointer returned from GetCategoryGroupEnabledInternal() points to a
  // value with zero or more of the following bits. Used in this class only.
  // The TRACE_EVENT macros should only use the value as a bool.
  // These values must be in sync with macro values in TraceEvent.h in Blink.
  enum CategoryGroupEnabledFlags {
    // Category group enabled for the recording mode.
    ENABLED_FOR_RECORDING = 1 << 0,
    // Category group enabled by SetEventCallbackEnabled().
    ENABLED_FOR_EVENT_CALLBACK = 1 << 2,
    // Category group enabled to export events to ETW.
    ENABLED_FOR_ETW_EXPORT = 1 << 3
  };

  static TraceLog* GetInstance();

  // Get set of known category groups. This can change as new code paths are
  // reached. The known category groups are inserted into |category_groups|.
  void GetKnownCategoryGroups(std::vector<std::string>* category_groups);

  // Retrieves a copy (for thread-safety) of the current TraceConfig.
  TraceConfig GetCurrentTraceConfig() const;

  // Initializes the thread-local event buffer, if not already initialized and
  // if the current thread supports that (has a message loop).
  void InitializeThreadLocalEventBufferIfSupported();

  // Enables normal tracing (recording trace events in the trace buffer).
  // See TraceConfig comments for details on how to control what categories
  // will be traced. If tracing has already been enabled, |category_filter| will
  // be merged into the current category filter.
  void SetEnabled(const TraceConfig& trace_config, Mode mode);

  // Disables normal tracing for all categories.
  void SetDisabled();

  bool IsEnabled() { return mode_ != DISABLED; }

  // The number of times we have begun recording traces. If tracing is off,
  // returns -1. If tracing is on, then it returns the number of times we have
  // recorded a trace. By watching for this number to increment, you can
  // passively discover when a new trace has begun. This is then used to
  // implement the TRACE_EVENT_IS_NEW_TRACE() primitive.
  int GetNumTracesRecorded();

#if defined(OS_ANDROID)
  void StartATrace();
  void StopATrace();
  void AddClockSyncMetadataEvent();
#endif

  // Enabled state listeners give a callback when tracing is enabled or
  // disabled. This can be used to tie into other library's tracing systems
  // on-demand.
  class BASE_EXPORT EnabledStateObserver {
   public:
    virtual ~EnabledStateObserver() = default;

    // Called just after the tracing system becomes enabled, outside of the
    // |lock_|. TraceLog::IsEnabled() is true at this point.
    virtual void OnTraceLogEnabled() = 0;

    // Called just after the tracing system disables, outside of the |lock_|.
    // TraceLog::IsEnabled() is false at this point.
    virtual void OnTraceLogDisabled() = 0;
  };
  void AddEnabledStateObserver(EnabledStateObserver* listener);
  void RemoveEnabledStateObserver(EnabledStateObserver* listener);
  bool HasEnabledStateObserver(EnabledStateObserver* listener) const;

  TraceLogStatus GetStatus() const;
  bool BufferIsFull() const;

  // Computes an estimate of the size of the TraceLog including all the retained
  // objects.
  void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead);

  // Not using base::Callback because of its limited by 7 parameters.
  // Also, using primitive type allows directly passing callback from WebCore.
  // WARNING: It is possible for the previously set callback to be called
  // after a call to SetEventCallbackEnabled() that replaces or a call to
  // SetEventCallbackDisabled() that disables the callback.
  // This callback may be invoked on any thread.
  // For TRACE_EVENT_PHASE_COMPLETE events, the client will still receive pairs
  // of TRACE_EVENT_PHASE_BEGIN and TRACE_EVENT_PHASE_END events to keep the
  // interface simple.
  typedef void (*EventCallback)(TimeTicks timestamp,
                                char phase,
                                const unsigned char* category_group_enabled,
                                const char* name,
                                const char* scope,
                                unsigned long long id,
                                int num_args,
                                const char* const arg_names[],
                                const unsigned char arg_types[],
                                const unsigned long long arg_values[],
                                unsigned int flags);

  // Enable tracing for EventCallback.
  void SetEventCallbackEnabled(const TraceConfig& trace_config,
                               EventCallback cb);
  void SetEventCallbackDisabled();
  void SetArgumentFilterPredicate(
      const ArgumentFilterPredicate& argument_filter_predicate);

  // Flush all collected events to the given output callback. The callback will
  // be called one or more times either synchronously or asynchronously from
  // the current thread with IPC-bite-size chunks. The string format is
  // undefined. Use TraceResultBuffer to convert one or more trace strings to
  // JSON. The callback can be null if the caller doesn't want any data.
  // Due to the implementation of thread-local buffers, flush can't be
  // done when tracing is enabled. If called when tracing is enabled, the
  // callback will be called directly with (empty_string, false) to indicate
  // the end of this unsuccessful flush. Flush does the serialization
  // on the same thread if the caller doesn't set use_worker_thread explicitly.
  typedef base::Callback<void(const scoped_refptr<base::RefCountedString>&,
                              bool has_more_events)> OutputCallback;
  void Flush(const OutputCallback& cb, bool use_worker_thread = false);

  // Cancels tracing and discards collected data.
  void CancelTracing(const OutputCallback& cb);

  // Called by TRACE_EVENT* macros, don't call this directly.
  // The name parameter is a category group for example:
  // TRACE_EVENT0("renderer,webkit", "WebViewImpl::HandleInputEvent")
  static const unsigned char* GetCategoryGroupEnabled(const char* name);
  static const char* GetCategoryGroupName(
      const unsigned char* category_group_enabled);

  // Called by TRACE_EVENT* macros, don't call this directly.
  // If |copy| is set, |name|, |arg_name1| and |arg_name2| will be deep copied
  // into the event; see "Memory scoping note" and TRACE_EVENT_COPY_XXX above.
  TraceEventHandle AddTraceEvent(
      char phase,
      const unsigned char* category_group_enabled,
      const char* name,
      const char* scope,
      unsigned long long id,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);
  TraceEventHandle AddTraceEventWithBindId(
      char phase,
      const unsigned char* category_group_enabled,
      const char* name,
      const char* scope,
      unsigned long long id,
      unsigned long long bind_id,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);
  TraceEventHandle AddTraceEventWithProcessId(
      char phase,
      const unsigned char* category_group_enabled,
      const char* name,
      const char* scope,
      unsigned long long id,
      int process_id,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);
  TraceEventHandle AddTraceEventWithThreadIdAndTimestamp(
      char phase,
      const unsigned char* category_group_enabled,
      const char* name,
      const char* scope,
      unsigned long long id,
      int thread_id,
      const TimeTicks& timestamp,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);
  TraceEventHandle AddTraceEventWithThreadIdAndTimestamp(
      char phase,
      const unsigned char* category_group_enabled,
      const char* name,
      const char* scope,
      unsigned long long id,
      unsigned long long bind_id,
      int thread_id,
      const TimeTicks& timestamp,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);

  // Adds a metadata event that will be written when the trace log is flushed.
  void AddMetadataEvent(
      const unsigned char* category_group_enabled,
      const char* name,
      int num_args,
      const char** arg_names,
      const unsigned char* arg_types,
      const unsigned long long* arg_values,
      scoped_ptr<ConvertableToTraceFormat>* convertable_values,
      unsigned int flags);

  void UpdateTraceEventDuration(const unsigned char* category_group_enabled,
                                const char* name,
                                TraceEventHandle handle);

  // For every matching event, the callback will be called.
  typedef base::Callback<void()> WatchEventCallback;
  void SetWatchEvent(const std::string& category_name,
                     const std::string& event_name,
                     const WatchEventCallback& callback);
  // Cancel the watch event. If tracing is enabled, this may race with the
  // watch event notification firing.
  void CancelWatchEvent();

  int process_id() const { return process_id_; }

  uint64_t MangleEventId(uint64_t id);

  // Exposed for unittesting:

  void WaitSamplingEventForTesting();

  // Allows deleting our singleton instance.
  static void DeleteForTesting();

  // Allow tests to inspect TraceEvents.
  TraceEvent* GetEventByHandle(TraceEventHandle handle);

  void SetProcessID(int process_id);

  // Process sort indices, if set, override the order of a process will appear
  // relative to other processes in the trace viewer. Processes are sorted first
  // on their sort index, ascending, then by their name, and then tid.
  void SetProcessSortIndex(int sort_index);

  // Sets the name of the process.
  void SetProcessName(const std::string& process_name);

  // Processes can have labels in addition to their names. Use labels, for
  // instance, to list out the web page titles that a process is handling.
  void UpdateProcessLabel(int label_id, const std::string& current_label);
  void RemoveProcessLabel(int label_id);

  // Thread sort indices, if set, override the order of a thread will appear
  // within its process in the trace viewer. Threads are sorted first on their
  // sort index, ascending, then by their name, and then tid.
  void SetThreadSortIndex(PlatformThreadId thread_id, int sort_index);

  // Allow setting an offset between the current TimeTicks time and the time
  // that should be reported.
  void SetTimeOffset(TimeDelta offset);

  size_t GetObserverCountForTest() const;

  // Call this method if the current thread may block the message loop to
  // prevent the thread from using the thread-local buffer because the thread
  // may not handle the flush request in time causing lost of unflushed events.
  void SetCurrentThreadBlocksMessageLoop();

#if defined(OS_WIN)
  // This function is called by the ETW exporting module whenever the ETW
  // keyword (flags) changes. This keyword indicates which categories should be
  // exported, so whenever it changes, we adjust accordingly.
  void UpdateETWCategoryGroupEnabledFlags();
#endif

 private:
  typedef unsigned int InternalTraceOptions;

  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
                           TraceBufferRingBufferGetReturnChunk);
  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
                           TraceBufferRingBufferHalfIteration);
  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
                           TraceBufferRingBufferFullIteration);
  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture, TraceBufferVectorReportFull);
  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
                           ConvertTraceConfigToInternalOptions);
  FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
                           TraceRecordAsMuchAsPossibleMode);

  // This allows constructor and destructor to be private and usable only
  // by the Singleton class.
  friend struct DefaultSingletonTraits<TraceLog>;

  // MemoryDumpProvider implementation.
  bool OnMemoryDump(const MemoryDumpArgs& args,
                    ProcessMemoryDump* pmd) override;

  // Enable/disable each category group based on the current mode_,
  // category_filter_, event_callback_ and event_callback_category_filter_.
  // Enable the category group in the enabled mode if category_filter_ matches
  // the category group, or event_callback_ is not null and
  // event_callback_category_filter_ matches the category group.
  void UpdateCategoryGroupEnabledFlags();
  void UpdateCategoryGroupEnabledFlag(size_t category_index);

  // Configure synthetic delays based on the values set in the current
  // trace config.
  void UpdateSyntheticDelaysFromTraceConfig();

  InternalTraceOptions GetInternalOptionsFromTraceConfig(
      const TraceConfig& config);

  class ThreadLocalEventBuffer;
  class OptionalAutoLock;

  TraceLog();
  ~TraceLog() override;
  const unsigned char* GetCategoryGroupEnabledInternal(const char* name);
  void AddMetadataEventsWhileLocked();

  InternalTraceOptions trace_options() const {
    return static_cast<InternalTraceOptions>(
        subtle::NoBarrier_Load(&trace_options_));
  }

  TraceBuffer* trace_buffer() const { return logged_events_.get(); }
  TraceBuffer* CreateTraceBuffer();

  std::string EventToConsoleMessage(unsigned char phase,
                                    const TimeTicks& timestamp,
                                    TraceEvent* trace_event);

  TraceEvent* AddEventToThreadSharedChunkWhileLocked(TraceEventHandle* handle,
                                                     bool check_buffer_is_full);
  void CheckIfBufferIsFullWhileLocked();
  void SetDisabledWhileLocked();

  TraceEvent* GetEventByHandleInternal(TraceEventHandle handle,
                                       OptionalAutoLock* lock);

  void FlushInternal(const OutputCallback& cb,
                     bool use_worker_thread,
                     bool discard_events);

  // |generation| is used in the following callbacks to check if the callback
  // is called for the flush of the current |logged_events_|.
  void FlushCurrentThread(int generation, bool discard_events);
  // Usually it runs on a different thread.
  static void ConvertTraceEventsToTraceFormat(
      scoped_ptr<TraceBuffer> logged_events,
      const TraceLog::OutputCallback& flush_output_callback,
      const ArgumentFilterPredicate& argument_filter_predicate);
  void FinishFlush(int generation, bool discard_events);
  void OnFlushTimeout(int generation, bool discard_events);

  int generation() const {
    return static_cast<int>(subtle::NoBarrier_Load(&generation_));
  }
  bool CheckGeneration(int generation) const {
    return generation == this->generation();
  }
  void UseNextTraceBuffer();

  TimeTicks OffsetNow() const { return OffsetTimestamp(TimeTicks::Now()); }
  TimeTicks OffsetTimestamp(const TimeTicks& timestamp) const {
    return timestamp - time_offset_;
  }

  // Internal representation of trace options since we store the currently used
  // trace option as an AtomicWord.
  static const InternalTraceOptions kInternalNone;
  static const InternalTraceOptions kInternalRecordUntilFull;
  static const InternalTraceOptions kInternalRecordContinuously;
  static const InternalTraceOptions kInternalEchoToConsole;
  static const InternalTraceOptions kInternalEnableSampling;
  static const InternalTraceOptions kInternalRecordAsMuchAsPossible;
  static const InternalTraceOptions kInternalEnableArgumentFilter;

  // This lock protects TraceLog member accesses (except for members protected
  // by thread_info_lock_) from arbitrary threads.
  mutable Lock lock_;
  // This lock protects accesses to thread_names_, thread_event_start_times_
  // and thread_colors_.
  Lock thread_info_lock_;
  Mode mode_;
  int num_traces_recorded_;
  scoped_ptr<TraceBuffer> logged_events_;
  std::vector<scoped_ptr<TraceEvent>> metadata_events_;
  subtle::AtomicWord /* EventCallback */ event_callback_;
  bool dispatching_to_observer_list_;
  std::vector<EnabledStateObserver*> enabled_state_observer_list_;

  std::string process_name_;
  base::hash_map<int, std::string> process_labels_;
  int process_sort_index_;
  base::hash_map<int, int> thread_sort_indices_;
  base::hash_map<int, std::string> thread_names_;

  // The following two maps are used only when ECHO_TO_CONSOLE.
  base::hash_map<int, std::stack<TimeTicks>> thread_event_start_times_;
  base::hash_map<std::string, int> thread_colors_;

  TimeTicks buffer_limit_reached_timestamp_;

  // XORed with TraceID to make it unlikely to collide with other processes.
  unsigned long long process_id_hash_;

  int process_id_;

  TimeDelta time_offset_;

  // Allow tests to wake up when certain events occur.
  WatchEventCallback watch_event_callback_;
  subtle::AtomicWord /* const unsigned char* */ watch_category_;
  std::string watch_event_name_;

  subtle::AtomicWord /* Options */ trace_options_;

  // Sampling thread handles.
  scoped_ptr<TraceSamplingThread> sampling_thread_;
  PlatformThreadHandle sampling_thread_handle_;

  TraceConfig trace_config_;
  TraceConfig event_callback_trace_config_;

  ThreadLocalPointer<ThreadLocalEventBuffer> thread_local_event_buffer_;
  ThreadLocalBoolean thread_blocks_message_loop_;
  ThreadLocalBoolean thread_is_in_trace_event_;

  // Contains the message loops of threads that have had at least one event
  // added into the local event buffer. Not using SingleThreadTaskRunner
  // because we need to know the life time of the message loops.
  hash_set<MessageLoop*> thread_message_loops_;

  // For events which can't be added into the thread local buffer, e.g. events
  // from threads without a message loop.
  scoped_ptr<TraceBufferChunk> thread_shared_chunk_;
  size_t thread_shared_chunk_index_;

  // Set when asynchronous Flush is in progress.
  OutputCallback flush_output_callback_;
  scoped_refptr<SingleThreadTaskRunner> flush_task_runner_;
  ArgumentFilterPredicate argument_filter_predicate_;
  subtle::AtomicWord generation_;
  bool use_worker_thread_;

  DISALLOW_COPY_AND_ASSIGN(TraceLog);
};

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_TRACE_LOG_H_


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

    <title></title>
    <meta name="generator" content="HTML::TextToHTML v2.51"/>

break: break [n]

 Exit for, while, or until loops.

 Exit a FOR, WHILE or UNTIL loop. If N is specified, break N enclosing
    loops.

 Exit Status:

    The exit status is 0 unless N is not greater than or equal to 1.


text:
package org.owasp.webgoat.lessons;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.PRE;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;

public class LogSpoofing extends LessonAdapter
{

	private static final String USERNAME = "username";

	private static final String PASSWORD = "password";

	private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
			.setBorder(0).setHspace(0).setVspace(0);

	protected Element createContent(WebSession s)
	{

		ElementContainer ec = null;
		String inputUsername = null;
		try
		{

			Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
			TR row1 = new TR();
			TR row2 = new TR();
			TR row3 = new TR();

			row1.addElement(new TD(new StringElement("Username: ")));
			Input username = new Input(Input.TEXT, USERNAME, "");
			row1.addElement(new TD(username));

			row2.addElement(new TD(new StringElement("Password: ")));
			Input password = new Input(Input.PASSWORD, PASSWORD, "");
			row2.addElement(new TD(password));

			Element b = ECSFactory.makeButton("Login");
			row3.addElement(new TD(new StringElement("  ")));
			row3.addElement(new TD(b)).setAlign("right");

			t.addElement(row1);
			t.addElement(row2);
			t.addElement(row3);

			ec = new ElementContainer();
			ec.addElement(t);

			inputUsername = new String(s.getParser().getRawParameter(USERNAME, ""));
			if (inputUsername.length() != 0)
			{
				inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
			}

			ec.addElement(new PRE(" "));

			Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
			TR row4 = new TR();
			row4.addElement(new TD(new PRE("Login failed for username: " + inputUsername))).setBgColor(HtmlColor.GRAY);

			t2.addElement(row4);

			ec.addElement(t2);

			if (inputUsername.length() != 0
					&& inputUsername.toUpperCase().indexOf(
															System.getProperty("line.separator")
																	+ "LOGIN SUCCEEDED FOR USERNAME:") >= 0)
			{
				makeSuccess(s);
			}
		} catch (UnsupportedEncodingException e)
		{
			s.setMessage("Error generating " + this.getClass().getName());
			e.printStackTrace();
		}
		return ec;
	}

	private final static Integer DEFAULT_RANKING = new Integer(72);

	protected Integer getDefaultRanking()
	{
		return DEFAULT_RANKING;
	}

	@Override
	protected List<String> getHints(WebSession s)
	{
		List<String> hints = new ArrayList<String>();
		hints.add("Try to fool the human eye by using new lines.");
		hints.add("Use CR (%0d) and LF (%0a) for a new line.");
		hints.add("Try: Smith%0d%0aLogin Succeeded for username: admin");
		hints
				.add("Try: Smith%0d%0aLogin Succeeded for username: admin<script>alert(document.cookie)</script>");

		return hints;
	}

	@Override
	public String getTitle()
	{
		return "Log Spoofing";
	}

	@Override
	protected Category getDefaultCategory()
	{
		return Category.INJECTION;
	}

	public Element getCredits()
	{
		return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
	}
}


text:
"use strict";

exports.__esModule = true;
exports.default = PickerItem;

var _createElement = _interopRequireDefault(require("../createElement"));

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

function PickerItem(props) {
  var color = props.color,
      label = props.label,
      testID = props.testID,
      value = props.value;
  var style = {
    color: color
  };
  return (0, _createElement.default)('option', {
    style: style,
    testID: testID,
    value: value
  }, label);
}

module.exports = exports.default;


text:
@implementation MKWebView

@synthesize lastHitTestDate;

- (NSView *)hitTest:(NSPoint)aPoint
{
    //NSLog(@"hitTest: %@", NSStringFromPoint(aPoint));
    lastHitTestDate = [NSDate date];
    return [super hitTest:aPoint];
}

@end


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\BezeroZigorra;
use AppBundle\Form\BezeroZigorraType;

/**
 * BezeroZigorra controller.
 *
 * @Route("/kudeatu/bezerozigorra")
 */
class BezeroZigorraController extends Controller
{
    /**
     * Lists all BezeroZigorra entities.
     *
     * @Route("/", name="kudeatu_bezerozigorra_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $bezeroZigorras = $em->getRepository('AppBundle:BezeroZigorra')->findAll();

        return $this->render('bezerozigorra/index.html.twig', array(
            'bezeroZigorras' => $bezeroZigorras,
        ));
    }

    /**
     * Creates a new BezeroZigorra entity.
     *
     * @Route("/new", name="kudeatu_bezerozigorra_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $bezeroZigorra = new BezeroZigorra();
        $form = $this->createForm('AppBundle\Form\BezeroZigorraType', $bezeroZigorra);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $bezeroZigorra->setUpdatedAt(new \DateTime());
            $em->persist($bezeroZigorra);
            $em->flush();

            return $this->redirectToRoute('kudeatu_bezerozigorra_index');
        }

        return $this->render('bezerozigorra/new.html.twig', array(
            'bezeroZigorra' => $bezeroZigorra,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a BezeroZigorra entity.
     *
     * @Route("/{id}", name="kudeatu_bezerozigorra_show")
     * @Method("GET")
     */
    public function showAction(BezeroZigorra $bezeroZigorra)
    {
        $deleteForm = $this->createDeleteForm($bezeroZigorra);

        return $this->render('bezerozigorra/show.html.twig', array(
            'bezeroZigorra' => $bezeroZigorra,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing BezeroZigorra entity.
     *
     * @Route("/{id}/edit", name="kudeatu_bezerozigorra_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, BezeroZigorra $bezeroZigorra)
    {
        $deleteForm = $this->createDeleteForm($bezeroZigorra);
        $editForm = $this->createForm('AppBundle\Form\BezeroZigorraType', $bezeroZigorra);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $bezeroZigorra->setUpdatedAt(new \DateTime());
            $em->persist($bezeroZigorra);
            $em->flush();

            return $this->redirectToRoute('kudeatu_bezerozigorra_edit', array('id' => $bezeroZigorra->getId()));
        }

        return $this->render('bezerozigorra/edit.html.twig', array(
            'bezeroZigorra' => $bezeroZigorra,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a BezeroZigorra entity.
     *
     * @Route("/{id}", name="kudeatu_bezerozigorra_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, BezeroZigorra $bezeroZigorra)
    {
        $form = $this->createDeleteForm($bezeroZigorra);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($bezeroZigorra);
            $em->flush();
        }

        return $this->redirectToRoute('kudeatu_bezerozigorra_index');
    }

    /**
     * Creates a form to delete a BezeroZigorra entity.
     *
     * @param BezeroZigorra $bezeroZigorra The BezeroZigorra entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(BezeroZigorra $bezeroZigorra)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('kudeatu_bezerozigorra_delete', array('id' => $bezeroZigorra->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
{-# LANGUAGE ParallelListComp #-}
module Test.LazySmallCheck2012(
  -- * Depth-bounded, demand-driven property testing
  depthCheck, depthCheckResult, pruneStats, PruneStats(..), test, Testable(),
  -- ** Property language
  Property(), PropertyLike(..),
  tt, ff, inv, (*&&*), (*==>*), (==>), (|&&|),
  forAll, exists, forAllDeeperBy, existsDeeperBy,
  -- * Serial and Series definition
  Serial(series), Series(), seriesSize,
  -- * Series construction
  module Control.Applicative, (\/), (><), applZC,
  deeperBy, zeroCost, drawnFrom, (<.>),
  -- ** cons\<N\> combinators,
  cons, cons0, cons1, cons2, cons3, cons4, cons5,
  -- * Argument construction,
  Argument(..), BaseCast(), isoIntNat, fromBaseCast, toBaseCast,
  -- * Default instances for 'Serial' and 'Argument'
  module Test.LazySmallCheck2012.Instances,
  module Test.LazySmallCheck2012.FunctionalValues.Instances
  ) where

import Control.Applicative
import Control.Monad
import Data.Data
import Data.Generics.Instances
import Data.Typeable
import System.Exit
import Data.IORef
import Control.Exception
import System.CPUTime

import Test.LazySmallCheck2012.Core
import Test.LazySmallCheck2012.FunctionalValues hiding (Sum)
import Test.LazySmallCheck2012.Instances
import Test.LazySmallCheck2012.FunctionalValues.Instances
import Test.LazySmallCheck2012.Stats

-- | Check a `Testable` `Property` to a specified depth.
depthCheck :: (Data a, Typeable a, Testable a) => Depth -> a -> IO ()
depthCheck d p = case counterexample d (mkTestWithCtx $ pure p) of
  (C ct Nothing)   -> putStrLn $ "LSC: Property holds after "
                                 ++ show (ct) ++ " tests."
  (C ct (Just cx)) -> do putStrLn $ "LSC: Counterexample found after "
                                    ++ show (ct) ++ " tests."
                         print cx
                         exitFailure

depthCheckResult :: (Data a, Typeable a, Testable a) => Depth -> a -> IO Bool
depthCheckResult d p = case counterexample d (mkTestWithCtx $ pure p) of
  (C ct Nothing)   -> do putStrLn $ "LSC: Property holds after "
                                    ++ show (ct) ++ " tests."
                         return True
  (C ct (Just cx)) -> do putStrLn $ "LSC: Counterexample found after "
                                    ++ show (ct) ++ " tests."
                         print cx
                         return False

-- | Machine readable output
data PruneStats = PruneStats { psTests :: Integer, psIsTrue :: Integer }
  deriving Show

pruneStats :: (Data a, Typeable a, Testable a) => Depth -> a -> IO ()
pruneStats d p = do let space = mkTestWithCtx $ pure p
                    pgrs <- getCPUTime >>= newIORef . (,) 0 . (,) (seriesSize d space)
                    result <- evaluate $ allSat (Just pgrs) 0 d space
                    let C ct cp = either (error "LSC: Unresolved expansion") id
                                           `fmap` result
                    print $ PruneStats ct cp

seriesSize :: Depth -> Series a -> Integer
seriesSize d = tSize . mergeTerms . ($ d) . runSeries

-- | Check a `Testable` `Property` for all depths. Runs forever.
test :: (Data a, Typeable a) => Testable a => a -> IO ()
test p = sequence_ [ do putStrLn $ "LSC: Depth " ++ show d ++ ":"
                        depthCheck d p
                   | d <- [0..] ]

-- | Simulates composition in SC & LSC2008.
(<.>) :: Series a -> (Depth -> Depth) -> Series a
(<.>) = flip deeperBy


text:
angular.module("sportsStoreAdmin")
.constant("authUrl", "http://localhost:5500/users/login")
.constant("userInfoUrl", "http://localhost:5500/users/me")
.constant("ordersUrl", "http://localhost:5500/orders")
.controller("adminCtrl", function($scope, $http, userInfoUrl) {

	$scope.data = {
		loggedUser: {}
	};

})
.controller("authCtrl", function($scope, $http, $location, authUrl, userInfoUrl) {

	$scope.authenticate = function (user, pass) {
		$http.post(authUrl,
		{
			username: user,
			password: pass
		},
		{
			withCredentials: true
		})
		.success(function (data) {
			$http.get(userInfoUrl, { withCredentials: true })
				.success(function(data) {
					$scope.data.loggedUser = data;
					$location.path("/main");
				})
				.error(function(error) {
					$location.path("/login");
				});
		})
		.error(function (error) {
			$scope.authenticationError = error;
		});
	}
})
.controller("mainCtrl", function($scope) {

	$scope.screens = ["Products", "Orders"];
	$scope.current = $scope.screens[0];

	$scope.setScreen = function (index) {
		$scope.current = $scope.screens[index];
	};

	$scope.getScreen = function () {
		return $scope.current == "Products"
		? "/views/adminProducts.html" : "/views/adminOrders.html";
	};
})
.controller("ordersCtrl", function ($scope, $http, ordersUrl) {

	$http.get(ordersUrl, {withCredentials : true})
	.success(function (data) {
		$scope.orders = data;
	})
	.error(function (error) {
		$scope.error = error;
	});

	$scope.selectedOrder;

	$scope.selectOrder = function(order) {
		$scope.selectedOrder = order;
	};

	$scope.calcTotal = function(order) {
		var total = 0;
		for (var i = 0; i < order.products.length; i++) {
			total +=
			order.products[i].count * order.products[i].price;
		}
		return total;
	}
});


text:
<?php

declare(strict_types=1);

namespace Bot\Interactions;

use FondBot\Conversation\Interaction;
use FondBot\Drivers\ReceivedMessage;
use Bot\Services\PullService;

class PullProjectInteraction extends Interaction
{
    /**
     * Run interaction.
     *
     * @param ReceivedMessage $message
     */
    public function run(ReceivedMessage $message): void
    {
        $this->sendMessage('Какой проект обновить?');
    }

    /**
     * Process received message.
     *
     * @param ReceivedMessage $reply
     */
    public function process(ReceivedMessage $reply): void
    {
        $text = $reply->getText();
        $text = mb_strtolower($text);

        $this->update($text);
    }

    /**
     * Обновление проекта
     * @param string $text
     * @return void
     */
    public function update(string $text)
    {
        if (! $project = $this->getProject($text)) {
            $this->sendMessage('Такого проекта я не знаю');
            $this->restart();
            return;
        }

        $this->sendMessage('Ок. обновляю ' . $project['title']);

        list($success, $message) = resolve(PullService::class)->pull($project['path']);

        if ($success) {
            $this->sendMessage('Обновил!' .  $message);
        } else {
            $this->sendMessage('Не удалось обновить: ' . $message ?? 'что-то пошло не так');
        }
    }

    /**
     * Узнаем путь к проекту, который нужно обновить
     * @param string $text
     * @return string|null
     */
    public function getProject(string $text)
    {
        // TODO: config
        $projects = [
            [
                'names' => [
                    'back',
                    'бэк',
                    'be',
                ],
                'path' => 'c:\\www\\bcs\\',
                'title' => 'Бэк',
            ],
            [
                'names' => [
                    'front',
                    'фронт',
                    'fe',
                ],
                'path' => 'c:\\www\\other\\fe\\',
                'title' => 'Фронт',
            ],
            [
                'names' => [
                    'bot',
                    'бот',
                    'be',
                ],
                'path' => 'c:\\www\\remotebot\\',
                'title' => 'Бота',
            ],
        ];

        foreach ($projects as $project) {
            if (in_array($text, $project['names']))
                return $project;
        }

        return null;
    }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js tools             **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013-2015, LAMP/EPFL   **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */

package org.scalajs.core.tools.linker.backend

import java.net.URI

import org.scalajs.core.tools.io.WritableVirtualJSFile
import org.scalajs.core.tools.javascript.ESLevel
import org.scalajs.core.tools.logging.Logger
import org.scalajs.core.tools.sem.Semantics

import org.scalajs.core.tools.linker.LinkingUnit
import org.scalajs.core.tools.linker.analyzer.SymbolRequirement

/** A backend of the Scala.js linker. Produces a
 *  [[org.scalajs.core.tools.io.VirtualJSFile VirtualJSFile]].
 *
 *  You probably want to use an instance of [[linker.Linker]], rather than this
 *  low-level class.
 */
abstract class LinkerBackend(
    val semantics: Semantics,
    val esLevel: ESLevel,
    val withSourceMap: Boolean,
    protected val config: LinkerBackend.Config) {

  /** Symbols this backend needs to be present in the linking unit. */
  val symbolRequirements: SymbolRequirement

  /** Emit the given [[LinkingUnit]] to the target output
   *
   *  @param unit [[LinkingUnit]] to emit
   *  @param output File to write to
   *  @param logger Logger to use
   */
  def emit(unit: LinkingUnit, output: WritableVirtualJSFile,
      logger: Logger): Unit

  /** Verify that a [[LinkingUnit]] corresponds to this [[LinkerBackend]]'s
   *  [[org.scalajs.core.tools.sem.Semantics Semantics]] and
   *  [[org.scalajs.core.tools.javascript.ESLevel ESLevel]] (specified via the
   *  [[org.scalajs.core.tools.javascript.OutputMode OutputMode]]).
   *  @throws java.lang.IllegalArgumentException if there is a mismatch
   */
  protected def verifyUnit(unit: LinkingUnit): Unit = {
    require(unit.semantics == semantics,
        "LinkingUnit and LinkerBackend must agree on semantics")
    require(unit.esLevel == esLevel,
        "LinkingUnit and LinkerBackend must agree on esLevel")
  }
}

object LinkerBackend {
  /** Configurations relevant to the backend */
  final class Config private (
      /** Base path to relativize paths in the source map. */
      val relativizeSourceMapBase: Option[URI] = None,
      /** Custom js code that wraps the output */
      val customOutputWrapper: (String, String) = ("", ""),
      /** Pretty-print the output. */
      val prettyPrint: Boolean = false
  ) {
    def withRelativizeSourceMapBase(relativizeSourceMapBase: Option[URI]): Config =
      copy(relativizeSourceMapBase = relativizeSourceMapBase)

    def withCustomOutputWrapper(customOutputWrapper: (String, String)): Config =
      copy(customOutputWrapper = customOutputWrapper)

    def withPrettyPrint(prettyPrint: Boolean): Config =
      copy(prettyPrint = prettyPrint)

    private def copy(
        relativizeSourceMapBase: Option[URI] = relativizeSourceMapBase,
        customOutputWrapper: (String, String) = customOutputWrapper,
        prettyPrint: Boolean = prettyPrint): Config = {
      new Config(relativizeSourceMapBase, customOutputWrapper, prettyPrint)
    }
  }

  object Config {
    def apply(): Config = new Config()
  }
}