text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class Home extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('mail_helper');
        $this->load->helper('staff_helper');
        $this->load->model('frontend/Home_model');
        $this->load->library('form_validation');
        $this->load->library('email');
    }

	/**
	 * @Function	-: index()
	 * @Description	-: This function used for display home of site
	 * @Param		-: No Parameter
	 * @Created on	-: 05-08-2016
	 *
	 */
	function index(){
		$data['js']=array('jquery-ui','jquery.selectBoxIt','jquery.flexslider');
		$data['meta']=array();
		$data['css']=array('flexslider','tab','common','home');
		try{
			$data['services']= $this->Home_model->getServices();
			$data['locations']= $this->Home_model->getLocation();
			$data['featuredGirls']= $this->Home_model->allStaff('1');
			$data['banners']=$this->Home_model->getHomePageBanner('1');
			$data['resetHeaderClass']	= 'reset-header-class';
		}catch(Exception $ex){
			log_message('error','Unable to find front end home page details '.$ex->getMessage());
		}
		$this->load->view('frontend/home-index', $data);
	}

	/**
	 * @Function		-: signUp()
	 * @Description		-: This function used for staff registration
	 * @Param			-: No Parameter
	 * @Return			-: Redirect/error
	 * Created on		-: 09-08-2016
	 */
	function signUp(){
		$data['js']=array('jquery-ui');
		$data['meta']=array();
		$data['css']=array('common','signup');
		try{
			$postData = $this->input->post();
			$postData = removeExtraspace($postData);
			if($postData){
				$this->form_validation->set_rules('username', 'User Name', 'trim|min_length[3]|max_length[100]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('email', 'Email Id', 'trim|min_length[3]|valid_email|max_length[100]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('password', 'Password', 'trim|min_length[8]|max_length[20]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('con-password', 'Confirm Password', 'trim|min_length[8]|max_length[20]|matches[password]|required',array('required' => 'You must provide a %s.'));
				if($this->form_validation->run()==true){
					$userGroup		= 2;
					$password		= $postData['password'];
					$password		= $password.'staff';
					$password		= md5($password);
					$email			= $postData['email'];
					$userName		= strtolower($postData['username']);
					$userStatus		= 0;
					$activationCode	= $userName.'-'.mt_rand();
					$ip_Address		= !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
					$registrationData= array('username'=>$userName,
											'email'=>$email,
											'password'=>$password,
											'active'=>$userStatus,
											'activation_code'=>$activationCode,
											'ip_address'=> $ip_Address
											);
						$userNameCheck 	= $this->Home_model->checkUniqueUsername($userName);
						if($userNameCheck){
							$EmailCheck 	= $this->Home_model->checkUniqueEmail($email);
							if($EmailCheck){
								$insert = $this->Home_model->userRegisteration($registrationData,$userGroup);
								if($insert){
									$link = "activate your account ";
									$responce = sendActivationMail($email,$userName,$link,'account-activation');
									$url  = base_url();
									redirect($url);
								}
							}else{
								$data['error'] = 'Email id already exists !.';
							}
						}else{
							$data['error'] = 'Username already exists !';
						}

				}else{
					$data['error'] = validation_errors();
				}
			}
		}catch(Exception	$ex){
			log_message('error',' Unable to sign up staff registration '.$ex->getMessage());
		}
		$data['resetHeaderClass']	= 'reset-header-class';
		$this->load->view('frontend/signup', $data);
	}

	/**
	 * @Function		-: clientSignUp()
	 * @Description		-: This function used for client registration
	 * @Param			-: No Parameter
	 * @Return			-: Redirect/error
	 * Created on		-: 09-08-2016
	 */
	function clientSignUp(){
		$data['js']=array('jquery-ui');
		$data['meta']=array();
		$data['css']=array('common','signup');
		try{
			$postData = $this->input->post();
			$postData = removeExtraspace($postData);
			if($postData){
				$this->form_validation->set_rules('username', 'User Name', 'trim|min_length[3]|max_length[100]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('email', 'Email Id', 'trim|min_length[3]|valid_email|max_length[100]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('password', 'Password', 'trim|min_length[8]|max_length[20]|required',array('required' => 'You must provide a %s.'));
				$this->form_validation->set_rules('con-password', 'Confirm Password', 'trim|min_length[8]|max_length[20]|matches[password]|required',array('required' => 'You must provide a %s.'));
				if($this->form_validation->run()==true){

					$userGroup		= 3;
					$password		= $postData['password'];
					$password		= $password.'client';
					$password		= md5($password);
					$email			= $postData['email'];
					$userName		= strtolower($postData['username']);
					$userStatus		= 0;
					$activationCode	= $userName.'-'.mt_rand();
					$ip_Address		= !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
					$registrationData= array('username'=>$userName,
											'email'=>$email,
											'password'=>$password,
											'active'=>$userStatus,
											'activation_code'=>$activationCode,
											'ip_address'=> $ip_Address
											);
						$userNameCheck 	= $this->Home_model->checkUniqueUsername($userName);
						if($userNameCheck){
							$EmailCheck 	= $this->Home_model->checkUniqueEmail($email);
							if($EmailCheck){
								$insert = $this->Home_model->userRegisteration($registrationData,$userGroup);
								if($insert){
									$link = "activate your account ";
									$responce = sendActivationMail($email,$userName,$link,'account-activation');
									$url  = base_url();
									redirect($url);
								}
							}else{
								$data['error'] = 'Email id already exists !.';
							}
						}else{
							$data['error'] = 'Username already exists !';
						}

				}else{
					$data['error'] = validation_errors();
				}
			}
		}catch(Exception	$ex){
			log_message('error',' Unable to sign up staff registration '.$ex->getMessage());
		}
		$data['resetHeaderClass']	= 'reset-header-class';
		$this->load->view('frontend/signup', $data);
	}

	/**
	 * @Function		-: checkUserName()
	 * @Description		-: This ajax function used for check unique user name
	 * @Param			-: No Parameter
	 * @Return 			-: array()
	 * @Created on		-: 08-08-2016
	 *
	 */

	public function checkUserName(){
		try{
			$userName = $this->input->post('username');
			$userName = trim($userName);
			$status	= "No";
			$msg	= "";
			$responseArray = array();
			if(!empty($userName)){
				$check = $this->Home_model->checkUniqueUsername($userName);
				if($check){
					$status	= "No";
					$msg	= "User name available !";
				}else{
					$status	= "Yes";
					$msg	= "User name already exists !";
				}
			}
			$responseArray['status'] = $status;$responseArray['msg'] = $msg;
			echo json_encode($responseArray);die;
		}catch(Exception $ex){
			log_message('error','unable to check unique user name '.$ex->getMessage());
		}
	}

	/**
	 * @Function		-: checkUserEmail()
	 * @Description		-: This ajax function used for check unique user email id
	 * @Param			-: No Parameter
	 * @Return 			-: array()
	 * @Created on		-: 08-08-2016
	 *
	 */

	public function checkUserEmail(){
		try{
			$userEmail = $this->input->post('useremail');
			$userEmail = trim($userEmail);
			$status	= "No";
			$msg	= "";
			$responseArray = array();
			if(!empty($userEmail)){
				$check = $this->Home_model->checkUniqueEmail($userEmail);
				if($check){
					$status	= "No";
					$msg	= "Email id available !";
				}else{
					$status	= "Yes";
					$msg	= "Email id already exists !";
				}
			}
			$responseArray['status'] = $status;$responseArray['msg'] = $msg;
			echo json_encode($responseArray);die;
		}catch(Exception $ex){
			log_message('error','unable to check unique user name '.$ex->getMessage());
		}
	}

	/**
	 * @Function	-: search()
	 * @Description	-: This function used for display searching staff list
	 * @Param		-: No Parameter
	 * @Created On	-: 08-08-2016
	 *
	 */

	function search($type,$service=null,$start=0){
		$data['js']=array('jquery-ui','jquery.selectBoxIt','ion.rangeSlider');
		$data['meta']=array();
		$data['css']=array('common','stafflist','normalize','ion.rangeSlider','ion.rangeSlider.skinFlat');
		try{			$service=($service)?$service:'';
						$gender='';
						$location='';
						$searchtype='';
						$data['searchService']	= '';
						$data['searchGender']	= 'Female';
						$data['searchLocation']	= '';
			$postData = $this->input->post();

			if(!empty($postData)){
				$service	= !empty($postData['service_id']) ? $postData['service_id'] :'';
				$gender		= !empty($postData['gender']) ? $postData['gender'] :'';
				$location	= !empty($postData['location_id']) ? $postData['location_id'] :'';
				if(empty($gender)){
					$gender='Female';
					}

				if($gender=='Female'){
					$searchtype='1';
					}
					if($gender=='Male'){
					$searchtype='2';
					}
					 if($gender=='Other'){$searchtype='2';}
				$data['searchService']	= $service;
				$data['searchGender']	= $gender;
				$data['searchLocation']	= $location;

			}else{
				if(!empty($type)&&($type=='girls'||$type=='featured'))
				{
					$gender='Female';
					$data['searchGender']='Female';
					$searchtype='1';
				}
				if(!empty($type)&&$type=='guys')
				{
					$gender='Male';
					$data['searchGender']='Male';
					$searchtype='2';
				}
				 if(!empty($type)&&$type=='Other'){$gender='Male';$searchtype='2';$data['searchGender']='Male';}
			}
				/****** Getting Master tables data ******/
				$hairColors	= $this->Home_model->getHairColors($searchtype);
				$data['hairColors'] = $hairColors;
				$eyeColors	= $this->Home_model->getEyeColors($searchtype);
				$data['eyeColors'] = $eyeColors;
				$bodyTypes	= $this->Home_model->getBodyTypes($searchtype);
				$data['bodyTypes'] = $bodyTypes;
				$bustTypes	= $this->Home_model->getBustTypes($searchtype);
				$data['bustTypes'] = $bustTypes;
				$ethnicities= $this->Home_model->getEthnicities($searchtype);
				$data['ethnicities'] = $ethnicities;
				$locations		= $this->Home_model->getLocation();
				if($locations){
					$data['locations'] = $locations;
				}
				/****** Ending Master tables data ******/

				$services		= $this->Home_model->getServices($searchtype);
				if($services){
					$data['services'] = $services;
				}
		if(!empty($type)&&$type=='featured'){
			$staffLists = $this->Home_model->allStaff('1');
		}else{
			$staffLists = $this->Home_model->searchStaff($service,$gender,$location);
		}
				if($staffLists){
					$data['searchedStaffs'] = $staffLists;
				}
			$data['resetHeaderClass']	= 'reset-header-class';
			$this->load->view('frontend/stafflist', $data);
		}catch(Exception $ex){
			log_message('error',' Unable to display search page properly '.$ex->getMessage());
		}

	}

	/**
	 *
	 * @Function	-: ajaxStaffSearching()
	 * @Description	-: This function used for searching staff list
	 * @Param		-: No Parameter
	 * @Return		-: array()
	 * @Created On	-: 12-08-2016
	 *
	 */

	function ajaxStaffSearching(){
		try{
			$formData	= $this->input->post();
			$service	= !empty($formData['service_id']) ? $formData['service_id'] :'';
			$gender		= !empty($formData['gender']) ? $formData['gender'] :'';
			$location	= !empty($formData['location_id']) ? $formData['location_id'] :'';
			$hairColors	= !empty($formData['hair_colors']) ? $formData['hair_colors'] : array();
			$eyeColors	= !empty($formData['eye_colors']) ? $formData['eye_colors'] : array();
			$bodyTypes	= !empty($formData['body_types']) ? $formData['body_types'] : array();
			$bustTypes	= !empty($formData['bust_types']) ? $formData['bust_types'] : array();
			$ethnicities= !empty($formData['ethnicities']) ? $formData['ethnicities'] : array();
			/****** Slider Values Price,Age Height ******/
			$defaultPrice	= '10;500';$defaultAge	= '16;50';$defaultHeight	= '4;7';
			$price		= !empty($formData['price_range']) ? $formData['price_range'] : $defaultPrice;
			$age		= !empty($formData['age_range']) ? $formData['age_range'] : $defaultAge;
			$height		= !empty($formData['height_range']) ? $formData['height_range'] : $defaultHeight;
			$staffs		= $this->Home_model->searchStaff($service,$gender,$location,$hairColors,$eyeColors,$bodyTypes,$bustTypes,$ethnicities,$price,$age,$height);
			$responseArray = array();
			/****** Searching Staffs Lists ******/
			$html		= "";
			if(!empty($staffs)){
				foreach($staffs as $staff){
					$name = !empty($staff->first_name) ? $staff->first_name .' '.$staff->last_name : '' ;
					$userImg = !empty($staff->image) ? $staff->image : 'natalia.jpg' ;
					$city = !empty($staff->city) ? $staff->city : '' ;
					$serviceId = !empty($staff->serviceId) ? $staff->serviceId : 0 ;
					$minPrice = getStaffMinServicePrice($staff->userId,$serviceId);
					$html .= 'username).'">
';
					$html .= '

'.$name.'
';
					$html .= '
'.$city.'

';
					$html .= '
from $'.$minPrice.'

';
				}
			}else{
				$html .= '
 No Staff Found
';
			}
			//****** Top Service name location and service description ******/
			$htmlTop	= "";
			$locationName ="";
				if(!empty($location) && is_numeric($location)){
					$locationDetails= getLocationDetils($location);
					$locationName	= !empty($locationDetails->name) ? ' in '.$locationDetails->name : '';
				}

				if(!empty($service) && is_numeric($service)){
					$serviceDetails	= getServiceDetils($service);
					$serviceName	= !empty($serviceDetails->name) ? $serviceDetails->name : '' ;
					$serviceDesc	= !empty($serviceDetails->description) ? $serviceDetails->description : '' ;
				$htmlTop .= '
';
				$htmlTop .= ''.$serviceName.' '.$locationName.'';
				$htmlTop .= '';
				$htmlTop .= '

'.$serviceDesc.'
';
				}
			$responseArray['headInfo'] = $htmlTop;
			$responseArray['staffs'] = $html;
			echo json_encode($responseArray);die;
		}catch(Exception	$ex){
			log_message('error',' Unable to search staff list '.$ex->getMessage());
		}
	}

	function staffs($username){
		try{
			$url = base_url();
			if(empty($username)){
				redirect($url);
			}
			$userdetails = getUserIdByUsername($username);
			if(empty($userdetails)){
				redirect($url);
			}
			$userId		= $userdetails->id;
			$userProfile= $userdetails->image;
			if($userProfile){
				$data['profileImage'] = $userProfile;
			}
			/****** Manage Recently Staff Views Section ******/
			$clientId	= logginUserId();
			$viewStaffId	= $userId;
			$ipAddress		= getIpAddress();
			$dateTime		= date('Y-m-d H:i');
			$recentlyViewData	= array('staff_id'=>$viewStaffId,'client_id'=>$clientId,'ip_address'=>$ipAddress,'date_time'=>$dateTime);
			$manageRecentlyView = $this->Home_model->manageRecentlyStaffViews($recentlyViewData);
			//****** Get Cookies view staff id ******//
			if(!empty($_COOKIE['staffs'])){
				$viewStaffId = $_COOKIE['staffs'];
			}else{
				$viewStaffId = getRecentlyViewsStaffIds();
			}
			$recentlyViewStaffs = getRecentlyViewsStaffs($viewStaffId);
			if($recentlyViewStaffs){
				$data['recentlyViewStaff']	= $recentlyViewStaffs;
			}
			//dump($recentlyViewStaffs);die;
			$userName			= !empty($userdetails->first_name) ? $userdetails->first_name.' '.$userdetails->last_name : "";
			$data['userInfo']	= $userdetails;
			$userServices		= getUserServices($userId);
			if($userServices){
				$data['userServices'] = $userServices;
			}
			$useraddress	= getUseraddress($userId);
			if($useraddress){
				$data['useraddress'] = $useraddress;
			}
			$userDetails	= getUserDetails($userId);
			if($userDetails){
				$data['userDetails'] = $userDetails;
			}
			$clientReview	= getUserReviews($userId);
			if($clientReview){
				$data['reviews'] = $clientReview;
			}
			//dump($clientReview);die;
			$userMedias		= getUserMedias($userId);
			if($userMedias){
				$userImages		= $userMedias->images;
				$userVideos		= $userMedias->videos;
				if(!empty($userImages)){
					$userImages = explode(',',$userImages);
				}

				$data['userImages'] = $userImages;
				//dump($userImages);die;
				if(!empty($userVideos)){
					$userVideos = explode(',',$userVideos);
				}
				$data['userVideos'] = $userVideos;

			}
			$data['js']		= array('jquery-ui','jquery.flexslider','timepicki');
			$data['meta']	= array();
			$data['css']	= array('flexslider','common','staffdetails','timepicki');
			$this->load->view('frontend/staffdetails', $data);
		}catch(Exception	$ex){
			log_message('error',' Unable to user details on staff details page');
		}
	}

	/**
	 * @Function	-: sendCustomMail()
	 * @Description	-: This function used for send an email (Custom)
	 * @Param		-: No Parameter
	 * @Return		-: array()
	 * @Created on	-: 08-08-2016
	 *
	 */

	function sendCustomMail($email,$subject,$content){
			$config = array(
				'protocol' => 'smtp',
				'smtp_host' => 'ssl://smtp.gmail.com',
				'smtp_port' => 465,
				'smtp_user' => 'tisuser@gmail.com',
				'smtp_pass' => '#tisindia123#',
				'mailtype' => 'html',
				'charset' => 'iso-8859-1'
			);
			$this->load->library('email', $config);
            $this->email->set_newline("\r\n");
            $this->email->from('tisuser@gmail.com', 'Babes Direct');
            $this->email->to($email);  // replace it with receiver mail id
            $this->email->subject($subject); // replace it with relevant subject
            $this->email->message($content);
            $email_sent = $this->email->send();
            if ($email_sent) {
                return true;
            } else {
                return $this->email->print_debugger();
            }
	}

	/**
	 * @Function	-: accountActivation()
	 * @Description	-: This function used for activate an account
	 * @Param		-: No Parameter
	 * @Return		-: array()
	 * @Created on	-: 08-08-2016
	 *
	 */

	function accountActivation(){
		try{
			$email = $this->input->get('email');
			$token = $this->input->get('token');
			$checkActivation = $this->Home_model->activeAccount($email,$token);
			if($checkActivation){
				//echo "Now your account activated.";
			}else{
				//echo "Unable to active your account";
			}
			redirect('frontend/home');
		}catch(Exception $ex){
			log_message('error',' Unable to active the account'.$ex->getMessage());
		}
	}

/**
 *
 *
 * */

 function getServiceByGender()
 {
	 $gender = $this->input->post('gender');
	 if(!empty($gender)){
		 if($gender=='Female'){$gender='1';}
		 if($gender=='Male'){$gender='2';}
		 if($gender=='Other'){$gender='3';}
		 $services		= $this->Home_model->getServices($gender);
		?>
		<select name="service_id" class="checkempty">
	<option value="">Select Service</option>
	<?php
		if(!empty($services) && is_array($services)){
			foreach($services as $service){
				echo '<option value="'.$service->id.'">'.$service->name.'</option>';
			}
		}
	?>
</select>
		<?php

		 }
 }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/tab_bckground"
    android:orientation="horizontal"
    android:paddingBottom="14dp"
    android:paddingTop="14dp"
    android:paddingLeft="24dp"
    android:paddingRight="24dp">

    <TextView
        android:id="@+id/tabText"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textColor="@color/selector"
        android:textSize="14sp" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
import logging
from collections import OrderedDict
from typing import Tuple

from bokeh.io import output_notebook
from bokeh.plotting import show

from cave.html.html_builder import HTMLBuilder
from cave.reader.runs_container import RunsContainer
from cave.utils.exceptions import Deactivated

class BaseAnalyzer(object):
    """
    The base class for analyzing methods. To create a new analyzer, inherit from this class and extend.
    If you already have an analyzer, but need a wrapper to call it, also inherit it from this class.
    You should overwrite the "get_name"-method.
    Currently the initialization calls the analysis. After the analyzer ran, the results should be saved to the member
    self.result, which is a dictionary with a defined structure.
    The docstrings (this part) will be used to display a tooltip / help for the analyzer, so it should be a descriptive
    and concise small paragraph describing the analyzer and it's results.
    Remember to call super.__init__(runscontainer) in your analyzer's __init__-method. This will initialize the logger,
    name and important attributes.
    All configurator data is available via the self.runscontainer.
    """
    def __init__(self,
                 runscontainer: RunsContainer,
                 *args,
                 **kwargs):
        """
        runscontainer: RunsContainer
            contains all important information about the configurator runs
        """
        self.logger = logging.getLogger(self.__module__ + '.' + self.__class__.__name__)
        self.name = self.get_name()
        self.logger.debug("Initializing %s", self.name)
        self.runscontainer = runscontainer
        self.result = OrderedDict()
        self.error = False

        options = self.runscontainer.analyzing_options
        if self.name not in options.sections():
            self.logger.warning("Please state in the analyzing options whether or not to run this Analyzer "
                                "(simply add a line to the .ini file containing [{}])".format(self.name))
        elif not options[self.name].getboolean('run'):
            raise Deactivated("{0} has been deactivated in the options. To enable, just set "
                              "[{0}][run] = True in the .ini file or pass the appropriate flags.".format(self.name))

        self.options = options[self.name]
        for k, v in kwargs.items():
            if v is not None:
                self.options[k] = v
        self.logger.debug("{} initialized with options: {}".format(self.name, str(dict(self.options))))

    def plot_bokeh(self):
        """
        This function should recreate the bokeh-plot from scratch with as little overhead as possible. This is needed to
        show the bokeh plot in jupyter AND save it to the webpage. The bokeh plot needs to be recreated to be displayed
        in different outputs for reasons beyond out control. So save all analysis results in the class and simply redo
        the plotting with this function.
        This function needs to be called if bokeh-plots are to be displayed in notebook AND saved to html-result.
        """
        raise NotImplementedError()

    def get_html(self, d=None, tooltip=None) -> Tuple[str, str]:
        """General reports in html-format, to be easily integrated in html-code. WORKS ALSO FOR BOKEH-OUTPUT.

        Parameters
        ----------
        d: Dictionary
            a dictionary that will be later turned into a website
        tooltip: string
            tooltip to be displayed in report. optional, will overwrite the docstrings that are used by default.

        Returns
        -------
        script, div: str, str
            header and body part of html-code
        """
        if len(self.result) == 1 and None in self.result:
            self.logger.debug("Detected None-key, abstracting away...")
            self.result = self.result[None]
        if d is not None:
            d[self.name] = self.result
            d[self.name]['tooltip'] = tooltip if tooltip is not None else self.__doc__
        script, div = HTMLBuilder("", "", "").add_layer(None, self.result)
        combine = "\n\n".join([script, div])
        return combine

    def get_jupyter(self):
        """Depending on analysis, this creates jupyter-notebook compatible output."""
        bokeh_plots = self.check_for_bokeh(self.result)
        if bokeh_plots:
            self.logger.warning("Bokeh plots cannot be re-used for notebook if they've already been \"components\"'ed. "
                                "To be sure, get_jupyter should be overwritten for bokeh-producing analyzers.")
            output_notebook()
            for bokeh_plot in bokeh_plots:
                show(bokeh_plot)
        else:
            from IPython.core.display import HTML, display
            display(HTML(self.get_html()))

    @classmethod
    def check_for_bokeh(cls, d):
        """
        Check if there is bokeh-plots in the output of this analyzer by checking the result-dictionary for the bokeh
        keyword.
        """
        result = []  # all bokeh models
        for k, v in d.items():
            if isinstance(v, dict):
                res = cls.check_for_bokeh(v)
                if res:
                    result.extend(res)
            if k == 'bokeh':
                result.append(v)
        return result

    def get_name(self):
        return self.__class__.__name__  # Back-up, can be overwritten, will be used as a name for analysis


text:
from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=300)
    tags = models.CharField(max_length=200)
    creationdate = models.DateTimeField()
    content = models.CharField(max_length=2000)

    def __str__(self):
        return self.title


text:
package alpine.model;

import org.junit.Assert;
import org.junit.Test;

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

public class ManagedUserTest {

    @Test
    public void idTest() {
        ManagedUser user = new ManagedUser();
        user.setId(123L);
        Assert.assertEquals(123L, user.getId());
    }

    @Test
    public void usernameTest() {
        ManagedUser user = new ManagedUser();
        user.setUsername("myUsername");
        Assert.assertEquals("myUsername", user.getUsername());
        Assert.assertEquals("myUsername", user.getName());
    }

    @Test
    public void passwordTest() {
        ManagedUser user = new ManagedUser();
        user.setPassword("Password123!");
        user.setNewPassword("Password1234!");
        user.setConfirmPassword("Password1234!");
        Assert.assertEquals("Password123!", user.getPassword());
        Assert.assertEquals("Password1234!", user.getNewPassword());
        Assert.assertEquals("Password1234!", user.getConfirmPassword());
    }

    @Test
    public void lastPasswordChangeTest() {
        Date date = new Date();
        ManagedUser user = new ManagedUser();
        user.setLastPasswordChange(date);
        Assert.assertEquals(date, user.getLastPasswordChange());
    }

    @Test
    public void fullnameTest() {
        ManagedUser user = new ManagedUser();
        user.setFullname("My Full Name");
        Assert.assertEquals("My Full Name", user.getFullname());
    }

    @Test
    public void emailTest() {
        ManagedUser user = new ManagedUser();
        user.setEmail("me@example.com");
        Assert.assertEquals("me@example.com", user.getEmail());
    }

    @Test
    public void suspendedTest() {
        ManagedUser user = new ManagedUser();
        Assert.assertFalse(user.isSuspended());
        user.setSuspended(true);
        Assert.assertTrue(user.isSuspended());
    }

    @Test
    public void forcePasswordChangeTest() {
        ManagedUser user = new ManagedUser();
        Assert.assertFalse(user.isForcePasswordChange());
        user.setForcePasswordChange(true);
        Assert.assertTrue(user.isForcePasswordChange());
    }

    @Test
    public void nonExpiryPasswordTest() {
        ManagedUser user = new ManagedUser();
        Assert.assertFalse(user.isNonExpiryPassword());
        user.setNonExpiryPassword(true);
        Assert.assertTrue(user.isNonExpiryPassword());
    }

    @Test
    public void teamsTest() {
        List<Team> teams = new ArrayList<>();
        teams.add(new Team());
        ManagedUser user = new ManagedUser();
        user.setTeams(teams);
        Assert.assertEquals(teams, user.getTeams());
        Assert.assertEquals(1, user.getTeams().size());
    }

    @Test
    public void permissionsTest() {
        List<Permission> permissions = new ArrayList<>();
        permissions.add(new Permission());
        ManagedUser user = new ManagedUser();
        user.setPermissions(permissions);
        Assert.assertEquals(permissions, user.getPermissions());
        Assert.assertEquals(1, user.getPermissions().size());
    }
}


text:
package com.github.felixgail.gplaymusic.api;

import com.github.felixgail.gplaymusic.exceptions.NetworkException;
import com.github.felixgail.gplaymusic.model.Album;
import com.github.felixgail.gplaymusic.model.Artist;
import com.github.felixgail.gplaymusic.model.Config;
import com.github.felixgail.gplaymusic.model.DeviceInfo;
import com.github.felixgail.gplaymusic.model.MutationResponse;
import com.github.felixgail.gplaymusic.model.Playlist;
import com.github.felixgail.gplaymusic.model.PlaylistEntry;
import com.github.felixgail.gplaymusic.model.PodcastSeries;
import com.github.felixgail.gplaymusic.model.Station;
import com.github.felixgail.gplaymusic.model.Track;
import com.github.felixgail.gplaymusic.model.enums.Provider;
import com.github.felixgail.gplaymusic.model.enums.StreamQuality;
import com.github.felixgail.gplaymusic.model.listennow.ListListenNowItemResponse;
import com.github.felixgail.gplaymusic.model.listennow.ListenNowSituation;
import com.github.felixgail.gplaymusic.model.requests.IncrementPlaycountRequest;
import com.github.felixgail.gplaymusic.model.requests.ListStationTracksRequest;
import com.github.felixgail.gplaymusic.model.requests.PagingRequest;
import com.github.felixgail.gplaymusic.model.requests.SearchTypes;
import com.github.felixgail.gplaymusic.model.requests.SharedPlaylistRequest;
import com.github.felixgail.gplaymusic.model.requests.TimeZoneOffset;
import com.github.felixgail.gplaymusic.model.requests.mutations.Mutator;
import com.github.felixgail.gplaymusic.model.responses.GenreResponse;
import com.github.felixgail.gplaymusic.model.responses.ListResult;
import com.github.felixgail.gplaymusic.model.responses.SearchResponse;
import com.github.felixgail.gplaymusic.model.responses.SharedPlaylistEntryListResult;
import com.github.felixgail.gplaymusic.util.language.Language;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;

public interface GPlayService {

  @GET("sj/v2.5/query")
  Call<SearchResponse> search(@Query("q") String query,
      @Query("max-results") int maxResults,
      @Query("ct") SearchTypes searchTypes);

  @GET("sj/v2.5/config?dv=0&tier=ff")
  Call<Config> config(@Query("hl") Locale locale);

  @GET("music/{provider}?net=mob&pt=e")
  Call<Void> getTrackLocationMJCK(@Header("X-Device-ID") String androidID,
      @Path("provider") Provider provider,
      @Query("opt") StreamQuality quality,
      @Query("slt") String salt,
      @Query("sig") String signature,
      @Query("mjck") String trackID,
      @QueryMap Map<String, String> kwargs);

  @GET("music/{provider}?net=mob&pt=e")
  Call<Void> getTrackLocationSongId(@Header("X-Device-ID") String androidID,
      @Path("provider") Provider provider,
      @Query("opt") StreamQuality quality,
      @Query("slt") String salt,
      @Query("sig") String signature,
      @Query("songid") String trackID,
      @QueryMap Map<String, String> kwargs);

  @GET("sj/v2.5/devicemanagementinfo")
  Call<ListResult<DeviceInfo>> getDevices();

  @POST("sj/v2.5/ephemeral/top")
  Call<ListResult<Track>> getPromotedTracks();

  @POST("sj/v2.5/radio/station")
  Call<ListResult<Station>> listStations();

  @POST("sj/v2.5/radio/station")
  Call<ListResult<Station>> listStations(@Body PagingRequest body);

  @POST("sj/v2.5/playlistfeed")
  Call<ListResult<Playlist>> listPlaylists();

  @POST("sj/v2.5/playlistfeed")
  Call<ListResult<Playlist>> listPlaylists(@Body PagingRequest body);

  @POST("sj/v2.5/trackfeed")
  Call<ListResult<Track>> listTracks();

  @POST("sj/v2.5/trackfeed")
  Call<ListResult<Track>> listTracks(@Body PagingRequest body);

  @GET("sj/v2.5/podcast/browse")
  Call<ListResult<PodcastSeries>> listBrowsePodcastSeries(@Query("id") String genre);

  @GET("sj/v2.5/listennow/getlistennowitems")
  Call<ListListenNowItemResponse> listListenNowItems();

  @POST("sj/v2.5/listennow/situations")
  Call<ListenNowSituation> getListenNowSituation(@Body TimeZoneOffset offset);

  /**
   * As far as my understanding goes, this simply returns a list containing every {@link
   * PlaylistEntry} from every {@link Playlist} that is {@link Playlist.PlaylistType#USER_GENERATED}.

   *
 Entries from {@link Playlist.PlaylistType#SHARED} playlists that the user is subscribed to
   * are not included. To fetch contents from such a playlist use {@link
   * #listSharedPlaylistEntries(SharedPlaylistRequest)}.
 The Server has no option to return the
   * contents of a single private Playlist.
   *
   * @return the {@link Call} to request a list of {@link PlaylistEntry}
   */
  @POST("sj/v2.5/plentryfeed")
  Call<ListResult<PlaylistEntry>> listPrivatePlaylistEntries();

  /**
   * As far as my understanding goes, this simply returns a list containing every {@link
   * PlaylistEntry} from every {@link Playlist} that is {@link Playlist.PlaylistType#USER_GENERATED}.

   *
 Entries from {@link Playlist.PlaylistType#SHARED} playlists that the user is subscribed to
   * are not included. To fetch contents from such a playlist use {@link
   * #listSharedPlaylistEntries(SharedPlaylistRequest)}.
 The Server has no option to return the
   * contents of a single private Playlist.
   *
   * @return the {@link Call} to request a list of {@link PlaylistEntry}
   */
  @POST("sj/v2.5/plentryfeed")
  Call<ListResult<PlaylistEntry>> listPrivatePlaylistEntries(@Body PagingRequest body);

  @POST("sj/v2.5/plentries/shared")
  Call<SharedPlaylistEntryListResult> listSharedPlaylistEntries(
      @Body SharedPlaylistRequest request);

  @POST
  Call<MutationResponse> batchCall(@Url String path, @Body Mutator mutator);

  @POST("sj/v2.5/radio/stationfeed?")
  Call<ListResult<Station>> getFilledStations(@Body ListStationTracksRequest request);

  @POST("sj/v2.5/trackstats")
  Call<MutationResponse> incremetPlaycount(@Body IncrementPlaycountRequest request);

  @GET("sj/v2.5/explore/genres")
  Call<GenreResponse> getGenres(@Query("parent-genre") String parentGenre);

  @GET("sj/v2.5/fetchalbum")
  Call<Album> getAlbum(@Query("nid") String albumID,
      @Query("include-tracks") boolean includeTracks);

  @GET("sj/v2.5/fetchtrack")
  Call<Track> fetchTrack(@Query("nid") String trackId);

  /**
   * Fetches for an artist by {@code artistID}.
   *
   * @param artistID {@link Artist#getArtistId()} of the artist searched for.
   * @param includeAlbums whether albums of the artist shall be included in the response.
   * @param numTopTracks response includes up to provided number of most heard songs in response
   * @param numRelArtist response includes up to provided number of similar artist in response
   * @return An executable call which returns an artist on execution.
   */
  @GET("sj/v2.5/fetchartist")
  Call<Artist> getArtist(@Query("nid") String artistID,
      @Query("include-albums") boolean includeAlbums,
      @Query("num-top-tracks") int numTopTracks,
      @Query("num-related-artists") int numRelArtist);

  default MutationResponse makeBatchCall(String path, Mutator body)
      throws IOException {
    Response<MutationResponse> response = batchCall("sj/v2.5/" + path, body).execute();
    if (!response.body().checkSuccess()) {
      NetworkException exception = new NetworkException(400, Language.get("network.GenericError"));
      exception.setResponse(response.raw());
      throw exception;
    }
    return response.body();
  }
}


text:
const base = require('../../../jest.config.base');
const packageJson = require('./package');

module.exports = {
    ...base,
    testEnvironment: 'jsdom', // This is overriden, from the base testEnvironment
    name: packageJson.name,
    displayName: packageJson.name,
};


text:
namespace ash {

namespace {

using ::chromeos::WindowStateType;

// Time between calls to "RecordPeriodicMetrics".
constexpr base::TimeDelta kRecordPeriodicMetricsInterval = base::Minutes(30);

enum ActiveWindowStateType {
  ACTIVE_WINDOW_STATE_TYPE_NO_ACTIVE_WINDOW,
  ACTIVE_WINDOW_STATE_TYPE_OTHER,
  ACTIVE_WINDOW_STATE_TYPE_MAXIMIZED,
  ACTIVE_WINDOW_STATE_TYPE_FULLSCREEN,
  ACTIVE_WINDOW_STATE_TYPE_SNAPPED,
  ACTIVE_WINDOW_STATE_TYPE_PINNED,
  ACTIVE_WINDOW_STATE_TYPE_TRUSTED_PINNED,
  ACTIVE_WINDOW_STATE_TYPE_PIP,
  ACTIVE_WINDOW_STATE_TYPE_FLOATED,
  ACTIVE_WINDOW_STATE_TYPE_COUNT,
};

ActiveWindowStateType GetActiveWindowState() {
  ActiveWindowStateType active_window_state_type =
      ACTIVE_WINDOW_STATE_TYPE_NO_ACTIVE_WINDOW;
  WindowState* active_window_state = WindowState::ForActiveWindow();
  if (active_window_state) {
    switch (active_window_state->GetStateType()) {
      case WindowStateType::kMaximized:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_MAXIMIZED;
        break;
      case WindowStateType::kFullscreen:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_FULLSCREEN;
        break;
      case WindowStateType::kPrimarySnapped:
      case WindowStateType::kSecondarySnapped:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_SNAPPED;
        break;
      case WindowStateType::kPinned:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_PINNED;
        break;
      case WindowStateType::kTrustedPinned:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_TRUSTED_PINNED;
        break;
      case WindowStateType::kPip:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_PIP;
        break;
      case WindowStateType::kFloated:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_FLOATED;
        break;
      case WindowStateType::kDefault:
      case WindowStateType::kNormal:
      case WindowStateType::kMinimized:
      case WindowStateType::kInactive:
        active_window_state_type = ACTIVE_WINDOW_STATE_TYPE_OTHER;
        break;
    }
  }
  return active_window_state_type;
}

// Returns true if kiosk mode is active.
bool IsKioskModeActive() {
  return Shell::Get()->session_controller()->login_status() ==
         LoginStatus::KIOSK_APP;
}

// Returns true if there is an active user and their session isn't currently
// locked.
bool IsUserActive() {
  SessionControllerImpl* session = Shell::Get()->session_controller();
  return session->IsActiveUserSessionStarted() && !session->IsScreenLocked();
}

// Records the number of items in the shelf as an UMA statistic.
void RecordShelfItemCounts() {
  int pinned_item_count = 0;
  int unpinned_item_count = 0;
  for (const ShelfItem& item : ShelfModel::Get()->items()) {
    if (item.type == TYPE_PINNED_APP || item.type == TYPE_BROWSER_SHORTCUT)
      ++pinned_item_count;
    else
      ++unpinned_item_count;
  }

  UMA_HISTOGRAM_COUNTS_100("Ash.Shelf.NumberOfItems",
                           pinned_item_count + unpinned_item_count);
  UMA_HISTOGRAM_COUNTS_100("Ash.Shelf.NumberOfPinnedItems", pinned_item_count);
  UMA_HISTOGRAM_COUNTS_100("Ash.Shelf.NumberOfUnpinnedItems",
                           unpinned_item_count);
}

}  // namespace

UserMetricsRecorder::UserMetricsRecorder() {
  StartTimer();
  login_metrics_recorder_ = std::make_unique<LoginMetricsRecorder>();
}

UserMetricsRecorder::UserMetricsRecorder(bool record_periodic_metrics) {
  if (record_periodic_metrics)
    StartTimer();
}

UserMetricsRecorder::~UserMetricsRecorder() {
  timer_.Stop();
}

// static
void UserMetricsRecorder::RecordUserClickOnTray(
    LoginMetricsRecorder::TrayClickTarget target) {
  LoginMetricsRecorder* recorder =
      Shell::Get()->metrics()->login_metrics_recorder();
  recorder->RecordUserTrayClick(target);
}

// static
void UserMetricsRecorder::RecordUserClickOnShelfButton(
    LoginMetricsRecorder::ShelfButtonClickTarget target) {
  LoginMetricsRecorder* recorder =
      Shell::Get()->metrics()->login_metrics_recorder();
  recorder->RecordUserShelfButtonClick(target);
}

void UserMetricsRecorder::StartDemoSessionMetricsRecording() {
  demo_session_metrics_recorder_ =
      std::make_unique<DemoSessionMetricsRecorder>();
  Shell::Get()->AddPreTargetHandler(demo_session_metrics_recorder_.get());
}

void UserMetricsRecorder::OnShellInitialized() {
  // Lazy creation of the DesktopTaskSwitchMetricRecorder because it accesses
  // Shell::Get() which is not available when |this| is instantiated.
  if (!desktop_task_switch_metric_recorder_) {
    desktop_task_switch_metric_recorder_ =
        std::make_unique<DesktopTaskSwitchMetricRecorder>();
  }
  pointer_metrics_recorder_ = std::make_unique<PointerMetricsRecorder>();
  stylus_metrics_recorder_ = std::make_unique<StylusMetricsRecorder>();
}

void UserMetricsRecorder::OnShellShuttingDown() {
  // Doing the nullptr check as the recorder is not initialized outside demo
  // session. It was initialized during StartDemoSessionMetricsRecording().
  if (demo_session_metrics_recorder_ != nullptr) {
    Shell::Get()->RemovePreTargetHandler(demo_session_metrics_recorder_.get());
    demo_session_metrics_recorder_.reset();
  }
  desktop_task_switch_metric_recorder_.reset();

  // To clean up pointer_metrics_recorder_ and stylus_metrics_recorder_
  // properly, a valid shell instance is required, so explicitly delete them
  // before the shell instance becomes invalid.
  pointer_metrics_recorder_.reset();
  stylus_metrics_recorder_.reset();
}

void UserMetricsRecorder::RecordPeriodicMetrics() {
  Shelf* shelf = Shelf::ForWindow(Shell::GetPrimaryRootWindow());
  // TODO(bruthig): Investigating whether the check for |manager| is necessary
  // and add tests if it is.
  if (shelf) {
    // TODO(bruthig): Consider tracking the time spent in each alignment.
    UMA_HISTOGRAM_ENUMERATION("Ash.ShelfAlignmentOverTime",
                              static_cast<ShelfAlignmentUmaEnumValue>(
                                  shelf->SelectValueForShelfAlignment(
                                      SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM,
                                      SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT,
                                      SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT)),
                              SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT);
  }

  if (IsUserInActiveDesktopEnvironment()) {
    RecordShelfItemCounts();
    RecordPeriodicAppListMetrics();

    base::UmaHistogramBoolean(
        "Ash.AppNotificationBadgingPref",
        Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
            prefs::kAppNotificationBadgingEnabled));
  }

  // TODO(bruthig): Find out if this should only be logged when the user is
  // active.
  // TODO(bruthig): Consider tracking how long a particular type of window is
  // active at a time.
  UMA_HISTOGRAM_ENUMERATION("Ash.ActiveWindowShowTypeOverTime",
                            GetActiveWindowState(),
                            ACTIVE_WINDOW_STATE_TYPE_COUNT);
}

bool UserMetricsRecorder::IsUserInActiveDesktopEnvironment() const {
  return IsUserActive() && !IsKioskModeActive();
}

void UserMetricsRecorder::StartTimer() {
  timer_.Start(FROM_HERE, kRecordPeriodicMetricsInterval, this,
               &UserMetricsRecorder::RecordPeriodicMetrics);
}

}  // namespace ash


text:
<?php

class YFlashMessages extends YWidget
{
    const NOTICE_MESSAGE  = 'notice';
    const WARNING_MESSAGE = 'warning';
    const ERROR_MESSAGE   = 'error';

    public $error           = 'error';
    public $warning         = 'warning';
    public $notice          = 'notice';
    public $autoHide        = false;
    public $autoHideSeconds = 3600;
    public $divId           = 'flash';
    public $customJsCode;

    public function run()
    {
        if (count(Yii::app()->user->getFlashes(false)))
        {
            if ($this->autoHide)
            {
                $this->autoHideSeconds = (int) $this->autoHideSeconds;
                $this->error           =       CHtml::encode($this->error);
                $this->warning         =       CHtml::encode($this->warning);
                $this->notice          =       CHtml::encode($this->notice);

                $js = "$('#{$this->divId}').fadeOut({$this->autoHideSeconds});";

                Yii::app()->getClientScript()->registerCoreScript('jquery');
                Yii::app()->getClientScript()->registerScript(md5($this->id), $js, CClientScript::POS_END);
            }
            else if ($this->customJsCode)
            {
                Yii::app()->getClientScript()->registerCoreScript('jquery');
                Yii::app()->getClientScript()->registerScript(md5($this->customJsCode), $this->customJsCode, CClientScript::POS_END);
            }

            $this->render('flashmessages');
        }
    }
}


text:
package web

import (
	"html/template"
	"log"
	"net/http"
	"sort"
	"sync"

	"github.com/joneskoo/httpmonitor/fetcher"
)

// protects statusMap
var statusMapMutex sync.RWMutex

// protected by statusMapMutex as it is read and written concurrently
var statusMap map[string]fetcher.Result

// Status list page contents
const tpl = `
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>HTTP monitor</title>

                        URL
                        Status
                        Response time

{{range .}}
                        {{ .URL }}
                        {{ .StatusText }}
                        {{ .ResponseTime }}

{{else}}

                        no data

                {{end}}

`

func list(w http.ResponseWriter, r *http.Request) {
	// Reader for statusMap
	statusMapMutex.RLock()
	defer statusMapMutex.RUnlock()
	var keys []string
	for k := range statusMap {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	type Status struct {
		URL, StatusText, ResponseTime string
	}
	var statuses []Status
	for _, k := range keys {
		s := statusMap[k]
		statuses = append(statuses, Status{s.URL, s.StatusText(), s.Dur.String()})
	}

	t := template.Must(template.New("list").Parse(tpl))
	t.ExecuteTemplate(w, "list", statuses)
	return
}

// StartListening initializes the server that presents the latest data
// from web server status monitoring
func StartListening(addr string, events chan fetcher.Result) {
	statusMap = make(map[string]fetcher.Result)
	log.Print("Listening on http://", addr)
	http.HandleFunc("/", list)
	go http.ListenAndServe(addr, nil)
	go func(events chan fetcher.Result) {
		for {
			// Writer for statusMap
			res := <-events
			statusMapMutex.Lock()
			statusMap[res.URL] = res
			statusMapMutex.Unlock()
		}
	}(events)
}

func main() {
	addr := "[::1]:8000"
	dummy := make(chan fetcher.Result)
	StartListening(addr, dummy)
}


text:
package org.terracotta.client.message.tracker.demo;

import org.terracotta.client.message.tracker.OOOMessageHandler;
import org.terracotta.client.message.tracker.OOOMessageHandlerConfiguration;
import org.terracotta.entity.ClientSourceId;
import org.terracotta.entity.ConfigurationException;
import org.terracotta.entity.EntityMessage;
import org.terracotta.entity.EntityResponse;
import org.terracotta.entity.EntityUserException;
import org.terracotta.entity.InvokeContext;
import org.terracotta.entity.PassiveServerEntity;
import org.terracotta.entity.ServiceException;
import org.terracotta.entity.ServiceRegistry;

public class DemoPassiveEntity implements PassiveServerEntity {

  private final OOOMessageHandler<EntityMessage, EntityResponse> messageHandler;

  public DemoPassiveEntity(ServiceRegistry serviceRegistry) throws ServiceException {
    OOOMessageHandlerConfiguration<EntityMessage, EntityResponse> messageHandlerConfiguration =
        new OOOMessageHandlerConfiguration<>("foo", msg -> msg instanceof TrackableMessage, 1, m -> 0);
    messageHandler = serviceRegistry.getService(messageHandlerConfiguration);
  }

  @Override
  public void invokePassive(InvokeContext context, EntityMessage message) throws EntityUserException {
    InvokeContext realContext;
    if (message instanceof DeferredMessage) {
      DeferredMessage deferredMessage = (DeferredMessage) message;
      realContext = new InvokeContext() {

        @Override
        public ClientSourceId getClientSource() {
          return deferredMessage.getDeferredClientSource();
        }

        @Override
        public long getCurrentTransactionId() {
          return deferredMessage.getDeferredTransactionId();
        }

        @Override
        public long getOldestTransactionId() {
          return context.getCurrentTransactionId();
        }

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

        @Override
        public ClientSourceId makeClientSourceId(long l) {
          return null;
        }

        @Override
        public int getConcurrencyKey() {
          return 0;
        }
      };
    } else {
      realContext = context;
    }

    messageHandler.invoke(realContext, message, this::processMessage);
  }

  private EntityResponse processMessage(InvokeContext context, EntityMessage message) {
    if (message instanceof MessageTrackerSyncMessage) {
      MessageTrackerSyncMessage trackerSyncMessage = (MessageTrackerSyncMessage) message;
      messageHandler.loadTrackedResponsesForSegment(trackerSyncMessage.getSegmentIndex(), trackerSyncMessage.getClientSourceId(),
          trackerSyncMessage.getTrackedResponses());
    } else {
      // entity message handling logic
    }

    return null;
  }

  @Override
  public void startSyncEntity() {

  }

  @Override
  public void endSyncEntity() {

  }

  @Override
  public void startSyncConcurrencyKey(int i) {

  }

  @Override
  public void endSyncConcurrencyKey(int i) {

  }

  @Override
  public void notifyDestroyed(ClientSourceId sourceId) {
    messageHandler.untrackClient(sourceId);
  }

  @Override
  public void createNew() throws ConfigurationException {

  }

  @Override
  public void destroy() {

  }
}


text:
Go is an open source project.

It is the work of hundreds of contributors. We appreciate your help!

## Filing issues

When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:

1.  What version of Go are you using (`go version`)?
2.  What operating system and processor architecture are you using?
3.  What did you do?
4.  What did you expect to see?
5.  What did you see instead?

General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.

## Verifying changes during development

In order to verify changes to the slides or code examples while developing
locally compile with your local toolchain:

    $ go install golang.org/x/tour/gotour
    $ $GOPATH/bin/gotour

## Running the App Engine version locally

To view the App Engine version of the slides while developing locally, install
the [Go App Engine SDK](https://cloud.google.com/appengine/downloads?hl=en)
and then:

    $ cd $GOPATH/src/golang.org/x/tour
    $ $SDK_PATH/dev_appserver.py .

The App Engine version runs code examples against the service at play.golang.org.
To verify changes to the code examples you must use your local toolchain to compile
and run `gotour` locally.

## Contributing code

Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.

Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.


text:
function MacroCommand() {
	this.commands = [];
}

MacroCommand.prototype.undo = function() {
	for (var i = this.commands.length - 1; i >= 0; i--) {
		this.commands[i].undo();
	}
};

MacroCommand.prototype.redo = function() {
	for (var i = 0; i < this.commands.length; i++) {
		this.commands[i].redo();
	}
};

////////////////////////////////////////////////////////////////////////////////
// class UndoStack
//
// This class is based off QUndoStack from the Qt framework:
// http://doc.qt.nokia.com/stable/qundostack.html
////////////////////////////////////////////////////////////////////////////////

function UndoStack() {
	this.macros = [];
	this.commands = [];
	this.currentIndex = 0;
	this.cleanIndex = 0;
}

UndoStack.prototype._push = function(command) {
	// Only push the macro if it's non-empty, otherwise it leads to weird behavior
	if (command instanceof MacroCommand && command.commands.length == 0) {
		return;
	}

	if (this.macros.length == 0) {
		// Remove all commands after our position in the undo buffer (these are
		// ones we have undone, and once we do something else we shouldn't be able
		// to redo these anymore)
		this.commands = this.commands.slice(0, this.currentIndex);

		// If we got to the current position by undoing from a clean state, set
		// the clean state to invalid because we won't be able to get there again
		if (this.cleanIndex > this.currentIndex) this.cleanIndex = -1;

		this.commands.push(command);
		this.currentIndex++;
	} else {
		// Merge adjacent commands together in the same macro by calling mergeWith()
		// on the previous command and passing it the next command.  If it returns
		// true, the information from the next command has been merged with the
		// previous command and we can forget about the next command (so we return
		// instead of pushing it).
		var commands = this.macros[this.macros.length - 1].commands;
		if (commands.length > 0) {
			var prevCommand = commands[commands.length - 1];
			if ('mergeWith' in prevCommand && prevCommand.mergeWith(command)) {
				return;
			}
		}

		commands.push(command);
	}
};

UndoStack.prototype.push = function(command) {
	this._push(command);
	command.redo();
};

UndoStack.prototype.canUndo = function() {
	return this.macros.length == 0 && this.currentIndex > 0;
};

UndoStack.prototype.canRedo = function() {
	return this.macros.length == 0 && this.currentIndex < this.commands.length;
};

UndoStack.prototype.beginMacro = function() {
	this.macros.push(new MacroCommand());
};

UndoStack.prototype.endMacro = function() {
	if (this.macros.length > 0) this._push(this.macros.pop());
};

UndoStack.prototype.endAllMacros = function() {
	while (this.macros.length > 0) this.endMacro();
};

UndoStack.prototype.undo = function() {
	if (this.canUndo()) this.commands[--this.currentIndex].undo();
};

UndoStack.prototype.redo = function() {
	if (this.canRedo()) this.commands[this.currentIndex++].redo();
};

UndoStack.prototype.getCurrentIndex = function() {
	return this.currentIndex;
};

UndoStack.prototype.setCleanIndex = function(index) {
	this.cleanIndex = index;
};

UndoStack.prototype.clear = function() {
	this.macros = [];
	this.commands = [];
	this.currentIndex = this.cleanIndex = 0;
};


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('echonest-urls', 'Unit | Model | echonest urls', {
  // Specify the other units that are required for this test.
  needs: []
});

test('it exists', function(assert) {
  let model = this.subject();
  // let store = this.store();
  assert.ok(!!model);
});


text:
using System;
using System.Xml.Linq;

namespace NotaFiscalNet.Core
{
    public static class Constants
    {
        /// <summary>
        /// Versão do Leiaute NF-e.
        /// </summary>
        public const string VersaoLeiaute = "3.10";

        /// <summary>
        /// Versão do leiaute do Lote NF-e.
        /// </summary>
        public const string VersaoLeiauteLote = "3.10";

        /// <summary>
        /// Versão do leiaute da Consulta de Lote.
        /// </summary>
        public const string VersaoLeiauteConsultaLote = "2.00";

        /// <summary>
        /// Versão do leiaute de Cancelamento.
        /// </summary>
        public const string VersaoLeiauteCancelamento = "2.00";

        /// <summary>
        /// Versão do leiaute de Inutilização
        /// </summary>
        public const string VersaoLeiauteInutilizacao = "2.00";

        /// <summary>
        /// Versão do leiaute de Inutilização
        /// </summary>
        public const string VersaoLeiauteInutilizacaoNFCe = "3.10";

        /// <summary>
        /// Versão do leiaute de Eventos.
        /// </summary>
        public const string VersaoLeiauteEventos = "1.00";

        /// <summary>
        /// Namespace padrão para extrair recursos armazenados no assembly.
        /// </summary>
        public const string DefaultResourceNamespace = "MaxNFe";

        /// <summary>
        /// Código do Modelo do Documento Fiscal para uma Nota Fiscal Eletrônica
        /// </summary>
        public const string CodigoModeloDocFiscalNFe = "55";

        /// <summary>
        /// Código do Modelo do Documento Fiscal para uma Nota Fiscal de Consumidor Eletrônica
        /// </summary>
        public const string CodigoModeloDocFiscalNFCe = "65";

        /// <summary>
        /// Xml namespace padrão para NF-e (http://www.portalfiscal.inf.br/nfe).
        /// </summary>
        public const string NamespacePortalFiscalNFe = "http://www.portalfiscal.inf.br/nfe";

        /// <summary>
        /// Retorna o nome do arquivo xsd utilizado para validar o xml do arquivo de licença.
        /// </summary>
        public const string InfomaxXmlSchemaFilename = "license.xsd";

        public const string InfomaxXmlSchemaBasicoFilename = "basicos.xsd";
        public const string InformaxXmlSchemaXmldsigFilename = "xmldsig.xsd";

        /// <summary>
        /// Namespace do padrão xmldsig#.
        /// </summary>
        public const string NamespaceXmldsig = "http://www.w3.org/2000/09/xmldsig#";

        public const string NamespaceSchemaXsi = "http://www.w3.org/2001/XMLSchema-instance";

        public const string DeclaracaoXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

        /// <summary>
        /// Quantidade máxima de itens em um Lote de Notas Fiscais Eletrônicas.
        /// </summary>
        public const int MaxLoteItens = 50;

        /// <summary>
        /// Tamanho máximo xml web services.
        /// </summary>
        public const int MaxXmlLength = 512000; // 500 KB

        public const int SignatureAvgLength = 3072; // 3KB

        /// <summary>
        /// Tempo de espera (em milisegundos) para resposta do web service da Sefaz (1 minuto).
        /// </summary>
        [Obsolete("Usar 'MaxNFe.Processor.Configuration.AppSettingsHelper.NFeProcessorSettings.TimeoutWsAutorizacao'")]
        public const int RequestTimeoutRetornoSefaz = 60000; // 1 Minuto

        /// <summary>
        /// Tempo de espera (em milisegundos) para resposta do web service da Sefaz (15 segundos).
        /// </summary>
        [Obsolete(
            "Usar 'MaxNFe.Processor.Configuration.AppSettingsHelper.NFeProcessorSettings.TimeoutWsConsultaSituacao'")]
        public const int ConsultaTimeoutRetornoSefaz = 15000; // 15 Segundos

        public static readonly XNamespace XNamespacePortalFiscalNFe = NamespacePortalFiscalNFe;

        /// <summary>
        /// Namespace do padrão xmldsig# como objeto XNamespace.
        /// </summary>
        public static readonly XNamespace XNamespaceXmldsig = NamespaceXmldsig;
    }
}


text:
- [Changing redraw strategy](#changing-redraw-strategy)
- [Difference between computation methods and m.redraw](#difference-between-computation-methods-and-m-redraw)
- [Preventing redraws on events](#preventing-redraws-on-events)
- [Forcing redraw](#forcing-redraw)
- [Signature](#signature)

---

Redraws the view for the currently active component. Use [`m.mount()`](mithril.mount.md) or [`m.route()`](mithril.route.md) to activate a component.

Calling `m.redraw` triggers a redraw regardless of whether AJAX requests (and other asynchronous services) are completed. Therefore, you should ensure that templates have null checks in place to account for the possibility of variables being uninitialized when the forced redraw occurs.

If you are developing an asynchronous model-level service and finding that Mithril is not redrawing the view after your code runs, you should consider using [`m.startComputation` and `m.endComputation`](mithril.computation.md) to integrate with Mithril's auto-redrawing system instead.

Assuming your templates have appropriate null checks in place, `m.redraw` is useful for transient DOM state such as loading indicators and to commit state to the DOM for the purposes of reading back computed values (for example, `offsetWidth` or `scrollHeight`)

---

### Difference between computation methods and m.redraw

The [`m.startComputation` / `m.endComputation` pair](mithril.computation.md) is designed to be "stacked", i.e. multiple asynchronous services can each call this pair of functions to indicate that they want the redrawing algorithm to wait for them to finish before a redraw occurs. In contrast, `m.redraw` is "aggressive": it redraws as many times as it is called (with the caveat that redraws are batched if they occur less than one animation frame apart in time). In practice, this means that calling `m.redraw` may cause a redraw to happen before some AJAX calls have finished, which in turn, may cause null reference exceptions in templates that try to use the data from these requests without first checking that the data exists.

Therefore, using the computation methods is recommended in order to reduce the amount of intermediate redraws that would otherwise occur as multiple asynchronous services are resolved.

When computation methods are used dilligently and religiously, templates are never redrawn with incomplete data. However, it's important to always write conditional tests in templates to account for the possibility of nullables, because redraws may come to occur more aggressively than data is available (perhaps because a newly introduced 3rd party library calls `m.redraw`, or because you might want a more aggressive redraw policy to implement a specific feature down the road).

Defending against nullables can typically be achieved via the `initialValue` option in [`m.request`](mithril.request.md) and basic null checks (e.g. `data ? m("div", data) : null`).

---

### Changing redraw strategy

If you need to change how Mithril performs a redraw, you can change the value of the `m.redraw.strategy` getter-setter to either `"all"`, `"diff"` or `"none"`. The new strategy will apply to the next scheduled redraw, if any. By default, Mithril sets this value to `"all"` before running controller constructors, and it sets it to `"diff"` before event handlers are triggered.

After the redraw, Mithril resets the value of the flag to either "all" or "diff", depending on whether the redraw was due to a route change or not.

Changing the flag outside of a redrawable context does nothing since the flag gets reset when entering one of the documented redrawable contexts above.

When the flag is set to "all", Mithril throws away the current view and redraws from scratch. This is the default for going from one route to another.

When the flag is set to "diff", Mithril performs a diff between the old view and the new view and applies patches to the DOM only where needed.

When the flag is set to "none", Mithril skips the next redraw. You don't need to change this flag to something else again later, since Mithril does that for you.

```javascript
var Component1 = {
	controller: function() {
		//this component will attempt to diff its template when routing, as opposed to re-creating the view from scratch.
		//this allows config contexts to live across route changes, if its element does not need to be recreated by the diff
		m.redraw.strategy("diff")
	},
	view: function() {
		return m("h1", {config: Component1.config}, "test") //assume all routes display the same thing
	},
	config: function(el, isInit, ctx) {
		if (!isInit) ctx.data = "foo" //we wish to initialize this only once, even if the route changes
	}
}
```

Common reasons why one might need to change redraw strategy are:

-	in order to prevent redraw when dealing with `keypress` events where the event's keyCode is not of interest

	```javascript
	//model
	var saved = false
	function save(e) {
		if (e.keyCode == 13) {
			//this causes a redraw, since event handlers active auto-redrawing by default
			saved = true
		}
		else {
			//we don't care about other keys, so don't redraw
			m.redraw.strategy("none")
		}
	}

	//view
	var view = function() {
		return m("div", [
			m("button[type=button]", {onkeypress: save}, "Save"),
			saved ? "Saved" : ""
		])
	}
	```

-	in order to avoid the full-page recreation when changing routes, for the sake of performance of global 3rd party components.

	```javascript
	//diff when routing, instead of redrawing from scratch
	//this preserves the `<input>` element and its 3rd party plugin after route changes, since the `<input>` doesn't change
	var Component1 = {
		controller: function() {
			m.redraw.strategy("diff")
		},
		view: function() {
			return m("div", [
				m("h1", "Hello Foo"),
				m("input", {config: plugin}) //assuming `plugin` initializes a 3rd party library
			])
		}
	}

	var Component2 = {
		controller: function() {
			m.redraw.strategy("diff")
		},
		view: function() {
			return m("div", [
				m("h1", "Hello Bar"),
				m("input", {config: plugin}) //assuming `plugin` initializes a 3rd party library
			])
		}
	}

	m.route(document.body, "/foo", {
		"/foo": Component1,
		"/bar": Component2,
	})
	```

Note that the redraw strategy is a global setting that affects the entire template trees of all components on the page. In order to prevent redraws in *some parts* of an application, but not others, see [subtree directives](mithril.render.md#subtree-directives)

You can also configure individual elements to always be diffed, instead of recreated from scratch (even across route changes), by using the [`ctx.retain` flag](mithril.md#persisting-dom-elements-across-route-changes). If you need to persist DOM state across route changes, it's recommended that you use the `ctx.retain` flag instead of `m.redraw.strategy("diff")`.

---

### Preventing redraws on events

Sometimes you only care about a particular condition in an event and want the event to not trigger a redraw if this condition is not met.
For example, you might only be interested in running a redraw if a user presses the space bar, and you might not want to waste a redraw if the user presses any other key. In that case, it's possible to skip redrawing altogether by calling `m.redraw.strategy("none")`

```javascript
m("input", {onkeydown: function(e) {
	if (e.keyCode == 13) vm.save() //do things and re-render only if the `enter` key was pressed
	else m.redraw.strategy("none") //otherwise, ignore
}})
```

There are some important semantic caveats for `m.redraw.strategy("none")` that you should be aware of: Setting the strategy to `"none"` only affects **synchronous** redraws. As soon as the event handler returns, the strategy is set back to "diff".

If you set strategy to `"none"` but then proceed to trigger a redraw asynchronously, either via `start/endComputation`, `m.redraw` or `m.request`, a redraw *will* occur, using the `"diff"` strategy.

Additionally, calling `m.redraw` synchronously after calling `m.redraw.strategy("none")` resets the strategy to `"diff"`.

Lastly, be aware that if a user action triggers more than one event handler (for example, oninput and onkeypress, or an event bubbling up to event handlers in multiple ancestor elements), every event triggers a redraw by default. Setting strategy to none in any one of those handlers will not affect the redrawing strategy of other handlers (and remember that `strategy("none")` has no effect on asynchronous redraws).

---

### Forcing redraw

If you find yourself needing to redraw before the browsers normal redraw cycle, you can force a synchronous redraw by passing a boolean `true` as a parameter to `m.redraw`.

```javascript
m.redraw(true) // force
```

Normally, you should only do this if you need to synchronously read a value from the DOM that requires a browser repaint (e.g. `offsetTop` or a CSS rule). If you need to read DOM values, try to read them all at once, because alternating reading and writing to the DOM causes multiple browser repaints, and repaints are expensive.

---

### Signature

[How to read signatures](how-to-read-signatures.md)

```clike
void redraw([Boolean forceSync]) { GetterSetter strategy }

where:
	GetterSetter :: String getterSetter([String value])
```

-	**Boolean forceSync** (optional)

	If set to true, forces the redraw to be synchronous. By default, event handlers schedule redraws to be done asynchronously in order to allow simultaneous events to run before redrawing (for example, the keypress and input are often used together for inputs). Defaults to `false`

-

	### m.redraw.strategy

	**GetterSetter strategy**

	The `m.redraw.strategy` getter-setter indicates how the next component redraw will occur. It can be one of three values:

	-	`"all"` - recreates the DOM tree from scratch
	-	`"diff"` - updates only DOM elements if needed
	-	`"none"` - leaves the DOM tree intact

	This value can be programmatically changed in controllers and event handlers to modify the next redrawing strategy. It is modified internally by Mithril to the value `"all"` before running controller constructors, and to the value `"diff"` after all redraws.

	Calling this function without arguments returns the currently assigned redraw strategy.


text:
package io.cattle.platform.engine.manager.impl;

import io.cattle.platform.engine.context.EngineContext;
import io.cattle.platform.engine.process.ExitReason;
import io.cattle.platform.engine.process.LaunchConfiguration;
import io.cattle.platform.engine.process.ProcessPhase;
import io.cattle.platform.engine.process.ProcessResult;
import io.cattle.platform.engine.process.log.ProcessLog;

import java.util.Date;

public class ProcessRecord extends LaunchConfiguration {
    Long id;
    Date startTime;
    Date endTime;
    ProcessLog processLog;
    ProcessResult result;
    ExitReason exitReason;
    ProcessPhase phase = ProcessPhase.REQUESTED;
    String startProcessServerId;
    String runningProcessServerId;

    public ProcessRecord() {
    }

    public ProcessRecord(LaunchConfiguration config, Long id, String startProcessServerId) {
        super(config);
        this.id = id;
        this.startProcessServerId = startProcessServerId;
        this.startTime = new Date();

        if (this.startProcessServerId == null) {
            this.startProcessServerId = EngineContext.getProcessServerId();
        }
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public ProcessPhase getPhase() {
        return phase;
    }

    public void setPhase(ProcessPhase phase) {
        this.phase = phase;
    }

    public ProcessLog getProcessLog() {
        return processLog;
    }

    public void setProcessLog(ProcessLog processLog) {
        this.processLog = processLog;
    }

    public String getStartProcessServerId() {
        return startProcessServerId;
    }

    public void setStartProcessServerId(String startProcessServerId) {
        this.startProcessServerId = startProcessServerId;
    }

    public String getRunningProcessServerId() {
        return runningProcessServerId;
    }

    public void setRunningProcessServerId(String runningProcessServerId) {
        this.runningProcessServerId = runningProcessServerId;
    }

    public Long getId() {
        return id;
    }

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

    public ExitReason getExitReason() {
        return exitReason;
    }

    public void setExitReason(ExitReason exitReason) {
        this.exitReason = exitReason;
    }

    public ProcessResult getResult() {
        return result;
    }

    public void setResult(ProcessResult result) {
        this.result = result;
    }

}


text:
import unittest
from testbin import TestBin

class TestBinOsocci(TestBin, unittest.TestCase):

    def setUp(self):
        self.bin = 'testosocci'

    def tearDown(self):
        pass


text:
import optparse
import qmrdk as qm
import struct

#parser for options
parser = optparse.OptionParser();
parser.add_option('--f', action="store", dest="file_out", default="radar.out", help="File Name of Capture")
parser.add_option('--s', action="store", dest="frame_rate", default="1024", help="Frame Rate: [0 - 4096], default=1024.")
parser.add_option('--fst', action="store", dest="frequency_start", default="2.4", help="Initial Frequency in GHz")
parser.add_option('--fed', action="store", dest="frequency_stop", default="2.5", help="Final Frequency in GHz")
parser.add_option('--fdiv', action="store", dest="frequency_div", default="1", help="Frequency Divider: [1 to 256]")
parser.add_option('--swty', action="store", dest="sweep_type", default="3", help="Type of Sweep: 0 = Ramp / 1 = Triangle / 2 = Auto Triangle / 3 = CW")
parser.add_option('--swtim', action="store", dest="sweep_time", default="100", help="Sweep Time: [1 to 65536]")
parser.add_option('--dev', action="store", dest="device_address", default="2012:0013", help="USB Device Address of the QMRDK (Def: 2012:0013)")

options, args = parser.parse_args();
dump_file = open(options.file_out, 'wb') #binary write
no_frames = int(options.frame_rate)

start_freq = float(options.frequency_start)
stop_freq = float(options.frequency_stop)
freq_div = int(options.frequency_div)

type_sweep = int(options.sweep_type)
sweep_time = int(options.sweep_time)
qmrdk_addr = options.device_address.split(':')

radar = qm.qmrdk(qmrdk_addr[0], qmrdk_addr[1]) #connect to the device
rad_info = radar.qmrdk_get_system_info() #get system info
temp_val = radar.qmrdk_get_temperature() #get temperature

print "Found a " + rad_info[0] + ": " + rad_info[1] + " " + rad_info[3]
print "Device Current Temperature is: " + str(temp_val)

print "Dumping samples at " + str(no_frames) + " Samples/second in file: " + options.file_out

radar.qmrdk_set_sweep_configuration(type_sweep, sweep_time) #CW and a simple sweep time
radar.qmrdk_set_frequency_configuration(start_freq, stop_freq, freq_div) #Freq Start, End and Freq Div
radar.qmrdk_set_radio(1) #start the Radar

#capture forever and plot
while 1:
    try:
        values = radar.qmrdk_get_data_frame(no_frames) #grab the samples
        for k in range(0,len(values)):
            dump_file.write(struct.pack('f', values[k]))

        #safety measure, look at the temperature and if it is too hot, shutdown
        stat = radar.qmrdk_get_status()

        if (stat[0] == 110):
            print "Panic! Over temperature. Device will be shutdown..."
            dump_file.close()
            radar.qmrdk_set_radio(0) #stop the radar
            break

    except KeyboardInterrupt:
        dump_file.close()
        radar.qmrdk_set_radio(0) #stop the radar
        print "Interrupt detected, closing..."
        break


text:
//
//  YRNavigationViewController.m
//  YR-BSBDJ
//
//  Created by macbook on 15/10/21.
//  Copyright © 2015年 HYR. All rights reserved.
//

#import "YRNavigationViewController.h"

@interface YRNavigationViewController ()

@end

@implementation YRNavigationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
var DBModel = require('./db_model');

var ZoneRule = DBModel.extend({

  attributes: {
    'id': undefined,
    'category_ids': undefined,
    'zone_id': undefined,
    'operator': undefined
  }

}, {

  table: 'zone_rules'

})

module.exports = ZoneRule


text:
//Problem 10. Find sum in array

//Write a program that finds in given array of integers a sequence of given sum S (if present).

using System;

namespace Problem10FindSumInArray
{
    class FindSumInArray
    {
        static void Main()
        {
            // Enter array length
            Console.WriteLine("Enter length of array: ");
            int len = int.Parse(Console.ReadLine());
            Console.WriteLine("S: ");
            int s = int.Parse(Console.ReadLine());

            int[] array = new int[len];

            // Enter values for array
            for (int i = 0; i < len; i++)
            {
                Console.WriteLine("Enter Array[{0}]: ", i);
                array[i] = int.Parse(Console.ReadLine());
            }

            int minCurIndex = 0;
            int currentSum = 0;

            // Search for most frequent number
            for (int i = 0; i < len; i++)
            {
                currentSum = 0;
                minCurIndex = i;

                for (int j = i; j < len; j++)
                {
                    currentSum += array[j];

                    if (currentSum == s)
                    {
                        // Sum found
                        Console.WriteLine("Sum found: ");
                        for (int k = i; k < j + 1; k++) Console.Write(array[k] + ", ");
                        return;
                    }
                }
            }

            // Result
            Console.WriteLine("Sum not found in the array!");
        }
    }
}


text:
#ifndef _WMX_SDK_APDO_CTRL_H
#define _WMX_SDK_APDO_CTRL_H

#include "wmxSDK_Apdo_Cmn.h"

/// <summary>
/// This API initializes the APDO wrapper.
///
/// A call to this API should be preceded with a successful call to the iWmxSDK DLL's wmxSDK_Init() API.
/// This API should be called only once for all threads of a user application.
/// If the user wishes to "reset" the wrapper he should call the wmxApdo_Finalize() API before calling wmxApdo_Init() again.
/// </summary>
///
/// <returns>A wmx_Status_t value indicating the API call's success/error.</returns>
wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxApdo_Init();

/// <summary>
/// This API finalizes the APDO wrapper.
///
/// If the user wishes to finish working with the iWmxSDK DLL altogether, then a call to this API
/// should be followed with a call to the iWmxSDK DLL's wmxSDK_Finalize() API.
/// </summary>
void WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxApdo_Finalize();

#endif // _WMX_SDK_APDO_CTRL_H


text:
// Copyright © 2008, 2011, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// 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; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

using System.Text;
using MySql.Data.MySqlClient;
#if EF6
using System.Data.Entity.Core.Common.CommandTrees;
#else
using System.Data.Common.CommandTrees;
using System.Data.Metadata.Edm;
#endif

namespace MySql.Data.Entity
{
  class DeleteGenerator : SqlGenerator
  {
    public override string GenerateSQL(DbCommandTree tree)
    {
      DbDeleteCommandTree commandTree = tree as DbDeleteCommandTree;

      DeleteStatement statement = new DeleteStatement();

      statement.Target = commandTree.Target.Expression.Accept(this);
      scope.Add("target", statement.Target as InputFragment);

      statement.Where = commandTree.Predicate.Accept(this);

      return statement.ToString();
    }
  }
}


text:
/**
 *
 * @param {type} div        Div on se carregarà el resultat de la cridada ajax
 * @param {type} f          Direcció del fitxer php a executar amb GET params
 * @param {type} param      Paràmetre per realitzar alguna tasca auxiliar amb JS
 * @param {type} async      L'execució de AJAX serà sincrona si és false
 * @returns {undefined}
 */
function loadXMLDoc(div,f,param,async)
{
    //Per defecte, l'Ajax s'executa de forma Asynchronous
    param =  typeof param !== 'undefined' ? param : '';
    async =  typeof async !== 'undefined' ? async : true;

    switch (param) {
        case 'ADD':   /* Add a machine to an Issue */
            var num, i=0, chb, hid, total=0, machines = "";

            //Loop on all the machines that have appeared after the search
            while(document.getElementById("ch"+i)) {
               if (document.getElementById("ch"+i).checked) {
                   if (total)
                       machines += ",";  //separador
                   //Get the id from the machine from a HIDDEN field named hid1, hid2, ...
                   machines += document.getElementById("hid"+i).value;
                   total++;
                }
                i++;
            }
            if (total>0)
                f += "&machines="+machines;
            break;
    }

    //Ajax mitjançant JQUERY
    $.ajax({
        type: "GET", /* Crec que tanmateix, per defecte és GET - xxtoni */
        url: f,
        async: async,
        success : function(resultat) {
    //He de resoldre el problema de la sincronia expressat més avall
            $("#"+div).html(resultat);
        }
    });
}


text:
require 'formula'

class CKermit < Formula
  homepage 'http://www.kermitproject.org/'
  url 'http://www.kermitproject.org/ftp/kermit/archives/cku302.tar.gz'
  version '9.0.302'
  sha1 'd04c8b5600bc0bb0f163d294881f7a5a0d4395b5'

  def install
    system "make macosx"
    man1.mkpath

    # The makefile adds /man to the end of manroot when running install
    # hence we pass share here, not man.  If we don't pass anything it
    # uses {prefix}/man
    system "make", "prefix=#{prefix}", "manroot=#{share}", "install"
  end
end


text:
// Copyright (c) 2013 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.

/**
 * Handles requests sent by the content script.  Shows an infobar.
 */
function onRequest(request, sender, sendResponse) {
  // The number of matches is sent in the request - pass it to the
  // infobar.
  var url = "infobar.html#" + request.count;

  // Show the infobar on the tab where the request was sent.
  chrome.infobars.show({
    tabId: sender.tab.id,
    path: url
  });

  // Return nothing to let the connection be cleaned up.
  sendResponse({});
};

// Listen for the content script to send a message to the background page.
chrome.extension.onRequest.addListener(onRequest);


text:
package org.elasticsearch.spark.sql

import scala.collection.mutable.Buffer
import org.elasticsearch.hadoop.cfg.Settings
import org.elasticsearch.hadoop.serialization.SettingsAware
import org.elasticsearch.hadoop.EsHadoopIllegalStateException

private[sql] trait RowValueReader extends SettingsAware {

  protected var readMetadata = false
  var metadataField = ""
  protected var rowMap: scala.collection.Map[String, Seq[String]] = Map.empty
  protected var currentField = MappingUtils.ROOT_LEVEL_NAME

  abstract override def setSettings(settings: Settings) = {
    super.setSettings(settings)

    val csv = settings.getScrollFields
    readMetadata = settings.getReadMetadata
    rowMap = MappingUtils.getRowOrder(settings)
  }

  def rowOrder(currentField: String): Seq[String] = {
     rowMap.get(currentField) match {
      case Some(v) => v
      case None => throw new EsHadoopIllegalStateException(s"Field '$currentField' not found; typically this occurs with arrays which are not mapped as single value")
    }
  }

  def addToBuffer(esRow: ScalaEsRow, key: AnyRef, value: Any) {
    val pos = esRow.rowOrder.indexOf(key.toString())
    esRow.values.update(pos, value)
  }
}


text:
module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-custom-media')
  ]
}


text:
package org.hisp.dhis.dataadmin.action.duplicatedataelimination;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.datamerge.DataMergeService;

import com.opensymphony.xwork2.Action;

/**
 * @author Lars Helge Overland
 */
public class EliminateDuplicateDataAction
    implements Action
{
    private static final Log log = LogFactory.getLog( EliminateDuplicateDataAction.class );

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private DataMergeService dataMergeService;

    public void setDataMergeService( DataMergeService dataMergeService )
    {
        this.dataMergeService = dataMergeService;
    }

    private DataElementService dataElementService;

    public void setDataElementService( DataElementService dataElementService )
    {
        this.dataElementService = dataElementService;
    }

    private DataElementCategoryService categoryService;

    public void setCategoryService( DataElementCategoryService categoryService )
    {
        this.categoryService = categoryService;
    }

    // -------------------------------------------------------------------------
    // Input
    // -------------------------------------------------------------------------

    private Integer dataElementToEliminate;

    public void setDataElementToEliminate( Integer dataElementToEliminate )
    {
        this.dataElementToEliminate = dataElementToEliminate;
    }

    private Integer categoryOptionComboToEliminate;

    public void setCategoryOptionComboToEliminate( Integer categoryOptionComboToEliminate )
    {
        this.categoryOptionComboToEliminate = categoryOptionComboToEliminate;
    }

    private Integer dataElementToKeep;

    public void setDataElementToKeep( Integer dataElementToKeep )
    {
        this.dataElementToKeep = dataElementToKeep;
    }

    private Integer categoryOptionComboToKeep;

    public void setCategoryOptionComboToKeep( Integer categoryOptionComboToKeep )
    {
        this.categoryOptionComboToKeep = categoryOptionComboToKeep;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
    {
        DataElement dataElementEliminate = dataElementService.getDataElement( dataElementToEliminate );

        DataElementCategoryOptionCombo categoryOptionComboEliminate = categoryService.getDataElementCategoryOptionCombo( categoryOptionComboToEliminate );

        DataElement dataElementKeep = dataElementService.getDataElement( dataElementToKeep );

        DataElementCategoryOptionCombo categoryOptionComboKeep = categoryService.getDataElementCategoryOptionCombo( categoryOptionComboToKeep );

        log.info( "Eliminating: " + dataElementEliminate + " " + categoryOptionComboEliminate  );
        log.info( "Keeping: " + dataElementKeep + " " + categoryOptionComboKeep );

        if ( !( dataElementToEliminate == dataElementToKeep && categoryOptionComboEliminate == categoryOptionComboKeep ) )
        {
            dataMergeService.eliminateDuplicateDataElement( dataElementKeep, categoryOptionComboKeep, dataElementEliminate, categoryOptionComboEliminate );
        }

        log.info( "Elimination done" );

        return SUCCESS;
    }
}


text:
```
This course was taken by a great person who blocked me after Chrome Dev Summit - 2014 "for doing nothing or no harm".

After few months, i also blocked that person.

This is nothing new for me.
Few over-genius engineers too blocked me having a judgemental thought that i am "stupid".

I am taking this course only for my own purpose.
```
```
Just wanted to say that... hmmm... nothing!

:(
```


text:
package org.apache.struts2.components;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;

import com.opensymphony.xwork2.util.ValueStack;

/**
 *
 *
 * Render an HTML input tag of type select.
 *
 *
 *
 *
 Examples
 *

 *
 *
 * <s:select label="Pets"
 *        name="petIds"
 *        list="petDao.pets"
 *        listKey="id"
 *        listValue="name"
 *        multiple="true"
 *        size="3"
 *        required="true"
 *        value="%{petDao.pets.{id}}"
 * />
 *
 * <s:select label="Months"
 *        name="months"
 *        headerKey="-1" headerValue="Select Month"
 *        list="#{'01':'Jan', '02':'Feb', [...]}"
 *        value="selectedMonth"
 *        required="true"
 * />
 *
 * // The month id (01, 02, ...) returned by the getSelectedMonth() call
 * // against the stack will be auto-selected
 *
 *
 *

 *
 *

 *
 *
 *
 * Note: For any of the tags that use lists (select probably being the most ubiquitous), which uses the OGNL list
 * notation (see the "months" example above), it should be noted that the map key created (in the months example,
 * the '01', '02', etc.) is typed. '1' is a char, '01' is a String, "1" is a String. This is important since if
 * the value returned by your "value" attribute is NOT the same type as the key in the "list" attribute, they
 * WILL NOT MATCH, even though their String values may be equivalent. If they don't match, nothing in your list
 * will be auto-selected.

 *
 *
 *
 */
@StrutsTag(
    name="select",
    tldTagClass="org.apache.struts2.views.jsp.ui.SelectTag",
    description="Render a select element",
    allowDynamicAttributes=true)
public class Select extends ListUIBean {
    final public static String TEMPLATE = "select";

    protected String emptyOption;
    protected String headerKey;
    protected String headerValue;
    protected String multiple;
    protected String size;

    public Select(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
        super(stack, request, response);
    }

    protected String getDefaultTemplate() {
        return TEMPLATE;
    }

    public void evaluateExtraParams() {
        super.evaluateExtraParams();

        if (emptyOption != null) {
            addParameter("emptyOption", findValue(emptyOption, Boolean.class));
        }

        if (multiple != null) {
            addParameter("multiple", findValue(multiple, Boolean.class));
        }

        if (size != null) {
            addParameter("size", findString(size));
        }

        if ((headerKey != null) && (headerValue != null)) {
            addParameter("headerKey", findString(headerKey));
            addParameter("headerValue", findString(headerValue));
        }
    }

    @StrutsTagAttribute(description="Whether or not to add an empty (--) option after the header option", type="Boolean", defaultValue="false")
    public void setEmptyOption(String emptyOption) {
        this.emptyOption = emptyOption;
    }

    @StrutsTagAttribute(description=" Key for first item in list. Must not be empty! '-1' and '' is correct, '' is bad.")
    public void setHeaderKey(String headerKey) {
        this.headerKey = headerKey;
    }

    @StrutsTagAttribute(description="Value expression for first item in list")
    public void setHeaderValue(String headerValue) {
        this.headerValue = headerValue;
    }

    @StrutsTagAttribute(description=" Creates a multiple select. The tag will pre-select multiple values" +
                " if the values are passed as an Array or a Collection(of appropriate types) via the value attribute. If one of the keys equals" +
                " one of the values in the Collection or Array it wil be selected", type="Boolean", defaultValue="false")
    public void setMultiple(String multiple) {
        this.multiple = multiple;
    }

    @StrutsTagAttribute(description="Size of the element box (# of elements to show)", type="Integer")
    public void setSize(String size) {
        this.size = size;
    }
}