text:
package sk.henrichg.phoneprofilesplus;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import java.util.List;

class LocationScanner
{
    private LocationManager mLocationManager;
    private final LocationScannerListener mLocationListener;
    private boolean mListenerEnabled = false;

    final Context context;
    //private final DataWrapper dataWrapper;

    static volatile boolean useGPS = true; // must be static
    static volatile boolean mUpdatesStarted = false; // must be static

    static volatile boolean mTransitionsUpdated = false;

    static final int INTERVAL_DIVIDE_VALUE = 6;
    static final int INTERVAL_DIVIDE_VALUE_FOR_GPS = 3;

    LocationScanner(Context context) {
        this.context = context;
        //dataWrapper = new DataWrapper(context.getApplicationContext(), false, 0, false);

        mLocationListener = new LocationScannerListener();
    }

    void connect(boolean resetUseGPS) {
        try {
            synchronized (PPApplication.locationScannerMutex) {
                //if (dataWrapper.getDatabaseHandler().getGeofenceCount() > 0)

                try {
                    if (mLocationManager == null)
                        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    if (resetUseGPS)
                        useGPS = true;

                    final Context appContext = context.getApplicationContext();
                    //PPApplication.startHandlerThreadPPScanners(/*"LocationScanner.onConnected"*/);
                    //final Handler __handler6 = new Handler(PPApplication.handlerThreadPPScanners.getLooper());
                    //__handler6.post(new PPApplication.PPHandlerThreadRunnable(
                    //        context.getApplicationContext()) {
                    //__handler6.post(() -> {
                    Runnable runnable = () -> {
//                            PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=LocationScanner.connect");

                        //Context appContext= appContextWeakRef.get();
                        //if (appContext != null) {
                            PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
                            PowerManager.WakeLock wakeLock = null;
                            try {
                                if (powerManager != null) {
                                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":LocationScanner_connect");
                                    wakeLock.acquire(10 * 60 * 1000);
                                }

                                if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isLocationScannerStarted()) {
                                    LocationScanner scanner = PhoneProfilesService.getInstance().getLocationScanner();
                                    if (scanner != null) {
                                        scanner.clearAllEventGeofences();
                                        String provider = scanner.startLocationUpdates();
                                        scanner.updateTransitionsByLastKnownLocation(provider);
                                    }
                                }

                            } catch (SecurityException e) {
                                //
                            } catch (Exception e) {
//                                PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
                                PPApplication.recordException(e);
                            } finally {
                                if ((wakeLock != null) && wakeLock.isHeld()) {
                                    try {
                                        wakeLock.release();
                                    } catch (Exception ignored) {
                                    }
                                }
                            }
                        //}
                    }; //);
                    PPApplication.createScannersExecutor();
                    PPApplication.scannersExecutor.submit(runnable);
                } catch (Exception ee) {
                    //Log.e("##### LocationScanner.onConnected", Log.getStackTraceString(e));
                    PPApplication.recordException(ee);
                }

            }
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    void disconnect() {
        try {
            stopLocationUpdates();
            LocationScannerSwitchGPSBroadcastReceiver.removeAlarm(context);
            //useGPS = true; disconnect is called from screen on/off broadcast therefore not change this
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    void updateGeofencesInDB() {
        synchronized (PPApplication.locationScannerMutex) {
            if (PPApplication.lastLocation == null)
                return;

            List<Geofence> geofences = DatabaseHandler.getInstance(context).getAllGeofences();

            //boolean change = false;

            for (Geofence geofence : geofences) {

                Location geofenceLocation = new Location("GL");
                geofenceLocation.setLatitude(geofence._latitude);
                geofenceLocation.setLongitude(geofence._longitude);

                float distance;
                float radius;
                synchronized (PPApplication.locationScannerLastLocationMutex) {
                    Location _lastLocation = new Location("GL");
                    _lastLocation.setLatitude(PPApplication.lastLocation.getLatitude());
                    _lastLocation.setLongitude(PPApplication.lastLocation.getLongitude());

                    distance = Math.abs(_lastLocation.distanceTo(geofenceLocation));
                    radius = PPApplication.lastLocation.getAccuracy() + geofence._radius;
                }

                int transitionType;
                if (distance <= radius) {
                    transitionType = Geofence.GEOFENCE_TRANSITION_ENTER;
                }
                else {
                    transitionType = Geofence.GEOFENCE_TRANSITION_EXIT;
                }

                //int savedTransition = DatabaseHandler.getInstance(context).getGeofenceTransition(geofence._id);

                if (geofence._transition != transitionType) {
                    DatabaseHandler.getInstance(context).updateGeofenceTransition(geofence._id, transitionType);
                    //change = true;
                }
            }

            mTransitionsUpdated = true;
        }
    }

    void clearAllEventGeofences() {
        synchronized (PPApplication.locationScannerMutex) {
            // clear all geofence transitions
            DatabaseHandler.getInstance(context).clearAllGeofenceTransitions();
            mTransitionsUpdated = false;
        }
    }

    //-------------------------------------------

    String getProvider() {
        String provider;

        boolean isPowerSaveMode = GlobalUtils.isPowerSaveMode(context);
        if ((!ApplicationPreferences.applicationEventLocationUseGPS) || isPowerSaveMode || (!useGPS)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            provider = LocationManager.GPS_PROVIDER;
        }

        /*
        // do not force GPS when device is in power save mode
        // removed - consume battery
        boolean gpsForced = false;
        if (provider.equals(LocationManager.NETWORK_PROVIDER) &&
                (!CheckOnlineStatusBroadcastReceiver.isOnline(context)) &&
                (!isPowerSaveMode)) {
            // device is not connected to network, force GPS_PROVIDER
            provider = LocationManager.GPS_PROVIDER;
            gpsForced = true;
        }
        */

        boolean locationEnabled = false;
        // check if GPS provider is enabled in system settings
        if (provider.equals(LocationManager.GPS_PROVIDER)) {
            try {
                locationEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if ((!locationEnabled)/* && (!gpsForced)*/)
                    provider = LocationManager.NETWORK_PROVIDER;
            } catch (Exception e) {
                // we may get IllegalArgumentException if gps location provider
                // does not exist or is not yet installed.
                //locationEnabled = false;
            }
        }
        if (!locationEnabled) {
            // check if network provider is enabled in system settings
            if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
                try {
                    // if device is in power save mode, force NETWORK_PROVIDER
                    locationEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
                                        (isPowerSaveMode);
                } catch (Exception e) {
                    // we may get IllegalArgumentException if network location provider
                    // does not exist or is not yet installed.
                    //locationEnabled = false;
                }
            }
        }
        if (!locationEnabled) {
            if (isPowerSaveMode) {
                // in power save mode force NETWORK_PROVIDER
                provider = LocationManager.NETWORK_PROVIDER;
                locationEnabled = true;
            }
            else {
                // get best provider
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                //criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
                provider = mLocationManager.getBestProvider(criteria, false);
                locationEnabled = (provider != null) && (!provider.isEmpty());
            }
        }

        if (!locationEnabled) {
            provider = "";
            showNotification();
        }

        return provider;
    }

    /**
     * Requests location updates from the FusedLocationApi.
     */
    String startLocationUpdates() {
        if (!ApplicationPreferences.applicationEventLocationEnableScanning)
            return "";

        String provider = "";

        if ((!mUpdatesStarted) /*|| mUpdateTransitionsByLastKnownLocationIsRunning*/) {
            synchronized (PPApplication.locationScannerMutex) {
                try {
                    if (Permissions.checkLocation(context)) {
                        if (!mListenerEnabled) {

                            provider = getProvider();

                            if (!provider.isEmpty()) {
                                try {
                                    // check power save mode
                                    String applicationEventLocationUpdateInPowerSaveMode = ApplicationPreferences.applicationEventLocationUpdateInPowerSaveMode;
                                    boolean isPowerSaveMode = GlobalUtils.isPowerSaveMode(context);
                                    boolean canScan = true;
                                    if (isPowerSaveMode && applicationEventLocationUpdateInPowerSaveMode.equals("2")) {
                                        canScan = false;
                                    }
                                    else {
                                        if (ApplicationPreferences.applicationEventLocationScanInTimeMultiply.equals("2")) {
                                            if (GlobalUtils.isNowTimeBetweenTimes(
                                                    ApplicationPreferences.applicationEventLocationScanInTimeMultiplyFrom,
                                                    ApplicationPreferences.applicationEventLocationScanInTimeMultiplyTo)) {
                                                // not scan wi-fi in configured time
                                                canScan = false;
                                            }
                                        }
                                    }
                                    if (canScan) {
                                        int interval = 25; // seconds
                                        if (ApplicationPreferences.applicationEventLocationUpdateInterval > 1) {
                                            // interval is in minutes
                                            if (!CheckOnlineStatusBroadcastReceiver.isOnline(context))
                                                interval = (ApplicationPreferences.applicationEventLocationUpdateInterval * 60) / INTERVAL_DIVIDE_VALUE_FOR_GPS;
                                            else
                                                interval = (ApplicationPreferences.applicationEventLocationUpdateInterval * 60) / INTERVAL_DIVIDE_VALUE;
                                        }
                                        if (isPowerSaveMode && applicationEventLocationUpdateInPowerSaveMode.equals("1"))
                                            interval = 2 * interval;
                                        final long UPDATE_INTERVAL_IN_MILLISECONDS = (interval * 1000L) / 2;

                                        PPApplication.startHandlerThreadLocation();
                                        mLocationManager.requestLocationUpdates(provider, UPDATE_INTERVAL_IN_MILLISECONDS, 10, mLocationListener, PPApplication.handlerThreadLocation.getLooper());

                                        mListenerEnabled = true;

                                        mUpdatesStarted = true;
                                    }
                                    else
                                        PPApplication.cancelWork(LocationSensorWorker.LOCATION_SENSOR_WORK_TAG, false);

                                } catch (SecurityException securityException) {
                                    // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
                                    mUpdatesStarted = false;
                                    return "";
                                }
                            }
                            //else {
                            //    mListenerEnabled = true;
                            //}
                        }
                    }
                } catch (Exception e) {
                    mUpdatesStarted = false;
                }
            }
        }

        if (!mListenerEnabled)
            provider = "";

        //if (ApplicationPreferences.applicationEventLocationUseGPS &&
        //        CheckOnlineStatusBroadcastReceiver.isOnline(context)) {
            // recursive call this for switch usage of GPS
            LocationScannerSwitchGPSBroadcastReceiver.setAlarm(context);
        //}
        //else
        //    LocationScannerSwitchGPSBroadcastReceiver.removeAlarm(context);

        return provider;
    }

    /**
     * Removes location updates from the FusedLocationApi.
     */
    void stopLocationUpdates() {
        // It is a good practice to remove location requests when the activity is in a paused or
        // stopped state. Doing so helps battery performance and is especially
        // recommended in applications that request frequent location updates.

        if (mUpdatesStarted) {
            synchronized (PPApplication.locationScannerMutex) {
                if (mListenerEnabled) {
                    try {
                        PPApplication.cancelWork(LocationSensorWorker.LOCATION_SENSOR_WORK_TAG, false);

                        if (mLocationManager != null)
                            mLocationManager.removeUpdates(mLocationListener);
                        mListenerEnabled = false;
                        mUpdatesStarted = false;
                    } catch (Exception e) {
                        PPApplication.recordException(e);
                    }
                }
            }
        }
    }

    void updateTransitionsByLastKnownLocation(String provider) {
        try {
            Location location;
            if (provider.isEmpty()) {
                if (useGPS)
                    location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                else
                    location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            } else {
                location = mLocationManager.getLastKnownLocation(provider);
            }

            LocationSensorWorker.enqueueWork(true, context);
            doLocationChanged(location, true);
        } catch (SecurityException e) {
            //
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    static void doLocationChanged(Location location, boolean callEventsHandler) {
        if (location == null)
            return;

        if ((!location.hasAccuracy()))
            return;

        if (location.getAccuracy() > 500)
            return;

        synchronized (PPApplication.locationScannerLastLocationMutex) {
            if (PPApplication.lastLocation == null) {
                PPApplication.lastLocation = new Location("GL");
            }
            PPApplication.lastLocation.set(location);
            //PPApplication.logE("[IN_LISTENER] LocationScanner.doLocationChanged", "lastLocation=" + lastLocation);
        }

        if (Event.getGlobalEventsRunning()) {
            if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isLocationScannerStarted()) {
                LocationScanner scanner = PhoneProfilesService.getInstance().getLocationScanner();
                scanner.updateGeofencesInDB();
                /*if (useGPS) {
                    // location is from enabled GPS, disable it
                    LocationScannerSwitchGPSBroadcastReceiver.setAlarm(scanner.context);
                }*/
                //}
                //if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isLocationScannerStarted()) {
                //LocationScanner scanner = PhoneProfilesService.getInstance().getGeofencesScanner();

                if (callEventsHandler) {
//                    PPApplication.logE("[EVENTS_HANDLER] LocationScanner.doLocationChanged", "sensorType=SENSOR_TYPE_LOCATION_SCANNER");
                    EventsHandler eventsHandler = new EventsHandler(scanner.context);
                    eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_LOCATION_SCANNER);
                }
            }
        }
    }

    static class LocationScannerListener implements LocationListener {

        public void onLocationChanged(Location location) {
//            PPApplication.logE("[IN_LISTENER] LocationScanner.LocationScannerListener.onLocationChanged", "xxx");
            doLocationChanged(location, false);
        }

        public void onProviderDisabled(String provider) {
//            PPApplication.logE("[IN_LISTENER] LocationScanner.LocationScannerListener.onProviderDisabled", "xxx");
        }

        public void onProviderEnabled(String provider) {
//            PPApplication.logE("[IN_LISTENER] LocationScanner.LocationScannerListener.onProviderEnabled", "xxx");
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
//            PPApplication.logE("[IN_LISTENER] LocationScanner.LocationScannerListener.onStatusChanged", "xxx");
        }
    }

    static void onlineStatusChanged(Context context) {
        if (PhoneProfilesService.getInstance() != null) {
            PhoneProfilesService serviceInstance = PhoneProfilesService.getInstance();
            LocationScanner scanner = serviceInstance.getLocationScanner();
            if (scanner != null) {
                if (serviceInstance.isLocationScannerStarted()) {

                    if (ApplicationPreferences.applicationEventLocationUseGPS &&
                            (!CheckOnlineStatusBroadcastReceiver.isOnline(context))) {
                        // device is not online

//                        if (PPApplication.lastLocation == null) {
//                            PPApplication.lastLocation = new Location("GL");
//                        }
//
//                        doLocationChanged(PPApplication.lastLocation, true);

                        scanner.stopLocationUpdates();

                        GlobalUtils.sleep(1000);

                        // force useGPS
                        LocationScanner.useGPS = true;

                        // this also calls LocationScannerSwitchGPSBroadcastReceiver.setAlarm()
                        String provider = scanner.startLocationUpdates();
                        scanner.updateTransitionsByLastKnownLocation(provider);

                    } else {
                        // device is online

                        scanner.stopLocationUpdates();

                        GlobalUtils.sleep(1000);

                        // this also calls LocationScannerSwitchGPSBroadcastReceiver.setAlarm()
                        String provider = scanner.startLocationUpdates();
                        scanner.updateTransitionsByLastKnownLocation(provider);
                    }
                }
            }
        }
    }

    private void showNotification() {
        String nText = context.getString(R.string.location_scanner_location_not_working_notification_text);

        PPApplication.createExclamationNotificationChannel(context);
        NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(context, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
                .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))
                .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
                .setContentTitle(context.getString(R.string.location_scanner_location_not_working_notification_title)) // title for notification
                .setContentText(nText) // message for notification
                .setAutoCancel(true); // clear notification after click
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));

        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);

        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        //if (android.os.Build.VERSION.SDK_INT >= 21)
        //{
        mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        //}

        mBuilder.setGroup(PPApplication.SYTEM_CONFIGURATION_ERRORS_NOTIFICATION_GROUP);

        NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(context);
        try {
            mNotificationManager.notify(
                    PPApplication.LOCATION_NOT_WORKING_NOTIFICATION_TAG,
                    PPApplication.LOCATION_NOT_WORKING_NOTIFICATION_ID, mBuilder.build());
        } catch (Exception e) {
            //Log.e("ActionForExternalApplicationActivity.showNotification", Log.getStackTraceString(e));
            PPApplication.recordException(e);
        }
    }

}


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

namespace argparse.UnitTests
{
        public class ArgumentAttributeTests
    {
//        [Fact]
//        public void NullNameShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute(null, typeof(string)));
//        }

//        [Fact]
//        public void EmptyNameShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute(string.Empty, typeof(string)));
//        }

//        [Fact]
//        public void SingleCharacterNameShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("A", typeof(string)));
//        }

//        [Fact]
//        public void LowercaseNameShouldPass()
//        {
//            string name = "flag";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void MixedCaseNameShouldPass()
//        {
//            string name = "Flag";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void MixedCaseNameWithNumberShouldPass()
//        {
//            string name = "Flag10";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void NameWithHyphenShouldPass()
//        {
//            string name = "my-flag";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void NameWithUnderscoreShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("my_flag", typeof(string)));
//        }

//        [Fact]
//        public void NameWithSpecialCharactersShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag$", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag#", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag(", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag+", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag=", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag|", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag\\", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag/", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("$flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("#flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("(flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("+flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("=flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("|flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("\\flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("/flag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl$ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl#ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl(ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl+ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl=ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl|ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl\\ag", typeof(string)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("fl/ag", typeof(string)));
//        }

//        [Fact]
//        public void StartingLowerLetterNameShouldPass()
//        {
//            string name = "flag";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void StartingUppercaseLetterNameShouldPass()
//        {
//            string name = "Flag";
//            Assert.Equal(name, new ArgumentAttribute(name, typeof(string)).Name);
//        }

//        [Fact]
//        public void StartingNumberNameShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("1flag", typeof(string)));
//        }

//        [Fact]
//        public void StartingHyphenNameShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("-flag", typeof(string)));
//        }

//        [Fact]
//        public void SupportedTypesShouldPass()
//        {
//            foreach (Type type in ArgumentParser.SupportedTypes)
//            {
//                Assert.Equal(type, new ArgumentAttribute("flag", type).Type);
//            }
//        }

//        [Fact]
//        public void UnknownTypesShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(object)));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(ArgumentAttributeTests)));
//        }

//        [Fact]
//        public void DefaultFlagShouldBe_charMinValue()
//        {
//            Assert.Equal(char.MinValue, new ArgumentAttribute("flag", typeof(string)).Flag);
//        }

//        [Fact]
//        public void LowercaseFlagShouldPass()
//        {
//            Assert.Equal('f', new ArgumentAttribute("flag", typeof(string), flag: 'f').Flag);
//        }

//        [Fact]
//        public void UppercaseFlagShouldPass()
//        {
//            Assert.Equal('F', new ArgumentAttribute("flag", typeof(string), flag: 'F').Flag);
//        }

//        [Fact]
//        public void NumberFlagShouldPass()
//        {
//            Assert.Equal('1', new ArgumentAttribute("flag", typeof(string), flag: '1').Flag);
//        }

//        [Fact]
//        public void SpecialCharacterFlagShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '$'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '@'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '%'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '-'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '='));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '\\'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '/'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '.'));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: ','));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), flag: '+'));
//        }

//        [Fact]
//        public void NullHelpTextSetsToEmptyString()
//        {
//            Assert.Equal(string.Empty, new ArgumentAttribute("flag", typeof(string), help: null).Help);
//        }

//        [Fact]
//        public void HelpTextWithEmptyStringShouldPass()
//        {
//            Assert.Equal(string.Empty, new ArgumentAttribute("flag", typeof(string), help: string.Empty).Help);
//            Assert.Equal("", new ArgumentAttribute("flag", typeof(string), help: "").Help);
//        }

//        [Fact]
//        public void HelpTextIsNotManipulated()
//        {
//            string help = "This is a help string";

//            Assert.Equal(help, new ArgumentAttribute("flag", typeof(string), help: help).Help);
//        }

//        [Fact]
//        public void HelpTextCanBeMultiline()
//        {
//            string help =
//@"This is a help string
//With multiple
//Lines.";

//            Assert.Equal(help, new ArgumentAttribute("flag", typeof(string), help: help).Help);
//        }

//        [Fact]
//        public void HelpTextCanHaveNewlineAndEscapeCharacters()
//        {
//            string help =
//@"This is a help string\n
//\t\tWith multiple\r\n
//Lines and \ escape charaters";

//            Assert.Equal(help, new ArgumentAttribute("flag", typeof(string), help: help).Help);
//        }

//        [Fact]
//        public void CountShouldPassOnType_short()
//        {
//            Assert.True(new ArgumentAttribute("countableflag", typeof(short), count: true).Count);
//        }

//        [Fact]
//        public void CountShouldPassOnType_int()
//        {
//            Assert.True(new ArgumentAttribute("countableflag", typeof(int), count: true).Count);
//        }

//        [Fact]
//        public void CountShouldPassOnType_uint()
//        {
//            Assert.True(new ArgumentAttribute("countableflag", typeof(uint), count: true).Count);
//        }

//        [Fact]
//        public void CountShouldPassOnType_long()
//        {
//            Assert.True(new ArgumentAttribute("countableflag", typeof(long), count: true).Count);
//        }

//        [Fact]
//        public void CountShouldPassOnType_ulong()
//        {
//            Assert.True(new ArgumentAttribute("countableflag", typeof(ulong), count: true).Count);
//        }

//        [Fact]
//        public void CountWithNonNumberTypeShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(string), count: true));
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(Enum), count: true));
//        }

//        [Fact]
//        public void NullDefaultValueShouldPass()
//        {
//            Assert.IsNull(new ArgumentAttribute("flag", typeof(string), defaultValue: null).DefaultValue);
//        }

//        [Fact]
//        public void DefaultValueOfSameTypeAsTypeShouldPass()
//        {
//            Assert.Equal("default", new ArgumentAttribute("flag", typeof(string), defaultValue: "default").DefaultValue);
//            Assert.Equal(10, new ArgumentAttribute("flag", typeof(int), defaultValue: 10).DefaultValue);
//        }

//        [Fact]
//        public void DefaultValueWithDifferentTypeAsTypeShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(int), defaultValue: "default"));
//        }

//        [Fact]
//        public void RequiredWithDefaultParametersShouldPass()
//        {
//            Assert.True(new ArgumentAttribute("flag", typeof(string), required: true).Required);
//        }

//        [Fact]
//        public void RequiredAndFallThroughSilentlyBothSetShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(int), required: true, fallThroughSilentlyOnError: true));
//        }

//        [Fact]
//        public void FallThroughSilentlyWithDefaultParametersShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(int), fallThroughSilentlyOnError: true));
//        }

//        [Fact]
//        public void FallThroughSilentlyAndNullDefaultValueShouldThrowArgumentException()
//        {
//            Assert.Throws<ArgumentException>(() => new ArgumentAttribute("flag", typeof(int), defaultValue: null, fallThroughSilentlyOnError: true));
//        }

//        [Fact]
//        public void FallThroughSilentlyAndDefaultValueSetShouldPass()
//        {
//            Assert.True(new ArgumentAttribute("flag", typeof(int), defaultValue: 1, fallThroughSilentlyOnError: true).FallThroughSilentlyOnError);
//        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ch.qos.logback.core.boolex;

import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.LifeCycle;

/**
 * Evaluates whether a given an event matches user-specified criteria.
 *
 *

 * Implementations are free to evaluate the event as they see fit. In
 * particular, the evaluation results may depend on previous events.
 *
 * @author Ceki Gülcü
 */

public interface EventEvaluator<E> extends ContextAware, LifeCycle {

    /**
     * Evaluates whether the event passed as parameter matches some user-specified
     * criteria.
     *
     *

     * The Evaluator is free to evaluate the event as it pleases. In
     * particular, the evaluation results may depend on previous events.
     *
     * @param event
     *          The event to evaluate
     * @return true if there is a match, false otherwise.
     * @throws NullPointerException
     *           can be thrown in presence of null values
     * @throws EvaluationException
     *           may be thrown during faulty evaluation
     */
    boolean evaluate(E event) throws NullPointerException, EvaluationException;

    /**
     * Evaluators are named entities.
     *
     * @return The name of this evaluator.
     */
    String getName();

    /**
     * Evaluators are named entities.
     */
    void setName(String name);
}


text:
package iso20022

// Instruction from an investor to sell investment fund units back to the fund.
type RedemptionOrder4 struct {

	// Unique and unambiguous identifier for an order, as assigned by the instructing party.
	OrderReference *Max35Text `xml:"OrdrRef"`

	// Specifies the category of the investment fund order.
	OrderType []*FundOrderType1 `xml:"OrdrTp,omitempty"`

	// Investment fund class related to an order.
	FinancialInstrumentDetails *FinancialInstrument6 `xml:"FinInstrmDtls"`

	// Quantity of investment fund units redeemed.
	UnitsNumber *FinancialInstrumentQuantity1 `xml:"UnitsNb"`

	// Amount of money used to derive the quantity of investment fund units to be sold.
	NetAmount *ActiveOrHistoricCurrencyAndAmount `xml:"NetAmt"`

	// Portion of the investor's holdings, in a specific investment fund/ fund class, that is redeemed.
	HoldingsRedemptionRate *PercentageRate `xml:"HldgsRedRate"`

	// Indicates the rounding direction applied to nearest unit.
	Rounding *RoundingDirection2Code `xml:"Rndg,omitempty"`

	// Amount of money used to derive the quantity of investment fund units to be sold, including all charges, commissions, and tax.
	GrossAmount *ActiveOrHistoricCurrencyAndAmount `xml:"GrssAmt,omitempty"`

	// Information needed to process a currency exchange or conversion.
	ForeignExchangeDetails *ForeignExchangeTerms5 `xml:"FXDtls,omitempty"`

	// Dividend option chosen by the account owner based on the options offered in the prospectus.
	IncomePreference *IncomePreference1Code `xml:"IncmPref,omitempty"`

	// Tax group to which the purchased investment fund units belong. The investor indicates to the intermediary operating pooled nominees, which type of unit is to be sold.
	Group1Or2Units *UKTaxGroupUnitCode `xml:"Grp1Or2Units,omitempty"`

	// Charge for the placement of an order.
	ChargeDetails []*Charge8 `xml:"ChrgDtls,omitempty"`

	// Commission linked to the execution of an investment fund order.
	CommissionDetails []*Commission6 `xml:"ComssnDtls,omitempty"`

	// Tax applicable to an investment fund order.
	TaxDetails []*Tax6 `xml:"TaxDtls,omitempty"`

	// Parameters used to execute the settlement of an investment fund order.
	SettlementAndCustodyDetails *FundSettlementParameters3 `xml:"SttlmAndCtdyDtls,omitempty"`

	// Indicates whether the financial instrument is to be physically delivered.
	PhysicalDeliveryIndicator *YesNoIndicator `xml:"PhysDlvryInd"`

	// Information related to physical delivery of the securities.
	PhysicalDeliveryDetails *DeliveryParameters3 `xml:"PhysDlvryDtls,omitempty"`

	// Currency requested for settlement of cash proceeds.
	RequestedSettlementCurrency *CurrencyCode `xml:"ReqdSttlmCcy,omitempty"`

	// Currency to be used for pricing the fund. This currency must be among the set of currencies in which the price may be expressed, as stated in the prospectus.
	RequestedNAVCurrency *CurrencyCode `xml:"ReqdNAVCcy,omitempty"`

	// Payment transaction resulting from the investment fund order execution.
	CashSettlementDetails *PaymentTransaction15 `xml:"CshSttlmDtls,omitempty"`
}

func (r *RedemptionOrder4) SetOrderReference(value string) {
	r.OrderReference = (*Max35Text)(&value)
}

func (r *RedemptionOrder4) AddOrderType() *FundOrderType1 {
	newValue := new(FundOrderType1)
	r.OrderType = append(r.OrderType, newValue)
	return newValue
}

func (r *RedemptionOrder4) AddFinancialInstrumentDetails() *FinancialInstrument6 {
	r.FinancialInstrumentDetails = new(FinancialInstrument6)
	return r.FinancialInstrumentDetails
}

func (r *RedemptionOrder4) AddUnitsNumber() *FinancialInstrumentQuantity1 {
	r.UnitsNumber = new(FinancialInstrumentQuantity1)
	return r.UnitsNumber
}

func (r *RedemptionOrder4) SetNetAmount(value, currency string) {
	r.NetAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (r *RedemptionOrder4) SetHoldingsRedemptionRate(value string) {
	r.HoldingsRedemptionRate = (*PercentageRate)(&value)
}

func (r *RedemptionOrder4) SetRounding(value string) {
	r.Rounding = (*RoundingDirection2Code)(&value)
}

func (r *RedemptionOrder4) SetGrossAmount(value, currency string) {
	r.GrossAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (r *RedemptionOrder4) AddForeignExchangeDetails() *ForeignExchangeTerms5 {
	r.ForeignExchangeDetails = new(ForeignExchangeTerms5)
	return r.ForeignExchangeDetails
}

func (r *RedemptionOrder4) SetIncomePreference(value string) {
	r.IncomePreference = (*IncomePreference1Code)(&value)
}

func (r *RedemptionOrder4) SetGroup1Or2Units(value string) {
	r.Group1Or2Units = (*UKTaxGroupUnitCode)(&value)
}

func (r *RedemptionOrder4) AddChargeDetails() *Charge8 {
	newValue := new(Charge8)
	r.ChargeDetails = append(r.ChargeDetails, newValue)
	return newValue
}

func (r *RedemptionOrder4) AddCommissionDetails() *Commission6 {
	newValue := new(Commission6)
	r.CommissionDetails = append(r.CommissionDetails, newValue)
	return newValue
}

func (r *RedemptionOrder4) AddTaxDetails() *Tax6 {
	newValue := new(Tax6)
	r.TaxDetails = append(r.TaxDetails, newValue)
	return newValue
}

func (r *RedemptionOrder4) AddSettlementAndCustodyDetails() *FundSettlementParameters3 {
	r.SettlementAndCustodyDetails = new(FundSettlementParameters3)
	return r.SettlementAndCustodyDetails
}

func (r *RedemptionOrder4) SetPhysicalDeliveryIndicator(value string) {
	r.PhysicalDeliveryIndicator = (*YesNoIndicator)(&value)
}

func (r *RedemptionOrder4) AddPhysicalDeliveryDetails() *DeliveryParameters3 {
	r.PhysicalDeliveryDetails = new(DeliveryParameters3)
	return r.PhysicalDeliveryDetails
}

func (r *RedemptionOrder4) SetRequestedSettlementCurrency(value string) {
	r.RequestedSettlementCurrency = (*CurrencyCode)(&value)
}

func (r *RedemptionOrder4) SetRequestedNAVCurrency(value string) {
	r.RequestedNAVCurrency = (*CurrencyCode)(&value)
}

func (r *RedemptionOrder4) AddCashSettlementDetails() *PaymentTransaction15 {
	r.CashSettlementDetails = new(PaymentTransaction15)
	return r.CashSettlementDetails
}


text:
using System;
using System.Threading.Tasks;
using AutoFixture;
using EmployeeDirectory.DataAccess.Contracts;
using EmployeeDirectory.Example.BLL.Contracts;
using EmployeeDirectory.Example.BLL.Implementation;
using EmployeeDirectory.Example.Domain;
using EmployeeDirectory.Example.Domain.Models;
using FluentAssertions;
using Moq;
using NUnit.Framework;

namespace EmployeeDirectory.Example.BLL.Tests.Unit
{
    public class EmployeeCreateServiceTests
    {
        [Test]
        public async Task CreateAsync_DepartmentValidationSucceed_CreatesEmployee()
        {
            // Arrange
            var employee = new EmployeeUpdateModel();
            var expected = new Employee();

            var departmentGetService = new Mock<IDepartmentGetService>();
            departmentGetService.Setup(x => x.ValidateAsync(employee));

            var employeeDataAccess = new Mock<IEmployeeDataAccess>();
            employeeDataAccess.Setup(x => x.InsertAsync(employee)).ReturnsAsync(expected);

            var employeeGetService = new EmployeeCreateService(employeeDataAccess.Object, departmentGetService.Object);

            // Act
            var result = await employeeGetService.CreateAsync(employee);

            // Assert
            result.Should().Be(expected);
        }

        [Test]
        public async Task CreateAsync_DepartmentValidationFailed_ThrowsError()
        {
            // Arrange
            var fixture = new Fixture();
            var employee = new EmployeeUpdateModel();
            var expected = fixture.Create<string>();

            var departmentGetService = new Mock<IDepartmentGetService>();
            departmentGetService
                .Setup(x => x.ValidateAsync(employee))
                .Throws(new InvalidOperationException(expected));

            var employeeDataAccess = new Mock<IEmployeeDataAccess>();

            var employeeGetService = new EmployeeCreateService(employeeDataAccess.Object, departmentGetService.Object);

            // Act
            var action = new Func<Task>(() => employeeGetService.CreateAsync(employee));

            // Assert
            await action.Should().ThrowAsync<InvalidOperationException>().WithMessage(expected);
            employeeDataAccess.Verify(x => x.InsertAsync(employee), Times.Never);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/michiel/workspace/AndroidStudioProjects/EspLight/app/src/main/res/values-w820dp/dimens.xml -->
    <eat-comment/>
    <dimen name="activity_horizontal_margin">64dp</dimen>
</resources>


text:
<?php
/**
 * Feedback mail.
 *
 * @var string $email
 * @var string $message
 * @var \Anthem\Auth\Model\User|null $user
 * @var \Anthem\Core\View\ViewHelpers $view
 * @var \Anthem\Core\View\LinkHelpers $link
 * @var \Silex\Application $app
 */
?>

<?php $view->beginSlot('content') ?>

<?php echo _t('Feedback.MAIL', $app['request']->getUriForPath('/'), $app['Core']['project']) ?>

<?php echo nl2br(htmlspecialchars($message)) ?>

<?php if ($user): ?>

<?php echo _t('Feedback.MAIL_CAN_REPLY_REGISTERED', $email, $link->url('admin.page', array('page' => 'auth.admin.users'), true) . '#id=' . $user->getId()) ?>

<?php elseif ($email): ?>

<?php echo _t('Feedback.MAIL_CAN_REPLY', $email) ?>

<?php else: ?>

<?php echo _t('Feedback.MAIL_CANNOT_REPLY') ?>

<?php endif; ?>

<?php $view->endSlot() ?>
<?php echo $view->sub('Anthem/Core:mail_layout.php') ?>


text:
package com.ibm.datapower.er.mgmt;

//import java.util.logging.Level;
//import java.util.logging.Logger;

/**
 * General exception from ERMgmt.
 * <p>
 * This is a superclass to a number of ERMgmt exceptions.
 *
 * @author Dana Numkena
 */

public class ERMgmtException extends Exception {

    //private static Logger logger=Logger.getLogger("er.mgmt.exception.log");

    ERMgmtException (String a) {
        super(a);
        //logger.log(Level.WARNING, a);
        //System.out.print(a);
    }
    /**
     * Constructs a new exception with the specified detail message and cause.
     *
     * @param message the detail message (which is saved for later retrieval by the Throwable.getMessage() method).
     * @param e       the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
     */
    ERMgmtException (String message, Throwable e){
    	super(message, e);
    }
}


text:
require 'simplecov'
require 'webmock'
require 'vcr'

class InceptionFormatter
  def format(result)
    Coveralls::SimpleCov::Formatter.new.format(result)
  end
end

def setup_formatter
  SimpleCov.formatter = if ENV['TRAVIS'] || ENV['COVERALLS_REPO_TOKEN']
    InceptionFormatter
  else
    SimpleCov::Formatter::HTMLFormatter
  end

  # SimpleCov.start 'test_frameworks'
  SimpleCov.start do
    add_filter do |source_file|
      source_file.filename =~ /spec/ && !(source_file.filename =~ /fixture/)
    end
  end
end

setup_formatter

require 'coveralls'

VCR.configure do |c|
  c.cassette_library_dir = 'fixtures/vcr_cassettes'
  c.hook_into :webmock
end

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
  config.include WebMock::API
  config.expect_with :rspec do |c|
    c.syntax = [:should, :expect]
  end
  config.mock_with :rspec do |c|
    c.syntax = [:should, :expect]
  end
  config.after(:suite) do
    WebMock.disable!
  end
end

def stub_api_post
  body = "{\"message\":\"\",\"url\":\"\"}"
  stub_request(:post, Coveralls::API::API_BASE+"/jobs").with(
    :body => /.+/,
    :headers => {
      'Accept'=>'*/*; q=0.5, application/xml',
      'Accept-Encoding'=>'gzip, deflate',
      'Content-Length'=>/.+/,
      'Content-Type'=>/.+/,
      'User-Agent'=>'Ruby'
    }
  ).to_return(:status => 200, :body => body, :headers => {})
end

def silence
  return yield if ENV['silence'] == 'false'

  silence_stream(STDOUT) do
    yield
  end
end

module Kernel
  def silence_stream(stream)
    old_stream = stream.dup
    stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
    stream.sync = true
    yield
  ensure
    stream.reopen(old_stream)
  end
end


text:
<md-card *ngIf='user'>
	<md-card-title-group>

		<md-card-title class='non-empty'> {{ user.displayName }} </md-card-title>
		<md-card-subtitle>

 {{ user.location }}

 {{ 'PROFILE.EDIT.INSTRUCTION' | translate }}

		</md-card-subtitle>
	</md-card-title-group>

	<form [formGroup]='profileForm' (ngSubmit)='onSubmit()'>
		<md-card-content>

<md-input type='text' id='name' formControlName='name' required
				placeholder="{{ 'PROFILE.EDIT.NAME' | translate }}">
				<md-hint [style.visibility]='showError("name")'>
					{{ 'APP.FORM.REQUIRED' | translate }}
				</md-hint>
			</md-input>

<md-input type='text' id='nickname' formControlName='nickname'
				placeholder="{{ 'PROFILE.EDIT.NICKNAME' | translate }}">
			</md-input>

<md-input type='text' id='location' formControlName='location'
				required autocomplete='off'
				placeholder="{{ 'PROFILE.EDIT.LOCATION' | translate }}">
				<md-hint [style.visibility]='showError("location")'>
					{{ 'APP.FORM.REQUIRED' | translate }}
				</md-hint>
			</md-input>

			<md-nav-list dense *ngIf='locations'>

					{{ location }}

			</md-nav-list>

		</md-card-content>

		<md-card-actions>
			<button type="submit" md-button [disabled]="!profileForm.valid">
				{{ 'APP.FORM.SAVE' | translate }}
			</button>

				{{ 'APP.FORM.CANCEL' | translate }}

		</md-card-actions>
	</form>
</md-card>


text:
<?php

namespace Weixin\Biz\Exception;

use Exception;

class AesDecryptErrorException extends Exception
{

    public function __construct()
    {
        parent::__construct('AES 解密失败', -40007);
    }

}


text:
package org.xbmc.kore.eventclient;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Locale;

/**
 * Event Client Class
 *
 * Implements an XBMC-Client. This class can be used to implement your own application which
 * should act as a Input device for XBMC. Also starts a Ping-Thread, which tells the XBMC EventServer
 * that the client is alive. Therefore if you close your application you SHOULD call stopClient()!
 * @author Stefan Agner
 *
 */
public class EventClient
{
	private final boolean hasIcon;
	private String deviceName;
	private PingThread oPingThread;
	private byte iconType = Packet.ICON_PNG;
	private byte[] iconData;
	private InetAddress hostAddress;
	private int hostPort;

	/**
	 * Starts a XBMC EventClient.
	 * @param hostAddress Address of the Host running XBMC
	 * @param hostPort Port of the Host running XBMC (default 9777)
	 * @param deviceName Name of the Device
	 * @param iconFile Path to the Iconfile (PNG, JPEG or GIF)
	 * @throws IOException Exception
	 */
	public EventClient(InetAddress hostAddress, int hostPort, String deviceName, String iconFile) throws IOException
	{
		byte iconType = Packet.ICON_PNG;
		// Assume png as icon type
		if(iconFile.toLowerCase(Locale.US).endsWith(".jpeg"))
			iconType = Packet.ICON_JPEG;
		if(iconFile.toLowerCase(Locale.US).endsWith(".jpg"))
			iconType = Packet.ICON_JPEG;
		if(iconFile.toLowerCase(Locale.US).endsWith(".gif"))
			iconType = Packet.ICON_GIF;

		// Read the icon file to the byte array...
		FileInputStream iconFileStream = new FileInputStream(iconFile);
		byte[] iconData = new byte[iconFileStream.available()];
		iconFileStream.read(iconData);

		hasIcon = true;

		// Call start-Method...
		startClient(hostAddress, hostPort, deviceName, iconType, iconData);
	}

	/**
	 * Starts a XBMC EventClient.
	 * @param hostAddress Address of the Host running XBMC
	 * @param hostPort Port of the Host running XBMC (default 9777)
	 * @param deviceName Name of the Device
	 * @param iconType Type of the icon file (see Packet.ICON_PNG, Packet.ICON_JPEG or Packet.ICON_GIF)
	 * @param iconData The icon itself as a Byte-Array
	 */
	public EventClient(InetAddress hostAddress, int hostPort, String deviceName, byte iconType, byte[] iconData) throws IOException
	{
		hasIcon = true;
		startClient(hostAddress, hostPort, deviceName, iconType, iconData);
	}

	/**
	 * Starts a XBMC EventClient without an icon.
	 * @param hostAddress Address of the Host running XBMC
	 * @param hostPort Port of the Host running XBMC (default 9777)
	 * @param deviceName Name of the Device
	 */
	public EventClient(InetAddress hostAddress, int hostPort, String deviceName) throws IOException
	{
		hasIcon = false;
		byte iconType = Packet.ICON_NONE;
		byte[] iconData = null;
		startClient(hostAddress, hostPort, deviceName, iconType, iconData);
	}

	/**
	 * Starts a XBMC EventClient.
	 * @param hostAddress Address of the Host running XBMC
	 * @param hostPort Port of the Host running XBMC (default 9777)
	 * @param deviceName Name of the Device
	 * @param iconType Type of the icon file (see Packet.ICON_PNG, Packet.ICON_JPEG or Packet.ICON_GIF)
	 * @param iconData The icon itself as a Byte-Array
	 */
	private void startClient(InetAddress hostAddress, int hostPort, String deviceName, byte iconType, byte[] iconData) throws IOException
	{
		// Save host address and port
		this.hostAddress = hostAddress;
		this.hostPort = hostPort;
		this.deviceName = deviceName;

		this.iconType = iconType;
		this.iconData = iconData;

		// Send Hello Packet...
		PacketHELO p;
		if(hasIcon)
			p = new PacketHELO(deviceName, iconType, iconData);
		else
			p = new PacketHELO(deviceName);

		p.send(hostAddress, hostPort);

		// Start Thread (for Ping packets...)
		oPingThread = new PingThread(hostAddress, hostPort, 20000);
		oPingThread.start();
	}

	/**
	 * Stops the XBMC EventClient (especially the Ping-Thread)
	 */
	public void stopClient() throws IOException
	{
		// Stop Ping-Thread...
		oPingThread.giveup();
		oPingThread.interrupt();

		PacketBYE p = new PacketBYE();
		p.send(hostAddress, hostPort);
	}

	/**
	 * Displays a notification window in XBMC.
	 * @param title Message title
	 * @param message The actual message
	 */
	public void sendNotification(String title, String message) throws IOException
	{
		PacketNOTIFICATION p;
		if(hasIcon)
			p = new PacketNOTIFICATION(title, message, iconType, iconData);
		else
			p = new PacketNOTIFICATION(title, message);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Sends a Button event
	 * @param code raw button code (default: 0)
	 * @param repeat this key press should repeat until released (default: 1)
     * Note that queued pressed cannot repeat.
	 * @param down if this is 1, it implies a press event, 0 implies a release
     * event. (default: 1)
	 * @param queue a queued key press means that the button event is
     * executed just once after which the next key press is processed.
     * It can be used for macros. Currently there is no support for
     * time delays between queued presses. (default: 0)
	 * @param amount unimplemented for now; in the future it will be used for
     * specifying magnitude of analog key press events
	 * @param axis Axis
	 */
	public void sendButton(short code, boolean repeat, boolean down, boolean queue, short amount, byte axis) throws IOException
	{
		PacketBUTTON p = new PacketBUTTON(code, repeat, down, queue, amount, axis);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Sends a Button event
	 * @param map_name a combination of map_name and button_name refers to a
     * mapping in the user's Keymap.xml or Lircmap.xml.
     * map_name can be one of the following:
     *

     *
"KB" => standard keyboard map ( <keyboard> section )

     *
"XG" => xbox gamepad map ( <gamepad> section )

     *
"R1" => xbox remote map ( <remote> section )

     *
"R2" => xbox universal remote map ( <universalremote> section )

     *
"LI:devicename" => LIRC remote map where 'devicename' is the
     * actual device's name

	 * @param button_name a button name defined in the map specified in map_name.
     * For example, if map_name is "KB" refering to the <keyboard> section in Keymap.xml
     * then, valid button_names include "printscreen", "minus", "x", etc.
	 * @param repeat this key press should repeat until released (default: 1)
     * Note that queued pressed cannot repeat.
	 * @param down if this is 1, it implies a press event, 0 implies a release
     * event. (default: 1)
	 * @param queue a queued key press means that the button event is
     * executed just once after which the next key press is processed.
     * It can be used for macros. Currently there is no support for
     * time delays between queued presses. (default: 0)
	 * @param amount unimplemented for now; in the future it will be used for
     * specifying magnitude of analog key press events
	 * @param axis Axis
	 */
	public void sendButton(String map_name, String button_name, boolean repeat, boolean down, boolean queue, short amount, byte axis) throws IOException
	{
		PacketBUTTON p = new PacketBUTTON(map_name, button_name, repeat, down, queue, amount, axis);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Sets the mouse position in XBMC
	 * @param x horitontal position ranging from 0 to 65535
	 * @param y vertical position ranging from 0 to 65535
	 */
	public void sendMouse(int x, int y) throws IOException
	{
		PacketMOUSE p = new PacketMOUSE(x, y);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Sends a ping to the XBMC EventServer
	 */
	public void ping() throws IOException
	{
		PacketPING p = new PacketPING();
		p.send(hostAddress, hostPort);
	}

	/**
	 * Tells XBMC to log the message to xbmc.log with the loglevel as specified.
	 * @param loglevel the loglevel, follows XBMC standard.
	 *

	 *
0 = DEBUG

	 *
1 = INFO

	 *
2 = NOTICE

	 *
3 = WARNING

	 *
4 = ERROR

	 *
5 = SEVERE

	 *

	 * @param logmessage the message to log
	 */
	public void sendLog(byte loglevel, String logmessage) throws IOException
	{
		PacketLOG p = new PacketLOG(loglevel, logmessage);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Tells XBMC to do the action specified, based on the type it knows were it needs to be sent.
	 * @param actionmessage Actionmessage (as in scripting/skinning)
	 */
	public void sendAction(String actionmessage) throws IOException
	{
		PacketACTION p = new PacketACTION(actionmessage);
		p.send(hostAddress, hostPort);
	}

	/**
	 * Implements a PingThread which tells XBMC EventServer that the Client is alive (this should
	 * be done at least every 60 seconds!
	 * @author Stefan Agner
	 *
	 */
	static class PingThread extends Thread
	{
		private final InetAddress hostAddress;
		private final int hostPort;
		private final int sleepTime;
		private boolean giveup = false;

		public PingThread(InetAddress hostAddress, int hostPort, int sleepTime)
		{
			super("XBMC EventClient Ping-Thread");
			this.hostAddress = hostAddress;
			this.hostPort = hostPort;
			this.sleepTime = sleepTime;
		}

		public void giveup()
		{
			giveup = true;
		}

		public void run()
		{
			while(!giveup)
			{
				try {
					PacketPING p = new PacketPING();
					p.send(hostAddress, hostPort);
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException ignored) {
				}
			}
		}
	}
}


text:
module Spree
  module Admin
    class ProductPropertiesController < ResourceController
      belongs_to 'spree/product', :find_by => :slug
      before_action :find_properties
      before_action :setup_property, only: :index, if: -> { can?(:create, model_class) }
      before_action :setup_variant_property_rules, only: :index

      private

        def find_properties
          @properties = Spree::Property.pluck(:name)
        end

        def setup_property
          @product.product_properties.build
        end

        def setup_variant_property_rules
          @option_types = @product.variant_option_values_by_option_type
          @option_value_ids = (params[:ovi] || []).reject(&:blank?).map(&:to_i)
          @variant_property_rule = @product.find_variant_property_rule(@option_value_ids) || @product.variant_property_rules.build
          @variant_property_rule.values.build if can?(:create, Spree::VariantPropertyRuleValue)
        end
    end
  end
end


text:
import {Component, EventEmitter, HostBinding, HostListener, Input, Output} from '@angular/core';
import {SplitterType} from '../splitter.component';
import {IgxSplitterPaneComponent} from '../splitter-pane/splitter-pane.component';
import {DragDirection, IDragMoveEventArgs, IDragStartEventArgs} from '../../directives/drag-drop/drag-drop.directive';

export const SPLITTER_INTERACTION_KEYS = new Set('right down left up arrowright arrowdown arrowleft arrowup'.split(' '));

/**
 * @hidden @internal
 * Represents the draggable bar that visually separates panes and allows for changing their sizes.
 */
@Component({
    selector: 'igx-splitter-bar',
    templateUrl: './splitter-bar.component.html'
})
export class IgxSplitBarComponent {
    /**
     * Set css class to the host element.
     */
    @HostBinding('class.igx-splitter-bar-host')
    public cssClass = 'igx-splitter-bar-host';

    /**
     * Gets/Sets the orientation.
     */
    @Input()
    public type: SplitterType = SplitterType.Horizontal;

    /**
     * Sets/gets the element order.
     */
    @HostBinding('style.order')
    @Input()
    public order!: number;

    /**
     * @hidden
     * @internal
     */
    @HostBinding('attr.tabindex')
    public get tabindex() {
        return this.resizeDisallowed ? null : 0;
    }

    /**
     * @hidden
     * @internal
     */
    @HostBinding('attr.aria-orientation')
    public get orientation() {
        return this.type === SplitterType.Horizontal ? 'horizontal' : 'vertical';
    }

    /**
     * @hidden
     * @internal
     */
    public get cursor() {
        if (this.resizeDisallowed) {
            return '';
        }
        return this.type === SplitterType.Horizontal ? 'col-resize' : 'row-resize';
    }

    /**
     * Sets/gets the `SplitPaneComponent` associated with the current `SplitBarComponent`.
     *
     * @memberof SplitBarComponent
     */
    @Input()
    public pane!: IgxSplitterPaneComponent;

    /**
     * Sets/Gets the `SplitPaneComponent` sibling components associated with the current `SplitBarComponent`.
     */
    @Input()
    public siblings!: Array<IgxSplitterPaneComponent>;

    /**
     * An event that is emitted whenever we start dragging the current `SplitBarComponent`.
     */
    @Output()
    public moveStart = new EventEmitter<IgxSplitterPaneComponent>();

    /**
     * An event that is emitted while we are dragging the current `SplitBarComponent`.
     */
    @Output()
    public moving = new EventEmitter<number>();

    @Output()
    public movingEnd = new EventEmitter<number>();

    /**
     * A temporary holder for the pointer coordinates.
     */
    private startPoint!: number;

    /**
     * @hidden @internal
     */
    public get prevButtonHidden() {
        return this.siblings[0].collapsed && !this.siblings[1].collapsed;
    }

    /**
     * @hidden @internal
     */
    @HostListener('keydown', ['$event'])
    public keyEvent(event: KeyboardEvent) {
        const key = event.key.toLowerCase();
        const ctrl = event.ctrlKey;
        event.stopPropagation();
        if (SPLITTER_INTERACTION_KEYS.has(key)) {
            event.preventDefault();
        }
            switch (key) {
                case 'arrowup':
                case 'up':
                    if (this.type === SplitterType.Vertical) {
                        if (ctrl) {
                            this.onCollapsing(false);
                            break;
                        }
                        if (!this.resizeDisallowed) {
                            event.preventDefault();
                            this.moveStart.emit(this.pane);
                            this.moving.emit(10);
                        }
                    }
                    break;
                case 'arrowdown':
                case 'down':
                    if (this.type === SplitterType.Vertical) {
                        if (ctrl) {
                            this.onCollapsing(true);
                            break;
                        }
                        if (!this.resizeDisallowed) {
                            event.preventDefault();
                            this.moveStart.emit(this.pane);
                            this.moving.emit(-10);
                        }
                    }
                    break;
                case 'arrowleft':
                case 'left':
                    if (this.type === SplitterType.Horizontal) {
                        if (ctrl) {
                            this.onCollapsing(false);
                            break;
                        }
                        if (!this.resizeDisallowed) {
                            event.preventDefault();
                            this.moveStart.emit(this.pane);
                            this.moving.emit(10);
                        }
                    }
                    break;
                case 'arrowright':
                case 'right':
                    if (this.type === SplitterType.Horizontal) {
                        if (ctrl) {
                            this.onCollapsing(true);
                            break;
                        }
                        if (!this.resizeDisallowed) {
                            event.preventDefault();
                            this.moveStart.emit(this.pane);
                            this.moving.emit(-10);
                        }
                    }
                    break;
                default:
                    break;
            }
    }

    /**
     * @hidden @internal
     */
    public get dragDir() {
        return this.type === SplitterType.Horizontal ? DragDirection.VERTICAL : DragDirection.HORIZONTAL;
    }

    /**
     * @hidden @internal
     */
    public get nextButtonHidden() {
        return this.siblings[1].collapsed && !this.siblings[0].collapsed;
    }

    /**
     * @hidden @internal
     */
    public onDragStart(event: IDragStartEventArgs) {
        if (this.resizeDisallowed) {
            event.cancel = true;
            return;
        }
        this.startPoint = this.type === SplitterType.Horizontal ? event.startX : event.startY;
        this.moveStart.emit(this.pane);
    }

    /**
     * @hidden @internal
     */
    public onDragMove(event: IDragMoveEventArgs) {
        const isHorizontal = this.type === SplitterType.Horizontal;
        const curr =  isHorizontal ? event.pageX : event.pageY;
        const delta = this.startPoint - curr;
        if (delta !== 0) {
            this.moving.emit(delta);
            event.cancel = true;
            event.owner.element.nativeElement.style.transform = '';
        }
    }

    public onDragEnd(event: any) {
        const isHorizontal = this.type === SplitterType.Horizontal;
        const curr =  isHorizontal ? event.pageX : event.pageY;
        const delta = this.startPoint - curr;
        if (delta !== 0) {
            this.movingEnd.emit(delta);
        }
    }

    protected get resizeDisallowed() {
        const relatedTabs = this.siblings;
        return !!relatedTabs.find(x => x.resizable === false || x.collapsed === true);
    }

    /**
     * @hidden @internal
     */
    public onCollapsing(next: boolean) {
        const prevSibling = this.siblings[0];
        const nextSibling = this.siblings[1];
        let target;
        if (next) {
            // if next is clicked when prev pane is hidden, show prev pane, else hide next pane.
            target = prevSibling.collapsed ? prevSibling : nextSibling;
        } else {
            // if prev is clicked when next pane is hidden, show next pane, else hide prev pane.
            target = nextSibling.collapsed ? nextSibling : prevSibling;
        }
        target.toggle();
    }
}


text:
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/init-capsule.php';

use Illuminate\Database\Capsule\Manager as Capsule;

class World extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'World';
    public $timestamps = false;
}

$capsule->bootEloquent();


text:
namespace Result.Tests
{
	using System;
	using System.Threading.Tasks;
	using Jane;
	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class TaskExtensionsTests
	{
		[TestMethod]
		public void AsTask_should_return_completed_task_with_result_set()
		{
			var result = Result.Success();
			var task = result.AsTask();
			Assert.IsTrue(task.IsCompleted);
			Assert.IsTrue(Object.ReferenceEquals(result, task.Result));
		}

		[TestMethod]
		public void AsTask_T_should_return_completed_task_with_result_set()
		{
			var val = new { };
			var result = Result.Success(val);
			var task = result.AsTask();
			Assert.IsTrue(task.IsCompleted);
			Assert.IsTrue(Object.ReferenceEquals(result, task.Result));
			Assert.IsTrue(Object.ReferenceEquals(result.Value, task.Result.Value));
		}
	}
}


text:
import logging
import httplib
from socket import timeout
from threading import Thread
from time import sleep

from tweepy.models import Status
from tweepy.api import API
from tweepy.error import TweepError

from tweepy.utils import import_simplejson, urlencode_noplus
json = import_simplejson()

STREAM_VERSION = '1.1'

class StreamListener(object):

    def __init__(self, api=None):
        self.api = api or API()

    def on_connect(self):
        """Called once connected to streaming server.

        This will be invoked once a successful response
        is received from the server. Allows the listener
        to perform some work prior to entering the read loop.
        """
        pass

    def on_data(self, raw_data):
        """Called when raw data is received from connection.

        Override this method if you wish to manually handle
        the stream data. Return False to stop stream and close connection.
        """
        data = json.loads(raw_data)

        if 'in_reply_to_status_id' in data:
            status = Status.parse(self.api, data)
            if self.on_status(status) is False:
                return False
        elif 'delete' in data:
            delete = data['delete']['status']
            if self.on_delete(delete['id'], delete['user_id']) is False:
                return False
        elif 'limit' in data:
            if self.on_limit(data['limit']['track']) is False:
                return False
        elif 'disconnect' in data:
            if self.on_disconnect(data['disconnect']) is False:
                return False
        else:
            logging.error("Unknown message type: " + str(raw_data))

    def on_status(self, status):
        """Called when a new status arrives"""
        return

    def on_delete(self, status_id, user_id):
        """Called when a delete notice arrives for a status"""
        return

    def on_limit(self, track):
        """Called when a limitation notice arrvies"""
        return

    def on_error(self, status_code):
        """Called when a non-200 status code is returned"""
        return False

    def on_timeout(self):
        """Called when stream connection times out"""
        return

    def on_disconnect(self, notice):
        """Called when twitter sends a disconnect notice

        Disconnect codes are listed here:
        https://dev.twitter.com/docs/streaming-apis/messages#Disconnect_messages_disconnect
        """
        return

class Stream(object):

    host = 'stream.twitter.com'

    def __init__(self, auth, listener, **options):
        self.auth = auth
        self.listener = listener
        self.running = False
        self.timeout = options.get("timeout", 300.0)
        self.retry_count = options.get("retry_count")
        # values according to https://dev.twitter.com/docs/streaming-apis/connecting#Reconnecting
        self.retry_time_start = options.get("retry_time", 5.0)
        self.retry_420_start = options.get("retry_420", 60.0)
        self.retry_time_cap = options.get("retry_time_cap", 320.0)
        self.snooze_time_step = options.get("snooze_time", 0.25)
        self.snooze_time_cap = options.get("snooze_time_cap", 16)
        self.buffer_size = options.get("buffer_size",  1500)
        if options.get("secure", True):
            self.scheme = "https"
        else:
            self.scheme = "http"

        self.api = API()
        self.headers = options.get("headers") or {}
        self.parameters = None
        self.body = None
        self.retry_time = self.retry_time_start
        self.snooze_time = self.snooze_time_step

    def _run(self):
        # Authenticate
        url = "%s://%s%s" % (self.scheme, self.host, self.url)

        # Connect and process the stream
        error_counter = 0
        conn = None
        exception = None
        while self.running:
            if self.retry_count is not None and error_counter > self.retry_count:
                # quit if error count greater than retry count
                break
            try:
                if self.scheme == "http":
                    conn = httplib.HTTPConnection(self.host, timeout=self.timeout)
                else:
                    conn = httplib.HTTPSConnection(self.host, timeout=self.timeout)
                self.auth.apply_auth(url, 'POST', self.headers, self.parameters)
                conn.connect()
                conn.request('POST', self.url, self.body, headers=self.headers)
                resp = conn.getresponse()
                if resp.status != 200:
                    if self.listener.on_error(resp.status) is False:
                        break
                    error_counter += 1
                    if resp.status == 420:
                        self.retry_time = max(self.retry_420_start, self.retry_time)
                    sleep(self.retry_time)
                    self.retry_time = min(self.retry_time * 2, self.retry_time_cap)
                else:
                    error_counter = 0
                    self.retry_time = self.retry_time_start
                    self.snooze_time = self.snooze_time_step
                    self.listener.on_connect()
                    self._read_loop(resp)
            except timeout:
                if self.listener.on_timeout() == False:
                    break
                if self.running is False:
                    break
                conn.close()
                sleep(self.snooze_time)
                self.snooze_time = min(self.snooze_time + self.snooze_time_step,
                                       self.snooze_time_cap)
            except Exception, exception:
                # any other exception is fatal, so kill loop
                break

        # cleanup
        self.running = False
        if conn:
            conn.close()

        if exception:
            raise

    def _data(self, data):
        if self.listener.on_data(data) is False:
            self.running = False

    def _read_loop(self, resp):

        while self.running and not resp.isclosed():

            # Note: keep-alive newlines might be inserted before each length value.
            # read until we get a digit...
            c = '\n'
            while c == '\n' and self.running and not resp.isclosed():
                c = resp.read(1)
            delimited_string = c

            # read rest of delimiter length..
            d = ''
            while d != '\n' and self.running and not resp.isclosed():
                d = resp.read(1)
                delimited_string += d

            # read the next twitter status object
            if delimited_string.strip().isdigit():
                next_status_obj = resp.read( int(delimited_string) )
                self._data(next_status_obj)

        if resp.isclosed():
            self.on_closed(resp)

    def _start(self, async):
        self.running = True
        if async:
            Thread(target=self._run).start()
        else:
            self._run()

    def on_closed(self, resp):
        """ Called when the response has been closed by Twitter """
        pass

    def userstream(self, count=None, async=False, secure=True):
        self.parameters = {'delimited': 'length'}
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/2/user.json?delimited=length'
        self.host='userstream.twitter.com'
        self._start(async)

    def firehose(self, count=None, async=False):
        self.parameters = {'delimited': 'length'}
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%s/statuses/firehose.json?delimited=length' % STREAM_VERSION
        if count:
            self.url += '&count=%s' % count
        self._start(async)

    def retweet(self, async=False):
        self.parameters = {'delimited': 'length'}
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%s/statuses/retweet.json?delimited=length' % STREAM_VERSION
        self._start(async)

    def sample(self, count=None, async=False):
        self.parameters = {'delimited': 'length'}
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%s/statuses/sample.json?delimited=length' % STREAM_VERSION
        if count:
            self.url += '&count=%s' % count
        self._start(async)

    def filter(self, follow=None, track=None, async=False, locations=None,
        count = None, stall_warnings=False, languages=None):
        self.parameters = {}
        self.headers['Content-type'] = "application/x-www-form-urlencoded"
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%s/statuses/filter.json?delimited=length' % STREAM_VERSION
        if follow:
            self.parameters['follow'] = ','.join(map(str, follow))
        if track:
            self.parameters['track'] = ','.join(map(str, track))
        if locations and len(locations) > 0:
            assert len(locations) % 4 == 0
            self.parameters['locations'] = ','.join(['%.2f' % l for l in locations])
        if count:
            self.parameters['count'] = count
        if stall_warnings:
            self.parameters['stall_warnings'] = stall_warnings
        if languages:
            self.parameters['language'] = ','.join(map(str, languages))
        self.body = urlencode_noplus(self.parameters)
        self.parameters['delimited'] = 'length'
        self._start(async)

    def disconnect(self):
        if self.running is False:
            return
        self.running = False


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 300860 $ -->

<chapter xml:id="xsl.setup" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 &reftitle.setup;

 <!-- {{{ Requirements -->
 <section xml:id="xsl.requirements">
  &reftitle.required;
  &libxml.required;
  <para>
   This extension uses <productname>libxslt</productname> which can be
   found at <link xlink:href="&url.libxslt;">&url.libxslt;</link>. libxslt
   version 1.1.0 or greater is required.
  </para>
 </section>
 <!-- }}} -->

 <!-- {{{ Installation -->
 &reference.xsl.configure;
 <!-- }}} -->

 <!-- {{{ Configuration -->
 <section xml:id="xsl.configuration">
  &reftitle.runtime;
  &no.config;
 </section>
 <!-- }}} -->

 <!-- {{{ Resources -->
 <section xml:id="xsl.resources">
  &reftitle.resources;
  &no.resource;
 </section>
 <!-- }}} -->

</chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package asmilk.ascloud.domain;

import java.io.Serializable;

import asmilk.ascloud.data.cloudant.model.Document;

public class Book extends Document implements Serializable {

	private static final long serialVersionUID = 158223506149006607L;

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "{_id=" + getId() + ", _rev=" + getRevision() + "}; @" + this.getClass().getName() + " [name=" + name
				+ "]";
	}

}


text:
public abstract class DocInfo
{
    public DocInfo(String rawCommentText, SourcePositionInfo sp)
    {
        mRawCommentText = rawCommentText;
        mPosition = sp;
    }

    public boolean isHidden()
    {
        return comment().isHidden();
    }

    public boolean isDocOnly() {
        return comment().isDocOnly();
    }

    public String getRawCommentText()
    {
        return mRawCommentText;
    }

    public Comment comment()
    {
        if (mComment == null) {
            mComment = new Comment(mRawCommentText, parent(), mPosition);
        }
        return mComment;
    }

    public SourcePositionInfo position()
    {
        return mPosition;
    }

    public abstract ContainerInfo parent();

    public void setSince(String since) {
        mSince = since;
    }

    public String getSince() {
        return mSince;
    }

    private String mRawCommentText;
    Comment mComment;
    SourcePositionInfo mPosition;
    private String mSince;
}


text:
namespace System
{
    public sealed class AppDomainSetup
    {
        internal AppDomainSetup() { }
        public string? ApplicationBase => AppContext.BaseDirectory;
        public string? TargetFrameworkName => AppContext.TargetFrameworkName;
    }
}


text:
<?php
class Formadores extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
        // modelos
        $this->load->model('menu_model');
        $this->load->model('modulo_model');
        $this->load->model('formador_model');
        $this->load->model('pagina_predisenada_model');
        // bibliotecas
        $this->load->library('nested_set');

        // configuracion de menu
        $this->nested_set->setControlParams('menu','lft','rgt','id','padre_id','titulo');
    }

    public function index()
	{
       $pagina_formadores = $this->pagina_predisenada_model->get_values('metadescripcion, metapalabras_clave, id, hits, estado', array('alias'=>'formadores-score-bolivia'));
       if($pagina_formadores->estado == PUBLICADO){
           $this->pagina_predisenada_model->update(array('hits'=>$pagina_formadores->hits + 1),$pagina_formadores->id);
           $data['titulo'] = $this->lang->line('score_sitio_formadores');
           $data['metadescripcion'] = $pagina_formadores->metadescripcion;
           $data['metapalabras_clave'] = $pagina_formadores->metapalabras_clave;
           $data['menus'] = $this->nested_set->getMenuBootstrap();
    	   $data['formadores'] = $this->formador_model->get_all('',array('estado'=>PUBLICADO),'','','apellidos asc','');
           $data['mod_pie'] = $this->modulo_model->get_values('contenido',array('modulo'=>'mod_pie','estado'=>PUBLICADO));
           $data['mod_logo'] = $this->modulo_model->get_values('contenido',array('modulo'=>'mod_logotipo','estado'=>PUBLICADO));
           $this->load->view('frontend/formadores',$data);
       }elseif($pagina_formadores->estado == DESPUBLICADO){
           redirect('404_override');
       }
	}
}


text:
using System;

namespace ShadowsOfShadows.Helpers
{
    public enum Fraction
    {
        Warrior,
        Mage,
        Hunter
    }
}


text:
"""
Automated tests for probability estimation algorithms in the probability_estimation module.
"""

import logging
import unittest

from gensim.topic_coherence import probability_estimation
from gensim.corpora.hashdictionary import HashDictionary

class TestProbabilityEstimation(unittest.TestCase):
    def setUp(self):
        self.texts = [['human', 'interface', 'computer'],
                      ['eps', 'user', 'interface', 'system'],
                      ['system', 'human', 'system', 'eps'],
                      ['user', 'response', 'time'],
                      ['trees'],
                      ['graph', 'trees']]
        self.dictionary = HashDictionary(self.texts)
        # Following is the mapping:
        # {'computer': 10608,
        #  'eps': 31049,
        #  'graph': 18451,
        #  'human': 31002,
        #  'interface': 12466,
        #  'response': 5232,
        #  'system': 5798,
        #  'time': 29104,
        #  'trees': 23844,
        #  'user': 12736}
        self.corpus = [self.dictionary.doc2bow(text) for text in self.texts]
        # Suppose the segmented topics from s_one_pre are:
        self.segmented_topics = [[(5798, 18451), (10608, 18451), (10608, 5798)], [(10608, 18451), (12736, 18451), (12736, 10608)]]

    def testPBooleanDocument(self):
        """Test p_boolean_document()"""
        # Unique topic ids are 5798, 10608, 12736 and 18451
        obtained, _ = probability_estimation.p_boolean_document(self.corpus, self.segmented_topics)
        expected = {18451: set([5]), 12736: set([1, 3]), 5798: set([1, 2]), 10608: set([0])}
        self.assertTrue(obtained == expected)

    def testPBooleanSlidingWindow(self):
        """Test p_boolean_sliding_window()"""
        # Test with window size as 2. window_id is zero indexed.
        obtained, _ = probability_estimation.p_boolean_sliding_window(self.texts, self.segmented_topics, self.dictionary, 2)
        expected = {10608: set([1]), 12736: set([8, 2, 3]), 18451: set([11]), 5798: set([4, 5, 6, 7])}
        self.assertTrue(obtained == expected)

if __name__ == '__main__':
    logging.root.setLevel(logging.WARNING)
    unittest.main()


text:
import {ContentModel} from "../../../core/models/impl/ContentModel";
export class TweetContentComponent implements ng.IComponentOptions {
    public controller: any = TweetContentController;
    public template: string = `

Feed

These are the most recent tweets

{{::tweet.user}} Tweeted

{{::tweet.content}}

                        <star starred="tweet.starred" class="pull-right"></star>

    `;
}
export class TweetContentController {
    public static $inject: Array<string> = ["ContentModel"];
    constructor(public model: ContentModel) {
    }
}


text:
/* eslint import/no-extraneous-dependencies: [error, { devDependencies: true }] */
'use strict';

const express = require('express');
const xapp = require('../');

const app = module.exports = express();

// enabled X-App headers
app.use(xapp({}, require('./package')));

// normal route
app.get('/', (req, res) => {
  res.send('Hello World');
});

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000'); // eslint-disable-line no-console
}


text:
layout: page
title: iMinor dossier Frank
description: "Dossier Frank"
image:
  feature: abstract-10.jpg
  credit: dargadgetz
  creditlink: http://www.dargadgetz.com/ios-7-abstract-wallpaper-pack-for-iphone-5-and-ipod-touch-retina/
share: false
comments: false
---
Competentie vijf: analyse en ontwerpgericht onderzoek,

De educatief multimediaal ontwikkelaar kan adequaat onderzoek doen waar het gaat om de realisatie en uitvoering van het educatief multimediaal product/project.

Copyright:

Voor onze website hebben we gewerkt met het kleurenpalet van DarGadgetz. Om hiervan gebruik te maken hebben wij een mail gestuurd naar dit bedrijf om zo toestemming te vragen om gebruik te maken van de content.

Multimediaal concept:

Zoals eerder in het verslag is uitgelegd, verwacht de opdrachtgever van ons een website met daarin projecten voor zijn klassen, kleuren die passen bij het Alfa College en het vak Engels (rood, blauw, wit) en dat we werken volgens een stappenplan (introductie, opdracht, proces, etc.). Deze wensen hebben wij omgezet in de vorm van onze website en vanuit de feedback komt duidelijk naar voren dat de opdrachtgever tevreden is met het resultaat. Deze feedback kunt u vinden in de bijlagen (Evaluaties).

Analyse doelgroep:

In het hoofdstuk Competentie 3: didactische aspecten van het te ontwikkelen product heb ik beschreven wat wij hebben gedaan om te bepalen wat onze doelgroep inhoud. Als voorbeeld gaf ik daarbij een cirkeldiagram, waarin de leeftijd van de studenten onderzocht was. Verder hebben wij gekeken naar het jongen/meisjes ratio in de klassen, waarmee wij vervolgens rekening hielden met het ontwerpen van opdrachten, zodat er een prettige aansluiting is met de belevingswereld van de studenten. Door dit in het begin te onderzoeken welke doelgroep je voor je hebt, zorg je ervoor dat het product hierbij aansluit.

Tussentijdse evaluatie en eindevaluatie:

Zodra de docent bezig ging met de website, vroeg hij zijn studenten om aan het eind enquêtes in te vullen, om zo te controleren of de studenten prettig werkten aan de projecten. De uiteindelijke uitkomsten van deze enquêtes zagen positief uit. Deze zijn in de bijlages hieronder te vinden.

Geel: Overig: korter maken, niet leuk, uitleg in het Nederlands

Blauw: Alleen werken

Rood: Zo doorgaan met deze manier van werken

Conclusie:

De afgelopen periodes hebben de studenten van Administratief medewerker en Leisure gewerkt met projecten die aansluiten bij hun opleidingen. Hier hebben zij met plezier aan gewerkt en ze vonden dat de opdrachten aansloten bij de opleidingen. Uiteraard waren er ook studenten die op en aanmerkingen hadden op de opdrachten. De meest voorkomende tip was om bepaalde opdrachten korter te maken, omdat deze soms te lang duurden. Dit hebben we geverifieerd bij de docent en hij was van mening dat het voor sommige studenten, moeilijker was dan voor de anderen, maar benadrukte dat de opdrachten wel pasten bij het niveau Engels die verwacht wordt van de studenten.

Competentie vier

Competentie zes


text:
NSString *const kDateFormatShortMonthFullYearTime = @"LLL d, yyyy hh:mm a";

@implementation NSDate (CKExtension)

NSUInteger const kUnitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;

+ (NSDate *)_dateFromDate:(NSDate *)date
                      day:(NSInteger)day
                    month:(NSInteger)month
                     year:(NSInteger)year
                   addDay:(NSInteger)addDay
                 addMonth:(NSInteger)addMonth
                  addYear:(NSInteger)addYear
                normalize:(BOOL)normalize timeZone:(NSTimeZone *)timeZone {
  NSCalendar *calendar = [NSCalendar currentCalendar];
  if (timeZone) {
    [calendar setTimeZone:timeZone];
  }

  NSDateComponents *comps = [calendar components:kUnitFlags fromDate:date];
  if (normalize) {
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];
  }

  if (day != 0) [comps setDay:day];
  if (month != 0) [comps setMonth:month];
  if (year != 0) [comps setYear:year];

  if (addDay != 0) [comps setDay:([comps day] + addDay)];
  if (addMonth != 0) [comps setMonth:([comps month] + addMonth)];
  if (addYear != 0) [comps setYear:([comps year] + addYear)];

  return [calendar dateFromComponents:comps];
}

+ (NSDate *)dateFromDate:(NSDate *)date addDay:(NSInteger)addDay normalize:(BOOL)normalize {
  return [self _dateFromDate:date day:0 month:0 year:0 addDay:addDay addMonth:0 addYear:0
                   normalize:normalize timeZone:nil];
}

+ (NSDate *)dateWithDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year
               timeZone:(NSTimeZone *)timeZone {
  return [self dateWithDay:day month:month year:year addDay:0 addMonth:0 addYear:0 timeZone:timeZone];
}

+ (NSDate *)dateWithDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year
                 addDay:(NSInteger)addDay addMonth:(NSInteger)addMonth addYear:(NSInteger)addYear
               timeZone:(NSTimeZone *)timeZone {
  return [self _dateFromDate:[NSDate date] day:day month:month year:year addDay:addDay addMonth:addMonth addYear:addYear
                   normalize:YES timeZone:timeZone];

}

- (NSDateComponents *)dateComponentsFromFlags:(NSUInteger)flags timeZone:(NSTimeZone *)timeZone {
  NSCalendar *calendar = [NSCalendar currentCalendar];
  if (timeZone) {
    [calendar setTimeZone:timeZone];
  }
  return [calendar components:flags fromDate:self];
}

- (NSInteger)day {
  return [self dayForTimeZone:nil];
}

- (NSInteger)dayForTimeZone:(NSTimeZone *)timeZone {
  return [[self dateComponentsFromFlags:NSDayCalendarUnit timeZone:timeZone] day];
}

- (NSInteger)month {
  return [self monthForTimeZone:nil];
}

- (NSInteger)monthForTimeZone:(NSTimeZone *)timeZone {
  return [[self dateComponentsFromFlags:NSMonthCalendarUnit timeZone:timeZone] month];
}

- (NSInteger)year {
  return [self yearForTimeZone:nil];
}

- (NSInteger)yearForTimeZone:(NSTimeZone *)timeZone {
  return [[self dateComponentsFromFlags:NSYearCalendarUnit timeZone:timeZone] year];
}

+ (NSArray *)monthSymbols {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  NSArray *monthSymbols = [dateFormatter standaloneMonthSymbols];
  return monthSymbols;
}

- (NSDate *)addDays:(NSInteger)days {
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSDateComponents *comps = [calendar components:kUnitFlags fromDate:self];
  if (days != 0) [comps setDay:[comps day] + days];
  return [calendar dateFromComponents:comps];
}

- (NSDate *)beginningOfDay {
  return [NSDate dateFromDate:self addDay:0 normalize:YES];
}

+ (NSDate *)yesterday {
  return [NSDate dateFromDate:[NSDate date] addDay:-1 normalize:YES];
}

+ (NSDate *)tomorrow {
  return [NSDate dateFromDate:[NSDate date] addDay:1 normalize:YES];
}

- (BOOL)isTomorrow {
  return ([[self beginningOfDay] compare:[NSDate tomorrow]] == NSOrderedSame);
}

- (BOOL)isToday {
  return ([[self beginningOfDay] compare:[[NSDate date] beginningOfDay]] == NSOrderedSame);
}

- (BOOL)wasYesterday {
  return ([[self beginningOfDay] compare:[NSDate yesterday]] == NSOrderedSame);
}

- (NSString *)weekday:(NSDateFormatter *)formatter {
  if ([self isTomorrow]) return NSLocalizedString(@"Tomorrow", nil);
  else if ([self isToday]) return NSLocalizedString(@"Today", nil);
  else if ([self wasYesterday]) return NSLocalizedString(@"Yesterday", nil);

  if (!formatter) return nil;

  NSInteger weekday = [[[NSCalendar currentCalendar] components:kUnitFlags fromDate:self] weekday] - 1;
  return [[formatter weekdaySymbols] objectAtIndex:weekday];
}

- (NSString *)format:(NSString *)format useWeekday:(BOOL)useWeekday {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:format];
  NSString *formatted = [dateFormatter stringFromDate:self];
  if (useWeekday) {
    NSString *specialWeekday = [self weekday:dateFormatter];
    formatted = [NSString stringWithFormat:@"%@, %@", specialWeekday, formatted];
  }
  return formatted;
}

- (NSString *)timeAgo:(BOOL)includeSeconds {
  return [NSString stringForTimeInterval:[self timeIntervalSinceNow] includeSeconds:includeSeconds];
}

- (NSString *)timeAgoAbbreviated {
  return [NSString abbreviatedStringForTimeInterval:[self timeIntervalSinceNow]];
}

- (long long)millisSince1970 {
  NSTimeInterval secondsSince1970 = [self timeIntervalSince1970];
  return (long long)round(secondsSince1970 * 1000);
}

- (NSNumber *)millisNumberSince1970 {
  long long millis = [self millisSince1970];
  return [NSNumber numberWithLongLong:millis];
}

- (long long)secondsSince1970 {
  NSTimeInterval secondsSince1970 = [self timeIntervalSince1970];
  return (long long)round(secondsSince1970);
}

- (NSNumber *)secondsNumberSince1970 {
  long long seconds = [self secondsSince1970];
  return [NSNumber numberWithLongLong:seconds];
}

@end


text:
class CartItemRepresenter < ApplicationDecorator
  property :type, getter: ->(_) {'cart_item'}, writeable: false
  property :pricing_id, type: Representable::Coercion::Types::Params::Integer
  property :quantity, type: Representable::Coercion::Types::Params::Integer
  property :product_name, writeable: false
  property :unit_price, writeable: false, type: Representable::Coercion::Types::Params::Integer
  property :total_price, writeable: false, type: Representable::Coercion::Types::Params::Integer
end