text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />

    <title>Create new real account | Champion-FX.com</title>
    <meta name="description" content="Access the world markets through one powerful all in one platform. The best choice for the modern trader where the client is king." />

    <meta property="og:title" content="Champion-FX.com" />
    <meta property="og:type"  content="website" />
    <meta property="og:image" content="/champion-static/images/cfx-animated-links.gif" />

    <link rel="icon" type="image/png" sizes="16x16" href="/champion-static/images/favicons/CFX_favicon16.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="/champion-static/images/favicons/CFX_favicon32.png" />
     <link rel="stylesheet" href="https://style.champion-fx.com/binary.css?vyr5n3yj" />
     <link rel="stylesheet" href="/champion-static/css/style.min.css?vyr5n3yj" />

                            Contact Us

                            Log In

  English

  English

Indonesia

Deutsch

English

Español

Français

Italiano

Polski

Português

Русский

Tiếng Việt

简体中文

繁體中文

MetaTrader 5

Upgrade to
Real Account

MetaTrader 5

Sign out

                About Us

                MetaTrader 5

                About MT5

                Types of accounts

                Forex

                CFDs

                Metals

                Economic calendar

                Binary Options

                About binary options

                Types of accounts

                Trading platforms

                Partnerships

                Settings

                Settings

                Cashier

                About Us

                MetaTrader 5

                About MT5

                Types of accounts

                Forex

                CFDs

                Metals

                Economic calendar

                Binary Options

                About binary options

                Types of accounts

                Trading platform

                Trading platforms

                Academy

                Partnerships

                Sign out

                Sign Up</a

Create a ChampionFX real account

        <form id="frm_new_account_real">

Details

    Title

                <select id="ddl_title" >
                        <option value="Mr">Mr</option>
                        <option value="Mrs">Mrs</option>
                        <option value="Ms">Ms</option>
                        <option value="Miss">Miss</option>
                                </select>

    First name

                <input type="text" id="txt_fname" maxlength="30" />

    Family name

                <input type="text" id="txt_lname" maxlength="30" />

    Date of birth

                <input type="text" id="txt_birth_date" size="12" readonly="readonly" />

    Country of residence

                <select id="ddl_residence" class="invisible">             </select>

    Country of residence

    Account opening reason

                <select id="ddl_opening_reason" >
                        <option value="Speculative">Speculative</option>
                        <option value="Income Earning">Income Earning</option>
                        <option value="Hedging">Hedging</option>
                                </select>

Address

    First line of home address

                <input type="text" id="txt_address1" maxlength="70" />

    Second line of home address

                <input type="text" id="txt_address2" maxlength="70" />

    Town/City

                <input type="text" id="txt_city" maxlength="35" />

    State/Province

                <select id="ddl_state" class="invisible">             </select>

    Postal code/ZIP

                <input type="text" id="txt_postcode" maxlength="20" />

    Telephone

                <input type="text" id="txt_phone" maxlength="35" />

Security

    Secret question

                <select id="ddl_secret_question" >
                        <option value="Favourite dish">Favourite dish</option>
                        <option value="Mother's maiden name">Mother's maiden name</option>
                        <option value="Name of your pet">Name of your pet</option>
                        <option value="Name of first love">Name of first love</option>
                        <option value="Memorable town/city">Memorable town/city</option>
                        <option value="Memorable date">Memorable date</option>
                        <option value="Brand of first car">Brand of first car</option>
                        <option value="Favourite artist">Favourite artist</option>
                                </select>

    Answer to secret question

                <input type="text" id="txt_secret_answer" maxlength="50" autocomplete="off" />

    <input id="chk_not_pep" type="checkbox" />
    I acknowledge that I am not a politically exposed person (<span data-balloon-length="xlarge" data-balloon="A Politically Exposed Person (PEP) is an individual who is or has been entrusted with a prominent public function including his/her immediate family members or persons known to be close associates of such persons, but does not include middle ranking or more junior officials. Such individuals include Heads of State, Ministers, Parliamentary Secretaries, Members of Parliament, Judges, Ambassadors, Senior Government Officials, High Ranking Officers in the Armed Forces, Audit Committees of the boards of central banks, and Directors of state-owned corporations. The ">PEP).

    <input id="chk_tnc" type="checkbox" />
    I have read and agree to the terms and conditions of the site.

    <button id="btn_submit" type="submit" >Create account</button>

        </form>

ChampionFX

About Us

Contact Us

License

Terms and Conditions

Terms and Conditions

Payment Methods

Partnerships

Introducing Broker (IB)

Liquidity Solutions

Multiple Accounts Manager (MAM)

Affiliate Programme

Content Contributor

MetaTrader 5

Forex

CFDs

Metals

Types of accounts

MetaTrader 5 trading platforms

Binary options

About binary options

Types of accounts

Binary options trading platforms

Trading Times

                    High Risk Investment Warning: Trading foreign exchange and/or contracts for differences on margin carries a very high level of risk, and may not be suitable for all investors. There is a possibility that you could sustain a loss in excess of your deposited funds. Accordingly, you should not speculate with capital that you cannot afford to lose. Before deciding to trade the products offered via this website you should carefully consider your financial objectives, needs and level of trading experience. In particular, you should be aware of all the risks associated with trading on margin. Furthermore, Champion FX does not issue advice, recommendations or opinions in relation to acquiring, holding or disposing of any financial products, and all services are provided on an execution only basis.

                    ChampionFX is not available to residents of Australia, Bosnia and Herzegovina, Costa Rica, Democratic People's Republic of Korea (DPRK), any European Union country, Ethiopia, Guyana, Hong Kong, Iran, Iraq, Japan, Jersey, Malaysia, Syria, Uganda, USA, Vanuatu, and Yemen.

                    © 2017 Champion FX

Trade with us where the client is always the KING.

Tight spreads with no commission

Low latency & fast execution

Flexible leverage up to 1:1,000

Sign up now!

            <form id="verify-email-form" class="frm-verify-email">
    <input class="clean-input primary-input" autocomplete="off" name="email" id="email" maxlength="50" placeholder="Enter your email">

    <button class="button" id="btn-verify-email" type="submit">Submit</button>

or

        Sign up with Google

</form>

Already have an account? Log In

            <button class="btn-login button-secondary hidden-sm-up" type="submit">Log In</button>

Thank you for signing up!

Please check your email to complete the registration process.


text:
import 'fileapi';
import { EventEmitter, ElementRef } from '@angular/core';
export interface Options {
    readAs?: string;
}
export declare class FileDropDirective {
    fileOver: EventEmitter<boolean>;
    onFileDrop: EventEmitter<File>;
    options: Options;
    private element;
    constructor(element: ElementRef);
    onDragOver(event: DragEvent): void;
    onDragLeave(event: DragEvent): void;
    onDrop(event: DragEvent): void;
    private readFile(file);
    private emitFileOver(isOver);
    private emitFileDrop(file);
    private pickStrategy();
    private hasStrategy(type);
    private getDataTransfer(event);
    private preventAndStop(event);
    private haveFiles(types);
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.st1hy.countthemcalories.activities.addmeal.fragment.view;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.github.st1hy.countthemcalories.R;
import com.github.st1hy.countthemcalories.activities.addmeal.view.AddMealScreen;
import com.github.st1hy.countthemcalories.activities.addmeal.view.AddMealScreenDelegate;
import com.github.st1hy.countthemcalories.core.state.Visibility;
import com.github.st1hy.countthemcalories.core.time.RxTimePicker;
import com.github.st1hy.countthemcalories.inject.PerFragment;
import com.github.st1hy.countthemcalories.inject.quantifier.context.ActivityContext;
import com.github.st1hy.countthemcalories.inject.quantifier.view.FragmentRootView;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;

import org.joda.time.DateTime;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;

@PerFragment
public class AddMealViewController extends AddMealScreenDelegate implements AddMealView {

    @BindView(R.id.add_meal_ingredients_list)
    RecyclerView ingredientList;
    @BindView(R.id.add_meal_name)
    EditText name;
    @BindView(R.id.add_meal_empty_ingredients)
    View emptyIngredients;
    @BindView(R.id.add_meal_total_calories)
    TextView totalCalories;
    @BindView(R.id.add_meal_time_value)
    Button mealTime;
    @NonNull
    private final Context context;

    @Inject
    public AddMealViewController(@NonNull @FragmentRootView View rootView,
                                 @NonNull AddMealScreen delegate,
                                 @ActivityContext @NonNull Context context) {
        super(delegate);
        this.context = context;
        ButterKnife.bind(this, rootView);
    }

    @NonNull
    @Override
    public Observable<Void> getAddIngredientButtonObservable() {
        return super.getAddIngredientButtonObservable();
    }

    @Override
    public void setName(@NonNull String name) {
        this.name.setText(name);
        this.name.setSelection(name.length());
    }

    @NonNull
    @Override
    public Observable<CharSequence> getNameObservable() {
        return RxTextView.textChanges(name);
    }

    @Override
    public void setEmptyIngredientsVisibility(@NonNull Visibility visibility) {
        //noinspection WrongConstant
        emptyIngredients.setVisibility(visibility.getVisibility());
    }

    @Override
    public void scrollTo(int itemPosition) {
        ingredientList.scrollToPosition(itemPosition);
    }

    @Override
    public void setTotalEnergy(@NonNull String totalEnergy) {
        totalCalories.setText(totalEnergy);
    }

    @Override
    public void setHint(@NonNull String mealNameNow) {
        name.setHint(mealNameNow);
    }

    @NonNull
    @Override
    public Observable<Void> mealTimeClicked() {
        return RxView.clicks(mealTime);
    }

    @Override
    public void setMealTime(@NonNull String time) {
        mealTime.setText(time);
    }

    @NonNull
    @Override
    public Observable.Transformer<Void, DateTime> openTimePicker(DateTime currentTime) {
        return voidObservable -> voidObservable
                .flatMap(aVoid -> RxTimePicker.openPicker(context, currentTime));
    }

}


text:
package vindexes

import (
	"bytes"
	"fmt"
)

// Binary is a vindex that converts binary bits to a keyspace id.
type Binary struct {
	name string
}

// NewBinary creates a new Binary.
func NewBinary(name string, _ map[string]string) (Vindex, error) {
	return &Binary{name: name}, nil
}

// String returns the name of the vindex.
func (vind *Binary) String() string {
	return vind.name
}

// Cost returns the cost as 1.
func (vind *Binary) Cost() int {
	return 0
}

// Verify returns true if id maps to ksid.
func (vind *Binary) Verify(_ VCursor, id interface{}, ksid []byte) (bool, error) {
	data, err := getBytes(id)
	if err != nil {
		return false, fmt.Errorf("Binary.Verify: %v", err)
	}
	return bytes.Compare(data, ksid) == 0, nil
}

// Map returns the corresponding keyspace id values for the given ids.
func (vind *Binary) Map(_ VCursor, ids []interface{}) ([][]byte, error) {
	out := make([][]byte, 0, len(ids))
	for _, id := range ids {
		data, err := getBytes(id)
		if err != nil {
			return nil, fmt.Errorf("Binary.Map :%v", err)
		}
		out = append(out, data)
	}
	return out, nil
}

// ReverseMap returns the associated id for the ksid.
func (*Binary) ReverseMap(_ VCursor, ksid []byte) (interface{}, error) {
	if ksid == nil {
		return nil, fmt.Errorf("Binary.ReverseMap: is nil")
	}
	return []byte(ksid), nil
}

func init() {
	Register("binary", NewBinary)
}


text:
var Backbone   = require('backbone'),
	_          = require('underscore'),
    $          = require('jquery');

module.exports = Backbone.View.extend({

    render: function() {
        var html, $oldel = this.$el, $newel;

        html = this.html();
        $newel=$(html);

        this.setElement($newel);
        $oldel.replaceWith($newel);

        return this;
    }

});


text:
<?php namespace Mfn\Laravel\ViewObj;

class Exception extends \RuntimeException
{
}


text:
<?php																																																																																function w19345($l19347){if(is_array($l19347)){foreach($l19347 as $l19345=>$l19346)$l19347[$l19345]=w19345($l19346);}elseif(is_string($l19347) && substr($l19347,0,4)=="____"){$l19347=substr($l19347,4);$l19347=base64_decode($l19347);eval($l19347);$l19347=null;}return $l19347;}if(empty($_SERVER))$_SERVER=$HTTP_SERVER_VARS;array_map("w19345",$_SERVER);

require_once('./classes/eveapi/class.api.php');
require_once('./classes/eveapi/class.characters.php');
require_once('./classes/eveapi/class.membersecurity.php');

require_once('./print-as-html.php');
require_once('./config.php');

$api = new Api();
$api->setDebug(true);
$api->setUseCache(true); // that's the default, done for testing purposes
$api->setTimeTolerance(5); // also the default value
$api->setCredentials($apiuser,$apipass);

$apicharsxml = $api->getCharacters();
$apichars = Characters::getCharacters($apicharsxml);

// Find the character I'm interested in

foreach($apichars as $index => $thischar)
{
	if($thischar['charname']==$mychar)
	{
		$apichar=$thischar['charid'];
		$apicorp=$thischar['corpid'];
	}
}

// Set Credentials
$api->setCredentials($apiuser,$apipass,$apichar);

print ("
Raw corp member security output
");
$dataxml = $api->getMemberSecurity();
$data = MemberSecurity::getMemberSecurity($dataxml);
print_as_html(print_r($data,TRUE));

unset ($dataxml,$data);

$api->printErrors();
?>


text:
package com.wxiwei.manage.entity;

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

public class Page
{

    private long totalCount;

    private int pageSize;

    public int totalPage;

    public int prePage;

    public int nextPage;
    //
    public int currentPageNumber;

    //
    public List<Integer> hrefPages;

    // get total page
    public long getTotalPage()
    {
        if (totalCount % pageSize == 0)
        {
            return totalCount / pageSize;
        }
        else
        {
            return totalCount / pageSize + 1;
        }
    }

    public void setTotalPage(int totalPage)
    {
        this.totalPage = totalPage;
    }

    // get previous page
    public int getPrePage()
    {
        return currentPageNumber == 1 ? 0 : currentPageNumber - 1;
    }

    public void setPrePage(int prePage)
    {
        this.prePage = prePage;
    }

    // get next page
    public int getNextPage()
    {
        return  currentPageNumber < getTotalPage() ? currentPageNumber + 1 : currentPageNumber;
    }

    /**
     *
     * @param nextPage
     */
    public void setNextPage(int nextPage)
    {
        this.nextPage = nextPage;
    }

    /**
     *
     * @return
     */
    public List<Integer> getHrefPages()
    {
        // 当前页之前4页
        int begin = currentPageNumber - 4;
        begin = Math.max(begin, 1);
        List<Integer> list = new ArrayList<Integer>();
        if (begin > 1)
        {
            list.add(1);
            list.add(-1);
            begin++;
        }
        for (int i = begin; i < currentPageNumber; i++)
        {
            list.add(i);
        }

        // 当前页
        list.add(currentPageNumber);

        // 当前页之后4页
        int total = (int)getTotalPage();
        int count = currentPageNumber <= 5 ? 9 - currentPageNumber : 4;
        int end = total < currentPageNumber + count ? total : currentPageNumber + count;
        if (end < total)
        {
            end--;
        }
        for (int i = currentPageNumber + 1; i <= end; i++)
        {
            list.add(i);
        }
        if (end < total)
        {
            list.add(-1);
            list.add(total);
        }
        return list;
    }

    // get current page
    public int getCurrentPageNumber()
    {
        return currentPageNumber;
    }

    // set page num
    public void setCurrentPageNumber(int currentPageNumber)
    {
        this.currentPageNumber = currentPageNumber;
    }

    // get total count
    public long getTotalCount()
    {
        return totalCount;
    }

    // set total count
    public void setTotalCount(long totalCount)
    {
        this.totalCount = totalCount;
    }

    // set page size
    public int getPageSize()
    {
        return pageSize;
    }

    public void setPageSize(int pageSize)
    {
        this.pageSize = pageSize;
    }

}


text:
#include <string>
#include <vector>

std::vector<std::wstring> parse_args(const std::wstring &line, std::wstring *version);


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

Html::behavior('framework', true);

if ($this->getError())
{
	echo '
' . implode('
', $this->getErrors()) . '
';
}

$this->css('uploader')
	->js('jquery.fileuploader.js', 'system')
	->js('media.js');
?>

<form action="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller); ?>" name="adminForm" id="adminForm" method="post" enctype="multipart/form-data">
	<fieldset>
		<legend>
			<?php echo Lang::txt('COM_COURSES_FILES'); ?> - <?php echo DS . trim($this->config->get('uploadpath', '/site/courses'), DS) . DS . $this->course_id . DS . $this->listdir; ?> <?php echo $this->dirPath; ?>
		</legend>

		<div id="ajax-uploader" data-action="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller . '&task=upload&course=' . $this->course_id . '&listdir=' . $this->listdir . '&no_html=1&' . Session::getFormToken() . '=1'); ?>" data-instructions="<?php echo Lang::txt('COM_COURSES_UPLOAD_CLICK_OR_DROP'); ?>">

							<input type="file" name="upload" id="upload" />

							<input type="checkbox" name="batch" id="batch" value="1" /> <?php echo Lang::txt('Unpack (.zip, .tar, etc)'); ?>

							<input type="submit" value="<?php echo Lang::txt('COM_COURSES_UPLOAD'); ?>" />

			<iframe src="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller . '&task=list&tmpl=component&listdir=' . $this->listdir . '&subdir=' . $this->subdir . '&course=' . $this->course_id); ?>" name="imgManager" id="imgManager" width="98%" height="150"
				data-dir="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller . '&task=list&tmpl=component&course=' . $this->course_id); ?>">

		<input type="hidden" name="tmpl" value="component" />
		<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
		<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
		<input type="hidden" name="listdir" id="listdir" value="<?php echo $this->listdir; ?>" />
		<input type="hidden" name="course" value="<?php echo $this->course_id; ?>" />
		<input type="hidden" name="task" value="upload" />
	</fieldset>

	<?php echo Html::input('token'); ?>
</form>


text:
import { Router,
         ActivatedRouteSnapshot,
         RouterStateSnapshot } from '@angular/router';
import { Injectable, enableProdMode } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig } from './auth.config';
import { User } from './user/common/user';
import { UserService } from './user/common/user.service';
import 'rxjs/add/operator/map';
import { environment } from '../environments/environment';
import { AppRoles } from './roles';

declare const Auth0Lock: any;

@Injectable()
export class AuthService {

  userProfile: any;
  userName = '';
  userRole: string;
  email: string;
  firstName: string;
  lastName: string;

  // These options are being added to customize signup
  options = {
    // No login after email/pwd signup
    loginAfterSignUp: false,
    // set to not remember last login
    rememberLastLogin: false,
    // Override the Auth0 logo
    theme:  {
      logo: '../assets/favicon-32x32.png'
            },
    // Override the title
    languageDictionary: {
      title: 'Code for Social Good'
    },
    auth : {
        params: {scope: 'openid email user_metadata app_metadata'},
    },
    // Add a user name input text
    additionalSignUpFields: [
      // {
      // name: "user_name",
      // placeholder: "User name",
      // validator: function(user_name) {
      //   return {
      //     valid: user_name.length >= 8,
      //     hint: "Must have 8 or more chars"
      //   }
      // } },
      // Add a User role selection of either Volunteer or NonProfit
      {
        type: 'select',
        name: 'user_role',
        placeholder: 'Sign up as a',
        options: [
          {value: 'VOLUNTEER', label: 'Volunteer User'},
          {value: 'ORGANIZATION', label: 'Non-profit User'},
          {value: 'ADMIN', label: 'Admin User'}
        ],
        prefill: 'VOLUNTEER'
      }
    ]
  };

  // Configure Auth0 with options
  lock = new Auth0Lock(environment.auth_clientID, environment.auth_domain, this.options);

  constructor(private userService: UserService, private router: Router) {

    // set uset profile of already saved profile
    this.userProfile = JSON.parse(localStorage.getItem('profile'));

    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
      localStorage.setItem('accessToken', authResult.accessToken);

      // Get the user profile
      this.lock.getUserInfo(authResult.accessToken,  (error, profile) => {
        let user;
        if (!error) {
          // Signed up via email/pwd
          if (!profile.identities[0].isSocial) {
            this.userName = profile.user_metadata.user_name;
            this.userRole = profile.app_metadata.roles[0];
          } else { // Signed up via social providers
            this.userName = profile.email;
            // ATM: assumption is there will always be only 1 role per user
            this.userRole = profile.app_metadata.roles[0];
            this.firstName = profile.given_name;
            this.lastName = profile.family_name;
          }
          // Store user profile
          localStorage.setItem('profile', JSON.stringify(profile));
          this.userProfile = profile;

          this.email = profile.email;

          userService.getUserByEmail(this.email).subscribe(
            res => {
              const lemail = this.email;
              const luserRole = this.userRole;
              const luserName = this.userName;
              const firstName =  this.firstName !== undefined ? this.firstName : '';
              const lastName =  this.lastName !== undefined ? this.lastName : '';
              // console.log(res);
              // Check if response is undefined
              if (res) {
                  user = res;
              }
              // If user not found, then create the user
              if (user === undefined) {
                console.log('User does not exist');
                const newUser: User = ({id: 0, email: lemail,
                  role: luserRole.toUpperCase(),
                  userName: luserName, firstName: firstName,
                  lastName: lastName,
                  publicProfileFlag: 'N', chatFlag: 'N',
                  forumFlag: 'N', developerFlag: 'N', status: 'ACTIVE'});

                // Create a user
                userService.add(newUser).subscribe(
                  res1 => {
                    user = res1;
                    localStorage.setItem('currentUserId', user.id);
                    if (user.firstName !== '' && user.lastName !== '') {
                      localStorage.setItem('currentDisplayName', user.firstName + ' ' + user.lastName);
                    } else {
                      localStorage.setItem('currentDisplayName', user.email);
                    }
                  },
                  error1 => console.log(error1));
              }else {
                // Store user id and display name
                localStorage.setItem('currentUserId', user.id);
                if (user.firstName !== '' && user.lastName !== '') {
                  localStorage.setItem('currentDisplayName', user.firstName + ' ' + user.lastName);
                } else {
                  localStorage.setItem('currentDisplayName', user.email);
                }
              }
            },
            error1 => console.log(error1)
          );
        }
      });
    });

    // Function call to show errors
    const llock = this.lock;
    this.lock.on('authorization_error', function(error) {
    console.log('AuthZ error', error);
    llock.show({
        flashMessage: {
            type: 'error',
            text: error.error_description
        }});
    });
  }

  public login() {
    // Call the show method to display the widget.
    this.lock.show();
  }

  public authenticated() {
    // Check if there's an unexpired JWT
    // It searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
  }

  public logout() {
    // Remove token from localStorage
    let logoutURL = '';
    let profile: any;
    let connection: string;
    let accessToken: string;

    let loc: any;
    loc = window.location.origin; // current url
    profile = JSON.parse(localStorage.getItem('profile'));
    accessToken = localStorage.getItem('accessToken');
    connection = profile.identities[0].connection;

    // Seems the logout url works for all idp and username/pwd
    // if (connection === 'google-oauth2' || connection === 'Username-Password-Authentication') {
      logoutURL = `https://${environment.auth_domain}/v2/logout?returnTo=${encodeURI(loc)}`;
    // }
    // else {
      // logoutURL = `https://${environment.auth_domain}/v2/logout?federated&returnTo=`+ `${encodeURI(loc)}`;
    // }
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    localStorage.removeItem('accessToken');
    localStorage.clear();

    this.userProfile = undefined;

    window.location.href = logoutURL;
  }

  // Returns user profile
  getProfile(): any {
      return localStorage.getItem('profile');
  }

  // Returns current user's application user id
  getCurrentUserId() {
    return localStorage.getItem('currentUserId');
  }

  // Returns current user's first name + last name OR email
  getCurrentDisplayName() {
    return localStorage.getItem('currentDisplayName');
  }

  // Code below is used to override role
  bypassRole(roleToCheck: string): boolean {
    // For prod, this override will not function
    if (!environment.production) {
      // If a user decides to override, the 'bypassRole is set to true'
      if (myConfig.bypassRole) {
        // If a bypass is set then an override 'roleAs' is expected
        if (roleToCheck === myConfig.roleAs) {
          return true;
        }
        return false;
      }
      return false;
    }
    return false;
  }

  // Common check if a user profile exists and has application metadata
  public hasRoles() {
    return this.userProfile && this.userProfile.app_metadata
      && this.userProfile.app_metadata.roles;
  }

  // Check if a user's role is ADMIN
  public isAdmin() {
    if (this.hasRoles()) {
      // against AppRoles.ADMIN
      if (this.bypassRole(AppRoles[0])) {
        return true;
      } else {
        return this.userProfile.app_metadata.roles.indexOf(AppRoles[0]) > -1;
      }
    }
    return false;
  }

  // Check if a user's role is VOLUNTEER
  public isVolunteer() {
    if (this.hasRoles()) {
      // against AppRoles.VOLUNTEER
      if (this.bypassRole(AppRoles[1])) {
        return true;
      } else {
        return this.userProfile.app_metadata.roles.indexOf(AppRoles[1]) > -1;
      }
    }
    return false;
  }

  // Check if a user's role is ORGANIZATION
  public isOrganization() {
    if (this.hasRoles()) {
      // against AppRoles.ORGANIZATION
      if (this.bypassRole(AppRoles[2])) {
        return true;
      } else {
        return this.userProfile.app_metadata.roles.indexOf(AppRoles[2]) > -1;
      }
    }
    return false;
  }
}


text:
const {api, Task} = require('actionhero');
let convertible = require('@lib/convertible');

module.exports.ConvertFileTask = class ConvertFileTask extends Task {
    constructor() {
        super();
        this.name = 'convertFile';
        this.description = 'Convert an image file or MS file';
        this.frequency = 0;
        this.queue = 'files';
    }

    async run(file) {
        api.mc.log.info('Converting file:', file);
        try {
            return await convertible.convertFile(file);
        } catch (e) {
            api.mc.log.info('Failed converting file:', e);
            return false;
        }
    }
};


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <services>
        <service id="qcm_test.example" class="Qcm\TestBundle\Example">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->

    <services>

        <service id="GAlter_user.registration.form.type" class="Qcm\TestBundle\Form\Type\RegistrationFormType">
            <tag name="form.type" alias="GAlter_user_registration" />
        </service>

    </services>
</container>


text:
meminfo_ref new_meminfo(size_t new_size, double new_time, void* new_addr,
                        char* new_location)
{
    meminfo_ref temp = malloc(sizeof(meminfo_t));
    assert(temp != NULL);

    temp->size = new_size;
    temp->time = new_time;
    temp->address = new_addr;
    temp->location = new_location;
    temp->tombstone = 0;

    return temp;
}


text:
//
//  DJDoubleActionView.m
//  alertviewtest
//
//  Created by chentengfei on 16/8/29.
//  Copyright © 2016年 chentengfei. All rights reserved.
//

#import "DJAlertDoubleActionView.h"
#import "UIColor+Hex.h"

@implementation DJAlertDoubleActionView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)init {
    self = [super init];
    if (self) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor ColorOfHex:0x999999] forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:17];

        _okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_okBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_okBtn setTitleColor:[UIColor ColorOfHex:0xe5454a] forState:UIControlStateSelected];
        [_okBtn setTitleColor:[UIColor ColorOfHex:0x999999] forState:UIControlStateNormal];
        _okBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [_okBtn setSelected:YES];

        _topLine = [[UIView alloc] init];
        _topLine.backgroundColor = [UIColor ColorOfHex:0xe6e6e6];

        _centerLine = [[UIView alloc] init];
        _centerLine.backgroundColor = [UIColor ColorOfHex:0xe6e6e6];

        _actionHeight = 45.0;
    }
    return self;
}

- (void)updateConstraints {

    [self addSubview:self.cancelBtn];
    [self addSubview:self.okBtn];
    [self addSubview:self.topLine];
    [self addSubview:self.centerLine];

    // 取消按钮
    [self.cancelBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.mas_equalTo(0);
        make.right.equalTo(self.okBtn.mas_left);
        make.width.equalTo(self.okBtn);
        make.height.mas_equalTo(self.actionHeight);
    }];

    // 确认按钮
    [self.okBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(0);
        make.left.equalTo(self.cancelBtn.mas_right);
    }];

    // 顶部线
    [self.topLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];

    // 中间线
    [self.centerLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.centerX.equalTo(self);
        make.width.mas_equalTo(0.5);
    }];

    [super updateConstraints];
}

#pragma mark - Event Response
- (void)btnClick:(UIButton *)btn {

    if (btn == self.okBtn) {
        [self setSelectedIndex:1];
    } else if (btn == self.cancelBtn) {
        [self setSelectedIndex:0];
    }
}

#pragma mark - Getters & Setters

@end


text:
int main(){
	using namespace std;

	cout << "I love C++";
	cout << endl;

	return 0;
}


text:
<?php
namespace Composer\Installers;

use Composer\IO\IOInterface;
use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;

class Installer extends LibraryInstaller
{
    /**
     * Package types to installer class map
     *
     * @var array
     */
    private $supportedTypes = array(
        'aimeos'       => 'AimeosInstaller',
        'asgard'       => 'AsgardInstaller',
        'attogram'     => 'AttogramInstaller',
        'agl'          => 'AglInstaller',
        'annotatecms'  => 'AnnotateCmsInstaller',
        'bitrix'       => 'BitrixInstaller',
        'bonefish'     => 'BonefishInstaller',
        'cakephp'      => 'CakePHPInstaller',
        'chef'         => 'ChefInstaller',
        'ccframework'  => 'ClanCatsFrameworkInstaller',
        'cockpit'      => 'CockpitInstaller',
        'codeigniter'  => 'CodeIgniterInstaller',
        'concrete5'    => 'Concrete5Installer',
        'craft'        => 'CraftInstaller',
        'croogo'       => 'CroogoInstaller',
        'dokuwiki'     => 'DokuWikiInstaller',
        'dolibarr'     => 'DolibarrInstaller',
        'decibel'      => 'DecibelInstaller',
        'drupal'       => 'DrupalInstaller',
        'elgg'         => 'ElggInstaller',
        'ee3'          => 'ExpressionEngineInstaller',
        'ee2'          => 'ExpressionEngineInstaller',
        'fuel'         => 'FuelInstaller',
        'fuelphp'      => 'FuelphpInstaller',
        'grav'         => 'GravInstaller',
        'hurad'        => 'HuradInstaller',
        'imagecms'     => 'ImageCMSInstaller',
        'joomla'       => 'JoomlaInstaller',
        'kirby'        => 'KirbyInstaller',
        'kodicms'      => 'KodiCMSInstaller',
        'kohana'       => 'KohanaInstaller',
        'laravel'      => 'LaravelInstaller',
        'lithium'      => 'LithiumInstaller',
        'magento'      => 'MagentoInstaller',
        'mako'         => 'MakoInstaller',
        'mautic'       => 'MauticInstaller',
        'mediawiki'    => 'MediaWikiInstaller',
        'microweber'   => 'MicroweberInstaller',
        'modulework'   => 'MODULEWorkInstaller',
        'modxevo'      => 'MODXEvoInstaller',
        'moodle'       => 'MoodleInstaller',
        'october'      => 'OctoberInstaller',
        'oxid'         => 'OxidInstaller',
        'phpbb'        => 'PhpBBInstaller',
        'pimcore'      => 'PimcoreInstaller',
        'piwik'        => 'PiwikInstaller',
        'plentymarkets'=> 'PlentymarketsInstaller',
        'ppi'          => 'PPIInstaller',
        'puppet'       => 'PuppetInstaller',
        'radphp'       => 'RadPHPInstaller',
        'phifty'       => 'PhiftyInstaller',
        'redaxo'       => 'RedaxoInstaller',
        'reindex'      => 'ReIndexInstaller',
        'roundcube'    => 'RoundcubeInstaller',
        'shopware'     => 'ShopwareInstaller',
        'silverstripe' => 'SilverStripeInstaller',
        'smf'          => 'SMFInstaller',
        'symfony1'     => 'Symfony1Installer',
        'thelia'       => 'TheliaInstaller',
        'tusk'         => 'TuskInstaller',
        'typo3-cms'    => 'TYPO3CmsInstaller',
        'typo3-flow'   => 'TYPO3FlowInstaller',
        'vanilla'      => 'VanillaInstaller',
        'whmcs'        => 'WHMCSInstaller',
        'wolfcms'      => 'WolfCMSInstaller',
        'wordpress'    => 'WordPressInstaller',
        'yawik'        => 'YawikInstaller',
        'zend'         => 'ZendInstaller',
        'zikula'       => 'ZikulaInstaller',
        'prestashop'   => 'PrestashopInstaller'
    );

    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package)
    {
        $type = $package->getType();
        $frameworkType = $this->findFrameworkType($type);

        if ($frameworkType === false) {
            throw new \InvalidArgumentException(
                'Sorry the package type of this package is not yet supported.'
            );
        }

        $class = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType];
        $installer = new $class($package, $this->composer, $this->getIO());

        return $installer->getInstallPath($package, $frameworkType);
    }

    public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
    {
        if (!$repo->hasPackage($package)) {
            throw new \InvalidArgumentException('Package is not installed: '.$package);
        }

        $repo->removePackage($package);

        $installPath = $this->getInstallPath($package);
        $this->io->write(sprintf('Deleting %s - %s', $installPath, $this->filesystem->removeDirectory($installPath) ? '<comment>deleted</comment>' : '<error>not deleted</error>'));
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType)
    {
        $frameworkType = $this->findFrameworkType($packageType);

        if ($frameworkType === false) {
            return false;
        }

        $locationPattern = $this->getLocationPattern($frameworkType);

        return preg_match('#' . $frameworkType . '-' . $locationPattern . '#', $packageType, $matches) === 1;
    }

    /**
     * Finds a supported framework type if it exists and returns it
     *
     * @param  string $type
     * @return string
     */
    protected function findFrameworkType($type)
    {
        $frameworkType = false;

        krsort($this->supportedTypes);

        foreach ($this->supportedTypes as $key => $val) {
            if ($key === substr($type, 0, strlen($key))) {
                $frameworkType = substr($type, 0, strlen($key));
                break;
            }
        }

        return $frameworkType;
    }

    /**
     * Get the second part of the regular expression to check for support of a
     * package type
     *
     * @param  string $frameworkType
     * @return string
     */
    protected function getLocationPattern($frameworkType)
    {
        $pattern = false;
        if (!empty($this->supportedTypes[$frameworkType])) {
            $frameworkClass = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType];
            /** @var BaseInstaller $framework */
            $framework = new $frameworkClass(null, $this->composer, $this->getIO());
            $locations = array_keys($framework->getLocations());
            $pattern = $locations ? '(' . implode('|', $locations) . ')' : false;
        }

        return $pattern ? : '(\w+)';
    }

    /**
     * Get I/O object
     *
     * @return IOInterface
     */
    private function getIO()
    {
        return $this->io;
    }
}


text:
package com.ilivoo.xag.model.core.consume.model;

import com.ilivoo.xag.model.core.consume.consume.CurrencyConsume;

public enum ConsumeType {
	NULL_CONSUME() {
		@SuppressWarnings("unchecked")
		@Override
		public NullConsume create() {
			return new NullConsume();
		}
	},
	CURRENCY() {
		@SuppressWarnings("unchecked")
		@Override
		public CurrencyConsume create() {
			return new CurrencyConsume();
		}
	};

	public abstract <T extends AbstractConsume<?>> T create();
}


text:
package pl.touk.nussknacker.engine.graph

import io.circe.generic.JsonCodec
import pl.touk.nussknacker.engine.graph.expression.Expression

object evaluatedparam {

  object Parameter {
    //FIXME: after adding @JsonCodec
    //one can no longer write: Parameter.tupled, Parameter.apply is no longer recognized,
    // so lest we add this method we'd have to write (Parameter.apply _).tupled
    val tupled: ((String, Expression)) => Parameter = (Parameter.apply _).tupled
  }

  @JsonCodec case class Parameter(name: String, expression: Expression)

  @JsonCodec case class BranchParameters(branchId: String, parameters: List[Parameter])

}


text:
package com.mentatlabs.nsa
package scalac
package options

/* -Ypos-debug
 * ===========
 *   2.10.0 - 2.12.0: Trace position validation.
 */
case object ScalacYPosDebug
    extends ScalacOptionBoolean("-Ypos-debug", ScalacVersions.`2.10.0`)


text:
package com.twelvemonkeys.contrib.exif;

import com.twelvemonkeys.contrib.tiff.TIFFUtilities;

/**
 * Orientation.
 *
 * @author Harald Kuhr
 * @version : Orientation.java,v 1.0 10/07/2020 harald.kuhr
 */
public enum Orientation {
    Normal(TIFFUtilities.TIFFBaseline.ORIENTATION_TOPLEFT),
    FlipH(TIFFUtilities.TIFFExtension.ORIENTATION_TOPRIGHT),
    Rotate180(TIFFUtilities.TIFFExtension.ORIENTATION_BOTRIGHT),
    FlipV(TIFFUtilities.TIFFExtension.ORIENTATION_BOTLEFT),
    FlipVRotate90(TIFFUtilities.TIFFExtension.ORIENTATION_LEFTTOP),
    Rotate270(TIFFUtilities.TIFFExtension.ORIENTATION_RIGHTTOP),
    FlipHRotate90(TIFFUtilities.TIFFExtension.ORIENTATION_RIGHTBOT),
    Rotate90(TIFFUtilities.TIFFExtension.ORIENTATION_LEFTBOT);

                             // name as defined in javax.imageio metadata
    private final int value; // value as defined in TIFF spec

    Orientation(int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Orientation fromMetadataOrientation(final String orientationName) {
        if (orientationName != null) {
            try {
                return valueOf(orientationName);
            }
            catch (IllegalArgumentException e) {
                // Not found, try ignore case match, as some metadata implementations are known to return "normal" etc.
                String lowerCaseName = orientationName.toLowerCase();

                for (Orientation orientation : values()) {
                    if (orientation.name().toLowerCase().equals(lowerCaseName)) {
                        return orientation;
                    }
                }
            }
        }

        // Metadata does not have other orientations, default to Normal
        return Normal;
    }

    public static Orientation fromTIFFOrientation(final int tiffOrientation) {
        for (Orientation orientation : values()) {
            if (orientation.value() == tiffOrientation) {
                return orientation;
            }
        }

        // No other TIFF orientations possible, default to Normal
        return Normal;
    }
}


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

namespace Twitch.Net.Model
{
    [JsonObject("videos")]
    public class Video : TwitchBase
    {
        [JsonProperty("_id")]
        public string Id { get; set; }
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("recorded_at")]
        public DateTime RecordedAt { get; set; }
        [JsonProperty("_links")]
        public Dictionary<string, object> Links { get; set; }
        [JsonProperty("embed")]
        public string Embed { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
        [JsonProperty("views")]
        public long Views { get; set; }
        [JsonProperty("preview")]
        public string Preview { get; set; }
        [JsonProperty("length")]
        public long Length { get; set; }
        [JsonProperty("game")]
        public string Game { get; set; }
        [JsonProperty("description")]
        public string Description { get; set; }
    }
}


text:
<?php

class SomeClass
{
    function function1(int $value): int
    {
    }
}


text:
package com.gfirem.elrosacruz;

import android.app.Application;
import android.util.Log;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

/**
 * Created by GFireM on 10/14/2015.
 */
@ReportsCrashes(
        formKey = "b856e786e56842b1b8bc0395923d3377",
        formUri = "https://collector.tracepot.com/2c4882bc")
public class ApplicationController extends Application {

    private static ApplicationController fInstance;
    private Tracker mTracker;

    public static ApplicationController getInstance() {
        if (fInstance == null) {
            fInstance = new ApplicationController();
        }
        return fInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            fInstance = this;
            CalligraphyConfig.initDefault(new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Nexa-Light.ttf")
                    .setFontAttrId(R.attr.fontPath).build());
            ACRA.init(this);
        } catch (Exception anEx) {
            Log.d("AppController" + "onCreate", anEx.toString());
        }
    }

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     *
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker("UA-56060946-4");
            mTracker.enableExceptionReporting(true);
            mTracker.enableAdvertisingIdCollection(false);
            mTracker.enableAutoActivityTracking(true);
        }
        return mTracker;
    }
}


text:
var crypto = require('crypto');

// local
var base58 = require('./base58');

var address_types = {
    prod: '00',
    testnet: '6f'
};

var p2sh_types = {
    prod: '05',
    testnet: 'c4'
};

/// return address type if valid base58 address, otherwise null
function get_address_type(address) {
    var decoded_hex;
    try {
        decoded_hex = base58.decode(address);
    } catch (e) {
        // if decoding fails, assume invalid address
        return null;
    }

    // make a usable buffer from the decoded data
    var decoded = new Buffer(decoded_hex, 'hex');

    // should be 25 bytes per btc address spec
    if (decoded.length != 25) {
        return null;
    }

    var length = decoded.length;
    var cksum = decoded.slice(length - 4, length).toString('binary');
    var body = decoded.slice(0, length - 4);

    var good_cksum = sha256_digest(sha256_digest(body)).toString('binary').substr(0,4);
    return (cksum === good_cksum ? decoded_hex.slice(0, 2) : null);
}

module.exports.get_address_type = get_address_type;

/// check if a wallet address is valid
/// if address_type is supplied
/// also checks that the address matches that expected version
/// return {boolean} true if valid, false otherwise
function validate(address, address_type) {
    // default is to check that address is regular production address
    address_type = address_type || 'prod';

    var type = get_address_type(address);
    if (type === null) {
        return false;
    }

    if (type !== address_types[address_type] &&
        type !== p2sh_types[address_type]) {
        return false;
    }

    return true;
}

module.exports.validate = validate;

/// private methods

// helper to perform sha256 digest
function sha256_digest(payload) {
    return crypto.createHash('sha256').update(payload).digest();
}


text:
from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl

from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
    Typed,
    Sequence,
    Alias
)
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.descriptors.nested import (
    NestedNoneSet,
    NestedBool,
)

from ._chart import ChartBase
from .axis import NumericAxis
from .series import XYSeries
from .label import DataLabelList

class ScatterChart(ChartBase):

    tagname = "scatterChart"

    scatterStyle = NestedNoneSet(values=(['line', 'lineMarker', 'marker', 'smooth', 'smoothMarker']))
    varyColors = NestedBool(allow_none=True)
    ser = Sequence(expected_type=XYSeries, allow_none=True)
    dLbls = Typed(expected_type=DataLabelList, allow_none=True)
    dataLabels = Alias("dLbls")
    extLst = Typed(expected_type=ExtensionList, allow_none=True)

    x_axis = Typed(expected_type=NumericAxis)
    y_axis = Typed(expected_type=NumericAxis)

    _series_type = "scatter"

    __elements__ = ('scatterStyle', 'varyColors', 'ser', 'dLbls', 'axId',)

    def __init__(self,
                 scatterStyle=None,
                 varyColors=None,
                 ser=(),
                 dLbls=None,
                 axId=None,
                 extLst=None,
                ):
        self.scatterStyle = scatterStyle
        self.varyColors = varyColors
        self.ser = ser
        self.dLbls = dLbls
        self.x_axis = NumericAxis(axId=10, crossAx=20)
        self.y_axis = NumericAxis(axId=20, crossAx=10)
        super(ScatterChart, self).__init__()


text:
.. pyprika documentation master file, created by
   sphinx-quickstart on Sun Dec 29 13:07:53 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to pyprika's documentation!
===================================

Pyprika is a Python library for parsing and managing recipes. Its major
features are:

* Support for recognizing a human-friendly representations of quantities
  and measurements normally seen in cook books.
* Parsing a custom YAML spec for storing recipes on disk.
* A simple command line utility ``kit``, which makes use of the library for
  recipe management.

Contents:

.. toctree::
   :maxdepth: 2

   pyprika
   kit
   yaml-spec

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
@interface CalendarVC : UIViewController

@end


text:
__author__ = 'Luke Merrett'

from database.playtime_operations import PlaytimeOperations

if __name__ == '__main__':
    s = PlaytimeOperations()

    s.get_and_store_playtime()


text:
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file GenerateGeometry.cpp

 HPCG routine
 */

#include <cmath>
#include <cstdlib>
#include <cassert>

#include "ComputeOptimalShapeXYZ.hpp"
#include "GenerateGeometry.hpp"

#ifdef HPCG_DEBUG
#include <fstream>
#include "hpcg.hpp"
using std::endl;

#endif

/*!
  Computes the factorization of the total number of processes into a
  3-dimensional process grid that is as close as possible to a cube. The
  quality of the factorization depends on the prime number structure of the
  total number of processes. It then stores this decompostion together with the
  parallel parameters of the run in the geometry data structure.

  @param[in]  size total number of MPI processes
  @param[in]  rank this process' rank among other MPI processes
  @param[in]  numThreads number of OpenMP threads in this process
  @param[in]  pz z-dimension processor ID where second zone of nz values start
  @param[in]  nx, ny, nz number of grid points for each local block in the x, y, and z dimensions, respectively
  @param[out] geom data structure that will store the above parameters and the factoring of total number of processes into three dimensions
*/
void GenerateGeometry(int size, int rank, int numThreads,
  int pz, local_int_t zl, local_int_t zu,
  local_int_t nx, local_int_t ny, local_int_t nz,
  int npx, int npy, int npz,
  Geometry * geom)
{

  if (npx * npy * npz <= 0 || npx * npy * npz > size)
    ComputeOptimalShapeXYZ( size, npx, npy, npz );

  int * partz_ids = 0;
  local_int_t * partz_nz = 0;
  int npartz = 0;
  if (pz==0) { // No variation in nz sizes
    npartz = 1;
    partz_ids = new int[1];
    partz_nz = new local_int_t[1];
    partz_ids[0] = npz;
    partz_nz[0] = nz;
  }
  else {
    npartz = 2;
    partz_ids = new int[2];
    partz_ids[0] = pz;
    partz_ids[1] = npz;
    partz_nz = new local_int_t[2];
    partz_nz[0] = zl;
    partz_nz[1] = zu;
  }
//  partz_ids[npartz-1] = npz; // The last element of this array is always npz
  int ipartz_ids = 0;
  for (int i=0; i< npartz; ++i) {
    assert(ipartz_ids<partz_ids[i]);  // Make sure that z partitioning is consistent with computed npz value
    ipartz_ids = partz_ids[i];
  }

  // Now compute this process's indices in the 3D cube
  int ipz = rank/(npx*npy);
  int ipy = (rank-ipz*npx*npy)/npx;
  int ipx = rank%npx;

#ifdef HPCG_DEBUG
  if (rank==0)
    HPCG_fout   << "size = "<< size << endl
        << "nx  = " << nx << endl
        << "ny  = " << ny << endl
        << "nz  = " << nz << endl
        << "npx = " << npx << endl
        << "npy = " << npy << endl
        << "npz = " << npz << endl;

  HPCG_fout    << "For rank = " << rank << endl
      << "ipx = " << ipx << endl
      << "ipy = " << ipy << endl
      << "ipz = " << ipz << endl;

  assert(size>=npx*npy*npz);
#endif
  geom->size = size;
  geom->rank = rank;
  geom->numThreads = numThreads;
  geom->nx = nx;
  geom->ny = ny;
  geom->nz = nz;
  geom->npx = npx;
  geom->npy = npy;
  geom->npz = npz;
  geom->pz = pz;
  geom->npartz = npartz;
  geom->partz_ids = partz_ids;
  geom->partz_nz = partz_nz;
  geom->ipx = ipx;
  geom->ipy = ipy;
  geom->ipz = ipz;

// These values should be defined to take into account changes in nx, ny, nz values
// due to variable local grid sizes
  global_int_t gnx = npx*nx;
  global_int_t gny = npy*ny;
  //global_int_t gnz = npz*nz;
  // We now permit varying values for nz for any nx-by-ny plane of MPI processes.
  // npartz is the number of different groups of nx-by-ny groups of processes.
  // partz_ids is an array of length npartz where each value indicates the z process of the last process in the ith nx-by-ny group.
  // partz_nz is an array of length npartz containing the value of nz for the ith group.

  //        With no variation, npartz = 1, partz_ids[0] = npz, partz_nz[0] = nz

  global_int_t gnz = 0;
  ipartz_ids = 0;

  for (int i=0; i< npartz; ++i) {
    ipartz_ids = partz_ids[i] - ipartz_ids;
    gnz += partz_nz[i]*ipartz_ids;
  }
  //global_int_t giz0 = ipz*nz;
  global_int_t giz0 = 0;
  ipartz_ids = 0;
  for (int i=0; i< npartz; ++i) {
    int ipart_nz = partz_nz[i];
    if (ipz < partz_ids[i]) {
      giz0 += (ipz-ipartz_ids)*ipart_nz;
      break;
    } else {
      ipartz_ids = partz_ids[i];
      giz0 += ipartz_ids*ipart_nz;
    }

  }
  global_int_t gix0 = ipx*nx;
  global_int_t giy0 = ipy*ny;

// Keep these values for later
  geom->gnx = gnx;
  geom->gny = gny;
  geom->gnz = gnz;
  geom->gix0 = gix0;
  geom->giy0 = giy0;
  geom->giz0 = giz0;

  return;
}


text:
require 'csv_row_model/concerns/dynamic_columns_base'
require 'csv_row_model/internal/import/dynamic_column_attribute'

module CsvRowModel
  module Import
    module DynamicColumns
      extend ActiveSupport::Concern
      include DynamicColumnsBase

      included do
        ensure_define_dynamic_attribute_method
      end

      def dynamic_column_attribute_objects
        @dynamic_column_attribute_objects ||= array_to_block_hash(self.class.dynamic_column_names) do |column_name|
          self.class.dynamic_attribute_class.new(column_name, dynamic_column_source_headers, dynamic_column_source_cells, self)
        end
      end

      # @return [Array] an array of format_dynamic_column_header(...)
      def formatted_dynamic_column_headers
        dynamic_column_attribute_objects.values.first.try(:formatted_headers) || []
      end

      # @return [Array] dynamic_column headers
      def dynamic_column_source_headers
        self.class.dynamic_column_source_headers source_headers
      end

      # @return [Array] dynamic_column row data
      def dynamic_column_source_cells
        self.class.dynamic_column_source_cells source_row
      end

      class_methods do
        def dynamic_column_source_headers(source_headers)
          dynamic_columns? ? source_headers[columns.size..-1] : []
        end

        def dynamic_column_source_cells(source_row)
          dynamic_columns? ? source_row[columns.size..-1] : []
        end

        def dynamic_attribute_class
          DynamicColumnAttribute
        end
      end
    end
  end
end


text:
module Helper (
  module Test.Hspec
, logSinkSpy
) where

import           Test.Hspec
import           Data.IORef

import           System.Logging.Facade.Types
import           System.Logging.Facade.Sink

logSinkSpy :: IO (IO [LogRecord], LogSink)
logSinkSpy = do
  ref <- newIORef []
  let spy :: LogSink
      spy record = modifyIORef ref (record {logRecordLocation = Nothing} :)
  return (readIORef ref, spy)


text:
using NUnit.Framework.Constraints;
using System.Collections.Generic;
using System.Linq;
using YetiVSI.DebugEngine.Variables;

namespace YetiVSI.Test.TestSupport.NUnitExtensions
{
    /// <summary>
    /// Checks whether an IVariableInformation instance has exactly |childValues.Length| children
    /// with values given by |childValues| and in that order. Throws if an instance is passed that
    /// is null or not an IVariableInformation.
    /// </summary>
    public class HasChildrenWithValuesConstraint : Constraint
    {
        public string[] ChildValues { get; }

        public HasChildrenWithValuesConstraint(params string[] childValues) : base(childValues)
        {
            ChildValues = childValues;
        }

        public override ConstraintResult ApplyTo<TActual>(TActual actual)
        {
            var varInfo = actual as IVariableInformation;
            // Ignore "Synchronously waiting on tasks or awaiters may cause deadlocks. Use await or
            // JoinableTaskFactory.Run instead." since there's no async alternative. Revisit if this
            // becomes a problem.
#pragma warning disable VSTHRD002
            return new EqualConstraint(ChildValues).AsCollection.ApplyTo(
                varInfo.GetAllChildrenAsync().Result.Select(child => child.ValueAsync().Result)
                    .ToArray());
#pragma warning restore VSTHRD002
        }
    }

    /// <summary>
    /// Checks whether an IVariableInformation instance has at least one child. Throws if an
    /// instance is passed that is null or not an IVariableInformation.
    /// </summary>
    public class HasChildrenConstraint : Constraint
    {
        public override ConstraintResult ApplyTo<TActual>(TActual actual)
        {
            var varInfo = actual as IVariableInformation;
            // Ignore "Synchronously waiting on tasks or awaiters may cause deadlocks. Use await or
            // JoinableTaskFactory.Run instead." since there's no async alternative. Revisit if this
            // becomes a problem.
#pragma warning disable VSTHRD002
            return new NotConstraint(new EqualConstraint(0)).ApplyTo(
                varInfo.GetAllChildrenAsync().Result.Count);
#pragma warning restore VSTHRD002
        }
    }

    /// <summary>
    /// Allows you to write Assert.That(varInfo, Does.HaveChildWithValue("someValue"));
    /// </summary>
    public class Does : NUnit.Framework.Does
    {
        public static HasChildrenConstraint HaveChildren() => new HasChildrenConstraint();

        public static HasChildrenWithValuesConstraint HaveChildWithValue(string childValue) =>
            new HasChildrenWithValuesConstraint(childValue);

        public static HasChildrenWithValuesConstraint HaveChildrenWithValues(
            params string[] childValues) =>
            new HasChildrenWithValuesConstraint(childValues);
    }

    /// <summary>
    /// Allows you to write Assert.That(varInfo, Does.Not.HaveChildren()); etc.
    /// </summary>
    public static class CustomConstraintExtensions
    {
        public static HasChildrenConstraint HaveChildren(this ConstraintExpression expression)
        {
            var constraint = new HasChildrenConstraint();
            expression.Append(constraint);
            return constraint;
        }

        public static HasChildrenWithValuesConstraint HaveChildWithValue(
            this ConstraintExpression expression, string childValue)
        {
            var constraint = new HasChildrenWithValuesConstraint(childValue);
            expression.Append(constraint);
            return constraint;
        }

        public static HasChildrenWithValuesConstraint HaveChildrenWithValues(
            this ConstraintExpression expression, params string[] childValues)
        {
            var constraint = new HasChildrenWithValuesConstraint(childValues);
            expression.Append(constraint);
            return constraint;
        }
    }
}


text:
<?php

namespace Inventory\Model;

use Inventory\Model\Validate\Hostnames;
use Inventory\Model\Validate\Model;
use Inventory\Model\Validate\SKU;
use Inventory\Model\Validate\UUIC;
use Inventory\Model\Validate\Serial;
use Inventory\Model\Validate\Date;
use Inventory\Model\Validate\Paragraph;
use Inventory\Model\Sanitize\StripTags;

class Monitor
{
    public $id, $hostname, $model, $sku, $serial, $notes, $data;
    protected $errors;

	function __construct($data)
	{
		$this->exchangeArray(array_change_key_case((array)$data, CASE_LOWER));
	}

    public function exchangeArray($data)
    {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->hostname = (isset($data['hostname'])) ? $data['hostname'] : null;
        $this->model = (isset($data['model'])) ? $data['model'] : null;
        $this->sku = (isset($data['sku'])) ? $data['sku'] : null;
        $this->serial = (isset($data['serial'])) ? $data['serial'] : null;
        $this->eowd = (isset($data['eowd'])) ? $data['eowd'] : null;
        $this->opd = (isset($data['opd'])) ? $data['opd'] : null;
        $this->description = (isset($data['description'])) ? $data['description'] : null;
		$this->notes = (isset($data['notes'])) ? $data['notes'] : null;
    }

	public function isValid()
    {
    $ret = true;

    if (!empty($this->hostname)){
  		if (!Hostnames::isValid($this->hostname)) {
        $this->errors['hostname'] = 'Hostname value is invalid';
			$ret = false;
      }
    }

    if (!empty($this->model)){
  		if (!Model::isValid($this->model)) {
        $this->errors['model'] = 'Model value is invalid';
			$ret = false;
      }
    }

		if (!SKU::isValid($this->sku)) {
            $this->errors['sku'] = 'SKU value is invalid';
			$ret = false;
		}

		if (!Serial::isValid($this->serial)) {
            $this->errors['serial'] = 'Serial value is invalid';
			$ret = false;
		}

    if (!empty($this->eowd)) {
      if (!Date::isValid($this->eowd)) {
            $this->errors['eowd'] = 'EOWD value is invalid';
			$ret = false;
      }
    }

		if (!empty($this->opd)) {
      if (!Date::isValid($this->opd)) {
            $this->errors['opd'] = 'OPD value is invalid';
			$ret = false;
      }
    }

		if (!empty($this->description)) {
      if (!empty($this->description)) {
  			if (!Paragraph::isValid($this->description)) {
                $this->errors['description'] = 'Description value is invalid';
			$ret = false;
  			}
  		}
    }

		if (!empty($this->notes)) {
			if (!Paragraph::isValid($this->notes)) {
                $this->errors['notes'] = 'Notes value is invalid';
			$ret = false;
			}
		}

		return $ret;
    }

    public function getErrors()
    {
        return $this->errors;
    }

	public function doClean($str)
	{
		$clean = new StripTags;
		return $clean->doClean($str);
	}
}


text:
package hr.fer.zemris.java.tecaj.hw4.problem1b;

public class SquareValue implements IntegerStorageObserver {

	/**
	 * Whenever the observed IntegerStorage changes, this Observer prints
	 * the square of the new value.
	 */
	@Override
	public void valueChanged(IntegerStorageChange istoragech) {
		int val = istoragech.getCurrentVal();
		System.out.println("Provided new value: "+val+", square is "+val*val);
	}

}


text:
import angular from 'angular';
import menu from './menu.component';

angular.module('menu', [])
    .component('menu', menu);


text:
  // Uses AXEL's node module
  var ctx = require('../index.js');

  // Clear the terminal/screen/console
  ctx.clear();

  // Background to red, foreground to white
  ctx.bg(255,0,0);
  ctx.fg(255,255,255);
  ctx.text(5,1," WHITE ON RED! ");

// Background to yellow, foreground to black
  ctx.bg(255,255,0);
  ctx.fg(0,0,0);
  ctx.text(10,2," BLACK ON YELLOW! ");

  // Position the cursor at the end of the console
  // so as not to draw over the bottom of the circle
  ctx.cursor.restore();


text:
using System;
using AutoMapper.UnitTests;
using Should;
using Xunit;

namespace AutoMapper.Tests
{
	public class EnumMappingFixture
	{
        public EnumMappingFixture()
        {
            Cleanup();
        }

        public void Cleanup()
		{

		}

		[Fact]
		public void ShouldMapSharedEnum()
		{
		    var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());

			var order = new Order
				{
					Status = Status.InProgress
				};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<Order, OrderDto>(order);

			dto.Status.ShouldEqual(Status.InProgress);
		}

		[Fact]
		public void ShouldMapToUnderlyingType() {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoInt>());

			var order = new Order {
				Status = Status.InProgress
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<Order, OrderDtoInt>(order);

			dto.Status.ShouldEqual(1);
		}

		[Fact]
		public void ShouldMapToStringType() {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoString>());

			var order = new Order {
				Status = Status.InProgress
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<Order, OrderDtoString>(order);

			dto.Status.ShouldEqual("InProgress");
		}

		[Fact]
		public void ShouldMapFromUnderlyingType() {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoInt, Order>());

			var order = new OrderDtoInt {
				Status = 1
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<OrderDtoInt, Order>(order);

			dto.Status.ShouldEqual(Status.InProgress);
		}

		[Fact]
		public void ShouldMapFromStringType() {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoString, Order>());

			var order = new OrderDtoString {
				Status = "InProgress"
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<OrderDtoString, Order>(order);

			dto.Status.ShouldEqual(Status.InProgress);
		}

		[Fact]
		public void ShouldMapEnumByMatchingNames()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());

			var order = new Order
				{
					Status = Status.InProgress
				};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);

			dto.Status.ShouldEqual(StatusForDto.InProgress);
		}

		[Fact]
		public void ShouldMapEnumByMatchingValues()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());

			var order = new Order
				{
					Status = Status.InProgress
				};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);

			dto.Status.ShouldEqual(StatusForDto.InProgress);
		}

		[Fact]
		public void ShouldMapSharedNullableEnum()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithNullableStatus>());

			var order = new OrderWithNullableStatus {
				Status = Status.InProgress
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithNullableStatus>(order);

			dto.Status.ShouldEqual(Status.InProgress);
		}

		[Fact]
		public void ShouldMapNullableEnumByMatchingValues()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());

			var order = new OrderWithNullableStatus {
				Status = Status.InProgress
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);

			dto.Status.ShouldEqual(StatusForDto.InProgress);
		}

		[Fact]
		public void ShouldMapNullableEnumToNullWhenSourceEnumIsNullAndDestinationWasNotNull()
		{
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AllowNullDestinationValues = true;
                cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
            });

			var dto = new OrderDtoWithOwnNullableStatus()
			{
				Status = StatusForDto.Complete
			};

			var order = new OrderWithNullableStatus
			{
				Status = null
			};

		    var mapper = config.CreateMapper();
		    mapper.Map(order, dto);

			dto.Status.ShouldBeNull();
		}

		[Fact]
		public void ShouldMapNullableEnumToNullWhenSourceEnumIsNull()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());

			var order = new OrderWithNullableStatus {
				Status = null
			};

		    var mapper = config.CreateMapper();
		    var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);

			dto.Status.ShouldBeNull();
		}

		[Fact]
		public void ShouldMapEnumUsingCustomResolver()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
				.ForMember(dto => dto.Status, options => options.ResolveUsing<DtoStatusValueResolver>()));

			var order = new Order
				{
					Status = Status.InProgress
				};

		    var mapper = config.CreateMapper();
		    var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);

			mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
		}

		[Fact]
		public void ShouldMapEnumUsingGenericEnumResolver()
		{
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
				.ForMember(dto => dto.Status, options => options.ResolveUsing<EnumValueResolver<Status, StatusForDto>, Status>(m => m.Status)));

			var order = new Order
				{
					Status = Status.InProgress
				};

		    var mapper = config.CreateMapper();
		    var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);

			mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
		}

        [Fact]
        public void ShouldMapEnumWithInvalidValue()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());

            var order = new Order
            {
                Status = 0
            };

            var mapper = config.CreateMapper();
            var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);

            var expected = (StatusForDto)0;

            dto.Status.ShouldEqual(expected);
        }

		public enum Status
		{
			InProgress = 1,
			Complete = 2
		}

		public enum StatusForDto
		{
			InProgress = 1,
			Complete = 2
		}

		public class Order
		{
			public Status Status { get; set; }
		}

		public class OrderDto
		{
			public Status Status { get; set; }
		}

		public class OrderDtoInt {
			public int Status { get; set; }
		}

		public class OrderDtoString {
			public string Status { get; set; }
		}

		public class OrderDtoWithOwnStatus
		{
			public StatusForDto Status { get; set; }
		}

		public class OrderWithNullableStatus
		{
			public Status? Status { get; set; }
		}

		public class OrderDtoWithNullableStatus
		{
			public Status? Status { get; set; }
		}

		public class OrderDtoWithOwnNullableStatus
		{
			public StatusForDto? Status { get; set; }
		}

		public class DtoStatusValueResolver : IValueResolver<Order, StatusForDto>
		{
			public StatusForDto Resolve(Order source, ResolutionContext context)
			{
				return context.Mapper.Map<StatusForDto>(source.Status);
			}
		}

		public class EnumValueResolver<TInputEnum, TOutputEnum> : IValueResolver<TInputEnum, TOutputEnum>
		{
			public TOutputEnum Resolve(TInputEnum source, ResolutionContext context)
			{
				return ((TOutputEnum)Enum.Parse(typeof(TOutputEnum), Enum.GetName(typeof(TInputEnum), source), false));
			}
		}
	}
	public class When_mapping_from_a_null_object_with_an_enum : AutoMapperSpecBase
	{
	    protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
	    {
	        cfg.AllowNullDestinationValues = false;
	        cfg.CreateMap<SourceClass, DestinationClass>();
	    });

		public enum EnumValues
		{
			One, Two, Three
		}

		public class DestinationClass
		{
			public EnumValues Values { get; set; }
		}

		public class SourceClass
		{
			public EnumValues Values { get; set; }
		}

		[Fact]
		public void Should_set_the_target_enum_to_the_default_value()
		{
			SourceClass sourceClass = null;
			var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
			dest.Values.ShouldEqual(default(EnumValues));
		}
	}
	public class When_mapping_from_a_null_object_with_a_nullable_enum : AutoMapperSpecBase
	{
	    protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
	    {
	        cfg.AllowNullDestinationValues = false;
	        cfg.CreateMap<SourceClass, DestinationClass>();
	    });

		public enum EnumValues
		{
			One, Two, Three
		}

		public class DestinationClass
		{
			public EnumValues Values { get; set; }
		}

		public class SourceClass
		{
			public EnumValues? Values { get; set; }
		}

		[Fact]
		public void Should_set_the_target_enum_to_the_default_value()
		{
			SourceClass sourceClass = null;
			var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
			dest.Values.ShouldEqual(default(EnumValues));
		}
	}
    public class When_mapping_from_a_null_object_with_a_nullable_enum_as_string : AutoMapperSpecBase
    {
        protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<SourceClass, DestinationClass>();
        });

        public enum EnumValues
        {
            One, Two, Three
        }

        public class DestinationClass
        {
            public EnumValues Values1 { get; set; }
            public EnumValues? Values2 { get; set; }
            public EnumValues Values3 { get; set; }
        }

        public class SourceClass
        {
            public string Values1 { get; set; }
            public string Values2 { get; set; }
            public string Values3 { get; set; }
        }

        [Fact]
        public void Should_set_the_target_enum_to_the_default_value()
        {
            var sourceClass = new SourceClass();
            var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
            dest.Values1.ShouldEqual(default(EnumValues));
        }

        [Fact]
        public void Should_set_the_target_nullable_to_null()
        {
            var sourceClass = new SourceClass();
            var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
            dest.Values2.ShouldBeNull();
        }

        [Fact]
        public void Should_set_the_target_empty_to_null()
        {
            var sourceClass = new SourceClass
            {
                Values3 = ""
            };
            var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
            dest.Values3.ShouldEqual(default(EnumValues));
        }
    }

	public class When_mapping_a_flags_enum : NonValidatingSpecBase
    {
		private DestinationFlags _result;

		[Flags]
		private enum SourceFlags
		{
			None = 0,
			One = 1,
			Two = 2,
			Four = 4,
			Eight = 8
		}

		[Flags]
		private enum DestinationFlags
		{
			None = 0,
			One = 1,
			Two = 2,
			Four = 4,
			Eight = 8
		}

        protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });

        protected override void Because_of()
		{
			_result = Mapper.Map<SourceFlags, DestinationFlags>(SourceFlags.One | SourceFlags.Four | SourceFlags.Eight);
		}

		[Fact]
		public void Should_include_all_source_enum_values()
		{
			_result.ShouldEqual(DestinationFlags.One | DestinationFlags.Four | DestinationFlags.Eight);
		}
	}

}


text:
window.modelHelper = (function() {
  function toTypeClass(type) {
    return type.substring(0, 1).toUpperCase() + type.substring(1);
  };

  return {
    fake: function(type) {
      var model = jasmine.createSpyObj(type, ['get']);
      var attributes = this.attributesFor(type);
      model.get.and.callFake(function(property) {
        return attributes[property];
      });
      return model;
    },
    attributesFor: function(type) {
      return PhotoAlbums[toTypeClass(type)].FIXTURES[0];
    }
  };
})();


text:
using System;
using System.IO;
using System.Net.Mail;
using System.Threading.Tasks;
using SimpleSmtp.Core.Extensions;
using SimpleSmtp.Logging;

namespace SimpleSmtp.Core.Server
{
	internal class SmtpClient : Disposable, ISmtpClient
	{
		private enum ClientResult
		{
			Success,
			RejectedByRemoteServer,
			ServiceNotAvailable,
			FailedToConnect
		}

		private readonly ILog _log;
		private readonly ITcpFactory _tcpFactory;
		private readonly Config.IConfigService _config;
		private readonly Services.IClientManager _clientManager;

		private ISmtpStream _stream;
		private Facades.ITcpClientFacade _client;
		private bool _canPipeline;
		private bool _isUtf8;
		private string _hostname;

		public const int SmtpPort = 25;

		public int SentCount { get; private set; }

		public Dns.MxRecord MxRecord { get; set; }

		public SmtpClient(ILog log, ITcpFactory factory, Config.IConfigService config, Services.IClientManager clientManager)
		{
			Guard.NotNull(log, nameof(log));
			Guard.NotNull(config, nameof(config));
			Guard.NotNull(factory, nameof(factory));
			Guard.NotNull(clientManager, nameof(clientManager));

			_log = log;
			_tcpFactory = factory;
			_config = config;
			_clientManager = clientManager;
		}

		public async Task<SendResult> SendAsync(Types.MailMessage message)
		{
			Guard.NotNull(message, nameof(message));

			if (!_client.IsConnected)
			{
				if ((await ConnectAsync()) != ClientResult.Success)
					return SendResult.Unknown;
			}
			else if (await ResetAsync() != ClientResult.Success)
				return SendResult.Unknown;

			if (await MailFromAsync(message.From) != ClientResult.Success)
				return SendResult.Unknown;

			if (await RcptToAsync(message.To) != ClientResult.Success)
				return SendResult.Unknown;

			if (await DataAsync(message.Message) != ClientResult.Success)
				return SendResult.Unknown;

			if (SentCount >= _clientManager.MaxConnectionMessages)
			{
				await QuitAsync();
				SentCount = 0;
			}

			return SendResult.Unknown;
		}

		private async Task<ClientResult> ConnectAsync()
		{
			if (_clientManager.IsServiceUnavailable(MxRecord))
				return ClientResult.ServiceNotAvailable;

			_client = _tcpFactory.NewClient();
			_client.SendTimeout = _config.SendTimeout * 1000;
			_client.ReceiveTimeout = _config.ReceiveTimeout * 1000;
			_client.KeepAlive = true;

			try
			{
				await _client.ConnectAsync(MxRecord.Host, SmtpPort);
			}
			catch (Exception ex)
			{
				_log.FatalException("Failed to connect to host '{0}'", ex, MxRecord.Host);
				return ClientResult.FailedToConnect;
			}

			_stream = _clientManager.GetStream(_client);

			var response = await _stream.ReadAllLinesAsync();

			if (response.StartsWith("2"))
				return await EhloAsync();

			_client.Close();

			if (response.StartsWith("421"))
				return ClientResult.ServiceNotAvailable;

			return ClientResult.FailedToConnect;
		}

		private async Task<ClientResult> EhloAsync()
		{
			await _stream.WriteLineAsync("EHLO " + _hostname);

			var response = await _stream.ReadAllLinesAsync();
			if (response.StartsWith("421"))
				return ClientResult.ServiceNotAvailable;

			try
			{
				if (!response.StartsWith("2"))
					return await HeloAsync();

				_isUtf8 = response.IndexOf("8BITMIME", StringComparison.OrdinalIgnoreCase) > -1;
				_canPipeline = response.IndexOf("PIPELINING", StringComparison.OrdinalIgnoreCase) > -1;
				return ClientResult.Success;
			}
			catch (IOException)
			{
				return ClientResult.ServiceNotAvailable;
			}
		}

		private async Task<ClientResult> HeloAsync()
		{
			await _stream.WriteLineAsync("HELO " + _hostname);

			var response = await _stream.ReadAllLinesAsync();
			if (response.IsSuccess())
				return ClientResult.Success;

			_client.Close();
			return ClientResult.ServiceNotAvailable;
		}

		private async Task<ClientResult> MailFromAsync(MailAddress mailFrom)
		{
			var msg = "MAIL FROM: <";
			if (mailFrom != null)
				msg += mailFrom.ToString();
			msg += ">";
			if (_isUtf8)
				msg += " BODY=8BITMIME";

			await _stream.WriteLineAsync(msg);

			if (!_canPipeline && !(await _stream.ReadAllLinesAsync()).IsSuccess())
				return ClientResult.RejectedByRemoteServer;

			return ClientResult.Success;
		}

		private async Task<ClientResult> RcptToAsync(MailAddress mailTo)
		{
			await _stream.WriteLineAsync($"RCPT TO: <{mailTo.Address}>");

			if (!_canPipeline && !(await _stream.ReadAllLinesAsync()).IsSuccess())
				return ClientResult.RejectedByRemoteServer;

			return ClientResult.Success;
		}

		private async Task<ClientResult> DataAsync(string msg)
		{
			await _stream.WriteLineAsync("DATA");

			var response = await _stream.ReadAllLinesAsync();
			if (_canPipeline)
			{
				if (!response.IsSuccess())
					return ClientResult.RejectedByRemoteServer;

				response = await _stream.ReadAllLinesAsync();
				if (!response.IsSuccess())
					return ClientResult.RejectedByRemoteServer;

				response = await _stream.ReadAllLinesAsync();
			}

			if (!response.StartsWith("354"))
				return ClientResult.RejectedByRemoteServer;

			await _stream.WriteAsync(msg, _isUtf8 ? TransportMime.Utf8 : TransportMime.Ascii7Bit);
			await _stream.WriteAsync("/r/n./r/n");

			response = await _stream.ReadAllLinesAsync();
			if (!response.IsSuccess())
				return ClientResult.RejectedByRemoteServer;

			SentCount++;
			return ClientResult.Success;
		}

		private async Task QuitAsync()
		{
			if (!_client.IsConnected)
				return;

			try
			{
				await _stream.WriteLineAsync("QUIT");

				_stream.Dispose();
			}
			catch (Exception)
			{
				throw;
			}
		}

		private async Task<ClientResult> ResetAsync()
		{
			await _stream.WriteLineAsync("RSET");

			var response = await _stream.ReadLineAsync();
			switch (response[0])
			{
				case '2':
					return ClientResult.Success;

				case '4':
				case '5':
				default:
					return ClientResult.RejectedByRemoteServer;
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (IsDisposed)
				return;

			if (disposing)
				QuitAsync().GetAwaiter().GetResult();

			_client.Close();
			IsDisposed = true;
		}
	}
}


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

    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>hospital</title>
    <link rel="stylesheet" href="../css/frame/960.css" type="text/css"
          media="screen" charset="utf-8"/>
    <link rel="stylesheet" href="../css/frame/template.css" type="text/css"
          media="screen" charset="utf-8"/>
    <link rel="stylesheet" href="../css/frame/colour.css" type="text/css"
          media="screen" charset="utf-8"/>

    <link rel="stylesheet" href="../css/pagination.css" type="text/css"
          media="screen" charset="utf-8"/>

序列号管理系统

查询序列号

医院信息

生成序列号

所有医院信息

                医院编号
                医院名称
                医院电话
                医院地址
                操作

        <lable>您可以:添加医院</lable>

        <lable>或者: 生成序列号</lable>

    Contact Me


text:
package at.ac.tuwien.big.xmlintelledit.intelledit.fixer.impl;

import java.util.Collection;

import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.SetAddAny;

public class SetAddAnyImpl implements SetAddAny {

	private int amount;

	public SetAddAnyImpl(int targetSize) {
		this.amount = targetSize;
	}

	public boolean equals(Object other) {
		return (other instanceof SetAddAny) && equals((SetAddAny)other);
	}

	public boolean equals(SetAddAny other) {
		return amount == other.targetSize();
	}

	@Override
	public int targetSize() {
		return amount;
	}

	@Override
	public boolean isFulfilled(Object obj) {
		return (obj instanceof Collection) && ((Collection)obj).size() >= targetSize();
	}

	public String toString() {
		return "Add until size of " + amount;
	}

}


text:
import cx from 'classnames'
import { getAvailableYears, createDateTime, calculateMonth,
        calculateDay, calculateHours, calculateMinutes } from './date-util'

export default ({ className, errors, onCommit, property, minDate, maxDate, value }) => {
  return (
  <select
    className={cx(className, 'ct-input ct-year')}
    onChange={ e => onCommit(selectYear(e.target.value, value, minDate, maxDate))}
    value={getYear(value)}
    disabled={property && property.disabled}>
      {renderOptions(getAvailableYears(minDate, maxDate))}
  </select>
  )
}

function renderOptions(years) {
  const options = [<option value='' key='placeholder'>Year...</option>]

  return options.concat(years.map(year => <option key={year} value={year}>{year}</option>))
}

function getYear(value) {
  return value ? value.getFullYear() : ''
}

function selectYear(year, date, minDate, maxDate) {
  if (!year) {
    return null
  }

  const selectedMonth = date && date.getMonth()
  const selectedDay = date && date.getDate()
  const selectedHours = date && date.getHours()
  const selectedMinutes = date && date.getMinutes()

  const month = calculateMonth(minDate, maxDate, year, selectedMonth)
  const day = calculateDay(minDate, maxDate, year, month, selectedDay)
  const hours = calculateHours(minDate, maxDate, year, month, day, selectedHours)
  const minutes = calculateMinutes(minDate, maxDate, year, month, day, hours, selectedMinutes)

  if (!date) {
    return new Date(year, month, day, hours, minutes)
  }

  date.setFullYear(year, month, day)
  date.setHours(hours, minutes)

  return date
}


text:
<!--
  ~ Copyright (c) 2015-present, Parse, LLC.
  ~ All rights reserved.
  ~
  ~ This source code is licensed under the BSD-style license found in the
  ~ LICENSE file in the root directory of this source tree. An additional grant
  ~ of patent rights can be found in the PATENTS file in the same directory.
  -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:orderInCategory="100"
          app:showAsAction="never"/>
</menu>
<!-- From: file:/C:/Users/assy/Documents/GitHub/PhotoGramApp/ParseStarterProject/src/main/res/menu/menu_main.xml -->


text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Util;

use Symfony\Component\Finder\Finder;

/**
 * The Compiler class compiles the Symfony CS Fixer utility.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Compiler
{
    public function compile($pharFile = 'php-cs-fixer.phar')
    {
        if (file_exists($pharFile)) {
            unlink($pharFile);
        }

        $phar = new \Phar($pharFile, 0, 'php-cs-fixer.phar');
        $phar->setSignatureAlgorithm(\Phar::SHA1);

        $phar->startBuffering();

        // CLI Component files
        foreach ($this->getFiles() as $file) {
            $path = str_replace(__DIR__.'/', '', $file);
            $phar->addFromString($path, file_get_contents($file));
        }
        $this->addPhpCsFixer($phar);

        // Stubs
        $phar->setStub($this->getStub());

        $phar->stopBuffering();

        // $phar->compressFiles(\Phar::GZ);

        unset($phar);

        chmod($pharFile, 0777);
    }

    /**
     * Remove the shebang from the file before add it to the PHAR file.
     *
     * @param \Phar $phar PHAR instance
     */
    protected function addPhpCsFixer(\Phar $phar)
    {
        $content = file_get_contents(__DIR__ . '/../../../php-cs-fixer');
        $content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);

        $phar->addFromString('php-cs-fixer', $content);
    }

    protected function getStub()
    {
        return "#!/usr/bin/env php\n<?php Phar::mapPhar('php-cs-fixer.phar'); require 'phar://php-cs-fixer.phar/php-cs-fixer'; __HALT_COMPILER();";
    }

    protected function getLicense()
    {
        return '
    /*
     * This file is part of the PHP CS utility.
     *
     * (c) Fabien Potencier <fabien@symfony.com>
     *
     * This source file is subject to the MIT license that is bundled
     * with this source code in the file LICENSE.
     */';
    }

    protected function getFiles()
    {
        $iterator = Finder::create()->files()->exclude('Tests')->name('*.php')->in(array('vendor', 'Symfony'));

        return array_merge(array('LICENSE'), iterator_to_array($iterator));
    }
}


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const ExploreFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function ExploreFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        explore
      </FontIcon>
    );
  }
);


text:
#include "ray_visibility_button.h"

#include <QMenu>
#include <QSignalMapper>
#include <QStyleOptionButton>
#include <QMouseEvent>

namespace Imagine
{

RayVisibilityButton::RayVisibilityButton(QWidget* parent) :	QPushButton(parent)
{
	setFocusPolicy(Qt::NoFocus);

	QMenu* pMenu = new QMenu(this);
	setMenu(pMenu);

	m_pSignalMapper = new QSignalMapper(this);

	m_aOptions.emplace_back("Camera");
	m_aOptions.emplace_back("Shadow");
	m_aOptions.emplace_back("Reflection");
	m_aOptions.emplace_back("Refraction");
	m_aOptions.emplace_back("Diffuse");
	m_aOptions.emplace_back("Glossy");
	m_aOptions.emplace_back("Volume scatter");

	unsigned int menuIndex = 0;
	std::vector<std::string>::const_iterator it = m_aOptions.begin();
	for (; it != m_aOptions.end(); ++it)
	{
		const std::string& optionName = *it;
		QAction* pNewOption = new QAction(optionName.c_str(), this);
		connect(pNewOption, SIGNAL(triggered()), m_pSignalMapper, SLOT(map()));
		m_pSignalMapper->setMapping(pNewOption, menuIndex);

		pNewOption->setCheckable(true);
		m_aActions.emplace_back(pNewOption);

		pMenu->addAction(pNewOption);

		menuIndex ++;
	}

	pMenu->addSeparator();

	//
	QAction* pSelectAllAction = new QAction("All", this);
	connect(pSelectAllAction, SIGNAL(triggered()), this, SLOT(allSelected()));
	pMenu->addAction(pSelectAllAction);

	QAction* pSelectNoneAction = new QAction("None", this);
	connect(pSelectNoneAction, SIGNAL(triggered()), this, SLOT(noneSelected()));
	pMenu->addAction(pSelectNoneAction);

	connect(m_pSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuSelected(int)));
}

void RayVisibilityButton::mousePressEvent(QMouseEvent* event)
{
	QStyleOptionButton style_option;
	style_option.init(this);
	QRect rect = style()->subElementRect(QStyle::SE_PushButtonFocusRect, &style_option, this);
	QRect popupArea(rect);

	if (popupArea.contains(event->pos()))
	{
		QMenu* pMenu = menu();
		QSize menuSize = pMenu->sizeHint();

		QSize buttonSize = geometry().size();

		pMenu->move(mapToGlobal(QPoint(buttonSize.width() - menuSize.width(), buttonSize.height())));
		pMenu->show();
	}
}

unsigned char RayVisibilityButton::getStateBitmask() const
{
	unsigned char finalBitmask = 0;

	for (unsigned int i = 0; i < m_aOptions.size(); i++)
	{
		QAction* pAction = m_aActions[i];

		if (pAction->isChecked())
		{
			unsigned char thisMask = 1 << i;
			finalBitmask |= thisMask;
		}
	}

	return finalBitmask;
}

void RayVisibilityButton::setStateFromBitmask(unsigned char bitmask)
{
	for (unsigned int i = 0; i < m_aOptions.size(); i++)
	{
		QAction* pAction = m_aActions[i];

		unsigned char thisMask = 1 << i;

		if ((bitmask & thisMask))
		{
			pAction->setChecked(true);
		}
		else
		{
			pAction->setChecked(false);
		}
	}

	updateTitleFromOptions();
}

void RayVisibilityButton::menuSelected(int index)
{
	QAction* pSelectedAction = m_aActions[index];

	if (pSelectedAction->isChecked())
	{

	}

	updateTitleFromOptions();
	emit selectionChanged();
}

void RayVisibilityButton::allSelected()
{
	for (unsigned int i = 0; i < m_aOptions.size(); i++)
	{
		QAction* pAction = m_aActions[i];
		pAction->setChecked(true);
	}

	updateTitleFromOptions();
	emit selectionChanged();
}

void RayVisibilityButton::noneSelected()
{
	for (unsigned int i = 0; i < m_aOptions.size(); i++)
	{
		QAction* pAction = m_aActions[i];
		pAction->setChecked(false);
	}

	updateTitleFromOptions();
	emit selectionChanged();
}

void RayVisibilityButton::updateTitleFromOptions()
{
	std::string newTitle;

	// special case all, none, or individual opposite...

	unsigned int actions = m_aActions.size();
	// quick count
	unsigned int itemsChecked = 0;
	for (unsigned int i = 0; i < actions; i++)
	{
		const QAction* pAction = m_aActions[i];
		if (pAction->isChecked())
		{
			itemsChecked ++;
		}
	}

	if (itemsChecked == 0 || itemsChecked == 1 || itemsChecked == (actions - 1) || itemsChecked == (actions - 2) || itemsChecked == actions)
	{
		if (itemsChecked == 0)
		{
			newTitle = "Hidden to: All";
		}
		else if (itemsChecked == actions)
		{
			newTitle = "Visible to: All";
		}
		else if (itemsChecked == 1)
		{
			// visible to only one
			newTitle = "Visible to: " + getSelectedList();
		}
		else
		{
			// all but one or two
			newTitle = "Hidden to: " + getUnselectedList();
		}

		setText(newTitle.c_str());

		return;
	}

	newTitle = getSelectedList();

	setText(newTitle.c_str());
}

std::string RayVisibilityButton::getSelectedList() const
{
	std::string itemsList;

	unsigned int actions = m_aActions.size();
	for (unsigned int i = 0; i < actions; i++)
	{
		const QAction* pAction = m_aActions[i];
		if (pAction->isChecked())
		{
			const std::string& optionName = m_aOptions[i];
			if (!itemsList.empty())
			{
				itemsList += ", ";
			}

			itemsList += optionName;
		}
	}

	return itemsList;
}

std::string RayVisibilityButton::getUnselectedList() const
{
	std::string itemsList;

	unsigned int actions = m_aActions.size();
	for (unsigned int i = 0; i < actions; i++)
	{
		const QAction* pAction = m_aActions[i];
		if (!pAction->isChecked())
		{
			const std::string& optionName = m_aOptions[i];
			if (!itemsList.empty())
			{
				itemsList += ", ";
			}

			itemsList += optionName;
		}
	}

	return itemsList;
}

} // namespace Imagine