text:
package de.stephanlindauer.criticalmaps.fragments;

import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;

import com.squareup.otto.Subscribe;

import org.osmdroid.tileprovider.modules.SqlTileWriter;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay;
import org.osmdroid.views.overlay.infowindow.InfoWindow;

import javax.inject.Inject;

import de.stephanlindauer.criticalmaps.App;
import de.stephanlindauer.criticalmaps.R;
import de.stephanlindauer.criticalmaps.databinding.FragmentMapBinding;
import de.stephanlindauer.criticalmaps.events.GpsStatusChangedEvent;
import de.stephanlindauer.criticalmaps.events.NetworkConnectivityChangedEvent;
import de.stephanlindauer.criticalmaps.events.NewLocationEvent;
import de.stephanlindauer.criticalmaps.events.NewServerResponseEvent;
import de.stephanlindauer.criticalmaps.handler.ShowGpxHandler;
import de.stephanlindauer.criticalmaps.managers.LocationUpdateManager;
import de.stephanlindauer.criticalmaps.model.OtherUsersLocationModel;
import de.stephanlindauer.criticalmaps.model.OwnLocationModel;
import de.stephanlindauer.criticalmaps.overlays.LocationMarker;
import de.stephanlindauer.criticalmaps.prefs.SharedPrefsKeys;
import de.stephanlindauer.criticalmaps.provider.EventBus;
import de.stephanlindauer.criticalmaps.utils.AlertBuilder;
import de.stephanlindauer.criticalmaps.utils.MapViewUtils;
import info.metadude.android.typedpreferences.BooleanPreference;

public class MapFragment extends Fragment {
    private final static String KEY_MAP_ZOOMLEVEL = "map_zoomlevel";
    private final static String KEY_MAP_POSITION = "map_position";
    private final static String KEY_MAP_ORIENTATION = "map_orientation";
    private final static String KEY_INITIAL_LOCATION_SET = "initial_location_set";

    private final static double DEFAULT_ZOOM_LEVEL = 12;
    private final static double NO_GPS_PERMISSION_ZOOM_LEVEL = 3;

    @Inject
    OwnLocationModel ownLocationModel;

    @Inject
    OtherUsersLocationModel otherUsersLocationModel;

    @Inject
    EventBus eventBus;

    @Inject
    LocationUpdateManager locationUpdateManager;

    @Inject
    ShowGpxHandler showGpxHandler;

    @Inject
    SharedPreferences sharedPreferences;

    private MapView mapView;
    private InfoWindow oberserverInfowWindow;

    private final GeoPoint defaultGeoPoint = new GeoPoint(52.499571, 13.4140875, 15);
    private boolean isInitialLocationSet = false;
    private ObjectAnimator gpsSearchingAnimator;

    // cache drawables
    private Drawable locationIcon;
    private Drawable ownLocationIcon;
    private Drawable ownLocationIconObserver;

    private FragmentMapBinding binding;

    private final View.OnClickListener centerLocationOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ownLocationModel.ownLocation != null)
                animateToLocation(ownLocationModel.ownLocation);
        }
    };

    private final View.OnClickListener rotationNorthOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            float currentRotation = mapView.getMapOrientation() % 360;

            if (currentRotation == 0.0f) {
                // no animation required; also works around bug where map does a full rotation
                // because of mapView wrapping 360° to 0° while View allows 360°
                return;
            }

            if (currentRotation < 0.0f) {
                currentRotation = 360.0f + currentRotation;
                binding.mapSetNorthFab.setRotation(currentRotation);
                mapView.setMapOrientation(currentRotation);
            }

            float destinationRotation = currentRotation > 180.0f ? 360.0f : 0.0f;
            ViewCompat.animate(binding.mapSetNorthFab)
                    .rotation(destinationRotation)
                    .setDuration(300L)
                    .setUpdateListener(view -> mapView.setMapOrientation(view.getRotation()))
                    .start();
        }
    };

    private final View.OnClickListener noGpsOnClickListener = v -> AlertBuilder.show(getActivity(),
            R.string.map_no_gps_title,
            R.string.map_no_gps_text);

    private final View.OnClickListener gpsDisabledOnClickListener =
            v -> AlertBuilder.show(getActivity(),
                    R.string.map_gps_disabled_title,
                    R.string.map_gps_disabled_text);

    private final View.OnClickListener gpsNoPermissionsOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            locationUpdateManager.requestPermission();
        }
    };

    private final View.OnClickListener gpsPermissionsPermanentlyDeniedOnClickListener = v ->
            new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
                    .setTitle(R.string.map_gps_permissions_permanently_denied_title)
                    .setMessage(R.string.map_gps_permissions_permanently_denied_text)
                    .setNegativeButton(R.string.no, null)
                    .setPositiveButton(R.string.permissions_open_settings, (dialog, which) -> {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                Uri.fromParts("package", getActivity().getPackageName(), null));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    })
                    .create()
                    .show();

    private final View.OnClickListener searchingForLocationOnClickListener = v ->
            Toast.makeText(getActivity(), R.string.map_searching_for_location, Toast.LENGTH_SHORT)
                    .show();

    private final SharedPreferences.OnSharedPreferenceChangeListener observerModeOnSharedPreferenceChangeListener =
            (sharedPreferences, key) -> {
                if (SharedPrefsKeys.OBSERVER_MODE_ACTIVE.equals(key)) {
                    refreshView();
                }
            };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        binding = FragmentMapBinding.inflate(inflater, container, false);

        //noinspection ConstantConditions
        locationIcon = AppCompatResources.getDrawable(getActivity(), R.drawable.ic_map_marker);
        ownLocationIcon = AppCompatResources.getDrawable(
                getActivity(), R.drawable.ic_map_marker_own);
        ownLocationIconObserver = AppCompatResources.getDrawable(
                getActivity(), R.drawable.ic_map_marker_observer);

        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(final Bundle savedState) {
        super.onActivityCreated(savedState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            adjustToWindowsInsets();
        }

        App.components().inject(this);

        binding.mapOsmNoticeText.setMovementMethod(LinkMovementMethod.getInstance());

        mapView = MapViewUtils.createMapView(getActivity());
        binding.mapContainerLayout.addView(mapView);

        oberserverInfowWindow = MapViewUtils.createObserverInfoWindow(mapView);

        binding.mapSetCenterFab.setOnClickListener(centerLocationOnClickListener);
        binding.mapSetNorthFab.setOnClickListener(rotationNorthOnClickListener);

        binding.mapNoDataConnectivityFab.setOnClickListener(v -> AlertBuilder.show(getActivity(),
                R.string.map_no_internet_connection_title,
                R.string.map_no_internet_connection_text));

        if (new BooleanPreference(sharedPreferences, SharedPrefsKeys.DISABLE_MAP_ROTATION).get()) {
            binding.mapSetNorthFab.setVisibility(View.GONE);
        } else {
            RotationGestureOverlay rotationGestureOverlay = new RotationGestureOverlay(mapView) {
                @Override
                public void onRotate(float deltaAngle) {
                    super.onRotate(deltaAngle);
                    binding.mapSetNorthFab.setRotation(mapView.getMapOrientation());
                }
            };
            rotationGestureOverlay.setEnabled(true);
            mapView.setMultiTouchControls(true);
            mapView.getOverlays().add(rotationGestureOverlay);
        }

        if (savedState != null) {
            Double zoomLevel = (Double) savedState.get(KEY_MAP_ZOOMLEVEL);
            GeoPoint position = savedState.getParcelable(KEY_MAP_POSITION);
            Float orientation = (Float) savedState.get(KEY_MAP_ORIENTATION);

            if (zoomLevel != null && position != null && orientation != null) {
                mapView.getController().setZoom(zoomLevel);
                if (!new BooleanPreference(sharedPreferences, SharedPrefsKeys.DISABLE_MAP_ROTATION)
                        .get()) {
                    mapView.setMapOrientation(orientation);
                }
                setToLocation(position);
            }

            isInitialLocationSet = savedState.getBoolean(KEY_INITIAL_LOCATION_SET, false);
        }
        binding.mapSetNorthFab.setRotation(mapView.getMapOrientation());

        showGpxHandler.showGpx(mapView);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void adjustToWindowsInsets() {
        // No-op on < API21
        ViewCompat.setOnApplyWindowInsetsListener(binding.mapOverlayContainerLayout, (v, insets) -> {
            // inset the map overlays for the status bar
            v.setPaddingRelative(
                    v.getPaddingStart(), v.getPaddingTop() + insets.getSystemWindowInsetTop(),
                    v.getPaddingEnd(), v.getPaddingBottom());

            // clear this listener so insets aren't re-applied
            ViewCompat.setOnApplyWindowInsetsListener(binding.mapOverlayContainerLayout, null);
            return insets;
        });

        // without this insets aren't reapplied on fragment changes
        ViewCompat.requestApplyInsets(binding.mapOverlayContainerLayout);
    }

    private void refreshView() {
        for (Overlay overlay : mapView.getOverlays()) {
            if (overlay instanceof LocationMarker) {
                mapView.getOverlays().remove(overlay);
            }
        }

        for (GeoPoint currentOtherUsersLocation : otherUsersLocationModel.getOtherUsersLocations()) {
            LocationMarker otherPeoplesMarker = new LocationMarker(mapView);
            otherPeoplesMarker.setPosition(currentOtherUsersLocation);
            otherPeoplesMarker.setIcon(locationIcon);
            mapView.getOverlays().add(otherPeoplesMarker);
        }

        if (ownLocationModel.ownLocation != null) {
            GeoPoint currentUserLocation = ownLocationModel.ownLocation;
            LocationMarker ownMarker = new LocationMarker(mapView);
            ownMarker.setPosition(currentUserLocation);
            if (new BooleanPreference(
                    sharedPreferences, SharedPrefsKeys.OBSERVER_MODE_ACTIVE).get()) {
                ownMarker.setIcon(ownLocationIconObserver);
                ownMarker.setInfoWindow(oberserverInfowWindow);
                // since we're currently creating new markers on every refresh, this workaround
                // is needed to update the info window's position if it's open
                if (oberserverInfowWindow.isOpen()) {
                    ownMarker.showInfoWindow();
                }
            } else {
                oberserverInfowWindow.close();
                ownMarker.setIcon(ownLocationIcon);
            }
            mapView.getOverlays().add(ownMarker);
        }

        mapView.invalidate();
    }

    @Override
    public void onResume() {
        super.onResume();
        eventBus.register(this);

        sharedPreferences.registerOnSharedPreferenceChangeListener(
                observerModeOnSharedPreferenceChangeListener);

        if (locationUpdateManager.checkPermission()) {
            locationUpdateManager.startListening();
        } else {
            zoomToLocation(defaultGeoPoint, NO_GPS_PERMISSION_ZOOM_LEVEL);
        }
    }

    private void handleFirstLocationUpdate() {
        setGpsStatusFixed();
        zoomToLocation(ownLocationModel.ownLocation, DEFAULT_ZOOM_LEVEL);
        isInitialLocationSet = true;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putDouble(KEY_MAP_ZOOMLEVEL, mapView.getZoomLevelDouble());
        outState.putParcelable(KEY_MAP_POSITION, (GeoPoint) mapView.getMapCenter());
        outState.putFloat(KEY_MAP_ORIENTATION, mapView.getMapOrientation());
        outState.putBoolean(KEY_INITIAL_LOCATION_SET, isInitialLocationSet);
    }

    @Override
    public void onPause() {
        super.onPause();
        eventBus.unregister(this);

        sharedPreferences.unregisterOnSharedPreferenceChangeListener(
                observerModeOnSharedPreferenceChangeListener);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // properly closes the cache db since it's stored in a static field in osmdroid...
        ((SqlTileWriter) mapView.getTileProvider().getTileWriter()).refreshDb();
        mapView = null;
        binding = null;
    }

    @Subscribe
    public void handleNewServerData(NewServerResponseEvent e) {
        refreshView();
    }

    @Subscribe
    public void handleNewLocation(NewLocationEvent e) {
        // if this is the first location update handle it accordingly
        if (ownLocationModel.ownLocation != null && !isInitialLocationSet) {
            handleFirstLocationUpdate();
        }

        refreshView();
    }

    @Subscribe
    public void handleNetworkConnectivityChanged(NetworkConnectivityChangedEvent e) {
        if (e.isConnected) {
            binding.mapNoDataConnectivityFab.hide();
        } else {
            binding.mapNoDataConnectivityFab.show();
        }
    }

    @Subscribe
    public void handleGpsStatusChangedEvent(GpsStatusChangedEvent e) {
        if (e.status == GpsStatusChangedEvent.Status.NONEXISTENT) {
            setGpsStatusNonexistent();
        } else if (e.status == GpsStatusChangedEvent.Status.DISABLED) {
            setGpsStatusDisabled();
        } else if (e.status == GpsStatusChangedEvent.Status.PERMISSION_PERMANENTLY_DENIED) {
            setGpsStatusPermissionsPermanentlyDenied();
        } else if (e.status == GpsStatusChangedEvent.Status.NO_PERMISSIONS) {
            setGpsStatusNoPermissions();
        } else if (e.status == GpsStatusChangedEvent.Status.LOW_ACCURACY ||
                e.status == GpsStatusChangedEvent.Status.HIGH_ACCURACY) {
            if (ownLocationModel.ownLocation != null) {
                setGpsStatusFixed();
            } else {
                setGpsStatusSearching();
            }
        }
    }

    private void setGpsStatusNonexistent() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
                noGpsOnClickListener);
    }

    private void setGpsStatusDisabled() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
                gpsDisabledOnClickListener);
    }

    private void setGpsStatusNoPermissions() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
                gpsNoPermissionsOnClickListener);
    }

    private void setGpsStatusPermissionsPermanentlyDenied() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
                gpsPermissionsPermanentlyDeniedOnClickListener);
    }

    private void setGpsStatusFixed() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.colorSecondary, R.drawable.ic_map_center_location,
                centerLocationOnClickListener);
    }

    private void setGpsStatusSearching() {
        cancelGpsSearchingAnimationIfRunning();
        setGpsStatusCommon(R.color.map_fab_searching, R.drawable.ic_map_gps_not_fixed,
                searchingForLocationOnClickListener);

        gpsSearchingAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(
                getActivity(),
                R.animator.map_gps_fab_searching_animation);
        gpsSearchingAnimator.setTarget(binding.mapSetCenterFab);
        gpsSearchingAnimator.start();
    }

    private void setGpsStatusCommon(@ColorRes int colorResId, @DrawableRes int iconResId,
                                    View.OnClickListener onClickListener) {
        //noinspection ConstantConditions
        binding.mapSetCenterFab.setBackgroundTintList(
                ContextCompat.getColorStateList(getActivity(), colorResId));
        binding.mapSetCenterFab.setImageResource(iconResId);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            binding.mapSetCenterFab.refreshDrawableState();
        }
        binding.mapSetCenterFab.setOnClickListener(onClickListener);
    }

    private void cancelGpsSearchingAnimationIfRunning() {
        if (gpsSearchingAnimator != null) {
            gpsSearchingAnimator.cancel();
            binding.mapSetCenterFab.setAlpha(1.0f);
        }
    }

    private void zoomToLocation(final GeoPoint location, final double zoomLevel) {
        // TODO use setCenter() + zoomTo() here; currently broken and ends up in a wrong location
        mapView.getController().setZoom(zoomLevel);
        animateToLocation(location);
    }

    private void animateToLocation(final GeoPoint location) {
        mapView.getController().animateTo(location);
    }

    private void setToLocation(final GeoPoint location) {
        mapView.getController().setCenter(location);
    }
}


text:
namespace suil::docker {

    json::Object Container::ps(bool all, int limit, bool size, std::string& filter)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/json");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (all)       req.args("all", "true");
            if (limit)     req.args("limit", limit);
            if (size)      req.args("size", "true");
            if (!filter.empty()) req.args("filters", filter);

            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

    json::Object Container::create(const CreateReq &config)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/create");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            req << config;
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::CREATED) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

    json::Object Container::inspect(const String id, bool size)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/json");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (size) req.args("size", "true");
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

    json::Object Container::top(const String id, const String args)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/top");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (args) req.args("ps_args", args);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

    String Container::logs(const String id, const LogsReq& args)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/logs");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (args.follow) req.args("follow",  "true");
            if (args.stdOut) req.args("stdout",   "true");
            if (args.stdErr) req.args("stderr",   "true");
            if (args.since)  req.args("since",    args.since);
            if (args.until)  req.args("until",    args.until);
            if (args.timestamps) req.args("timestamps", args.timestamps);
            if (args.tail)   req.args("tail", args.tail);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() == http::Status::SWITCHING_PROTOCOLS) {
            // switch to streaming
            ierror("Streaming API currently unsupported");
            return nullptr;
        } else if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        return resp.getbody();
    }

    json::Object Container::changes(const suil::String id)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/changes");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource());

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

    void Container::Export(const suil::String id)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/export");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource());

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    json::Object Container::stats(const suil::String id, bool stream)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/stats");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::get(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (stream) req.args("stream", true);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object obj;
        json::decode(resp(), obj);
        return obj;
    }

    void Container::resize(const suil::String id, uint32_t x, uint32_t y)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/resize");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (x) req.args("x", x);
            if (y) req.args("y", y);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    void Container::start(const suil::String id, const suil::String detachKeys)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/start");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (detachKeys) req.args("detachKeys", detachKeys);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    void Container::stop(const suil::String id, uint64_t t)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/stop");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (t) req.args("t", t);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    void Container::restart(const suil::String id, uint64_t t)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/restart");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (t) req.args("t", t);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    void Container::kill(const suil::String id, const suil::String sig)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/kill");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (sig) req.args("signal", sig);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    json::Object Container::update(const suil::String id, const UpdateReq &request)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/update");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            req << request;
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return std::move(respObj);
    }

    void Container::pause(const suil::String id)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/pause");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource());

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    void Container::unpause(const suil::String id)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/pause");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource());

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    json::Object Container::wait(const suil::String id, const suil::String condition)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/wait");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (condition) req.args("condition", condition);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return std::move(respObj);
    }

    void Container::remove(const suil::String id, const RemoveQuery &query)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/wait");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::del(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (query.v) req.args("v", "true");
            if (query.force) req.args("force", "true");
            if (query.link)  req.args("link",  "true");
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }
    }

    String Container::archiveInfo(const suil::String id, const suil::String path)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/archive");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::head(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            if (path) req.args("path", path);
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::NO_CONTENT) {
            // request failed
            Docker::reportFailure(resp);
        }

        auto tmp = resp.hdr("X-Docker-Container-Path-Stat");
        if (tmp.empty())
            return nullptr;
        else
            return String{tmp}.dup();
    }

    json::Object Container::prune(const PruneQuery &filters)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/prune");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            req.args("filters", json::encode(filters));
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::OK) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return std::move(respObj);
    }

    json::Object Container::exec(const suil::String id, const ExecCreateReq &request)
    {
        auto resource = utils::catstr(ref.apiBase, "/containers/", id, "/exec");
        itrace("requesting resource at %s", resource());
        auto resp = http::client::post(ref.httpSession, resource(), [&](http::client::Request& req) {
            // build custom request
            req << request;
            return true;
        });

        itrace("request resource status %d", resp.status());
        if (resp.status() != http::Status::CREATED) {
            // request failed
            Docker::reportFailure(resp);
        }

        json::Object respObj;
        json::decode(resp(), respObj);
        return respObj;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This code class represents a class property.
 *
 * @category   QualityAssurance
 * @package    PHP_Depend
 * @subpackage Code
 * @author     Manuel Pichler <mapi@pdepend.org>
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://pdepend.org/
 */
class PHP_Depend_Code_Property
       extends ReflectionProperty
    implements PHP_Depend_Code_NodeI
{
    /**
     * The type of this class.
     *
     * @since 0.10.0
     */
    const CLAZZ = __CLASS__;

    /**
     * The unique identifier for this function.
     *
     * @var string $_uuid
     */
    private $uuid = null;

    /**
     * The source file for this item.
     *
     * @var PHP_Depend_Code_File $_sourceFile
     */
    private $sourceFile = null;

    /**
     * The parent type object.
     *
     * @var PHP_Depend_Code_Class $_declaringClass
     */
    private $declaringClass = null;

    /**
     * The wrapped field declaration instance.
     *
     * @var PHP_Depend_Code_ASTFieldDeclaration
     * @since 0.9.6
     */
    private $fieldDeclaration = null;

    /**
     * The wrapped variable declarator instance.
     *
     * @var PHP_Depend_Code_ASTVariableDeclarator
     * @since 0.9.6
     */
    private $variableDeclarator = null;

    /**
     * Constructs a new item for the given field declaration and variable
     * declarator.
     *
     * @param PHP_Depend_Code_ASTFieldDeclaration   $fieldDeclaration   The context
     *        field declaration where this property was declared in the source.
     * @param PHP_Depend_Code_ASTVariableDeclarator $variableDeclarator The context
     *        variable declarator for this property instance.
     */
    public function __construct(
        PHP_Depend_Code_ASTFieldDeclaration $fieldDeclaration,
        PHP_Depend_Code_ASTVariableDeclarator $variableDeclarator
    ) {
        $this->fieldDeclaration   = $fieldDeclaration;
        $this->variableDeclarator = $variableDeclarator;

        $this->uuid = spl_object_hash($this);
    }

    /**
     * Returns the item name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->variableDeclarator->getImage();
    }

    /**
     * Returns a uuid for this code node.
     *
     * @return string
     */
    public function getUuid()
    {
        return $this->uuid;
    }

    /**
     * This method returns a OR combined integer of the declared modifiers for
     * this property.
     *
     * @return integer
     * @since 0.9.6
     */
    public function getModifiers()
    {
        return $this->fieldDeclaration->getModifiers();
    }

    /**
     * Returns true if this node is marked as public, otherwise the
     * returned value will be false.
     *
     * @return boolean
     */
    public function isPublic()
    {
        return $this->fieldDeclaration->isPublic();
    }

    /**
     * Returns true if this node is marked as protected, otherwise the
     * returned value will be false.
     *
     * @return boolean
     */
    public function isProtected()
    {
        return $this->fieldDeclaration->isProtected();
    }

    /**
     * Returns true if this node is marked as private, otherwise the
     * returned value will be false.
     *
     * @return boolean
     */
    public function isPrivate()
    {
        return $this->fieldDeclaration->isPrivate();
    }

    /**
     * Returns true when this node is declared as static, otherwise
     * the returned value will be false.
     *
     * @return boolean
     */
    public function isStatic()
    {
        return $this->fieldDeclaration->isStatic();
    }

    /**
     * This method will return true when this property doc comment
     * contains an array type hint, otherwise the it will return false.
     *
     * @return boolean
     * @since 0.9.6
     */
    public function isArray()
    {
        $typeNode = $this->fieldDeclaration->getFirstChildOfType(
            PHP_Depend_Code_ASTType::CLAZZ
        );
        if ($typeNode === null) {
            return false;
        }
        return $typeNode->isArray();
    }

    /**
     * This method will return true when this property doc comment
     * contains a primitive type hint, otherwise the it will return false.
     *
     * @return boolean
     * @since 0.9.6
     */
    public function isPrimitive()
    {
        $typeNode = $this->fieldDeclaration->getFirstChildOfType(
            PHP_Depend_Code_ASTType::CLAZZ
        );
        if ($typeNode === null) {
            return false;
        }
        return $typeNode->isPrimitive();
    }

    /**
     * Returns the type of this property. This method will return null
     * for all scalar type, only class properties will have a type.
     *
     * @return PHP_Depend_Code_AbstractClassOrInterface
     * @since 0.9.5
     */
    public function getClass()
    {
        $reference = $this->fieldDeclaration->getFirstChildOfType(
            PHP_Depend_Code_ASTClassOrInterfaceReference::CLAZZ
        );
        if ($reference === null) {
            return null;
        }
        return $reference->getType();
    }

    /**
     * Returns the source file for this item.
     *
     * @return PHP_Depend_Code_File
     */
    public function getSourceFile()
    {
        return $this->sourceFile;
    }

    /**
     * Sets the source file for this item.
     *
     * @param PHP_Depend_Code_File $sourceFile The item source file.
     *
     * @return void
     */
    public function setSourceFile(PHP_Depend_Code_File $sourceFile)
    {
        if ($this->sourceFile === null || $this->sourceFile->getName() === null) {
            $this->sourceFile = $sourceFile;
        }
    }

    /**
     * Returns the doc comment for this item or null.
     *
     * @return string
     */
    public function getDocComment()
    {
        return $this->fieldDeclaration->getComment();
    }

    /**
     * Returns the line number where the property declaration can be found.
     *
     * @return integer
     * @since 0.9.6
     */
    public function getStartLine()
    {
        return $this->variableDeclarator->getStartLine();
    }

    /**
     * Returns the column number where the property declaration starts.
     *
     * @return integer
     * @since 0.9.8
     */
    public function getStartColumn()
    {
        return $this->variableDeclarator->getStartColumn();
    }

    /**
     * Returns the line number where the property declaration ends.
     *
     * @return integer
     * @since 0.9.6
     */
    public function getEndLine()
    {
        return $this->variableDeclarator->getEndLine();
    }

    /**
     * Returns the column number where the property declaration ends.
     *
     * @return integer
     * @since 0.9.8
     */
    public function getEndColumn()
    {
        return $this->variableDeclarator->getEndColumn();
    }

    /**
     * This method will return the class where this property was declared.
     *
     * @return PHP_Depend_Code_AbstractClassOrInterface
     * @since 0.9.6
     */
    public function getDeclaringClass()
    {
        return $this->declaringClass;
    }

    /**
     * Sets the declaring class object.
     *
     * @param PHP_Depend_Code_Class $declaringClass The declaring class.
     *
     * @return void
     * @since 0.9.6
     */
    public function setDeclaringClass(PHP_Depend_Code_Class $declaringClass)
    {
        $this->declaringClass = $declaringClass;
    }

    /**
     * This method will return true when the parameter declaration
     * contains a default value.
     *
     * @return boolean
     * @since 0.9.6
     */
    public function isDefaultValueAvailable()
    {
        $value = $this->variableDeclarator->getValue();
        if ($value === null) {
            return false;
        }
        return $value->isValueAvailable();
    }

    /**
     * This method will return the default value for this property instance or
     * null when this property was only declared and not initialized.
     *
     * @return mixed
     * @since 0.9.6
     */
    public function getDefaultValue()
    {
        $value = $this->variableDeclarator->getValue();
        if ($value === null) {
            return null;
        }
        return $value->getValue();
    }

    /**
     * This method will return the value for this property instance on the given
     * object or null when the property has no value.
     *
     * @param stdClass $object The context object for PHP's native reflection api.
     *
     * @return mixed
     * @since 0.9.6
     * @SuppressWarnings("PMD.UnusedFormalParameter")
     */
    public function getValue($object = null)
    {
        throw new ReflectionException(__METHOD__ . '() is not supported.');
    }

    /**
     * This method is used to modifiy the property value of the given object.
     *
     * @param stdClass $object The context class where this property should set
     *                         the given value.
     * @param mixed    $value  Default value used by the native Reflection api
     *                         as new property default value.
     *
     * @return void
     * @since 0.9.6
     * @SuppressWarnings("PMD.UnusedFormalParameter")
     */
    public function setValue($object, $value = null)
    {
        throw new ReflectionException(__METHOD__ . '() is not supported.');
    }

    /**
     * This method can be used in PHP's native reflection api to allow access to
     * private or protected object property. This userland implementation will
     * always throw an exception.
     *
     * @param boolean $value Boolean true for accessible and false
     *        for a write protected property.
     *
     * @return void
     * @since 0.9.6
     * @SuppressWarnings("PMD.UnusedFormalParameter")
     */
    public function setAccessible($value)
    {
        throw new ReflectionException(__METHOD__ . '() is not supported.');
    }

    /**
     * This method will return true when the context property was
     * declared during compile time and not dynamically during runtime. In this
     * reflection implementation the default value will be always true.
     *
     * @return boolean
     * @since 0.9.6
     */
    public function isDefault()
    {
        return true;
    }

    /**
     * Visitor method for node tree traversal.
     *
     * @param PHP_Depend_VisitorI $visitor The context visitor
     *                                              implementation.
     *
     * @return void
     */
    public function accept(PHP_Depend_VisitorI $visitor)
    {
        $visitor->visitProperty($this);
    }

    /**
     * This method returns a string representation of this parameter.
     *
     * @return string
     * @since 0.9.6
     */
    public function __toString()
    {
        $default = ($this->isDefault() === true ? ' <default>' : '');
        $static  = '';

        if ($this->isStatic() === true) {
            $default = '';
            $static  = ' static';
        }

        $visibility = ' public';
        if ($this->isProtected() === true) {
            $visibility = ' protected';
        } else if ($this->isPrivate() === true) {
            $visibility = ' private';
        }

        return sprintf(
            'Property [%s%s%s %s ]%s',
            $default,
            $visibility,
            $static,
            $this->getName(),
            PHP_EOL
        );
    }

    // @codeCoverageIgnoreStart

    /**
     * This method can be called by the PHP_Depend runtime environment or a
     * utilizing component to free up memory. This methods are required for
     * PHP version < 5.3 where cyclic references can not be resolved
     * automatically by PHP's garbage collector.
     *
     * @return void
     * @since 0.9.12
     * @deprecated Since 1.0.0
     */
    public function free()
    {
        trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
    }

    // @codeCoverageIgnoreEnd
}


text:
class ChatroomsController < ApplicationController
  def index
  end

  def messages
    @messages = ChatMessage.all.order(created_at: :asc)
  end

  def giphy
    @giphy = Giphy.search(params['query'], limit: 1).first
  end
end


text:
""" Discord Bot """

import os

import praw
from discord.ext import commands
from dotenv import load_dotenv, find_dotenv

import helper

load_dotenv(find_dotenv())

REDDIT = praw.Reddit(
    client_id=os.environ.get("REDDIT_CLIENT_ID"),
    client_secret=os.environ.get("REDDIT_CLIENT_SECRET"),
    user_agent="aySH Bot")

# Verify that we are in `read_only` mode
print(REDDIT.read_only)

# Bot config
PREFIX = '!'
DESC = 'aySH'
CLIENT = commands.Bot(description=DESC, command_prefix=PREFIX)

# Make a startup command
@CLIENT.event
async def on_ready():
    print("[*]I'm in")
    print('[*] Name: {}'.format(CLIENT.user.name))

# subreddit
@CLIENT.command(pass_context=True)
async def reddit(ctx, subreddit="all", time="day"):
    await helper.top_subreddit(CLIENT, REDDIT, subreddit, time)

# random
@CLIENT.command(pass_context=True)
async def random(ctx):
    await helper.top_subreddit(CLIENT, REDDIT, 'random', 'all')

# probuild
@CLIENT.command(pass_context=True)
async def build(ctx, champion="janna"):
    await CLIENT.say('http://www.probuilds.net/champions/details/' + champion)

# counter
@CLIENT.command(pass_context=True)
async def counter(ctx, champion="janna"):
    await CLIENT.say('http://lolcounter.com/champions/' + champion)

@CLIENT.command(pass_context=True)
async def ben(ctx):
    await helper.play(CLIENT, await helper.get_user_voice_channel(ctx),
                      'sound/ben.mp3')

@CLIENT.command(pass_context=True)
async def yt(ctx, link, volumue = 5):
    await helper.play_youtube(CLIENT, await helper.get_user_voice_channel(ctx),
                              link, volume)

CLIENT.run(os.environ.get("DISCORD_CLIENT_TOKEN"))


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**notificationRequestItem** | [**NotificationRequestItemDetails**](NotificationRequestItemDetails.md) |  | [optional]


text:
package com.taobao.android.dx.util;

/**
 * Utilities for parsing hexadecimal text.
 */
public final class HexParser {
    /**
     * This class is uninstantiable.
     */
    private HexParser() {
        // This space intentionally left blank.
    }

    /**
     * Parses the given text as hex, returning a {@code byte[]}
     * corresponding to the text. The format is simple: Each line may
     * start with a hex offset followed by a colon (which is verified
     * and presumably used just as a comment), and then consists of
     * hex digits freely interspersed with whitespace. If a pound sign
     * is encountered, it and the rest of the line are ignored as a
     * comment. If a double quote is encountered, then the ASCII value
     * of the subsequent characters is used, until the next double
     * quote. Quoted strings may not span multiple lines.
     *
     * @param src {@code non-null;} the source string
     * @return {@code non-null;} the parsed form
     */
    public static byte[] parse(String src) {
        int len = src.length();
        byte[] result = new byte[len / 2];
        int at = 0;
        int outAt = 0;

        while (at < len) {
            int nlAt = src.indexOf('\n', at);
            if (nlAt < 0) {
                nlAt = len;
            }
            int poundAt = src.indexOf('#', at);

            String line;
            if ((poundAt >= 0) && (poundAt < nlAt)) {
                line = src.substring(at, poundAt);
            } else {
                line = src.substring(at, nlAt);
            }
            at = nlAt + 1;

            int colonAt = line.indexOf(':');

            atCheck:
            if (colonAt != -1) {
                int quoteAt = line.indexOf('\"');
                if ((quoteAt != -1) && (quoteAt < colonAt)) {
                    break atCheck;
                }

                String atStr = line.substring(0, colonAt).trim();
                line = line.substring(colonAt + 1);
                int alleged = Integer.parseInt(atStr, 16);
                if (alleged != outAt) {
                    throw new RuntimeException("bogus offset marker: " +
                                               atStr);
                }
            }

            int lineLen = line.length();
            int value = -1;
            boolean quoteMode = false;

            for (int i = 0; i < lineLen; i++) {
                char c = line.charAt(i);

                if (quoteMode) {
                    if (c == '\"') {
                        quoteMode = false;
                    } else {
                        result[outAt] = (byte) c;
                        outAt++;
                    }
                    continue;
                }

                if (c <= ' ') {
                    continue;
                }
                if (c == '\"') {
                    if (value != -1) {
                        throw new RuntimeException("spare digit around " +
                                                   "offset " + Hex.u4(outAt));
                    }
                    quoteMode = true;
                    continue;
                }

                int digVal = Character.digit(c, 16);
                if (digVal == -1) {
                    throw new RuntimeException("bogus digit character: \"" +
                                               c + "\"");
                }
                if (value == -1) {
                    value = digVal;
                } else {
                    result[outAt] = (byte) ((value << 4) | digVal);
                    outAt++;
                    value = -1;
                }
            }

            if (value != -1) {
                throw new RuntimeException("spare digit around offset " +
                                           Hex.u4(outAt));
            }

            if (quoteMode) {
                throw new RuntimeException("unterminated quote around " +
                                           "offset " + Hex.u4(outAt));
            }
        }

        if (outAt < result.length) {
            byte[] newr = new byte[outAt];
            System.arraycopy(result, 0, newr, 0, outAt);
            result = newr;
        }

        return result;
    }
}


text:
package org.optaplanner.core.impl.exhaustivesearch.node.bounder;

import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
import org.optaplanner.core.impl.score.director.InnerScoreDirectorFactory;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.core.impl.score.trend.InitializingScoreTrend;

public class TrendBasedScoreBounder implements ScoreBounder {

    protected final ScoreDefinition scoreDefinition;
    protected final InitializingScoreTrend initializingScoreTrend;

    public TrendBasedScoreBounder(InnerScoreDirectorFactory scoreDirectorFactory) {
        scoreDefinition = scoreDirectorFactory.getScoreDefinition();
        initializingScoreTrend = scoreDirectorFactory.getInitializingScoreTrend();
    }

    @Override
    public Score calculateOptimisticBound(ScoreDirector scoreDirector, Score score) {
        return scoreDefinition.buildOptimisticBound(initializingScoreTrend, score);
    }

    @Override
    public Score calculatePessimisticBound(ScoreDirector scoreDirector, Score score) {
        return scoreDefinition.buildPessimisticBound(initializingScoreTrend, score);
    }

}


text:
<!doctype html>

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

		<meta charset="UTF-8" />

		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">

		<title>Think Like Zuck - Traditionist Traditionist</title>

		<link rel="stylesheet" href="../../app/themes/trad/style-v=.css">

		<link rel="pingback" href="../../xmlrpc.php.html" />

		<link href="http://fonts.googleapis.com/css?family=Montserrat+Alternates:400,700" rel="stylesheet" type="text/css">
		<link href="http://fonts.googleapis.com/css?family=Lato:300,400'%20rel='stylesheet" type='text/css'>
		<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300" rel='stylesheet' type='text/css'>

		<link rel="shortcut icon" href="../../app/uploads/2013/02/fav3.png">

		<link rel="apple-touch-icon-precomposed" href="../../app/uploads/2013/02/touch.png">

<link rel="canonical" href="index.html" />
<meta property='og:locale' content='en_US'/>
<meta property='og:type' content='article'/>
<meta property='og:title' content='Think Like Zuck - Traditionist'/>
<meta property='og:description' content='Think Like Zuck We were thrilled to have the opportunity to design and develop this highly focused website for Think Like Zuck. We worked directly with the author, Ekaterina Walter to harness the power of her message, and deliver a web presence that utilized the principles of the book, and by doing so, made it a [...]'/>
<meta property='og:url' content='http://traditionist.com/portfolio/little-bird/'/>
<meta property='og:site_name' content='Traditionist'/>
<meta property='og:image' content='http://traditionist.com/app/uploads/2013/01/tlz-743x1024.png'/>

<meta name="generator" content="WordPress 3.5.2" />

Traditionist

Portfolio /

Think Like Zuck

Think Like Zuck

We were thrilled to have the opportunity to design and develop this highly focused website for Think Like Zuck.

We worked directly with the author, Ekaterina Walter to harness the power of her message, and deliver a web presence that utilized the principles of the book, and by doing so, made it a New York Times and Wall Street Journal bestseller.

PASSION—Keep your energy and commitment fully charged at all times by pursuing something you believe in

PURPOSE—Don't just create a great product; drive a meaningful movement

PEOPLE—Build powerful teams that can execute your vision

PRODUCT—Create a product that is innovative, that breaks all the rules, that changes everything

PARTNERSHIPS—Build powerful partnerships with people who fuel imagination and energize execution

For additional details, or information on our custom e-commerce solutions, please contact us.

 You might be also interested in..

Ray Kurzweil

Seniors Helping Seniors

			© 2013 Traditionist.


text:
(function (angular) {
    angular.module("gameOfLife").controller("gameOfLifeController", Controller)
    function Controller($scope, $http, config) {
        var loadConfig = function (config) {
            $scope.config = config
            $scope.loadGame = loadGame
            $scope.startGame = startGame
            $scope.stopGame = stopGame
            loadGame(config.columns, config.rows)
        }
        var loadGame = function (columns, rows) {
            var cells = []
            for (var y = 0; y < rows; y++) {
                cells[y] = []
                for (var x = 0; x < columns; x++) {
                    cells[y][x] = {y: y, x: x, alive: false}
                }
            }
            $scope.cells = cells;
        }
        var startGame = function (cells, config, firstCall) {
            if ((config.running || firstCall) && config.steps > 0) {
                $http.put("/api/v1/game-of-life", cells).success(function (data) {
                    cells = data
                    $scope.cells = cells
                    config.gameStarted = config.steps > 1 && (config.gameStarted || firstCall)
                    config.running = config.steps > 1 && (config.running || firstCall)
                    config.steps--
                    $scope.config = config
                    setTimeout(function () {
                        startGame(cells, config, false)
                    }, config.ms)
                }).error(function () {
                    stopGame(config)
                })
            }
        }
        var stopGame = function (config) {
            config.gameStarted = false
            config.running = false
            $scope.config = config
        }
        loadConfig(config)
    }
})(angular)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2016-2022 52°North Spatial Information Research GmbH

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<wps:GetCapabilities
  xmlns:ows="http://www.opengis.net/ows/2.0"
  xmlns:wps="http://www.opengis.net/wps/2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.opengis.net/wps/2.0 http://schemas.opengis.net/wps/2.0/wps.xsd ">
</wps:GetCapabilities>


text:
Legion-Cache is an example program and test bed for the
[Legion](https://github.com/taphu/legion) framework.

It implements a replicated, in-memeory, distributed key/value store. It
is still very much experimental (as is the Legion framework) and is not
suitable for production use at this time.

## Getting started

The easiest way to get started is to configure two nodes and run them locally.
The configuration for node 1 might look like this:

    port: 8010
    adminPort: 8011
    adminHost: "*"

    logging:
        level: DEBUG

    peerAddr: ipv4:localhost:8012
    joinAddr: ipv4:localhost:8013

    ekgPort: 8014

The configuration for node 2 might look like this:

    port: 8020
    adminPort: 8021
    adminHost: "*"

    logging:
        level: DEBUG

    peerAddr: ipv4:localhost:8022
    joinAddr: ipv4:localhost:8023

    ekgPort: 8024

To start up the first node, run:

    $ stack build && stack exec legion-cache -- -c <config-file-1>

The default behavior when starting up is to create a new cluster, which is what
this command will do.

To start up the second node, run:

    $ stack build && stack exec legion-cache -- -c <config-file-2> -j ipv4:localhost:8013

The `-j` option tells legion-cache to try and join an existing Legion cluster.

Now you should have two nodes running, one on port 8010, and one on port 8020.

## Usage example

Try to store a new cache value by sending a PUT request to the first nodes:

    $ curl -v -X PUT \
        -H 'Content-Type: text/plain' \
        -d 'foo' \
        http://localhost:8010/cache/0

Try to retrieve the cache value you just stored from the second node:

    $ curl -v http://localhost:8020/cache/0


text:
import futurist
import testtools

from taskflow.engines.action_engine import engine
from taskflow.engines.action_engine import executor
from taskflow.patterns import linear_flow as lf
from taskflow.persistence import backends
from taskflow import test
from taskflow.tests import utils
from taskflow.utils import eventlet_utils as eu
from taskflow.utils import persistence_utils as pu

class ParallelCreationTest(test.TestCase):
    @staticmethod
    def _create_engine(**kwargs):
        flow = lf.Flow('test-flow').add(utils.DummyTask())
        backend = backends.fetch({'connection': 'memory'})
        flow_detail = pu.create_flow_detail(flow, backend=backend)
        options = kwargs.copy()
        return engine.ParallelActionEngine(flow, flow_detail,
                                           backend, options)

    def test_thread_string_creation(self):
        for s in ['threads', 'threaded', 'thread']:
            eng = self._create_engine(executor=s)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelThreadTaskExecutor)

    def test_process_string_creation(self):
        for s in ['process', 'processes']:
            eng = self._create_engine(executor=s)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelProcessTaskExecutor)

    def test_thread_executor_creation(self):
        with futurist.ThreadPoolExecutor(1) as e:
            eng = self._create_engine(executor=e)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelThreadTaskExecutor)

    def test_process_executor_creation(self):
        with futurist.ProcessPoolExecutor(1) as e:
            eng = self._create_engine(executor=e)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelProcessTaskExecutor)

    @testtools.skipIf(not eu.EVENTLET_AVAILABLE, 'eventlet is not available')
    def test_green_executor_creation(self):
        with futurist.GreenThreadPoolExecutor(1) as e:
            eng = self._create_engine(executor=e)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelThreadTaskExecutor)

    def test_sync_executor_creation(self):
        with futurist.SynchronousExecutor() as e:
            eng = self._create_engine(executor=e)
            self.assertIsInstance(eng._task_executor,
                                  executor.ParallelThreadTaskExecutor)

    def test_invalid_creation(self):
        self.assertRaises(ValueError, self._create_engine, executor='crap')
        self.assertRaises(TypeError, self._create_engine, executor=2)
        self.assertRaises(TypeError, self._create_engine, executor=object())


text:
module MeshiyasApiHelper
end


text:
namespace blink {

WebGLCompressedTextureS3TCsRGB::WebGLCompressedTextureS3TCsRGB(
    WebGLRenderingContextBase* context)
    : WebGLExtension(context) {
  context->ExtensionsUtil()->EnsureExtensionEnabled(
      "GL_EXT_texture_compression_s3tc_srgb");

  // TODO(kainino): update these with _EXT versions once
  // GL_EXT_compressed_texture_s3tc_srgb is ratified
  context->AddCompressedTextureFormat(GL_COMPRESSED_SRGB_S3TC_DXT1_NV);
  context->AddCompressedTextureFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV);
  context->AddCompressedTextureFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV);
  context->AddCompressedTextureFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV);
}

WebGLExtensionName WebGLCompressedTextureS3TCsRGB::GetName() const {
  return kWebGLCompressedTextureS3TCsRGBName;
}

bool WebGLCompressedTextureS3TCsRGB::Supported(
    WebGLRenderingContextBase* context) {
  Extensions3DUtil* extensions_util = context->ExtensionsUtil();
  return extensions_util->SupportsExtension(
      "GL_EXT_texture_compression_s3tc_srgb");
}

const char* WebGLCompressedTextureS3TCsRGB::ExtensionName() {
  return "WEBGL_compressed_texture_s3tc_srgb";
}

}  // namespace blink


text:
using BadgerJaus.Util;

namespace BadgerJaus.Messages.LocalPoseSensor
{
    public class ReportLocalPose : QueryLocalPose
    {
        JausUnsignedInteger x;
        JausUnsignedInteger y;
        JausUnsignedInteger z;
        JausUnsignedInteger positionRMS;

        JausUnsignedShort roll;
        JausUnsignedShort pitch;
        JausUnsignedShort yaw;
        JausUnsignedShort attitudeRMS;

        JausTimeStamp timeStamp;

        public const int X_BIT = 0;
        public const int Y_BIT = 1;
        public const int Z_BIT = 2;
        public const int P_RMS = 3;
        public const int ROLL_BIT = 4;
        public const int PITCH_BIT = 5;
        public const int YAW_BIT = 6;
        public const int A_RMS = 7;
        public const int TS_BIT = 8;

        private const int POSE_MIN = -100000;
        private const int POSE_MAX = 100000;

        private const double ORIENT_MIN = -System.Math.PI;
        private const double ORIENT_MAX = System.Math.PI;

        protected override int CommandCode
        {
            get { return JausCommandCode.REPORT_LOCAL_POSE; }
        }

        protected override void InitFieldData()
        {
            base.InitFieldData();
            x = new JausUnsignedInteger();
            y = new JausUnsignedInteger();
            z = new JausUnsignedInteger();
            positionRMS = new JausUnsignedInteger();
            roll = new JausUnsignedShort();
            pitch = new JausUnsignedShort();
            yaw = new JausUnsignedShort();
            attitudeRMS = new JausUnsignedShort();
            timeStamp = new JausTimeStamp();
        }

        public void SetX(double xValue)
        {
            x.SetValueFromDouble(xValue, POSE_MIN, POSE_MAX);
            presence.setBit(X_BIT);
        }

        public void SetY(double yValue)
        {
            y.SetValueFromDouble(yValue, POSE_MIN, POSE_MAX);
            presence.setBit(Y_BIT);
        }

        public void SetZ(double zValue)
        {
            z.SetValueFromDouble(zValue, POSE_MIN, POSE_MAX);
            presence.setBit(Z_BIT);
        }

        public void SetRoll(double rollValue)
        {
            roll.SetValueFromDouble(rollValue, ORIENT_MIN, ORIENT_MAX);
            presence.setBit(ROLL_BIT);
        }

        public void SetPitch(double pitchValue)
        {
            pitch.SetValueFromDouble(pitchValue, ORIENT_MIN, ORIENT_MAX);
            presence.setBit(PITCH_BIT);
        }

        public void SetYaw(double yawValue)
        {
            yaw.SetValueFromDouble(yawValue, ORIENT_MIN, ORIENT_MAX);
            presence.setBit(YAW_BIT);
        }

        public void SetTimestamp(int timeValue)
        {
            //timeStamp.setValue(timeValue);
            presence.setBit(TS_BIT);
        }

        public double GetX()
        {
            return x.ScaleValueToDouble(POSE_MIN, POSE_MAX);
        }

        public double GetY()
        {
            return y.ScaleValueToDouble(POSE_MIN, POSE_MAX);
        }

        public double GetZ()
        {
            return z.ScaleValueToDouble(POSE_MIN, POSE_MAX);
        }

        public double GetRoll()
        {
            return roll.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
        }

        public double GetPitch()
        {
            return pitch.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
        }

        public double GetYaw()
        {
            return yaw.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
        }

        public override int GetPayloadSize()
        {
            int payloadSize = 0;
            payloadSize += base.GetPayloadSize();

            if (presence.IsBitSet(X_BIT))
                payloadSize += JausBaseType.INT_BYTE_SIZE;

            if (presence.IsBitSet(Y_BIT))
                payloadSize += JausBaseType.INT_BYTE_SIZE;

            if (presence.IsBitSet(Z_BIT))
                payloadSize += JausBaseType.INT_BYTE_SIZE;

            if (presence.IsBitSet(YAW_BIT))
                payloadSize += JausBaseType.SHORT_BYTE_SIZE;

            if (presence.IsBitSet(TS_BIT))
                payloadSize += JausBaseType.INT_BYTE_SIZE;

            return payloadSize;
        }

        protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
        {
            bool status;

            status = base.PayloadToJausBuffer(buffer, index, out indexOffset);
            if (!status)
                return false;

            if (presence.IsBitSet(X_BIT))
            {
                if (!x.Serialize(buffer, indexOffset, out indexOffset))
                    return false;
            }

            if (presence.IsBitSet(Y_BIT))
            {
                if (!y.Serialize(buffer, indexOffset, out indexOffset))
                    return false;
            }

            if (presence.IsBitSet(Z_BIT))
            {
                if (!z.Serialize(buffer, indexOffset, out indexOffset))
                    return false;
            }

            if (presence.IsBitSet(YAW_BIT))
            {
                if (!y.Serialize(buffer, indexOffset, out indexOffset))
                    return false;
            }

            if (presence.IsBitSet(TS_BIT))
            {
                if (!timeStamp.Serialize(buffer, indexOffset, out indexOffset))
                    return false;
            }

            return true;
        }

        protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
        {
            base.SetPayloadFromJausBuffer(buffer, index, out indexOffset);

            if (presence.IsBitSet(X_BIT))
            {
                x.Deserialize(buffer, indexOffset, out indexOffset);
            }

            if (presence.IsBitSet(Y_BIT))
            {
                y.Deserialize(buffer, indexOffset, out indexOffset);
            }

            if (presence.IsBitSet(Z_BIT))
            {
                z.Deserialize(buffer, indexOffset, out indexOffset);
            }

            if (presence.IsBitSet(YAW_BIT))
            {
                yaw.Deserialize(buffer, indexOffset, out indexOffset);
            }

            if (presence.IsBitSet(TS_BIT))
            {
                timeStamp.Deserialize(buffer, indexOffset, out indexOffset);
            }

            return true;
        }

        public void SetToCurrentTime()
        {
            presence.setBit(TS_BIT);
            timeStamp.setToCurrentTime();
        }
    }
}


text:
module.exports = UIElement;

function UIElement() {
  if (!(this instanceof UIElement)){
    return new UIElement();
  }

  this._children = null;
  this._parent = null;
}

UIElement.prototype.render = function () {
  if (this._children) {
    this._children.forEach(renderChild);
  }
};

UIElement.prototype.appendChild = function (child, visualParent) {
  (this._children || (this._children = [])).push(child);
  child._setParent(this);
  child._appendToDom(visualParent || this._dom);
};

UIElement.prototype.removeChild = function (child) {
  if (this._children) {
    // whelps O(n). TODO: Need to be faster!
    var idx = this._children.indexOf(child);
    if (idx >= 0) {
      this._children.splice(idx, 1);
    }
  }
  child._dispose();
  if (child._dom && this._dom) {
    this._dom.removeChild(child._dom);
  }
};

UIElement.prototype.dataContext = function (context) {
  this._dataContext = context;
};

UIElement.prototype.getOwnerDocument = function () {
  return this._ownerDocument;
};

UIElement.prototype.getVisual = function () {
  return this._dom;
};

UIElement.prototype.markup = function (markup) {
  this._markup = markup;
};

UIElement.prototype.createElement = function (name) {
  return document.createElementNS('http://www.w3.org/2000/svg', name);
};

UIElement.prototype._setParent = function (parent) {
  this._parent = parent;
  this._ownerDocument = parent._ownerDocument;
  this._inheritDataContext();
};

UIElement.prototype._appendToDom = function (dom) {
  if (this._dom) {
    dom.appendChild(this._dom);
  }
};

UIElement.prototype._dispose = function () {
  // we need to let each child deallocate resource
  // todo: bindings tracking/registration should not happen here
  if (this._bindings) { this._bindings.forEach(disposeBinding); }
  if (this._children) {
    this._children.forEach(disposeChild);
  }
};

UIElement.prototype._registerBinding = function (binding) {
  (this._bindings || (this._bindings = [])).push(binding);
};

UIElement.prototype._inheritDataContext = function () {
  if (!this._dataContext && this._parent) {
    // is this good enough, or there is a better way?
    this._dataContext = this._parent._dataContext;
  }
};

function renderChild(child) {
  child.render();
}

function disposeChild(child) {
  child._dispose();
}

function disposeBinding(binding) {
  binding.off(); // todo: this is not right, since it will kill all notifications
}


text:
<?php

namespace Scrutinizer\PhpAnalyzer\PhpParser\Type;

class StringType extends PhpType
{
    public function visit(VisitorInterface $v)
    {
        return $v->visitStringType();
    }

    public function isStringType()
    {
        return true;
    }

    public function testForEquality(PhpType $that)
    {
        $rs = parent::testForEquality($that);

        if (null !== $rs) {
            return $rs;
        }

        if ($that->isUnknownType()
                || $that->isResourceType()
                || $that->isSubTypeOf($this->registry->getNativeType('object_number_string_boolean'))) {
            return TernaryValue::get('unknown');
        }

        return TernaryValue::get('false');
    }

    public function isSubTypeOf(PhpType $type)
    {
        if (parent::isSubTypeOf($type)) {
            return true;
        }

        if ($type->isCallableType()) {
            return true;
        }

        return false;
    }

    public function getDisplayName()
    {
        return 'string';
    }

    public function getPossibleOutcomesComparedToBoolean()
    {
        return array(true, false);
    }
}


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

namespace SpecificationPatternExample.Specifications
{
    public class AndSpecification<T> : CompositeSpecification<T>
    {
        ISpecification<T> leftSpecification;
        ISpecification<T> rightSpecification;

        public AndSpecification(ISpecification<T> left, ISpecification<T> right)
        {
            this.leftSpecification = left;
            this.rightSpecification = right;
        }

        public override bool IsSatisfiedBy(T o)
        {
            return this.leftSpecification.IsSatisfiedBy(o)
                && this.rightSpecification.IsSatisfiedBy(o);
        }
    }

}


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

require APPPATH.'/libraries/API_Base.php';

class Article extends API_Base {

  public function __construct() {
    parent::__construct();
    $this->load->model('Article', 'articles_model', TRUE);
  }

  public function index_get() {

    $this->response($this->authors_model->getAll());
  }

  public function index_post() {
    $this->restrict();

    $created = $this->authors_model->create($this->post());
    if ($created) {
      if(!$this->input->is_ajax_request()) {
        redirect('/authors' . '/'. $created['id']);
      } else {
        $this->response($created);
      }

    } else {
      $this->response((object)array('status' => FALSE, 'message' => 'Database insert failed'), 500);
    }

  }

  public function author_get($id) {
    log_message('info', 'Searching author with id ' . $id);
    $author = $this->authors_model->get($id);
    $this->response($author);
  }

  public function author_put($id) {
    $this->restrict();

    log_message('info', 'Updating author with id ' . $id);
    $data = array(
      'id'          =>  $id,
      'name'       =>  $this->put('name'),
    );
    $book = $this->authors_model->update($id, $data);
  }

  public function author_delete($id) {
    $this->restrict();

    log_message('info', 'Deleting author with id ' . $id);
    $result = $this->authors_model->delete($id);
    if($result) {
      log_message('info', 'Author with id ' . $id . ' deleted');
      $this->response((object)array('status' => FALSE, 'id' => $id), 200);
    } else {
      log_message('error', 'Author with id ' . $id . ' could not be deleted');
      $this->response((object)array('status' => FALSE, 'message' => 'Could not delete author with id ' . $id), 500);
    }

  }
}


text:
import { makeHtmlAttributes } from '@rollup/plugin-html';
import { generateCss, generateJs } from 'rollup-plugin-legacy-bundle';
import fs from 'fs';

const globalCSS = fs.readFileSync('./public/global.css', 'utf8');

function includeGA(id) {
  if (!id) {
    return '';
  }

  return `
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-19088556-6"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${id}');
    </script>
  `.trim();
}

export default options => ({ attributes, files, publicPath, title }) => `
<!DOCTYPE html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
  <!-- Start Single Page Apps for GitHub Pages -->
  <script>!function(i){if(i.search){var a={};i.search.slice(1).split("&").forEach(function(i){var l=i.split("=");a[l[0]]=l.slice(1).join("=").replace(/~and~/g,"&")}),void 0!==a.p&&window.history.replaceState(null,null,i.pathname.slice(0,-1)+(a.p||"")+(a.q?"?"+a.q:"")+i.hash)}}(window.location);</script>
  <!-- End Single Page Apps for GitHub Pages -->
  ${includeGA(options.analyticsId)}
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>${title}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">

  <link rel="apple-touch-icon" sizes="180x180" href="${publicPath}app-icons/apple-touch-icon.png">
  <link rel="icon" href="${publicPath}app-icons/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="${publicPath}app-icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="${publicPath}app-icons/favicon-16x16.png">
  <link rel="manifest" href="${publicPath}manifest.json">
  <link rel="mask-icon" href="${publicPath}app-icons/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="theme-color" content="#ffffff">
  <meta name="keywords" content="roles management, permissions, permission management, ACL, ABAC, RBAC, CASL, javascript" />
  <meta name="description" content="CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries." />
  <meta property="og:title" content="CASL. Isomorphic Authorization JavaScript library" />
  <meta property="og:description" content="CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries." />
  <meta property="og:image" content="${publicPath}app-icons/android-chrome-256x256.png" />
  <style>${
  globalCSS
    .replace(/~@\//g, publicPath)
    .replace(/[\n\r]+ */g, '')
    .replace(/([:;,]) +/, '$1')
}</style>
  ${generateCss(files.css, { publicPath, attrs: attributes.link })}
</head>
<body>
  <casl-docs></casl-docs>

  <script src="${publicPath}@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
  <script src="${publicPath}@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
  ${generateJs(files.js, { publicPath, attrs: attributes.script, includeSafariFix: true })}
  ${options.sharethis ? `<script async src="${options.sharethis}"></script>` : ''}
</body>
</html>
`.trim();


text:
package com.yourcompany.np2;
import org.libsdl.app.SDLActivity;
/*
 * A sample wrapper class that just calls SDLActivity
 */
public class Np2Activity extends SDLActivity
{
}


text:
package org.apache.activemq.artemis.jndi;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NotContextException;
import javax.naming.OperationNotSupportedException;
import javax.naming.Reference;
import javax.naming.spi.NamingManager;

import org.apache.activemq.artemis.core.client.ActiveMQClientLogger;

/**
 * A read-only Context
 *

 * This version assumes it and all its subcontext are
 * read-only and any attempt to modify (e.g. through bind) will result in an
 * OperationNotSupportedException. Each Context in the tree builds a cache of
 * the entries in all sub-contexts to optimise the performance of lookup.
 *

 *

 * This implementation is intended to optimise the performance of lookup(String)
 * to about the level of a HashMap get. It has been observed that the scheme
 * resolution phase performed by the JVM takes considerably longer, so for
 * optimum performance lookups should be coded like:
 *

 *
 * Context componentContext = (Context)new InitialContext().lookup("java:comp");
 * String envEntry = (String) componentContext.lookup("env/myEntry");
 * String envEntry2 = (String) componentContext.lookup("env/myEntry2");
 *
 */
@SuppressWarnings("unchecked")
public class ReadOnlyContext implements Context, Serializable {

   public static final String SEPARATOR = "/";
   protected static final NameParser NAME_PARSER = new NameParserImpl();
   private static final long serialVersionUID = -5754338187296859149L;

   protected final Hashtable<String, Object> environment; // environment for this context
   protected final Map<String, Object> bindings; // bindings at my level
   protected final Map<String, Object> treeBindings; // all bindings under me

   private boolean frozen;
   private String nameInNamespace = "";

   public ReadOnlyContext() {
      environment = new Hashtable<>();
      bindings = new HashMap<>();
      treeBindings = new HashMap<>();
   }

   public ReadOnlyContext(Hashtable env) {
      if (env == null) {
         this.environment = new Hashtable<>();
      }
      else {
         this.environment = new Hashtable<>(env);
      }
      this.bindings = Collections.EMPTY_MAP;
      this.treeBindings = Collections.EMPTY_MAP;
   }

   public ReadOnlyContext(Hashtable environment, Map<String, Object> bindings) {
      if (environment == null) {
         this.environment = new Hashtable<>();
      }
      else {
         this.environment = new Hashtable<>(environment);
      }
      this.bindings = new HashMap<>();
      treeBindings = new HashMap<>();
      if (bindings != null) {
         for (Map.Entry<String, Object> binding : bindings.entrySet()) {
            try {
               internalBind(binding.getKey(), binding.getValue());
            }
            catch (Throwable e) {
               ActiveMQClientLogger.LOGGER.error("Failed to bind " + binding.getKey() + "=" + binding.getValue(), e);
            }
         }
      }
      frozen = true;
   }

   public ReadOnlyContext(Hashtable environment, Map<String, Object> bindings, String nameInNamespace) {
      this(environment, bindings);
      this.nameInNamespace = nameInNamespace;
   }

   protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) {
      this.bindings = clone.bindings;
      this.treeBindings = clone.treeBindings;
      this.environment = new Hashtable<>(env);
   }

   protected ReadOnlyContext(ReadOnlyContext clone, Hashtable<String, Object> env, String nameInNamespace) {
      this(clone, env);
      this.nameInNamespace = nameInNamespace;
   }

   public void freeze() {
      frozen = true;
   }

   boolean isFrozen() {
      return frozen;
   }

   /**
    * internalBind is intended for use only during setup or possibly by
    * suitably synchronized superclasses. It binds every possible lookup into a
    * map in each context. To do this, each context strips off one name segment
    * and if necessary creates a new context for it. Then it asks that context
    * to bind the remaining name. It returns a map containing all the bindings
    * from the next context, plus the context it just created (if it in fact
    * created it). (the names are suitably extended by the segment originally
    * lopped off).
    *
    * @param name
    * @param value
    * @return
    * @throws javax.naming.NamingException
    */
   protected Map<String, Object> internalBind(String name, Object value) throws NamingException {
      assert name != null && name.length() > 0;
      assert !frozen;

      Map<String, Object> newBindings = new HashMap<>();
      int pos = name.indexOf('/');
      if (pos == -1) {
         if (treeBindings.put(name, value) != null) {
            throw new NamingException("Something already bound at " + name);
         }
         bindings.put(name, value);
         newBindings.put(name, value);
      }
      else {
         String segment = name.substring(0, pos);
         assert segment != null;
         assert !segment.equals("");
         Object o = treeBindings.get(segment);
         if (o == null) {
            o = newContext();
            treeBindings.put(segment, o);
            bindings.put(segment, o);
            newBindings.put(segment, o);
         }
         else if (!(o instanceof ReadOnlyContext)) {
            throw new NamingException("Something already bound where a subcontext should go");
         }
         ReadOnlyContext readOnlyContext = (ReadOnlyContext) o;
         String remainder = name.substring(pos + 1);
         Map<String, Object> subBindings = readOnlyContext.internalBind(remainder, value);
         for (Map.Entry<String, Object> entry : subBindings.entrySet()) {
            String subName = segment + "/" + entry.getKey();
            Object bound = entry.getValue();
            treeBindings.put(subName, bound);
            newBindings.put(subName, bound);
         }
      }
      return newBindings;
   }

   protected ReadOnlyContext newContext() {
      return new ReadOnlyContext();
   }

   @Override
   public Object addToEnvironment(String propName, Object propVal) throws NamingException {
      return environment.put(propName, propVal);
   }

   @Override
   public Hashtable<String, Object> getEnvironment() throws NamingException {
      return (Hashtable<String, Object>) environment.clone();
   }

   @Override
   public Object removeFromEnvironment(String propName) throws NamingException {
      return environment.remove(propName);
   }

   @Override
   public Object lookup(String name) throws NamingException {
      if (name.length() == 0) {
         return this;
      }
      Object result = treeBindings.get(name);
      if (result == null) {
         result = bindings.get(name);
      }
      if (result == null) {
         int pos = name.indexOf(':');
         if (pos > 0) {
            String scheme = name.substring(0, pos);
            Context ctx = NamingManager.getURLContext(scheme, environment);
            if (ctx == null) {
               throw new NamingException("scheme " + scheme + " not recognized");
            }
            return ctx.lookup(name);
         }
         else {
            // Split out the first name of the path
            // and look for it in the bindings map.
            CompositeName path = new CompositeName(name);

            if (path.size() == 0) {
               return this;
            }
            else {
               String first = path.get(0);
               Object obj = bindings.get(first);
               if (obj == null) {
                  throw new NameNotFoundException(name);
               }
               else if (obj instanceof Context && path.size() > 1) {
                  Context subContext = (Context) obj;
                  obj = subContext.lookup(path.getSuffix(1));
               }
               return obj;
            }
         }
      }
      if (result instanceof LinkRef) {
         LinkRef ref = (LinkRef) result;
         result = lookup(ref.getLinkName());
      }
      if (result instanceof Reference) {
         try {
            result = NamingManager.getObjectInstance(result, null, null, this.environment);
         }
         catch (NamingException e) {
            throw e;
         }
         catch (Exception e) {
            throw (NamingException) new NamingException("could not look up : " + name).initCause(e);
         }
      }
      if (result instanceof ReadOnlyContext) {
         String prefix = getNameInNamespace();
         if (prefix.length() > 0) {
            prefix = prefix + SEPARATOR;
         }
         result = new ReadOnlyContext((ReadOnlyContext) result, environment, prefix + name);
      }
      return result;
   }

   @Override
   public Object lookup(Name name) throws NamingException {
      return lookup(name.toString());
   }

   @Override
   public Object lookupLink(String name) throws NamingException {
      return lookup(name);
   }

   @Override
   public Name composeName(Name name, Name prefix) throws NamingException {
      Name result = (Name) prefix.clone();
      result.addAll(name);
      return result;
   }

   @Override
   public String composeName(String name, String prefix) throws NamingException {
      CompositeName result = new CompositeName(prefix);
      result.addAll(new CompositeName(name));
      return result.toString();
   }

   @Override
   public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
      Object o = lookup(name);
      if (o == this) {
         return new ListEnumeration();
      }
      else if (o instanceof Context) {
         return ((Context) o).list("");
      }
      else {
         throw new NotContextException();
      }
   }

   @Override
   public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
      Object o = lookup(name);
      if (o == this) {
         return new ListBindingEnumeration();
      }
      else if (o instanceof Context) {
         return ((Context) o).listBindings("");
      }
      else {
         throw new NotContextException();
      }
   }

   @Override
   public Object lookupLink(Name name) throws NamingException {
      return lookupLink(name.toString());
   }

   @Override
   public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
      return list(name.toString());
   }

   @Override
   public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
      return listBindings(name.toString());
   }

   @Override
   public void bind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void bind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void close() throws NamingException {
      // ignore
   }

   @Override
   public Context createSubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public Context createSubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void destroySubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void destroySubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public String getNameInNamespace() throws NamingException {
      return nameInNamespace;
   }

   @Override
   public NameParser getNameParser(Name name) throws NamingException {
      return NAME_PARSER;
   }

   @Override
   public NameParser getNameParser(String name) throws NamingException {
      return NAME_PARSER;
   }

   @Override
   public void rebind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void rebind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void rename(Name oldName, Name newName) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void rename(String oldName, String newName) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void unbind(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   @Override
   public void unbind(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }

   private abstract class LocalNamingEnumeration implements NamingEnumeration {

      private final Iterator<Map.Entry<String, Object>> i = bindings.entrySet().iterator();

      @Override
      public boolean hasMore() throws NamingException {
         return i.hasNext();
      }

      @Override
      public boolean hasMoreElements() {
         return i.hasNext();
      }

      protected Map.Entry<String, Object> getNext() {
         return i.next();
      }

      @Override
      public void close() throws NamingException {
      }
   }

   private class ListEnumeration extends LocalNamingEnumeration {

      ListEnumeration() {
      }

      @Override
      public Object next() throws NamingException {
         return nextElement();
      }

      @Override
      public Object nextElement() {
         Map.Entry<String, Object> entry = getNext();
         return new NameClassPair(entry.getKey(), entry.getValue().getClass().getName());
      }
   }

   private class ListBindingEnumeration extends LocalNamingEnumeration {

      ListBindingEnumeration() {
      }

      @Override
      public Object next() throws NamingException {
         return nextElement();
      }

      @Override
      public Object nextElement() {
         Map.Entry<String, Object> entry = getNext();
         return new Binding(entry.getKey(), entry.getValue());
      }
   }
}


text:
export const GET_SQUAD = 'GET_SQUAD';
export const GET_SQUADS = 'GET_SQUADS';
export const CREATE_SQUAD = 'ADD_SQUAD';
export const UPDATE_SQUAD = 'UPDATE_SQUAD';
export const DELETE_SQUAD = 'DELETE_SQUAD';

export const getSquad(id) => {
    return {
        type: GET_SQUAD,
        id
    };
}

export const createSquad(data) => {
    return {
        type: CREATE_SQUAD,
        data
    };
}

export const deleteSquad(id) => {
    return {
        type: DELETE_SQUAD,
        id
    };
}

export const updateSquad(id, data) => {
    return {
        type: UPDATE_SQUAD,
        id,
        data
    };
}

export const getSquads(limit = 100, offset = 0) => {
    return {
        type: GET_SQUADS,
        limit,
        offset
    };
}


text:
//Licensed under MIT License see LICENSE.TXT in project root folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RFIDModuleScan.Core.Models;
using RFIDModuleScan.Core.Enums;

namespace RFIDModuleScan.Core.Scanners
{
    public class ConnectionStateEventArgs : EventArgs
    {
        public ScannerState State { get; set; }
    }
}