text:
package com.google.android.material.color;

import com.google.android.material.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import androidx.annotation.ChecksSdkIntAtLeast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.core.os.BuildCompat;
import com.google.android.material.color.utilities.Scheme;
import com.google.android.material.resources.MaterialAttributes;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/** Utility for applying dynamic colors to application/activities. */
public class DynamicColors {
  private static final int[] DYNAMIC_COLOR_THEME_OVERLAY_ATTRIBUTE =
      new int[] {R.attr.dynamicColorThemeOverlay};

  private static final DeviceSupportCondition DEFAULT_DEVICE_SUPPORT_CONDITION =
      new DeviceSupportCondition() {
        @Override
        public boolean isSupported() {
          return true;
        }
      };

  @SuppressLint("PrivateApi")
  private static final DeviceSupportCondition SAMSUNG_DEVICE_SUPPORT_CONDITION =
      new DeviceSupportCondition() {
        private Long version;

        @Override
        public boolean isSupported() {
          if (version == null) {
            try {
              Method method = Build.class.getDeclaredMethod("getLong", String.class);
              method.setAccessible(true);
              version = (long) method.invoke(null, "ro.build.version.oneui");
            } catch (Exception e) {
              version = -1L;
            }
          }
          return version >= 40100L;
        }
      };

  private static final Map<String, DeviceSupportCondition> DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS;

  static {
    Map<String, DeviceSupportCondition> deviceMap = new HashMap<>();
    deviceMap.put("fcnt", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("google", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("hmd global", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("infinix", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("infinix mobility limited", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("itel", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("kyocera", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("lenovo", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("lge", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("motorola", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("nothing", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("oneplus", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("oppo", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("realme", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("robolectric", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("samsung", SAMSUNG_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("sharp", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("sony", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("tcl", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("tecno", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("tecno mobile limited", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("vivo", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("wingtech", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("xiaomi", DEFAULT_DEVICE_SUPPORT_CONDITION);
    DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS = Collections.unmodifiableMap(deviceMap);
  }

  private static final Map<String, DeviceSupportCondition> DYNAMIC_COLOR_SUPPORTED_BRANDS;

  static {
    Map<String, DeviceSupportCondition> deviceMap = new HashMap<>();
    deviceMap.put("asus", DEFAULT_DEVICE_SUPPORT_CONDITION);
    deviceMap.put("jio", DEFAULT_DEVICE_SUPPORT_CONDITION);
    DYNAMIC_COLOR_SUPPORTED_BRANDS = Collections.unmodifiableMap(deviceMap);
  }

  private static final int USE_DEFAULT_THEME_OVERLAY = 0;

  private DynamicColors() {}

  /**
   * Applies dynamic colors to all activities with the theme overlay designated by the theme
   * attribute {@code dynamicColorThemeOverlay} by registering a {@link ActivityLifecycleCallbacks}
   * to your application.
   *
   * @see #applyToActivitiesIfAvailable(Application, DynamicColorsOptions) for more detailed info
   *     and examples.
   * @param application The target application.
   */
  public static void applyToActivitiesIfAvailable(@NonNull Application application) {
    applyToActivitiesIfAvailable(application, new DynamicColorsOptions.Builder().build());
  }

  /**
   * Applies dynamic colors to all activities with the given theme overlay by registering a {@link
   * ActivityLifecycleCallbacks} to your application.
   *
   * @param application The target application.
   * @param theme The resource ID of the theme overlay that provides dynamic color definition.
   * @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
   *     instead.
   */
  @Deprecated
  public static void applyToActivitiesIfAvailable(
      @NonNull Application application, @StyleRes int theme) {
    applyToActivitiesIfAvailable(
        application, new DynamicColorsOptions.Builder().setThemeOverlay(theme).build());
  }

  /**
   * Applies dynamic colors to all activities with the theme overlay designated by the theme
   * attribute {@code dynamicColorThemeOverlay} according to the given precondition by registering a
   * {@link ActivityLifecycleCallbacks} to your application.
   *
   * @param application The target application.
   * @param precondition The precondition to decide if dynamic colors should be applied.
   * @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
   *     instead.
   */
  @Deprecated
  public static void applyToActivitiesIfAvailable(
      @NonNull Application application, @NonNull Precondition precondition) {
    applyToActivitiesIfAvailable(
        application, new DynamicColorsOptions.Builder().setPrecondition(precondition).build());
  }

  /**
   * Applies dynamic colors to all activities with the given theme overlay according to the given
   * precondition by registering a {@link ActivityLifecycleCallbacks} to your application.
   *
   * @param application The target application.
   * @param theme The resource ID of the theme overlay that provides dynamic color definition.
   * @param precondition The precondition to decide if dynamic colors should be applied.
   * @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
   *     instead.
   */
  @Deprecated
  public static void applyToActivitiesIfAvailable(
      @NonNull Application application, @StyleRes int theme, @NonNull Precondition precondition) {
    applyToActivitiesIfAvailable(
        application,
        new DynamicColorsOptions.Builder()
            .setThemeOverlay(theme)
            .setPrecondition(precondition)
            .build());
  }

  /**
   * Applies dynamic colors to all activities based on the provided {@link DynamicColorsOptions}, by
   * registering a {@link ActivityLifecycleCallbacks} to your application.
   *
   *
A normal usage of this method should happen only once in {@link Application#onCreate()} or
   * any methods that run before any of your activities are created. For example:
   *
   *

   * public class YourApplication extends Application {
   *   @Override
   *   public void onCreate() {
   *     super.onCreate();
   *     DynamicColors.applyToActivitiesWithCallbacks(this);
   *   }
   * }
   *

   *
   * This method will try to apply the given dynamic color theme overlay in every activity's {@link
   * ActivityLifecycleCallbacks#onActivityPreCreated(Activity, Bundle)} callback. Therefore, if you
   * are applying any other theme overlays after that, you will need to be careful about not
   * overriding the colors or you may lose the dynamic color support.
   *
   * @param application The target application.
   * @param dynamicColorsOptions The dynamic colors options object that specifies the theme resource
   *     ID, precondition to decide if dynamic colors should be applied and the callback function
   *     for after dynamic colors have been applied.
   */
  public static void applyToActivitiesIfAvailable(
      @NonNull Application application, @NonNull DynamicColorsOptions dynamicColorsOptions) {
    application.registerActivityLifecycleCallbacks(
        new DynamicColorsActivityLifecycleCallbacks(dynamicColorsOptions));
  }

  /**
   * Applies dynamic colors to the given activity with the theme overlay designated by the theme
   * attribute {@code dynamicColorThemeOverlay}.
   *
   * @param activity The target activity.
   * @deprecated Use {@link #applyToActivityIfAvailable(Activity)} instead.
   */
  @Deprecated
  public static void applyIfAvailable(@NonNull Activity activity) {
    applyToActivityIfAvailable(activity);
  }

  /**
   * Applies dynamic colors to the given activity with the given theme overlay.
   *
   * @param activity The target activity.
   * @param theme The resource ID of the theme overlay that provides dynamic color definition.
   * @deprecated Use {@link #applyToActivityIfAvailable(Activity, DynamicColorsOptions)} instead.
   */
  @Deprecated
  public static void applyIfAvailable(@NonNull Activity activity, @StyleRes int theme) {
    applyToActivityIfAvailable(
        activity, new DynamicColorsOptions.Builder().setThemeOverlay(theme).build());
  }

  /**
   * Applies dynamic colors to the given activity with the theme overlay designated by the theme
   * attribute {@code dynamicColorThemeOverlay} according to the given precondition.
   *
   * @param activity The target activity.
   * @param precondition The precondition to decide if dynamic colors should be applied.
   * @deprecated Use {@link #applyToActivityIfAvailable(Activity, DynamicColorsOptions)} instead.
   */
  @Deprecated
  public static void applyIfAvailable(
      @NonNull Activity activity, @NonNull Precondition precondition) {
    applyToActivityIfAvailable(
        activity, new DynamicColorsOptions.Builder().setPrecondition(precondition).build());
  }

  /**
   * Applies dynamic colors to the given activity.
   *
   * @param activity The target activity.
   * @see #applyToActivityIfAvailable(Activity, DynamicColorsOptions)
   */
  public static void applyToActivityIfAvailable(@NonNull Activity activity) {
    applyToActivityIfAvailable(activity, new DynamicColorsOptions.Builder().build());
  }

  /**
   * Applies dynamic colors to the given activity with {@link DynamicColorsOptions} provided.
   *
   * @param activity The target activity.
   * @param dynamicColorsOptions The dynamic colors options object that specifies the theme resource
   *     ID, precondition to decide if dynamic colors should be applied and the callback function
   *     for after dynamic colors have been applied.
   */
  public static void applyToActivityIfAvailable(
      @NonNull Activity activity, @NonNull DynamicColorsOptions dynamicColorsOptions) {
    if (!isDynamicColorAvailable()) {
      return;
    }
    // Set default theme overlay as 0, as it's not used in content-based dynamic colors.
    int theme = 0;
    // Only retrieves the theme overlay if we're applying just dynamic colors.
    if (dynamicColorsOptions.getContentBasedSeedColor() == null) {
      theme =
          dynamicColorsOptions.getThemeOverlay() == USE_DEFAULT_THEME_OVERLAY
              ? getDefaultThemeOverlay(activity)
              : dynamicColorsOptions.getThemeOverlay();
    }

    if (dynamicColorsOptions.getPrecondition().shouldApplyDynamicColors(activity, theme)) {
      // Applies content-based dynamic colors if content-based source is provided.
      if (dynamicColorsOptions.getContentBasedSeedColor() != null) {
        Scheme colorScheme =
            MaterialAttributes.resolveBoolean(
                    activity, R.attr.isLightTheme, /* defaultValue= */ true)
                ? Scheme.lightContent(dynamicColorsOptions.getContentBasedSeedColor())
                : Scheme.darkContent(dynamicColorsOptions.getContentBasedSeedColor());
        ColorResourcesOverride resourcesOverride = ColorResourcesOverride.getInstance();
        if (resourcesOverride == null) {
          return;
        } else {
          if (!resourcesOverride.applyIfPossible(
              activity,
              MaterialColorUtilitiesHelper.createColorResourcesIdsToColorValues(colorScheme))) {
            return;
          }
        }
      } else {
        ThemeUtils.applyThemeOverlay(activity, theme);
      }
      // Applies client's callback after content-based dynamic colors or just dynamic colors has
      // been applied.
      dynamicColorsOptions.getOnAppliedCallback().onApplied(activity);
    }
  }

  /**
   * Wraps the given context with the theme overlay designated by the theme attribute {@code
   * dynamicColorThemeOverlay}. The returned context can be used to create views with dynamic color
   * support.
   *
   *
If dynamic color support or the dynamic color theme overlay is not available, the original
   * context will be returned.
   *
   * @param originalContext The original context.
   */
  @NonNull
  public static Context wrapContextIfAvailable(@NonNull Context originalContext) {
    return wrapContextIfAvailable(originalContext, USE_DEFAULT_THEME_OVERLAY);
  }

  /**
   * Wraps the given context with the given theme overlay. The returned context can be used to
   * create views with dynamic color support.
   *
   *
If dynamic color support is not available, the original context will be returned.
   *
   * @param originalContext The original context.
   * @param theme The resource ID of the theme overlay that provides dynamic color definition.
   */
  @NonNull
  public static Context wrapContextIfAvailable(
      @NonNull Context originalContext, @StyleRes int theme) {
    if (!isDynamicColorAvailable()) {
      return originalContext;
    }
    if (theme == USE_DEFAULT_THEME_OVERLAY) {
      theme = getDefaultThemeOverlay(originalContext);
    }
    return theme == 0 ? originalContext : new ContextThemeWrapper(originalContext, theme);
  }

  /** Returns {@code true} if dynamic colors are available on the current SDK level. */
  @SuppressLint("DefaultLocale")
  @ChecksSdkIntAtLeast(api = VERSION_CODES.S)
  public static boolean isDynamicColorAvailable() {
    if (VERSION.SDK_INT < VERSION_CODES.S) {
      return false;
    }
    if (BuildCompat.isAtLeastT()) {
      return true;
    }
    DeviceSupportCondition deviceSupportCondition =
        DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS.get(Build.MANUFACTURER.toLowerCase());
    if (deviceSupportCondition == null) {
      deviceSupportCondition = DYNAMIC_COLOR_SUPPORTED_BRANDS.get(Build.BRAND.toLowerCase());
    }
    return deviceSupportCondition != null && deviceSupportCondition.isSupported();
  }

  private static int getDefaultThemeOverlay(@NonNull Context context) {
    TypedArray dynamicColorAttributes =
        context.obtainStyledAttributes(DYNAMIC_COLOR_THEME_OVERLAY_ATTRIBUTE);
    final int theme = dynamicColorAttributes.getResourceId(0, 0);
    dynamicColorAttributes.recycle();
    return theme;
  }

  /** The interface that provides a precondition to decide if dynamic colors should be applied. */
  public interface Precondition {

    /**
     * Return {@code true} if dynamic colors should be applied on the given activity with the given
     * theme overlay.
     */
    boolean shouldApplyDynamicColors(@NonNull Activity activity, @StyleRes int theme);
  }

  /** The interface that provides a callback method after dynamic colors have been applied. */
  public interface OnAppliedCallback {

    /** The callback method after dynamic colors have been applied. */
    void onApplied(@NonNull Activity activity);
  }

  private static class DynamicColorsActivityLifecycleCallbacks
      implements ActivityLifecycleCallbacks {
    private final DynamicColorsOptions dynamicColorsOptions;

    DynamicColorsActivityLifecycleCallbacks(@NonNull DynamicColorsOptions options) {
      this.dynamicColorsOptions = options;
    }

    @Override
    public void onActivityPreCreated(
        @NonNull Activity activity, @Nullable Bundle savedInstanceState) {
      applyToActivityIfAvailable(activity, dynamicColorsOptions);
    }

    @Override
    public void onActivityCreated(
        @NonNull Activity activity, @Nullable Bundle savedInstanceState) {}

    @Override
    public void onActivityStarted(@NonNull Activity activity) {}

    @Override
    public void onActivityResumed(@NonNull Activity activity) {}

    @Override
    public void onActivityPaused(@NonNull Activity activity) {}

    @Override
    public void onActivityStopped(@NonNull Activity activity) {}

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {}
  }

  private interface DeviceSupportCondition {
    boolean isSupported();
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package logicparser;
import java.util.Scanner;
import java.util.ArrayList;
/**
 *
 * @author shatterwaltz
 */
public class LogicParser {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        System.out.println("& - and\n/ - or\n! - not\n> - implies\nInput must be fully disambiguated with parentheses.\nUse only one letter for variables.\n*******************\nEnter well formed formula:\n");
        Scanner s = new Scanner(System.in);
        Parser p = new Parser(s.nextLine());
        System.out.println("I interpreted: " + p.getWff());
        TruthGenerator t=new TruthGenerator(p);
        System.out.println(t.getTable());

    }
}

redpajama_set_name: RedPajamaGithub


text:
package dk.itu.pervasive.mobile.tests;

import com.eclipsesource.json.JsonObject;
import dk.itu.pervasive.mobile.utils.Constants;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by centos on 4/4/14.
 */
public class TestServer {

    public static void main(String[] args) {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(55556);
        } catch (IOException e) {
            System.out.println("Port taken");
            System.exit(1);

        }

        try {
            Socket socket = serverSocket.accept();

            BufferedReader stream = new BufferedReader(new InputStreamReader(socket.getInputStream() , "UTF-16"));

//            //receive start message
//            String line = stream.readLine();
//
//            System.out.println(line);

//            //send request for images
            JsonObject json = new JsonObject(); // send request object to get all images
            json.add(Constants.Action.ACTION , Constants.Action.REQUEST);
            String msg = "[" + json.toString() + "]\n";

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
               socket.getOutputStream() , "UTF-16"
            ));

            writer.write(msg);
            writer.flush();

            //send image
            File imageFile = new File("blue.jpeg");

////
            json = new JsonObject();
            json.add(Constants.Action.ACTION , Constants.Action.SEND);
            json.add(Constants.NAME , imageFile.getName());
            json.add(Constants.SIZE , String.valueOf(imageFile.length()));

            String sendAction = "[" + json.toString() + "]\n";

            writer.write(sendAction);
            writer.flush();
//
            transfer(imageFile , socket);

            Scanner sc = new Scanner(System.in);

            sc.nextLine();

            socket.getOutputStream().close();
            socket.close();

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

        if( !serverSocket.isClosed() )
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

    }

    public static void transfer(final File f, Socket socket) throws IOException {
        final BufferedOutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
        final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f));
        final byte[] buffer = new byte[1024];
        for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer)){
            outStream.write(buffer, 0, read);
        }

        outStream.flush();
    }
}


text:
> The goal of this project is to allow symantic relationships between multiple orms/databases.
> While it is generally not advised to use multiple storage methods if it can be avoided this handles
> the case when it can't be avoided or you have no choice.

##Currently Supported ORMS:
* Mongoid

###Current Status:
[![Build Status](https://travis-ci.org/h55nick/ActiveRecordBridge.svg)](https://travis-ci.org/h55nick/ActiveRecordBridge)

## EXAMPLES

Active Record Classes:
```ruby
class Property < ActiveRecord::Base
#   ...
   has_many_documents :default_rules
   has_one_document :address
#   ...
end
```
----
Mongoid Classes:
```ruby
class Rule
  include Mongoid::Document
  include ActiveRecordBridge::Mongoid
#   ...
  belongs_to_record :property
  belongs_to_record :updated_by, class_name: 'User'
  belongs_to_record :approved_by, class_name: 'User'
#   ...
end
```

This project rocks and uses MIT-LICENSE.


text:
from unittest import TestCase
from django.core.exceptions import ImproperlyConfigured
from rest_framework.test import APIRequestFactory
from tests.models import TestObject
from tests.serializers import TestObjectSerializer
from tests.views import TestObjectViewSet

class DynamicFieldsMixinTests(TestCase):

    def get_request(self, address=""):
        """
        Get a Django Rest Framework request from an address using a Request Factory.
        :param address:
        :return:
        """
        return TestObjectViewSet(action_map={'get': 'list'}).initialize_request(self.factory.get(address))

    def setUp(self):
        self.factory = APIRequestFactory()
        self.test_object = TestObject(field_one="1", field_two="2", field_three="3", field_four="4")

    def test_exception_raised_without_request_in_context(self):
        with self.assertRaises(ImproperlyConfigured):
            TestObjectSerializer(self.test_object, context={}).data

    def test_exception_raised_without_context(self):
        with self.assertRaises(ImproperlyConfigured):
            TestObjectSerializer(self.test_object).data

    def test_serializer_get_with_no_fields_specified_returns_default(self):
        request = self.get_request("test")
        data1 = TestObjectSerializer(self.test_object, context={"request": request}).data
        request = self.get_request("test/?field_set=default")
        data2 = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertEqual(data1, data2)

    def test_serializer_exclude_returns_everything_in_default_except_excluded_object(self):
        request = self.get_request("test/?exclude_fields=field_one")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertNotIn("field_one", data.keys())
        self.assertIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        # Four not in the default set
        self.assertNotIn("field_four", data.keys())

    def test_serializer_include_returns_nothing_except_field_name(self):
        request = self.get_request("test/?include_fields=field_two")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertNotIn("field_one", data.keys())
        self.assertIn("field_two", data.keys())
        self.assertNotIn("field_three", data.keys())
        self.assertNotIn("field_four", data.keys())

    def test_serializer_field_sets_returns_only_fields_in_list(self):
        request = self.get_request("test/?field_set=one_and_three")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertIn("field_one", data.keys())
        self.assertNotIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        self.assertNotIn("field_four", data.keys())

    def test_no_default_specified_returns_the_full_resource(self):
        default = TestObjectSerializer.Meta.field_sets.pop("default")
        request = self.get_request("test")
        serializer = TestObjectSerializer(self.test_object, context={"request": request})
        data = serializer.data
        self.assertIn("field_one", data.keys())
        self.assertIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        self.assertIn("field_four", data.keys())
        TestObjectSerializer.Meta.field_sets['default'] = default

    def test_include_field_that_does_not_exist_returns_none(self):
        request = self.get_request("test/?include_fields=field_five")
        serializer = TestObjectSerializer(self.test_object, context={"request": request})
        data = serializer.data
        self.assertEqual(len(data.keys()), 0)

    def test_exclude_field_that_does_not_exist_uses_default_serializer(self):
        request = self.get_request("test/?exclude_fields=field_five")
        serializer = TestObjectSerializer(self.test_object, context={"request": request})
        data = serializer.data
        self.assertIn("field_one", data.keys())
        self.assertIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        self.assertNotIn("field_four", data.keys())

    def test_field_set_specified_that_does_not_exist_uses_default_field_set(self):
        request = self.get_request("test/?field_set=doesNotExist")
        data1 = TestObjectSerializer(self.test_object, context={"request": request}).data
        request = self.get_request("test/?field_set=default")
        print(data1)
        data2 = TestObjectSerializer(self.test_object, context={"request": request}).data
        print(data2)
        self.assertEqual(data1, data2)

    def test_no_lingering_effects_integration(self):
        request = self.get_request("test/?field_set=one_and_three")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertIn("field_one", data.keys())
        self.assertNotIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        self.assertNotIn("field_four", data.keys())
        request = self.get_request("test/?field_set=all")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertIn("field_one", data.keys())
        self.assertIn("field_two", data.keys())
        self.assertIn("field_three", data.keys())
        self.assertIn("field_four", data.keys())
        request = self.get_request("test/?include_fields=field_one")
        data = TestObjectSerializer(self.test_object, context={"request": request}).data
        self.assertIn("field_one", data.keys())
        self.assertNotIn("field_two", data.keys())
        self.assertNotIn("field_three", data.keys())
        self.assertNotIn("field_four", data.keys())


text:
package org.apereo.cas.influxdb;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.model.support.influxdb.InfluxDbProperties;
import org.apereo.cas.configuration.support.Beans;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.io.Closeable;
import java.util.concurrent.TimeUnit;

/**
 * This is {@link InfluxDbConnectionFactory}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Slf4j
public class InfluxDbConnectionFactory implements Closeable {

    /**
     * The Influx db.
     */
    private final InfluxDB influxDb;

    /**
     * The Influx db properties.
     */
    private InfluxDbProperties influxDbProperties;

    /**
     * Instantiates a new Influx db connection factory.
     *
     * @param url          the url
     * @param uid          the uid
     * @param psw          the psw
     * @param dbName       the db name
     * @param dropDatabase the drop database
     */
    public InfluxDbConnectionFactory(final String url, final String uid,
                                     final String psw, final String dbName,
                                     final boolean dropDatabase) {

        if (StringUtils.isBlank(dbName) || StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("Database name/url cannot be blank and must be specified");
        }

        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        this.influxDb = InfluxDBFactory.connect(url, uid, psw, builder);
        this.influxDb.enableGzip();

        if (dropDatabase) {
            this.influxDb.deleteDatabase(dbName);
        }

        if (!this.influxDb.databaseExists(dbName)) {
            this.influxDb.createDatabase(dbName);
        }

        this.influxDb.setLogLevel(InfluxDB.LogLevel.NONE);
        if (LOGGER.isDebugEnabled()) {
            this.influxDb.setLogLevel(InfluxDB.LogLevel.FULL);
        } else if (LOGGER.isInfoEnabled()) {
            this.influxDb.setLogLevel(InfluxDB.LogLevel.BASIC);
        } else if (LOGGER.isWarnEnabled()) {
            this.influxDb.setLogLevel(InfluxDB.LogLevel.HEADERS);
        } else if (LOGGER.isErrorEnabled()) {
            this.influxDb.setLogLevel(InfluxDB.LogLevel.NONE);
        }
    }

    /**
     * Instantiates a new Influx db connection factory.
     *
     * @param props the props
     */
    public InfluxDbConnectionFactory(final InfluxDbProperties props) {
        this(props.getUrl(), props.getUsername(), props.getPassword(), props.getDatabase(), props.isDropDatabase());

        if (StringUtils.isNotBlank(props.getRetentionPolicy())) {
            this.influxDb.setRetentionPolicy(props.getRetentionPolicy());
        }

        influxDb.setConsistency(InfluxDB.ConsistencyLevel.valueOf(props.getConsistencyLevel().toUpperCase()));

        if (props.getPointsToFlush() > 0 && StringUtils.isNotBlank(props.getBatchInterval())) {
            final int interval = (int) Beans.newDuration(props.getBatchInterval()).toMillis();
            this.influxDb.enableBatch(props.getPointsToFlush(), interval, TimeUnit.MILLISECONDS);
        }

        this.influxDbProperties = props;
    }

    /**
     * Write measurement point.
     *
     * @param point the point
     */
    public void write(final Point point) {
        this.influxDb.write(influxDbProperties.getDatabase(), influxDbProperties.getRetentionPolicy(), point);
    }

    /**
     * Write measurement point.
     *
     * @param point  the point
     * @param dbName the db name
     */
    public void write(final Point point, final String dbName) {
        this.influxDb.write(dbName, "autogen", point);
    }

    /**
     * Query all result.
     *
     * @param measurement the measurement
     * @return the query result
     */
    public QueryResult query(final String measurement) {
        return query("*", measurement);
    }

    /**
     * Query result.
     *
     * @param fields      the fields
     * @param measurement the measurement
     * @return the query result
     */
    public QueryResult query(final String fields, final String measurement) {
        return query(fields, measurement, influxDbProperties.getDatabase());
    }

    /**
     * Query result.
     *
     * @param fields      the fields
     * @param measurement the table
     * @param dbName      the db name
     * @return the query result
     */
    public QueryResult query(final String fields, final String measurement, final String dbName) {
        final String filter = String.format("SELECT %s FROM %s", fields, measurement);
        final Query query = new Query(filter, dbName);
        return this.influxDb.query(query);
    }

    @Override
    public void close() {
        this.influxDb.close();
    }
}


text:
package com.schinizer.hackernews.data;

import com.schinizer.hackernews.AppModule;
import com.schinizer.hackernews.utility.schedulers.SchedulersModule;

import javax.inject.Singleton;

import dagger.Component;

/**
 * Created by DPSUser on 10/14/2016.
 */

@Singleton
@Component(modules = {AppModule.class, NetModule.class, SchedulersModule.class, APIModule.class, AndroidAPIModule.class, ItemDataSourceModule.class})
public interface ItemRepositoryComponent {
    ItemRepository getItemRepository();
}


text:
package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Gateway authentication keys.
 */
public class GatewayKeysContractInner {
    /**
     * Primary gateway key.
     */
    @JsonProperty(value = "primary")
    private String primary;

    /**
     * Secondary gateway key.
     */
    @JsonProperty(value = "secondary")
    private String secondary;

    /**
     * Get primary gateway key.
     *
     * @return the primary value
     */
    public String primary() {
        return this.primary;
    }

    /**
     * Set primary gateway key.
     *
     * @param primary the primary value to set
     * @return the GatewayKeysContractInner object itself.
     */
    public GatewayKeysContractInner withPrimary(String primary) {
        this.primary = primary;
        return this;
    }

    /**
     * Get secondary gateway key.
     *
     * @return the secondary value
     */
    public String secondary() {
        return this.secondary;
    }

    /**
     * Set secondary gateway key.
     *
     * @param secondary the secondary value to set
     * @return the GatewayKeysContractInner object itself.
     */
    public GatewayKeysContractInner withSecondary(String secondary) {
        this.secondary = secondary;
        return this;
    }

}


text:
package jetbrains.buildServer.clouds.kubernetes;

/**
 * Created by ekoshkin (koshkinev@gmail.com) on 07.06.17.
 */
public class KubeTeamCityLabels {
    public static final String TEAMCITY_AGENT_LABEL = "teamcity-agent";
    public static final String TEAMCITY_SERVER_UUID = "teamcity-server-uuid";
    public static final String TEAMCITY_CLOUD_PROFILE = "teamcity-cloud-profile";
    public static final String TEAMCITY_CLOUD_IMAGE = "teamcity-cloud-image";
}


text:
__author__ = 'Georgios Rizos (georgerizos@iti.gr)'

from collections import deque
import numpy as np

from reveal_graph_embedding.eps_randomwalk.push import pagerank_limit_push
from reveal_graph_embedding.eps_randomwalk.push import pagerank_lazy_push
from reveal_graph_embedding.eps_randomwalk.push import cumulative_pagerank_difference_limit_push

def fast_approximate_personalized_pagerank(s,
                                           r,
                                           w_i,
                                           a_i,
                                           out_degree,
                                           in_degree,
                                           seed_node,
                                           rho=0.2,
                                           epsilon=0.00001):
    """
    Calculates the approximate personalized PageRank starting from a seed node without self-loops.
    """
    # Initialize approximate PageRank and residual distributions
    # s = np.zeros(number_of_nodes, dtype=np.float64)
    # r = np.zeros(number_of_nodes, dtype=np.float64)
    r[seed_node] = 1.0

    # Initialize queue of nodes to be pushed
    pushable = deque()
    pushable.append(seed_node)

    # Do one push anyway
    push_node = pushable.popleft()

    pagerank_limit_push(s,
                        r,
                        w_i[push_node],
                        a_i[push_node],
                        push_node,
                        rho)
    number_of_push_operations = 1

    i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
    if i.size > 0:
        pushable.extend(a_i[push_node][i])

    while len(pushable) > 0:
        # While there are nodes with large residual probabilities, push
        push_node = pushable.popleft()
        if r[push_node]/in_degree[push_node] >= epsilon:
            pagerank_limit_push(s,
                                r,
                                w_i[push_node],
                                a_i[push_node],
                                push_node,
                                rho)
            number_of_push_operations += 1

            i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
            if i.size > 0:
                pushable.extend(a_i[push_node][i])

    return number_of_push_operations

def lazy_approximate_personalized_pagerank(s,
                                           r,
                                           w_i,
                                           a_i,
                                           out_degree,
                                           in_degree,
                                           seed_node,
                                           rho=0.2,
                                           epsilon=0.00001,
                                           laziness_factor=0.5):
    """
    Calculates the approximate personalized PageRank starting from a seed node with self-loops.

    Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
                   Local graph partitioning using pagerank vectors.
                   In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE.
    """
    # Initialize approximate PageRank and residual distributions
    # s = np.zeros(number_of_nodes, dtype=np.float64)
    # r = np.zeros(number_of_nodes, dtype=np.float64)
    r[seed_node] = 1.0

    # Initialize queue of nodes to be pushed
    pushable = deque()
    pushable.append(seed_node)

    # Do one push anyway
    push_node = pushable.popleft()

    pagerank_lazy_push(s,
                       r,
                       w_i[push_node],
                       a_i[push_node],
                       push_node,
                       rho,
                       laziness_factor)
    number_of_push_operations = 1

    i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
    if i.size > 0:
        pushable.extend(a_i[push_node][i])

    while r[push_node]/in_degree[push_node] >= epsilon:
        pagerank_lazy_push(s,
                           r,
                           w_i[push_node],
                           a_i[push_node],
                           push_node,
                           rho,
                           laziness_factor)
        number_of_push_operations += 1

    # While there are nodes with large residual probabilities, push
    while len(pushable) > 0:
        push_node = pushable.popleft()

        if r[push_node]/in_degree[push_node] >= epsilon:
            pagerank_lazy_push(s,
                               r,
                               w_i[push_node],
                               a_i[push_node],
                               push_node,
                               rho,
                               laziness_factor)
            number_of_push_operations += 1

            i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
            if i.size > 0:
                pushable.extend(a_i[push_node][i])

        while r[push_node]/in_degree[push_node] >= epsilon:
            pagerank_lazy_push(s,
                               r,
                               w_i[push_node],
                               a_i[push_node],
                               push_node,
                               rho,
                               laziness_factor)
            number_of_push_operations += 1

    return number_of_push_operations

def fast_approximate_cumulative_pagerank_difference(s,
                                                    r,
                                                    w_i,
                                                    a_i,
                                                    out_degree,
                                                    in_degree,
                                                    seed_node,
                                                    rho=0.2,
                                                    epsilon=0.00001):
    """
    Calculates cumulative PageRank difference probability starting from a seed node without self-loops.

    Inputs:  - w_i: A NumPy array of arrays of probability transition weights from the seed nodes to its adjacent nodes.
             - a_i: A NumPy array of arrays of the nodes adjacent to the seed node.
             - out_degree: A NumPy array of node out_degrees.
             - in_degree: A NumPy array of node in_degrees.
             - seed_node: The seed for the node-centric personalized PageRank.
             - rho: The restart probability. Usually set in [0.1, 0.2].
             - epsilon: The error threshold.

    Outputs: - s in 1xn: A sparse vector that contains the approximate absorbing random walk cumulative probabilities.
             - r in 1xn: A sparse vector that contains the residual probability distribution.
             - nop: The number of limit probability push operations performed.
    """
    # Initialize the similarity matrix slice and the residual distribution
    # s = np.zeros(number_of_nodes, dtype=np.float64)
    # r = np.zeros(number_of_nodes, dtype=np.float64)
    s[seed_node] = 1.0
    r[seed_node] = 1.0

    # Initialize double-ended queue of nodes to be pushed
    pushable = deque()
    pushable.append(seed_node)

    # Do one push for free
    push_node = pushable.popleft()

    cumulative_pagerank_difference_limit_push(s,
                                              r,
                                              w_i[push_node],
                                              a_i[push_node],
                                              push_node,
                                              rho)
    number_of_push_operations = 1

    i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
    if i.size > 0:
        pushable.extend(a_i[push_node][i])

    # While there are nodes with large residual probabilities, push
    while len(pushable) > 0:
        push_node = pushable.popleft()

        # If the threshold is not satisfied, perform a push operation
        # Both this and the later check are needed, since the pushable queue may contain duplicates.
        if r[push_node]/in_degree[push_node] >= epsilon:
            cumulative_pagerank_difference_limit_push(s,
                                                      r,
                                                      w_i[push_node],
                                                      a_i[push_node],
                                                      push_node,
                                                      rho)
            number_of_push_operations += 1

            # Update pushable double-ended queue
            i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
            if i.size > 0:
                pushable.extend(a_i[push_node][i])

    # Sparsify and return.
    # s_sparse = sparse.csr_matrix(s, shape=(1, number_of_nodes))
    # r_sparse = sparse.csr_matrix(r, shape=(1, number_of_nodes))

    return number_of_push_operations


text:
package action_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"errors"
	. "github.com/cloudfoundry/bosh-agent/agent/action"
	fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes"
	fakeappl "github.com/cloudfoundry/bosh-agent/agent/applier/fakes"
	fakejobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor/fakes"
)

func init() {
	Describe("Start", func() {
		var (
			jobSupervisor *fakejobsuper.FakeJobSupervisor
			applier       *fakeappl.FakeApplier
			specService   *fakeas.FakeV1Service
			action        StartAction
		)

		BeforeEach(func() {
			jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
			applier = fakeappl.NewFakeApplier()
			specService = fakeas.NewFakeV1Service()
			action = NewStart(jobSupervisor, applier, specService)
		})

		It("is synchronous", func() {
			Expect(action.IsAsynchronous()).To(BeFalse())
		})

		It("is not persistent", func() {
			Expect(action.IsPersistent()).To(BeFalse())
		})

		It("returns started", func() {
			started, err := action.Run()
			Expect(err).ToNot(HaveOccurred())
			Expect(started).To(Equal("started"))
		})

		It("starts monitor services", func() {
			_, err := action.Run()
			Expect(err).ToNot(HaveOccurred())
			Expect(jobSupervisor.Started).To(BeTrue())
		})

		It("configures jobs", func() {
			_, err := action.Run()
			Expect(err).ToNot(HaveOccurred())
			Expect(applier.Configured).To(BeTrue())
		})

		It("apply errs if a job fails configuring", func() {
			applier.ConfiguredError = errors.New("fake error")
			_, err := action.Run()

			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Configuring jobs"))
		})
	})
}


text:
import time
import warnings
import functools
from logging import getLogger

from sentry_sdk import capture_exception
from sqlalchemy.exc import SQLAlchemyError

from feedrsub.database import db
from feedrsub.models.feedstats import FeedStats

logger = getLogger("tasks")

def deprecated(func):
    """This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emmitted
    when the function is used."""

    @functools.wraps(func)
    def new_func(*args, **kwargs):
        warnings.simplefilter("always", DeprecationWarning)  # turn off filter
        warnings.warn(
            "Call to deprecated function {}.".format(func.__name__),
            category=DeprecationWarning,
            stacklevel=2,
        )
        warnings.simplefilter("default", DeprecationWarning)  # reset filter
        return func(*args, **kwargs)

    return new_func

def timeit(function=None, *, slow: float = 0):
    """
    A decorator used to log the function execution time.

    :param function: the function to be decorated.
    :param slow: the function will only be logged if duration of the function is greater
        than the "slow" value in seconds.
    """

    def _decorate(function):

        # Use functools.wraps to ensure function name is not changed
        # http://stackoverflow.com/questions/13492603/celery-task-with-multiple-decorators-not-auto-registering-task-name
        @functools.wraps(function)
        def wrapped_function(*args, **kwargs):
            start = time.perf_counter()
            result = function(*args, **kwargs)
            duration_ms = int((time.perf_counter() - start) * 1000)
            msg = {
                "task_name": function.__module__ + "." + function.__name__,
                "duration": duration_ms,
                # Use 'task_args' instead of 'args' because 'args' conflicts with
                # attribute of LogRecord
                "task_args": args,
                "task_kwargs": kwargs,
            }
            # Only log if slow value not provided
            # or duration in milliseconds is greater than slow value in milliseconds.
            if not slow or duration_ms > int(slow * 1000):
                if function.__name__.startswith("task_"):
                    logger.info(
                        "TASK: function=%s duration=%sms",
                        function.__name__,
                        duration_ms,
                        extra=msg,
                    )
                else:
                    logger.info(
                        "FUNC: function=%s duration=%sms",
                        function.__name__,
                        duration_ms,
                        extra=msg,
                    )
            return result

        return wrapped_function

    if function:
        return _decorate(function)
    return _decorate

def save_stats_and_commit(func):
    """
    A decorator which saves FeedStats and ensures the DB session is committed.

    Records time separately from timeit wrapper, as we can't include commit time in
    FeedStats, unless we put FeedStats in separate commit or task, which we don't
    want for performance reasons.
    """

    @functools.wraps(func)
    def wrap(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        dur = int((time.perf_counter() - start) * 1000)

        stats = kwargs.get("stats")
        if stats:
            stats["parse_time"] = dur
            FeedStats.save_stats(stats)

        try:
            db.session.commit()
        except SQLAlchemyError as exception:
            capture_exception(exception)
            logger.exception("EXCEPT: function=%s msg=%s", func.__name__, exception)
            db.session.rollback()
        return result

    return wrap

def commit(func):
    """
    Ensures the database session is committed after a function.

    :param func: Function
    :return: Decorated Function
    """

    @functools.wraps(func)
    def wrap(*args, **kwargs):
        result = func(*args, **kwargs)
        try:
            db.session.commit()
        except SQLAlchemyError as exception:
            capture_exception(exception)
            logger.exception("EXCEPT: function=%s msg=%s", func.__name__, exception)
            db.session.rollback()
        return result

    return wrap


text:
<?php

class HTMLPurifier_AttrTransform_EnumToCSSTest extends HTMLPurifier_AttrTransformHarness
{

    public function setUp()
    {
        parent::setUp();
        $this->obj = new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
            'left' => 'text-align:left;',
            'right' => 'text-align:right;'
        ));
    }

    public function testEmptyInput()
    {
        $this->assertResult(array());
    }

    public function testPreserveArraysWithoutInterestingAttributes()
    {
        $this->assertResult(array('style' => 'font-weight:bold;'));
    }

    public function testConvertAlignLeft()
    {
        $this->assertResult(
            array('align' => 'left'),
            array('style' => 'text-align:left;')
        );
    }

    public function testConvertAlignRight()
    {
        $this->assertResult(
            array('align' => 'right'),
            array('style' => 'text-align:right;')
        );
    }

    public function testRemoveInvalidAlign()
    {
        $this->assertResult(
            array('align' => 'invalid'),
            array()
        );
    }

    public function testPrependNewCSS()
    {
        $this->assertResult(
            array('align' => 'left', 'style' => 'font-weight:bold;'),
            array('style' => 'text-align:left;font-weight:bold;')
        );

    }

    public function testCaseInsensitive()
    {
        $this->obj = new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
            'right' => 'text-align:right;'
        ));
        $this->assertResult(
            array('align' => 'RIGHT'),
            array('style' => 'text-align:right;')
        );
    }

    public function testCaseSensitive()
    {
        $this->obj = new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
            'right' => 'text-align:right;'
        ), true);
        $this->assertResult(
            array('align' => 'RIGHT'),
            array()
        );
    }

}

// vim: et sw=4 sts=4


text:
'use strict';

angular.module('users').controller('SettingsController', ['$scope', '$http', '$location', 'Users', 'Authentication', '$upload', '$timeout',
	function($scope, $http, $location, Users, Authentication,  $upload, $timeout) {
		$scope.user = Authentication.user;

		// If user is not signed in then redirect back home
		if (!$scope.user) $location.path('/');

		// Check if there are additional accounts
		$scope.hasConnectedAdditionalSocialAccounts = function(provider) {
			for (var i in $scope.user.additionalProvidersData) {
				return true;
			}

			return false;
		};

		// Check if provider is already in use with current user
		$scope.isConnectedSocialAccount = function(provider) {
			return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]);
		};

		// Remove a user social account
		$scope.removeUserSocialAccount = function(provider) {
			$scope.success = $scope.error = null;

			$http.delete('/users/accounts', {
				params: {
					provider: provider
				}
			}).success(function(response) {
				// If successful show success message and clear form
				$scope.success = true;
				$scope.user = Authentication.user = response;
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		// Update a user profile
		$scope.updateUserProfile = function(isValid) {
			if (isValid) {
				$scope.success = $scope.error = null;
				var user = new Users($scope.user);

				user.$update(function(response) {
					$scope.success = true;
					Authentication.user = response;
				}, function(response) {
					$scope.error = response.data.message;
				});
			} else {
				$scope.submitted = true;
			}
		};

		// Change user password
		$scope.changeUserPassword = function() {
			$scope.success = $scope.error = null;

			$http.post('/users/password', $scope.passwordDetails).success(function(response) {
				// If successful show success message and clear form
				$scope.success = true;
				$scope.passwordDetails = null;
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

        $scope.upload = function($files) {
            //console.log($files);
            $upload.upload({
                url: 'users/me/upload-pic',
                method: 'POST',
                //data: {
                //    resto: $scope.resto
                //}, // Any data needed to be submitted along with the files
                file: $files
            }).progress(function(evt) {
                $scope.picFile[0].progress = parseInt(100.0 * evt.loaded / evt.total);
            }).success(function(data, status, headers, config) {
                //console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
                $scope.user = data;
                setTimeout(function(){
                    $scope.picFile[0].progress = 0;
                },3000)
            }).error(function(err) {
                console.log('error');
            });
        };

        $scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);
        $scope.generateThumb = function(file) {
            if (file != null) {
                if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
                    $timeout(function() {
                        var fileReader = new FileReader();
                        fileReader.readAsDataURL(file);
                        fileReader.onload = function(e) {
                            $timeout(function() {
                                file.dataUrl = e.target.result;
                            });
                        }
                    });
                }
            }
        }
	}
]);


text:
using MicroOrm.Business.BLO.Base;
using MicroOrm.Business.Management;
using MicroOrm.Data.Infra.Contexts;
using MicroOrm.Models;

namespace MicroOrm.Business.BLO
{
  public partial class UserBLO : BaseBLO<User>
  {
    public static UserBLO GetInstance()
    {
      return new UserBLO(ObjectManager.GetUow());
    }

    public UserBLO(IUnitOfWork uow) : base(uow) { }
  }
}


text:
drop table users if exists;
drop table users2 if exists;

create table users (
id int,
name varchar(16)
);

create table users2 (
id int IDENTITY,
name varchar(16)
);


text:
package org.wso2.carbon.apimgt.keymgt.model.entity;

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

public class ApplicationList {

    private Integer count = null;
    private List<Application> list = new ArrayList<>();

    public Integer getCount() {

        return count;
    }

    public void setCount(Integer count) {

        this.count = count;
    }

    public List<Application> getList() {

        return list;
    }

    public void setList(List<Application> list) {

        this.list = list;
    }
}


text:
set -e
echo "${OS_DISTRO}: Bootstrapping image metadata"
################################################################################
. /etc/os-container.env
. /opt/harbor/service-hosts.sh
. /opt/harbor/harbor-common.sh
. /opt/harbor/ceilometer/vars.sh

################################################################################
check_required_vars CEILOMETER_CONFIG_FILE

################################################################################
tail -f /dev/null


text:
package org.openksavi.sponge.core.kb;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.openksavi.sponge.SpongeException;
import org.openksavi.sponge.kb.KnowledgeBaseEngineOperations;
import org.openksavi.sponge.kb.KnowledgeBaseType;

/**
 * Non script based knowledge base interpreter.
 */
public abstract class BaseNonScriptKnowledgeBaseInterpreter extends BaseKnowledgeBaseInterpreter {

    protected Map<String, Object> variables = Collections.synchronizedMap(new LinkedHashMap<>());

    /**
     * Creates a new knowledge base interpreter.
     *
     * @param engineOperations an engine operations.
     * @param type a knowledge base type.
     */
    protected BaseNonScriptKnowledgeBaseInterpreter(KnowledgeBaseEngineOperations engineOperations, KnowledgeBaseType type) {
        super(engineOperations, type);
    }

    @Override
    public void setVariable(String name, Object value) {
        variables.put(name, value);
    }

    @Override
    public Object getVariable(String name) {
        if (!variables.containsKey(name)) {
            throw new SpongeException("Variable " + name + " not found");
        }

        return variables.get(name);
    }

    @Override
    public boolean hasVariable(String name) {
        return variables.containsKey(name);
    }

    @Override
    public boolean isKnowledgeBaseException(Throwable exception) {
        return false;
    }

    @Override
    public Throwable getJavaException(Throwable knowledgeBaseException) {
        return knowledgeBaseException;
    }

    @Override
    public String getScriptKnowledgeBaseProcessorClassName(Object processorClass) {
        return null;
    }
}


text:
#include <ros/console.h>

#include <runtime_manager/ConfigLaneStop.h>
#include <runtime_manager/traffic_light.h>
#include <waypoint_follower/LaneArray.h>

#include <lane_planner/vmap.hpp>

namespace {

bool config_manual_detection = true;

ros::Publisher traffic_pub;

waypoint_follower::LaneArray current_red_lane;
waypoint_follower::LaneArray current_green_lane;

const waypoint_follower::LaneArray *previous_lane = &current_red_lane;

void select_current_lane(const runtime_manager::traffic_light& msg)
{
	const waypoint_follower::LaneArray *current;
	switch (msg.traffic_light) {
	case lane_planner::vmap::TRAFFIC_LIGHT_RED:
		current = &current_red_lane;
		break;
	case lane_planner::vmap::TRAFFIC_LIGHT_GREEN:
		current = &current_green_lane;
		break;
	case lane_planner::vmap::TRAFFIC_LIGHT_UNKNOWN:
		current = previous_lane; // if traffic light state is unknown, keep previous state
		break;
	default:
		ROS_ERROR_STREAM("undefined traffic light");
		return;
	}

	if (current->lanes.empty()) {
		ROS_ERROR_STREAM("empty lanes");
		return;
	}

	traffic_pub.publish(*current);

	previous_lane = current;
}

void receive_auto_detection(const runtime_manager::traffic_light& msg)
{
	if (!config_manual_detection)
		select_current_lane(msg);
}

void receive_manual_detection(const runtime_manager::traffic_light& msg)
{
	if (config_manual_detection)
		select_current_lane(msg);
}

void cache_red_lane(const waypoint_follower::LaneArray& msg)
{
	current_red_lane = msg;
}

void cache_green_lane(const waypoint_follower::LaneArray& msg)
{
	current_green_lane = msg;
}

void config_parameter(const runtime_manager::ConfigLaneStop& msg)
{
	config_manual_detection = msg.manual_detection;
}

} // namespace

int main(int argc, char **argv)
{
	ros::init(argc, argv, "lane_stop");

	ros::NodeHandle n;

	int sub_light_queue_size;
	n.param<int>("/lane_stop/sub_light_queue_size", sub_light_queue_size, 1);
	int sub_waypoint_queue_size;
	n.param<int>("/lane_stop/sub_waypoint_queue_size", sub_waypoint_queue_size, 1);
	int sub_config_queue_size;
	n.param<int>("/lane_rule/sub_config_queue_size", sub_config_queue_size, 1);
	int pub_waypoint_queue_size;
	n.param<int>("/lane_stop/pub_waypoint_queue_size", pub_waypoint_queue_size, 1);
	bool pub_waypoint_latch;
	n.param<bool>("/lane_stop/pub_waypoint_latch", pub_waypoint_latch, true);

	traffic_pub = n.advertise<waypoint_follower::LaneArray>("/traffic_waypoints_array", pub_waypoint_queue_size,
								pub_waypoint_latch);

	ros::Subscriber light_sub = n.subscribe("/light_color", sub_light_queue_size, receive_auto_detection);
	ros::Subscriber light_managed_sub = n.subscribe("/light_color_managed", sub_light_queue_size,
							receive_manual_detection);
	ros::Subscriber red_sub = n.subscribe("/red_waypoints_array", sub_waypoint_queue_size, cache_red_lane);
	ros::Subscriber green_sub = n.subscribe("/green_waypoints_array", sub_waypoint_queue_size, cache_green_lane);
	ros::Subscriber config_sub = n.subscribe("/config/lane_stop", sub_config_queue_size, config_parameter);

	ros::spin();

	return EXIT_SUCCESS;
}


text:
<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Using FusionCharts XT with JSP > Charting Data from
        Forms
    </title>
<link rel="stylesheet" href="../../assets/ui/css/style.css" type="text/css" />

<link rel="stylesheet" type="text/css" href="../../assets/prettify/prettify.css" />

    Charting Data from
        Forms

In this section, we will show you how to use FusionCharts XT with JSP to plot
        data collected in forms.

We will build a simple restaurant sales example, where the user will enter the items sold by a restaurant in a given week. This data will be submitted in a form to the server. We will acquire this data and plot in on a chart. For the sake of simplicity, we will not process anything on this data. However, your real life applications might process data before presenting it on the chart.

Before you go further with this page, we recommend you to please see the previous section, Basic Examples, as we start off from concepts explained in that page.

The code examples contained in this
      page are present in Download Package > Code
      > J2EE > FormBased folder.

    Building the Form

The form is contained in Default.jsp
      and looks as under:

It's a very simple form which submits to Chart.jsp.
      You can also use java server faces to create such form. Here, we have used plain HTML in our page. We are not going into the code of the form, you can directly open the source from download and see it.

    Requesting the Data and Creating the Chart

The work of requesting the data from submitted
      form, setting it in the bean which constructs the XML and rendering the chart is done in Chart.jsp,
      present in the same folder. It contains the following code:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.fusioncharts.com/jsp/core" prefix="fc" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<jsp:useBean id="restaurantBean" class="com.fusioncharts.sampledata.RestaurantBean"/>
<c:set var="folderPath" value="../../FusionCharts/"/>
<c:set var="title" value="FusionCharts - Form Based Data Charting Example" scope="request"/>
<c:set var="header1" value="FusionCharts Form-Based Data Example" scope="request"/>
<c:set var="header2" value="Restaurant Sales Chart below" scope="request"/>
<c:set var="intro" value="Click on any pie slice to see slicing effect. Or,
right click on chart and choose 'Enable Rotation', and then drag and
rotate the chart."/>
<c:set var="jsPath" value="${folderPath}" scope="request"/>
<c:set target="${restaurantBean}" property="soups" value="${param.Soups}"/>
<c:set target="${restaurantBean}" property="salads" value="${param.Salads}"/>
<c:set target="${restaurantBean}" property="sandwiches" value="${param.Sandwiches}"/>
<c:set target="${restaurantBean}" property="beverages" value="${param.Beverages}"/>
<c:set target="${restaurantBean}" property="desserts" value="${param.Desserts}"/>
<tags:template2>
<fc:render chartId="${restaurantBean.chartId}" swfFilename="${folderPath}${restaurantBean.filename}"
           width="${restaurantBean.width}" height="${restaurantBean.height}"
           xmlData="${restaurantBean.xml}" />
<br/>
<a href='javascript:history.go(-1);'>Enter data again</a> <br/><br/>
</tags:template2>

As you can see in the above code, we are doing the following:

Included the path to the folder containing the javascript files, which are required when using the JavaScript method.

Requesting data from the submitted form and setting it in the bean. (c:set tags)

Getting the XML from RestaurantBean for the chart.

Rendering a Pie 3D chart by using the fc:render tag and passing the XML as attribute.

The actual XML is constructed in RestaurantBean as shown below:

//Initialize <chart> element
xml = "<chart caption='Sales by Product Category' subCaption='For this week'
showPercentValues='0' pieSliceDepth='30' showBorder='1'>";
//Add all data
xml += "<set label='Soups' value='" + soups + "' />";
xml += "<set label='Salads' value='" + salads + "' />";
xml += "<set label='Sandwiches' value='" + sandwiches + "' />";
xml += "<set label='Beverages' value='" + beverages + "' />";
xml += "<set label='Desserts' value='" + desserts + "' />";
//Close <chart> element
xml += "</chart>";

Here, soups, salads, sandwiches, beverages and desserts are names of the bean class members whose values are set using c:set tags in Chart.jsp.

When you finally run the code, you will see a chart as under:


text:
<?php

namespace Shop\Discount;

class Calculator{

	protected $order;
	protected $discounts;
	protected $modifier;

	protected $log = array();

	public function __construct(\Order $order, $context = array()) {
		$this->order = $order;
		//get qualifying discounts for this order
		$this->discounts = \Discount::get_matching($this->order, $context);
		$this->modifier = $this->order->getModifier("OrderDiscountModifier", true);
	}

	/**
	 * Work out the discount for a given order.
	 * @param Order $order
	 * @return double - discount amount
	 */
	public function calculate() {
		$total = 0;
		//clear any existing linked discounts
		$this->modifier->Discounts()->removeAll();

		//work out all item-level discounts, and load into infoitems
		$infoitems = $this->createPriceInfoList($this->order->Items());
		foreach($this->getItemDiscounts() as $discount){
			//item discounts will update info items
			$action = $discount->Type === "Percent" ?
				new \ItemPercentDiscount($infoitems, $discount) :
				new \ItemFixedDiscount($infoitems, $discount);
			$amount = $action->perform();
		}

		//select best item-level discounts
		foreach($infoitems as $infoitem){
			$bestadjustment = $infoitem->getBestAdjustment();
			if(!$bestadjustment){
				continue;
			}
			$amount = $bestadjustment->getValue();
			//prevent discounting more than original price
			if($amount > $infoitem->getOriginalTotal()){
				$amount = $infoitem->getOriginalTotal();
			}
			$total += $amount;
			//remove any existing linked discounts
			$infoitem->getItem()->Discounts()->removeAll();
			$infoitem->getItem()->Discounts()->add(
				$bestadjustment->getAdjuster(),
				array('DiscountAmount' => $amount)
			);
			$this->logDiscountAmount("Item", $amount, $bestadjustment->getAdjuster());
		}

		//work out all cart-level discounts, and load into cartpriceinfo
		$cartpriceinfo = new PriceInfo($this->order->SubTotal());
		foreach($this->getCartDiscounts()as $discount){
			$action = new \SubtotalDiscountAction(
				$this->getDiscountableAmount($discount),
				$discount
			);
			$action->reduceRemaining($this->discountSubtotal($discount));
			$cartpriceinfo->adjustPrice(
				new Adjustment($action->perform(), $discount)
			);
		}

		$cartremainder = $cartpriceinfo->getOriginalPrice() - $total;
		//keep remainder sane, i.e above 0
		$cartremainder = $cartremainder < 0 ? 0 : $cartremainder;

		//select best cart-level disount
		if($bestadjustment = $cartpriceinfo->getBestAdjustment()){
			$discount = $bestadjustment->getAdjuster();
			$amount = $bestadjustment->getValue();
			//don't let amount be greater than remainder
			$amount = $amount > $cartremainder ? $cartremainder : $amount;
			$total += $amount;
			$this->modifier->Discounts()->add(
				$discount,
				array('DiscountAmount' => $amount)
			);
			$this->logDiscountAmount("Cart", $amount, $discount);
		}

		if(class_exists('ShippingFrameworkModifier') && $shipping = $this->order->getModifier("ShippingFrameworkModifier")){
			//work out all shipping-level discounts, and load into shippingpriceinfo
			$shippingpriceinfo = new PriceInfo($shipping->Amount);
			foreach($this->getShippingDiscounts() as $discount){
				$action = new \SubtotalDiscountAction($shipping->Amount, $discount);
				$action->reduceRemaining($this->discountSubtotal($discount));
				$shippingpriceinfo->adjustPrice(
					new Adjustment($action->perform(), $discount)
				);
			}
			//select best shipping-level disount
			if($bestadjustment = $shippingpriceinfo->getBestAdjustment()){
				$discount = $bestadjustment->getAdjuster();
				$amount = $bestadjustment->getValue();
				//don't let amount be greater than remainder
				$total += $amount;
				$this->modifier->Discounts()->add(
					$discount,
					array('DiscountAmount' => $amount)
				);
				$this->logDiscountAmount("Shipping", $amount, $discount);
			}
		}

		return $total;
	}

	/**
	 * Work out the total discountable amount for a given discount
	 */
	protected function getDiscountableAmount($discount){
		$amount = 0;
		foreach($this->order->Items() as $item){
			if(\ItemDiscountConstraint::match($item, $discount)){
				$amount += method_exists($item, "DiscountableAmount") ?
							$item->DiscountableAmount() :
							$item->Total();
			}
		}

		return $amount;
	}

	/**
	 * Work out how much the given discount has already
	 * been used.
	 */
	protected function discountSubtotal($discount) {
		 return $this->modifier->Discounts()
		 			->filter("ID", $discount->ID)
		 			->sum("DiscountAmount");
	}

	protected function createPriceInfoList(\DataList $list) {
		$output = array();
		foreach($list as $item){
			$output[] = new ItemPriceInfo($item);
		}
		return $output;
	}

	protected function getItemDiscounts() {
		return $this->discounts->filter("ForItems", true);
	}

	protected function getCartDiscounts() {
		return $this->discounts->filter("ForCart", true);
	}

	protected function getShippingDiscounts() {
		return $this->discounts->filter("ForShipping", true);
	}

	/**
	 * Store details about discounts for loggging / debubgging
	 * @param  string   $level
	 * @param  double   $amount
	 * @param  Discount $discount
	 */
	public function logDiscountAmount($level, $amount, \Discount $discount) {
		$this->log[] = array(
			"Level" => $level,
			"Amount" => $amount,
			"Discount" => $discount->Title
		);
	}

	public function getLog(){
		return $this->log;
	}

}


text:
package de.halfbit.tinybus.impl;

import junit.framework.TestCase;
import de.halfbit.tinybus.Produce;
import de.halfbit.tinybus.Subscribe;
import de.halfbit.tinybus.TinyBus;
import de.halfbit.tinybus.mocks.Callbacks;
import de.halfbit.tinybus.mocks.Event1;
import de.halfbit.tinybus.mocks.Event2;
import de.halfbit.tinybus.mocks.Event3;

public class RegisterUnregisterInsidePostTest extends TestCase {

	protected class DynamicSubscriber extends Callbacks {
		@Subscribe
		public void onEvent(Event3 event) {
			onCallback(event);
		}
	}

	protected class DynamicProducer extends Callbacks {

		public Event3 lastEvent = new Event3("event3", 76);

		@Subscribe
		public void onEvent(Event1 event) {
			onCallback(event);
		}

		@Produce
		public Event3 getEvent() {
			return lastEvent;
		}
	}

	protected class RegisteringSubscriber extends Callbacks {

		@Subscribe
		public void onEvent(Event1 event) {
			onCallback(event);
			bus.register(dynamicProducer);
		}

		@Subscribe
		public void onEvent(Event2 event) {
			onCallback(event);
			bus.register(dynamicSubscriber);

		}

		@Subscribe
		public void onEvent(Event3 event) {
			onCallback(event);
		}
	}

	protected class SelfUnregisteringProducer extends Callbacks {

		public Event1 lastEvent = new Event1("event1");

		@Subscribe
		public void onEvent2(Event2 event) {
			onCallback(event);
			bus.unregister(this);
		}

		@Produce
		public Event1 getEvent1() {
			return lastEvent;
		}
	}

	protected class SelfUnregisteringSubscriber extends Callbacks {

		@Subscribe
		public void onEvent1(Event1 event) {
			onCallback(event);
			bus.unregister(this);
		}

		@Subscribe
		public void onEvent2(Event2 event) {
			onCallback(event);
		}
	}

	protected class ListeningSubscriber extends Callbacks {

		@Subscribe
		public void onEvent1(Event1 event) {
			onCallback(event);
		}

		@Subscribe
		public void onEvent2(Event2 event) {
			onCallback(event);
		}

		@Subscribe
		public void onEvent3(Event3 event) {
			onCallback(event);
		}
	}

	private TinyBus bus;
	private SelfUnregisteringSubscriber selfUnregisteringSubscriber;
	private SelfUnregisteringProducer selfUnregisteringProducer;
	private ListeningSubscriber listeningSubscriber1;
	private ListeningSubscriber listeningSubscriber2;
	private RegisteringSubscriber registeringSubscriber;
	private DynamicSubscriber dynamicSubscriber;
	private DynamicProducer dynamicProducer;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		bus = new TinyBus();
		listeningSubscriber1 = new ListeningSubscriber();
		listeningSubscriber2 = new ListeningSubscriber();
		selfUnregisteringSubscriber = new SelfUnregisteringSubscriber();
		selfUnregisteringProducer = new SelfUnregisteringProducer();
		registeringSubscriber = new RegisteringSubscriber();
		dynamicSubscriber = new DynamicSubscriber();
		dynamicProducer = new DynamicProducer();
	}

	@Override
	protected void tearDown() throws Exception {
		bus = null;
		listeningSubscriber1 = null;
		listeningSubscriber2 = null;
		selfUnregisteringSubscriber = null;
		selfUnregisteringProducer = null;
		registeringSubscriber = null;
		dynamicSubscriber = null;
		dynamicProducer = null;
		super.tearDown();
	}

	public void testUnregisterSubscriberInsidePost() {
		bus.register(listeningSubscriber1);
		bus.register(selfUnregisteringSubscriber);
		bus.register(listeningSubscriber2);

		Event1 event1 = new Event1("event1");
		Event2 event2 = new Event2(2);
		Event1 event3 = new Event1("event3");

		bus.post(event1);
		bus.post(event2);
		bus.post(event3);

		listeningSubscriber1.assertSameEvents(event1, event2, event3);
		selfUnregisteringSubscriber.assertSameEvents(event1);
		listeningSubscriber1.assertSameEvents(event1, event2, event3);
	}

	public void testUnregisterProducerInsidePost() {
		bus.register(listeningSubscriber1);
		bus.register(selfUnregisteringProducer);

		Event1 event1 = new Event1("event1");
		Event2 event2 = new Event2(2);
		Event1 event3 = new Event1("event3");

		bus.post(event1);
		bus.post(event2);

		bus.register(listeningSubscriber2);
		bus.post(event3);

		listeningSubscriber1.assertSameEvents(selfUnregisteringProducer.lastEvent, event1, event2, event3);
		selfUnregisteringProducer.assertSameEvents(event2);
		listeningSubscriber2.assertSameEvents(event3);
	}

	public void testRegisterSubscriber() {
		bus.register(listeningSubscriber1);
		bus.register(registeringSubscriber);
		bus.register(listeningSubscriber2);

		Event1 event1 = new Event1("event1");
		Event2 event2 = new Event2(2);
		Event3 event3 = new Event3("event3", 3);

		bus.post(event1);
		bus.post(event2);
		bus.post(event3);

		listeningSubscriber1.assertSameEvents(event1, dynamicProducer.lastEvent, event2, event3);
		registeringSubscriber.assertSameEvents(event1, dynamicProducer.lastEvent, event2, event3);
		dynamicProducer.assertNoEvents();
		dynamicSubscriber.assertSameEvents(dynamicProducer.lastEvent, event3);
		listeningSubscriber2.assertSameEvents(event1, dynamicProducer.lastEvent, event2, event3);
	}

}


text:
import numpy as np
from scipy import stats

import utils

def fit(xdata, ydata):
    """Calculate 2D regression.

    Args:
        xdata (numpy.ndarray): 1D array of independent data [ntim],
            where ntim is the number of time points (or other independent
            points).
        ydata (numpy.ndarray): 2D array of dependent data [ntim, nspat],
            where nspat is the number of spatial points (or other dependent
            points).

    Returns:
        numpy.ndarray of dimension [5, nspat].  The 5 outputs are: slope,
        intercept, Pearson's correlation coefficient, two-sided p-value for
        a hypothesis test with null hypothesis that the slope is zero,
        standard error for the slope estimate.

    """
    # Small number to prevent divide-by-zero errors
    TINY = 1.0e-20

    # Dimensions
    ntim = xdata.shape[0]
    nspat = ydata.shape[1]

    # Add a constant (1) to the xdata to allow for intercept calculation
    xdata_plus_const = utils.add_constant(xdata)

    # Calculate parameters of the regression by solving the OLS problem
    # in its matrix form
    mat1 = np.swapaxes(np.dot(xdata_plus_const.T,
                              (xdata_plus_const[np.newaxis, :, :])), 0, 1)
    mat2 = np.dot(xdata_plus_const.T, ydata)
    beta = np.linalg.solve(mat1, mat2.T)
    output = beta.T

    # Pearson correlation coefficient
    xm, ym = xdata-xdata.mean(0), ydata-ydata.mean(0)
    r_num = np.dot(xm, ym)
    r_den = np.sqrt(stats.ss(xm) * stats.ss(ym))
    pearson_r = r_num / r_den

    # Two-sided p-value for a hypothesis test whose null hypothesis is that
    # the slope is zero.
    df = ntim - 2
    tval = pearson_r * np.sqrt(df / ((1.0 - pearson_r + TINY) *
                                     (1.0 + pearson_r + TINY)))
    pval = stats.distributions.t.sf(np.abs(tval), df)*2

    # Standard error of the slope estimate
    sst = np.sum(ym ** 2, 0)
    ssr = (output[0, :] ** 2) * np.sum(xm ** 2)
    se = np.sqrt((1. / df) * (sst - ssr))
    stderr = se / np.sqrt(np.sum(xm ** 2))

    return np.vstack([output, pearson_r, pval, stderr])


text:
#include "Gwen/Controls/CheckBox.h"

using namespace Gwen;
using namespace Gwen::Controls;

GWEN_CONTROL_CONSTRUCTOR( CheckBox )
{
	SetSize( 15, 15 );
	m_bChecked = true;
	Toggle();
}

void CheckBox::Render( Skin::Base* skin )
{
	skin->DrawCheckBox( this, m_bChecked, IsDepressed() );
}

void CheckBox::OnPress()
{
	if ( IsDisabled() )
	{ return; }

	if ( IsChecked() && !AllowUncheck() )
	{ return; }

	Toggle();
}

void CheckBox::OnCheckStatusChanged()
{
	if ( IsChecked() )
	{
		onChecked.Call( this );
	}
	else
	{
		onUnChecked.Call( this );
	}

	onCheckChanged.Call( this );
}

void CheckBox::SetChecked( bool bChecked )
{
	if ( m_bChecked == bChecked ) { return; }

	m_bChecked = bChecked;
	OnCheckStatusChanged();
}


text:
require 'spec_helper'

describe ApiAuth::RequestDrivers::FaradayEnv do
  let(:timestamp) { Time.now.utc.httpdate }

  let(:request) do
    Faraday::Env.new(verb, body, URI(uri), {}, Faraday::Utils::Headers.new(headers))
  end

  let(:verb) { :put }
  let(:uri) { 'https://localhost/resource.xml?foo=bar&bar=foo' }
  let(:body) { "hello\nworld" }

  let(:headers) do
    {
      'Authorization' => 'APIAuth 1044:12345',
      'X-Authorization-Content-SHA256' => '47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=',
      'content-type' => 'text/plain',
      'date' => timestamp
    }
  end

  subject(:driven_request) { described_class.new(request) }

  describe 'getting headers correctly' do
    it 'gets the content_type' do
      expect(driven_request.content_type).to eq('text/plain')
    end

    context 'without Content-Type' do
      let(:headers) { {} }

      it 'defaults to url-encoded' do
        expect(driven_request.content_type).to eq 'application/x-www-form-urlencoded'
      end
    end

    it 'gets the content_hash' do
      expect(driven_request.content_hash).to eq('47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=')
    end

    it 'gets the request_uri' do
      expect(driven_request.request_uri).to eq('/resource.xml?foo=bar&bar=foo')
    end

    it 'gets the timestamp' do
      expect(driven_request.timestamp).to eq(timestamp)
    end

    it 'gets the authorization_header' do
      expect(driven_request.authorization_header).to eq('APIAuth 1044:12345')
    end

    describe '#calculated_hash' do
      it 'calculates hash from the body' do
        expect(driven_request.calculated_hash).to eq('JsYKYdAdtYNspw/v1EpqAWYgQTyO9fJZpsVhLU9507g=')
        expect(driven_request.body.bytesize).to eq(11)
      end

      context 'no body' do
        let(:body) { nil }

        it 'treats no body as empty string' do
          expect(driven_request.calculated_hash).to eq('47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=')
          expect(driven_request.body.bytesize).to eq(0)
        end
      end

      context 'multipart content' do
        let(:body) { File.new('spec/fixtures/upload.png') }

        it 'calculates correctly for multipart content' do
          expect(driven_request.calculated_hash).to eq('AlKDe7kjMQhuKgKuNG8I7GA93MasHcaVJkJLaUT7+dY=')
          expect(driven_request.body.bytesize).to eq(5112)
        end
      end
    end

    describe 'http_method' do
      context 'when put request' do
        let(:verb) { :put }

        it 'returns upcased put' do
          expect(driven_request.http_method).to eq('PUT')
        end
      end

      context 'when get request' do
        let(:verb) { :get }

        it 'returns upcased get' do
          expect(driven_request.http_method).to eq('GET')
        end
      end
    end
  end

  describe 'setting headers correctly' do
    let(:headers) do
      {
        'content-type' => 'text/plain'
      }
    end

    describe '#populate_content_hash' do
      context 'when request type has no body' do
        let(:verb) { :get }

        it "doesn't populate content hash" do
          driven_request.populate_content_hash
          expect(request.request_headers['X-Authorization-Content-SHA256']).to be_nil
        end
      end

      context 'when request type has a body' do
        let(:verb) { :put }

        it 'populates content hash' do
          driven_request.populate_content_hash
          expect(request.request_headers['X-Authorization-Content-SHA256']).to eq('JsYKYdAdtYNspw/v1EpqAWYgQTyO9fJZpsVhLU9507g=')
        end

        it 'refreshes the cached headers' do
          driven_request.populate_content_hash
          expect(driven_request.content_hash).to eq('JsYKYdAdtYNspw/v1EpqAWYgQTyO9fJZpsVhLU9507g=')
        end
      end
    end

    describe '#set_date' do
      before do
        allow(Time).to receive_message_chain(:now, :utc, :httpdate).and_return(timestamp)
      end

      it 'sets the date header of the request' do
        driven_request.set_date
        expect(request.request_headers['DATE']).to eq(timestamp)
      end
    end

    describe '#set_auth_header' do
      it 'sets the auth header' do
        driven_request.set_auth_header('APIAuth 1044:54321')
        expect(request.request_headers['Authorization']).to eq('APIAuth 1044:54321')
      end
    end
  end

  describe 'content_hash_mismatch?' do
    context 'when request type has no body' do
      let(:verb) { :get }

      it 'is false' do
        expect(driven_request.content_hash_mismatch?).to be false
      end
    end

    context 'when request type has a body' do
      let(:verb) { :put }

      context 'when calculated matches sent' do
        before do
          request.request_headers['X-Authorization-Content-SHA256'] = 'JsYKYdAdtYNspw/v1EpqAWYgQTyO9fJZpsVhLU9507g='
        end

        it 'is false' do
          expect(driven_request.content_hash_mismatch?).to be false
        end
      end

      context "when calculated doesn't match sent" do
        before do
          request['X-Authorization-Content-SHA256'] = '3'
        end

        it 'is true' do
          expect(driven_request.content_hash_mismatch?).to be true
        end
      end
    end
  end

  describe 'fetch_headers' do
    it 'returns request headers' do
      expect(driven_request.fetch_headers).to include('CONTENT-TYPE' => 'text/plain')
    end
  end
end


text:
package com.elchris.elrand.items;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;

import com.elchris.elrand.Elrand;
import com.elchris.elrand.init.ElrandItems;

public class ElrandArmor extends ItemArmor{

	public ElrandArmor(String unlocalizedName, ArmorMaterial material, int renderIndex, int armorType) {
        super(material, renderIndex, armorType);

        this.setUnlocalizedName(unlocalizedName);
        this.setCreativeTab(Elrand.tabElrand);
    }

	@Override
	public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) {
		if (player.inventory.armorItemInSlot(3) != null && player.inventory.armorItemInSlot(3).getItem() == ElrandItems.elrand_helmet
		        && player.inventory.armorItemInSlot(2) != null && player.inventory.armorItemInSlot(2).getItem() == ElrandItems.elrand_chestplate
		        && player.inventory.armorItemInSlot(1) != null && player.inventory.armorItemInSlot(1).getItem() == ElrandItems.elrand_leggings
		        && player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(0).getItem() == ElrandItems.elrand_boots) {
		        this.effectPlayer(player, Potion.regeneration, 1);
		        this.effectPlayer(player, Potion.jump, 2);
		        this.effectPlayer(player, Potion.moveSpeed, 2);
		        this.effectPlayer(player, Potion.damageBoost, 2);
		}
	}

	private void effectPlayer(EntityPlayer player, Potion potion, int amplifier) {
	    //Always effect for 8 seconds, then refresh
	    if (player.getActivePotionEffect(potion) == null || player.getActivePotionEffect(potion).getDuration() <= 1)
	        player.addPotionEffect(new PotionEffect(potion.id, 159, amplifier, true, true));
	}
}


text:
package net.firejack.platform.service.securitymanager.broker;

import net.firejack.platform.api.securitymanager.domain.SecuredRecord;
import net.firejack.platform.core.broker.ServiceBroker;
import net.firejack.platform.core.domain.IdLookup;
import net.firejack.platform.core.domain.NamedValues;
import net.firejack.platform.core.exception.ObjectNotFoundException;
import net.firejack.platform.core.model.registry.RegistryNodeModel;
import net.firejack.platform.core.model.registry.authority.SecuredRecordModel;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import net.firejack.platform.core.store.registry.IRegistryNodeStore;
import net.firejack.platform.core.store.registry.ISecuredRecordStore;
import net.firejack.platform.core.store.registry.helper.SecuredRecordPathHelper;
import net.firejack.platform.core.utils.StringUtils;
import net.firejack.platform.web.statistics.annotation.TrackDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@TrackDetails
@Component("moveSecuredRecordBroker")
public class MoveSecuredRecordBroker extends ServiceBroker
        <ServiceRequest<NamedValues>, ServiceResponse<SecuredRecord>> {

    public static final String PARAM_ENTITY_ID = "entityId";
    public static final String PARAM_ENTITY_LOOKUP = "entityLookup";
    public static final String PARAM_PARENT_ID = "parentId";
    public static final String PARAM_PARENT_LOOKUP = "parentLookup";
    public static final String PARAM_OLD_PARENTS = "oldParents";

    @Autowired
    @Qualifier("registryNodeStore")
    private IRegistryNodeStore<RegistryNodeModel> registryNodeStore;

    @Autowired
    @Qualifier("securedRecordStore")
    private ISecuredRecordStore store;

    @Autowired
    @Qualifier("securedRecordPathHelper")
    private SecuredRecordPathHelper securedRecordPathHelper;

    @Override
    protected ServiceResponse<SecuredRecord> perform(ServiceRequest<NamedValues> request)
		    throws Exception {
        Long entityId = (Long) request.getData().get(PARAM_ENTITY_ID);
        String entityLookup = (String) request.getData().get(PARAM_ENTITY_LOOKUP);
        Long parentId = (Long) request.getData().get(PARAM_PARENT_ID);
        String parentLookup = (String) request.getData().get(PARAM_PARENT_LOOKUP);
        IdLookup[] oldParents = (IdLookup[]) request.getData().get(PARAM_OLD_PARENTS);

        //MoveEntityDataVO vo = message.getVO();
        RegistryNodeModel registryNode = registryNodeStore.findByLookup(entityLookup);

        SecuredRecordModel parentSecuredRecord = null;
        if (StringUtils.isNotBlank(parentLookup)) {
            RegistryNodeModel parentRegistryNode = registryNodeStore.findByLookup(parentLookup);
            if (parentRegistryNode != null) {
                parentSecuredRecord = store.findByExternalIdAndRegistryNode(parentId, parentRegistryNode);
            } else {
                throw new ObjectNotFoundException();
            }
        }

        SecuredRecordModel securedRecord = store.findByExternalIdAndRegistryNode(entityId, registryNode);
        if (securedRecord == null) {
            throw new ObjectNotFoundException();
        }

        for (IdLookup idLookup: oldParents) {
            Long oldParentId = idLookup.getId();
            String oldParentLookup = idLookup.getLookup();

            SecuredRecordModel oldParentSecuredRecord;

            RegistryNodeModel oldParentRegistryNode = registryNodeStore.findByLookup(oldParentLookup);
            if (oldParentRegistryNode != null) {
                oldParentSecuredRecord =
                        store.findByExternalIdAndRegistryNode(oldParentId, oldParentRegistryNode);

                if (oldParentSecuredRecord != null) {
                    String paths = securedRecordPathHelper.removeIdFromPaths(
                            securedRecord.getPaths(), oldParentSecuredRecord);
                    securedRecord.setPaths(paths);

                    securedRecord.removeParentSecuredRecords(oldParentSecuredRecord);
                }
            } else {
                throw new ObjectNotFoundException();
            }
        }

//        if (securedRecord != null && parentSecuredRecord != null && oldParentSecuredRecord != null) {
//            String paths = securedRecordPathHelper.switchPathToPaths(
//                    securedRecord.getPaths(), parentSecuredRecord, oldParentSecuredRecord);
//            securedRecord.setPaths(paths);
//        } else {
//            throw new ObjectNotFoundException();
//        }
//
//        securedRecord.removeParentSecuredRecords(oldParentSecuredRecord);

        if (parentSecuredRecord != null) {
            String paths = securedRecordPathHelper.addIdToPaths(securedRecord.getPaths(), parentSecuredRecord);
            securedRecord.setPaths(paths);
            securedRecord.addParentSecuredRecords(parentSecuredRecord);
        }

        store.saveOrUpdateRecursive(securedRecord);

        if (securedRecord.getRegistryNode() != null) {
            securedRecord.getRegistryNode().setParent(null);
        }
        securedRecord.setParentSecuredRecords(null);

        SecuredRecord securedRecordForClient =
                this.factory.convertTo(SecuredRecord.class, securedRecord);
        return new ServiceResponse<SecuredRecord>(
                securedRecordForClient, "Secured record has created successfully", true);
    }

}


text:
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/67f0a9e168b3457385f2f7fcd09a9afa)](https://www.codacy.com/app/vecseigabor.x/Color-Tracker?utm_source=github.com&utm_medium=referral&utm_content=gaborvecsei/Color-Tracker&utm_campaign=Badge_Grade)
[![PyPI version](https://badge.fury.io/py/color-tracker.svg)](https://badge.fury.io/py/color-tracker)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3](https://img.shields.io/badge/Python-3-brightgreen.svg)](https://www.python.org/downloads/)
[![DOI](https://zenodo.org/badge/101786270.svg)](https://zenodo.org/badge/latestdoi/101786270)

# Color Tracker - Multi Object Tracker

Easy to use **multi object tracking** package based on colors :art:

## Install

```
pip install color-tracker
```

```
pip install git+https://github.com/gaborvecsei/Color-Tracker.git
```

## Object Tracker

- Check out the **[examples folder](examples)**, or go straight to the **[sample tracking app](examples/tracking.py)** which is an extended version of the script below.
This script tracks the red-ish objects, if you'd like to track another color, then start with the `hsv_color_detector.py` script
    ``` python
    $ python examples/tracking.py --help

    usage: tracking.py [-h] [-low LOW LOW LOW] [-high HIGH HIGH HIGH]
                   [-c CONTOUR_AREA] [-v]

    optional arguments:
      -h, --help            show this help message and exit
      -low LOW LOW LOW, --low LOW LOW LOW
                            Lower value for the HSV range. Default = 155, 103, 82
      -high HIGH HIGH HIGH, --high HIGH HIGH HIGH
                            Higher value for the HSV range. Default = 178, 255,
                            255
      -c CONTOUR_AREA, --contour-area CONTOUR_AREA
                            Minimum object contour area. This controls how small
                            objects should be detected. Default = 2500
      -v, --verbose
    ```
- Simple script:

    ``` python
    import cv2
    import color_tracker

    def tracker_callback(t: color_tracker.ColorTracker):
        cv2.imshow("debug", t.debug_frame)
        cv2.waitKey(1)

    tracker = color_tracker.ColorTracker(max_nb_of_objects=1, max_nb_of_points=20, debug=True)
    tracker.set_tracking_callback(tracker_callback)

    with color_tracker.WebCamera() as cam:
        # Define your custom Lower and Upper HSV values
        tracker.track(cam, [155, 103, 82], [178, 255, 255], max_skipped_frames=24)
    ```

## Color Range Detection

This is a tool which you can use to easily determine the necessary *HSV* color values and kernel sizes for you app

You can find **[the HSV Color Detector code here](examples/hsv_color_detector.py)**

``` python
python examples/hsv_color_detector.py
```

## Donate :coffee:

If you feel like it is a **useful package** and it **saved you time and effor**, then you can donate a coffe for me, so I can keep on staying awake for days :smiley:

## About

Gábor Vecsei

- [Website](https://gaborvecsei.com)
- [Personal Blog](https://gaborvecsei.com)
- [LinkedIn](https://www.linkedin.com/in/gaborvecsei)
- [Twitter](https://twitter.com/GAwesomeBE)
- [Github](https://github.com/gaborvecsei)

```
@misc{vecsei2018colortracker,
      doi = {10.5281/ZENODO.4097717},
      howpublished={\url{https://github.com/gaborvecsei/Color-Tracker}},
      author = {Gabor Vecsei},
      title = {Color Tracker - Multi Object Tracker},
      year = {2018},
      copyright = {MIT License}
}
```


text:
package org.apache.cassandra.exceptions;

import java.util.HashMap;
import java.util.Map;

import org.apache.cassandra.transport.ProtocolException;
import org.apache.cassandra.utils.Shared;

import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;

/**
 * Exceptions code, as defined by the binary protocol.
 */
@Shared(scope = SIMULATION)
public enum ExceptionCode
{
    SERVER_ERROR    (0x0000),
    PROTOCOL_ERROR  (0x000A),

    BAD_CREDENTIALS (0x0100),

    // 1xx: problem during request execution
    UNAVAILABLE         (0x1000),
    OVERLOADED          (0x1001),
    IS_BOOTSTRAPPING    (0x1002),
    TRUNCATE_ERROR      (0x1003),
    WRITE_TIMEOUT       (0x1100),
    READ_TIMEOUT        (0x1200),
    READ_FAILURE        (0x1300),
    FUNCTION_FAILURE    (0x1400),
    WRITE_FAILURE       (0x1500),
    CDC_WRITE_FAILURE   (0x1600),
    CAS_WRITE_UNKNOWN   (0x1700),

    // 2xx: problem validating the request
    SYNTAX_ERROR    (0x2000),
    UNAUTHORIZED    (0x2100),
    INVALID         (0x2200),
    CONFIG_ERROR    (0x2300),
    ALREADY_EXISTS  (0x2400),
    UNPREPARED      (0x2500);

    public final int value;
    private static final Map<Integer, ExceptionCode> valueToCode = new HashMap<>(ExceptionCode.values().length);
    static
    {
        for (ExceptionCode code : ExceptionCode.values())
            valueToCode.put(code.value, code);
    }

    ExceptionCode(int value)
    {
        this.value = value;
    }

    public static ExceptionCode fromValue(int value)
    {
        ExceptionCode code = valueToCode.get(value);
        if (code == null)
            throw new ProtocolException(String.format("Unknown error code %d", value));
        return code;
    }
}