text:
<?php
/**
 * BuddyPress Member Notifications Loader.
 *
 * Initializes the Notifications component.
 *
 * @package BuddyPress
 * @subpackage NotificationsLoader
 * @since 1.9.0
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Set up the bp-notifications component.
 *
 * @since 1.9.0
 */
function bp_setup_notifications() {
	buddypress()->notifications = new BP_Notifications_Component();
}
add_action( 'bp_setup_components', 'bp_setup_notifications', 6 );

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<question testSet="unseen-answers" qtype="Q_EXPLAIN_GENERIC" id="DAMAGED_BULB_EXPLAIN_2_Q" module="SwitchesBulbsSeries" stype="QUESTION">
  <questionText>Why does a damaged bulb impact a circuit?</questionText>
  <referenceAnswers>
    <referenceAnswer category="BEST" id="answer64" fileID="DAMAGED_BULB_EXPLAIN_2_Q_ANS1">a damaged bulb creates a gap</referenceAnswer>
    <referenceAnswer category="GOOD" id="answer66" fileID="DAMAGED_BULB_EXPLAIN_2_Q_ANS3">there is a gap in the circuit</referenceAnswer>
    <referenceAnswer category="GOOD" id="answer67" fileID="DAMAGED_BUILD_EXPLAIN_2_Q_ANS4">there is an open path</referenceAnswer>
    <referenceAnswer category="MINIMAL" id="answer68" fileID="DAMAGED_BUILD_EXPLAIN_2_Q_ANS4A">there is no closed path</referenceAnswer>
    <referenceAnswer category="GOOD" id="answer69" fileID="DAMAGED_BUILD_EXPLAIN_2_Q_ANS5">there is an incomplete circuit</referenceAnswer>
  </referenceAnswers>
  <studentAnswers>
    <studentAnswer count="1" answerMatch="answer64" raw_text="if a bulb is damaged the path is opned at that bulb" id="SwitchesBulbsSeries-DAMAGED_BULB_EXPLAIN_2_Q.sbj3-l1.qa98" accuracy="correct">
      <token status="ok" id="tok1724">if</token>
      <token status="ok" id="tok1725">a</token>
      <token status="ok" id="tok1726">bulb</token>
      <token status="ok" id="tok1727">is</token>
      <token status="ok" id="tok1728">damaged</token>
      <token status="ok" id="tok1729">the</token>
      <token status="ok" id="tok1730">path</token>
      <token status="ok" id="tok1731">is</token>
      <token status="ok" id="tok1732" original="opned">opened</token>
      <token status="ok" id="tok1733">at</token>
      <token status="ok" id="tok1734">that</token>
      <token status="ok" id="tok1735">bulb</token>
    </studentAnswer>
    <studentAnswer count="1" answerMatch="answer64" raw_text="because it creates a gap" id="SwitchesBulbsSeries-DAMAGED_BULB_EXPLAIN_2_Q.sbj10-l1.qa112" accuracy="correct">
      <token status="ok" id="tok1860">because</token>
      <token status="ok" id="tok1861">it</token>
      <token status="ok" id="tok1862">creates</token>
      <token status="ok" id="tok1863">a</token>
      <token status="ok" id="tok1864">gap</token>
    </studentAnswer>
    <studentAnswer count="2" answerMatch="answer66" raw_text="there is a gap in the circuit" id="SwitchesBulbsSeries-DAMAGED_BULB_EXPLAIN_2_Q.sbj46-l1.qa105" accuracy="correct">
      <token status="ok" id="tok1725">there</token>
      <token status="ok" id="tok1726">is</token>
      <token status="ok" id="tok1727">a</token>
      <token status="ok" id="tok1728">gap</token>
      <token status="ok" id="tok1729">in</token>
      <token status="ok" id="tok1730">the</token>
      <token status="ok" id="tok1731">circuit</token>
    </studentAnswer>
    <studentAnswer count="1" raw_text="doesnt allow for current to run through the circuit" id="SwitchesBulbsSeries-DAMAGED_BULB_EXPLAIN_2_Q.sbjb24-l1.qa85" accuracy="irrelevant">
      <token status="ok" id="tok1371a">does</token>
      <token status="pennTokenFragment" id="tok1371b" original="nt">n't</token>
      <token status="ok" id="tok1372">allow</token>
      <token status="ok" id="tok1373">for</token>
      <token status="ok" id="tok1374">current</token>
      <token status="ok" id="tok1375">to</token>
      <token status="ok" id="tok1376">run</token>
      <token status="ok" id="tok1377">through</token>
      <token status="ok" id="tok1378">the</token>
      <token status="ok" id="tok1379">circuit</token>
    </studentAnswer>
    <studentAnswer count="1" answerMatch="answer69" raw_text="It destroys the path way" id="SwitchesBulbsSeries-DAMAGED_BULB_EXPLAIN_2_Q.sbjb37-l1.qa79" accuracy="correct">
      <token status="ok" id="tok1319">It</token>
      <token status="ok" id="tok1320">destroys</token>
      <token status="ok" id="tok1321">the</token>
      <token status="ok" id="tok1322+">pathway</token>
    </studentAnswer>
  </studentAnswers>
</question>


text:
using System;
using Xunit;

namespace NString.Tests.StringExtensionsTests
{
    public class JoinTests
    {
        [Fact]
        public void Join_Throws_If_Argument_Is_Null()
        {
            TestHelper.AssertThrowsWhenArgumentNull(() => new[] { "a", "b", "c" }.Join(" "));
        }

        [Fact]
        public void Join_Concatenates_Values_If_Separator_Is_Null()
        {
            var values = new[] { "Hello", "World", "!" };
            string expected = String.Concat(values);
            string actual = values.Join();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void Join_Concatenates_Values_With_Separator()
        {
            var values = new[] { "Hello", "World", "!" };
            string expected = String.Join(" ", values);
            string actual = values.Join(" ");
            Assert.Equal(expected, actual);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Pair</title>
<meta name="date" content="2014-05-23">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

jbc.utils

Class Pair<X,Y>

java.lang.Object

jbc.utils.Pair<X,Y>

public class Pair<X,Y>
extends java.lang.Object

Since:

0.1.0

Author:

Kewei Ma

Field Summary

Fields

Modifier and Type
Field and Description

X
fst

Y
snd

Constructor Summary

Constructors

Constructor and Description

Pair(X fst,
    Y snd)

Method Summary

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

fst

public final X fst

snd

public final Y snd

Constructor Detail

Pair

public Pair(X fst,
    Y snd)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:dither="true">

    <item android:drawable="@drawable/quickaction_slider_btn_on" android:state_checked="true"/>
    <item android:drawable="@drawable/quickaction_slider_btn_on" android:state_window_focused="false"/>
    <item android:drawable="@drawable/quickaction_slider_btn_clicked" android:state_pressed="true"/>
    <item android:drawable="@drawable/quickaction_slider_btn_clicked" android:state_focused="true"/>
    <item android:drawable="@drawable/quickaction_slider_btn_on"/>

</selector>


text:
@interface Buffer : NSObject {
 @public
  uint8_t buf_[1024];
  int bufStart_;
  unsigned int bufLen_;
  int fileLen_;
  int bufPos_;
  NSInputStream *stream_;
  NSFileHandle *file;
}

+ (int)getEOF;
- (id)initWithJavaIoInputStream:(NSInputStream *)s withData:(NSData*)byteData;
- (id)initWithNSString:(NSString *)fileName;
- (id)initWithBuffer:(Buffer *)b;
- (void)dealloc;
- (void)Close;
- (int)Read;
- (int)Peek;
- (NSString *)GetStringWithInt:(int)beg
                       withInt:(int)end;
- (int)getPos;
- (void)setPosWithInt:(int)value;
- (int)ReadNextStreamChunk;
@end


text:
import { FakeTypeA } from './fakeTypeA'
import { FakeTypeB } from './fakeTypeB'

export class FakeTypeC {

  public fackeTypeAIntance: FakeTypeA
  public fackeTypeBIntance: FakeTypeB

  constructor (fakeTypeA: FakeTypeA, fakeTypeB: FakeTypeB) { this.fackeTypeAIntance = fakeTypeA; this.fackeTypeBIntance = fakeTypeB }
}


text:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

namespace think\queue;

use think\App;

class CallQueuedHandler
{
    protected $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function call(Job $job, array $data)
    {
        $command = unserialize($data['command']);

        $this->app->invoke([$command, 'handle']);

        if (!$job->isDeletedOrReleased()) {
            $job->delete();
        }
    }

    public function failed(array $data)
    {
        $command = unserialize($data['command']);

        if (method_exists($command, 'failed')) {
            $command->failed();
        }
    }
}


text:
/*
* Generated by SGWrapperGen - DO NOT EDIT!
*
* SwinGame wrapper for C - Animations
*
* Wrapping sgAnimations.pas
*/

#include "SGSDK.h"
#include "Animations.h"

#include "Types.h"

int32_t animation_count(animation_script script)
{
    return sg_Animations_AnimationCount(script);
}

int32_t animation_current_cell(animation anim)
{
    return sg_Animations_AnimationCurrentCell(anim);
}

vector animation_current_vector(animation anim)
{
    return sg_Animations_AnimationCurrentVector(anim);
}

bool animation_ended(animation anim)
{
    return sg_Animations_AnimationEnded(anim) != 0;
}

bool animation_entered_frame(animation anim)
{
    return sg_Animations_AnimationEnteredFrame(anim) != 0;
}

float animation_frame_time(animation anim)
{
    return sg_Animations_AnimationFrameTime(anim);
}

int32_t animation_index(animation_script temp, const char *name)
{
    return sg_Animations_AnimationIndex(temp, name);
}

void animation_name(animation temp, char *result)
{
    sg_Animations_AnimationName(temp, result);
}

#ifdef __cplusplus

void animation_name(animation_script temp, int32_t idx, char *result)
{
    sg_Animations_AnimationScriptAnimationName(temp, idx, result);
}

#endif

void animation_script_animation_name(animation_script temp, int32_t idx, char *result)
{
    sg_Animations_AnimationScriptAnimationName(temp, idx, result);
}

void animation_script_name(animation_script script, char *result)
{
    sg_Animations_AnimationScriptName(script, result);
}

animation_script animation_script_named(const char *name)
{
    return sg_Animations_AnimationScriptNamed(name);
}

void assign_animation(animation anim, int32_t idx, animation_script script)
{
    sg_Animations_AssignAnimation(anim, idx, script);
}

#ifdef __cplusplus

void assign_animation(animation anim, const char *name, animation_script script)
{
    sg_Animations_AssignAnimationNamed(anim, name, script);
}

#endif

void assign_animation_named(animation anim, const char *name, animation_script script)
{
    sg_Animations_AssignAnimationNamed(anim, name, script);
}

#ifdef __cplusplus

void assign_animation(animation anim, const char *name, animation_script script, bool withSound)
{
    sg_Animations_AssignAnimationNamedWithSound(anim, name, script, withSound != 0);
}

#endif

void assign_animation_named_with_sound(animation anim, const char *name, animation_script script, bool withSound)
{
    sg_Animations_AssignAnimationNamedWithSound(anim, name, script, withSound != 0);
}

#ifdef __cplusplus

void assign_animation(animation anim, int32_t idx, animation_script script, bool withSound)
{
    sg_Animations_AssignAnimationWithSound(anim, idx, script, withSound != 0);
}

#endif

void assign_animation_with_sound(animation anim, int32_t idx, animation_script script, bool withSound)
{
    sg_Animations_AssignAnimationWithSound(anim, idx, script, withSound != 0);
}

#ifdef __cplusplus

animation create_animation(const char *identifier, animation_script script)
{
    return sg_Animations_CreateAnimationNamed(identifier, script);
}

#endif

animation create_animation_named(const char *identifier, animation_script script)
{
    return sg_Animations_CreateAnimationNamed(identifier, script);
}

#ifdef __cplusplus

animation create_animation(int32_t identifier, animation_script script)
{
    return sg_Animations_CreateAnimationWithSound(identifier, script);
}

#endif

animation create_animation_with_sound(int32_t identifier, animation_script script)
{
    return sg_Animations_CreateAnimationWithSound(identifier, script);
}

animation create_animation(int32_t identifier, animation_script script, bool withSound)
{
    return sg_Animations_CreateAnimation(identifier, script, withSound != 0);
}

#ifdef __cplusplus

animation create_animation(const char *identifier, animation_script script, bool withSound)
{
    return sg_Animations_CreateAnimationNamedWithSound(identifier, script, withSound != 0);
}

#endif

animation create_animation_named_with_sound(const char *identifier, animation_script script, bool withSound)
{
    return sg_Animations_CreateAnimationNamedWithSound(identifier, script, withSound != 0);
}

#ifdef __cplusplus

void draw_animation(animation ani, bitmap bmp, const point2d &pt)
{
    sg_Animations_DrawAnimationAtPoint(ani, bmp, &pt);
}

#endif

void draw_animation_at_point(animation ani, bitmap bmp, const point2d *pt)
{
    sg_Animations_DrawAnimationAtPoint(ani, bmp, pt);
}

void draw_animation_at_point_byval(animation ani, bitmap bmp, const point2d pt)
{
    sg_Animations_DrawAnimationAtPoint(ani, bmp, &pt);
}

#ifdef __cplusplus

void draw_animation(animation ani, bitmap bmp, const point2d &pt, const drawing_options &opts)
{
    sg_Animations_DrawAnimationAtPointWithOptions(ani, bmp, &pt, &opts);
}

#endif

void draw_animation_at_point_with_options(animation ani, bitmap bmp, const point2d *pt, const drawing_options *opts)
{
    sg_Animations_DrawAnimationAtPointWithOptions(ani, bmp, pt, opts);
}

void draw_animation_at_point_with_options_byval(animation ani, bitmap bmp, const point2d pt, const drawing_options opts)
{
    sg_Animations_DrawAnimationAtPointWithOptions(ani, bmp, &pt, &opts);
}

void draw_animation(animation ani, bitmap bmp, float x, float y)
{
    sg_Animations_DrawAnimation(ani, bmp, x, y);
}

#ifdef __cplusplus

void draw_animation(animation ani, bitmap bmp, float x, float y, const drawing_options &opts)
{
    sg_Animations_DrawAnimationWithOptions(ani, bmp, x, y, &opts);
}

#endif

void draw_animation_with_options(animation ani, bitmap bmp, float x, float y, const drawing_options *opts)
{
    sg_Animations_DrawAnimationWithOptions(ani, bmp, x, y, opts);
}

void draw_animation_with_options_byval(animation ani, bitmap bmp, float x, float y, const drawing_options opts)
{
    sg_Animations_DrawAnimationWithOptions(ani, bmp, x, y, &opts);
}

#ifdef __cplusplus

void free_animation(animation &ani)
{
    sg_Animations_FreeAnimation(&ani);
}

#endif

void free_animation(animation *ani)
{
    sg_Animations_FreeAnimation(ani);
}

#ifdef __cplusplus

void free_animation_script(animation_script &scriptToFree)
{
    sg_Animations_FreeAnimationScript(&scriptToFree);
}

#endif

void free_animation_script(animation_script *scriptToFree)
{
    sg_Animations_FreeAnimationScript(scriptToFree);
}

bool has_animation_script(const char *name)
{
    return sg_Animations_HasAnimationScript(name) != 0;
}

animation_script load_animation_script(const char *filename)
{
    return sg_Animations_LoadAnimationScript(filename);
}

animation_script load_animation_script_named(const char *name, const char *filename)
{
    return sg_Animations_LoadAnimationScriptNamed(name, filename);
}

void release_all_animation_scripts()
{
    sg_Animations_ReleaseAllAnimationScripts();
}

void release_animation_script(const char *name)
{
    sg_Animations_ReleaseAnimationScript(name);
}

void restart_animation(animation anim)
{
    sg_Animations_RestartAnimation(anim);
}

#ifdef __cplusplus

void restart_animation(animation anim, bool withSound)
{
    sg_Animations_ResetAnimationWithSound(anim, withSound != 0);
}

#endif

void reset_animation_with_sound(animation anim, bool withSound)
{
    sg_Animations_ResetAnimationWithSound(anim, withSound != 0);
}

void update_animation(animation anim)
{
    sg_Animations_UpdateAnimation(anim);
}

#ifdef __cplusplus

void update_animation(animation anim, float pct)
{
    sg_Animations_UpdateAnimationPct(anim, pct);
}

#endif

void update_animation_pct(animation anim, float pct)
{
    sg_Animations_UpdateAnimationPct(anim, pct);
}

#ifdef __cplusplus

void update_animation(animation anim, float pct, bool withSound)
{
    sg_Animations_UpdateAnimationPctAndSound(anim, pct, withSound != 0);
}

#endif

void update_animation_pct_and_sound(animation anim, float pct, bool withSound)
{
    sg_Animations_UpdateAnimationPctAndSound(anim, pct, withSound != 0);
}


text:
extern crate memcache;

use std::error;
use std::error::Error as _StdError;
use std::fmt;

/// A unified enum of errors by memcache::Connection
#[derive(Debug)]
pub enum Error {
    /// A memcache::MemcacheError
    Other(memcache::MemcacheError),
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.cause() {
            Some(cause) => write!(fmt, "{}: {}", self.description(), cause),
            None => write!(fmt, "{}", self.description()),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Other(ref err) => err.description(),
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Other(ref err) => err.cause(),
        }
    }
}


text:
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"runtime"
)

// check an error, report it and exit with the callers line number.
func check(e error) {
	if e != nil {
		_, _, lineno, _ := runtime.Caller(1)
		log.Fatalf("ERROR:%v %v", lineno, e)
	}
}

// truncate string
// same as s[:w] in python
func trunc(s string, w int) string {
	if w < 1 || len(s) <= w {
		return s
	}
	n := s[:w-1] + "$" // add $ at the end to show that we truncated
	return n
}

// debug prints a debug message with the callers
// line number.
func debug(f string, a ...interface{}) {
	_, _, lineno, _ := runtime.Caller(1)
	s := fmt.Sprintf(f, a...)
	fmt.Fprint(os.Stderr, "DEBUG:")
	log.Printf(":%v %v\n", lineno, s)
}

// info prints a info message with the callers
// line number.
func info(f string, a ...interface{}) {
	_, _, lineno, _ := runtime.Caller(1)
	s := fmt.Sprintf(f, a...)
	fmt.Fprint(os.Stderr, "INFO:")
	log.Printf(":%v %v\n", lineno, s)
}

// readlines reads lines from a text file
// If no data is available, the lines slice is empty.
func readLines(path string) (lines []string) {
	lines = []string{}

	fp, err := os.Open(path)
	check(err)
	defer fp.Close()

	s := bufio.NewScanner(fp)
	for s.Scan() {
		lines = append(lines, s.Text())
	}
	return
}


text:
maintainer       "RightScale, Inc."
maintainer_email "support@rightscale.com"
license          IO.read(File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'LICENSE')))
description      "Installs/configures a MySQL database server with automated backups."
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version          "0.0.1"

depends "mysql", "= 0.9"

provides "db_mysql_restore(url, branch, user, credentials, file_path, schema_name, tmp_dir)"
provides "db_mysql_set_privileges(type, username, password)"

recipe  "db_mysql::default", "Runs the 'install_mysql' recipes."
recipe  "db_mysql::install_mysql", "Installs packages required for MySQL servers without manual intervention."
recipe  "db_mysql::setup_admin_privileges", "Add username and password for superuser privileges."

#
# required attributes
#
attribute "db_mysql",
  :display_name => "General Database Options",
  :type => "hash"

attribute "db/admin/user",
  :display_name => "Database Admin Username",
  :description => "The username of the database user that has 'admin' privileges.",
  :required => true,
  :recipes => [ "db_mysql::setup_admin_privileges" ]

attribute "db/admin/password",
  :display_name => "Database Admin Password",
  :description => "The password of the database user that has 'admin' privileges.",
  :required => true,
  :recipes => [ "db_mysql::setup_admin_privileges" ]

#
# recommended attributes
#
attribute "db_mysql/server_usage",
  :display_name => "Server Usage",
  :description => "* dedicated (where the mysql config file allocates all existing resources of the machine)\n* shared (where the MySQL config file is configured to use less resources so that it can be run concurrently with other apps like Apache and Rails for example)",
  :recipes => [ "db_mysql::install_mysql", "db_mysql::default" ],
  :default => "dedicated"

#
# optional attributes
#
#attribute "db_mysql/log_bin",
#  :display_name => "MySQL Binlog Destination",
#  :description => "Defines the filename and location of your MySQL stored binlog files.  This sets the log-bin variable in the MySQL config file.  If you do not specify an absolute path, it will be relative to the data directory.",
#  :recipes => [ "db_mysql::install_mysql", "db_mysql::default" ],
#  :default => "/mnt/mysql-binlogs/mysql-bin"

#attribute "db_mysql/datadir_relocate",
#  :display_name => "MySQL Data-Directory Destination",
#  :description => "Sets the final destination of the MySQL data directory. (i.e. an LVM or EBS volume)",
#  :default => "/mnt/mysql"

#attribute "db_mysql/tmpdir",
#  :display_name => "MySQL Tmp Directory",
#  :description => "Sets the tmp variable in the MySQL config file.",
#  :default => "/tmp"


text:
package com.ouwenjie.note.activity.account;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;

import com.ouwenjie.note.NoteApplication;
import com.ouwenjie.note.R;
import com.ouwenjie.note.helper.TencentSDKHelper;
import com.ouwenjie.note.model.JideUser;
import com.ouwenjie.note.utils.DisplayAnimUtils;

/**
 *
 * Created by 文杰 on 2015/6/19.
 */
public class UserCenterActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private ViewGroup userInfoLayout;
    private ViewGroup userNoteCountLayout;
    private ViewGroup userLogOutLayout;

    private TencentSDKHelper tencentSDKHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_center);
        initToolbar();

        tencentSDKHelper = TencentSDKHelper.getInstance(this.getApplicationContext());

        userInfoLayout = (ViewGroup) findViewById(R.id.user_info_layout);
        userNoteCountLayout = (ViewGroup) findViewById(R.id.user_note_count_layout);
        userLogOutLayout = (ViewGroup) findViewById(R.id.user_logout_layout);
        userInfoLayout.setOnClickListener(this);
        userNoteCountLayout.setOnClickListener(this);
        userLogOutLayout.setOnClickListener(this);
    }

    private void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setTitle("账号");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_chevron_left_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                DisplayAnimUtils.slideRightOut(UserCenterActivity.this);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_info_layout:
                break;
            case R.id.user_note_count_layout:
                break;
            case R.id.user_logout_layout:
                tencentSDKHelper.logout();
                NoteApplication.getNoteApplication(this).setVisitor(true);

                JideUser.setLoginStatusChanged(this.getApplicationContext(), true);  // 登录状态改变了

                finish();
                DisplayAnimUtils.slideRightOut(this);
                break;
            default:
                break;
        }
    }

}


text:
using DotLiquid;
using DotLiquid.Tags;
using System;
using System.IO;
using ZKWebStandard.Extensions;

namespace ZKWeb.Templating.DynamicContents
{
    ///
    /// Built-in template widget renderer

    /// 内置的模板模块描画器

    ///
    /// <seealso cref="TemplateWidget"/>
    /// <seealso cref="TemplateAreaManager"/>
    public class TemplateWidgetRenderer : ITemplateWidgetRenderer
    {
        ///
        /// Get html before widget contents

        /// 获取描画前的Html内容

        ///
        protected virtual string GetBeforeHtml(Context context, TemplateWidget widget)
        {
            var cacheKey = widget.GetCacheKey();
            return $"
";
        }

        ///
        /// Get html after widget contents

        /// 获取描画后的Html内容

        ///
        protected virtual string GetAfterHtml(Context context, TemplateWidget widget)
        {
            return "
";
        }

        ///
        /// Render widget

        /// Return render result

        /// 描画模板模块

        /// 返回描画结果

        ///
        public string Render(Context context, TemplateWidget widget)
        {
            var templateManager = Application.Ioc.Resolve<TemplateManager>();
            var writer = new StringWriter();
            var scope = templateManager.CreateHash(widget.Args);
            context.Stack(scope, () =>
            {
                writer.Write(GetBeforeHtml(context, widget));
                try
                {
                    var includeTag = new Include();
                    var htmlPath = widget.Path + TemplateWidgetInfo.HtmlExtension;
                    includeTag.Initialize("include", htmlPath, null);
                    includeTag.Render(context, writer);
                }
                catch (Exception ex)
                {
                    writer.Write(ex.ToDetailedString());
                }
                writer.Write(GetAfterHtml(context, widget));
            });
            return writer.ToString();
        }
    }
}


text:
Specify this `acts_as` extension if you want to model a tree structure by providing parent and children associations

## Installation

Add this line to your application's Gemfile:

    gem 'dzap-acts_as_tree', :github => 'dzap/acts_as_tree'

And then execute:

    $ bundle

## Usage ##

Requires a `:foreign_key` option which defaults to `:parent_id`

	class Category < ActiveRecord::Base
	  # schema
	  #   id,        integer
	  #   parent_id, integer
	  #   name,      string

	  acts_as_tree
	end

Also accepts `:order` and `:counter_cache` (defaults to `false`) options

## Example ##

	root
	  \_ child1
	    \_ subchild1
	    \_ subchild2

	root      = Category.create(:name => 'root')
	child1    = root.children.create(:name => 'child1')
	subchild1 = child1.children.create(:name => 'subchild1')

	root.parent   # nil
	child1.parent # root
	root.children # [child1]
	root.children.first.children.first # subchild1

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * @fileoverview    functions used on the server databases list page
 * @name            Server Databases
 *
 * @requires    jQuery
 * @requires    jQueryUI
 * @required    js/functions.js
 */

/**
 * Unbind all event handlers before tearing down a page
 */
AJAX.registerTeardown('server_databases.js', function() {
    $("#dbStatsForm").die('submit');
    $('#create_database_form.ajax').die('submit');
});

/**
 * AJAX scripts for server_databases.php
 *
 * Actions ajaxified here:
 * Drop Databases
 *
 */
AJAX.registerOnload('server_databases.js', function() {
    /**
     * Attach Event Handler for 'Drop Databases'
     */
    $("#dbStatsForm").live('submit', function(event) {
        event.preventDefault();

        var $form = $(this);

        /**
         * @var selected_dbs Array containing the names of the checked databases
         */
        var selected_dbs = [];
        // loop over all checked checkboxes, except the #checkall checkbox
        $form.find('input:checkbox:checked:not(#checkall)').each(function () {
            $(this).closest('tr').addClass('removeMe');
            selected_dbs[selected_dbs.length] = 'DROP DATABASE `' + escapeHtml($(this).val()) + '`;';
        });
        if (! selected_dbs.length) {
            PMA_ajaxShowMessage(
                $('
').text(
                    PMA_messages.strNoDatabasesSelected
                ),
                2000
            );
            return;
        }
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question =
            PMA_messages.strDropDatabaseStrongWarning + ' '
            + $.sprintf(PMA_messages.strDoYouReally, selected_dbs.join('
'));

        $(this).PMA_confirm(
            question,
            $form.prop('action')
                + '?' + $(this).serialize()
                + '&drop_selected_dbs=1&is_js_confirmed=1&ajax_request=true',
            function(url) {
                PMA_ajaxShowMessage(PMA_messages.strProcessingRequest, false);

                $.post(url, function(data) {
                    if (data.success == true) {
                        PMA_ajaxShowMessage(data.message);

                        var $rowsToRemove = $form.find('tr.removeMe');
                        var $databasesCount = $('#databases_count');
                        var newCount = parseInt($databasesCount.text()) - $rowsToRemove.length;
                        $databasesCount.text(newCount);

                        $rowsToRemove.remove();
                        $form.find('tbody').PMA_sort_table('.name');
                        if ($form.find('tbody').find('tr').length == 0) {
                            // user just dropped the last db on this page
                            PMA_commonActions.refreshMain();
                        }
                        PMA_reloadNavigation();
                    } else {
                        $form.find('tr.removeMe').removeClass('removeMe');
                        PMA_ajaxShowMessage(data.error, false);
                    }
                }); // end $.post()
        }); // end $.PMA_confirm()
    }) ; //end of Drop Database action

    /**
     * Attach Ajax event handlers for 'Create Database'.
     */
    $('#create_database_form.ajax').live('submit', function(event) {
        event.preventDefault();

        $form = $(this);

        var newDbNameInput = $form.find('input[name=new_db]');
        if (newDbNameInput.val() === '') {
            newDbNameInput.focus();
            alert(PMA_messages['strFormEmpty']);
            return;
        }

        PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
        PMA_prepareForAjaxRequest($form);

        $.post($form.attr('action'), $form.serialize(), function(data) {
            if (data.success == true) {
                PMA_ajaxShowMessage(data.message);

                //Append database's row to table
                $("#tabledatabases")
                .find('tbody')
                .append(data.new_db_string)
                .PMA_sort_table('.name');

                var $databases_count_object = $('#databases_count');
                var databases_count = parseInt($databases_count_object.text()) + 1;
                $databases_count_object.text(databases_count);
                PMA_reloadNavigation();
            } else {
                PMA_ajaxShowMessage(data.error, false);
            }
        }); // end $.post()
    }); // end $().live()
}); // end $()


text:
<?php
class Kwc_Directories_AjaxView_View_SearchForm_Component extends Kwc_Form_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['useAjaxRequest'] = false;
        $ret['method'] = 'get';
        $ret['generators']['child']['component']['success'] = false;
        return $ret;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_lifecycle_demostration"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.owolp.lifecycledemostration.LifecycleDemostration">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>


text:
package workbench.gui.tools;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import workbench.resource.Settings;

import workbench.db.ColumnIdentifier;
import workbench.db.importer.RowDataProducer;

import workbench.gui.WbSwingUtilities;
import workbench.gui.components.WbScrollPane;

import workbench.util.SqlUtil;
import workbench.util.StringUtil;

/**
 * A panel to map columns from one table definition to another.
 * Source and target are populated with a list of ColumnIdentifiers.
 * Identifiers that have the same name are automatically "mapped".
 *
 * @author  Thomas Kellerer
 */
public class ColumnMapper
	extends JPanel
{
	private JTable columnDisplay;
	private List<ColumnIdentifier> sourceColumns;
	private List<ColumnIdentifier> targetColumns;
	private ColumnMapRow[] mapping;
	protected JComboBox sourceDropDown;
	private final MapDataModel EMPTY_DATA_MODEL = new MapDataModel(new ColumnMapRow[0]);
	private MapDataModel data;

	private boolean allowTargetEditing = false;
	protected boolean allowSourceEditing = false;

	static final SkipColumnIndicator SKIP_COLUMN = new SkipColumnIndicator();

	public ColumnMapper()
	{
		super();
		this.setLayout(new BorderLayout());
		this.columnDisplay = this.createMappingTable();
		this.columnDisplay.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		this.columnDisplay.setRowSelectionAllowed(false);
		WbScrollPane scroll = new WbScrollPane(this.columnDisplay);
		this.add(scroll, BorderLayout.CENTER);
		this.columnDisplay.setModel(EMPTY_DATA_MODEL);
		this.adjustKeyColumn();
	}

	private void adjustKeyColumn()
	{
		TableColumnModel colMod = this.columnDisplay.getColumnModel();
		TableColumn col = colMod.getColumn(2);
		Font f = this.columnDisplay.getTableHeader().getFont();
		FontMetrics fm = this.columnDisplay.getTableHeader().getFontMetrics(f);
		String label = colMod.getColumn(2).getHeaderValue().toString();
		int width = fm.stringWidth(label);
		int addWidth = fm.stringWidth("WWWW");
		col.setMinWidth(width + addWidth);
		col.setMaxWidth(width + addWidth);
		//col.setPreferredWidth(width);
	}

	public void resetData()
	{
		if (this.columnDisplay.getModel() != EMPTY_DATA_MODEL)
		{
			this.columnDisplay.setModel(EMPTY_DATA_MODEL);
		}
	}

	private JTable createMappingTable()
	{
		// Create a specialized JTable which enables or
		// disables the editing of the sourceDropDown based on the
		// current value of the column (if the value is set to "Skip column"
		// then it may not be edited even if source editing is allowed
		JTable t = new JTable()
		{
			@Override
			public TableCellEditor getCellEditor(int row, int column)
			{
				TableCellEditor editor = super.getCellEditor(row, column);
				if (allowSourceEditing && column == 0)
				{
					Object current = getValueAt(row, column);
					if (current == null || current instanceof SkipColumnIndicator)
					{
						sourceDropDown.setEditable(false);
					}
					else
					{
						sourceDropDown.setEditable(allowSourceEditing);
					}
				}
				return editor;
			}
		};
		return t;
	}

	public void defineColumns(List<ColumnIdentifier> source, List<ColumnIdentifier> target, boolean syncDataTypes, boolean keepSourceOrder)
	{
		if (source == null || target == null) throw new IllegalArgumentException("Both column lists have to be specified");
		this.sourceColumns = source;
		this.targetColumns = target;

		// we cannot have more mapping entries then the number of columns in the target
		int numTargetCols = this.targetColumns.size();
		//int numSourceCols = this.sourceColumns.size();
		this.mapping = new ColumnMapRow[numTargetCols];
		for (int i=0; i < numTargetCols; i++)
		{
			ColumnMapRow row = new ColumnMapRow();
			ColumnIdentifier targetCol = this.targetColumns.get(i);
			row.setTarget(targetCol);

			ColumnIdentifier sourceCol = this.findSourceColumnByName(SqlUtil.removeObjectQuotes(targetCol.getDisplayName()));
			if (syncDataTypes && sourceCol != null)
			{
				sourceCol.setDataType(targetCol.getDataType());
				sourceCol.setColumnTypeName(targetCol.getColumnTypeName());
				sourceCol.setDbmsType(targetCol.getDbmsType());
				sourceCol.setDecimalDigits(targetCol.getDecimalDigits());
			}
			row.setSource(sourceCol);
			this.mapping[i] = row;
		}

		this.data = new MapDataModel(this.mapping);
		if (keepSourceOrder)
		{
			data.sortBySourcePosition();
		}
		this.data.setAllowTargetEditing(this.allowTargetEditing);
		this.columnDisplay.setModel(this.data);
		TableColumnModel colMod = this.columnDisplay.getColumnModel();
		TableColumn col = colMod.getColumn(0);

		this.sourceDropDown = this.createDropDown(this.sourceColumns, true);
		Component c = this.sourceDropDown.getEditor().getEditorComponent();
		if (c instanceof JComponent)
		{
			JComponent ce = (JComponent)c;
			ce.setBorder(WbSwingUtilities.EMPTY_BORDER);
		}
		DefaultCellEditor edit = new DefaultCellEditor(this.sourceDropDown);
		col.setCellEditor(edit);

		JTextField targetEditor = new JTextField();
		Font f = Settings.getInstance().getDataFont();
		if (f != null) targetEditor.setFont(f);
		targetEditor.setBorder(WbSwingUtilities.EMPTY_BORDER);
		edit = new DefaultCellEditor(targetEditor);
		col = colMod.getColumn(1);
		col.setCellEditor(edit);

		this.adjustKeyColumn();
		this.columnDisplay.setRowHeight(20);
	}

	public ColumnIdentifier findSourceColumnByName(String aName)
	{
		for (ColumnIdentifier col : this.sourceColumns)
		{
			if (SqlUtil.removeObjectQuotes(col.getDisplayName()).equalsIgnoreCase(aName)) return col;
		}
		return null;
	}

	public void setAllowSourceEditing(boolean aFlag)
	{
		this.allowSourceEditing = aFlag;
		this.sourceDropDown.setEditable(aFlag);
	}

	public void setAllowTargetEditing(boolean aFlag)
	{
		this.allowTargetEditing = true;
		if (this.data != null)
		{
			this.data.setAllowTargetEditing(aFlag);
		}
	}

	private JComboBox createDropDown(List cols, boolean allowEditing)
	{
		JComboBox result = new JComboBox();
		Font f = Settings.getInstance().getDataFont();
		if (f != null) result.setFont(f);
		result.setEditable(allowEditing);
		int count = cols.size();
		if (allowEditing) result.addItem(SKIP_COLUMN);
		for (int i=0; i < count; i++)
		{
			result.addItem(cols.get(i));
		}
		return result;
	}

	private ColumnIdentifier getTargetColumn(ColumnIdentifier source)
	{
		int count = this.mapping.length;
		for (int i=0; i < count; i++)
		{
			ColumnMapRow row = this.mapping[i];
			ColumnIdentifier sourceCol = row.getSource();
			if (sourceCol == null) continue;
			if (sourceCol.getDisplayName().equals(source.getDisplayName()))
			{
				return row.getTarget();
			}
		}
		return null;
	}

	/**
	 * Return the columns from the input file as they should
	 * be specified for the WbImport command
	 */
	public List<ColumnIdentifier> getMappingForImport()
	{
		int count = this.sourceColumns.size();
		ArrayList<ColumnIdentifier> result = new ArrayList<>(count);
		ColumnIdentifier skipId = new ColumnIdentifier(RowDataProducer.SKIP_INDICATOR);
		for (int i=0; i < count; i++)
		{
			ColumnIdentifier col = this.sourceColumns.get(i);

			ColumnIdentifier target = getTargetColumn(col);

			if (target == null)
			{
				result.add(skipId);
			}
			else
			{
				result.add(target);
			}
		}
		return result;
	}

	MappingDefinition getMapping()
	{
		int count = this.mapping.length;
		int realCount = 0;
		for (int i=0; i < count; i++)
		{
			ColumnMapRow row = this.mapping[i];
			String s = null;

			if (row.getSource() != null)
			{
				s = row.getSource().getDisplayName();
				if (StringUtil.isBlank(s)) continue;
				realCount ++;
			}
		}
		MappingDefinition def = new MappingDefinition();
		def.sourceColumns = new ColumnIdentifier[realCount];
		def.targetColumns = new ColumnIdentifier[realCount];
		def.hasSkippedColumns = (realCount != count);

		int index = 0;
		for (int i=0; i < count; i++)
		{
			ColumnMapRow row = this.mapping[i];
			String s = null;

			if (row.getSource() != null)
			{
				s = row.getSource().getDisplayName();
				if (StringUtil.isBlank(s)) continue;
				def.sourceColumns[index] = row.getSource();
				def.targetColumns[index] = row.getTarget();
				index ++;
			}
		}
		return def;
	}

	static class MappingDefinition
	{
		public ColumnIdentifier[] sourceColumns;
		public ColumnIdentifier[] targetColumns;
		public boolean hasSkippedColumns;
	}

}


text:
require "log4r"

require "vagrant/util/file_mode"
require "vagrant/util/platform"
require "vagrant/util/safe_exec"
require "vagrant/util/which"

module Vagrant
  module Util
    # This is a class that has helpers on it for dealing with SSH. These
    # helpers don't depend on any part of Vagrant except what is given
    # via the parameters.
    class SSH
      LOGGER = Log4r::Logger.new("vagrant::util::ssh")

      # Checks that the permissions for a private key are valid, and fixes
      # them if possible. SSH requires that permissions on the private key
      # are 0600 on POSIX based systems. This will make a best effort to
      # fix these permissions if they are not properly set.
      #
      # @param [Pathname] key_path The path to the private key.
      def self.check_key_permissions(key_path)
        # Don't do anything if we're on Windows, since Windows doesn't worry
        # about key permissions.
        return if Platform.windows?

        LOGGER.debug("Checking key permissions: #{key_path}")
        stat = key_path.stat

        if stat.owned? && FileMode.from_octal(stat.mode) != "600"
          LOGGER.info("Attempting to correct key permissions to 0600")
          key_path.chmod(0600)

          # Re-stat the file to get the new mode, and verify it worked
          stat = key_path.stat
          if FileMode.from_octal(stat.mode) != "600"
            raise Errors::SSHKeyBadPermissions, :key_path => key_path
          end
        end
      rescue Errno::EPERM
        # This shouldn't happen since we verify we own the file, but
        # it is possible in theory, so we raise an error.
        raise Errors::SSHKeyBadPermissions, :key_path => key_path
      end

      # Halts the running of this process and replaces it with a full-fledged
      # SSH shell into a remote machine.
      #
      # Note: This method NEVER returns. The process ends after this.
      #
      # @param [Hash] ssh_info This is the SSH information. For the keys
      #   required please see the documentation of {Machine#ssh_info}.
      # @param [Hash] opts These are additional options that are supported
      #   by exec.
      def self.exec(ssh_info, opts={})
        # Ensure the platform supports ssh. On Windows there are several programs which
        # include ssh, notably git, mingw and cygwin, but make sure ssh is in the path!
        if !Which.which("ssh")
          if Platform.windows?
            raise Errors::SSHUnavailableWindows,
              :host => ssh_info[:host],
              :port => ssh_info[:port],
              :username => ssh_info[:username],
              :key_path => ssh_info[:private_key_path]
          end

          raise Errors::SSHUnavailable
        end

        # If plain mode is enabled then we don't do any authentication (we don't
        # set a user or an identity file)
        plain_mode = opts[:plain_mode]

        options = {}
        options[:host] = ssh_info[:host]
        options[:port] = ssh_info[:port]
        options[:username] = ssh_info[:username]
        options[:private_key_path] = ssh_info[:private_key_path]

        # Command line options
        command_options = [
          "-p", options[:port].to_s,
          "-o", "LogLevel=FATAL",
          "-o", "StrictHostKeyChecking=no",
          "-o", "UserKnownHostsFile=/dev/null"]

        # Solaris/OpenSolaris/Illumos uses SunSSH which doesn't support the
        # IdentitiesOnly option. Also, we don't enable it in plain mode so
        # that SSH properly searches our identities and tries to do it itself.
        if !Platform.solaris? && !plain_mode
          command_options += ["-o", "IdentitiesOnly=yes"]
        end

        # If we're not in plain mode, attach the private key path.
        command_options += ["-i", options[:private_key_path].to_s] if !plain_mode

        if ssh_info[:forward_x11]
          # Both are required so that no warnings are shown regarding X11
          command_options += [
            "-o", "ForwardX11=yes",
            "-o", "ForwardX11Trusted=yes"]
        end

        # Configurables -- extra_args should always be last due to the way the
        # ssh args parser works. e.g. if the user wants to use the -t option,
        # any shell command(s) she'd like to run on the remote server would
        # have to be the last part of the 'ssh' command:
        #
        #   $ ssh localhost -t -p 2222 "cd mydirectory; bash"
        #
        # Without having extra_args be last, the user loses this ability
        command_options += ["-o", "ForwardAgent=yes"] if ssh_info[:forward_agent]
        command_options.concat(opts[:extra_args]) if opts[:extra_args]

        # Build up the host string for connecting
        host_string = options[:host]
        host_string = "#{options[:username]}@#{host_string}" if !plain_mode
        command_options.unshift(host_string)

        # Invoke SSH with all our options
        LOGGER.info("Invoking SSH: #{command_options.inspect}")
        SafeExec.exec("ssh", *command_options)
      end
    end
  end
end


text:
require "test_helper"

class Edition::ImagesTest < ActiveSupport::TestCase
  class EditionWithImages < Edition
    include ::Edition::Images

    def previously_published
      false
    end
  end

  include ActionDispatch::TestProcess

  test "editions can be created with multiple images" do
    edition = EditionWithImages.create!(
      valid_edition_attributes.merge(
        images_attributes: [
          {
            alt_text: "Something about this image",
            caption: "Text to be visible along with the image",
            image_data_attributes: {
              file: upload_fixture("minister-of-funk.960x640.jpg", "image/jpg"),
            },
          },
          {
            alt_text: "alt-text-2",
            caption: "caption-2",
            image_data_attributes: {
              file: upload_fixture("minister-of-funk.960x640.jpg", "image/jpg"),
            },
          },
        ],
      ),
    )

    assert_equal 2, edition.images.count
    assert_equal "Something about this image", edition.images[0].alt_text
    assert_equal "Text to be visible along with the image", edition.images[0].caption
    assert_equal "alt-text-2", edition.images[1].alt_text
    assert_equal "caption-2", edition.images[1].caption
  end

  test "#create_draft should include copies of image attributes" do
    image = create(:image, caption: "image-caption")
    published_edition = EditionWithImages.create!(
      valid_edition_attributes.merge(
        state: "published",
        major_change_published_at: Time.zone.now,
        first_published_at: Time.zone.now,
        images: [image],
      ),
    )

    draft_edition = published_edition.create_draft(build(:user))
    draft_edition.change_note = "change-note"

    assert draft_edition.valid?

    new_image = draft_edition.images.last
    assert_not_equal image, new_image
    assert_equal image.alt_text, new_image.alt_text
    assert_equal image.caption, new_image.caption
  end

  test "#create_draft should not duplicate the actual image data" do
    image = create(:image)
    published_edition = EditionWithImages.create!(
      valid_edition_attributes.merge(
        state: "published",
        major_change_published_at: Time.zone.now,
        first_published_at: Time.zone.now,
        images: [image],
      ),
    )

    draft_edition = published_edition.create_draft(build(:user))
    new_image = draft_edition.images.last

    assert_equal image.image_data_id, new_image.image_data_id
  end

  test "#create_draft should carry-over images even when there are validation errors in image data" do
    published_edition = EditionWithImages.new(
      valid_edition_attributes.merge(
        state: "published",
        document: create(:document),
        major_change_published_at: Time.zone.now,
        first_published_at: Time.zone.now,
        images_attributes: [{
          alt_text: "image smaller than 960x640",
          caption: "some-caption",
          image_data_attributes: {
            file: upload_fixture("horrible-image.64x96.jpg", "image/jpg"),
          },
        }],
      ),
    )
    published_edition.save!(validate: false)

    new_draft = published_edition.create_draft(build(:user))
    new_draft.reload

    assert_equal 1, new_draft.images.count
    assert_equal new_draft.images.first.image_data, published_edition.images.first.image_data
  end

  test "captions for images can be changed between versions" do
    published_edition = EditionWithImages.create!(
      valid_edition_attributes.merge(
        state: "published",
        major_change_published_at: Time.zone.now,
        first_published_at: Time.zone.now,
        images_attributes: [{
          alt_text: "alt-text",
          caption: "original-caption",
          image_data_attributes: {
            file: upload_fixture("minister-of-funk.960x640.jpg", "image/jpg"),
          },
        }],
      ),
    )

    draft_edition = published_edition.create_draft(build(:user))
    draft_edition.images.first.update!(caption: "new-caption")

    assert_equal "original-caption", published_edition.images.first.caption
  end

  test "#destroy should also remove the image" do
    Services.asset_manager.stubs(:whitehall_asset).returns("id" => "http://asset-manager/assets/asset-id")
    image = create(:image)
    edition = EditionWithImages.create!(valid_edition_attributes.merge(images: [image]))
    edition.destroy!
    assert_not Image.find_by(id: image.id)
  end

  test "should indicate that it allows image attachments" do
    assert EditionWithImages.new.allows_image_attachments?
  end

private

  def valid_edition_attributes
    {
      title: "edition-title",
      body: "edition-body",
      summary: "edition-summary",
      creator: build(:user),
    }
  end
end


text:
from django.db.models.fields import TextField
from django.db.models import SubfieldBase
import pickle, base64

class SerializedDataField(TextField):
    """
    A field which serializes python values to the database, and returns
    them intact.
    """
    __metaclass__ = SubfieldBase

    def to_python(self, value):
        if value is None or value is "": return
        if not isinstance(value, basestring): return value
        try:
            return pickle.loads(base64.b64decode(value))
        except:
            return

    def get_db_prep_save(self, value):
        if value is None or value is "": return
        return base64.b64encode(pickle.dumps(value))


text: This resource contains printouts for Kidbots activities.


text:
const monk = require('monk');
const config = require('../config.js');
const CardService = require('../services/CardService.js');

let db = monk(config.dbPath);
let cardService = new CardService(db);

module.exports.init = function(server) {
    server.get('/api/cards', function(req, res, next) {
        cardService.getAllCards({ shortForm: true })
            .then(cards => {
                res.send({ success: true, cards: cards });
            })
            .catch(err => {
                return next(err);
            });
    });

    server.get('/api/packs', function(req, res, next) {
        cardService.getAllPacks()
            .then(packs => {
                res.send({ success: true, packs: packs });
            })
            .catch(err => {
                return next(err);
            });
    });

    server.get('/api/factions', function(req, res) {
        let factions = [
            { name: 'House Baratheon', value: 'baratheon' },
            { name: 'House Greyjoy', value: 'greyjoy' },
            { name: 'House Lannister', value: 'lannister' },
            { name: 'House Martell', value: 'martell' },
            { name: 'The Night\'s Watch', value: 'thenightswatch' },
            { name: 'House Stark', value: 'stark' },
            { name: 'House Targaryen', value: 'targaryen' },
            { name: 'House Tyrell', value: 'tyrell' }
        ];
        res.send({ success: true, factions: factions });
    });
};


text:
package org.spongepowered.common.event.tracking.phase.tick;

import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldServer;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.common.entity.PlayerTracker;
import org.spongepowered.common.event.tracking.IPhaseState;
import org.spongepowered.common.event.tracking.PhaseContext;
import org.spongepowered.common.event.tracking.PhaseData;
import org.spongepowered.common.event.tracking.phase.TrackingPhase;
import org.spongepowered.common.interfaces.block.IMixinBlockEventData;
import org.spongepowered.common.interfaces.world.IMixinWorldServer;

import java.util.ArrayList;

import javax.annotation.Nullable;

public final class TickPhase extends TrackingPhase {

    public static final class Tick {

        public static final IPhaseState<BlockTickContext> NO_CAPTURE_BLOCK = new NoCaptureBlockTickPhaseState("NoCaptureBlockTickPhase");
        public static final IPhaseState<BlockTickContext> BLOCK = new BlockTickPhaseState("BlockTickPhase");
        public static final IPhaseState<BlockTickContext> RANDOM_BLOCK = new BlockTickPhaseState("RandomBlockTickPhase");

        public static final IPhaseState<EntityTickContext> ENTITY = new EntityTickPhaseState();

        public static final IPhaseState<DimensionContext> DIMENSION = new DimensionTickPhaseState();
        public static final IPhaseState<TileEntityTickContext> TILE_ENTITY = new TileEntityTickPhaseState();
        public static final IPhaseState<BlockEventTickContext> BLOCK_EVENT = new BlockEventTickPhaseState();
        public static final IPhaseState<PlayerTickContext> PLAYER = new PlayerTickPhaseState();
        public static final IPhaseState<?> WEATHER = new WeatherTickPhaseState();

        private Tick() { // No instances for you!
        }
    }

    public static TickPhase getInstance() {
        return Holder.INSTANCE;
    }

    private TickPhase() {
    }

    private static final class Holder {
        static final TickPhase INSTANCE = new TickPhase();
    }

    @Override
    public void addNotifierToBlockEvent(IPhaseState<?> phaseState, PhaseContext<?> context, IMixinWorldServer mixinWorld, BlockPos pos, IMixinBlockEventData blockEvent) {
    }

    @Override
    public void appendNotifierPreBlockTick(IMixinWorldServer mixinWorld, BlockPos pos, IPhaseState<?> currentState, PhaseContext<?> context, PhaseContext<?> newContext) {
        if (currentState == Tick.BLOCK || currentState == Tick.RANDOM_BLOCK) {

        }
    }

    @Override
    public void associateNeighborStateNotifier(IPhaseState<?> state, PhaseContext<?> context, @Nullable BlockPos sourcePos, Block block, BlockPos notifyPos,
                                               WorldServer minecraftWorld, PlayerTracker.Type notifier) {
        ((TickPhaseState<?>) state).associateNeighborBlockNotifier(context, sourcePos, block, notifyPos, minecraftWorld, notifier);
    }

    @Override
    public boolean alreadyCapturingItemSpawns(IPhaseState<?> currentState) {
        return currentState != Tick.NO_CAPTURE_BLOCK;
    }

    @Override
    public void appendContextPreExplosion(PhaseContext<?> phaseContext, PhaseData currentPhaseData) {
        ((TickPhaseState<?>) currentPhaseData.state).appendExplosionContext(phaseContext, currentPhaseData.context);
    }
}


text:
using System;
using NUnit.Framework;
using ServiceStack.Common.Tests.Models;
using ServiceStack.Common.Utils;
using ServiceStack.DesignPatterns.Model;

namespace ServiceStack.Common.Tests
{
	[TestFixture]
	public class IdUtilsTests
	{
		private const int IntValue = 1;
		private const string StringValue = "A";

		public class HasIntId : IHasIntId
		{
			public int Id
			{
				get { return IntValue; }
			}
		}

		public class HasGenericIdInt : IHasId<int>
		{
			public int Id
			{
				get { return IntValue; }
			}
		}

		public class HasGenericIdString : IHasId<string>
		{
			public string Id
			{
				get { return StringValue; }
			}
		}

		public class HasIdProperty
		{
			public int Id
			{
				get { return IntValue; }
			}
		}

		public class HasIdStringProperty
		{
			public string Id
			{
				get { return StringValue; }
			}
		}

		public class HasIdCustomStringProperty
		{
			public string CustomId
			{
				get { return StringValue; }
			}
		}

		public class HasIdCustomIntProperty
		{
			public int CustomId
			{
				get { return IntValue; }
			}
		}

		[Test]
		public void Can_get_if_HasIntId()
		{
			Assert.That(new HasIntId().GetId(), Is.EqualTo(IntValue));
		}

		[Test]
		public void Can_get_if_HasGenericIdInt()
		{
			Assert.That(new HasGenericIdInt().GetId(), Is.EqualTo(IntValue));
		}

		[Test]
		public void Can_get_if_HasGenericIdString()
		{
			Assert.That(new HasGenericIdString().GetId(), Is.EqualTo(StringValue));
		}

		[Test]
		public void Can_get_if_HasIdProperty()
		{
			Assert.That(new HasIdProperty().GetId(), Is.EqualTo(IntValue));
		}

		[Test]
		public void Can_get_if_HasIdStringProperty()
		{
			Assert.That(new HasIdStringProperty().GetId(), Is.EqualTo(StringValue));
		}

		[Test]
		public void Can_get_if_HasIdCustomStringProperty()
		{
			ModelConfig<HasIdCustomStringProperty>.Id(x => x.CustomId);

			Assert.That(new HasIdCustomStringProperty().GetId(), Is.EqualTo(StringValue));
		}

		[Test]
		public void Can_get_if_HasIdCustomIntProperty()
		{
			ModelConfig<HasIdCustomIntProperty>.Id(x => x.CustomId);

			Assert.That(new HasIdCustomIntProperty().GetId(), Is.EqualTo(IntValue));
		}

	}
}


text:
package certs

import (
	"crypto"
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"os"
	"path"
	"testing"

	certutil "k8s.io/client-go/util/cert"
	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	"k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
)

func TestCertListOrder(t *testing.T) {
	tests := []struct {
		certs Certificates
		name  string
	}{
		{
			name:  "Default Certificate List",
			certs: GetDefaultCertList(),
		},
		{
			name:  "Cert list less etcd",
			certs: GetCertsWithoutEtcd(),
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			var lastCA *KubeadmCert
			for i, cert := range test.certs {
				if i > 0 && lastCA == nil {
					t.Fatalf("CA not present in list before certificate %q", cert.Name)
				}
				if cert.CAName == "" {
					lastCA = cert
				} else {
					if cert.CAName != lastCA.Name {
						t.Fatalf("expected CA name %q, got %q, for certificate %q", lastCA.Name, cert.CAName, cert.Name)
					}
				}
			}
		})
	}
}

func TestCAPointersValid(t *testing.T) {
	tests := []struct {
		certs Certificates
		name  string
	}{
		{
			name:  "Default Certificate List",
			certs: GetDefaultCertList(),
		},
		{
			name:  "Cert list less etcd",
			certs: GetCertsWithoutEtcd(),
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {

			certMap := test.certs.AsMap()

			for _, cert := range test.certs {
				if cert.CAName != "" && certMap[cert.CAName] == nil {
					t.Errorf("Certificate %q references nonexistent CA %q", cert.Name, cert.CAName)
				}
			}
		})
	}
}

func TestMakeCertTree(t *testing.T) {
	rootCert := &KubeadmCert{
		Name: "root",
	}
	leaf0 := &KubeadmCert{
		Name:   "leaf0",
		CAName: "root",
	}
	leaf1 := &KubeadmCert{
		Name:   "leaf1",
		CAName: "root",
	}
	selfSigned := &KubeadmCert{
		Name: "self-signed",
	}

	certMap := CertificateMap{
		"root":        rootCert,
		"leaf0":       leaf0,
		"leaf1":       leaf1,
		"self-signed": selfSigned,
	}

	orphanCertMap := CertificateMap{
		"leaf0": leaf0,
	}

	if _, err := orphanCertMap.CertTree(); err == nil {
		t.Error("expected orphan cert map to error, but got nil")
	}

	certTree, err := certMap.CertTree()
	t.Logf("cert tree: %v", certTree)
	if err != nil {
		t.Errorf("expected no error, but got %v", err)
	}

	if len(certTree) != 2 {
		t.Errorf("Expected tree to have 2 roots, got %d", len(certTree))
	}

	if len(certTree[rootCert]) != 2 {
		t.Errorf("Expected root to have 2 leaves, got %d", len(certTree[rootCert]))
	}

	if _, ok := certTree[selfSigned]; !ok {
		t.Error("Expected selfSigned to be present in tree, but missing")
	}
}

func TestCreateCertificateChain(t *testing.T) {
	dir, err := ioutil.TempDir("", t.Name())
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	ic := &kubeadmapi.InitConfiguration{
		NodeRegistration: kubeadmapi.NodeRegistrationOptions{
			Name: "test-node",
		},
		ClusterConfiguration: kubeadmapi.ClusterConfiguration{
			CertificatesDir: dir,
		},
	}

	caCfg := Certificates{
		{
			config:   pkiutil.CertConfig{},
			Name:     "test-ca",
			BaseName: "test-ca",
		},
		{
			config: pkiutil.CertConfig{
				Config: certutil.Config{
					AltNames: certutil.AltNames{
						DNSNames: []string{"test-domain.space"},
					},
					Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
				},
			},
			configMutators: []configMutatorsFunc{
				setCommonNameToNodeName(),
			},
			CAName:   "test-ca",
			Name:     "test-daughter",
			BaseName: "test-daughter",
		},
	}

	certTree, err := caCfg.AsMap().CertTree()
	if err != nil {
		t.Fatalf("unexpected error getting tree: %v", err)
	}

	if certTree.CreateTree(ic); err != nil {
		t.Fatal(err)
	}

	caCert, _ := parseCertAndKey(path.Join(dir, "test-ca"), t)
	daughterCert, _ := parseCertAndKey(path.Join(dir, "test-daughter"), t)

	pool := x509.NewCertPool()
	pool.AddCert(caCert)

	_, err = daughterCert.Verify(x509.VerifyOptions{
		DNSName:   "test-domain.space",
		Roots:     pool,
		KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	})
	if err != nil {
		t.Errorf("couldn't verify daughter cert: %v", err)
	}

}

func parseCertAndKey(basePath string, t *testing.T) (*x509.Certificate, crypto.PrivateKey) {
	certPair, err := tls.LoadX509KeyPair(basePath+".crt", basePath+".key")
	if err != nil {
		t.Fatalf("couldn't parse certificate and key: %v", err)
	}

	parsedCert, err := x509.ParseCertificate(certPair.Certificate[0])
	if err != nil {
		t.Fatalf("couldn't parse certificate: %v", err)
	}

	return parsedCert, certPair.PrivateKey
}


text:
import { MongoClient } from 'mongodb';
import { mongo as mongoLogger } from '~/loggers';
import config from '~/config';

const logger = mongoLogger.context({ url: config.mongo });

const mongoConnectionPromise = MongoClient.connect(config.mongo, {
  reconnectTries : Number.MAX_VALUE,
  reconnectInterval: 3000,
  autoReconnect : true,
  logger,
});

const getCollection = (collection) => mongoConnectionPromise.then((connection) => connection.collection(collection));

export const authFacebookCollection = getCollection('auth_facebook');
export const authPhoneCollection = getCollection('auth_phone');
export const bookCollection = getCollection('books');
export const salesCollection = getCollection('sales');
export const smsCollection = getCollection('sms');
export const userCollection = getCollection('users');


text:
App.ready(function() {
  "use strict";

  $('body.show #titlebar_right').click(function() {
    $(this).toggleClass('active');
  });

  $('body.show #active_admin_content').click(function() {
    $('body.show #titlebar_right').removeClass('active');
  });
});


text:
@protocol DLTFeed <NSObject>

@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic, copy, readonly) NSString *subtitle;
@property (nonatomic, copy, readonly) NSDate *updated;
@property (nonatomic, copy, readonly) NSArray *entries;

- (instancetype)initWithDocument:(ONOXMLDocument *)document;
@end

@interface DLTFeed : NSObject

+ (id<DLTFeed>)feedWithData:(NSData *)data error:(NSError **)error;
+ (id<DLTFeed>)feedWithDocument:(ONOXMLDocument *)document;

@end


text:
namespace Apache.Ignite.Core.Tests
{
    using Apache.Ignite.Core.Common;
    using NUnit.Framework;

    /// <summary>
    /// Test marshaller initialization.
    /// </summary>
    public class MarshallerTest
    {
        /// <summary>
        /// Tests the default marhsaller.
        /// By default, binary marshaller is used.
        /// </summary>
        [Test]
        public void TestDefaultMarhsaller()
        {
            using (var grid = StartIgnite("config\\marshaller-default.xml"))
            {
                var cache = grid.GetOrCreateCache<int, int>("default");

                cache.Put(1, 1);

                Assert.AreEqual(1, cache.Get(1));
            }
        }

        /// <summary>
        /// Tests the binary marhsaller.
        /// Marshaller can be specified explicitly in config.
        /// </summary>
        [Test]
        public void TestExplicitMarhsaller()
        {
            using (var grid = StartIgnite("config\\marshaller-explicit.xml"))
            {
                var cache = grid.GetOrCreateCache<int, int>("default");

                cache.Put(1, 1);

                Assert.AreEqual(1, cache.Get(1));
            }
        }

        /// <summary>
        /// Tests the invalid marshaller.
        /// </summary>
        [Test]
        public void TestInvalidMarshaller()
        {
            var ex = Assert.Throws<IgniteException>(() => StartIgnite("config\\marshaller-invalid.xml"));
            Assert.AreEqual("Unsupported marshaller (only org.apache.ignite.internal.binary.BinaryMarshaller " +
                            "can be used when running Apache Ignite.NET): org.apache.ignite.internal." +
                            "marshaller.optimized.OptimizedMarshaller", ex.Message, ex.ToString());
        }

        /// <summary>
        /// Starts the ignite.
        /// </summary>
        private static IIgnite StartIgnite(string xml)
        {
            return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                SpringConfigUrl = xml
            });
        }
    }
}


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace awt
      {
        namespace peer
        {
            class KDEDesktopPeer;
        }
      }
    }
  }
}

class gnu::java::awt::peer::KDEDesktopPeer : public ::gnu::java::awt::peer::ClasspathDesktopPeer
{

public:
  KDEDesktopPeer();
public: // actually protected
  virtual ::java::lang::String * getCommand(::java::lang::String *);
  virtual jboolean supportCommand(::java::lang::String *);
public:
  virtual void mail();
public: // actually protected
  virtual ::java::lang::String * execQuery(::java::lang::String *);
private:
  static ::java::lang::String * BROWSER_QUERY_GNOME;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_java_awt_peer_KDEDesktopPeer__


text:
package com.silverforge.elasticsearchrawclient.queryDSL.queries.innerQueries;

import com.silverforge.elasticsearchrawclient.exceptions.MandatoryParametersAreMissingException;
import com.silverforge.elasticsearchrawclient.model.QueryTypeItem;
import com.silverforge.elasticsearchrawclient.queryDSL.Constants;
import com.silverforge.elasticsearchrawclient.definition.SpanQueryable;
import com.silverforge.elasticsearchrawclient.queryDSL.generator.QueryFactory;
import com.silverforge.elasticsearchrawclient.utils.QueryTypeArrayList;

public class SpanOrQuery
        implements SpanQueryable {

    private QueryTypeArrayList<QueryTypeItem> queryBag;

    SpanOrQuery(QueryTypeArrayList<QueryTypeItem> queryBag) {
        this.queryBag = queryBag;
    }

    @Override
    public String getQueryString() {
        return QueryFactory
                .spanOrQueryGenerator()
                .generate(queryBag);
    }

    public static Init<?> builder() {
        return new SpanOrQueryBuilder();
    }

    public static class SpanOrQueryBuilder
            extends Init<SpanOrQueryBuilder> {

        @Override
        protected SpanOrQueryBuilder self() {
            return this;
        }
    }

    public static abstract class Init<T extends Init<T>> {

        private QueryTypeArrayList<QueryTypeItem> queryBag = new QueryTypeArrayList<>();

        protected abstract T self();

        public T clauses(SpanQueryable... clauses) {
            queryBag.addItem(Constants.CLAUSES, clauses);
            return self();
        }

        public SpanOrQuery build() throws MandatoryParametersAreMissingException {
            if(!queryBag.containsKey(Constants.CLAUSES)) {
                throw new MandatoryParametersAreMissingException(Constants.CLAUSES);
            }
            return new SpanOrQuery(queryBag);
        }

    }
}


text:
require 'test_helper'

class GithubBasicDetectiveTest < ActiveSupport::TestCase
  setup do
    @full_name = 'linuxfoundation/cii-best-practices-badge'
    @human_name = 'Core Infrastructure Initiative Best Practices Badge'
    @evidence = Evidence.new({})
    @repo_url = "https://github.com/#{@full_name}"
  end

  test 'Mocked GitHub retrieves our name and license' do
    VCR.use_cassette('unit_test_github_basic_detective') do
      results = GithubBasicDetective.new.analyze(@evidence, repo_url: @repo_url)

      assert results.key?(:name)
      assert results[:name].key?(:value)
      assert results[:name][:value] == @human_name

      assert results.key?(:license)
      assert results[:license].key?(:value)
      assert results[:license][:value] == 'MIT'
    end
  end
end


text:
<?
class Image {

	const COMBINE_BELOW = 1;
	const COMBINE_ABOVE = 2;

	const PALLETED = 10;
	const TRUE_COLOR = 11;

	protected $filepath = "";
	protected $type = 0;
	protected $image = null;

	protected $width = 0;
	protected $height = 0;

	protected $valid = false;

	function __construct($filepath = "", $type = 0) {

		$this->filepath = $filepath;
		$this->type = $type;

		if (strlen(trim($filepath))) {

			if (!$this->type) {

				$temp = getimagesize($this->filepath);
				$this->type = $temp[2];

			}

			switch ($this->type) {

				case IMAGETYPE_GIF:
					$this->image = imagecreatefromgif($this->filepath);
					break;

				case IMAGETYPE_JPEG:
					$this->image = imagecreatefromjpeg($this->filepath);
					break;

				case IMAGETYPE_PNG:
					$this->image = imagecreatefrompng($this->filepath);
					break;

				case IMAGETYPE_BMP:
					$this->image = imagecreatefromwbmp($this->filepath);
					break;

			}

		}

	}

	function __destruct() {
		$this->destroy();
	}

	function setType($type = 0) {

		if ($type) {
			$this->type = $type;
		} else {
			$temp = getimagesize($this->filepath);
			$this->type = $temp[2];
		}

		switch ($this->type) {

			case IMAGETYPE_GIF:
				$this->image = imagecreatefromgif($this->filepath);
				break;

			case IMAGETYPE_JPEG:
				$this->image = imagecreatefromjpeg($this->filepath);
				break;

			case IMAGETYPE_PNG:
				$this->image = imagecreatefrompng($this->filepath);
				break;

			case IMAGETYPE_BMP:
				$this->image = imagecreatefromwbmp($this->filepath);
				break;

		}

	}

	function create($width, $height, $type = Image::PALLETED) {

		$this->width = $width;
		$this->height = $height;

		if ($type == Image::PALLETED) {
			$this->image = imagecreate($this->width, $this->height);
		} else {
			$this->image = imagecreatetruecolor($this->width, $this->height);
		}

	}

	function resizeToWidth($tgtX) {

		$srcX = imagesx($this->image);
		$srcY = imagesy($this->image);

		$srcAspect = $srcX / $srcY;

		$tgtY = $tgtX * (1 / $srcAspect);

		$tmpImg = imagecreatetruecolor($tgtX, $tgtY);
		imagealphablending($tmpImg, 1);

		imagecopyresampled($tmpImg, $this->image, 0, 0, 0, 0, $tgtX, $tgtY, $srcX, $srcY);

		$this->image = $tmpImg;

	}

	function resizeToHeight($tgtY) {

		$srcX = imagesx($this->image);
		$srcY = imagesy($this->image);

		$srcAspect = $srcY / $srcX;

		$tgtX = $tgtY * (1 / $srcAspect);

		$tmpImg = imagecreatetruecolor($tgtX, $tgtY);
		imagealphablending($tmpImg, 1);

		imagecopyresampled($tmpImg, $this->image, 0, 0, 0, 0, $tgtX, $tgtY, $srcX, $srcY);

		$this->image = $tmpImg;

	}

	function resize($width, $height) {

		$srcX = imagesx($this->image);
		$srcY = imagesy($this->image);

		$tmpImg = imagecreatetruecolor($width, $height);

		$this->setAlphaBlending(true);
		imagealphablending($tmpImg, true);
		imagecolortransparent($tmpImg, imagecolortransparent($this->image));

		imagecopyresampled($tmpImg, $this->image, 0, 0, 0, 0, $width, $height, $srcX, $srcY);

		$this->image = $tmpImg;

	}

	function resizeToMax($intWidth, $intHeight) {

		$intOriginWidth = imagesx($this->image);
		$intOriginHeight = imagesy($this->image);

		$dblOriginRatio = $intOriginWidth / $intOriginHeight;
		$dblTargetRatio = $intWidth / $intHeight;

		if ($dblOriginRatio < $intTargetRatio)
			$this->resizeToHeight($intHeight);
		else
			$this->resizeToWidth($intWidth);

	}

	function clipTo($width, $height) {

		$tmpImg = imagecreatetruecolor($width, $height);
		imagealphablending($tmpImg, true);

		imagecopy($tmpImg, $this->image, 0, 0, (imagesx($this->image) - $width) / 2, (imagesy($this->image) - $height) / 2, imagesx($this->image), imagesy($this->image));

		$this->image = $tmpImg;

	}

	function combine($combineWhere, $image, $x = 0, $y = 0, $widthDiff = 0, $heightDiff = 0) {

		$image->setAlphaBlending(true);
		$this->setAlphaBlending(true);

		switch ($combineWhere) {

			case Image::COMBINE_BELOW:

				$newImg = imagecreatetruecolor($image->getWidth(), $image->getHeight());
				imagealphablending($newImg, true);

				imagecopy($newImg, $image->getImage(), 0, 0, 0, 0, $image->getWidth(), $image->getHeight());
				imagecopyresampled($newImg, $this->image, $x, $y, 0, 0, $this->getWidth(), $this->getHeight(), $this->getWidth() - $widthDiff, $this->getHeight() - $heightDiff);
				$this->image = $newImg;

				break;

			case Image::COMBINE_ABOVE:

				$newImg = imagecreatetruecolor($this->getWidth(), $this->getHeight());
				imagealphablending($newImg, true);

				imagecopy($newImg, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight());
				imagecopyresampled($newImg, $image->getImage(), $x, $y, 0, 0, $image->getWidth() - $widthDiff, $image->getHeight() - $heightDiff, $image->getWidth(), $image->getHeight());
				$this->image = $newImg;

				break;

		}

	}

	function setAlphaBlending($blending) {

		imagealphablending($this->image, $blending);

	}

	function getWidth() {

		return imagesx($this->image);

	}

	function getHeight() {

		return imagesy($this->image);

	}

	function fill($hexColor) {

		$color = $this->getColor($hexColor);

		imagefill($this->image, 0, 0, $color);

	}

	function fillBehind($color) {

		$fillImg = new Image();
		$fillImg->create($this->getWidth(), $this->getHeight(), TRUE_COLOR);
		$fillImg->setAlphaBlending(true);
		$fillImg->fill("#ffffff");

		$this->combine(Image::COMBINE_BELOW, $fillImg);

	}

	function drawRectangle($x, $y, $width, $height, $hexColor) {

		$color = $this->getColor($hexColor);

		imagefilledrectangle($this->image, $x, $y, $x + $width, $y + $height, $color);

	}

	function drawLine($startX, $startY, $endX, $endY, $hexColor) {

		$color = $this->getColor($hexColor);

		imageline($this->image, $startX, $startY, $endX, $endY, $color);

	}

	function drawBorder($width, $hexColor) {

		$maxX = imagesx($this->image) - 1;
		$maxY = imagesy($this->image) - 1;

		$color = $this->getColor($hexColor);

		// Draw top just line
		imageline($this->image, 0, 0, $maxX, 0, $color);

		// Draw left line
		imageline($this->image, 0, 0, 0, $maxY, $color);

		// Draw right line
		imageline($this->image, $maxX, 0, $maxX, $maxY, $color);

		// Draw bottom line
		imageline($this->image, 0, $maxY, $maxX, $maxY, $color);

	}

	function exportToBrowser($type = IMAGETYPE_JPEG, $quality = 80) {

		switch ($type) {

			case IMAGETYPE_JPEG:
				header('Content-Type: image/jpeg');
				imagejpeg($this->image, "", $quality);
				break;

			case IMAGETYPE_GIF:
				header('Content-Type: image/gif');
				imagegif($this->image);
				break;

			case IMAGETYPE_PNG:
				header('Content-Type: image/png');
				imagepng($this->image);
				break;

			case IMAGETYPE_BMP:
				header('Content-Type: image/bmp');
				imagewbmp($this->image);
				break;

		}

	}

	function export($filename, $type = IMAGETYPE_JPEG, $quality = 80) {

		switch ($type) {

			case IMAGETYPE_JPEG:
				imagejpeg($this->image, $filename, $quality);
				break;

			case IMAGETYPE_GIF:
				imagegif($this->image, $filename);
				break;

			case IMAGETYPE_PNG:
				imagepng($this->image, $filename);
				break;

			case IMAGETYPE_BMP:
				imagewbmp($this->image, $filename);
				break;

		}

	}

	function saveAsGif($filename) {

		$this->export($filename, IMAGETYPE_GIF);

	}

	function destroy() {

		@imagedestroy($this->image);

	}

	function getImage() {

		return $this->image;

	}

	function getColor($hexColor) {

		if (strlen($hexColor) == 7 && substr($hexColor, 0, 1) == "#") {
			$hexColor = substr($hexColor, 1);
		} elseif (strlen($hexColor) != 6) {
			return;
		}

		$red = hexdec(substr($hexColor, 0, 2));
		$green = hexdec(substr($hexColor, 2, 2));
		$blue = hexdec(substr($hexColor, 4, 2));

		return imagecolorallocate($this->image, $red, $green, $blue);

	}

	function _rgba2c($r, $g, $b, $a = 0) {

		$c = 0;
		$c = $c | (($a & 0x7F) << 24);
		$c = $c | ($r << 16);
		$c = $c | ($g << 8);
		$c = $c | ($b);

		return $c;

	}

	function _c2rgba($c) {

		$a = ($c >> 24) & 0x7F;
		$r = ($c >> 16) & 0xFF;
		$g = ($c >> 8) & 0xFF;
		$b = $c & 0xFF;

		return array($r, $g, $b, $a);

	}

	function isValidImage() {

		$cmd = "/usr/bin/identify -format \"%m\" $this->filepath";

		exec($cmd, $output, $result);

		if ($result) {
			return false;
		} else {
			return true;
		}

	}

	function convertTo($type, $newFilename, $options = '') {

		chdir(dirname($this->filepath));

		if (file_exists(dirname($this->filepath) . '/' . $newFilename))
			@unlink(dirname($this->filepath) . '/' . $newFilename);

		$cmd = "/usr/bin/convert $options '" . basename($this->filepath) . "' '$type:$newFilename'";
		$oldFilepath = $this->filepath;
		$this->filepath = dirname($this->filepath) . "/$newFilename";

		exec($cmd, $output, $result);

		if($result || !is_file($this->filepath)) {
			return false;
		} else {
			$converted = 1;
			$error = 0;
			@unlink($oldFilepath);
		}

		return true;

	}

	function writeText($str, $x, $y, $hexColor, $font = 1) {
		imagestring($this->image, $font, $x, $y, $str, $this->getColor($hexColor));
	}

	function writeTTFText($str, $fontFile, $hexColor, $fontSize, $x, $y, $angle = 0) {

		imagettftext($this->image, $fontSize, $angle, $x, $y, $this->getColor($hexColor), $fontFile, $str);

	}

	function getTTFBoundingBox($str, $fontFile, $fontSize, $angle = 0) {

		/*
			Returns the following array indexes:

			0 lower left corner, X position
			1 lower left corner, Y position
			2 lower right corner, X position
			3 lower right corner, Y position
			4 upper right corner, X position
			5 upper right corner, Y position
			6 upper left corner, X position
			7 upper left corner, Y position

		*/

		return imagettfbbox($fontSize, $angle, $fontFile, $str);

	}

	function isAnimatedGIF() {

		exec('/usr/local/bin/identify ' . $this->filepath, $output, $result);

		if (strstr($output[0], 'GIF')) {
			return count($output) > 1 ? true : false;
		} else {
			return false;
		}

	}

}
?>


text:
import { ChangeDetectorRef, ContentChild, Directive, ElementRef, EventEmitter, forwardRef, Input, Output, Renderer } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ListHeader } from '../list/list-header';
import { isCheckedProperty, isTrueProperty } from '../../util/util';
export const /** @type {?} */ RADIO_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioGroup),
    multi: true
};
/**
 * \@name RadioGroup
 * \@description
 * A radio group is a group of [radio buttons](../RadioButton). It allows
 * a user to select at most one radio button from a set. Checking one radio
 * button that belongs to a radio group unchecks any previous checked
 * radio button within the same group.
 *
 * See the [Angular Forms Docs](https://angular.io/docs/ts/latest/guide/forms.html)
 * for more information on forms and inputs.
 *
 * \@usage
 * ```html
 * <ion-list radio-group [(ngModel)]="autoManufacturers">
 *
 *   <ion-list-header>
 *     Auto Manufacturers
 *   </ion-list-header>
 *
 *   <ion-item>
 *     <ion-label>Cord</ion-label>
 *     <ion-radio value="cord"></ion-radio>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label>Duesenberg</ion-label>
 *     <ion-radio value="duesenberg"></ion-radio>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label>Hudson</ion-label>
 *     <ion-radio value="hudson"></ion-radio>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label>Packard</ion-label>
 *     <ion-radio value="packard"></ion-radio>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label>Studebaker</ion-label>
 *     <ion-radio value="studebaker"></ion-radio>
 *   </ion-item>
 *
 * </ion-list>
 * ```
 *
 * \@demo /docs/v2/demos/src/radio/
 * @see {\@link /docs/v2/components#radio Radio Component Docs}
 * @see {\@link ../RadioButton RadioButton API Docs}
 */
export class RadioGroup {
    /**
     * @param {?} _renderer
     * @param {?} _elementRef
     * @param {?} _cd
     */
    constructor(_renderer, _elementRef, _cd) {
        this._renderer = _renderer;
        this._elementRef = _elementRef;
        this._cd = _cd;
        /**
         * @internal
         */
        this._disabled = false;
        /**
         * @private
         */
        this._btns = [];
        /**
         * @private
         */
        this._ids = -1;
        /**
         * @private
         */
        this._init = false;
        /**
         * @output {any} Emitted when the selected button has changed.
         */
        this.ionChange = new EventEmitter();
        this.id = ++radioGroupIds;
    }
    /**
     * \@input {boolean} If true, the user cannot interact with any of the buttons in the group.
     * @return {?}
     */
    get disabled() {
        return this._disabled;
    }
    /**
     * @param {?} val
     * @return {?}
     */
    set disabled(val) {
        this._disabled = isTrueProperty(val);
    }
    /**
     * @return {?}
     */
    ngAfterContentInit() {
        let /** @type {?} */ activeButton = this._btns.find(b => b.checked);
        if (activeButton) {
            this._setActive(activeButton);
        }
    }
    /**
     * @param {?} val
     * @return {?}
     */
    writeValue(val) {
        (void 0) /* console.debug */;
        this.value = val;
        if (this._init) {
            this._update();
            this.onTouched();
            this.ionChange.emit(val);
        }
        this._init = true;
    }
    /**
     * @param {?} fn
     * @return {?}
     */
    registerOnChange(fn) {
        this._fn = fn;
        this.onChange = (val) => {
            // onChange used when there's an formControlName
            (void 0) /* console.debug */;
            fn(val);
            this.value = val;
            this._update();
            this.onTouched();
            this.ionChange.emit(val);
        };
    }
    /**
     * @param {?} fn
     * @return {?}
     */
    registerOnTouched(fn) { this.onTouched = fn; }
    /**
     * @return {?}
     */
    _update() {
        // loop through each of the radiobuttons
        let /** @type {?} */ hasChecked = false;
        this._btns.forEach(radioButton => {
            // check this radiobutton if its value is
            // the same as the radiogroups value
            radioButton.checked = isCheckedProperty(this.value, radioButton.value) && !hasChecked;
            if (radioButton.checked) {
                // if this button is checked, then set it as
                // the radiogroup's active descendant
                this._setActive(radioButton);
                hasChecked = true;
            }
        });
    }
    /**
     * @param {?} radioButton
     * @return {?}
     */
    _setActive(radioButton) {
        this._renderer.setElementAttribute(this._elementRef.nativeElement, 'aria-activedescendant', radioButton.id);
    }
    /**
     * @param {?} button
     * @return {?}
     */
    add(button) {
        this._btns.push(button);
        // listen for radiobutton select events
        button.ionSelect.subscribe((val) => {
            // this radiobutton has been selected
            this.onChange(val);
        });
        return this.id + '-' + (++this._ids);
    }
    /**
     * @param {?} button
     * @return {?}
     */
    remove(button) {
        let /** @type {?} */ index = this._btns.indexOf(button);
        if (index > -1) {
            if (button.value === this.value) {
                this.value = null;
            }
            this._btns.splice(index, 1);
        }
    }
    /**
     * @param {?} header
     * @return {?}
     */
    set _header(header) {
        if (header) {
            if (!header.id) {
                header.id = 'rg-hdr-' + this.id;
            }
            this._renderer.setElementAttribute(this._elementRef.nativeElement, 'aria-describedby', header.id);
        }
    }
    /**
     * @param {?} val
     * @return {?}
     */
    onChange(val) {
        // onChange used when there is not an formControlName
        (void 0) /* console.debug */;
        this.value = val;
        this._update();
        this.onTouched();
        this.ionChange.emit(val);
        this._cd.detectChanges();
    }
    /**
     * @return {?}
     */
    onTouched() { }
    /**
     * @param {?} isDisabled
     * @return {?}
     */
    setDisabledState(isDisabled) {
        this.disabled = isDisabled;
    }
}
RadioGroup.decorators = [
    { type: Directive, args: [{
                selector: '[radio-group]',
                host: {
                    'role': 'radiogroup'
                },
                providers: [RADIO_VALUE_ACCESSOR]
            },] },
];
/** @nocollapse */
RadioGroup.ctorParameters = () => [
    { type: Renderer, },
    { type: ElementRef, },
    { type: ChangeDetectorRef, },
];
RadioGroup.propDecorators = {
    'disabled': [{ type: Input },],
    'ionChange': [{ type: Output },],
    '_header': [{ type: ContentChild, args: [ListHeader,] },],
};
function RadioGroup_tsickle_Closure_declarations() {
    /** @type {?} */
    RadioGroup.decorators;
    /**
     * @nocollapse
     * @type {?}
     */
    RadioGroup.ctorParameters;
    /** @type {?} */
    RadioGroup.propDecorators;
    /**
     * \@internal
     * @type {?}
     */
    RadioGroup.prototype._disabled;
    /** @type {?} */
    RadioGroup.prototype._btns;
    /** @type {?} */
    RadioGroup.prototype._fn;
    /** @type {?} */
    RadioGroup.prototype._ids;
    /** @type {?} */
    RadioGroup.prototype._init;
    /** @type {?} */
    RadioGroup.prototype.value;
    /** @type {?} */
    RadioGroup.prototype.id;
    /**
     * \@output {any} Emitted when the selected button has changed.
     * @type {?}
     */
    RadioGroup.prototype.ionChange;
    /** @type {?} */
    RadioGroup.prototype._renderer;
    /** @type {?} */
    RadioGroup.prototype._elementRef;
    /** @type {?} */
    RadioGroup.prototype._cd;
}
let /** @type {?} */ radioGroupIds = -1;
//# sourceMappingURL=radio-group.js.map