text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2018 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.util.ErrorMessages;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.Manifest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Non-visible component providing location information, including {@link #Latitude()},
 * {@link #Longitude()}, {@link #Altitude()} (if supported by the device), speed (if supported by
 * the device), and address. This can also perform "geocoding", converting a given address (not
 * necessarily the current one) to a latitude (with the {@link #LatitudeFromAddress(String)}
 * method) and a longitude (with the {@link #LongitudeFromAddress(String)} method).
 *
 * In order to function, the component must have its {@link #Enabled(boolean)} property set to
 * `true`{:.logic.block}, and the device must have location sensing enabled through wireless
 * networks or GPS satellites (if outdoors).
 *
 * Location information might not be immediately available when an app starts. You'll have to wait
 * a short time for a location provider to be found and used, or wait for the
 * {@link #LocationChanged(double, double, double, float)} event.
 *
 * The emulator does not emulate sensors on all devices. Code should be tested on a physical device.
 */
@DesignerComponent(version = YaVersion.LOCATIONSENSOR_COMPONENT_VERSION,
    description = "Non-visible component providing location information, " +
    "including longitude, latitude, altitude (if supported by the device), " +
    "speed (if supported by the device), " +
    "and address.  This can also perform \"geocoding\", converting a given " +
    "address (not necessarily the current one) to a latitude (with the " +
    "LatitudeFromAddress method) and a longitude (with the " +
    "LongitudeFromAddress method).
\n" +
    "
In order to function, the component must have its " +
    "Enabled property set to True, and the device must have " +
    "location sensing enabled through wireless networks or GPS " +
    "satellites (if outdoors).
\n" +
    "Location information might not be immediately available when an app starts.  You'll have to wait a short time for " +
    "a location provider to be found and used, or wait for the LocationChanged event",
    category = ComponentCategory.SENSORS,
    nonVisible = true,
    iconName = "images/locationSensor.png")
@SimpleObject
@UsesPermissions(permissionNames =
                 "android.permission.ACCESS_FINE_LOCATION," +
                 "android.permission.ACCESS_COARSE_LOCATION," +
                 "android.permission.ACCESS_MOCK_LOCATION," +
                 "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS")
public class LocationSensor extends AndroidNonvisibleComponent
    implements Component, OnStopListener, OnResumeListener, Deleteable {

  public interface LocationSensorListener extends LocationListener {
    void onTimeIntervalChanged(int time);
    void onDistanceIntervalChanged(int distance);
    void setSource(LocationSensor provider);
  }

  /**
   * Class that listens for changes in location, raises appropriate events,
   * and provides properties.
   *
   */
  private class MyLocationListener implements LocationListener {
    @Override
    // This sets fields longitude, latitude, altitude, hasLocationData, and
    // hasAltitude, then calls LocationSensor.LocationChanged(), all in the
    // enclosing class LocationSensor.
    public void onLocationChanged(final Location location) {
      lastLocation = location;
      longitude = location.getLongitude();
      latitude = location.getLatitude();
      speed = location.getSpeed();
      // If the current location doesn't have altitude information, the prior
      // altitude reading is retained.
      if (location.hasAltitude()) {
        hasAltitude = true;
        altitude = location.getAltitude();
      }

      // By default Location.latitude == Location.longitude == 0.
      // So we want to ignore that case rather than generating a changed event.
      if (longitude != UNKNOWN_VALUE || latitude != UNKNOWN_VALUE) {
        hasLocationData = true;
        final double argLatitude = latitude;
        final double argLongitude = longitude;
        final double argAltitude = altitude;
        final float argSpeed = speed;
        androidUIHandler.post(new Runnable() {
            @Override
            public void run() {
              LocationChanged(argLatitude, argLongitude, argAltitude, argSpeed);
              for (LocationSensorListener listener : listeners) {
                listener.onLocationChanged(location);
              }
            }
          });
      }
    }

    @Override
    public void onProviderDisabled(String provider) {
      StatusChanged(provider, "Disabled");
      stopListening();
      if (enabled) {
        RefreshProvider("onProviderDisabled");
      }
    }

    @Override
    public void onProviderEnabled(String provider) {
      StatusChanged(provider, "Enabled");
      RefreshProvider("onProviderEnabled");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
      switch (status) {
        // Ignore TEMPORARILY_UNAVAILABLE, because service usually returns quickly.
        case LocationProvider.TEMPORARILY_UNAVAILABLE:
          StatusChanged(provider, "TEMPORARILY_UNAVAILABLE");
          break;
        case LocationProvider.OUT_OF_SERVICE:
          // If the provider we were listening to is no longer available,
          // find another.
          StatusChanged(provider, "OUT_OF_SERVICE");

          if (provider.equals(providerName)) {
            stopListening();
            RefreshProvider("onStatusChanged");
          }
          break;
        case LocationProvider.AVAILABLE:
          // If another provider becomes available and is one we hadn't known
          // about see if it is better than the one we're currently using.
          StatusChanged(provider, "AVAILABLE");
          if (!provider.equals(providerName) &&
              !allProviders.contains(provider)) {
            RefreshProvider("onStatusChanged");
          }
          break;
      }
    }
  }

  /**
   * Constant returned by {@link #Longitude()}, {@link #Latitude()}, and
   * {@link #Altitude()} if no value could be obtained for them.  The client
   * can find this out directly by calling {@link #HasLongitudeLatitude()} or
   * {@link #HasAltitude()}.
   */
  public static final int UNKNOWN_VALUE = 0;

  // These variables contain information related to the LocationProvider.
  private final Criteria locationCriteria;
  private final Handler handler;
  private final LocationManager locationManager;

  private final Set<LocationSensorListener> listeners = new HashSet<LocationSensorListener>();

  private boolean providerLocked = false; // if true we can't change providerName
  private String providerName;
  // Invariant: providerLocked => providerName is non-empty

  private boolean initialized = false;

  private int timeInterval;
  private int distanceInterval;

  private MyLocationListener myLocationListener;

  private LocationProvider locationProvider;
  private boolean listening = false;
    // Invariant: listening <=> a myLocationListener is registered with locationManager
    // Invariant: !listening <=> locationProvider == null

  //This holds all the providers available when we last chose providerName.
  //The reported best provider is first, possibly duplicated.
  private List<String> allProviders;

  // These location-related values are set in MyLocationListener.onLocationChanged().
  private Location lastLocation;
  private double longitude = UNKNOWN_VALUE;
  private double latitude = UNKNOWN_VALUE;
  private double altitude = UNKNOWN_VALUE;
  private float speed = UNKNOWN_VALUE;
  private boolean hasLocationData = false;
  private boolean hasAltitude = false;

  // For posting events on the UI thread
  private final Handler androidUIHandler = new Handler();

  // This is used in reverse geocoding.
  private Geocoder geocoder;

  // User-settable properties
  private boolean enabled = true;  // the default value is true

  private boolean havePermission = false; // Do we have the necessary permission
  private static final String LOG_TAG = LocationSensor.class.getSimpleName();

  /**
   * Creates a new LocationSensor component.
   *
   * @param container  ignored (because this is a non-visible component)
   */
  public LocationSensor(ComponentContainer container) {
    this(container, true);
  }

  /**
   * Creates a new LocationSensor component with a default state of enabled.
   *
   * @param container  ignored (because this is a non-visible component)
   * @param enabled  true if the LocationSensor is enabled by default, otherwise false.
   */
  public LocationSensor(ComponentContainer container, boolean enabled) {
    super(container.$form());
    this.enabled = enabled;
    handler = new Handler();
    // Set up listener
    form.registerForOnResume(this);
    form.registerForOnStop(this);

    // Initialize sensor properties (60 seconds; 5 meters)
    timeInterval = 60000;
    distanceInterval = 5;

    // Initialize location-related fields
    Context context = container.$context();
    geocoder = new Geocoder(context);
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    locationCriteria = new Criteria();
    myLocationListener = new MyLocationListener();
    allProviders = new ArrayList<String>();
    // Do some initialization depending on the initial enabled state
    Enabled(enabled);
  }

  @SuppressWarnings({"unused"})  // Called from Scheme
  public void Initialize() {
    initialized = true;
    Enabled(enabled);
  }

  // Events

  /**
   * Indicates that a new location has been detected. Speed is reported in meters/second
   * Other values match their properties.
   */
  @SimpleEvent(description = "Indicates that a new location has been detected.")
  public void LocationChanged(double latitude, double longitude, double altitude, float speed) {
    EventDispatcher.dispatchEvent(this, "LocationChanged", latitude, longitude, altitude, speed);
  }

  /**
   * Indicates that the status of the location provider service has changed, such as when a
   * provider is lost or a new provider starts being used.
   */
  @SimpleEvent
  public void StatusChanged(String provider, String status) {
    if (enabled) {
      EventDispatcher.dispatchEvent(this, "StatusChanged", provider, status);
    }
  }

  // Properties

  /**
   * Indicates the source of the location information.  If there is no provider, the
   * string "NO PROVIDER" is returned.  This is useful primarily for debugging.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public String ProviderName() {
    if (providerName == null) {
      return "NO PROVIDER";
    } else {
      return providerName;
    }
  }

  /**
   * The current service provider. The provider will most likely be either GPS or network.
   *
   * @internaldoc
   * Change the location provider.
   * If the blocks program changes the name, try to change the provider.
   * Whatever happens now, the provider and the reported name may be switched to
   * Android's preferred provider later. This is primarily for debugging.
   */
  @SimpleProperty
  public void ProviderName(String providerName) {
    this.providerName = providerName;
    if (!empty(providerName) && startProvider(providerName)) {
      return;
    } else {
      RefreshProvider("ProviderName");
    }
  }

  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public boolean ProviderLocked() {
    return providerLocked;
  }

  /**
   * The device will not change the service provider.
   *
   *   It is possible for a device to switch service providers when the current provider is unable
   * to provide adequate location information. `ProviderLocked` is a Boolean value: true/false.
   * Set to `true`{:.logic.block} to prevent providers from changing. Set to `false`{:.logic.block}
   * to allow for automatic switching when necessary.
   *
   * @internaldoc
   * Indicates whether the sensor should allow the developer to
   * manually change the provider (GPS, GSM, Wifi, etc.)
   * from which location updates are received.
   */
  @SimpleProperty
  public void ProviderLocked(boolean lock) {
      providerLocked = lock;
  }

  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_SENSOR_TIME_INTERVAL,
      defaultValue = "60000")
  @SimpleProperty
  public void TimeInterval(int interval) {

      // make sure that the provided value is a valid one.
      // choose 1000000 miliseconds to be the upper limit
      if (interval < 0 || interval > 1000000)
          return;

      timeInterval = interval;

      // restart listening for location updates, using the new time interval
      if (enabled) {
          RefreshProvider("TimeInterval");
      }

      for (LocationSensorListener listener : listeners) {
        listener.onTimeIntervalChanged(timeInterval);
      }
  }

  /**
   * Determines the minimum time interval, in milliseconds, that the sensor will try to use for
   * sending out location updates. However, location updates will only be received when the
   * location of the phone actually changes, and use of the specified time interval is not
   * guaranteed. For example, if 30000 is used as the time interval, location updates will never
   * be fired sooner than 30000ms, but they may be fired anytime after.
   *
   *   Values smaller than 30000ms (30 seconds) are not practical for most devices. Small values
   * may drain battery and overwork the GPS.
   */
  @SimpleProperty(
      description = "Determines the minimum time interval, in milliseconds, that the sensor will try " +
          "to use for sending out location updates. However, location updates will only be received " +
          "when the location of the phone actually changes, and use of the specified time interval " +
          "is not guaranteed. For example, if 1000 is used as the time interval, location updates will " +
          "never be fired sooner than 1000ms, but they may be fired anytime after.",
          category = PropertyCategory.BEHAVIOR)
  public int TimeInterval() {
      return timeInterval;
  }

  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_SENSOR_DIST_INTERVAL,
      defaultValue = "5")
  @SimpleProperty
  public void DistanceInterval(int interval) {

      // make sure that the provided value is a valid one.
      // choose 1000 meters to be the upper limit
      if (interval < 0 || interval > 1000)
          return;

      distanceInterval = interval;

      // restart listening for location updates, using the new distance interval
      if (enabled) {
          RefreshProvider("DistanceInterval");
      }

      for (LocationSensorListener listener : listeners) {
        listener.onDistanceIntervalChanged(distanceInterval);
      }
  }

  /**
   * Determines the minimum distance interval, in meters, that the sensor will try to use for
   * sending out location updates. For example, if this is set to 50, then the sensor will fire a
   * {@link #LocationChanged(double, double, double, float)} event only after 50 meters have been
   * traversed. However, the sensor does not guarantee that an update will be received at exactly
   * the distance interval. It may take more than 5 meters to fire an event, for instance.
   *
   *   It is also useful to check against {@link #Accuracy()} when using this property. When your
   * device is moving, the accuracy of the detected location is constantly changing.
   */
  @SimpleProperty(
      description = "Determines the minimum distance interval, in meters, that the sensor will try " +
      "to use for sending out location updates. For example, if this is set to 5, then the sensor will " +
      "fire a LocationChanged event only after 5 meters have been traversed. However, the sensor does " +
      "not guarantee that an update will be received at exactly the distance interval. It may take more " +
      "than 5 meters to fire an event, for instance.",
      category = PropertyCategory.BEHAVIOR)
  public int DistanceInterval() {
      return distanceInterval;
  }

  /**
   * If `true`{:.logic.block}, the device can report longitude and latitude.  It is
   * always the case that either both or neither are.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public boolean HasLongitudeLatitude() {
    return hasLocationData && enabled;
  }

  /**
   * If `true`{:.logic.block}, the device can report its altitude.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public boolean HasAltitude() {
    return hasAltitude && enabled;
  }

  /**
   * If `true`{:.logic.block}, the device can report its accuracy level.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public boolean HasAccuracy() {
    return Accuracy() != UNKNOWN_VALUE && enabled;
  }

  /**
   * The most recent available longitude value in degrees reported to 5 decimal places.
   * If no value is available, 0 will be returned.
   * Longitude is a value between 180 (east) and -180 (west), where 0 marks the Prime Meridian.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public double Longitude() {
    return longitude;
  }

  /**
   * The most recently available latitude value in degrees reported to 5 decimal places.
   * If no value is available, 0 will be returned.
   * Latitude is a value between 90 (north) and -90 (south), where 0 marks the Equator.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public double Latitude() {
      return latitude;
  }

  /**
   * Altitude of the device measured in meters, if available.
   *
   *   Altitude is measured from the
   * [World Geodetic System 84 reference ellipsoid](https://gisgeography.com/wgs84-world-geodetic-system/),
   * not sea level.
   *
   *   Note that it is difficult for devices to accurately sense altitude. Altitude reported on a
   * phone/tablet can easily be off by 30 meters or more.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR,
      description = "The most recently available altitude value, in meters.  If no value is "
          + "available, 0 will be returned.")
  public double Altitude() {
    return altitude;
  }

  /**
   * The `LocationSensor` will be able to locate the device with a varying degree of confidence,
   * based on the quality of satellite, cell towers, and other data used to estimate location.
   * The `Accuracy` value is the radius in meters around the sensor's detected location. The device
   * has a 68% chance to be located within this radius. More precise location detection will result
   * in a smaller accuracy number, which allows the app to have more confidence where the device
   * is actually located.
   *
   *   If the accuracy is not known, the return value is 0.0
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR,
      description = "The most recent measure of accuracy, in meters.  If no value is available, "
          + "0 will be returned.")
  public double Accuracy() {
    if (lastLocation != null && lastLocation.hasAccuracy()) {
      return lastLocation.getAccuracy();
    } else if (locationProvider != null) {
      return locationProvider.getAccuracy();
    } else {
      return UNKNOWN_VALUE;
    }
  }

  /**
   * Indicates whether the user has specified that the sensor should
   * listen for location changes and raise the corresponding events.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public boolean Enabled() {
    return enabled;
  }

  /**
   * If `true`{:.logic.block}, the `LocationSensor` will attempt to read location information from
   * GPS, WiFi location, or other means available on the device. This setting does not control
   * whether location information is actually available. Device location must be enabled or
   * disabled in the device settings.
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN,
      defaultValue = "True")
  @SimpleProperty
  public void Enabled(boolean enabled) {
    this.enabled = enabled;
    if (!initialized) {
      return;
    }
    if (!enabled) {
      stopListening();
    } else {
      RefreshProvider("Enabled");
    }
  }

  /**
   * Physical street address of the device from Google's map database.
   *
   *   The address might not always be available from the provider, and the address reported may not
   * always be of the building where the device is located.
   *
   *   If Google has no address information available for a particular location, this will return
   * `No address available`.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR,
      description = "Provides a textual representation of the current address or \"No address "
          + "available\".")
  public String CurrentAddress() {
    if (hasLocationData &&
        latitude <= 90 && latitude >= -90 &&
        longitude <= 180 || longitude >= -180) {
      try {
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null && addresses.size() == 1) {
          Address address = addresses.get(0);
          if (address != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
              sb.append(address.getAddressLine(i));
              sb.append("\n");
            }
            return sb.toString();
          }
        }

      } catch (Exception e) {
        // getFromLocation can throw an IOException or an IllegalArgumentException
        // a bad result can give an indexOutOfBoundsException
        // are there others?
        if (e instanceof IllegalArgumentException
            || e instanceof IOException
            || e instanceof IndexOutOfBoundsException ) {
          Log.e(LOG_TAG, "Exception thrown by getting current address " + e.getMessage());
        } else {
          // what other exceptions can happen here?
          Log.e(LOG_TAG,
              "Unexpected exception thrown by getting current address " + e.getMessage());
        }
      }
    }
    return "No address available";
  }

  /**
   * Derives latitude from the given `locationName`.
   *
   * @param locationName  human-readable address
   *
   * @return latitude in degrees, 0 if not found.
   */
  @SimpleFunction(description = "Derives latitude of given address")
  public double LatitudeFromAddress(String locationName) {
    try {
      List<Address> addressObjs = geocoder.getFromLocationName(locationName, 1);
      Log.i(LOG_TAG, "latitude addressObjs size is " + addressObjs.size() + " for " + locationName);
      if ( (addressObjs == null) || (addressObjs.size() == 0) ){
        throw new IOException("");
      }
      return addressObjs.get(0).getLatitude();
    } catch (IOException e) {
      form.dispatchErrorOccurredEvent(this, "LatitudeFromAddress",
          ErrorMessages.ERROR_LOCATION_SENSOR_LATITUDE_NOT_FOUND, locationName);
      return 0;
    }
  }

  /**
   * Derives longitude from the given `locationName`.
   *
   * @param locationName  human-readable address
   *
   * @return longitude in degrees, 0 if not found.
   */
  @SimpleFunction(description = "Derives longitude of given address")
  public double LongitudeFromAddress(String locationName) {
    try {
      List<Address> addressObjs = geocoder.getFromLocationName(locationName, 1);
      Log.i(LOG_TAG, "longitude addressObjs size is " + addressObjs.size() + " for " + locationName);
      if ( (addressObjs == null) || (addressObjs.size() == 0) ){
        throw new IOException("");
      }
      return addressObjs.get(0).getLongitude();
    } catch (IOException e) {
      form.dispatchErrorOccurredEvent(this, "LongitudeFromAddress",
          ErrorMessages.ERROR_LOCATION_SENSOR_LONGITUDE_NOT_FOUND, locationName);
      return 0;
    }
  }

  /**
   * List of available service providers, such as gps or network. This information is provided
   * as a list and in text form.
   */
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public List<String> AvailableProviders () {
    return allProviders;
  }

  // Methods to stop and start listening to LocationProviders

  /**
   * Refresh provider attempts to choose and start the best provider unless
   * someone has set and locked the provider. Currently, blocks programmers
   * cannot do that because the relevant methods are not declared as properties.
   *
   */

  // @SimpleFunction(description = "Find and start listening to a location provider.")
  public void RefreshProvider(final String caller) {
    if (!initialized) return;    // Not yet ready to start...
    stopListening();             // In case another provider is active.
    final LocationSensor me = this;
    if (!havePermission) {
      // Make sure we do this on the UI thread
      androidUIHandler.post(new Runnable() {
          @Override
          public void run() {
            me.form.askPermission(Manifest.permission.ACCESS_FINE_LOCATION,
              new PermissionResultHandler() {
                @Override
                public void HandlePermissionResponse(String permission, boolean granted) {
                  if (granted) {
                    me.havePermission = true;
                    me.RefreshProvider(caller);
                    Log.d(LOG_TAG, "Permission Granted");
                  } else {
                    me.havePermission = false;
                    me.enabled = false;
                    me.form.dispatchPermissionDeniedEvent(me, caller, Manifest.permission.ACCESS_FINE_LOCATION);
                  }
                }
              });
          }
        });
    }
    if (providerLocked && !empty(providerName)) {
      listening = startProvider(providerName);
      return;
    }
    allProviders = locationManager.getProviders(true);  // Typically it's ("network" "gps")
    String bProviderName = locationManager.getBestProvider(locationCriteria, true);
    if (bProviderName != null && !bProviderName.equals(allProviders.get(0))) {
      allProviders.add(0, bProviderName);
    }
    // We'll now try the best first and stop as soon as one successfully starts.
    for (String providerN : allProviders) {
      listening = startProvider(providerN);
      if (listening) {
        if (!providerLocked) {
          providerName = providerN;
        }
        return;
      }
    }
  }

  /* Start listening to ProviderName.
   * Return true iff successful.
   */
  private boolean startProvider(final String providerName) {
    this.providerName = providerName;
    LocationProvider tLocationProvider = locationManager.getProvider(providerName);
    if (tLocationProvider == null) {
      Log.d(LOG_TAG, "getProvider(" + providerName + ") returned null");
      return false;
    }
    stopListening();
    locationProvider = tLocationProvider;
    locationManager.requestLocationUpdates(providerName, timeInterval,
          distanceInterval, myLocationListener);
    listening = true;
    return true;
  }

  /**
   * This unregisters {@link #myLocationListener} as a listener to location
   * updates.  It is safe to call this even if no listener had been registered,
   * in which case it has no effect.  This also sets the value of
   * {@link #locationProvider} to {@code null} and sets {@link #listening}
   * to {@code false}.
   */
  private void stopListening() {
    if (listening) {
      locationManager.removeUpdates(myLocationListener);
      locationProvider = null;
      listening = false;
    }
  }

  // OnResumeListener implementation

  @Override
  public void onResume() {
    if (enabled) {
      RefreshProvider("onResume");
    }
  }

  // OnStopListener implementation

  @Override
  public void onStop() {
    stopListening();
  }

  // Deleteable implementation

  @Override
  public void onDelete() {
    stopListening();
  }

  public void addListener(LocationSensorListener listener) {
    listener.setSource(this);
    listeners.add(listener);
  }

  public void removeListener(LocationSensorListener listener) {
    listeners.remove(listener);
    listener.setSource(null);
  }

  private boolean empty(String s) {
    return s == null || s.length() == 0;
  }
}


text:
<?php

// File generated from our OpenAPI spec

namespace Stripe\Service\Terminal;

class ReaderService extends \Stripe\Service\AbstractService
{
    /**
     * Returns a list of Reader objects.
     *
     * @param null|array $params
     * @param null|array|\Stripe\Util\RequestOptions $opts
     *
     * @throws \Stripe\Exception\ApiErrorException if the request fails
     *
     * @return \Stripe\Collection
     */
    public function all($params = null, $opts = null)
    {
        return $this->requestCollection('get', '/v1/terminal/readers', $params, $opts);
    }

    /**
     * Creates a new Reader object.
     *
     * @param null|array $params
     * @param null|array|\Stripe\Util\RequestOptions $opts
     *
     * @throws \Stripe\Exception\ApiErrorException if the request fails
     *
     * @return \Stripe\Terminal\Reader
     */
    public function create($params = null, $opts = null)
    {
        return $this->request('post', '/v1/terminal/readers', $params, $opts);
    }

    /**
     * Deletes a Reader object.
     *
     * @param string $id
     * @param null|array $params
     * @param null|array|\Stripe\Util\RequestOptions $opts
     *
     * @throws \Stripe\Exception\ApiErrorException if the request fails
     *
     * @return \Stripe\Terminal\Reader
     */
    public function delete($id, $params = null, $opts = null)
    {
        return $this->request('delete', $this->buildPath('/v1/terminal/readers/%s', $id), $params, $opts);
    }

    /**
     * Retrieves a Reader object.
     *
     * @param string $id
     * @param null|array $params
     * @param null|array|\Stripe\Util\RequestOptions $opts
     *
     * @throws \Stripe\Exception\ApiErrorException if the request fails
     *
     * @return \Stripe\Terminal\Reader
     */
    public function retrieve($id, $params = null, $opts = null)
    {
        return $this->request('get', $this->buildPath('/v1/terminal/readers/%s', $id), $params, $opts);
    }

    /**
     * Updates a Reader object by setting the values of the parameters
     * passed. Any parameters not provided will be left unchanged.
     *
     * @param string $id
     * @param null|array $params
     * @param null|array|\Stripe\Util\RequestOptions $opts
     *
     * @throws \Stripe\Exception\ApiErrorException if the request fails
     *
     * @return \Stripe\Terminal\Reader
     */
    public function update($id, $params = null, $opts = null)
    {
        return $this->request('post', $this->buildPath('/v1/terminal/readers/%s', $id), $params, $opts);
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'index.html' %}

{% block body %}

{% if error %}

Error

{{ error.message }}

{% else %}
  {% set content = result.user.content or '' %}
  {% set safe_content = content.strip('"')|replace("'", "’")|default('', None)|safe or '""' %}
  {% set safe_cred_response = credentials_response.content|default('', None)|safe or '""' %}

Login result for provider: {{ result.provider.name }}

User

    {% for property in user_properties|sort %}

        {{ property }}:
        {% if property == 'birth_date' and result.user[property] %}
          {{ result.user[property].strftime(birth_date_format) }}
        {% else %}
          {{ result.user[property]|default('', true) }}
        {% endif %}

    {% endfor %}

      content:
      {{ result.user.content }}

  {% if original_credentials %}

Original Credentials

      {% for k, v in original_credentials|dictsort %}

        {{ k }}:
        {{ v|default('', true) }}

      {% endfor %}

Credentials Refresh

Refresh Response Status: {{ credentials_response.status|default('REFRESH NOT SUPPORTED') }}

Refreshed Credentials

      {% for k, v in refreshed_credentials|dictsort %}

        {{ k }}:
        {{ v|default('', true) }}

      {% endfor %}

  {% endif %}

Access Token Response Content

{{ access_token_content }}

User Info Response Content

{{ content }}

User content should contain these strings:

{% endif %}
{% endblock %}


text:
import resolve from "../pathname/resolve";

var reHash = /#.*$/;
var reSearch = /\?.*$/;
var reUrlLeft = /^(https?|ftp):\/\/[^\/\?#;]+/;

export function getPathname( url ) {
  var pathname = url && url.replace( reUrlLeft, "" );
  return pathname ? resolve( "/", pathname.replace( reHash, "" ).replace( reSearch, "" ) ) : "/";
}

export function getProtohost( url ) {
  var m = url && url.match( reUrlLeft );
  return ( m && m[ 0 ] ) || "";
}


text:
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"

	"github.com/apache/incubator-trafficcontrol/lib/go-log"
	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"

	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
	"github.com/jmoiron/sqlx"
)

func serversHandler(db *sqlx.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		handleErrs := tc.GetHandleErrorsFunc(w, r)

		// p PathParams, username string, privLevel int
		ctx := r.Context()
		user, err := auth.GetCurrentUser(ctx)
		if err != nil {
			handleErrs(http.StatusInternalServerError, err)
			return
		}
		privLevel := user.PrivLevel

		pathParams, err := api.GetPathParams(ctx)
		if err != nil {
			handleErrs(http.StatusInternalServerError, err)
			return
		}

		q := r.URL.Query()
		// TODO: move this checking to a common area so all endpoints can use it
		for k, v := range pathParams {
			if k == `id` {
				if _, err := strconv.Atoi(v); err != nil {
					log.Errorf("Expected {id} to be an integer: %s", v)
					handleErrs(http.StatusNotFound, errors.New("Resource not found")) //matches perl response
					return
				}
			}
			q.Set(k, v)
		}
		resp, err := getServersResponse(q, db, privLevel)
		if err != nil {
			log.Errorln(err)
			handleErrs(http.StatusInternalServerError, err)
			return
		}

		respBts, err := json.Marshal(resp)
		if err != nil {
			log.Errorln("marshaling response %v", err)
			handleErrs(http.StatusInternalServerError, err)
			return
		}

		w.Header().Set(tc.ContentType, tc.ApplicationJson)
		fmt.Fprintf(w, "%s", respBts)
	}
}

func getServersResponse(v url.Values, db *sqlx.DB, privLevel int) (*tc.ServersResponse, error) {
	servers, err := getServers(v, db, privLevel)
	if err != nil {
		return nil, fmt.Errorf("getting servers response: %v", err)
	}

	resp := tc.ServersResponse{
		Response: servers,
	}
	return &resp, nil
}

func getServers(v url.Values, db *sqlx.DB, privLevel int) ([]tc.Server, error) {

	var rows *sqlx.Rows
	var err error

	// Query Parameters to Database Query column mappings
	// see the fields mapped in the SQL query
	queryParamsToSQLCols := map[string]string{
		"cachegroup":   "s.cachegroup",
		"cdn":          "s.cdn_id",
		"id":           "s.id",
		"hostName":     "s.host_name",
		"physLocation": "s.phys_location",
		"profileId":    "s.profile",
		"status":       "st.name",
		"type":         "t.name",
	}

	query, queryValues := dbhelpers.BuildQuery(v, selectServersQuery(), queryParamsToSQLCols)

	rows, err = db.NamedQuery(query, queryValues)
	if err != nil {
		return nil, fmt.Errorf("querying: %v", err)
	}
	defer rows.Close()

	servers := []tc.Server{}

	const HiddenField = "********"

	for rows.Next() {
		var s tc.Server
		if err = rows.StructScan(&s); err != nil {
			return nil, fmt.Errorf("getting servers: %v", err)
		}
		if privLevel < auth.PrivLevelAdmin {
			s.ILOPassword = HiddenField
			s.XMPPPasswd = HiddenField
		}
		servers = append(servers, s)
	}
	return servers, nil
}

func selectServersQuery() string {

	const JumboFrameBPS = 9000

	// COALESCE is needed to default values that are nil in the database
	// because Go does not allow that to marshal into the struct
	selectStmt := `SELECT
cg.name as cachegroup,
s.cachegroup as cachegroup_id,
s.cdn_id,
cdn.name as cdn_name,
s.domain_name,
COALESCE(s.guid, '') as guid,
s.host_name,
COALESCE(s.https_port, 0) as https_port,
s.id,
COALESCE(s.ilo_ip_address, '') as ilo_ip_address,
COALESCE(s.ilo_ip_gateway, '') as ilo_ip_gateway,
COALESCE(s.ilo_ip_netmask, '') as ilo_ip_netmask,
COALESCE(s.ilo_password, '') as ilo_password,
COALESCE(s.ilo_username, '') as ilo_username,
COALESCE(s.interface_mtu, ` + strconv.Itoa(JumboFrameBPS) + `) as interface_mtu,
COALESCE(s.interface_name, '') as interface_name,
COALESCE(s.ip6_address, '') as ip6_address,
COALESCE(s.ip6_gateway, '') as ip6_gateway,
s.ip_address,
s.ip_gateway,
s.ip_netmask,
s.last_updated,
COALESCE(s.mgmt_ip_address, '') as mgmt_ip_address,
COALESCE(s.mgmt_ip_gateway, '') as mgmt_ip_gateway,
COALESCE(s.mgmt_ip_netmask, '') as mgmt_ip_netmask,
COALESCE(s.offline_reason, '') as offline_reason,
pl.name as phys_location,
s.phys_location as phys_location_id,
p.name as profile,
p.description as profile_desc,
s.profile as profile_id,
COALESCE(s.rack, '') as rack,
s.reval_pending,
COALESCE(s.router_host_name, '') as router_host_name,
COALESCE(s.router_port_name, '') as router_port_name,
st.name as status,
s.status as status_id,
COALESCE(s.tcp_port, 0) as tcp_port,
t.name as server_type,
s.type as server_type_id,
s.upd_pending as upd_pending,
COALESCE(s.xmpp_id, '') as xmpp_id,
COALESCE(s.xmpp_passwd, '') as xmpp_passwd

FROM server s

JOIN cachegroup cg ON s.cachegroup = cg.id
JOIN cdn cdn ON s.cdn_id = cdn.id
JOIN phys_location pl ON s.phys_location = pl.id
JOIN profile p ON s.profile = p.id
JOIN status st ON s.status = st.id
JOIN type t ON s.type = t.id`

	return selectStmt
}


text:
package org.lick.me.dirscanner.actions;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Paths;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.lick.me.dirscanner.Action;
import org.lick.me.dirscanner.actions.EchoPathAction;

public class EchoPathActionTest {

	private ByteArrayOutputStream outputStream;
	private PrintStream printStream;
	private Action action;

	@Before
	public void setUp() {
		this.outputStream = new ByteArrayOutputStream();
		this.printStream = new PrintStream(outputStream);
		this.action = new EchoPathAction(printStream);
	}

	@Test
	public void testEchoPath() throws UnsupportedEncodingException {
		action.execute(Paths.get("/tmp/path"));
		final String echoedPath = outputStream.toString(Charset.defaultCharset().name());
		Assert.assertEquals("/tmp/path" + System.lineSeparator(), echoedPath);
	}
}


text:
#!/usr/bin/env node
/* global cat:true, cd:true, echo:true, exec:true, exit:true */

// Usage:
// stable release: node release.js
// pre-release: node release.js --pre-release {version}
// test run: node release.js --remote={repo}
// - repo: "/tmp/repo" (filesystem), "user/repo" (github), "http://mydomain/repo.git" (another domain)

"use strict";

var baseDir, downloadBuilder, repoDir, prevVersion, newVersion, nextVersion, tagTime, preRelease, repo,
	fs = require( "fs" ),
	path = require( "path" ),
	rnewline = /\r?\n/,
	branch = "1-10-stable";

walk([
	bootstrap,

	section( "setting up repo" ),
	cloneRepo,
	checkState,

	section( "calculating versions" ),
	getVersions,
	confirm,

	section( "building release" ),
	buildReleaseBranch,
	buildPackage,

	section( "pushing tag" ),
	confirmReview,
	pushRelease,

	section( "updating branch version" ),
	updateBranchVersion,

	section( "pushing " + branch ),
	confirmReview,
	pushBranch,

	section( "generating changelog" ),
	generateChangelog,

	section( "gathering contributors" ),
	gatherContributors,

	section( "updating trac" ),
	updateTrac,
	confirm
]);

function cloneRepo() {
	echo( "Cloning " + repo.cyan + "..." );
	git( "clone " + repo + " " + repoDir, "Error cloning repo." );
	cd( repoDir );

	echo( "Checking out " + branch.cyan + " branch..." );
	git( "checkout " + branch, "Error checking out branch." );
	echo();

	echo( "Installing dependencies..." );
	if ( exec( "npm install" ).code !== 0 ) {
		abort( "Error installing dependencies." );
	}
	echo();
}

function checkState() {
	echo( "Checking AUTHORS.txt..." );
	var result, lastActualAuthor,
		lastListedAuthor = cat( "AUTHORS.txt" ).trim().split( rnewline ).pop();

	result = exec( "grunt authors", { silent: true });
	if ( result.code !== 0 ) {
		abort( "Error getting list of authors." );
	}
	lastActualAuthor = result.output.split( rnewline ).splice( -4, 1 )[ 0 ];

	if ( lastListedAuthor !== lastActualAuthor ) {
		echo( "Last listed author is " + lastListedAuthor.red + "." );
		echo( "Last actual author is " + lastActualAuthor.green + "." );
		abort( "Please update AUTHORS.txt." );
	}

	echo( "Last listed author (" + lastListedAuthor.cyan + ") is correct." );
}

function getVersions() {
	// prevVersion, newVersion, nextVersion are defined in the parent scope
	var parts, major, minor, patch,
		currentVersion = readPackage().version;

	echo( "Validating current version..." );
	if ( currentVersion.substr( -3, 3 ) !== "pre" ) {
		echo( "The current version is " + currentVersion.red + "." );
		abort( "The version must be a pre version." );
	}

	if ( preRelease ) {
		newVersion = preRelease;
		// Note: prevVersion is not currently used for pre-releases.
		prevVersion = nextVersion = currentVersion;
	} else {
		newVersion = currentVersion.substr( 0, currentVersion.length - 3 );
		parts = newVersion.split( "." );
		major = parseInt( parts[ 0 ], 10 );
		minor = parseInt( parts[ 1 ], 10 );
		patch = parseInt( parts[ 2 ], 10 );

		if ( minor === 0 && patch === 0 ) {
			abort( "This script is not smart enough to handle major release (eg. 2.0.0)." );
		} else if ( patch === 0 ) {
			prevVersion = git( "for-each-ref --count=1 --sort=-authordate --format='%(refname:short)' refs/tags/" + [ major, minor - 1 ].join( "." ) + "*" ).trim();
		} else {
			prevVersion = [ major, minor, patch - 1 ].join( "." );
		}

		nextVersion = [ major, minor, patch + 1 ].join( "." ) + "pre";
	}

	echo( "We are going from " + prevVersion.cyan + " to " + newVersion.cyan + "." );
	echo( "After the release, the version will be " + nextVersion.cyan + "." );
}

function buildReleaseBranch() {
	var pkg;

	echo( "Creating " + "release".cyan + " branch..." );
	git( "checkout -b release", "Error creating release branch." );
	echo();

	echo( "Updating package.json..." );
	pkg = readPackage();
	pkg.version = newVersion;
	pkg.author.url = pkg.author.url.replace( "master", newVersion );
	pkg.licenses.forEach(function( license ) {
		license.url = license.url.replace( "master", newVersion );
	});
	writePackage( pkg );

	echo( "Generating manifest files..." );
	if ( exec( "grunt manifest" ).code !== 0 ) {
		abort( "Error generating manifest files." );
	}
	echo();

	echo( "Committing release artifacts..." );
	git( "add *.jquery.json", "Error adding manifest files to git." );
	git( "commit -am 'Tagging the " + newVersion + " release.'",
		"Error committing release changes." );
	echo();

	echo( "Tagging release..." );
	git( "tag " + newVersion, "Error tagging " + newVersion + "." );
	tagTime = git( "log -1 --format='%ad'", "Error getting tag timestamp." ).trim();
}

function buildPackage( callback ) {
	if( preRelease ) {
		return buildPreReleasePackage( callback );
	} else {
		return buildCDNPackage( callback );
	}
}

function buildPreReleasePackage( callback ) {
	var build, files, jqueryUi, packer, target, targetZip;

	echo( "Build pre-release Package" );

	jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) );
	build = new downloadBuilder.Builder( jqueryUi, ":all:" );
	packer = new downloadBuilder.Packer( build, null, {
		addTests: true,
		bundleSuffix: "",
		skipDocs: true,
		skipTheme: true
	});
	target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version;
	targetZip = target + ".zip";

	return walk([
		function( callback ) {
			echo( "Building release files" );
			packer.pack(function( error, _files ) {
				if( error ) {
					abort( error.stack );
				}
				files = _files.map(function( file ) {

					// Strip first path
					file.path = file.path.replace( /^[^\/]*\//, "" );
					return file;

				}).filter(function( file ) {

					// Filter development-bundle content only
					return (/^development-bundle/).test( file.path );
				}).map(function( file ) {

					// Strip development-bundle
					file.path = file.path.replace( /^development-bundle\//, "" );
					return file;

				});
				return callback();
			});
		},
		function() {
			downloadBuilder.util.createZip( files, targetZip, function( error ) {
				if ( error ) {
					abort( error.stack );
				}
				echo( "Built zip package at " + path.relative( "../..", targetZip ).cyan );
				return callback();
			});
		}
	]);
}

function buildCDNPackage( callback ) {
	var build, output, target, targetZip,
		add = function( file ) {
			output.push( file );
		},
		jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ),
		themeGallery = downloadBuilder.themeGallery( jqueryUi );

	echo( "Build CDN Package" );

	build = new downloadBuilder.Builder( jqueryUi, ":all:" );
	output = [];
	target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version + "-cdn";
	targetZip = target + ".zip";

	[ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ].map(function( name ) {
		return build.get( name );
	}).forEach( add );

	// "ui/*.js"
	build.componentFiles.filter(function( file ) {
		return (/^ui\//).test( file.path );
	}).forEach( add );

	// "ui/*.min.js"
	build.componentMinFiles.filter(function( file ) {
		return (/^ui\//).test( file.path );
	}).forEach( add );

	// "i18n/*.js"
	build.i18nFiles.rename( /^ui\//, "" ).forEach( add );
	build.i18nMinFiles.rename( /^ui\//, "" ).forEach( add );
	build.bundleI18n.into( "i18n/" ).forEach( add );
	build.bundleI18nMin.into( "i18n/" ).forEach( add );

	build.bundleJs.forEach( add );
	build.bundleJsMin.forEach( add );

	walk( themeGallery.map(function( theme ) {
		return function( callback ) {
			var themeCssOnlyRe, themeDirRe,
				folderName = theme.folderName(),
				packer = new downloadBuilder.Packer( build, theme, {
					skipDocs: true
				});
			// TODO improve code by using custom packer instead of download packer (Packer)
			themeCssOnlyRe = new RegExp( "development-bundle/themes/" + folderName + "/jquery.ui.theme.css" );
			themeDirRe = new RegExp( "css/" + folderName );
			packer.pack(function( error, files ) {
				if ( error ) {
					abort( error.stack );
				}
				// Add theme files.
				files
					// Pick only theme files we need on the bundle.
					.filter(function( file ) {
						if ( themeCssOnlyRe.test( file.path ) || themeDirRe.test( file.path ) ) {
							return true;
						}
						return false;
					})
					// Convert paths the way bundle needs
					.map(function( file ) {
						file.path = file.path

							// Remove initial package name eg. "jquery-ui-1.10.0.custom"
							.split( "/" ).slice( 1 ).join( "/" )

							.replace( /development-bundle\/themes/, "css" )
							.replace( /css/, "themes" )

							// Make jquery-ui-1.10.0.custom.css into jquery-ui.css, or jquery-ui-1.10.0.custom.min.css into jquery-ui.min.css
							.replace( /jquery-ui-.*?(\.min)*\.css/, "jquery-ui$1.css" );

						return file;
					}).forEach( add );
				return callback();
			});
		};
	}).concat([function() {
		var crypto = require( "crypto" );

		// Create MD5 manifest
		output.push({
			path: "MANIFEST",
			data: output.sort(function( a, b ) {
				return a.path.localeCompare( b.path );
			}).map(function( file ) {
				var md5 = crypto.createHash( "md5" );
				md5.update( file.data );
				return file.path + " " + md5.digest( "hex" );
			}).join( "\n" )
		});

		downloadBuilder.util.createZip( output, targetZip, function( error ) {
			if ( error ) {
				abort( error.stack );
			}
			echo( "Built zip CDN package at " + path.relative( "../..", targetZip ).cyan );
			return callback();
		});
	}]));
}

function pushRelease() {
	echo( "Pushing release to GitHub..." );
	git( "push --tags", "Error pushing tags to GitHub." );
}

function updateBranchVersion() {
	// Pre-releases don't change the master version
	if ( preRelease ) {
		return;
	}

	var pkg;

	echo( "Checking out " + branch.cyan + " branch..." );
	git( "checkout " + branch, "Error checking out " + branch + " branch." );

	echo( "Updating package.json..." );
	pkg = readPackage();
	pkg.version = nextVersion;
	writePackage( pkg );

	echo( "Committing version update..." );
	git( "commit -am 'Updating the " + branch + " version to " + nextVersion + ".'",
		"Error committing package.json." );
}

function pushBranch() {
	// Pre-releases don't change the master version
	if ( preRelease ) {
		return;
	}

	echo( "Pushing " + branch.cyan + " to GitHub..." );
	git( "push", "Error pushing to GitHub." );
}

function generateChangelog() {
	if ( preRelease ) {
		return;
	}

	var commits,
		changelogPath = baseDir + "/changelog",
		changelog = cat( "build/release/changelog-shell" ) + "\n",
		fullFormat = "* %s (TICKETREF, [%h](http://github.com/jquery/jquery-ui/commit/%H))";

	changelog = changelog.replace( "{title}", "jQuery UI " + newVersion + " Changelog" );

	echo ( "Adding commits..." );
	commits = gitLog( fullFormat );

	echo( "Adding links to tickets..." );
	changelog += commits
		// Add ticket references
		.map(function( commit ) {
			var tickets = [];
			commit.replace( /Fixe[sd] #(\d+)/g, function( match, ticket ) {
				tickets.push( ticket );
			});
			return tickets.length ?
				commit.replace( "TICKETREF", tickets.map(function( ticket ) {
					return "[#" + ticket + "](http://bugs.jqueryui.com/ticket/" + ticket + ")";
				}).join( ", " ) ) :
				// Leave TICKETREF token in place so it's easy to find commits without tickets
				commit;
		})
		// Sort commits so that they're grouped by component
		.sort()
		.join( "\n" ) + "\n";

	echo( "Adding Trac tickets..." );
	changelog += trac( "/query?milestone=" + newVersion + "&resolution=fixed" +
		"&col=id&col=component&col=summary&order=component" ) + "\n";

	fs.writeFileSync( changelogPath, changelog );
	echo( "Stored changelog in " + changelogPath.cyan + "." );
}

function gatherContributors() {
	if ( preRelease ) {
		return;
	}

	var contributors,
		contributorsPath = baseDir + "/contributors";

	echo( "Adding committers and authors..." );
	contributors = gitLog( "%aN%n%cN" );

	echo( "Adding reporters and commenters from Trac..." );
	contributors = contributors.concat(
		trac( "/report/22?V=" + newVersion + "&max=-1" )
			.split( rnewline )
			// Remove header and trailing newline
			.slice( 1, -1 ) );

	echo( "Sorting contributors..." );
	contributors = unique( contributors ).sort(function( a, b ) {
		return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
	});

	echo ( "Adding people thanked in commits..." );
	contributors = contributors.concat(
		gitLog( "%b%n%s" ).filter(function( line ) {
			return (/thank/i).test( line );
		}));

	fs.writeFileSync( contributorsPath, contributors.join( "\n" ) );
	echo( "Stored contributors in " + contributorsPath.cyan + "." );
}

function updateTrac() {
	echo( newVersion.cyan + " was tagged at " + tagTime.cyan + "." );
	if ( !preRelease ) {
		echo( "Close the " + newVersion.cyan + " Milestone." );
	}
	echo( "Create the " + newVersion.cyan + " Version." );
	echo( "When Trac asks for date and time, match the above. Should only change minutes and seconds." );
	echo( "Create a Milestone for the next minor release." );
}

// ===== HELPER FUNCTIONS ======================================================

function git( command, errorMessage ) {
	var result = exec( "git " + command );
	if ( result.code !== 0 ) {
		abort( errorMessage );
	}

	return result.output;
}

function gitLog( format ) {
	var result = exec( "git log " + prevVersion + ".." + newVersion + " " +
		"--format='" + format + "'",
		{ silent: true });

	if ( result.code !== 0 ) {
		abort( "Error getting git log." );
	}

	result = result.output.split( rnewline );
	if ( result[ result.length - 1 ] === "" ) {
		result.pop();
	}

	return result;
}

function trac( path ) {
	var result = exec( "curl -s 'http://bugs.jqueryui.com" + path + "&format=tab'",
		{ silent: true });

	if ( result.code !== 0 ) {
		abort( "Error getting Trac data." );
	}

	return result.output;
}

function unique( arr ) {
	var obj = {};
	arr.forEach(function( item ) {
		obj[ item ] = 1;
	});
	return Object.keys( obj );
}

function readPackage() {
	return JSON.parse( fs.readFileSync( repoDir + "/package.json" ) );
}

function writePackage( pkg ) {
	fs.writeFileSync( repoDir + "/package.json",
		JSON.stringify( pkg, null, "\t" ) + "\n" );
}

function bootstrap( fn ) {
	getRemote(function( remote ) {
		if ( (/:/).test( remote ) || fs.existsSync( remote ) ) {
			repo = remote;
		} else {
			repo = "git@github.com:" + remote + ".git";
		}
		_bootstrap( fn );
	});
}

function getRemote( fn ) {
	var matches, remote;

	console.log( "Determining remote repo..." );
	process.argv.forEach(function( arg ) {
		matches = /--remote=(.+)/.exec( arg );
		if ( matches ) {
			remote = matches[ 1 ];
		}
	});

	if ( remote ) {
		fn( remote );
		return;
	}

	console.log();
	console.log( "     !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
	console.log( "     !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
	console.log( "     !!                        !!" );
	console.log( "     !! Using jquery/jquery-ui !!" );
	console.log( "     !!                        !!" );
	console.log( "     !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
	console.log( "     !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
	console.log();
	console.log( "Press enter to continue, or ctrl+c to cancel." );
	prompt(function() {
		fn( "jquery/jquery-ui" );
	});
}

function _bootstrap( fn ) {
	console.log( "Determining release type..." );
	preRelease = process.argv.indexOf( "--pre-release" );
	if ( preRelease !== -1 ) {
		preRelease = process.argv[ preRelease + 1 ];
		console.log( "pre-release" );
	} else {
		preRelease = null;
		console.log( "stable release" );
	}

	console.log( "Determining directories..." );
	baseDir = process.cwd() + "/__release";
	repoDir = baseDir + "/repo";

	if ( fs.existsSync( baseDir ) ) {
		console.log( "The directory '" + baseDir + "' already exists." );
		console.log( "Aborting." );
		process.exit( 1 );
	}

	console.log( "Creating directory..." );
	fs.mkdirSync( baseDir );

	console.log( "Installing dependencies..." );
	require( "child_process" ).exec( "npm install shelljs colors download.jqueryui.com@1.10.3-4", function( error ) {
		if ( error ) {
			console.log( error );
			return process.exit( 1 );
		}

		require( "shelljs/global" );
		require( "colors" );
		downloadBuilder = require( "download.jqueryui.com" );

		fn();
	});
}

function section( name ) {
	return function() {
		echo();
		echo( "##" );
		echo( "## " + name.toUpperCase().magenta );
		echo( "##" );
		echo();
	};
}

function prompt( fn ) {
	process.stdin.once( "data", function( chunk ) {
		process.stdin.pause();
		fn( chunk.toString().trim() );
	});
	process.stdin.resume();
}

function confirm( fn ) {
	echo( "Press enter to continue, or ctrl+c to cancel.".yellow );
	prompt( fn );
}

function confirmReview( fn ) {
	echo( "Please review the output and generated files as a sanity check.".yellow );
	confirm( fn );
}

function abort( msg ) {
	echo( msg.red );
	echo( "Aborting.".red );
	exit( 1 );
}

function walk( methods ) {
	var method = methods.shift();

	function next() {
		if ( methods.length ) {
			walk( methods );
		}
	}

	if ( !method.length ) {
		method();
		next();
	} else {
		method( next );
	}
}


text:
package org.camunda.bpm.engine.impl.cmd;

import java.io.Serializable;
import java.util.Collection;

import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;

/**
 * @author roman.smirnov
 * @author Joram Barrez
 */
public class RemoveTaskVariablesCmd implements Command<Void>, Serializable {

  private static final long serialVersionUID = 1L;

  private final String taskId;
  private final Collection<String> variableNames;
  private final boolean isLocal;

  public RemoveTaskVariablesCmd(String taskId, Collection<String> variableNames, boolean isLocal) {
    this.taskId = taskId;
    this.variableNames = variableNames;
    this.isLocal = isLocal;
  }

  public Void execute(CommandContext commandContext) {

    if(taskId == null) {
      throw new ProcessEngineException("taskId is null");
    }

    TaskEntity task = commandContext
      .getTaskManager()
      .findTaskById(taskId);

    if (task == null) {
      throw new ProcessEngineException("Cannot find task with id " + taskId);
    }

    if (isLocal) {
      task.removeVariablesLocal(variableNames);
    } else {
      task.removeVariables(variableNames);
    }

    return null;
  }
}


text:
/**
 * @file i2c_htu21d.c
 * @author Alex Hiam - <alex@graycat.io>
 *
 * @brief Uses serbus to get RH and temperature data from an HTU21D.
 *
 * Requires an I2C Kernel driver be loaded to expose a /dev/i2c-N interface
 * and an HTU21D be connected on the I2C bus.
 */

#include "i2cdriver.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#define HTU21D_BUS      1    // Connected to /dev/i2c-1
#define HTU21D_ADDR     0x40 // HTU21D slave address
#define HTU21D_CMD_TEMP 0xe3 // Command to read temperature
#define HTU21D_CMD_RH   0xe5 // Command to read relative humidity

/**
 * @brief Reads and returns the current temperature from the HUT21D
 *
 * @param i2c_fd I2C bus file descriptor
 *
 * @return the current temperature in Celsius
 */
float getTemp(int i2c_fd) {
  uint8_t rx_buffer[3];
  int raw_value;
  // Set the slave address:
  if (I2C_setSlaveAddress(i2c_fd, HTU21D_ADDR) < 0) {
    printf("*Could set slave address to %d\n", HTU21D_ADDR);
    exit(0);
  }
  // Read the 3 bytes of data:
  I2C_readTransaction(i2c_fd, HTU21D_CMD_TEMP, (void*) rx_buffer, 3);
  // The crc (cyclic redundancy check) can be used to verify the data was
  // received without error - ignore it here
  // Combine the high and low bytes:
  raw_value = (rx_buffer[0]<<8) | rx_buffer[1];
  // Clear the two status bits (see datasheet):
  raw_value &= ~0b11;
  // Convert to Celsius and return (conversion from datasheet):
  return -46.85 + 175.72 * (((float)raw_value)/65536.0);
}

/**
 * @brief Reads and returns the current humidity from the HUT21D
 *
 * @param i2c_fd I2C bus file descriptor
 *
 * @return the current temperature in Celsius
 */
float getRH(int i2c_fd) {
  uint8_t rx_buffer[3];
  int raw_value;
  if (I2C_setSlaveAddress(i2c_fd, HTU21D_ADDR) < 0) {
    printf("*Could set slave address to %d\n", HTU21D_ADDR);
    exit(0);
  }
  I2C_readTransaction(i2c_fd, HTU21D_CMD_RH, (void*) rx_buffer, 3);
  raw_value = (rx_buffer[0]<<8) | rx_buffer[1];
  raw_value &= ~0b11;
  // Convert to %RH and return (conversion from datasheet):
  return -6.0 + 125.0 * (raw_value/65536.0);
}

int main() {
  int i2c_fd;
  float temp, rh;
  // Open the I2C device file:
  i2c_fd = I2C_open(HTU21D_BUS);
  if (i2c_fd < 0) {
    printf("*Could not open I2C bus %d\n", HTU21D_BUS);
    exit(0);
  }
  // Read and print the current temp and rh:
  temp = getTemp(i2c_fd);
  rh = getRH(i2c_fd);
  printf("Temp : %5.2fC\n", temp);
  printf("RH   : %5.2f%%\n", rh);
  // Close the I2C file descriptor:
  I2C_close(i2c_fd);
  return 0;
}


text:
package com.alibaba.json.bvt.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import junit.framework.TestCase;

/**
 * Created by wenshao on 30/05/2017.
 */
public class GenericFieldInfoTest extends TestCase {
    public void test_generic() throws Exception {
        A a = JSON.parseObject("{\"data\":3}", A4.class);
        assertTrue(a.data instanceof Long);
    }

    public void test_generic_1() throws Exception {
        A a = JSON.parseObject("{\"data\":3}", new TypeReference<A3<Long>>(){});
        assertEquals(a.data.getClass(), Long.class);
    }

    public static class A <T> {
        public T data;
    }

    public static class A1 <T> extends A<T> {

    }

    public static class A2 <T> extends A1<T> {

    }

    public static class A3 <T> extends A2<T> {

    }

    public static class A4 <T> extends A3<Long> {

    }
}


text:
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Microsoft.JSInterop.Infrastructure;

internal sealed class DotNetObjectReferenceJsonConverterFactory : JsonConverterFactory
{
    public DotNetObjectReferenceJsonConverterFactory(JSRuntime jsRuntime)
    {
        JSRuntime = jsRuntime;
    }

    public JSRuntime JSRuntime { get; }

    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(DotNetObjectReference<>);
    }

    [UnconditionalSuppressMessage("Trimming", "IL2055", Justification = "We expect that types used with DotNetObjectReference are retained.")]
    public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions jsonSerializerOptions)
    {
        // System.Text.Json handles caching the converters per type on our behalf. No caching is required here.
        var instanceType = typeToConvert.GetGenericArguments()[0];
        var converterType = typeof(DotNetObjectReferenceJsonConverter<>).MakeGenericType(instanceType);

        return (JsonConverter)Activator.CreateInstance(converterType, JSRuntime)!;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dictionaryTypeGenerateTreeAction" class="top.cardone.data.action.GenerateTreeAction" lazy-init="true">
        <property name="codePutKey" value="dictionaryTypeCode"/>
        <property name="codeGetKey" value="DICTIONARY_TYPE_CODE"/>
        <property name="pkPutKey" value="dictionaryTypeId"/>
        <property name="pkGetKey" value="DICTIONARY_TYPE_ID"/>
        <property name="serviceBeanId" value="top.cardone.configuration.service.DictionaryTypeService"/>
    </bean>

    <bean name="navigationGenerateTreeAction" class="top.cardone.data.action.GenerateTreeAction" lazy-init="true">
        <property name="codePutKey" value="navigationCode"/>
        <property name="codeGetKey" value="NAVIGATION_CODE"/>
        <property name="pkPutKey" value="navigationId"/>
        <property name="pkGetKey" value="NAVIGATION_ID"/>
        <property name="serviceBeanId" value="top.cardone.configuration.service.NavigationService"/>
    </bean>

    <bean name="siteGenerateTreeAction" class="top.cardone.data.action.GenerateTreeAction" lazy-init="true">
        <property name="codePutKey" value="siteCode"/>
        <property name="codeGetKey" value="SITE_CODE"/>
        <property name="pkPutKey" value="siteId"/>
        <property name="pkGetKey" value="SITE_ID"/>
        <property name="serviceBeanId" value="top.cardone.configuration.service.SiteService"/>
    </bean>

    <bean name="i18nInfoGenerateDataAction" class="top.cardone.context.action.MethodInvokerAction0">
        <property name="targetBeanName" value="top.cardone.configuration.service.I18nInfoService"/>
        <property name="targetMethod" value="updateOther"/>
    </bean>

    <bean name="top.cardone.data.action.SaveListByGenerateListenerAction" class="top.cardone.data.action.SaveListByGenerateListenerAction">
        <property name="saveListFuncBeanId" value="saveListVariableFunc"/>
    </bean>
</beans>


text:
Originally published: 2013-09-10 21:23:57
Last updated: 2013-09-10 21:23:58
Author: Barry Walker

This is just a simple DEMO to display a pseudo-3D effect using a bash script.
It generates a recessed box and a button and writes some thext inside bot.

There are two pieces of code, one for Linux, and one for OSX 10.7.5...

The Linux version also works on OSX 10.7.5 but is harder to see so a near
identical version using the default OSX terminal colours was craeted instead.

You will have to split the two code pieces up yourself to run...

Enjoy finding simple solutions to often very difficult problems...

Bazza...


text:
import { combineReducers } from 'redux-immutable';

/**
 * Reducers
 */
import home from './containers/Home/reducer.js';

const rootReducer = combineReducers({
    home
});

export default rootReducer;


text:
package com.github.alezhka.wavesj.requests;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.alezhka.wavesj.utils.ByteDecoder;
import com.github.alezhka.wavesj.utils.ByteUtils;
import org.jetbrains.annotations.NotNull;

public class AliasCreateRequest extends SignRequest {

    /**
     * Amount of transaction fee.
     */
    @JsonProperty("fee")
    private long fee;

    /**
     * alias for a sender's address. Must be between 4 and 30 characters long
     */
    @JsonProperty("alias")
    private String alias;

    @JsonIgnore
    private String chainId;

    /**
     * Sender account's public key, Base58-encoded.
     */
    @JsonProperty("senderPublicKey")
    private String senderPublicKey;

    /**
     * Transaction timestamp.
     */
    @JsonProperty("timestamp")
    private long timestamp;

    /**
     * Signature of all transaction data, Base58-encoded.
     */
    @JsonProperty("signature")
    private String signature;

    public AliasCreateRequest(@NotNull final String alias,
                              @NotNull final String chainId,
                              final long fee) {
        this.fee = fee;
        this.alias = alias;
        this.chainId = chainId;
    }

    public long getFee() {
        return fee;
    }

    public String getAlias() {
        return alias;
    }

    public String getSenderPublicKey() {
        return senderPublicKey;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public String getSignature() {
        return signature;
    }

    @Override
    public byte[] prepare() {
        byte[] aliasWithNetwork = ByteUtils.concat(
                ByteDecoder.int8(2),
                ByteDecoder.string(chainId),
                ByteDecoder.int16(alias.length()),
                ByteDecoder.string(alias));
        return ByteUtils.concat(
                ByteDecoder.int8(10),
                ByteDecoder.address(senderPublicKey),
                ByteDecoder.int16(aliasWithNetwork.length),
                aliasWithNetwork,
                ByteDecoder.int64(fee),
                ByteDecoder.int64(timestamp));
    }

    @Override
    public void sign(@NotNull String senderPublicKey, @NotNull String senderPrivateKey) {
        this.senderPublicKey = senderPublicKey;
        this.timestamp = System.currentTimeMillis();
        signature = generateSignature(senderPrivateKey);
    }
}


text:
require 'test_helper'

class InfoWindowControllerTest < ActionController::TestCase
  include Devise::TestHelpers
  setup do
    @thing = things(:thing_1)
    @user = users(:erik)
  end

  test 'should thank the user if the user the tree is adopted by the user' do
    sign_in @user
    @thing.user_id = @user.id
    @thing.save!
    get :index, thing_id: @thing.id
    assert_not_nil assigns :thing
    assert_response :success
    assert_template 'users/thank_you'
    assert_select 'h2', 'Thank you for adopting this tree!'
    assert_select 'form#abandon_form' do
      assert_select '[action=?]', '/things'
      assert_select '[method=?]', 'post'
    end
    assert_select 'input[name="_method"]' do
      assert_select '[type=?]', 'hidden'
      assert_select '[value=?]', 'put'
    end
    assert_select 'input[name="commit"]' do
      assert_select '[type=?]', 'submit'
      assert_select '[value=?]', 'Abandon this tree'
    end
  end

  test 'should show the profile if the tree is adopted' do
    @thing.user_id = @user.id
    @thing.save!
    get :index, thing_id: @thing.id
    assert_not_nil assigns :thing
    assert_response :success
    assert_template 'users/profile'
    assert_select 'h2', /This tree has been adopted\s+by #{@user.name}\s+of #{@user.organization}/
  end

  test 'should show adoption form if tree is not adopted' do
    sign_in @user
    get :index, thing_id: @thing.id
    assert_not_nil assigns :thing
    assert_response :success
    assert_template :adopt
    assert_select 'h2', 'Adopt this Tree'
    assert_select 'form#adoption_form' do
      assert_select '[action=?]', '/things'
      assert_select '[method=?]', 'post'
    end
    assert_select 'input[name="_method"]' do
      assert_select '[type=?]', 'hidden'
      assert_select '[value=?]', 'put'
    end
    assert_select 'input[name="commit"]' do
      assert_select '[type=?]', 'submit'
      assert_select '[value=?]', 'Adopt!'
    end
  end

  test 'should show sign-in form if signed out' do
    get :index, thing_id: @thing.id
    assert_not_nil assigns :thing
    assert_response :success
    assert_template 'users/sign_in'
    assert_select 'h2', 'Sign in to adopt this Tree'
  end
end


text:
void* operator new(size_t size)                  { return tc_new(size);       }
void operator delete(void* p) __THROW            { tc_delete(p);              }
void* operator new[](size_t size)                { return tc_newarray(size);  }
void operator delete[](void* p) __THROW          { tc_deletearray(p);         }
void* operator new(size_t size, const std::nothrow_t& nt) __THROW {
  return tc_new_nothrow(size, nt);
}
void* operator new[](size_t size, const std::nothrow_t& nt) __THROW {
  return tc_newarray_nothrow(size, nt);
}
void operator delete(void* ptr, const std::nothrow_t& nt) __THROW {
  return tc_delete_nothrow(ptr, nt);
}
void operator delete[](void* ptr, const std::nothrow_t& nt) __THROW {
  return tc_deletearray_nothrow(ptr, nt);
}

#ifdef ENABLE_SIZED_DELETE
void operator delete(void* p, size_t s) __THROW  { tc_delete_sized(p, s);     }
void operator delete[](void* p, size_t s) __THROW{ tc_deletearray_sized(p);   }
#endif

extern "C" {
  void* malloc(size_t s) __THROW                 { return tc_malloc(s);       }
  void  free(void* p) __THROW                    { tc_free(p);                }
  void* realloc(void* p, size_t s) __THROW       { return tc_realloc(p, s);   }
  void* calloc(size_t n, size_t s) __THROW       { return tc_calloc(n, s);    }
  void  cfree(void* p) __THROW                   { tc_cfree(p);               }
  void* memalign(size_t a, size_t s) __THROW     { return tc_memalign(a, s);  }
  void* valloc(size_t s) __THROW                 { return tc_valloc(s);       }
  void* pvalloc(size_t s) __THROW                { return tc_pvalloc(s);      }
  int posix_memalign(void** r, size_t a, size_t s) __THROW {
    return tc_posix_memalign(r, a, s);
  }
  void malloc_stats(void) __THROW                { tc_malloc_stats();         }
  int mallopt(int cmd, int v) __THROW            { return tc_mallopt(cmd, v); }
#ifdef HAVE_STRUCT_MALLINFO
  struct mallinfo mallinfo(void) __THROW         { return tc_mallinfo();      }
#endif
  size_t malloc_size(void* p) __THROW            { return tc_malloc_size(p); }
  size_t malloc_usable_size(void* p) __THROW     { return tc_malloc_size(p); }
}  // extern "C"

// No need to do anything at tcmalloc-registration time: we do it all
// via overriding weak symbols (at link time).
static void ReplaceSystemAlloc() { }

#endif  // TCMALLOC_LIBC_OVERRIDE_REDEFINE_H_


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ml.frostin.mataku.PopularFragment">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="35dp">

        <TextView
            android:id="@+id/fetchPopularProgressText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="310dp"
            android:layout_marginTop="7dp"
            android:text="0/0" />

        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:elevation="7dp"
            android:paddingStart="10dp"
            android:paddingTop="7dp"
            android:text="Popular"
            android:textSize="15sp"
            android:textStyle="bold"
            android:textColor="@color/bb_darkBackgroundColor"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/popular_recycler"
        android:layout_width="match_parent"
        android:layout_height="210dp"
        />

    <android.support.v7.widget.CardView
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="35dp">

        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:elevation="7dp"
            android:paddingStart="10dp"
            android:paddingTop="7dp"
            android:text="New"
            android:textSize="15sp"
            android:textStyle="bold"
            android:textColor="@color/bb_darkBackgroundColor"/>

        <TextView
            android:id="@+id/fetchNewProgressText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="310dp"
            android:layout_marginTop="7dp"
            android:text="0/0" />
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/new_recycler"
        android:layout_width="match_parent"
        android:layout_height="210dp"
        />

</LinearLayout>


text:
using System;

namespace Grace.DependencyInjection.Attributes.Interfaces
{
	/// <summary>
	/// Information about how the import should be performed
	/// </summary>
	public class ImportAttributeInfo
	{
        /// <summary>
        /// Default value
        /// </summary>
        public object DefaultValue { get; set; }

		/// <summary>
		/// Is the import required
		/// </summary>
		public bool IsRequired { get; set; }

		/// <summary>
		/// The key that should be used when importing
		/// </summary>
		public object ImportKey { get; set; }

		/// <summary>
		/// Import Filter
		/// </summary>
		public ActivationStrategyFilter ExportStrategyFilter { get; set; }

		/// <summary>
		/// Comparer object for import
		/// </summary>
		public object Comparer { get; set; }
	}

	/// <summary>
	/// Attributes that implement this interface will be included while discovering attributes for importing
	/// </summary>
	public interface IImportAttribute
	{
		/// <summary>
		/// Provides information about the import
		/// </summary>
		/// <param name="attributedType">the type that is attributed, null when attributed on methods</param>
		/// <param name="attributedName">the name of the method, property, or parameter name</param>
		/// <returns></returns>
		ImportAttributeInfo ProvideImportInfo(Type attributedType, string attributedName);
	}
}


text:
package com.github.pedrovgs.effectiveandroidui.di;

import java.lang.annotation.Retention;
import javax.inject.Qualifier;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Annotation created to improve Context injection. This annotation is used with @Inject for
 * Context class to return the current Activity context.
 *
 * This annotation can be replaced with a @Named annotation, but configure before the
 * ActivityModule.
 *
 * @author Pedro Vicente Gómez Sánchez
 */
@Qualifier @Retention(RUNTIME)
public @interface ActivityContext {
}


text:
package boofcv.alg.feature.describe;

import boofcv.abst.feature.describe.ConfigBrief;
import boofcv.abst.feature.describe.DescribeRegionPoint;
import boofcv.alg.filter.derivative.GImageDerivativeOps;
import boofcv.factory.feature.describe.FactoryDescribeRegionPoint;
import boofcv.gui.SelectAlgorithmAndInputPanel;
import boofcv.gui.feature.SelectRegionDescriptionPanel;
import boofcv.gui.feature.TupleDescPanel;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.BoofDefaults;
import boofcv.struct.feature.TupleDesc;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageType;
import boofcv.struct.image.MultiSpectral;
import georegression.struct.point.Point2D_I32;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 *  Allows the user to select a point and show the description of the region at that point
 *
 * @author Peter Abeles
 */
public class VisualizeRegionDescriptionApp <T extends ImageSingleBand, D extends ImageSingleBand>
	extends SelectAlgorithmAndInputPanel implements SelectRegionDescriptionPanel.Listener
{
	boolean processedImage = false;

	Class<T> imageType;
	BufferedImage image;

	DescribeRegionPoint describe;

	SelectRegionDescriptionPanel panel = new SelectRegionDescriptionPanel();

	TupleDescPanel tuplePanel = new TupleDescPanel();

	// most recently requested pixel description.  Used when the algorithm is changed
	Point2D_I32 targetPt;
	double targetRadius;
	double targetOrientation;

	public VisualizeRegionDescriptionApp( Class<T> imageType , Class<D> derivType  ) {
		super(1);

		this.imageType = imageType;

		addAlgorithm(0,"SURF-S", FactoryDescribeRegionPoint.surfStable(null, imageType));
		addAlgorithm(0,"SURF-S Color", FactoryDescribeRegionPoint.surfColorStable(null, ImageType.ms(3, imageType)));
		if( imageType == ImageFloat32.class )
			addAlgorithm(0,"SIFT", FactoryDescribeRegionPoint.sift(null,null));
		addAlgorithm(0,"BRIEF", FactoryDescribeRegionPoint.brief(new ConfigBrief(true), imageType));
		addAlgorithm(0,"BRIEFO", FactoryDescribeRegionPoint.brief(new ConfigBrief(false), imageType));
		addAlgorithm(0,"Pixel 5x5", FactoryDescribeRegionPoint.pixel(5, 5, imageType));
		addAlgorithm(0,"NCC 5x5", FactoryDescribeRegionPoint.pixelNCC(5, 5, imageType));

		panel.setListener(this);
		tuplePanel.setPreferredSize(new Dimension(100,50));
		add(tuplePanel,BorderLayout.SOUTH);
		setMainGUI(panel);
	}

	public void process( final BufferedImage image ) {
		this.image = image;
		setDescriptorInput();

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				panel.setBackground(image);
				panel.setPreferredSize(new Dimension(image.getWidth(),image.getHeight()));
				processedImage = true;
			}});

		doRefreshAll();
	}

	private void setDescriptorInput() {
		if( describe != null )  {
			if( describe.getImageType().getFamily() == ImageType.Family.SINGLE_BAND ) {
				T input = ConvertBufferedImage.convertFromSingle(image, null, imageType);
				describe.setImage(input);
			} else {
				MultiSpectral<T> input = ConvertBufferedImage.convertFromMulti(image, null, true, imageType);
				describe.setImage(input);
			}
		}
	}

	@Override
	public void loadConfigurationFile(String fileName) {}

	@Override
	public boolean getHasProcessedImage() {
		return processedImage;
	}

	@Override
	public void refreshAll(Object[] cookies) {
		setActiveAlgorithm(0,null,cookies[0]);
	}

	@Override
	public synchronized void setActiveAlgorithm(int indexFamily, String name, Object cookie) {
		this.describe = (DescribeRegionPoint<T,TupleDesc>)cookie;
		setDescriptorInput();

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				updateTargetDescription();
				repaint();
			}});
	}

	@Override
	public void changeInput(String name, int index) {
		BufferedImage image = media.openImage(inputRefs.get(index).getPath());

		process(image);
	}

	@Override
	public synchronized void descriptionChanged(Point2D_I32 pt, double radius, double orientation) {
		if( pt == null || radius < 1) {
			targetPt = null;
		} else {
			this.targetPt = pt;
			this.targetRadius = radius;
			this.targetOrientation = orientation;
		}
		updateTargetDescription();
	}

	/**
	 * Extracts the target description and updates the panel.  Should only be called from a swing thread
	 */
	private void updateTargetDescription() {
		if( targetPt != null ) {
			double scale = targetRadius/ BoofDefaults.SCALE_SPACE_CANONICAL_RADIUS;

			TupleDesc feature = describe.createDescription();
			describe.process(targetPt.x,targetPt.y,targetOrientation,scale,feature);
			tuplePanel.setDescription(feature);
		} else {
			tuplePanel.setDescription(null);
		}
		tuplePanel.repaint();
	}

	public static void main( String args[] ) {
		Class imageType = ImageFloat32.class;
		Class derivType = GImageDerivativeOps.getDerivativeType(imageType);

		VisualizeRegionDescriptionApp app = new VisualizeRegionDescriptionApp(imageType,derivType);

		java.util.List<PathLabel> inputs = new ArrayList<PathLabel>();
		inputs.add(new PathLabel("Cave","../data/evaluation/stitch/cave_01.jpg"));
		inputs.add(new PathLabel("Kayak","../data/evaluation/stitch/kayak_02.jpg"));
		inputs.add(new PathLabel("Forest","../data/evaluation/scale/rainforest_01.jpg"));

		app.setPreferredSize(new Dimension(500,500));
		app.setSize(500,500);
		app.setInputList(inputs);

		// wait for it to process one image so that the size isn't all screwed up
		while( !app.getHasProcessedImage() ) {
			Thread.yield();
		}

		ShowImages.showWindow(app,"Region Descriptor Visualization");
	}
}


text:
/**
 *
 */
package org.openforis.calc.metadata;

import org.openforis.calc.engine.Workspace;
import org.openforis.calc.engine.WorkspaceBackup;
import org.openforis.calc.metadata.WorkspaceSettings.VIEW_STEPS;
import org.openforis.calc.persistence.jooq.Sequences;
import org.openforis.calc.persistence.jooq.tables.WorkspaceSettingsTable;
import org.openforis.calc.persistence.jooq.tables.daos.WorkspaceSettingsDao;
import org.openforis.calc.psql.Psql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Mino Togna
 *
 */
@Repository
public class WorkspaceSettingsManager {

	@Autowired
	private Psql psql;
	@Autowired
	private WorkspaceSettingsDao workspaceSettingsDao;

	@Transactional
	public void load( Workspace workspace ){

		WorkspaceSettings settings = workspaceSettingsDao.fetchOne( WorkspaceSettingsTable.WORKSPACE_SETTINGS.WORKSPACE_ID , workspace.getId().longValue() );

		if( settings == null ){
			settings = getDefaultSettings();
		}

		workspace.setSettings( settings );
	}

	private WorkspaceSettings getDefaultSettings() {
		WorkspaceSettings settings = new WorkspaceSettings();
		settings.setViewSteps( VIEW_STEPS.AS_LIST );
		return settings;
	}

	@Transactional
	public void save(  Workspace workspace ){
		WorkspaceSettings settings = workspace.getSettings();

		if( settings == null ){
			settings = getDefaultSettings();
			workspace.setSettings( settings );
		}

		if( settings.getId() == null ){
			long id = psql.nextval( Sequences.WORKSPACE_SETTINGS_ID_SEQ ).longValue();
			settings.setId(id);
			workspaceSettingsDao.insert( settings );
		} else {
			workspaceSettingsDao.update( settings );
		}
	}

	@Transactional
	public void delete( Workspace workspace ){
		WorkspaceSettingsTable table = WorkspaceSettingsTable.WORKSPACE_SETTINGS;
		psql
			.delete( table )
			.where( table.WORKSPACE_ID.eq(workspace.getId().longValue()) )
			.execute();

		workspace.setSettings( null );
	}

	@Transactional
	public void importBackup( Workspace workspace, WorkspaceBackup workspaceBackup ){
		WorkspaceSettings settings = workspaceBackup.getWorkspace().getSettings();
		if( settings != null ){
			settings.setId( null );
		}
		workspace.setSettings( settings );

		save( workspace );
	}

}


text:
using System;

namespace _01.Resurrection
{
    public class StartUp
    {
        public static void Main()
        {
            int numberOfPhoenixes = int.Parse(Console.ReadLine());
            for (int i = 0; i < numberOfPhoenixes; i++)
            {
                long totalLength = long.Parse(Console.ReadLine());
                decimal totalWidth = decimal.Parse(Console.ReadLine());
                int wingSize = int.Parse(Console.ReadLine());

                decimal totalYears = totalLength * totalLength * (totalWidth + 2 * wingSize);
                Console.WriteLine(totalYears);
            }
        }
    }
}


text:
layout: content-main
title: Materiaali
course: rub5.1
published: true
---
-[Arviointipäivän ohjeet](/media/rub5/Kertausohjeet.pdf)

## Tekstien fraasit - tarkistus

-[Text 2 fraasien tarkistus](/media/rub5/Text 2_fraser.pdf)

-[Text 3 fraasien tarkistus](/media/rub5/Text3_fraasit.pdf)

-[Text 4 fraasien tarkistus](/media/rub5/Text4_fraser.pdf)

**[OTAVAN ÄÄNITIEDOSTO](http://tiedostot.otava.fi/aanet/fokus5/)**

Jos olit pois tunnilta jolloin uusi teksti käydään ensimmäisen kerran, kuuntele teksti kotona ja suomenna. Pyydä muistiinpanot kavereilta. Voit tehdä halutessasi myös äänitiedoston muita harjoituksia kuullunymmärtämisen treenamiseksi.

### [Suullisten tehtävien ohjeet](/media/rub5/Suullisen_ohjeet.pdf)

### [Ohjattujen kirjoitusharjoitusten yleisohje](/media/rub3/OKH_ohje.pdf)

### Quizletit

- [Text 1 fraasit - flashcards](https://quizlet.com/_630mg0)
- [Text 2 fraasit - flashcards](https://quizlet.com/_613ywq)
- [Text 3 fraasit - flashcards](https://quizlet.com/_61402f)
- [Text 4 fraasit - flashcards](https://quizlet.com/_62f0m4)
- [Text 5 fraasit - flashcards](https://quizlet.com/_62ffrr)

- [Ammattisanat](/media/rub5/ammattisanat.pdf)


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Argus.ComponentModel
{

    /// <summary>
    /// An observable class that implements INotifyPropertyChanged and provides a Generic method to modify
    /// properties.
    /// </summary>
    /// <example>
    ///     private int _length = 0;
    ///     public int Length
    ///     {
    ///         get
    ///         {
    ///             return _length;
    ///         }
    ///         set
    ///         {
    ///             Set(ref _length, value, "Length");
    ///         }
    ///     }
    /// </example>
    public class Observable : INotifyPropertyChanged
    {
        /// <summary>
        /// Event that is fired when the property is changed via Set as part of INotifyPropertyChanged.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Used to set the value of a property and fire PropertyChanged event of INotifyPropertyChanged.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="storage"></param>
        /// <param name="value"></param>
        /// <param name="propertyName"></param>
        protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return;
            }

            storage = value;
            OnPropertyChanged(propertyName);
        }

        /// <summary>
        /// OnPropertyChanged
        /// </summary>
        /// <param name="propertyName"></param>
        protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }

}


text:
package org.elasticsearch.snapshots;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

class UpdateIndexShardSnapshotStatusResponse extends ActionResponse {

    UpdateIndexShardSnapshotStatusResponse() {}

    UpdateIndexShardSnapshotStatusResponse(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {}
}


text:
namespace content {
class WebContents;
}

namespace permissions {

class PermissionPromptInfoBar : public PermissionPromptAndroid,
                                public infobars::InfoBarManager::Observer {
 public:
  PermissionPromptInfoBar(const PermissionPromptInfoBar&) = delete;
  PermissionPromptInfoBar& operator=(const PermissionPromptInfoBar&) = delete;
  ~PermissionPromptInfoBar() override;

  PermissionPromptDisposition GetPromptDisposition() const override;

  static std::unique_ptr<PermissionPromptInfoBar> Create(
      content::WebContents* web_contents,
      Delegate* delegate);

  // InfoBar::Manager:
  void OnInfoBarRemoved(infobars::InfoBar* infobar, bool animate) override;
  void OnManagerShuttingDown(infobars::InfoBarManager* manager) override;

 private:
  PermissionPromptInfoBar(content::WebContents* web_contents,
                          Delegate* delegate);

  // The infobar used to display the permission request. Never assume that this
  // pointer is currently alive.
  raw_ptr<infobars::InfoBar> permission_prompt_infobar_;

  base::WeakPtrFactory<PermissionPromptInfoBar> weak_factory_{this};
};

}  // namespace permissions

#endif  // COMPONENTS_PERMISSIONS_ANDROID_PERMISSION_PROMPT_PERMISSION_PROMPT_INFOBAR_H_


text:
package org.apache.gobblin.runtime.spec_store;

import com.google.common.collect.Iterators;
import com.typesafe.config.Config;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.gobblin.config.ConfigBuilder;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.metastore.testing.ITestMetastoreDatabase;
import org.apache.gobblin.metastore.testing.TestMetastoreDatabaseFactory;
import org.apache.gobblin.runtime.api.TopologySpec;
import org.apache.gobblin.runtime.api.FlowSpecSearchObject;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.spec_executorInstance.MockedSpecExecutor;
import org.apache.gobblin.runtime.spec_serde.JavaSpecSerDe;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MysqlBaseSpecStoreTest {
  private static final String USER = "testUser";
  private static final String PASSWORD = "testPassword";
  private static final String TABLE = "base_spec_store";

  private MysqlBaseSpecStore specStore;
  private final URI uri1 = new URI(new TopologySpec.Builder().getDefaultTopologyCatalogURI().toString() + "1");
  private final URI uri2 = new URI(new TopologySpec.Builder().getDefaultTopologyCatalogURI().toString() + "2");
  private TopologySpec topoSpec1, topoSpec2;

  public MysqlBaseSpecStoreTest()
      throws URISyntaxException { // (based on `uri1` and other initializations just above)
  }

  @BeforeClass
  public void setUp() throws Exception {
    ITestMetastoreDatabase testDb = TestMetastoreDatabaseFactory.get();

    // prefix keys to demonstrate disambiguation mechanism used to side-step intentially-sabatoged non-prefixed, 'fallback'
    Config config = ConfigBuilder.create()
        .addPrimitive(ConfigurationKeys.STATE_STORE_DB_URL_KEY, " SABATOGE! !" + testDb.getJdbcUrl())
        .addPrimitive(MysqlBaseSpecStore.CONFIG_PREFIX + "." + ConfigurationKeys.STATE_STORE_DB_URL_KEY, testDb.getJdbcUrl())
        .addPrimitive(MysqlBaseSpecStore.CONFIG_PREFIX + "." + ConfigurationKeys.STATE_STORE_DB_USER_KEY, USER)
        .addPrimitive(MysqlBaseSpecStore.CONFIG_PREFIX + "." + ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, PASSWORD)
        .addPrimitive(MysqlBaseSpecStore.CONFIG_PREFIX + "." + ConfigurationKeys.STATE_STORE_DB_TABLE_KEY, TABLE)
        .build();

    this.specStore = new MysqlBaseSpecStore(config, new JavaSpecSerDe());

    topoSpec1 = new TopologySpec.Builder(this.uri1)
        .withConfig(ConfigBuilder.create()
            .addPrimitive("key", "value")
            .addPrimitive("key3", "value3")
            .addPrimitive("config.with.dot", "value4").build())
        .withDescription("Test1")
        .withVersion("Test version")
        .withSpecExecutor(MockedSpecExecutor.createDummySpecExecutor(new URI("execA")))
        .build();
    topoSpec2 = new TopologySpec.Builder(this.uri2)
        .withConfig(ConfigBuilder.create().addPrimitive("converter", "value1,value2,value3")
            .addPrimitive("key3", "value3").build())
        .withDescription("Test2")
        .withVersion("Test version 2")
        .withSpecExecutor(MockedSpecExecutor.createDummySpecExecutor(new URI("execB")))
        .build();
  }

  @Test(expectedExceptions = UnsupportedOperationException.class)
  public void testSpecSearchUnsupported() throws Exception {
    FlowSpecSearchObject flowSpecSearchObject = FlowSpecSearchObject.builder().build();
    Collection<Spec> specs = this.specStore.getSpecs(flowSpecSearchObject);
  }

  @Test
  public void testAddSpec() throws Exception {
    this.specStore.addSpec(this.topoSpec1);
    this.specStore.addSpec(this.topoSpec2);

    Assert.assertEquals(this.specStore.getSize(), 2);
    Assert.assertTrue(this.specStore.exists(this.uri1));
    Assert.assertTrue(this.specStore.exists(this.uri2));
    Assert.assertFalse(this.specStore.exists(URI.create("dummy")));
  }

  @Test (dependsOnMethods = "testAddSpec")
  public void testGetSpec() throws Exception {
    TopologySpec result = (TopologySpec) this.specStore.getSpec(this.uri1);
    Assert.assertEquals(result, this.topoSpec1);

    Collection<Spec> specs = this.specStore.getSpecs();
    Assert.assertEquals(specs.size(), 2);
    Assert.assertTrue(specs.contains(this.topoSpec1));
    Assert.assertTrue(specs.contains(this.topoSpec1));

    Iterator<URI> uris = this.specStore.getSpecURIs();
    Assert.assertTrue(Iterators.contains(uris, this.uri1));
    Assert.assertTrue(Iterators.contains(uris, this.uri2));
  }

  @Test (dependsOnMethods = "testGetSpec")
  public void testGetSpecWithTag() throws Exception {
    //Creating and inserting specs with tags
    URI uri5 = URI.create("topospec5");
    TopologySpec topoSpec5 = new TopologySpec.Builder(uri5)
        .withConfig(ConfigBuilder.create()
            .addPrimitive("key5", "value5").build())
        .withDescription("Test5")
        .withVersion("Test version 5")
        .withSpecExecutor(MockedSpecExecutor.createDummySpecExecutor(new URI("execE")))
        .build();

    URI uri6 = URI.create("topospec6");
    TopologySpec topoSpec6 = new TopologySpec.Builder(uri6)
        .withConfig(ConfigBuilder.create()
            .addPrimitive("key6", "value6").build())
        .withDescription("Test6")
        .withVersion("Test version 6")
        .withSpecExecutor(MockedSpecExecutor.createDummySpecExecutor(new URI("execF")))
        .build();

    this.specStore.addSpec(topoSpec5, "dr");
    this.specStore.addSpec(topoSpec6, "dr");

    Assert.assertTrue(this.specStore.exists(uri5));
    Assert.assertTrue(this.specStore.exists(uri6));
    List<URI> result = new ArrayList<>();
    this.specStore.getSpecURIsWithTag("dr").forEachRemaining(result::add);
    Assert.assertEquals(result.size(), 2);
  }

  @Test (dependsOnMethods = "testGetSpecWithTag")
  public void testDeleteSpec() throws Exception {
    Assert.assertEquals(this.specStore.getSize(), 4);
    this.specStore.deleteSpec(this.uri1);
    Assert.assertEquals(this.specStore.getSize(), 3);
    Assert.assertFalse(this.specStore.exists(this.uri1));
  }
}


text:
using namespace std;

class SocketTCP;

using SocketTCPRef = shared_ptr<SocketTCP>;

bool initSockets();
void shutdownSockets();

class SocketTCP
{
public:
    static SocketTCPRef listen(int port);
    static SocketTCPRef connect(const std::string& ip, int port);

    virtual ~SocketTCP() {}

    virtual SocketTCPRef accept() = 0;
    virtual bool recv(vector<uint8_t> &out) = 0;
    virtual void send(const void *pData, int size) = 0;
    virtual void close() = 0;

protected:
    SocketTCP();

private:
};

#endif


text:
require_relative '../services/hiring_service'

class CompanyEmployeesController < ApplicationController
  before_action :set_company
  before_action :set_employee, only: [:show, :update, :destroy]
  before_action :set_hiring_service, only: [:create, :destroy]

  # GET /companies/1/employees
  def index
    render json: @company.employees
  end

  # GET /companies/1/employees/1
  def show
    render json: @employee
  end

  # POST /companies/1/employees
  def create
    employee = @hiring_service.hireEmployee(employee_params)
    if employee.errors.present?
      render json: employee.errors, status: :unprocessable_entity
    else
      render json: employee, status: :created, location: @company
    end
  end

  def update
    if @employee.update(employee_params)
      render json: @employee
    else
      render json: @employee.errors, status: :unprocessable_entity
    end
  end

  # DELETE /companies/1/employees/1
  def destroy
    @hiring_service.fireEmployee(@employee)
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_company
    @company = Company.find(params[:company_id])
  end

  def set_employee
    @employee = @company.employees.find(params[:id])
  end

  def set_hiring_service
    @hiring_service = HiringService.new(@company)
  end

  # Only allow a trusted parameter "white list" through.
  def employee_params
    params.require(:employee).permit(:first_name, :last_name, :social_number, :id)
  end
end