text:
<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;
use app\models\general\Upload;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
use common\models\general\GeneralFunction;
/**
 * This is the model class for table "tbl_khidmat_perubatan_dan_sains_sukan".
 *
 * @property integer $khidmat_perubatan_dan_sains_sukan_id
 * @property integer $kategori_servis
 * @property integer $servis
 * @property string $tempat
 * @property string $tarikh_mula
 * @property string $tarikh_tamat
 * @property string $status
 * @property string $muat_naik
 * @property string $kecederaan_jika_ada
 * @property integer $sukan
 * @property integer $program
 * @property string $mod_latihan
 * @property string $sasaran
 * @property integer $created_by
 * @property integer $updated_by
 * @property string $created
 * @property string $updated
 */
class KhidmatPerubatanDanSainsSukan extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_khidmat_perubatan_dan_sains_sukan';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['kategori_servis', 'tempat', 'tarikh_mula', 'tarikh_tamat', 'status'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['kategori_servis', 'servis', 'sukan', 'program', 'created_by', 'updated_by'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['tarikh_mula', 'tarikh_tamat', 'created', 'updated', 'catatan'], 'safe'],
            [['tempat'], 'string', 'max' => 90, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['status', 'mod_latihan', 'sasaran'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['muat_naik'], 'string', 'max' => 255, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['kecederaan_jika_ada'], 'string', 'max' => 100, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['muat_naik'],'validateFileUpload', 'skipOnEmpty' => false],
            [['tempat','status', 'mod_latihan', 'sasaran','kecederaan_jika_ada'], 'filter', 'filter' => function ($value) {
                return  \common\models\general\GeneralFunction::filterXSS($value);
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'khidmat_perubatan_dan_sains_sukan_id' => 'Khidmat Perubatan Dan Sains Sukan ID',
            'kategori_servis' => 'Kategori Servis',
            'servis' => '(Sub)',
            'tempat' => GeneralLabel::tempat,
            'tarikh_mula' => GeneralLabel::tarikh_mula,
            'tarikh_tamat' => GeneralLabel::tarikh_tamat,
            'status' => GeneralLabel::status,
            'muat_naik' => GeneralLabel::muat_naik,
			'catatan' => GeneralLabel::catatan,
            'kecederaan_jika_ada' => 'Kecederaan Jika Ada',
            'sukan' => 'Sukan',
            'program' => 'Program',
            'mod_latihan' => 'Mod Latihan',
            'sasaran' => 'Sasaran',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
            'created' => 'Created',
            'updated' => 'Updated',
        ];
    }

    /**
     * Validate upload file cannot be empty
     */
    public function validateFileUpload($attribute, $params){
        $file = UploadedFile::getInstance($this, $attribute);

        if($file && $file->getHasError()){
            $this->addError($attribute, 'File error :' . Upload::getUploadErrorDesc($file->error));
        }

        if($file){
            if(!GeneralFunction::checkFileExtension($file->getExtension())){
                $this->addError($attribute, GeneralMessage::uploadFileTypeError);
            }
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefStatusKhidmatPerubatan(){
        return $this->hasOne(RefStatusKhidmatPerubatan::className(), ['id' => 'status']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefKategoriServis(){
        return $this->hasOne(RefKategoriServis::className(), ['id' => 'kategori_servis']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefKategoriServisSub(){
        return $this->hasOne(RefKategoriServisSub::className(), ['id' => 'servis']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefTempatKhidmatPerubatan(){
        return $this->hasOne(RefTempatKhidmatPerubatan::className(), ['id' => 'tempat']);
    }
}


text:
if [ -d ~/.pyenv ]; then
  echo '########## pyenv already installed, skipping.'
else
  echo "########## Installing pyenv ..."
  sudo apt-get install -y --force-yes libssl-dev libreadline-dev zlib1g-dev git
  sudo apt-get install -y --force-yes build-essential checkinstall
  sudo apt-get install -y --force-yes libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
  git clone https://github.com/pyenv/pyenv.git ~/.pyenv
  mkdir -p ~/.pyenv/plugins
  pushd ~/.pyenv/plugins
  git clone https://github.com/pyenv/pyenv-ccache.git
  git clone https://github.com/pyenv/pyenv-version-ext.git
  popd
fi

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Duby, Bot. Gall. 2(2): 601 (1830)

#### Original name
Parmelia cetrarioides var. cetrarioides

### Remarks
null


text:
package org.orienteer.logger.server.service.enhancer;

import org.orienteer.logger.IOLoggerEventEnhancer;
import org.orienteer.logger.OLoggerEvent;
import org.orienteer.logger.server.model.OLoggerEventModel;

/**
 * Add seed class to event metadata
 */
public class OSeedClassEnhancer implements IOLoggerEventEnhancer {

    @Override
    public OLoggerEvent enhance(OLoggerEvent event) {
        Object seed = event.getSeed();
        if (seed != null) {
            event.setMetaData(OLoggerEventModel.PROP_SEED_CLASS, seed.getClass().getName());
        }
        return event;
    }

}


text:
Apache Zeppelin, an open source data analysis platform, is a top program of Apache; its back-end has multiple components to support a variety of data processing engine, such as Spark, Flink, Lens and so on; and provide notebook type UI to process visualization related operations. KAP has developed  corresponding Zeppelin modules and merged them with Zeppelin's major branches.  Correspondingly KAP is accessible with Zeppelin 0.5.6 and subsequent version.

### Zeppelin Architecture Introduction
As the following diagram shows, Zeppelin client is capable to interact  with servers through both HTTP Rest and Websocket. On the servers, Interpreter is supported by Zeppelin. For Kylin, users only need to develop Kylin-Interpreter and enable it integrate with Zeppelin, then users can correspond with Kylin server via Zeppelin's client, and visit related data on Kylin.

![](images/zeppelin/zeppelin_arc.png)

### Kylin-Interpreter Operational Principle
Kylin-Interpreter is based on Rest API of AP, so it is a classic using scenario for KAP API. Kylin-Interpreter would read front-end configuration of Zeppelin for KAP, such as URL, user, password, and  query corresponding project, limit, offset and ispartial. Combined with the previous queried API Rest, you probably know that the key issue is the joint of query request parameters. Besides, combining with configuration parameter, users could input SQL in front-end and obtain data through sending HTTP POST type request to KAP.

The following is part of the Kylin-Interpreter code. With notes, it would be clear to see how does Kylin-Interpreter visit KAP API.

```
  public HttpResponse prepareRequest(String sql) throws IOException {
    String KYLIN_PROJECT = getProperty(KYLIN_QUERY_PROJECT);
……
……
//Read account password from the configuration item and code base on Base64
    byte[] encodeBytes = Base64.encodeBase64(new String(getProperty(KYLIN_USERNAME)
        + ":" + getProperty(KYLIN_PASSWORD)).getBytes("UTF-8"));
    //Set request parameter
    String postContent = new String("{\"project\":" + "\"" + KYLIN_PROJECT + "\""
        + "," + "\"sql\":" + "\"" + sql + "\""
        + "," + "\"acceptPartial\":" + "\"" + getProperty(KYLIN_QUERY_ACCEPT_PARTIAL) + "\""
        + "," + "\"offset\":" + "\"" + getProperty(KYLIN_QUERY_OFFSET) + "\""
        + "," + "\"limit\":" + "\"" + getProperty(KYLIN_QUERY_LIMIT) + "\"" + "}");
    postContent = postContent.replaceAll("[\u0000-\u001f]", " ");
    StringEntity entity = new StringEntity(postContent, "UTF-8");
    entity.setContentType("application/json; charset=UTF-8");
    HttpPost postRequest = new HttpPost(getProperty(KYLIN_QUERY_API_URL));
postRequest.setEntity(entity);
//Set request header, then add Basic Authentication information
    postRequest.addHeader("Authorization", "Basic " + new String(encodeBytes));
    postRequest.addHeader("Accept-Encoding", "UTF-8");

    HttpClient httpClient = HttpClientBuilder.create().build();
    return httpClient.execute(postRequest);
  }
```

The front-end of Zeppelin has its own schema, so Kylin-Interpreter really needs to intercept KAP's returned data in order to keep it understandable to the front-end. So the main task for Kylin-Interpreter is to joint parameters so as to complete HTTP requests for KAP server, and formatting returned results.

### Apply Zeppelin to KAP

To begin, users need to download binary package of Zeppelin 0.5.6 or the subsequent versions, process configuration according to the official website's tips and start Zeppelin's front-end (detailed introduction is available from the official website).

* Configuration for Interpreter
  Open the configuration page of Zeppelin,  click 'Interpreter' page. The Interpreter configuration for a specific KAP project is show as follow:

![](images/zeppelin/zeppelin_config.png)

* Query
  Open Notebook to create a new note, input SQL in the note( please notice that for query against KAP, users need to input additional '%kylin' before SQL query,because Zeppelin's back-end needs to know use which Interpreter to handle the query. Results are as follow, users can drag dimensions and measures easily to get the results requested.

![](images/zeppelin/zeppelin_query.png)

* Zeppelin Public Function

For each query of Zeppelin, you can create a link and share it to others.
Interested readers can learn more on the [Zeppelin official website]( http://zeppelin.apache.org/).


text:
module Paperless

  class PDFUtils

    def self.convert_image_to_pdf(image_path, pdf_path)
      `convert #{image_path} #{pdf_path}`
      File.exist? pdf_path
    end
  end
end


text:
class MixedFieldType < ActiveRecord::Base
  validates :name, :presence => true, :uniqueness => true
  attr_accessible :name

  has_many :mixed_fields
end


text:
[angularjs]: https://github.com/angular/angular.js
[uirouter]: https://github.com/angular-ui/ui-router

###mySref Directive
Did you ever had a problem with binding a state through a variable?

```
example: <a ui-sref="{{myStateVar}}">awesome link</a>
```
... then this directive can solve your problem!

```
usage: <a my-sref="{{myStateVar}}">awesome link</a>
```


text:
<!DOCTYPE HTML>

  <title>Test for Bug 392318</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />

  <link rel="stylesheet" type="text/css" href="data:text/css;%20charset=utf-8,%23t%20%7B%0Awidth%3A%20200px%3B%0Aborder%3A%201px%20solid%20black%3B%0Aheight%3A%20100px%3B%0A%7D">

Mozilla Bug 392318


text:
package ru.lozenko.headwindsolutions.geofence.activities.location;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import ru.lozenko.headwindsolutions.geofence.BuildConfig;
import ru.lozenko.headwindsolutions.geofence.R;
import ru.lozenko.headwindsolutions.geofence.activities.BaseActivity;
import ru.lozenko.headwindsolutions.geofence.databinding.ActivitySetupTrackingBinding;
import ru.lozenko.headwindsolutions.geofence.services.GeoProcessingService;
import ru.lozenko.headwindsolutions.geofence.storage.SharedPreferencesStorageManager;
import ru.lozenko.headwindsolutions.geofence.storage.StorageManager;
import ru.lozenko.headwindsolutions.geofence.storage.TrackZone;

/**
 * Created by Ivan Lozenko on 20.10.2016.
 * Активити установки отслеживаемых координат
 */

public class SetupTrackingActivity extends BaseActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        ResultCallback<LocationSettingsResult>,
        SeekBar.OnSeekBarChangeListener {

    /**
     * Имя хранилища настроек
     */
    public static final String STORAGE_NAME = "track_zone_storage";
    /**
     * Идентификатор геозоны (логика программы заточена на отслеживание одной геозоны единовременно
     */
    public static final String REQUEST_NAME = "REQName";
    /**
     * Код задачи проверки системных настроек
     */
    private static final int CHECK_SETTINGS_CODE = 9;
    /**
     * Код проверки разрешений
     */
    private static final int PERMISSIONS_REQUEST_CODE = 10;
    /**
     * Код решения проблем подключения к PlayServices
     */
    private static final int CONNECTION_RESOLUTION_CODE = 11;
    /**
     * Код ошибки подключения
     */
    private static final int CONNECTION_ERROR_CODE = 12;
    private ActivitySetupTrackingBinding binding;
    private GoogleApiClient googleApiClient;
    private StorageManager storageManager;
    private PendingIntent servicePendingIntent;

    //В качестве явного признака отслеживания буду использовать null-состояние переменной
    private TrackZone trackZone;
    //Анонимный экземпляр требуется, поскольку активити уже реализует ResultCallback.
    //Поле, чтобы коллбек не выгрузился раньше активити. Для порядочной реализации лучше организовать
    //систему подключений на основе службы. Делаю так только потому, что это тестовое задание
    private ResultCallback<Status> enableResultCallback = new ResultCallback<Status>() {

        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                storageManager.setCurrentTrackZone(trackZone);
                showSnackBar(R.string.tracking_enabled_successfully, binding.radiusTextView);
            } else {
                trackZone = null;
                showSnackBar(R.string.error_enabling_tracking, binding.radiusTextView);
            }
            updateUi();
        }
    };
    private ResultCallback<Status> disableResultCallback = new ResultCallback<Status>() {

        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                trackZone = null;
                storageManager.setCurrentTrackZone(null);
                showSnackBar(R.string.tracking_disabled, binding.radiusTextView);
            }
            updateUi();
        }
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_setup_tracking);
        storageManager = new SharedPreferencesStorageManager(this, STORAGE_NAME);
        trackZone = storageManager.getCurrentTrackZone();
        binding.versionTextView.setText(BuildConfig.VERSION_NAME);
        binding.radiusTextView.setText("100");
        binding.radiusSeekBar.setOnSeekBarChangeListener(this);
        updateUi();
    }

    @Override
    protected void onStart() {
        super.onStart();
        googleApiClientConnect();
    }

    @Override
    protected void onStop() {
        if (googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) {
            googleApiClient.disconnect();
        }
        super.onStop();
    }

    /**
     * Проверяет необходимые разрешения и устанавливает подключение к PlayServices
     */
    private void googleApiClientConnect() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        googleApiClient.connect();
    }

    /**
     * PlayServices проверит настройки устройства (GPS, источники, кеширование) и предложит их включить
     */
    private void checkSettings() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));
        builder.addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY));
        builder.addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_LOW_POWER));
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(this);
    }

    private void enableTracking() {
        //LocationServices.GeofencingApi.addGeofences требует явной проверки разрешений в том методе, в котором вызывается
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (checkData()) {
                trackZone = new TrackZone(
                        Double.parseDouble(binding.latitudeEditText.getText().toString()),
                        Double.parseDouble(binding.longitudeEditText.getText().toString()),
                        binding.radiusSeekBar.getProgress() + 100
                );
                Geofence geofence = new Geofence.Builder()
                        .setRequestId(REQUEST_NAME)
                        .setCircularRegion(trackZone.latitude, trackZone.longitude, trackZone.radius)
                        .setExpirationDuration(Geofence.NEVER_EXPIRE)
                        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                        .build();
                GeofencingRequest request = new GeofencingRequest.Builder()
                        .addGeofence(geofence)
                        .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
                        .build();
                if (servicePendingIntent == null) {
                    servicePendingIntent = GeoProcessingService.getPendingIntent(this);
                }
                try {
                    LocationServices.GeofencingApi
                            .addGeofences(googleApiClient, request, servicePendingIntent)
                            .setResultCallback(enableResultCallback);
                } catch (Exception e) {
                    showSnackBar(e.getMessage(), binding.radiusTextView);
                }
            }
        } else {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION},
                    PERMISSIONS_REQUEST_CODE);
        }
    }

    private void disableTracking() {
        if (googleApiClient.isConnected()) {
            if (servicePendingIntent == null) {
                servicePendingIntent = GeoProcessingService.getPendingIntent(this);
            }
            LocationServices.GeofencingApi.removeGeofences(googleApiClient, servicePendingIntent).setResultCallback(disableResultCallback);
        } else {
            showSnackBar(R.string.play_services_is_not_connected_now, binding.radiusTextView);
        }
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private boolean checkData() {
        if (googleApiClient == null || !googleApiClient.isConnected()) {
            showSnackBar(R.string.play_services_is_not_connected_now, binding.radiusTextView);
            return false;
        }
        if (TextUtils.isEmpty(binding.latitudeEditText.getText()) ||
                TextUtils.isEmpty(binding.longitudeEditText.getText())) {
            showSnackBar(R.string.enter_correct_data, binding.radiusTextView);
            return false;
        }
        try {
            Double.parseDouble(binding.latitudeEditText.getText().toString());
            Double.parseDouble(binding.longitudeEditText.getText().toString());
        } catch (Exception ignored) {
            showSnackBar(R.string.enter_correct_data, binding.radiusTextView);
            return false;
        }
        return true;
    }

    public void onStartButtonPressed(View view) {
        if (trackZone == null) {
            enableTracking();
        } else {
            disableTracking();
        }
    }

    private void updateUi() {
        if (trackZone != null) {
            binding.latitudeEditText.setText(String.valueOf(trackZone.latitude));
            binding.longitudeEditText.setText(String.valueOf(trackZone.longitude));
            binding.radiusSeekBar.setProgress(trackZone.radius - 100);
            binding.radiusTextView.setText(String.valueOf(trackZone.radius));
            binding.nowTrackingTextView.setVisibility(View.VISIBLE);
            binding.latitudeEditText.setEnabled(false);
            binding.longitudeEditText.setEnabled(false);
            binding.radiusSeekBar.setEnabled(false);
            binding.startButton.setText(R.string.end_tracking);
        } else {
            binding.nowTrackingTextView.setVisibility(View.GONE);
            binding.latitudeEditText.setEnabled(true);
            binding.longitudeEditText.setEnabled(true);
            binding.radiusSeekBar.setEnabled(true);
            binding.startButton.setText(R.string.start_tracking);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.permissions_not_allowed)
                            .setMessage(R.string.need_permissions_explanation)
                            .setPositiveButton(R.string.allow, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    enableTracking();
                                }
                            })
                            .setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    finish();
                                }
                            })
                            .setCancelable(false)
                            .create().show();
                    return;
                }
            }
            enableTracking();
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        checkSettings();
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Не стал реализовывать. В нормальном варианте должна быть заглушка крутилки
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_RESOLUTION_CODE);
            } catch (IntentSender.SendIntentException e) {
                googleApiClient.connect();
            }
        } else {
            Dialog dialog = GoogleApiAvailability.getInstance()
                    .getErrorDialog(this, connectionResult.getErrorCode(), CONNECTION_ERROR_CODE);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    finish();
                }
            });
            dialog.show();
        }
    }

    @Override
    public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
        Status status = locationSettingsResult.getStatus();
        if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
            try {
                status.startResolutionForResult(
                        this,
                        CHECK_SETTINGS_CODE);
            } catch (IntentSender.SendIntentException e) {
                showSnackBar(e.getMessage(), binding.radiusTextView);
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        binding.radiusTextView.setText(String.valueOf(i + 100));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}


text:
package ru.org.codingteam.icfpc

import org.scalatest.{Matchers, FlatSpec}

class PRNGSpec extends FlatSpec with Matchers {

  "The PRNG" should "generate sequence from specification" in {
    val prng = new PRNG(17)
    val result = for (x <- List.range(0, 10)) yield prng.next
    val expected = List(0, 24107, 16552, 12125, 9427, 13152, 21440, 3383, 6873,
                        16117)

    assert(result === expected)
  }
}


text:
import time
import json

from tests.unit import  unittest
from boto.cloudformation.connection import CloudFormationConnection

BASIC_EC2_TEMPLATE = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "AWS CloudFormation Sample Template EC2InstanceSample",
    "Parameters": {
    },
    "Mappings": {
        "RegionMap": {
            "us-east-1": {
                "AMI": "ami-7f418316"
            }
        }
    },
    "Resources": {
        "Ec2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId": {
                    "Fn::FindInMap": [
                        "RegionMap",
                        {
                            "Ref": "AWS::Region"
                        },
                        "AMI"
                    ]
                },
                "UserData": {
                    "Fn::Base64": "a" * 15000
                }
            }
        }
    },
    "Outputs": {
        "InstanceId": {
            "Description": "InstanceId of the newly created EC2 instance",
            "Value": {
                "Ref": "Ec2Instance"
            }
        },
        "AZ": {
            "Description": "Availability Zone of the newly created EC2 instance",
            "Value": {
                "Fn::GetAtt": [
                    "Ec2Instance",
                    "AvailabilityZone"
                ]
            }
        },
        "PublicIP": {
            "Description": "Public IP address of the newly created EC2 instance",
            "Value": {
                "Fn::GetAtt": [
                    "Ec2Instance",
                    "PublicIp"
                ]
            }
        },
        "PrivateIP": {
            "Description": "Private IP address of the newly created EC2 instance",
            "Value": {
                "Fn::GetAtt": [
                    "Ec2Instance",
                    "PrivateIp"
                ]
            }
        },
        "PublicDNS": {
            "Description": "Public DNSName of the newly created EC2 instance",
            "Value": {
                "Fn::GetAtt": [
                    "Ec2Instance",
                    "PublicDnsName"
                ]
            }
        },
        "PrivateDNS": {
            "Description": "Private DNSName of the newly created EC2 instance",
            "Value": {
                "Fn::GetAtt": [
                    "Ec2Instance",
                    "PrivateDnsName"
                ]
            }
        }
    }
}

class TestCloudformationConnection(unittest.TestCase):
    def setUp(self):
        self.connection = CloudFormationConnection()
        self.stack_name = 'testcfnstack' + str(int(time.time()))

    def test_large_template_stack_size(self):
        # See https://github.com/boto/boto/issues/1037
        body = self.connection.create_stack(
            self.stack_name,
            template_body=json.dumps(BASIC_EC2_TEMPLATE))
        self.addCleanup(self.connection.delete_stack, self.stack_name)

        # A newly created stack should have events
        events = self.connection.describe_stack_events(self.stack_name)
        self.assertTrue(events)

        # No policy should be set on the stack by default
        policy = self.connection.get_stack_policy(self.stack_name)
        self.assertEqual(None, policy)

        # Our new stack should show up in the stack list
        stacks = self.connection.describe_stacks()
        self.assertEqual(self.stack_name, stacks[0].stack_name)

if __name__ == '__main__':
    unittest.main()


text:
var http = require('http');
var key = process.env.crunchbasekey;
var fs = require('fs');
var readline = require('readline');
var query = process.env.query;
var _ = require('underscore');
var permalinks = [];
var json2csv = require('json2csv');
var async = require('async');
var currentPage = 0;
var getpermalinks = function(page) {
            currentPage = page;

	try{
	http.get("http://api.crunchbase.com/v/1/search.js?query=" + query + "&api_key=" + key + "&page=" + page, function(res) {
        var data = "";
	currentPage = page;
	console.log("http://api.crunchbase.com/v/1/search.js?query=" + query + "&api_key=" + key + "&page=" + page);
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function() {
	try{
            var parsed_data = JSON.parse(data);
            var total_pages = parsed_data.total / 10;
            var page = parsed_data.page;
            permalinks.push(_.map(parsed_data.results, function(el) {
                return el.permalink;
            }));
            console.log(_.size(permalinks));
            if (page < total_pages) {
                getpermalinks(page + 1);
            } else {
                var permalinksFlat = _.flatten(permalinks); //WTF logic doing it serially I am not an idiot CB has rate limitations
                var parallelTasks = [];
                permalinksFlat.forEach(function(permalink) {
                    parallelTasks.push(function(callback) {
                        getSingleDetail(permalink, callback);
                    });
                });
                async.parallelLimit(parallelTasks,100, function(err, companyData) {
                    json2csv({
                        data: companyData,
                        fields: ['name', 'homepage_url', 'founded_year', 'deadpooled_year', 'overview', 'total_money_raised']
                    }, function(err, csv) {
                        if (err) console.log(err);
                        fs.writeFile('data/' + query + ".csv", csv, function(err) {
                            if (err) throw err;
                            console.log('file saved');
                        });
                    });
                });
            }
	} catch ( e){
		console.log("skipping " + currentPage);
		getpermalinks(currentPage + 1);
		}
        });
    });
	}catch(e){
		console.log("skipping"+currentPage);
		getpermalinks(currentPage + 1);

	}
};
var companyData = [];
var getSingleDetail = function(permalink, callback) {
    var data = "";
    console.log("http://api.crunchbase.com/v/1/company/" + permalink + ".js?api_key=" + key);
	try{
    	http.get("http://api.crunchbase.com/v/1/company/" + permalink + ".js?api_key=" + key, function(res) {
        console.log("fetching company data");
        //FIXME: add error handler. Requeue errored task
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function() {
           var parsedData = {};
		try{
		       	parsedData = JSON.parse(data);
		}catch(err){
			console.log("ignoring"+permalink);
		}
            	callback(null, parsedData);
        	});
    	}).on('error',function(){
		callback(null,{});
	});
	}catch(err){
		callback(null,{});
	}
}

getpermalinks(1);


text:
<?xml version="1.0" encoding="utf-8" ?>
<c2eventsheet>
    <!--All the 'name' attributes are ignored by Construct 2 - they are there for readability only.-->
    <name>room-9 (energy crystal)</name>
    <events>
        <include>Jplay</include>
        <include>ROMplay</include>
        <event-block any="1" sid="6867843775565983">
            <conditions>
                <condition id="-1" name="Compare X" sid="7621632899964263" type="ROM30">
                    <param id="0" name="Comparison">4</param>
                    <param id="1" name="X co-ordinate">840</param>
                </condition>
                <condition id="-1" name="Compare X" sid="356256482193868" type="J">
                    <param id="0" name="Comparison">4</param>
                    <param id="1" name="X co-ordinate">840</param>
                </condition>
            </conditions>
            <actions>
                <action id="-2" name="Go to layout" sid="410083481340787" type="System">
                    <param id="0" name="Layout">room-7</param>
                </action>
            </actions>
        </event-block>
    </events>
</c2eventsheet>


text:
[![Join the chat at https://gitter.im/kidpixo/pymimedetacher](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kidpixo/pymimedetacher?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Compact script to parse maildir structure, detach attachment and save them in a directory structure mirroring the mailbox folders.

It is based on python core-library [mailbox (Manipulate mailboxes in various formats — Python 2.7.10 documentation)](https://docs.python.org/2/library/mailbox.html).

## Options

`-h, --help`

show help message and exit

`-i PATH, --input=PATH`

Input [Maildir](https://en.wikipedia.org/wiki/Maildir) path to parse.

You easly can obtain a local copy of your IMAP mailbox with [OfflineIMAP](http://offlineimap.org/).

Some good tutorials on offlineimap setup specific to gmail:
- [The Homely Mutt / Steve Losh](http://stevelosh.com/blog/2012/10/the-homely-mutt/)
- [Mutt + Gmail + Offlineimap](https://pbrisbin.com/posts/mutt_gmail_offlineimap/)
- [OfflineIMAP - ArchWiki](https://wiki.archlinux.org/index.php/OfflineIMAP)

`-o OUTPATH, --output=OUTPATH`

Output path to store the attachments, the subfolders will mirror the mailbox folder structure.

`-d, --delete-attachment`

Delete the attachments in the original mail, default is to leave there.

`-s, --save_attachment`

Save and decode the attachments files, default is do nothing.

`-v, --verbose`

Print more verbose output.


text:
'use strict';

/* global Connector */

/** note: the discover page doesn't display the track artist for compilation albums.  This connector
    currently passes 'Various Artist' (or other variant) as the artist name so tracks on albums with
    various artists played on the discover page will most likely not be recognized.*/

// wire audio element to fire state changes
$('audio').bind('playing pause timeupdate', Connector.onStateChanged);

/**
 * remove zero width characters & trim
 * @param  {string} text to clean up
 * @return {string} cleaned up text
 */
function cleanText(input) {
	if (input === null) {
		return input;
	}
	return input.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
}

function getArtist() {
	var artist = $('.detail_item_link_2').text() ||
				$('span[itemprop=byArtist]').text() ||
				$('.detail-artist a').text() ||
				null;
	if (artist === null) {
		artist = $('.waypoint-artist-title').text().substr(3);
	}
	return cleanText(artist);
}

function getTrack() {
	var track = $('.track_info .title').first().text() ||
				$('.trackTitle').first().text() ||
				$('.waypoint-item-title').text() ||
				$('.track_info .title') ||
				null;
	return cleanText(track);
}

function artistIsVarious() {
	// album page: true if all tracks contain a hyphen or vertical bar (pipe symbol)
	// example of pipe usage: http://tigersmilkrecords.bandcamp.com/album/peru-maravilloso-vintage-latin-tropical-cumbia
	if ($('meta[property="og:type"]').attr('content') === 'album') {
		var allDashed = true;
		$('.track_list span[itemprop="name"]').each(function () {
			if (!/\||-/.test($(this).text())) {
				allDashed = false;
				return false;
			}
		});
		return allDashed;
	}
	// discover & song pages: true if artist name is 'Various' or 'Various Artists'
	// and track contains a hyphen or vertical bar.
	// Also takes into account misspelling of various as varios
	//    http://krefeld8ung.bandcamp.com/album/krefeld-8ung-vol-1
	return (/^Variou?s(\sArtists)?$/.test(getArtist()) && /\||-/.test(getTrack()));
}

/* @returns {{artist, track}} */
Connector.getArtistTrack = function () {
	var artist = getArtist(),
		track = getTrack(),
		separatorIndex;
	if (artistIsVarious()) {
		separatorIndex = Math.max(track.indexOf('-'), track.indexOf('|'));
		artist = cleanText(track.substring(0, separatorIndex));
		track = cleanText(track.substring(separatorIndex + 1));
	}
	return {
		artist: artist,
		track: track
	};
};

Connector.getAlbum = function () {
	var album = $('.detail_item_link').text() ||
				$('h2.trackTitle').text() ||
				$('[itemprop="inAlbum"] [itemprop="name"]').text() ||
				null;
	return cleanText(album);
};

Connector.playButtonSelector = 'div.playbutton:not(.playing)';

Connector.getTrackArt = function() {
	return $('#tralbumArt > a > img').attr('src') ||
	$('#detail_gallery_container img').attr('src') ||
	$('.discover-detail-inner img').attr('src');
};

Connector.getCurrentTime = function () {
	return Math.round($('audio')[0].currentTime);
};

Connector.getDuration = function () {
	return Math.round($('audio')[0].duration);
};

/** Returns a unique identifier of current track.
 *  @returns {String|null} */
Connector.getUniqueID = function () {
	var match = /&id=(\d+)&/.exec($('audio').first().attr('src'));
	if (match) {
		return match[1];
	}
	return null;
};


text:
package com.kiuwan.client.examples;

import java.util.List;

import com.kiuwan.client.KiuwanClientException;
import com.kiuwan.client.KiuwanRestApiClient;
import com.kiuwan.client.model.actionplan.ActionPlanBean;

public class ListActionPlans {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		if(args.length != 3)
	    {
	        System.out.println("You need to pass 3 parameters: username password applicationName");
	        return;
	    }

		String username = args[0];
		String password = args[1];
		String applicationName = args[2];

		KiuwanRestApiClient client = new KiuwanRestApiClient(username, password);

		try {
			List<ActionPlanBean> actionPlans = client.listActionPlans(applicationName);

			System.out.println("Found " + actionPlans.size() + " action plans in the application "+applicationName+".\n");
			for(ActionPlanBean actionPlan: actionPlans) {
				System.out.println(actionPlan);
			}

		} catch (KiuwanClientException e) {
			e.printStackTrace();
		}

	}

}


text:
function times (num, iterator, callback) {
  var i = 0
  var results = []

  function done (err, res) {
    results[i] = res
    i++

    if (err) {
      callback(err, results)
      callback = noop
      return
    }

    if (i === num) return callback(err, results)

    iter()
  }

  function noop () {}

  function iter () {
    iterator(i, done)
  }

  iter()
}

module.exports = times


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace TcxTools
{
    /// <remarks/>
    [XmlInclude(typeof(None))]
    [XmlInclude(typeof(Cadence))]
    [XmlInclude(typeof(HeartRate))]
    [XmlInclude(typeof(Speed))]
    [Serializable]
    [XmlType(Namespace = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2", TypeName = "Target_t")]
    public abstract class Target
    {
    }
}


text:
var RevealEmbedTweet = window.RevealEmbedTweet || (function(){
	var ready = false;
	window.twttr = (function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0],
				t = window.twttr || {};
		if (d.getElementById(id)) return t;
		js = d.createElement(s);
		js.id = id;
		js.src = "https://platform.twitter.com/widgets.js";
		fjs.parentNode.insertBefore(js, fjs);

		t._e = [];
		t.ready = function(f) {
				t._e.push(f);
		};
	}(document, "script", "twitter-wjs"));

	function load() {
		if ( twttr != undefined && !document.querySelector('section[data-markdown]:not([data-markdown-parsed])') ) {
			tweets = document.querySelectorAll(".tweet");
			for (i = 0; i < tweets.length; ++i) {
				tweets[i].style.cssText = "margin: 0;position: absolute; left: 50%;transform: translate(-50%,0%);" + tweets[i].style.cssText;
				tweets[i].innerHTML = 	'
Tweet
';
			}
			twttr.widgets.load()
		}
		else {
			// wait for markdown to be loaded and parsed
			setTimeout( load, 100 );
		}
	}

	Reveal.addEventListener( 'ready', function( event ) {
		load();
	} );

})();


text:
string name;

public string Name
{
    get
    {
        // BAD: Not thread-safe
        if (name == null)
            name = LoadNameFromDatabase();
        return name;
    }
}


text:
/*
 * unityplugin.cpp
 *
 *      Author: liushijian
 */

#include "unityplugin.h"

static IUnityInterfaces* s_UnityInterfaces = NULL;
static IUnityGraphics* s_Graphics = NULL;
static UnityGfxRenderer s_RendererType = kUnityGfxRendererNull;
static GLuint frameBufferTextureId = 0;
static GLuint frameBufferDepthTextureId = 0;
static GLint antiAliasing = 0;

// Unity plugin load event
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
    UnityPluginLoad(IUnityInterfaces* unityInterfaces)
{
    s_UnityInterfaces = unityInterfaces;
    s_Graphics = unityInterfaces->Get<IUnityGraphics>();

    s_Graphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent);

    // Run OnGraphicsDeviceEvent(initialize) manually on plugin load
    // to not miss the event in case the graphics device is already initialized
    OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize);
}

// Unity plugin unload event
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
    UnityPluginUnload()
{
    s_Graphics->UnregisterDeviceEventCallback(OnGraphicsDeviceEvent);
}

static void UNITY_INTERFACE_API
    OnGraphicsDeviceEvent(UnityGfxDeviceEventType eventType)
{
    switch (eventType)
    {
        case kUnityGfxDeviceEventInitialize:
        {
            s_RendererType = s_Graphics->GetRenderer();
            glFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVR)eglGetProcAddress ("glFramebufferTextureMultiviewOVR");
            if (!glFramebufferTextureMultiviewOVR)
            {
            	ANDROID_LOG("Can not get proc address for glFramebufferTextureMultiviewOVR.\n");
            	//exit(EXIT_FAILURE);
            }

            glFramebufferTextureMultisampleMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVR)eglGetProcAddress ("glFramebufferTextureMultisampleMultiviewOVR");
            if (!glFramebufferTextureMultisampleMultiviewOVR)
            {
            	ANDROID_LOG("Can not get proc address for glFramebufferTextureMultisampleMultiviewOVR.\n");
            	//exit(EXIT_FAILURE);
            }

            //Use Unity to init Texture2DArray, easy to use in Unity.
//            GL_CHECK(glGenTextures(1, &frameBufferTextureId));
//            GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, frameBufferTextureId));
//            GL_CHECK(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
//            GL_CHECK(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
//            GL_CHECK(glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA32F, 1024, 1024, 2));

            GL_CHECK(glGenTextures(1, &frameBufferDepthTextureId));
            GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, frameBufferDepthTextureId));
            GL_CHECK(glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_DEPTH_COMPONENT24, 1024, 1024, 2));
            break;
        }
        case kUnityGfxDeviceEventShutdown:
        {
            s_RendererType = kUnityGfxRendererNull;
            //TODO: Destroy FBO
            break;
        }
        case kUnityGfxDeviceEventBeforeReset:
        {
            //No use now
            break;
        }
        case kUnityGfxDeviceEventAfterReset:
        {
            //No use now
            break;
        }
    };
}

//Use for Debug
static bool CheckFramebufferStatus()
{
	GLenum result = GL_CHECK(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER));
	if (result != GL_FRAMEBUFFER_COMPLETE)
	{
		ANDROID_LOG("Frambeuffer incomplete [%08x] with %d %d", result, frameBufferTextureId, frameBufferDepthTextureId);
		//GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
		return false;
	} else
	{
		ANDROID_LOG("Frambeuffer COMPLETE with %d %d", frameBufferTextureId, frameBufferDepthTextureId);
		return true;
	}
}

static void HackFrambuffer()
{
//	CheckFramebufferStatus();

	GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0));
//	CheckFramebufferStatus();

	GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0));
//	CheckFramebufferStatus();

	GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0));
//	CheckFramebufferStatus();

    if (antiAliasing > 1)
    {
        GL_CHECK(glFramebufferTextureMultisampleMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, frameBufferTextureId, 0, antiAliasing, 0, 2));
        //	CheckFramebufferStatus();
        GL_CHECK(glFramebufferTextureMultisampleMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, frameBufferDepthTextureId, 0, antiAliasing, 0, 2));
        //	CheckFramebufferStatus();
    }
    else
    {
        GL_CHECK(glFramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, frameBufferTextureId, 0, 0, 2));
        //	CheckFramebufferStatus();

        GL_CHECK(glFramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, frameBufferDepthTextureId, 0, 0, 2));
        CheckFramebufferStatus();
    }

	//Use Unity commandbuffer to clear
	//GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
}

// Plugin function to handle a specific rendering event
static void UNITY_INTERFACE_API OnRenderEvent(int eventID)
{
	switch ((UnityCameraEvent)eventID)
	{
		case BeforeDepthTexture:
		{
			ANDROID_LOG("BeforeDepthTexture");
			break;
		}
		case AfterDepthTexture:
		{
			ANDROID_LOG("AfterDepthTexture");
			break;
		}
		case BeforeDepthNormalsTexture:
		{
			ANDROID_LOG("BeforeDepthNormalsTexture");
			break;
		}
		case AfterDepthNormalsTexture:
		{
			ANDROID_LOG("AfterDepthNormalsTexture");
			break;
		}
		case BeforeGBuffer:
		{
			ANDROID_LOG("BeforeGBuffer");
			break;
		}
		case AfterGBuffer:
		{
			ANDROID_LOG("AfterGBuffer");
			break;
		}
		case BeforeLighting:
		{
			ANDROID_LOG("BeforeLighting");
			break;
		}
		case AfterLighting:
		{
			ANDROID_LOG("AfterLighting");
			break;
		}
		case BeforeFinalPass:
		{
			ANDROID_LOG("BeforeFinalPass");
			break;
		}
		case AfterFinalPass:
		{
			ANDROID_LOG("AfterFinalPass");
			break;
		}
		case BeforeForwardOpaque:
		{
			ANDROID_LOG("BeforeForwardOpaque");
			if (frameBufferTextureId > 0) HackFrambuffer();
			break;
		}
		case AfterForwardOpaque:
		{
			ANDROID_LOG("AfterForwardOpaque");
			break;
		}
		case BeforeImageEffectsOpaque:
		{
			ANDROID_LOG("BeforeImageEffectsOpaque");
			break;
		}
		case AfterImageEffectsOpaque:
		{
			ANDROID_LOG("AfterImageEffectsOpaque");
			break;
		}
		case BeforeSkybox:
		{
			ANDROID_LOG("BeforeSkybox");
			break;
		}
		case AfterSkybox:
		{
			ANDROID_LOG("AfterSkybox");
			break;
		}
		case BeforeForwardAlpha:
		{
			ANDROID_LOG("BeforeForwardAlpha");
			break;
		}
		case AfterForwardAlpha:
		{
			ANDROID_LOG("AfterForwardAlpha");
			break;
		}
		case BeforeImageEffects:
		{
			ANDROID_LOG("BeforeImageEffects");
			break;
		}
		case AfterImageEffects:
		{
			ANDROID_LOG("AfterImageEffects");
			break;
		}
		case AfterEverything:
		{
			ANDROID_LOG("AfterEverything");
			break;
		}
		case BeforeReflections:
		{
			ANDROID_LOG("BeforeReflections");
			break;
		}
		case AfterReflections:
		{
			ANDROID_LOG("AfterReflections");
			break;
		}
	}
//	PrintCurrentFrameBufferID();
}

//Used for debug
static void PrintCurrentFrameBufferID()
{
	GLint drawFboId = 0, type = 0, name = 0, width = 0, height = 0;
	GL_CHECK(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFboId));
	GL_CHECK(glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
			GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type));
	GL_CHECK(glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
				GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name));
//	GL_CHECK(glBindTexture(GL_TEXTURE_2D, name));
//	GL_CHECK(glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width));
//	GL_CHECK(glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height));
//	GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0));
	ANDROID_LOG("Current FBO : %d name %d type %08x width %d height %d", drawFboId, name, type, width, height);
}

// Freely defined function to pass a callback to plugin-specific scripts
extern "C" UnityRenderingEvent UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
    GetRenderEventFunc()
{
    return OnRenderEvent;
}

static void UNITY_INTERFACE_API OnTextureID(int textureID)
{
	frameBufferTextureId = textureID;
	ANDROID_LOG("frameBufferTextureId [%d]", frameBufferTextureId);
}

extern "C" UnityRenderingEvent UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
    GetTextureIDFunc()
{
    return OnTextureID;
}

extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
    SetAntiAliasingLevel(int level)
{
    antiAliasing = level;
}


text:
class Solution:
    # @param num, a list of integers
    # @return an integer
    def majorityElement(self, num):
        ret = {}
        for x in num:
            ret[x] = 1 if x not in ret else (ret[x] + 1)

        ret = sorted(ret.items(), key = lambda item:item[1], reverse = True)
        return ret[0][0]

# test
# num = [1, 2, 3, 4, 5, 3, 2, 3, 5, 6]
# solution = Solution()
# ret = solution.majorityElement(num)
# print ret


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;

namespace Dserv.Server
{
    class EmbeddedResourceHandler : IHandler
    {
        public string Title => null;

        public bool CanHandle(HttpListenerRequest request)
		{
            var path = request.RawUrl.TrimStart('/');
            return _resources.ContainsKey(path);
		}

        Dictionary<string, Resource> _resources;

        public IReadOnlyDictionary<string, Resource> Resources => _resources;

        public EmbeddedResourceHandler(IEnumerable<Assembly> assemblies)
        {
            _resources =
                (
                    from assembly in assemblies.Concat(new[] { Assembly.GetExecutingAssembly() })
                    from resourceName in assembly.GetManifestResourceNames()
                    select new Resource(assembly, resourceName)
                )
                .ToDictionary(x => x.UrlPath);
        }

        public async Task HandleAsync(HttpListenerContext context)
        {
            var request = context.Request;
            var response = context.Response;
            var path = request.RawUrl.TrimStart('/');

            var resource = _resources[path];
            await response.WriteStreamAsync(resource.Stream, resource.ResourceName);
            response.OutputStream.Close();
        }

    }
}


text:
#ifndef INSPECTORPROPERTYGRIDPAGE_H
#define INSPECTORPROPERTYGRIDPAGE_H

#include "../StdAfx.h"

using namespace Math;

class MyVariant : public wxVariantData {
	Vector3 m_vector3;
public:
	MyVariant(Vector3 v) : wxVariantData(), m_vector3(v) { }

	bool Eq(wxVariantData &data) const {
		MyVariant *value_ptr = dynamic_cast<MyVariant*>(&data);
		return (value_ptr != 0) && ((*value_ptr).m_vector3 == m_vector3);
	}
	wxString GetType() const { return wxString("MyVariant"); }

	Vector3 GetVector3() const { return m_vector3; }
};

WX_PG_DECLARE_VARIANT_DATA(Vector3);

class nsVector3Property : public wxPGProperty
{
	WX_PG_DECLARE_PROPERTY_CLASS(nsVector3Property)
public:
	nsVector3Property(const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, const Vector3& data = Vector3());
	virtual ~nsVector3Property();

	virtual wxVariant ChildChanged(wxVariant& thisValue, int childIndex, wxVariant& childValue) const;

	virtual void RefreshChildren(void);
};

//class InspectorPropertyController;
class InspectorPropertyGridPage : public wxPropertyGridPage
{
	DECLARE_EVENT_TABLE()

public:
	InspectorPropertyGridPage(Scene::ISceneNodeBase* node/*InspectorPropertyController* ctrl*/);

	~InspectorPropertyGridPage(void);

	void Populate(void);

protected:
	void CreateGeneralCategory(void);

	void CreateTransformCategory(void);

	void OnPropertyChanged(wxPropertyGridEvent& event);

private:
	//InspectorPropertyController* propertyCtrl;
	Scene::ISceneNodeBase* sceneNode;
	wxPGProperty* nameID;
	wxPGProperty* typeID;

	wxPGProperty* positionID;
	wxPGProperty* scaleID;
};

#endif


text:
import h from 'spec/spec_helper';
import { config } from 'azk';
import { init } from 'azk/cmds/info';
import { ManifestRequiredError } from 'azk/utils/errors';

describe("Azk command info, run in an", function() {
  var outputs = [];
  var UI  = h.mockUI(beforeEach, outputs);
  var cmd = init(UI);

  describe("invalid SoS dir", function() {
    it("should return error if not have manifest", function() {
      return h.tmp_dir().then((dir) => {
        cmd.cwd = dir;
        return h.expect(cmd.run()).to.rejectedWith(ManifestRequiredError);
      });
    });
  });

  describe("valid SoS dir", function() {
    var manifest;

    before(() => {
      var data = { };
      return h.mockManifest(data).then((mf) => {
        manifest = mf;
      });
    });

    it("should show systems information", function() {
      cmd.cwd = manifest.manifestPath;
      return cmd.run().then(() => {
        var rx_manifest = RegExp("manifest:.*" + h.escapeRegExp(manifest.file));
        h.expect(outputs[0]).to.match(rx_manifest);

        var rx_cache = RegExp("cache_dir:.*" + h.escapeRegExp(manifest.cache_dir));
        h.expect(outputs[0]).to.match(rx_cache);

        var rx_default = RegExp("default_system:.*" + h.escapeRegExp(manifest.default_system));
        h.expect(outputs[0]).to.match(rx_default);

        var rx_name = RegExp(`${h.escapeRegExp("example".yellow)}:`)
        h.expect(outputs[0]).to.match(rx_name);

        h.expect(outputs[0]).to.match(RegExp(config('docker:image_default')));
        h.expect(outputs[0]).to.match(/command:.*socat/);
      });
    });
  });
});


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace RagnarokWeb {

    public partial class PortalCadastro {

        /// <summary>
        /// usernamecp control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox usernamecp;

        /// <summary>
        /// username control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox username;

        /// <summary>
        /// email control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox email;

        /// <summary>
        /// senha control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox senha;

        /// <summary>
        /// btnCadastrar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCadastrar;
    }
}


text:
#include "base/os.h"
#include <sys/socket.h>

#include <net/if.h>

#ifdef __linux__
#include <linux/netlink.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#endif

#ifdef __FreeBSD__
#include <sys/sockio.h>
#include <ifaddrs.h>
#endif

#include "testing/gunit.h"

#include <base/logging.h>
#include <io/event_manager.h>
#include <tbb/task.h>
#include <base/task.h>

#include <cmn/agent_cmn.h>
#include <init/agent_init.h>
#include <cmn/agent_factory.h>
#include <init/agent_param.h>

#include "oper/operdb_init.h"
#include "controller/controller_init.h"
#include "pkt/pkt_init.h"
#include "services/services_init.h"
#include "vrouter/ksync/ksync_init.h"
#include "oper/interface_common.h"
#include "test_cmn_util.h"
#include "vr_types.h"
#include "oper/crypt_tunnel.h"

#define VNSW_CRYPT_CONFIG_FILE "controller/src/vnsw/agent/test/vnswa_crypt_cfg.ini"

void RouterIdDepInit(Agent *agent) {
}

class CryptTunnelConfigTest : public ::testing::Test {
public:
    virtual void SetUp() {
        agent = Agent::GetInstance();
        PhysicalInterface::CreateReq(agent->interface_table(),
                                     "ipsec0", agent->fabric_vrf_name(),
                                     PhysicalInterface::FABRIC,
                                     PhysicalInterface::ETHERNET, false,
                                     boost::uuids::nil_uuid(), Ip4Address(0),
                                     Interface::TRANSPORT_ETHERNET);
    }

    bool WaitForAWhile(time_t target) {
        time_t now = time(NULL);
        return now >= target;
    }

    virtual void TearDown() {
    }

    CryptTunnelEntry *FindCryptTunnelEntry(const std::string &remote_ip) {
        CryptTunnelTable *table = agent->crypt_tunnel_table();
        return table->Find(remote_ip);
    }

protected:
    static const int kTimeoutSeconds = 15;
    Agent *agent;
};

struct CryptTunnel {
    std::string remote_ip;
    bool crypt;
};

TEST_F(CryptTunnelConfigTest, Basic) {
    // Create two tunnels
    struct EncryptTunnelEndpoint endpoints[] = {
        {"2.2.2.11"},
        {"2.2.2.12"}
    };
    unsigned int num_endpoints = sizeof(endpoints)/sizeof(EncryptTunnelEndpoint);
    EXPECT_TRUE(agent->crypt_tunnel_table()->Size() == 0);

    // Create VR to VR encryption, add the global vrouter configration
    AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "all");
    client->WaitForIdle();
    WAIT_FOR(100, 100, agent->crypt_tunnel_table()->Size() == num_endpoints);
    CryptTunnelEntry *entry;
    entry = agent->crypt_tunnel_table()->Find(endpoints[0].ip);
    EXPECT_TRUE(entry != NULL);

    // Check for encryption
    EXPECT_TRUE(entry->GetVRToVRCrypt() == true);
    // Tunnel should be available
    client->WaitForIdle();
    WAIT_FOR(2000, 1000, entry->GetTunnelAvailable());

    // Change and check for encryption false
    AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "none");
    client->WaitForIdle();
    WAIT_FOR(2000, 1000, entry->GetTunnelAvailable());
    WAIT_FOR(2000, 100, (entry = agent->crypt_tunnel_table()->Find(endpoints[1].ip)) != NULL);
    WAIT_FOR(200, 100, (entry->GetVRToVRCrypt() == false));

    // Change and check for encryption true
    AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "all");
    WAIT_FOR(2000, 100, (entry = agent->crypt_tunnel_table()->Find(endpoints[0].ip)) != NULL);
    WAIT_FOR(200, 100, (entry->GetVRToVRCrypt() == true));

    // Delete all entries
    for (unsigned int id = 0; id < num_endpoints; id++) {
        agent->crypt_tunnel_table()->Delete(endpoints[id].ip);
    }
    client->WaitForIdle();
    // Wait for deletion of tunnel entries
    //WAIT_FOR(2000, 100, agent->crypt_tunnel_table()->Size() == 0);

    // Delete configuration
    DeleteGlobalVrouterConfig();
}

int main(int argc, char **argv) {

    GETUSERARGS();
    client = TestInit(VNSW_CRYPT_CONFIG_FILE, ksync_init, false, false, false);
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    usleep(10000);

    TestShutdown();
    delete client;
    return ret;
}


text:
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject

class ErpJournalEntry(IdentifiedObject):
    """Details of an individual entry in a journal, which is to be posted to a ledger on the posting date.Details of an individual entry in a journal, which is to be posted to a ledger on the posting date.
    """

    def __init__(self, transactionDateTime='', sourceID='', postingDateTime='', amount=0.0, accountID='', status=None, ErpPayableLineItems=None, ErpInvoiceLineItem=None, ErpRecLineItems=None, ErpLedgerEntry=None, CostTypes=None, ErpJournal=None, *args, **kw_args):
        """Initialises a new 'ErpJournalEntry' instance.

        @param transactionDateTime: Date and time journal entry was recorded.
        @param sourceID: The identifer of the source for this entry.
        @param postingDateTime: Date and time this entry is to be posted to the ledger.
        @param amount: The amount of the debit or credit for this account.
        @param accountID: Account identifier for this entry.
        @param status:
        @param ErpPayableLineItems:
        @param ErpInvoiceLineItem:
        @param ErpRecLineItems:
        @param ErpLedgerEntry:
        @param CostTypes:
        @param ErpJournal:
        """
        #: Date and time journal entry was recorded.
        self.transactionDateTime = transactionDateTime

        #: The identifer of the source for this entry.
        self.sourceID = sourceID

        #: Date and time this entry is to be posted to the ledger.
        self.postingDateTime = postingDateTime

        #: The amount of the debit or credit for this account.
        self.amount = amount

        #: Account identifier for this entry.
        self.accountID = accountID

        self.status = status

        self._ErpPayableLineItems = []
        self.ErpPayableLineItems = [] if ErpPayableLineItems is None else ErpPayableLineItems

        self._ErpInvoiceLineItem = None
        self.ErpInvoiceLineItem = ErpInvoiceLineItem

        self._ErpRecLineItems = []
        self.ErpRecLineItems = [] if ErpRecLineItems is None else ErpRecLineItems

        self._ErpLedgerEntry = None
        self.ErpLedgerEntry = ErpLedgerEntry

        self._CostTypes = []
        self.CostTypes = [] if CostTypes is None else CostTypes

        self._ErpJournal = None
        self.ErpJournal = ErpJournal

        super(ErpJournalEntry, self).__init__(*args, **kw_args)

    _attrs = ["transactionDateTime", "sourceID", "postingDateTime", "amount", "accountID"]
    _attr_types = {"transactionDateTime": str, "sourceID": str, "postingDateTime": str, "amount": float, "accountID": str}
    _defaults = {"transactionDateTime": '', "sourceID": '', "postingDateTime": '', "amount": 0.0, "accountID": ''}
    _enums = {}
    _refs = ["status", "ErpPayableLineItems", "ErpInvoiceLineItem", "ErpRecLineItems", "ErpLedgerEntry", "CostTypes", "ErpJournal"]
    _many_refs = ["ErpPayableLineItems", "ErpRecLineItems", "CostTypes"]

    status = None

    def getErpPayableLineItems(self):

        return self._ErpPayableLineItems

    def setErpPayableLineItems(self, value):
        for p in self._ErpPayableLineItems:
            filtered = [q for q in p.ErpJournalEntries if q != self]
            self._ErpPayableLineItems._ErpJournalEntries = filtered
        for r in value:
            if self not in r._ErpJournalEntries:
                r._ErpJournalEntries.append(self)
        self._ErpPayableLineItems = value

    ErpPayableLineItems = property(getErpPayableLineItems, setErpPayableLineItems)

    def addErpPayableLineItems(self, *ErpPayableLineItems):
        for obj in ErpPayableLineItems:
            if self not in obj._ErpJournalEntries:
                obj._ErpJournalEntries.append(self)
            self._ErpPayableLineItems.append(obj)

    def removeErpPayableLineItems(self, *ErpPayableLineItems):
        for obj in ErpPayableLineItems:
            if self in obj._ErpJournalEntries:
                obj._ErpJournalEntries.remove(self)
            self._ErpPayableLineItems.remove(obj)

    def getErpInvoiceLineItem(self):

        return self._ErpInvoiceLineItem

    def setErpInvoiceLineItem(self, value):
        if self._ErpInvoiceLineItem is not None:
            filtered = [x for x in self.ErpInvoiceLineItem.ErpJournalEntries if x != self]
            self._ErpInvoiceLineItem._ErpJournalEntries = filtered

        self._ErpInvoiceLineItem = value
        if self._ErpInvoiceLineItem is not None:
            if self not in self._ErpInvoiceLineItem._ErpJournalEntries:
                self._ErpInvoiceLineItem._ErpJournalEntries.append(self)

    ErpInvoiceLineItem = property(getErpInvoiceLineItem, setErpInvoiceLineItem)

    def getErpRecLineItems(self):

        return self._ErpRecLineItems

    def setErpRecLineItems(self, value):
        for p in self._ErpRecLineItems:
            filtered = [q for q in p.ErpJournalEntries if q != self]
            self._ErpRecLineItems._ErpJournalEntries = filtered
        for r in value:
            if self not in r._ErpJournalEntries:
                r._ErpJournalEntries.append(self)
        self._ErpRecLineItems = value

    ErpRecLineItems = property(getErpRecLineItems, setErpRecLineItems)

    def addErpRecLineItems(self, *ErpRecLineItems):
        for obj in ErpRecLineItems:
            if self not in obj._ErpJournalEntries:
                obj._ErpJournalEntries.append(self)
            self._ErpRecLineItems.append(obj)

    def removeErpRecLineItems(self, *ErpRecLineItems):
        for obj in ErpRecLineItems:
            if self in obj._ErpJournalEntries:
                obj._ErpJournalEntries.remove(self)
            self._ErpRecLineItems.remove(obj)

    def getErpLedgerEntry(self):

        return self._ErpLedgerEntry

    def setErpLedgerEntry(self, value):
        if self._ErpLedgerEntry is not None:
            self._ErpLedgerEntry._ErpJounalEntry = None

        self._ErpLedgerEntry = value
        if self._ErpLedgerEntry is not None:
            self._ErpLedgerEntry.ErpJounalEntry = None
            self._ErpLedgerEntry._ErpJounalEntry = self

    ErpLedgerEntry = property(getErpLedgerEntry, setErpLedgerEntry)

    def getCostTypes(self):

        return self._CostTypes

    def setCostTypes(self, value):
        for p in self._CostTypes:
            filtered = [q for q in p.ErpJournalEntries if q != self]
            self._CostTypes._ErpJournalEntries = filtered
        for r in value:
            if self not in r._ErpJournalEntries:
                r._ErpJournalEntries.append(self)
        self._CostTypes = value

    CostTypes = property(getCostTypes, setCostTypes)

    def addCostTypes(self, *CostTypes):
        for obj in CostTypes:
            if self not in obj._ErpJournalEntries:
                obj._ErpJournalEntries.append(self)
            self._CostTypes.append(obj)

    def removeCostTypes(self, *CostTypes):
        for obj in CostTypes:
            if self in obj._ErpJournalEntries:
                obj._ErpJournalEntries.remove(self)
            self._CostTypes.remove(obj)

    def getErpJournal(self):

        return self._ErpJournal

    def setErpJournal(self, value):
        if self._ErpJournal is not None:
            filtered = [x for x in self.ErpJournal.ErpJournalEntries if x != self]
            self._ErpJournal._ErpJournalEntries = filtered

        self._ErpJournal = value
        if self._ErpJournal is not None:
            if self not in self._ErpJournal._ErpJournalEntries:
                self._ErpJournal._ErpJournalEntries.append(self)

    ErpJournal = property(getErpJournal, setErpJournal)


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Search — PPIDS Academy 2.0 documentation</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.3.6/cerulean/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/my-styles.css" type="text/css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="top" title="PPIDS Academy 2.0 documentation" href="index.html" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          PPIDS-UGM
        05.16

  PPIDS-Academy

Materi Hari 1

Github Social Coding

Tentang Git

Menggunakan Github

Bekerja dengan Repository

Instalasi pada Windows

Bekerja dengan Github

Melakukan kloning repository

What’s Next?

Kolaborasi Project dengan Github

Memahami alur kerja Github

Kolaborasi Project

Melakukan Forking Repository

Pengaturan Remote

Membuat Pull Request

What’s Next?

Rujukan

Materi Hari 2

Bekerja dengan Bootstrap

Mengenal Bootstrap

Memanggil Bootstrap

Berlatih dengan Bootstrap

Komponen Bootstrap

Rujukan

Peta Online dengan Leaflet

Tentang Leaflet

Memanggil Leaflet

Berlatih dengan Leaflet

Komponen Leaflet

What’s Next?

Rujukan

Lisensi Dokumen (GFDL V.1.3)

  Halaman ini

Materi Hari 1

Materi Hari 2

Lisensi Dokumen (GFDL V.1.3)

Materi Hari 1

Materi Hari 2

Lisensi Dokumen (GFDL V.1.3)

Search

    Please activate JavaScript to enable the search
    functionality.

    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.

  <form class="form-inline" action="" method="get">

      <input type="text" class="form-control" name="q" value="" />

    <input type="submit" class="btn btn-default" value="search" />

  </form>

      Back to top

        © Copyright 2016, DanyLaksono.

      Created using Sphinx 1.4.1.


text:
import MockSpark from '@ciscospark/test-helper-mock-spark';
import {assert} from '@ciscospark/test-helper-chai';
import sinon from '@ciscospark/test-helper-sinon';
import {cloneDeep} from 'lodash';
import deviceFixture from '../lib/device-fixture';
import Device from '@ciscospark/internal-plugin-wdm';

describe('plugin-wdm', () => {
  describe('FeaturesModel', () => {
    let spark;
    let deviceFeaturesChangeDeveloperSpy;
    let deviceChangeFeaturesDeveloperSpy;
    let deviceChangeFeaturesSpy;
    let deviceChangeSpy;
    let sparkChangeSpy;
    let sparkChangeDeviceSpy;
    let sparkChangeDeviceFeaturesSpy;
    let sparkChangeDeviceFeaturesDeveloperSpy;

    beforeEach(() => {
      spark = new MockSpark({
        children: {
          device: Device
        }
      });

      spark.internal.device._processRegistrationSuccess({body: cloneDeep(deviceFixture)});

      deviceFeaturesChangeDeveloperSpy = sinon.spy();
      deviceChangeFeaturesDeveloperSpy = sinon.spy();
      deviceChangeFeaturesSpy = sinon.spy();
      deviceChangeSpy = sinon.spy();
      sparkChangeSpy = sinon.spy();
      sparkChangeDeviceSpy = sinon.spy();
      sparkChangeDeviceFeaturesSpy = sinon.spy();
      sparkChangeDeviceFeaturesDeveloperSpy = sinon.spy();

      spark.internal.device.features.on('change:developer', deviceFeaturesChangeDeveloperSpy);
      spark.internal.device.on('change:features.developer', deviceChangeFeaturesDeveloperSpy);
      spark.internal.device.on('change:features', deviceChangeFeaturesSpy);
      spark.internal.device.on('change', deviceChangeSpy);
      spark.on('change', sparkChangeSpy);
      spark.on('change:internal.device', sparkChangeDeviceSpy);
      spark.on('change:internal.device.features', sparkChangeDeviceFeaturesSpy);
      spark.on('change:internal.device.features.developer', sparkChangeDeviceFeaturesDeveloperSpy);
    });

    describe('when a feature is added', () => {
      it('emits a change event', () => {
        spark.internal.device.features.developer.add({
          key: 'another-developer-feature',
          val: 'true',
          value: true,
          mutable: false
        });

        assert.calledOnce(deviceFeaturesChangeDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesSpy);
        assert.calledOnce(deviceChangeSpy);
        assert.calledOnce(sparkChangeSpy);
        assert.calledOnce(sparkChangeDeviceSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesDeveloperSpy);
      });
    });

    describe('when a feature changes', () => {
      it('emits a change event', () => {
        const data = cloneDeep(deviceFixture);
        data.features.developer[1] = {
          key: 'another-feature',
          val: 'false',
          value: false,
          mutable: false
        };
        spark.internal.device._processRegistrationSuccess({body: data});

        assert.calledOnce(deviceFeaturesChangeDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesSpy);
        assert.calledOnce(deviceChangeSpy);
        assert.calledOnce(sparkChangeSpy);
        assert.calledOnce(sparkChangeDeviceSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesDeveloperSpy);
      });
    });

    describe('when a feature is removed', () => {
      it('emits a change event', () => {
        const data = cloneDeep(deviceFixture);
        data.features.developer.pop();
        spark.internal.device._processRegistrationSuccess({body: data});

        assert.calledOnce(deviceFeaturesChangeDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesDeveloperSpy);
        assert.calledOnce(deviceChangeFeaturesSpy);
        assert.calledOnce(deviceChangeSpy);
        assert.calledOnce(sparkChangeSpy);
        assert.calledOnce(sparkChangeDeviceSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesSpy);
        assert.calledOnce(sparkChangeDeviceFeaturesDeveloperSpy);
      });
    });
  });
});


text:
package com.matt.forgehax.mods;

import com.matt.forgehax.asm.reflection.FastReflection;
import com.matt.forgehax.events.RenderEvent;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.block.material.Material;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.RenderBlockOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@RegisterMod
public class AntiOverlayMod extends ToggleMod {

  public AntiOverlayMod() {
    super(Category.PLAYER, "AntiOverlay", false, "Removes screen overlays");
  }

  /**
   * Disables water/lava fog
   */
  @SubscribeEvent
  public void onFogRender(EntityViewRenderEvent.FogDensity event) {
    if (event.getState().getMaterial().equals(Material.WATER)
        || event.getState().getMaterial().equals(Material.LAVA)) {
      event.setDensity(0);
      event.setCanceled(true);
    }
  }

  /**
   * Disables screen overlays
   */
  @SubscribeEvent
  public void onRenderBlockOverlay(RenderBlockOverlayEvent event) {
    event.setCanceled(true);
  }

  @SubscribeEvent
  public void onRenderGameOverlay(RenderGameOverlayEvent event) {
    if (event.getType().equals(RenderGameOverlayEvent.ElementType.HELMET)
        || event.getType().equals(RenderGameOverlayEvent.ElementType.PORTAL)) {
      event.setCanceled(true);
    }
  }

  @SubscribeEvent
  public void onRender(RenderEvent event) {
    ItemStack item = FastReflection.Fields.EntityRenderer_itemActivationItem.get(MC.entityRenderer);

    if (item != null && item.getItem() == Items.TOTEM_OF_UNDYING) {
      FastReflection.Fields.EntityRenderer_itemActivationItem.set(MC.entityRenderer, null);
    }
  }
}


text:
from __future__ import unicode_literals

from datetime import datetime
from PIL import ExifTags, Image

def get_exif_data_from_file(image_file):
    try:
        image_file.seek(0)

        try:
            img = Image.open(image_file)
            exif_data = img._getexif()
        except AttributeError:
            # Processing PNGs gets us here.
            return None
        finally:
            image_file.seek(0)

        if exif_data is None:
            # Take a JPEG, and remove Exif data from it (e.g. jhead
            # -purejpg myfile.jpg) to end up here.
            return None

        return {
            ExifTags.TAGS[k]: v
            for k, v in exif_data.items()
            if k in ExifTags.TAGS
        }
    except IOError:
        image_file.seek(0)
        return None

def is_valid_image(image_file):
    try:
        image_file.seek(0)
        Image.open(image_file)
        return True
    except IOError:
        return False
    finally:
        image_file.seek(0)

def get_date_taken_from_exif(exif):
    if not exif or 'DateTimeOriginal' not in exif:
        return None

    try:
        date_part = exif['DateTimeOriginal']
        resolved = datetime.strptime(
            date_part,
            '%Y:%m:%d %H:%M:%S'
        )
        return resolved
    except ValueError:
        return None

def gps_location_to_degrees(gps):
    parts = [float(x)/float(y) for x, y in gps]
    return parts[0] + parts[1]/60 + parts[2]/3600

def gps_latitude_to_degrees(gps, type):
    lat = gps_location_to_degrees(gps)

    if type == 'S':
        lat = -lat

    return lat

def gps_longitude_to_degrees(gps, type):
    lon = gps_location_to_degrees(gps)

    if type == 'W':
        lon = -lon

    return lon


text:
@interface DYMTLAnalyzerFinding : DYAnalyzerFinding
{
}

- (id)_simplifiedDetailsStringSubstituted:(id)arg1 plural:(BOOL)arg2;
- (BOOL)isTextureImageCompletelyUpdated;
- (BOOL)isBufferDataCompletelyUpdated;
- (BOOL)isInefficientStateUpdate;
- (BOOL)isRedundantCallOrQuery;
- (BOOL)isRedundantCall;
- (BOOL)isFrameStatistics;
- (BOOL)isDataRestoreUnnecessaryForFunc:(const struct Function *)arg1 targetArgIndex:(int)arg2 objectType:(unsigned int)arg3 analyzerEngine:(id)arg4;
- (id)localizedKind;
- (id)synopsis;

@end


text:
Bug #63066 (Calling an undefined method in a generator results in a seg fault)
--FILE--
<?php
function gen($o)
{
	yield 'foo';
	$o->fatalError();
}

foreach(gen(new stdClass()) as $value)
	echo $value, "\n";
--EXPECTF--
foo

Fatal error: Call to undefined method stdClass::fatalError() in %sbug63066.php on line 5


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listitem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/generic_clicked_states"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/item_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".5"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="40dp"
            android:layout_height="30dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp" />

        <TextView
            android:id="@+id/item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold" />
    </LinearLayout>

    <TextView
        android:id="@+id/amount"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:gravity="center" />

    <TextView
        android:id="@+id/percentage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:gravity="center" />

</LinearLayout>


text:
<?php
namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ReserveLRepository extends EntityRepository
{
    public function colision($id, $deb, $fin, $date)
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT r.id FROM AcmeStoreBundle:ReserveL r '
              . 'WHERE r.perioded <= :fin AND r.periodef >= :deb '
              . 'AND r.date = :date AND r.local = :id'
            )
            ->setParameter('id', $id)
            ->setParameter('deb', $deb)
            ->setParameter('fin', $fin)
            ->setParameter('date', $date)
            ->getResult();
    }
    public function reservation($id)
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT r FROM AcmeStoreBundle:ReserveL r '
              . 'WHERE r.user = :id ORDER BY r.date'
            )
            ->setParameter('id', $id)
            ->getResult();
    }
    public function horraire()//$day
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT r FROM AcmeStoreBundle:ReserveL r '
              //. 'WHERE DAYOFWEEK(r.date) = ":day" '
              . 'ORDER BY r.local, r.date, r.perioded'
            )
            //->setParameter('day', $day)
            ->getResult();

    }
    //Suppresion
    public function delete()
    {
        return $this->getEntityManager()
            ->createQuery(
                'DELETE FROM AcmeStoreBundle:ReserveL'
            )
            ->getResult();
    }
    public function annuler($id)
    {
        return $this->getEntityManager()
            ->createQuery(
                'DELETE FROM AcmeStoreBundle:ReserveL as r '
              . 'WHERE r.id = :id'
            )
            ->setParameter('id', $id)
            ->getResult();
    }
}


text:
> Cache object that can transform values when setting.

## Install
## Install with [npm](npmjs.org)

```bash
npm i transform-cache --save
```

## Run tests

```bash
npm test
```

## Usage

```js
var Cache = require('transform-cache');
```

## API
### [Cache](index.js#L31)

Create a cache that transforms values when setting.

* `cache` **{Object}**: Object to store the cache on.
* `options` **{Object}**

```js
function makeKey = function (key) { return key.toUpperCase(); };
function transform = function (value) { return value.toUpperCase(); };

var cache = new Cache(makeKey, tranform);
```

### [.set](index.js#L57)

Set a value on the cache. The value will be passed through the transform function before setting.

* `key` **{String}**: Key used to set the value on the cache.
* `value` **{Mixed}**: Value that gets set on the cache after being transformed.

```js
cache.set('foo', 'bar');
//=> { 'FOO': 'BAR' }
```

### [.get](index.js#L74)

Get a value from the cache.

* `key` **{String}**: Key used to lookup the value.
* `returns` **{Mixed}**: Value returned by the key.

```js
var bar = cache.get('foo');
//=> BAR
```

## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/doowb/transform-cache/issues)

## Author

**Brian Woodward**

+ [github/doowb](https://github.com/doowb)
+ [twitter/doowb](http://twitter.com/doowb)

## License
Copyright (c) 2015 Brian Woodward
Released under the MIT license

***

_This file was generated by [verb](https://github.com/assemble/verb) on February 03, 2015._


text:
package com.cube.storm.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ProgressBar;
import com.cube.storm.UiSettings;
import com.cube.storm.ui.data.ContentSize;
import com.cube.storm.ui.lib.helper.ImageHelper;
import com.cube.storm.ui.model.property.AnimationFrame;
import com.cube.storm.ui.model.property.AnimationImageProperty;
import com.cube.storm.ui.model.property.ImageProperty;
import com.cube.storm.ui.model.property.SpotlightImageProperty;
import com.cube.storm.ui.model.property.TextProperty;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

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

/**
 * Augmented image view which uses the UniveralImageLoader library to display images and handles Storm animations.
 * <p/>
 *
 * @author Tim Matthews
 * @Project LightningUi
 */
public class ImageView extends androidx.appcompat.widget.AppCompatImageView
{
	/**
	 * Listener alerted whenever the animation frame changes.
	 */
	public interface OnAnimationFrameChangeListener
	{
		public void onAnimationFrameChange(ImageView imageView, int frameIndex, AnimationImageProperty frame);
		public void onAnimationFrameChange(ImageView imageView, int frameIndex, SpotlightImageProperty frame);
	}

	/**
	 * Handler used to control animations. Null until an animation is explicitly
	 */
	private Handler animator = null;

	/**
	 * Runnable used to update the current frame. Null until an animation is explicitly
	 */
	private Runnable displayNextFrame = null;

	public ImageView(Context context)
	{
		super(context);
	}

	public ImageView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	public ImageView(Context context, AttributeSet attrs, int defStyleAttr)
	{
		super(context, attrs, defStyleAttr);
	}

	@Override protected void onDetachedFromWindow()
	{
		super.onDetachedFromWindow();

		if (animator != null)
		{
			animator.removeCallbacks(displayNextFrame);
		}
	}

	@Override protected void onAttachedToWindow()
	{
		super.onAttachedToWindow();

		if (animator != null)
		{
			animator.post(displayNextFrame);
		}
	}

	/**
	 * Alternately display each of a sequence of Storm animation frames.
	 *
	 * @param frames
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 */
	public void populate(@Nullable final AnimationImageProperty frames)
	{
		populate(frames, null);
	}

	/**
	 * Alternately display each of a sequence of Storm animation frames.
	 *
	 * @param frames
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 */
	public void populate(@Nullable final AnimationImageProperty frames, @Nullable final TextProperty accessibilityLabel)
	{
		populate(frames, accessibilityLabel, null);
	}

	/**
	 * Alternately display each of a sequence of Storm animation frames, alerting an optional listener whenever the
	 * frame changes.
	 *
	 * @param imageProperty If null, the current image is cleared and all pending animation tasks are cancelled.
	 * @param listener
	 */
	public void populate(@Nullable final AnimationImageProperty imageProperty, @Nullable final TextProperty accessibilityLabel, @Nullable final OnAnimationFrameChangeListener listener)
	{
		// Cancel all current loading tasks
		populate((ArrayList<ImageProperty>)null);

		if (imageProperty != null)
		{
			if (animator == null)
			{
				animator = new Handler();
			}

			displayNextFrame = new Runnable()
			{
				private int frameIndex = 0;

				@Override public void run()
				{
					AnimationFrame frame = imageProperty.getFrames().get(frameIndex % imageProperty.getFrames().size());
					populateFrame(frame.getImage(), accessibilityLabel, null, null);

					if (listener != null)
					{
						listener.onAnimationFrameChange(ImageView.this, frameIndex % imageProperty.getFrames().size(), imageProperty);
					}

					++frameIndex;

					if (imageProperty.getFrames().size() > 1)
					{
						animator.postDelayed(this, frame.getDelay());
					}
				}
			};
		}
	}

	/**
	 * Alternately display each of a sequence of Storm spotlight frames, updating a text view to display the spotlight
	 * text whenever it changes.
	 *
	 * @param frames
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 * @param textView
	 * 		{@link TextView#populate(com.cube.storm.ui.model.property.TextProperty, com.cube.storm.ui.model.property.LinkProperty)}
	 * 		will be called with the relevant details each time the spotlight changes.
	 */
	public void populate(@Nullable final List<? extends SpotlightImageProperty> frames, final @NonNull TextView textView)
	{
		populate(frames, new OnAnimationFrameChangeListener()
		{
			@Override public void onAnimationFrameChange(ImageView imageView, int frameIndex, AnimationImageProperty frame)
			{
			}

			@Override public void onAnimationFrameChange(ImageView imageView, int frameIndex, SpotlightImageProperty frame)
			{
				textView.populate(frame.getText(), frame.getLink());
			}
		});
	}

	/**
	 * Alternately display each of a sequence of Storm spotlight frames, updating a text view to display the spotlight
	 * text whenever it changes.
	 *
	 * @param frames
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 * @param listener
	 * 		The listener for frame change
	 */
	public void populate(@Nullable final List<? extends SpotlightImageProperty> frames, @Nullable final OnAnimationFrameChangeListener listener)
	{
		// Cancel all current loading tasks
		populate((ArrayList<ImageProperty>)null);

		if (frames != null)
		{
			if (animator == null)
			{
				animator = new Handler();
			}

			displayNextFrame = new Runnable()
			{
				private int frameIndex = 0;

				@Override public void run()
				{
					SpotlightImageProperty frame = frames.get(frameIndex % frames.size());
					populateFrame(frame.getImage(), frame.getAccessibilityLabel(), null, null);

					if (listener != null)
					{
						listener.onAnimationFrameChange(ImageView.this, frameIndex % frames.size(), frames.get(frameIndex % frames.size()));
					}

					++frameIndex;

					if (frames.size() > 1)
					{
						animator.postDelayed(this, frame.getDelay());
					}
				}
			};
		}
	}

	/**
	 * Load and display the specified image asynchronously.
	 *
	 * @param image
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 */
	public void populate(@Nullable final ArrayList<ImageProperty> image)
	{
		populate(image, null);
	}

	/**
	 * Load and display the specified image asynchronously.
	 *
	 * @param image
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 */
	public void populate(@Nullable final ArrayList<ImageProperty> image, @Nullable final TextProperty accessibilityLabel)
	{
		populate(image, accessibilityLabel, null);
	}

	/**
	 * Load and display the specified image asynchronously, with an optional progress bar visible until the image is
	 * loaded.
	 *
	 * @param image
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 * @param progress
	 */
	public void populate(@Nullable final ArrayList<ImageProperty> image, @Nullable final TextProperty accessibilityLabel, @Nullable final ProgressBar progress)
	{
		populate(image, accessibilityLabel, progress, null);
	}

	/**
	 * Load and display the specified image asynchronously, with an optional progress bar visible until the image is
	 * loaded.
	 *
	 * @param image
	 * 		If null, the current image is cleared and all pending animation tasks are cancelled.
	 * @param progress
	 * @param listener
	 *      If provided then the listener will receive callbacks at each stage of the image frame being loaded
	 */
	public void populate(@Nullable final ArrayList<ImageProperty> image, @Nullable final TextProperty accessibilityLabel, @Nullable final ProgressBar progress, @Nullable final ImageLoadingListener listener)
	{
		// If image size isnt calculated yet, wait till it has
		if (getWidth() == 0 && getHeight() == 0 && image != null && getVisibility() != GONE && UiSettings.getInstance().getContentSize() == ContentSize.AUTO)
		{
			getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
			{
				@Override public boolean onPreDraw()
				{
					getViewTreeObserver().removeOnPreDrawListener(this);

					if (getWidth() == 0 && getHeight() == 0)
					{
						// fuck android
						populateFrame(image, accessibilityLabel, progress, listener);
						return false;
					}

					populate(image, accessibilityLabel, progress, listener);
					return false;
				}
			});

			return;
		}

		// The user is explicitly setting a static image so cancel the animation task
		if (animator != null && displayNextFrame != null)
		{
			animator.removeCallbacks(displayNextFrame);
		}

		populateFrame(image, accessibilityLabel, progress, listener);
	}

	/**
	 * Used internally by all other image population tasks.
	 *
	 * @param image
	 * @param progress
	 */
	private void populateFrame(
		@Nullable final ArrayList<ImageProperty> image,
		@Nullable TextProperty accessibilityLabel,
		@Nullable final ProgressBar progress,
		@Nullable final ImageLoadingListener listener
	)
	{
		UiSettings.getInstance().getImageLoader().cancelDisplayTask(this);

		if (image != null && image.size() > 0)
		{
			if (accessibilityLabel == null)
			{
				// no explicit accessibility label provided. See if the images themselves have one...
				// we will choose an image to take the label from arbitrarily
				// all the images have the same label anyway for all Storm apps using the LegacyImageViewProcessor
				accessibilityLabel = image.get(0).getAccessibilityLabel();
			}

			// Set accessibility label (content description) on images
			String accessibilityLabelText = UiSettings.getInstance().getTextProcessor().process(accessibilityLabel);
			if (!TextUtils.isEmpty(accessibilityLabelText))
			{
				setContentDescription(accessibilityLabelText);
				setFocusable(true);
			}
			else
			{
				setContentDescription(null);
				setFocusable(false);
			}

			ImageHelper.displayImage(this, image, new SimpleImageLoadingListener()
			{
				@Override public void onLoadingStarted(String imageUri, View view)
				{
					if (listener != null)
					{
						listener.onLoadingStarted(imageUri, view);
					}

					if (animator == null)
					{
						setVisibility(View.INVISIBLE);
					}

					if (progress != null)
					{
						progress.setVisibility(View.VISIBLE);
					}
				}

				@Override public void onLoadingFailed(String imageUri, View view, FailReason failReason)
				{
					if (listener != null)
					{
						listener.onLoadingFailed(imageUri, view, failReason);
					}

					setVisibility(View.GONE);
					if (progress != null)
					{
						progress.setVisibility(View.GONE);
					}
				}

				@Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
				{
					if (listener != null)
					{
						listener.onLoadingComplete(imageUri, view, loadedImage);
					}

					setVisibility(View.VISIBLE);
					if (progress != null)
					{
						progress.setVisibility(View.GONE);
					}
				}
			});
		}
		else
		{
			setImageBitmap(null);
			setVisibility(View.GONE);
			setContentDescription(null);
			setFocusable(false);
		}
	}
}