text:
package org.symptomcheck.capstone;

import android.accounts.Account;
import android.annotation.TargetApi;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.activeandroid.query.Update;
import com.google.common.collect.Lists;

import org.symptomcheck.capstone.bus.DownloadEvent;
import org.symptomcheck.capstone.dao.DAOManager;
import org.symptomcheck.capstone.model.CheckIn;
import org.symptomcheck.capstone.model.Doctor;
import org.symptomcheck.capstone.model.PainMedication;
import org.symptomcheck.capstone.model.Patient;
import org.symptomcheck.capstone.model.PatientExperience;
import org.symptomcheck.capstone.model.Question;
import org.symptomcheck.capstone.model.UserInfo;
import org.symptomcheck.capstone.model.UserType;
import org.symptomcheck.capstone.network.DownloadHelper;
import org.symptomcheck.capstone.network.SymptomManagerSvcApi;
import org.symptomcheck.capstone.provider.ActiveContract;
import org.symptomcheck.capstone.ui.PatientExperiencesActivity;
import org.symptomcheck.capstone.utils.Constants;
import org.symptomcheck.capstone.utils.NetworkHelper;
import org.symptomcheck.capstone.preference.UserPreferencesManager;
import org.symptomcheck.capstone.utils.NotificationHelper;

import java.util.List;

import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

/**
 * Define a sync adapter for the app.
 *
 *
This class is instantiated in {@link SyncService}, which also binds SyncAdapter to the system.
 * SyncAdapter should only be initialized in SyncService, never anywhere else.
 *
 *
The system calls onPerformSync() via an RPC call through the IBinder object supplied by
 * SyncService.
 */
//TODO#BPR_8 Sync Adapter implementation spawns a thread to invoke a (potentially long) sync operation.
class SymptomSyncAdapter extends AbstractThreadedSyncAdapter {
    public final String TAG = SymptomSyncAdapter.this.getClass().getSimpleName();

    private SymptomManagerSvcApi mSymptomClient;
    /**
     * Constructor. Obtains handle to content resolver for later use.
     */
    public SymptomSyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
        //mContentResolver = context.getContentResolver();
    }

    /**
     * Constructor. Obtains handle to content resolver for later use.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public SymptomSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
        super(context, autoInitialize, allowParallelSyncs);
    }

    static Integer count = 0;
    /**
     * Called by the Android system in response to a request to run the sync adapter. The work
     * required to read data from the network, parse it, and store it in the content provider is
     * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
     * run on a background thread. For this reason, blocking I/O and other long-running tasks can be
     * run in situ, and you don't have to set up a separate thread for them.
     .
     *
     *
This is where we actually perform any work required to perform a sync.
     * {@link android.content.AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
     * so it is safe to perform blocking I/O here.
     *
     *
The syncResult argument allows you to pass information back to the method that triggered
     * the sync.
     */
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority,
                              ContentProviderClient provider, SyncResult syncResult) {

        final String accessToken = UserPreferencesManager.get().getBearerToken(getContext());
        final boolean isOnline =  NetworkHelper.isOnline(getContext());
        final boolean isOnlineOverWifi =  NetworkHelper.isOnlineOverWifi(getContext());

        Log.i(TAG, String.format("Beginning network synchronization:%s; isOnline:%b; isOnlineOverWifi:%b",
                extras.toString(),isOnline,isOnlineOverWifi));

        if(!accessToken.isEmpty()) {
            mSymptomClient = DownloadHelper.get().setAccessToken(accessToken).withRetrofitClient(getContext());

            String entity_id = extras.getString(SyncUtils.SYNC_ENTITY_ID, Constants.STRINGS.EMPTY);
            String owner_entity_id = extras.getString(SyncUtils.SYNC_OWNER_ENTITY_ID, Constants.STRINGS.EMPTY);
            String active_repo_local_to_sync;
            String active_repo_cloud_to_sync;

            boolean forceSync = ((extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL)
                                    && extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED)));

            if (forceSync) {
                active_repo_local_to_sync = ActiveContract.SYNC_ALL;
                active_repo_cloud_to_sync = ActiveContract.SYNC_ALL;
            } else if (extras.isEmpty()){
                // Periodic sync raised by system
                // normally he we would check only if remote data are changed,
                // for instance through a If-Modified-Since head request or similar pattern
                active_repo_local_to_sync = ActiveContract.SYNC_ALL;
                active_repo_cloud_to_sync = ActiveContract.SYNC_ALL;
            }else {
                active_repo_local_to_sync = extras.getString(SyncUtils.SYNC_LOCAL_ACTION_PARTIAL, ActiveContract.SYNC_NONE);
                active_repo_cloud_to_sync = extras.getString(SyncUtils.SYNC_CLOUD_ACTION_PARTIAL, ActiveContract.SYNC_NONE);
            }

            final UserInfo user = DAOManager.get().getUser();
            if (user != null) {
                Log.i(TAG, String.format("syncing: User:%s - Local:%s - Cloud:%s",
                        user.toString(),active_repo_local_to_sync,active_repo_cloud_to_sync));
                if (user.getLogged()) {
                    updateCloudData(active_repo_cloud_to_sync, user,owner_entity_id,entity_id);
                    updateLocalData(active_repo_local_to_sync, user);
                    handleOtherUserSpecificTasks(user.getUserType());

                }
            }

        }
        EventBus.getDefault().post(new DownloadEvent.Builder().setStatus(true).setValueEvnt(count).Build());

        Log.i(TAG, "Network synchronization completed");
    }

    private void handleOtherUserSpecificTasks(UserType userType){
        //TODO#BPR_1
        switch (userType){
            case PATIENT:
                break;
            case DOCTOR:
                checkPatientsBadExperience();
                break;
            case ADMIN:
                break;
        }

    }

    private void checkPatientsBadExperience(){
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method + "Verify the presence of Bad Experiences...");
        List<PatientExperience> patientExperiences = PatientExperience.checkBadExperiences();
        Log.i(TAG, "BadExperienceFound:" + patientExperiences.size());
        patientExperiences = PatientExperience.getAllNotNotified();
        final int count = patientExperiences.size();
        Log.i(TAG, "BadExperienceNotNotifiedYetFound:" + count);
        if(count > 0){
            for(PatientExperience patientExperience : patientExperiences) {
                (new Update(PatientExperience.class))
                        .set("notifiedToDoctor = 1")
                        .where("_id = ?", patientExperience.getId())
                        .execute();
            }
            //TODO#FDAR_13 Here we alert the Doctor of the presence of one or more Patient Bad Experiences
            final Context context = getContext();
            NotificationHelper.sendNotification(context, 3,
                    context.getResources().getString(R.string.title_bad_experience_notification),
                    context.getResources().getString(R.string.text_bad_experience_notification),
                    PatientExperiencesActivity.class, true, PatientExperiencesActivity.ACTION_NEW_PATIENT_BAD_EXPERIENCE, null);
        }
    }

    /**
     * Upload local data to remote repository
     * Basically we have to upload new Check-In submitted from the Patient
     * and Patient Medications list updated from the Doctor
     * @param sync sync type to be performed
     * @param
     */
    private synchronized void updateCloudData(String sync, UserInfo user, String owner_entity_id, String entity_id) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);
        //if(sync.equals(ActiveContract.SYNC_NONE)) {
        //TODO#BPR_1
        switch (user.getUserType()) {
               // if PATIENT
            // 1) look for Check-In to upload N.B Check-in are "marked" with a needSync field set to true
            case PATIENT:
                // get CheckIn to sync
                List<CheckIn> checkIns = CheckIn.getAllToSync();
                if(checkIns.size() > 0) {
                    Log.i(TAG, method + "::CheckIns to sync: " + checkIns.size());
                    for (CheckIn checkIn : checkIns) {
                        checkIn.setQuestions(Question.getAll(checkIn));
                        try {
                            //TODO#BPR_4
                            //TODO#FDAR_3 Save Checkin to remote datastore by calling REST Service exposed by Spring Server
                            mSymptomClient.addCheckIn(user.getUserIdentification(), checkIn);
                            new Update(CheckIn.class)
                                    .set("needSync = 0")
                                    .where("_id = ?", checkIn.getId())
                                    .execute();
                            Log.i(TAG, method + "::addCheckIn: " + checkIn.getId());
                        }catch (RetrofitError error){
                            DownloadHelper.get().handleRetrofitError(getContext(),error);
                            Log.e(TAG, method + "::addCheckIn error: " +  error.getMessage() +
                                    "; Status: " + error.getResponse().getStatus());
                        }catch (Exception e){
                            if(e.getCause().getClass().equals(RetrofitError.class)){
                                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
                            }
                            Log.e(TAG,"Error " + method + e.getMessage());
                        }
                    }
                }
                break;
            // if DOCTOR
            // 2) look for Medication to upload N.B Medication are "marked" with a needSync field set to true
            case DOCTOR:
                List<PainMedication> painMedications = PainMedication.getAllToSync();
                if(painMedications.size() > 0) {
                    Log.i(TAG, method + "::Medications to sync: " + painMedications.size());
                    for (PainMedication medication : painMedications) {
                        try {
                            mSymptomClient.addPainMedication(medication.getPatientMedicalNumber(), medication); //TODO#BPR_4 TODO#FDAR_12
                            new Update(PainMedication.class)
                                    .set("needSync = 0")
                                    .where("_id = ?", medication.getId())
                                    .execute();
                            Log.i(TAG, method + "::addPainMedication: " + medication.getId());
                        }catch (RetrofitError error){
                            DownloadHelper.get().handleRetrofitError(getContext(),error);
                            Log.e(TAG, method + "::addPainMedication error: " +  error.getMessage() +
                                    "; Status: " + error.getResponse().getStatus());
                        }catch (Exception e){
                            if(e.getCause().getClass().equals(RetrofitError.class)){
                                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
                            }
                            Log.e(TAG,"Error " + method + e.getMessage());
                        }
                    }
                }
                if(sync.equals(ActiveContract.SYNC_DELETE_MEDICINES)){
                    try {
                        final boolean deleted =  mSymptomClient.deletePainMedication(owner_entity_id, entity_id); //TODO#BPR_4 TODO#FDAR_12
                        Log.d(TAG, method + String.format("deletePainMedication:%s (of %s)=> %b ",entity_id,owner_entity_id,deleted));
                    }catch (RetrofitError error){
                        DownloadHelper.get().handleRetrofitError(getContext(),error);
                        Log.e(TAG, method + "::deletePainMedication error: " +  error.getCause().getMessage() +
                                "; Status: " + error.getResponse().getStatus());
                    }catch (Exception e){
                        if(e.getCause().getClass().equals(RetrofitError.class)){
                            DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
                        }
                        Log.e(TAG,"Error " + method + e.getCause().getMessage());
                    }

                }
                break;

        }
        //}
    }

    /**
     * Download data from the cloud in order to sync local repo with the remote one
     * @param sync sync type to be performed
     */
    private synchronized void updateLocalData(String sync, UserInfo user) {
        //TODO#BPR_1
        switch (user.getUserType()) {
            case DOCTOR:
                if (sync.equals(ActiveContract.SYNC_ALL)) {
                    // get and save Doctor detail
                    syncDoctorBaseInfo(user);
                    //get and save Doctor' Patients
                    syncDoctorPatients(user);
                    //sync All Patients' information
                    //get and save Patients' Check-Ins
                    syncPatientsCheckIns(user);
                    //get and save Patients' Medicines
                    syncPatientsMedicines(user);
                } else if (sync.equals(ActiveContract.SYNC_PATIENTS)) {
                    syncDoctorPatients(user);
                } else if (sync.equals(ActiveContract.SYNC_CHECK_IN)) { //TODO#FDAR_10 Fetch Check-In data from remote server
                    syncDoctorBaseInfo(user);
                    syncPatientsCheckIns(user);
                } else if (sync.equals(ActiveContract.SYNC_DOCTORS)) {
                    syncDoctorBaseInfo(user);
                } else if (sync.equals(ActiveContract.SYNC_MEDICINES)) {
                    syncPatientsMedicines(user);
                }
                break;
            case PATIENT:
                if (sync.equals(ActiveContract.SYNC_ALL)) {
                    // get and save Patient detail
                    syncPatientBaseInfo(user);
                    //sync All Patient' information
                    //get and save Patient' Doctors
                    syncPatientDoctors(user);
                    //get and save Patients' Check-Ins
                    syncPatientsCheckIns(user);
                    //get and save Patients' Medicines
                    syncPatientsMedicines(user);
                } else if (sync.equals(ActiveContract.SYNC_MEDICINES)) {
                    syncPatientsMedicines(user);
                } else if (sync.equals(ActiveContract.SYNC_CHECK_IN)) {
                    syncPatientsCheckIns(user);
                } else if (sync.equals(ActiveContract.SYNC_PATIENTS)) {
                    syncPatientBaseInfo(user);
                } else if (sync.equals(ActiveContract.SYNC_DOCTORS)) {
                    syncPatientDoctors(user);
                }
                break;
            case ADMIN:
                break;
            default:
                break;
        }
    }

    private List<Doctor> syncPatientDoctors(UserInfo user) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);
        List<Doctor> doctors = null;
        try {
            doctors = (List<Doctor>) mSymptomClient.findDoctorsByPatient(user.getUserIdentification()); //TODO#BPR_4
            DAOManager.get().rebuildDoctors(doctors, user.getUserIdentification());
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
        }catch (Exception e){
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
            Log.e(TAG,"Error rebuildDoctors:" + e.getMessage());
        }
        return doctors;
    }

    private void syncPatientBaseInfo(UserInfo user) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);
        try {
            Patient patient = mSymptomClient.findPatientByMedicalRecordNumber(user.getUserIdentification()); //TODO#BPR_4
            DAOManager.get().rebuildPatients(Lists.newArrayList(patient), user.getUserIdentification());
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
        }catch (Exception e){
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
            Log.e(TAG,"Error syncPatientBaseInfo:" + e.getMessage());
        }
    }

    private void syncDoctorBaseInfo(UserInfo user){
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);
        try {
            Doctor doctor = mSymptomClient.findDoctorByUniqueDoctorID(user.getUserIdentification()); //TODO#BPR_4
            DAOManager.get().rebuildDoctors(Lists.newArrayList(doctor), user.getUserIdentification());
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
        }catch (Exception e){
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
            Log.e(TAG,"Error syncDoctorBaseInfo:" + e.getMessage());
        }
    }

    private List<Patient> syncDoctorPatients(UserInfo user) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);

        List<Patient> patients = null;

        try {
             patients = (List<Patient>) mSymptomClient.findPatientsByDoctor(user.getUserIdentification()); //TODO#BPR_4
             DAOManager.get().rebuildPatients(patients, user.getUserIdentification());
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
        }catch (Exception e){
            Log.e(TAG,"Error rebuildPatients:" + e.getMessage());
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
        }
        return patients;
    }

    private boolean syncPatientsCheckIns(UserInfo user) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);
        boolean sync = true;
        List<Patient> patients = Patient.getAll();
        try {
            if(patients != null){
                List<CheckIn> checkInsToSync = CheckIn.getAllToSync();

                DAOManager.get().deleteCheckIns();
                for(Patient patient : patients){
                    List<CheckIn> checkIns = (List<CheckIn>) mSymptomClient.findCheckInsByPatient(patient.getMedicalRecordNumber()); //TODO#BPR_4
                    for(int idx=0; idx< checkIns.size(); idx++){
                        checkIns.get(idx).setNeedSync(0);
                    }
                    checkIns.addAll(checkInsToSync);
                    if((checkIns.size() > 0))
                        DAOManager.get().saveCheckIns(checkIns,
                                patient.getMedicalRecordNumber());
                }
            }else {
                Log.e(TAG, "syncPatientsCheckIns=> sync not possible: patients = null!");
            }
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "syncPatientsCheckIns=>Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
            sync = false;
        }catch (Exception e){
            Log.e(TAG,"syncPatientsCheckIns=>Error saveCheckIns:" + e.getMessage());
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
            sync = false;
        }
        return sync;
    }

    private boolean syncPatientsMedicines(UserInfo user) {
        String method = new Object(){}.getClass().getEnclosingMethod().getName();
        Log.i(TAG, method);

        boolean sync = true;
        List<Patient> patients = Patient.getAll();
        try {
            if(patients != null){
                List<PainMedication> medicationsToSync = PainMedication.getAllToSync();

                DAOManager.get().deleteMedicines();
                for(Patient patient : patients){
                    List<PainMedication> medications = (List<PainMedication>) mSymptomClient.findPainMedicationsByPatient(patient.getMedicalRecordNumber());//TODO#BPR_4
                    medications.addAll(medicationsToSync);
                    if((medications.size() > 0)) {
                        DAOManager.get().savePainMedications(medications, patient.getMedicalRecordNumber(), false);
                    }
                }
            }else {
                Log.e(TAG, "syncPatientsMedicines=> sync not possible: patients = null!");
            }
        }catch (RetrofitError e){
            DownloadHelper.get().handleRetrofitError(getContext(),e);
            Log.e(TAG, "syncPatientsMedicines=>Retrofit:" + e.getMessage() + "; Status: " + e.getResponse().getStatus());
            sync = false;
        }catch (Exception e){
            if(e.getCause().getClass().equals(RetrofitError.class)){
                DownloadHelper.get().handleRetrofitError(getContext(), (RetrofitError) e.getCause());
            }
            Log.e(TAG,"syncPatientsMedicines=>Error saveCheckIns:" + e.getMessage());
            sync = false;
        }
        return sync;
    }

}


text:
Web site for QIICR project

Hosted at http://qiicr.org

redpajama_set_name: RedPajamaGithub


text:
const Promise = require('bluebird');

module.exports =  Promise.delay(1500)
.return('promised content');


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.model.java.impl;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElementParameterizedCreator;
import org.jetbrains.jps.model.ex.JpsElementChildRoleBase;
import org.jetbrains.jps.model.java.JavaModuleIndex;
import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes;

/**
 * @author Eugene Zhuravlev
 */
public final class JavaModuleIndexRole extends JpsElementChildRoleBase<JavaModuleIndex> implements JpsElementParameterizedCreator<JavaModuleIndex, JpsCompilerExcludes>{
  public static final JavaModuleIndexRole INSTANCE = new JavaModuleIndexRole();

  private JavaModuleIndexRole() {
    super("java module index");
  }

  @Override
  @NotNull
  public JavaModuleIndex create(@NotNull JpsCompilerExcludes excludes) {
    return new JavaModuleIndexImpl(excludes);
  }
}


text:
package com.intellij.psi.util;

import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ClassUtil {
  private ClassUtil() {}

  public static String extractPackageName(String className) {
    if (className != null) {
      int i = className.lastIndexOf('.');
      return i == -1 ? "" : className.substring(0, i);

    }
    return null;
  }

  public static String extractClassName(@NotNull String fqName) {
    int i = fqName.lastIndexOf('.');
    return i == -1 ? fqName : fqName.substring(i + 1);
  }

  public static String createNewClassQualifiedName(String qualifiedName, String className) {
    if (className == null){
      return null;
    }
    if (qualifiedName == null || qualifiedName.isEmpty()){
      return className;
    }
    return qualifiedName + "." + extractClassName(className);
  }

  public static PsiDirectory sourceRoot(PsiDirectory containingDirectory) {
    while (containingDirectory != null) {
      if (JavaDirectoryService.getInstance().isSourceRoot(containingDirectory)) {
        return containingDirectory;
      }
      containingDirectory = containingDirectory.getParentDirectory();
    }
    return null;
  }

  public static void formatClassName(@NotNull final PsiClass aClass, final StringBuilder buf) {
    final String qName = aClass.getQualifiedName();
    if (qName != null) {
      buf.append(qName);
    }
    else {
      final PsiClass parentClass = getContainerClass(aClass);
      if (parentClass != null) {
        formatClassName(parentClass, buf);
        buf.append("$");
        buf.append(getNonQualifiedClassIdx(aClass));
        final String name = aClass.getName();
        if (name != null) {
          buf.append(name);
        }
      }
    }
  }

  @Nullable
  private static PsiClass getContainerClass(final PsiClass aClass) {
    PsiElement parent = aClass.getContext();
    while (parent != null && !(parent instanceof PsiClass)) {
      parent = parent.getContext();
    }
    return (PsiClass)parent;
  }

  public static int getNonQualifiedClassIdx(@NotNull final PsiClass psiClass) {
    final int[] result = {-1};
    final PsiClass containingClass = getContainerClass(psiClass);
    if (containingClass != null) {
      containingClass.accept(new JavaRecursiveElementVisitor() {
        private int myCurrentIdx = 0;

        @Override public void visitElement(PsiElement element) {
          if (result[0] == -1) {
            super.visitElement(element);
          }
        }

        @Override public void visitClass(PsiClass aClass) {
          super.visitClass(aClass);
          if (aClass.getQualifiedName() == null) {
            myCurrentIdx++;
            if (psiClass == aClass) {
              result[0] = myCurrentIdx;
            }
          }
        }
      });
    }
    return result[0];
  }

  public static PsiClass findNonQualifiedClassByIndex(final String indexName, @NotNull final PsiClass containingClass) {
    return findNonQualifiedClassByIndex(indexName, containingClass, false);
  }

  public static PsiClass findNonQualifiedClassByIndex(final String indexName, @NotNull final PsiClass containingClass,
                                                      final boolean jvmCompatible) {
    String prefix = getDigitPrefix(indexName);
    final int idx = !prefix.isEmpty() ? Integer.parseInt(prefix) : -1;
    final String name = prefix.length() < indexName.length() ? indexName.substring(prefix.length()) : null;
    final PsiClass[] result = new PsiClass[1];
    containingClass.accept(new JavaRecursiveElementVisitor() {
      private int myCurrentIdx = 0;

      @Override public void visitElement(PsiElement element) {
        if (result[0] == null) {
          super.visitElement(element);
        }
      }

      @Override public void visitClass(PsiClass aClass) {
        if (!jvmCompatible) {
          super.visitClass(aClass);
          if (aClass.getQualifiedName() == null) {
            myCurrentIdx++;
            if (myCurrentIdx == idx && Comparing.strEqual(name, aClass.getName())) {
              result[0] = aClass;
            }
          }
          return;
        }
        if (aClass == containingClass) {
          super.visitClass(aClass);
          return;
        }
        if (Comparing.strEqual(name, aClass.getName())) {
          myCurrentIdx++;
          if (myCurrentIdx == idx || idx == -1) {
            result[0] = aClass;
          }
        }
      }

      @Override public void visitTypeParameter(final PsiTypeParameter classParameter) {
        if (!jvmCompatible) {
          super.visitTypeParameter(classParameter);
        }
        else {
          visitElement(classParameter);
        }
      }
    });
    return result[0];
  }

  private static String getDigitPrefix(@NotNull String indexName) {
    int i;
    for (i = 0; i < indexName.length(); i++) {
      final char c = indexName.charAt(i);
      if (!Character.isDigit(c)) {
        break;
      }
    }
    return i == 0 ? "" : indexName.substring(0, i);
  }

  /**
   * Finds anonymous classes. Uses javac notation.
   * @param psiManager project to search
   * @param externalName class qualified name
   * @return found psiClass
   */
  @Nullable
  public static PsiClass findPsiClass(final PsiManager psiManager, String externalName){
    return findPsiClass(psiManager, externalName, null, false);
  }

  @Nullable
  public static PsiClass findPsiClass(final PsiManager psiManager,
                                      String externalName,
                                      PsiClass psiClass,
                                      boolean jvmCompatible) {
    return findPsiClass(psiManager, externalName, psiClass, jvmCompatible, GlobalSearchScope.allScope(psiManager.getProject()));
  }

  @Nullable
  public static PsiClass findPsiClass(final PsiManager psiManager,
                                      String externalName,
                                      @Nullable PsiClass psiClass,
                                      boolean jvmCompatible,
                                      final GlobalSearchScope scope) {
    final int topIdx = externalName.indexOf('$');
    if (topIdx > -1) {
      if (psiClass == null) {
        psiClass = JavaPsiFacade.getInstance(psiManager.getProject())
          .findClass(externalName.substring(0, topIdx), scope);
      }
      if (psiClass == null) return null;
      externalName = externalName.substring(topIdx + 1);
      return findSubclass(psiManager, externalName, psiClass, jvmCompatible);
    } else {
      return JavaPsiFacade.getInstance(psiManager.getProject()).findClass(externalName, scope);
    }
  }

  @Nullable
  private static PsiClass findSubclass(final PsiManager psiManager,
                                       final String externalName,
                                       final PsiClass psiClass,
                                       final boolean jvmCompatible) {
    final int nextIdx = externalName.indexOf('$');
    if (nextIdx > -1) {
      final PsiClass anonymousClass = findNonQualifiedClassByIndex(externalName.substring(0, nextIdx), psiClass, jvmCompatible);
      if (anonymousClass == null) return null;
      return findPsiClass(psiManager, externalName.substring(nextIdx), anonymousClass, jvmCompatible);
    }
    else {
      return findNonQualifiedClassByIndex(externalName, psiClass, jvmCompatible);
    }
  }

  @Nullable
  public static String getJVMClassName(@NotNull PsiClass aClass) {
    final PsiClass containingClass = aClass.getContainingClass();
    if (containingClass != null) {
      String parentName = getJVMClassName(containingClass);
      if (parentName == null) {
        return null;
      }

      return parentName + "$" + aClass.getName();
    }
    return aClass.getQualifiedName();
  }

  @Nullable
  public static PsiClass findPsiClassByJVMName(final PsiManager manager, final String jvmClassName) {
    return findPsiClass(manager, jvmClassName.replace('/', '.'), null, true);
  }
}


text:
package com.daxiang.android.http.ssl.https;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

/**
 *
 * @author daxiang
 * @date 2016-7-25
 */
public class LoginRequest {

	public static void main(String[] args) throws Exception {
		String url = "https://127.0.0.1:8443/HttpsServer/loginHttpServlet";
		String keystoreFile = "E:/HTTPS/clienttrust.keystore";
		String keystorePwd = "222222";
		TrustManager[] tms = { new X509TrustManagerImpl(keystoreFile,
				keystorePwd) };
		// Use factory
		SSLContext ctx = SSLContext.getInstance("TLS");
		ctx.init(null, tms, null);
		SSLSocketFactory sf = ctx.getSocketFactory();

		URL serverUrl = new URL(url);
		HttpsURLConnection httpsURLConnection = (HttpsURLConnection) serverUrl
				.openConnection();

		httpsURLConnection.setHostnameVerifier(new MyHostnameVerifier(
				"127.0.0.1"));
		httpsURLConnection.setSSLSocketFactory(sf);

		httpsURLConnection.addRequestProperty("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");

		httpsURLConnection.setDoInput(true);
		httpsURLConnection.setDoOutput(true);
		httpsURLConnection.setReadTimeout(30000);
		httpsURLConnection.setRequestMethod("POST");
		httpsURLConnection.setUseCaches(false);

		OutputStream outputStream = httpsURLConnection.getOutputStream();
		outputStream.write("userName=daxiang&userPwd=222222".getBytes());
		outputStream.flush();

		InputStream inputStream = httpsURLConnection.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				inputStream, "UTF-8"));
		String temp;
		StringBuffer responseStr = new StringBuffer();
		while ((temp = br.readLine()) != null) {

			responseStr.append(temp);
		}

		int statusCode = httpsURLConnection.getResponseCode();
		System.out.println("服务端返回的状态码:" + statusCode);
		System.out.println("服务端返回的响应:" + responseStr.toString());

		outputStream.close();
		br.close();
		inputStream.close();

	}

}


text:
(function(){
  var expect, matcher, container, ContextMatcher, factories, createUser;
  require('../../test_setup');
  expect = require('chai').expect;
  matcher = require('../../../index');
  container = matcher.container;
  ContextMatcher = container.ContextMatcher;
  factories = require('../../factories');
  createUser = factories.createUser;
  describe('ContextMatcher (intersect - default include)', function(){
    var permitMatcher, ctx, key, matcher, users, permits, requests, matching, noneMatching, intersect;
    users = {};
    permits = {};
    requests = {};
    ctx = {};
    matching = {};
    noneMatching = {};
    intersect = function(obj){
      return {
        intersect: obj
      };
    };
    before(function(){
      var createMatcher;
      users.kris = createUser.kris;
      users.emily = createUser.emily;
      ctx.base = {
        ctx: {
          area: 'guest',
          secret: '123'
        }
      };
      ctx.andMore = {
        ctx: {
          area: 'guest',
          secret: '123',
          more: 'So much more...'
        }
      };
      ctx.andLess = {
        ctx: {
          area: 'guest'
        }
      };
      requests.user = {
        user: users.kris
      };
      requests.userAndMore = {
        user: users.kris,
        area: 'admin'
      };
      requests.userAndLess = {
        user: users.kris
      };
      createMatcher = function(ctx, key, access, debug){
        debug == null && (debug = false);
        return new ContextMatcher(ctx, key, access, debug);
      };
      key = 'includes';
      return matcher = createMatcher(intersect(ctx.base), key, requests.user);
    });
    describe('init', function(){
      specify('has context', function(){
        return matcher.context.should.eql(intersect(ctx.base));
      });
      specify('has key', function(){
        return matcher.key.should.eql(key);
      });
      return specify('has access-request', function(){
        return matcher.accessRequest.should.eql(requests.user);
      });
    });
    describe('match', function(){
      return specify('by default always returns false', function(){
        return matcher.match().should.be['false'];
      });
    });
    return describe('intersect-on partial, access-request', function(){
      specify('intersects when same object', function(){
        return matcher.intersectOn(ctx.base).should.be['true'];
      });
      specify('intersects when more than context (covers)', function(){
        return matcher.intersectOn(ctx.andMore).should.be['true'];
      });
      specify('does not intersects when less than context', function(){
        return matcher.intersectOn(ctx.andLess).should.be['false'];
      });
      return specify('does not intersects when other object', function(){
        return matcher.intersectOn(requests.user).should.be['false'];
      });
    });
  });
}).call(this);


text:
package com.googleresearch.capturesync.softwaresync;

/** Helper conversions between time scales. */
public final class TimeUtils {

  public static double nanosToMillis(double nanos) {
    return nanos / 1_000_000L;
  }

  public static long nanosToSeconds(long nanos) {
    return nanos / 1_000_000_000L;
  }

  public static double nanosToSeconds(double nanos) {
    return nanos / 1_000_000_000L;
  }

  public static long millisToNanos(long millis) {
    return millis * 1_000_000L;
  }

  public static long secondsToNanos(int seconds) {
    return seconds * 1_000_000_000L;
  }

  private TimeUtils() {}
}


text:
from django.db import connection
from django.contrib.sites.models import Site
from django.contrib.auth.models import AnonymousUser, Group, User

import waffle
from waffle.models import Flag, Sample, Switch
from waffle.tests.base import TestCase

from test_app import views

from waffle.tests.test_waffle import get, process_request

class SiteTests(TestCase):
    def setUp(self):
        super(SiteTests, self).setUp()
        Site.objects.create(id=2, domain='example2.com', name='example2.com')
        Site.objects.create(id=3, domain='example3.com', name='example3.com')
        Site.objects.create(id=4, domain='example4.com', name='example4.com')

        self.site1 = Site.objects.get(name='example.com')
        self.site2 = Site.objects.get(name='example2.com')
        self.site3 = Site.objects.get(name='example3.com')
        self.site4 = Site.objects.get(name='example4.com')

    def test_switch_by_site(self):
        """ test that we can get different switch values by site """
        name = 'myswitch'
        Switch.objects.create(name=name, active=True, site=self.site1,
                              all_sites_override=False)
        self.assertTrue(waffle.switch_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.switch_is_active(get(), name))

    def test_switch_all_sites_override(self):
        name = 'myswitch'
        Switch.objects.create(name=name, active=True, site=self.site1)
        self.assertTrue(waffle.switch_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.switch_is_active(get(), name))

    def test_switch_inactive_all_sites_override(self):
        name = 'myswitch'
        Switch.objects.create(name=name, active=False, site=self.site1)
        self.assertFalse(waffle.switch_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.switch_is_active(get(), name))

    def test_switch_by_multisite(self):
        name = "myswitch"
        switch1 = Switch.objects.create(name=name, active=True, site=self.site1,
                                        all_sites_override=False)
        switch1.site.add(self.site2)
        switch1.site.add(self.site3)

        self.assertTrue(waffle.switch_is_active(get(), name))
        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.switch_is_active(get(), name))
        with self.settings(SITE_ID=3):
            self.assertTrue(waffle.switch_is_active(get(), name))
        with self.settings(SITE_ID=4):
            self.assertFalse(waffle.switch_is_active(get(), name))

    def test_switch_inactive_no_bound_sites(self):
        switch = Switch.objects.create(name='myswitch', active=True,
                                       all_sites_override=False)
        self.assertFalse(waffle.switch_is_active(get(), switch.name))

    def test_switch_site_default(self):
        name = 'myswitch'
        switch = Switch.objects.create(name=name, active=True)  # no site given

        self.assertTrue(waffle.switch_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.switch_is_active(get(), name))

    def test_get_switches_for_site(self):
        self.assertTrue(len(Switch.get_switches_for_site(self.site1)) == 0)
        name1 = "foo"
        Switch.objects.create(name=name1, active=True, site=self.site1)

        self.assertEqual([name1], [sw.name for sw in Switch.get_switches_for_site(self.site1)])
        # by default switch is sites-global
        self.assertEqual([name1], [sw.name for sw in Switch.get_switches_for_site(self.site2)])

        name2 = "bar"
        Switch.objects.create(name=name2, active=True, site=self.site2, all_sites_override=False)
        self.assertEqual({name1, name2}, set([sw.name for sw in Switch.get_switches_for_site(self.site2)]))
        self.assertEqual([name1], [sw.name for sw in Switch.get_switches_for_site(self.site1)])

    def test_sample_by_site(self):
        name = 'sample'
        Sample.objects.create(name=name, percent='100.0', site=self.site1,
                              all_sites_override=False)

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))

    def test_sample_all_sites_override(self):
        name = 'sample'
        Sample.objects.create(name=name, percent='100.0', site=self.site1)

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.sample_is_active(get(), name))

    def test_sample_inactive_all_sites_override(self):
        name = 'mysample'
        Sample.objects.create(name=name, percent='0.0', site=self.site1)
        self.assertFalse(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))

    def test_sample_site_default(self):
        name = 'sample'
        sample = Sample.objects.create(name=name, percent='100.0') # no site given

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.sample_is_active(get(), name))

    def test_get_samples_for_site(self):
        self.assertTrue(len(Sample.get_samples_for_site(self.site1)) == 0)
        name1 = "foo"
        Sample.objects.create(name=name1, percent='100.0', site=self.site1)

        self.assertEqual([name1], [s.name for s in Sample.get_samples_for_site(self.site1)])
        # by default sample is sites-global
        self.assertEqual([name1], [s.name for s in Sample.get_samples_for_site(self.site2)])

        name2 = "bar"
        Sample.objects.create(name=name2, percent='0.0', site=self.site2, all_sites_override=False)
        self.assertEqual({name1, name2}, set([s.name for s in Sample.get_samples_for_site(self.site2)]))
        self.assertEqual([name1], [s.name for s in Sample.get_samples_for_site(self.site1)])

    def test_flag_by_site(self):
        name = 'myflag'
        flag1 = Flag.objects.create(name=name, everyone=True, site=self.site1,
                                    all_sites_override=False)
        request = get()

        response = process_request(request, views.flag_in_view)
        self.assertContains(response, b'on')

        with self.settings(SITE_ID=2):
            response = process_request(request, views.flag_in_view)
            self.assertContains(response, b'off')

    def test_flag_all_sites_override(self):
        name = 'sample'
        Flag.objects.create(name=name, everyone=True, site=self.site1)

        self.assertTrue(waffle.flag_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.flag_is_active(get(), name))

    def test_get_flags_for_site(self):
        self.assertTrue(len(Flag.get_flags_for_site(self.site1)) == 0)
        name1 = "foo"
        Flag.objects.create(name=name1, everyone=True, site=self.site1)

        self.assertEqual([name1], [f.name for f in Flag.get_flags_for_site(self.site1)])
        # by default sample is sites-global
        self.assertEqual([name1], [f.name for f in Flag.get_flags_for_site(self.site2)])

        name2 = "bar"
        Flag.objects.create(name=name2,  everyone=True, site=self.site2, all_sites_override=False)
        self.assertEqual({name1, name2}, set([f.name for f in Flag.get_flags_for_site(self.site2)]))
        self.assertEqual([name1], [f.name for f in Flag.get_flags_for_site(self.site1)])


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /home/david/Documentos/curso/php/zf2.intermediario/module/Album/src/Album/Controller/AlbumController.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../../css/style.css" rel="stylesheet">

/home/david/Documentos/curso/php/zf2.intermediario/module/Album

src

Album

Controller

AlbumController.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 5

      CRAP

           0.00% covered (danger)

0.00%

0 / 10

      AlbumController

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 5

      30

           0.00% covered (danger)

0.00%

0 / 10

       indexAction

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 2

       addAction

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 2

       editAction

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 2

       deleteAction

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 2

       getAlbumTable

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 2

1
	<?php

2
	namespace Album\Controller;

3

4
	use Zend\Mvc\Controller\AbstractActionController;

5
	use Zend\View\Model\ViewModel;

6
	use Album\Model\Album;

7
	use Album\Form\AlbumForm;

8

9
	class AlbumController extends AbstractActionController

10
	{

11
	    protected $albumTable;

12

13
	    public function indexAction()

14
	    {

15

16
	    }

17

18
	    public function addAction()

19
	    {

20

21
	    }

22

23
	    public function editAction()

24
	    {

25
	    }

26

27
	    public function deleteAction()

28
	    {

29
	    }

30

31
	    public function getAlbumTable()

32
	    {

33
	    }

34
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 2.1.8 using PHP 5.6.9-0+deb8u1 and PHPUnit 4.7.7 at Sat Jul 25 0:38:41 BRT 2015.


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.09.16 at 10:18:45 AM CEST
//

package org.fiteagle.interactors.sfa.rspec.request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;

/**
 *
Java class for InstallServiceContents complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="InstallServiceContents">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <group ref="{http://www.geni.net/resources/rspec/3}AnyExtension"/>
 *       <attGroup ref="{http://www.geni.net/resources/rspec/3}AnyExtension"/>
 *       <attribute name="url" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="install_path" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InstallServiceContents", propOrder = {
    "any"
})
public class InstallServiceContents {

    @XmlAnyElement(lax = true)
    protected List<Object> any;
    @XmlAttribute(name = "url", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected String url;
    @XmlAttribute(name = "install_path", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected String installPath;
    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();

    /**
     * Gets the value of the any property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the any property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAny().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Object }
     * {@link Element }
     *
     *
     */
    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }

    /**
     * Gets the value of the url property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUrl() {
        return url;
    }

    /**
     * Sets the value of the url property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUrl(String value) {
        this.url = value;
    }

    /**
     * Gets the value of the installPath property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getInstallPath() {
        return installPath;
    }

    /**
     * Sets the value of the installPath property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setInstallPath(String value) {
        this.installPath = value;
    }

    /**
     * Gets a map that contains attributes that aren't bound to any typed property on this class.
     *
     *

     * the map is keyed by the name of the attribute and
     * the value is the string value of the attribute.
     *
     * the map returned by this method is live, and you can add new attribute
     * by updating the map directly. Because of this design, there's no setter.
     *
     *
     * @return
     *     always non-null
     */
    public Map<QName, String> getOtherAttributes() {
        return otherAttributes;
    }

}


text:
package space.dotcat.assistant.api;

import java.io.IOException;
import java.lang.annotation.Annotation;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import space.dotcat.assistant.content.ApiError;

public class BasicErrorParser extends ErrorParser {

    public ApiError parseError(Retrofit retrofit, Response response) {
        Converter<ResponseBody, ApiError> converter = retrofit
                .responseBodyConverter(ApiError.class, new Annotation[0]);

        ApiError error;

        try {
            error = converter.convert(response.errorBody());
        } catch (IOException e) {
            return null;
        }

        return error;
    }
}


text:
module Fog
  module Storage
    class AWS
      class Real

        require 'fog/aws/parsers/storage/list_multipart_uploads'

        # List multipart uploads for a bucket
        #
        # ==== Parameters
        # * bucket_name<~String> - Name of bucket to list multipart uploads for
        # * upload_id<~String> - upload id to list objects for
        # * options<~Hash> - config arguments for list.  Defaults to {}.
        #   * 'key-marker'<~String> - limits parts to only those that appear
        #     lexicographically after this key.
        #   * 'max-uploads'<~Integer> - limits number of uploads returned
        #   * 'upload-id-marker'<~String> - limits uploads to only those that appear
        #     lexicographically after this upload id.
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #   * body<~Hash>:
        #     * 'Bucket'<~string> - Bucket where the multipart upload was initiated
        #     * 'IsTruncated'<~Boolean> - Whether or not the listing is truncated
        #     * 'KeyMarker'<~String> - first key in list, only upload ids after this lexographically will appear
        #     * 'MaxUploads'<~Integer> - Maximum results to return
        #     * 'NextKeyMarker'<~String> - last key in list, for further pagination
        #     * 'NextUploadIdMarker'<~String> - last key in list, for further pagination
        #     * 'Upload'<~Hash>:
        #       * 'Initiated'<~Time> - Time when upload was initiated
        #       * 'Initiator'<~Hash>:
        #         * 'DisplayName'<~String> - Display name of upload initiator
        #         * 'ID'<~String> - Id of upload initiator
        #       * 'Key'<~String> - Key where multipart upload was initiated
        #       * 'Owner'<~Hash>:
        #         * 'DisplayName'<~String> - Display name of upload owner
        #         * 'ID'<~String> - Id of upload owner
        #       * 'StorageClass'<~String> - Storage class of object
        #       * 'UploadId'<~String> - upload id of upload containing part
        #     * 'UploadIdMarker'<String> - first key in list, only upload ids after this lexographically will appear
        #
        # ==== See Also
        # http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadListMPUpload.html
        #
        def list_multipart_uploads(bucket_name, options = {})
          request({
            :expects  => 200,
            :headers  => {},
            :host     => "#{bucket_name}.#{@host}",
            :idempotent => true,
            :method   => 'GET',
            :parser   => Fog::Parsers::Storage::AWS::ListMultipartUploads.new,
            :query    => options.merge!({'uploads' => nil})
          })
        end

      end
    end
  end
end


text:
<project name="Constellation" default="build" basedir="." xmlns:jacoco="antlib:org.jacoco.ant">

	<property name="version" value="2.0.0-SNAPSHOT" />
	<property name="jar" value="constellation-${version}.jar" />
	<property name="zip" value="constellation-${version}.zip" />
	<property name="src-zip" value="constellation-${version}-src.zip" />

	<property name="distdir" value="./lib" />
	<property name="builddir" value="./build" />
	<property name="javadoc" value="javadoc" />

  	<property name="main.build.dir" value="${builddir}/main"/>
  	<property name="main.src.dir" value="./src/main/java"/>

  	<property name="unittest.build.dir" value="${builddir}/test"/>
  	<property name="unittest.src.dir" value="./src/test/java"/>

  	<property name="integrationtest.build.dir" value="${builddir}/integrationTest"/>
  	<property name="integrationtest.src.dir" value="./src/integrationTests/java"/>

        <property name="result.dir" location="./target" />
        <property name="result.classes.dir" location="${result.dir}/classes" />
        <property name="result.report.dir" location="${result.dir}/site/jacoco" />
        <property name="result.exec.file" location="${result.dir}/jacoco.exec" />

	<path id="default.classpath">
		<fileset dir="external">
			<include name="**/*.jar" />
		</fileset>
	</path>

	<path id="test.classpath">
		<fileset dir="external">
			<include name="**/*.jar" />
		</fileset>
		<fileset dir="lib">
			<include name="**/*.jar" />
		</fileset>
	</path>

<!--
	<path id="test.classpath">
		<fileset dir="external">
			<include name="**/*.jar" />
		<fileset dir="lib">
		</fileset>
			<include name="**/*.jar" />
		</fileset>
	</path>
-->
        <!-- Step 1: Import JaCoCo Ant tasks -->
        <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
                <classpath path="./external/test/jacoco/lib/jacocoant.jar" />
        </taskdef>

	<!-- Compile constellation -->
	<target name="compile" depends="clean">
		<mkdir dir="${distdir}" />
		<mkdir dir="${main.build.dir}" />

		<javac destdir="${main.build.dir}" srcdir="${main.src.dir}" source="1.7" target="1.7" debug="true"
                                        includeantruntime="false" includes="**/*.java" classpathref="default.classpath" />

		<jar jarfile="${distdir}/${jar}" basedir="${main.build.dir}" includes="**">
			<manifest>
				<attribute name="Built-By" value="${user.name}" />
			</manifest>
		</jar>
	</target>

	<target name="unittest-compile" depends="compile">
		<mkdir dir="${unittest.build.dir}" />
		<mkdir dir="${result.classes.dir}" />
		<mkdir dir="${result.report.dir}" />

	        <copy todir="${unittest.build.dir}">
		        <file file="log4j.properties"/>
		</copy>

		<javac destdir="${unittest.build.dir}" srcdir="${unittest.src.dir}" source="1.7" target="1.7" debug="true" includeantruntime="false" includes="**/*.java">
        		<classpath>
          			<pathelement location="${distdir}/${jar}"/>
                                <path refid="test.classpath"/>
        		</classpath>
		</javac>
	</target>

	<target name="integrationtest-compile" depends="compile">
		<mkdir dir="${integrationtest.build.dir}" />
		<mkdir dir="${result.classes.dir}" />
		<mkdir dir="${result.report.dir}" />

	        <copy todir="${integrationtest.build.dir}">
		        <file file="log4j.properties"/>
		</copy>

		<javac destdir="${integrationtest.build.dir}" srcdir="${integrationtest.src.dir}" source="1.7" target="1.7" debug="true" includeantruntime="false" includes="**/*.java">
        		<classpath>
          			<pathelement location="${distdir}/${jar}"/>
                                <path refid="test.classpath"/>
        		</classpath>
		</javac>
	</target>

        <target name="copy-external">
	        <mkdir dir="lib" />
        	<!-- Copy external libraries to lib directory -->
	        <copy todir="lib">
		        <fileset dir="external" excludes="log4jME*.jar" />
		</copy>
	</target>

	<target name="javadoc" description="Create javadocs">
		<!-- Create the javadoc -->
		<mkdir dir="${javadoc}" />
		<javadoc destdir="${javadoc}" access="public" sourcepath="src" windowtitle="Constellation Documentation" packagenames="ibis.constellation, ibis.constellation.context" doctitle="Constellation Documentation" bottom="The Ibis project" classpathref="default.classpath">
		    <link href="http://docs.oracle.com/javase/6/docs/api/"/>
		</javadoc>

	</target>

	<target name="build" depends="clean,compile,copy-external">
	</target>

 	<target name="unittest" depends="unittest-compile">
                <jacoco:coverage destfile="${result.exec.file}">
    			<junit printsummary="on" haltonfailure="no" fork="true">
        			<classpath>
          				<path refid="test.classpath"/>
          				<pathelement location="${unittest.build.dir}"/>
        			</classpath>
        			<formatter type="brief" usefile="false" />
        			<batchtest>
            				<fileset dir="${unittest.src.dir}" includes="**/*Test.java" />
        			</batchtest>
    			</junit>
                </jacoco:coverage>
	</target>

 	<target name="integrationtest" depends="integrationtest-compile">
<!--	        <jacoco:coverage destfile="${result.exec.file}"> -->
    			<junit printsummary="on" haltonfailure="no" fork="true">
        			<classpath>
          				<path refid="test.classpath"/>
          				<pathelement location="${integrationtest.build.dir}"/>
        			</classpath>
        			<formatter type="brief" usefile="false" />
        			<batchtest>
            				<fileset dir="${integrationtest.src.dir}" includes="**/*Test.java" />
        			</batchtest>
    			</junit>
<!--                </jacoco:coverage> -->
	</target>

 	<target name="report">
                <jacoco:report>

                        <!-- This task needs the collected execution data and ... -->
                        <executiondata>
                                <file file="${result.exec.file}" />
                        </executiondata>

                        <!-- the class files and optional source files ... -->
                        <structure name="Constellation Test Coverage">
                                <classfiles>
                                        <fileset dir="${main.build.dir}" />
                                </classfiles>
                                <sourcefiles encoding="UTF-8">
                                        <fileset dir="${main.src.dir}" />
                                </sourcefiles>
                        </structure>

                        <!-- to produce reports in different formats. -->
                        <html destdir="${result.report.dir}" />
                        <csv destfile="${result.report.dir}/report.csv" />
                        <xml destfile="${result.report.dir}/report.xml" />
                </jacoco:report>
        </target>

 	<target name="test" depends="unittest,integrationtest,report">
        </target>

	<target name="bin.zip" depends="build">
		<delete failonerror="false" file="${zip}" />

		<zip destfile="${zip}">
			<zipfileset dir="." prefix="constellation-${version}" includes="external/**,jars/**,*.properties,*.example,notices/**,README.txt,INSTALL.txt,LICENSE.txt,javadoc/**" />
			<zipfileset dir="." prefix="constellation-${version}" filemode="755" includes="bin/**" />
		</zip>
	</target>

	<target name="src.zip" depends="build">
		<delete failonerror="false" file="${src-zip}" />

		<zip destfile="${src-zip}">
			<zipfileset dir="." prefix="constellation-${version}" includes="src/**,external/**,jars/**,*.properties,*.example,notices/**,README.txt,INSTALL.txt,LICENSE.txt,javadoc/**,build.xml" />
			<zipfileset dir="." prefix="constellation-${version}" filemode="755" includes="bin/**" />
		</zip>
	</target>

	<!-- remove all generated code -->
	<target name="clean" description="Removes the ${distdir} directory">
		<delete failonerror="false" dir="${builddir}" />
		<delete failonerror="false" dir="${distdir}" />
		<delete failonerror="false" dir="${javadoc}" />
		<delete failonerror="false" dir="${result.dir}" />
	</target>

	<target name="distclean" depends="clean">
		<delete failonerror="false" dir="./build-eclipse" />
		<delete failonerror="false" file="${zip}" />
		<delete failonerror="false" file="${src-zip}" />
	</target>

</project>


text:
using MarcelloDB.W81;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace UniversalTest
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public sealed partial class App : Application
    {
#if WINDOWS_PHONE_APP
        private TransitionCollection transitions;
#endif

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;

            var dataFolderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
            var session = new MarcelloDB.Session(new Platform(), dataFolderPath);
            var collection = session["data"].Collection<Article, int, ArticleIndex>("articles", a => a.ID);

            for (int i = 0; i < 1000; i++)
            {
                collection.Persist(new Article { ID = i, Name = string.Format("Article_{0}", i) });
            }
            for (int i = 0; i < 1000; i++)
           {
                var article = collection.Find(i);
                System.Diagnostics.Debug.Assert(article != null);
            }
            foreach (var article in collection.Indexes.Name.Between("Article_110").And("Article_120"))
            {
                System.Diagnostics.Debug.Assert(article != null);
            }

            System.Diagnostics.Debug.Assert(
                collection.Indexes.Name.Between("Article_110").AndIncluding("Article_120").Count() == 11
            );
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // TODO: change this value to a cache size that is appropriate for your application
                rootFrame.CacheSize = 1;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
#if WINDOWS_PHONE_APP
                // Removes the turnstile navigation for startup.
                if (rootFrame.ContentTransitions != null)
                {
                    this.transitions = new TransitionCollection();
                    foreach (var c in rootFrame.ContentTransitions)
                    {
                        this.transitions.Add(c);
                    }
                }

                rootFrame.ContentTransitions = null;
                rootFrame.Navigated += this.RootFrame_FirstNavigated;
#endif

                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }

#if WINDOWS_PHONE_APP
        /// <summary>
        /// Restores the content transitions after the app has launched.
        /// </summary>
        /// <param name="sender">The object where the handler is attached.</param>
        /// <param name="e">Details about the navigation event.</param>
        private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
        {
            var rootFrame = sender as Frame;
            rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
            rootFrame.Navigated -= this.RootFrame_FirstNavigated;
        }
#endif

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            // TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}


text:
package metadslx.core;

public interface MetaTypeConversionExpression extends metadslx.core.MetaExpression
{
    metadslx.core.MetaType getTypeReference();
    void setTypeReference(metadslx.core.MetaType value);
    metadslx.core.MetaExpression getExpression();
    void setExpression(metadslx.core.MetaExpression value);

}


text:
using Microsoft.EntityFrameworkCore.Migrations;

namespace TddBuddy.SpeedyLocalDb.EF.Example.Audit.DotNetCore.Migrations
{
    public partial class Added_Schema : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropPrimaryKey(
                name: "PK_AuditEntries",
                table: "AuditEntries");

            migrationBuilder.EnsureSchema(
                name: "aud");

            migrationBuilder.RenameTable(
                name: "AuditEntries",
                newName: "Entries",
                newSchema: "aud");

            migrationBuilder.AddPrimaryKey(
                name: "PK_Entries",
                schema: "aud",
                table: "Entries",
                column: "Id");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropPrimaryKey(
                name: "PK_Entries",
                schema: "aud",
                table: "Entries");

            migrationBuilder.RenameTable(
                name: "Entries",
                schema: "aud",
                newName: "AuditEntries");

            migrationBuilder.AddPrimaryKey(
                name: "PK_AuditEntries",
                table: "AuditEntries",
                column: "Id");
        }
    }
}


text:
package fr.paris.lutece.portal.business.user.parameter;

import fr.paris.lutece.portal.service.datastore.DatastoreService;

import org.apache.commons.lang3.StringUtils;

/**
 * The Class DefaultUserParameterHome.
 */
public final class DefaultUserParameterHome
{
    // Static variable pointed at the DAO instance
    /**
     * Instantiates a new default user parameter home.
     */
    private DefaultUserParameterHome( )
    {
    }

    /**
     * Load the parameter value.
     *
     * @param strParameterKey
     *            the parameter key
     * @return The parameter value
     */
    public static String findByKey( String strParameterKey )
    {
        return DatastoreService.getDataValue( strParameterKey, StringUtils.EMPTY );
    }

    /**
     * Update the parameter value.
     *
     * @param strParameterKey
     *            The User key
     * @param strParameterValue
     *            the value
     */
    public static void update( String strParameterKey, String strParameterValue )
    {
        DatastoreService.setDataValue( strParameterKey, strParameterValue );
    }
}


text:
import * as React from 'react';
import * as styles from './CommentThread.scss';
import {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import {BlogPost} from '../BlogPostDetail/BlogPostDetail';
import BlogPostSummary from '../BlogPostSummary/BlogPostSummary';
import logger from '../../../server/utils/logger/logger';
import CommentForm from './CommentForm';
import Comment from './Comment';
import {CommentData} from './Comment';
import Card from '../Card/Card';

interface CommentThreadProps {
  comments: CommentData[];
  user: any;
  onCommented: (content: string) => any;
}

const log = logger('COMMENT-THREAD');
export default class CommentThread extends Component<CommentThreadProps, void> {
  static propTypes = {
    comments: PropTypes.arrayOf(PropTypes.object),
    user: PropTypes.object,
    onCommented: PropTypes.func,
  };

  render() {
    const comments = this.props.comments || [];
    const hasComments = !!comments && !!comments.length;
    const user = this.props.user;
    const onCommented = this.props.onCommented;
    const showForm = !!user;

    log.info(`Comment thread has ${comments.length} comments`, user, comments);
    return (

Comments:

        {
          showForm && (<CommentForm profilePicUrl={user.pictureLargeUrl || user.pictureSmallUrl} onCommented={onCommented} />)
        }
        {
          !showForm && (
Sign in to comment
)
        }
        {
          !hasComments && (

              No comments on this blog post yet.

          )
        }
        {
          hasComments && (comments.map(comment => <Comment key={comment.id} comment={comment} />))
        }

    );
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Concept',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('lang', models.CharField(db_index=True, max_length=2, verbose_name='Language', choices=[(b'ru', 'Russian'), (b'en', 'English')])),
                ('about', models.URLField()),
                ('notation', models.CharField(max_length=32)),
                ('broader', models.URLField()),
                ('related', models.TextField(default=b'')),
                ('label', models.TextField()),
                ('notes', models.TextField(default=b'')),
            ],
            options={
                'ordering': ['notation'],
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name='concept',
            unique_together=set([('lang', 'notation'), ('lang', 'about')]),
        ),
    ]


text:
import Microcosm from '../../../src/microcosm'

describe('Effect::setup', function() {
  it('an effect is setup with options', function() {
    const repo = new Microcosm()
    const spy = jest.fn()

    class Effect {
      setup = spy
    }

    repo.addEffect(Effect, { test: true })

    expect(spy).toHaveBeenCalledWith(repo, { test: true })
  })
})


text:
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface HaxeEnumValueDeclaration extends HaxeComponent {

  @NotNull
  HaxeComponentName getComponentName();

  @Nullable
  HaxeEnumConstructorParameters getEnumConstructorParameters();

}


text:
.PHONY: test slow-test deploy

test:
	@echo "This is a test."
	@bash test.sh

slow-test:
	@sleep 1m && echo "This is a slow test."

deploy:
	@echo ":shipit:"


text:
export const environment = {
    production: false,
    server: 'https://uat-mksas-api.gaiaresources.com.au',
    apiExtension: '/api/',
    adminOnly: false,
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="slideswitch">
        <attr name="themeColor" format="color" />
        <attr name="isOpen" format="boolean" />
        <attr name="shape">
            <enum name="rect" value="1" />
            <enum name="circle" value="2" />
        </attr>
    </declare-styleable>
    <declare-styleable name="BezelImageView">
        <attr name="maskDrawable" format="reference" />
        <attr name="borderDrawable" format="reference" />
        <attr name="desaturateOnPress" format="boolean" />
    </declare-styleable>

    <declare-styleable name="CircleProgressBar">
        <attr name="mlpb_inner_radius" format="dimension"/>
        <attr name="mlpb_background_color" format="color"/>
        <attr name="mlpb_progress_color" format="color"/>
        <attr name="mlpb_progress_stoke_width" format="dimension"/>
        <attr name="mlpb_show_arrow" format="boolean"/>
        <attr name="mlpb_enable_circle_background" format="boolean"/>
        <attr name="mlpb_arrow_width" format="dimension"/>
        <attr name="mlpb_arrow_height" format="dimension"/>

        <attr name="mlpb_progress" format="integer"/>
        <attr name="mlpb_max" format="integer"/>

        <attr name="mlpb_progress_text_size" format="dimension"/>
        <attr name="mlpb_progress_text_color" format="color"/>

        <!--<attr name="mlpb_progress_text_offset" format="dimension"/>-->

        <attr name="mlpb_progress_text_visibility" format="enum">
            <enum name="visible" value="0"/>
            <enum name="invisible" value="1"/>
        </attr>
    </declare-styleable>
</resources>


text:
<!DOCTYPE html>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>check if requestAnimationFrame only schedules a single animation</title>

PASS If a red box display a text "500px" on screen

FAIL If a red box dosen't display a text "500px" on screen


text:
from buildbot.scheduler import Triggerable
from buildbot.schedulers.basic import SingleBranchScheduler

from master.factory import annotator_factory

m_annotator = annotator_factory.AnnotatorFactory()

def Update(config, active_master, c):
  c['schedulers'].extend([
      SingleBranchScheduler(name='mac_src',
                            branch='master',
                            treeStableTimer=60,
                            builderNames=[
          'Mac Builder',
          'Mac Builder (dbg)',
          'Mac GN',
          'Mac GN (dbg)',
      ]),
  ])
  specs = [
    {'name': 'Mac Builder'},
    {'name': 'Mac10.9 Tests'},
    {'name': 'Mac10.10 Tests'},
    {'name': 'Mac10.11 Tests'},
    {'name': 'Mac Builder (dbg)'},
    {'name': 'Mac10.9 Tests (dbg)'},
    {'name': 'Mac GN'},
    {'name': 'Mac GN (dbg)'},
  ]

  c['builders'].extend([
      {
        'name': spec['name'],
        'factory': m_annotator.BaseFactory(
            spec.get('recipe', 'chromium'),
            factory_properties=spec.get('factory_properties')),
        'notify_on_missing': True,
        'category': '3mac',
      } for spec in specs
  ])


text:
{-# LANGUAGE TypeFamilies #-}
import Control.Monad
import Criterion.Main
import Data.Mutable

test :: (MCState c ~ PrimState IO, RefElement c ~ Int, MutableRef c)
     => String
     -> (c -> c)
     -> Benchmark
test name forceType = bench name $ whnfIO $ do
    ref <- fmap forceType $ newRef (5 :: Int)
    replicateM_ 500 $ do
        modifyRef' ref (+ 1)
        modifyRef' ref (subtract 1)
        void $ readRef ref
    replicateM_ 500 $ do
        writeRef ref (5 :: Int)
        void $ readRef ref
{-# INLINE test #-}

main :: IO ()
main = defaultMain
    [ test "IORef" asIORef
    , test "STRef" asSTRef
    , test "MutVar" asMutVar
    , test "URef" asURef
    , test "PRef" asPRef
    , test "SRef" asSRef
    , test "BRef" asBRef
    ]


text:
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';

import config from '~api/config';
import { redisClient } from '~api/modules/redis';

const dateReviver = <T>(_: string, value: T): T | Date => {
  const isISO8601Z = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
  if (typeof value === 'string' && isISO8601Z.test(value)) {
    const tempDateNumber = Date.parse(value);
    if (!Number.isNaN(tempDateNumber)) {
      return new Date(tempDateNumber);
    }
  }
  return value;
};

export const redisClientSubscriber = new Redis(config.redis);

export const pubsub = new RedisPubSub({
  publisher: redisClient,
  subscriber: redisClientSubscriber,
  reviver: dateReviver,
});

export enum PubSubTopic {
  CashAllocationTargetUpdated = 'CashAllocationTargetUpdated',
  ConfigUpdated = 'ConfigUpdated',
  FundAllocationTargetsUpdated = 'FundAllocationTargetsUpdated',
  FundsChanged = 'FundsChanged',
  FundPricesUpdated = 'FundPricesUpdated',
  IncomeChanged = 'IncomeChanged',
  ListChanged = 'ListChanged',
  NetWorthCategoryCreated = 'NetWorthCategoryCreated',
  NetWorthCategoryUpdated = 'NetWorthCategoryUpdated',
  NetWorthCategoryDeleted = 'NetWorthCategoryDeleted',
  NetWorthSubcategoryCreated = 'NetWorthSubcategoryCreated',
  NetWorthSubcategoryUpdated = 'NetWorthSubcategoryUpdated',
  NetWorthSubcategoryDeleted = 'NetWorthSubcategoryDeleted',
  NetWorthEntryCreated = 'NetWorthEntryCreated',
  NetWorthEntryUpdated = 'NetWorthEntryUpdated',
  NetWorthEntryDeleted = 'NetWorthEntryDeleted',
  NetWorthCashTotalUpdated = 'NetWorthCashTotalUpdated',
  OverviewCostUpdated = 'OverviewCostUpdated',
  ReceiptCreated = 'ReceiptCreated',
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

include("./vendor/autoload.php");

use Omnipay\Omnipay;
use Omnipay\Common\CreditCard;

class Omnipaygateway extends Omnipay {

	protected $gateway = null;

	public function __construct($set_gateway='PayPal_Pro',$test_mode=true){
		$this->gateway = Omnipay::create($set_gateway);
		$this->gateway->setUsername('batikkode-facilitator_api1.gmail.com');
		$this->gateway->setPassword('SKJXNTSPZUUFR4L5');
		$this->gateway->setSignature('AFcWxV21C7fd0v3bYYYRCpSSRl31AHsyCp6cnyiiUJtWS.5bR.YdidWW');
		$this->gateway->setTestMode($test_mode);
	}

	public function sendPurchase($cardInput, $valTransaction){
		$card = new CreditCard($cardInput);
		$payArray = array(
			'amount'=> $valTransaction['amount'],
			'transactionId' => $valTransaction['transactionId'],
			'description'=> $valTransaction['description'],
			'currency'=>$valTransaction['currency'],
			'clientIp'=>$valTransaction['clientIp'],
			'returnUrl'=> $valTransaction['returnUrl'],
			'card'=>$card);
		$response = $this->gateway->purchase($payArray)->send();
		if($response->isSuccessful()){
			$paypalResponse = $response->getData();
		}elseif($response->isRedirect()){
			$paypalResponse = $response->getRedirectData();
		}else{
			$paypalResponse = $response->getMessage();
		}
		return $paypalResponse;
	}
}


text:
using GeoCoordinatePortable;
using OCM.API.Common;
using OCM.API.Common.Model.Extended;
using System;
using System.Collections.Generic;
using System.Linq;

namespace OCM.Core.Common
{
    public class DataAnalysisManager
    {
        public POIDuplicates GetAllPOIDuplicates(POIManager poiManager, int countryId, double maxDupeRange = 500)
        {
            List<DuplicatePOIItem> allDuplicates = new List<DuplicatePOIItem>();

            var dataModel = new OCM.Core.Data.OCMEntities();

            double DUPLICATE_DISTANCE_METERS = 25;
            double POSSIBLE_DUPLICATE_DISTANCE_METERS = maxDupeRange;

            //TODO: better method for large number of POIs
            //grab all live POIs (30-100,000 items)
            //var allPOIs = dataModel.ChargePoints.Where(s => s.AddressInfo.CountryID == countryId && (s.SubmissionStatusTypeID == 100 || s.SubmissionStatusTypeID == 200)).ToList();
            var allPOIs = poiManager.GetPOIList(new APIRequestParams { CountryIDs = new int[] { countryId }, MaxResults = 100000 });

            foreach (var poi in allPOIs)
            {
                //find pois which duplicate the given poi
                var dupePOIs = allPOIs.Where(p => p.ID != poi.ID &&
                    (
                        p.DataProvidersReference != null && p.DataProvidersReference.Length > 0 && p.DataProvidersReference == poi.DataProvidersReference
                        || new GeoCoordinate(p.AddressInfo.Latitude, p.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude)) < POSSIBLE_DUPLICATE_DISTANCE_METERS
                    )
                    );

                if (dupePOIs.Any())
                {
                    var poiModel = poi;// OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(poi, true, true, true, true);

                    foreach (var dupe in dupePOIs)
                    {
                        //poi has duplicates
                        DuplicatePOIItem dupePoi = new DuplicatePOIItem { DuplicatePOI = dupe, DuplicateOfPOI = poiModel };
                        dupePoi.Reasons = new List<string>();
                        if (dupe.AddressInfo.Latitude == poi.AddressInfo.Latitude && dupe.AddressInfo.Longitude == poi.AddressInfo.Longitude)
                        {
                            dupePoi.Reasons.Add("POI location is exact match for OCM-" + poi.ID);
                            dupePoi.Confidence = 95;
                        }
                        else
                        {
                            double distanceMeters = new GeoCoordinate(dupe.AddressInfo.Latitude, dupe.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude));
                            if (distanceMeters < DUPLICATE_DISTANCE_METERS)
                            {
                                dupePoi.Reasons.Add("POI location is close proximity (" + distanceMeters + "m) to OCM-" + poi.ID);
                                dupePoi.Confidence = 75;
                            }
                            else
                            {
                                if (distanceMeters < POSSIBLE_DUPLICATE_DISTANCE_METERS)
                                {
                                    dupePoi.Reasons.Add("POI location is in surrounding proximity (" + distanceMeters + "m) to OCM-" + poi.ID);
                                    dupePoi.Confidence = 50;
                                }
                            }
                        }

                        allDuplicates.Add(dupePoi);
                    }
                }
            }

            //arrange all duplicates into groups
            POIDuplicates duplicatesSummary = new POIDuplicates();
            duplicatesSummary.DuplicateSummaryList = new List<DuplicatePOIGroup>();
            foreach (var dupe in allDuplicates)
            {
                bool isNewGroup = false;
                var dupeGroup = duplicatesSummary.DuplicateSummaryList.FirstOrDefault(d => d.DuplicatePOIList.Any(p => p.DuplicateOfPOI.ID == dupe.DuplicateOfPOI.ID || p.DuplicatePOI.ID == dupe.DuplicatePOI.ID) || d.SuggestedBestPOI.ID == dupe.DuplicatePOI.ID);
                if (dupeGroup == null)
                {
                    isNewGroup = true;
                    dupeGroup = new DuplicatePOIGroup();
                    dupeGroup.SuggestedBestPOI = dupe.DuplicatePOI;//TODO: select best

                    dupeGroup.DuplicatePOIList = new List<DuplicatePOIItem>();
                }

                //only add to dupe group if not already added for another reason
                if (!dupeGroup.DuplicatePOIList.Contains(dupe) && !dupeGroup.DuplicatePOIList.Any(d => d.DuplicatePOI.ID == dupe.DuplicatePOI.ID))
                {
                    dupeGroup.DuplicatePOIList.Add(dupe);
                }

                if (isNewGroup)
                {
                    duplicatesSummary.DuplicateSummaryList.Add(dupeGroup);
                }
            }

            //loop through groups and rearrange
            RearrangeDuplicates(duplicatesSummary);

            //go through all groups and populate final list of All POI per group
            foreach (var g in duplicatesSummary.DuplicateSummaryList)
            {
                var poiList = new List<OCM.API.Common.Model.ChargePoint>();
                foreach (var d in g.DuplicatePOIList)
                {
                    if (!poiList.Contains(d.DuplicatePOI))
                    {
                        poiList.Add(d.DuplicatePOI);
                    }

                    if (!poiList.Contains(d.DuplicateOfPOI))
                    {
                        poiList.Add(d.DuplicateOfPOI);
                    }

                    g.AllPOI = poiList;
                }
            }

            //TODO: go through all dupe groups and nominate best poi to be main poi (most comments, most equipment info etc)
            return duplicatesSummary;
        }

        private bool OtherDuplicationPOIGroupListHasReference(POIDuplicates duplicates, int poiId, DuplicatePOIGroup currentGroup)
        {
            var mentionedGroups = duplicates.DuplicateSummaryList.Where(d => d.DuplicatePOIList.Any(p => p.DuplicateOfPOI.ID == poiId || p.DuplicatePOI.ID == poiId));
            if (mentionedGroups.Any(m => m != currentGroup))
            {
                //POI has a mention in another group
                return true;
            }
            else
            {
                //POI not mentioned in any other group
                return false;
            }
        }

        /// <summary>
        /// Recursive grouping of duplicates into groups, removing unused/redundant groups
        /// </summary>
        /// <param name="duplicates"></param>
        /// <returns></returns>
        private bool RearrangeDuplicates(POIDuplicates duplicates)
        {
            var actionRequired = false;

            var removedgroups = new List<DuplicatePOIGroup>();
            foreach (var dupegroup in duplicates.DuplicateSummaryList)
            {
                var removedDupes = new List<DuplicatePOIItem>();
                foreach (var dupe in dupegroup.DuplicatePOIList)
                {
                    //if dupe variation is identified an another group, remove from this group
                    if (OtherDuplicationPOIGroupListHasReference(duplicates, dupe.DuplicatePOI.ID, dupegroup))
                    {
                        removedDupes.Add(dupe);
                    }
                }

                if (removedDupes.Any())
                {
                    actionRequired = true;
                    //remove all dupes already present in other groups
                    dupegroup.DuplicatePOIList.RemoveAll(d => removedDupes.Contains(d));
                }

                if (!dupegroup.DuplicatePOIList.Any())
                {
                    actionRequired = true;
                    removedgroups.Add(dupegroup);
                }
            }

            if (removedgroups.Any())
            {
                actionRequired = true;
                //remove empty groups
                duplicates.DuplicateSummaryList.RemoveAll(g => removedgroups.Contains(g));
            }

            //did something this pass, recurse to see if more needed
            if (actionRequired) RearrangeDuplicates(duplicates);

            return actionRequired;
        }

        /// <summary>
        /// For given POI, return data quality report and supporting analysis results
        /// </summary>
        /// <param name="poi"></param>
        /// <returns></returns>
        public POIDataQualityReport CheckPOIDataQuality(OCM.API.Common.Model.ChargePoint poi)
        {
            var report = new POIDataQualityReport();
            report.POI = poi;

            DateTime recentUpdateThreshold = DateTime.UtcNow.AddMonths(-6);

            if (
                (poi.DateLastConfirmed.HasValue && !(poi.DateLastConfirmed.Value > recentUpdateThreshold))
                ||
                (poi.UserComments != null && poi.UserComments.Any(u => u.CheckinStatusType != null && u.CheckinStatusType.IsPositive == true && u.DateCreated > recentUpdateThreshold))
                ||
                (poi.MediaItems != null && poi.MediaItems.Any(u => u.DateCreated > recentUpdateThreshold))
                )
            {
                //has either a recent datelastconfirmed value or a recent positive checkin
                report.ReportItems.Add(new DataQualityReportItem { Category = "User Feedback", Comment = "Has recent user verification", IsPositive = true });
            }
            else
            {
                //low quality score for date last confirmed
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 10, Category = "User Feedback", Comment = "No recent user verification.", IsPositive = false });
            }

            if (poi.UserComments == null || (poi.UserComments != null && !poi.UserComments.Any()))
            {
                //low quality score for comments
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 10, Category = "User Feedback", Comment = "No comments or check-ins", IsPositive = false });
            }
            else
            {
                report.ReportItems.Add(new DataQualityReportItem { Category = "User Feedback", Comment = "Has comments or check-ins", IsPositive = true });
            }

            if (poi.MediaItems == null || (poi.MediaItems != null && !poi.MediaItems.Any()))
            {
                //low quality score for photos
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 10, Category = "User Feedback", Comment = "No photos", IsPositive = false });
            }
            else
            {
                report.ReportItems.Add(new DataQualityReportItem { Category = "User Feedback", Comment = "Has photos", IsPositive = true });
            }

            if (poi.UsageTypeID == null || (poi.UsageTypeID != null && poi.UsageType.ID == 0))
            {
                //low quality score for usage type
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 10, Category = "Data Completeness", Comment = "Unknown Usage Type", IsPositive = false });
            }
            else
            {
                report.ReportItems.Add(new DataQualityReportItem { Category = "Data Completeness", Comment = "Usage Type Known", IsPositive = true });
            }
            if (poi.StatusType == null || (poi.StatusType != null && poi.StatusType.ID == 0))
            {
                //low quality score for status type
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 10, Category = "Data Completeness", Comment = "Unknown Operational Status", IsPositive = false });
            }
            else
            {
                report.ReportItems.Add(new DataQualityReportItem { Category = "Data Completeness", Comment = "Operational Status Known", IsPositive = true });
            }

            if (poi.Connections == null || !poi.Connections.Any())
            {
                report.ReportItems.Add(new DataQualityReportItem { Weighting = 50, Category = "Data Completeness", Comment = "No Equipment Details", IsPositive = false });
            }
            else
            {
                report.ReportItems.Add(new DataQualityReportItem { Category = "Data Completeness", Comment = "Equipment Details Present", IsPositive = true });
            }

            //data quality score starts at 5 (excellent) and is reduced towards 0 for each data issue

            double totalPoints = 100;
            foreach (var p in report.ReportItems.Where(r => r.IsPositive == false))
            {
                totalPoints -= p.Weighting;
            }
            if (totalPoints < 0) totalPoints = 0;
            report.DataQualityScore = totalPoints;

            return report;
        }

        public DataQualityReport GetDataQualityReport(OCM.API.Common.Model.ChargePoint poi)
        {
            DataQualityReport report = new DataQualityReport();
            report.POIReports.Add(CheckPOIDataQuality(poi));
            return report;
        }

        public DataQualityReport GetDataQualityReport(List<OCM.API.Common.Model.ChargePoint> poiList)
        {
            DataQualityReport report = new DataQualityReport();

            foreach (var poi in poiList)
            {
                var poiReport = CheckPOIDataQuality(poi);
                report.POIReports.Add(poiReport);
            }

            return report;
        }
    }
}


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

using Xamarin.Forms;

namespace SwitchCloneDemo
{
    public partial class SwitchCloneDemoPage : ContentPage
    {
        public SwitchCloneDemoPage()
        {
            InitializeComponent();
        }
    }
}


text:
ContactSwitch::ContactSwitch(uint8_t buttonPin) {
    _pin           = buttonPin;
    _activeHigh    = LOW;           // Assume active-low button
    _btnState      = !_activeHigh;  // initial button state in active-high logic
    _lastState     = _btnState;
    _clickCount    = 0;
    depressed      = false;
    _lastBounceTime= 0;
    debounceTime   = 20;            // Debounce timer in ms
    pinMode(_pin, INPUT);
}

void ContactSwitch::Update() {
    long now = (long)millis();      // get current time
    _btnState = digitalRead(_pin);  // current appearant button state

    // If the switch changed, due to noise or a button press, reset the debounce timer
    if (_btnState != _lastState) _lastBounceTime = now;

    // debounce the button (Check if a stable, changed state has occured)
    if (now - _lastBounceTime > debounceTime) {
        stableState = _btnState;
    }

    _lastState = _btnState;
}