text:
<!DOCTYPE html>

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

<link rel="shortcut icon" type="image/x-icon" href="../../favicon.ico" />
<title>Retrieving the Current Location | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../assets/css/default.css" rel="stylesheet" type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../')"
onkeyup="return search_changed(event, false, '../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

        Getting Started

          Building Your First App

            Creating an Android Project

            Running Your Application

            Building a Simple User Interface

            Starting Another Activity

          Adding the Action Bar

            Setting Up the Action Bar

            Adding Action Buttons

            Styling the Action Bar

            Overlaying the Action Bar

          Supporting Different Devices

            Supporting Different Languages

            Supporting Different Screens

            Supporting Different Platform Versions

          Managing the Activity Lifecycle

            Starting an Activity

            Pausing and Resuming an Activity

            Stopping and Restarting an Activity

            Recreating an Activity

          Building a Dynamic UI with Fragments

            Creating a Fragment

            Building a Flexible UI

            Communicating with Other Fragments

Saving Data

            Saving Key-Value Sets

            Saving Files

            Saving Data in SQL Databases

          Interacting with Other Apps

            Sending the User to Another App

            Getting a Result from the Activity

            Allowing Other Apps to Start Your Activity

            Building Apps with
Content Sharing

                    Sharing Simple Data

                        Sending Simple Data to Other Apps

                        Receiving Simple Data from Other Apps

                        Adding an Easy Share Action

                    Sharing Files

                        Setting Up File Sharing

                        Sharing a File

                        Requesting a Shared File

                        Retrieving File Information

                    Sharing Files with NFC

                        Sending Files to Another Device

Receiving Files from Another Device

      Building Apps with
Multimedia

          Managing Audio Playback

            Controlling Your App's Volume and Playback

            Managing Audio Focus

            Dealing with Audio Output Hardware

          Capturing Photos

            Taking Photos Simply

            Recording Videos Simply

            Controlling the Camera

          Printing Content

            Photos

            HTML Documents

            Custom Documents

      Building Apps with
Graphics & Animation

          Displaying Bitmaps Efficiently

            Loading Large Bitmaps Efficiently

            Processing Bitmaps Off the UI Thread

            Caching Bitmaps

            Managing Bitmap Memory

            Displaying Bitmaps in Your UI

          Displaying Graphics with OpenGL ES

            Building an OpenGL ES Environment

            Defining Shapes

            Drawing Shapes

            Applying Projection and Camera Views

            Adding Motion

            Responding to Touch Events

            Adding Animations

            Crossfading Two Views

            Using ViewPager for Screen Slide

            Displaying Card Flip Animations

            Zooming a View

            Animating Layout Changes

      Building Apps with

              Connectivity & the Cloud

          Connecting Devices Wirelessly

            Using Network Service Discovery

            Creating P2P Connections with Wi-Fi

            Using Wi-Fi P2P for Service Discovery

          Performing Network Operations

            Connecting to the Network

            Managing Network Usage

            Parsing XML Data

          Transferring Data Without Draining the Battery

            Optimizing Downloads for Efficient Network Access

            Minimizing the Effect of Regular Updates

            Redundant Downloads are Redundant

            Modifying Patterns Based on the Connectivity Type

          Syncing to the Cloud

            Using the Backup API

            Making the Most of Google Cloud Messaging

Resolving Cloud Save Conflicts

          Transferring Data Using Sync Adapters

                Creating a Stub Authenticator

                Creating a Stub Content Provider

                Creating a Sync Adapter

                Running a Sync Adapter

      Building Apps with

              User Info & Location

          Accessing Contacts Data

                Retrieving a List of Contacts

                Retrieving Details for a Contact

                Modifying Contacts Using Intents

                Displaying the Quick Contact Badge

             Making Your App Location-Aware

            Retrieving the Current Location

            Receiving Location Updates

            Displaying a Location Address

            Creating and Monitoring Geofences

          Recognizing the User's Current Activity

          Testing Using Mock Locations

      Best Practices for

              User Experience & UI

          Designing Effective Navigation

            Planning Screens and Their Relationships

            Planning for Multiple Touchscreen Sizes

            Providing Descendant and Lateral Navigation

            Providing Ancestral and Temporal Navigation

            Putting it All Together: Wireframing the Example App

          Implementing Effective Navigation

            Creating Swipe Views with Tabs

            Creating a Navigation Drawer

            Providing Up Navigation

            Providing Proper Back Navigation

            Implementing Descendant Navigation

              Notifying the User

                  Building a Notification

                  Preserving Navigation when Starting an Activity

                  Updating Notifications

                  Using Big View Styles

                  Displaying Progress in a Notification

          Adding Search Functionality

            Setting up the Search Interface

            Storing and Searching for Data

            Remaining Backward Compatible

          Designing for Multiple Screens

Supporting Different Screen Sizes

Supporting Different Screen Densities

Implementing Adaptive UI Flows

Designing for TV

            Optimizing Layouts for TV

            Optimizing Navigation for TV

            Handling Features Not Supported on TV

          Creating Custom Views

            Creating a Custom View Class

            Implementing Custom Drawing

            Making the View Interactive

            Optimizing the View

          Creating Backward-Compatible UIs

            Abstracting the New APIs

            Proxying to the New APIs

            Creating an Implementation with Older APIs

            Using the Version-Aware Component

          Implementing Accessibility

            Developing Accessible Applications

            Developing Accessibility Services

          Managing the System UI

            Dimming the System Bars

            Hiding the Status Bar

            Hiding the Navigation Bar

            Responding to UI Visibility Changes

      Best Practices for

              User Input

          Using Touch Gestures

            Detecting Common Gestures

            Tracking Movement

            Animating a Scroll Gesture

            Handling Multi-Touch Gestures

            Dragging and Scaling

            Managing Touch Events in a ViewGroup

          Handling Keyboard Input

            Specifying the Input Method Type

            Handling Input Method Visibility

            Supporting Keyboard Navigation

            Handling Keyboard Actions

      Best Practices for

              Background Jobs

          Running in a Background Service

            Creating a Background Service

            Sending Work Requests to the Background Service

            Reporting Work Status

          Loading Data in the Background

            Running a Query with a CursorLoader

            Handling the Results

          Managing Device Awake State

            Keeping the Device Awake

            Scheduling Repeating Alarms

      Best Practices for

              Performance

        Managing Your App's Memory

        Performance Tips

          Improving Layout Performance

            Optimizing Layout Hierarchies

            Re-using Layouts with <include/>

            Loading Views On Demand

            Making ListView Scrolling Smooth

          Optimizing Battery Life

Monitoring the Battery Level and Charging State

Determining and Monitoring the Docking State and Type

Determining and Monitoring the Connectivity Status

Manipulating Broadcast Receivers On Demand

             Sending Operations to Multiple Threads

            Specifying the Code to Run on a Thread

            Creating a Manager for Multiple Threads

            Running Code on a Thread Pool Thread

            Communicating with the UI Thread

        Keeping Your App Responsive

        JNI Tips

        SMP Primer for Android

      Best Practices for

              Security & Privacy

        Security Tips

        Security with HTTPS and SSL

          Developing for Enterprise

            Enhancing Security with Device Management Policies

      Best Practices for

              Testing

            Testing Your Activity

            Setting Up Your Test Environment

            Creating and Running a Test Case

            Testing UI Components

            Creating Unit Tests

            Creating Functional Tests

      Using Google Play to

              Distribute & Monetize

            Selling In-app Products

            Preparing Your App

            Establishing Products for Sale

            Purchasing Products

            Testing Your App

          Maintaining Multiple APKs

            Creating Multiple APKs for Different API Levels

            Creating Multiple APKs for Different Screen Sizes

            Creating Multiple APKs for Different GL Textures

            Creating Multiple APKs with 2+ Dimensions

          Monetizing Your App

            Advertising without Compromising User Experience

Retrieving the Current Location

        Previous
        Next
        Get started

This lesson teaches you to

Specify App Permissions

Check for Google Play services

Define Location Services Callbacks

Connect the Location Client

Get the Current Location

You should also read

        Setup Google Play Services SDK

Try it out

  Download the sample

LocationUpdates.zip

    Location Services automatically maintains the user's current location, so all your app has to do
    is retrieve it as needed. The location's accuracy is based on the location permissions you've
    requested and location sensors that are currently active for the device.

    Location Services sends the current location to your app through a location client, which is
    an instance of the Location Services class
LocationClient.
    All requests for location information go through this client.

    Note: Before you start the lesson, be sure that your development environment
    and test device are set up correctly. To learn more about this, read the
    Setup section in the Google Play
    services guide.

Specify App Permissions

    Apps that use Location Services must request location permissions. Android has two location
    permissions: ACCESS_COARSE_LOCATION
    and ACCESS_FINE_LOCATION. The
    permission you choose controls the accuracy of the current location. If you request only coarse
    location permission, Location Services obfuscates the returned location to an accuracy
    that's roughly equivalent to a city block.

    Requesting ACCESS_FINE_LOCATION implies
    a request for ACCESS_COARSE_LOCATION.

    For example, to add ACCESS_COARSE_LOCATION, insert the following as a child element of the
    <manifest>
    element:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Check for Google Play Services

    Location Services is part of the Google Play services APK. Since it's hard to anticipate the
    state of the user's device, you should always check that the APK is installed before you attempt
    to connect to Location Services. To check that the APK is installed, call
GooglePlayServicesUtil.isGooglePlayServicesAvailable(),
    which returns one of the
    integer result codes listed in the reference documentation for
ConnectionResult.
    If you encounter an error, call
GooglePlayServicesUtil.getErrorDialog()
    to retrieve localized dialog that prompts users to take the correct action, then display
    the dialog in a DialogFragment. The dialog may allow the
    user to correct the problem, in which case Google Play services may send a result back to your
    activity. To handle this result, override the method
    onActivityResult().

    Since you usually need to check for Google Play services in more than one place in your code,
    define a method that encapsulates the check, then call the method before each connection
    attempt. The following snippet contains all of the code required to check for Google
    Play services:

public class MainActivity extends FragmentActivity {
    ...
    // Global constants
    /*
     * Define a request code to send to Google Play services
     * This code is returned in Activity.onActivityResult
     */
    private final static int
            CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    ...
    // Define a DialogFragment that displays the error dialog
    public static class ErrorDialogFragment extends DialogFragment {
        // Global field to contain the error dialog
        private Dialog mDialog;
        // Default constructor. Sets the dialog field to null
        public ErrorDialogFragment() {
            super();
            mDialog = null;
        }
        // Set the dialog to display
        public void setDialog(Dialog dialog) {
            mDialog = dialog;
        }
        // Return a Dialog to the DialogFragment.
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            return mDialog;
        }
    }
    ...
    /*
     * Handle results returned to the FragmentActivity
     * by Google Play services
     */
    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        // Decide what to do based on the original request code
        switch (requestCode) {
            ...
            case CONNECTION_FAILURE_RESOLUTION_REQUEST :
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
                switch (resultCode) {
                    case Activity.RESULT_OK :
                    /*
                     * Try the request again
                     */
                    ...
                    break;
                }
            ...
        }
     }
    ...
    private boolean servicesConnected() {
        // Check that Google Play services is available
        int resultCode =
                GooglePlayServicesUtil.
                        isGooglePlayServicesAvailable(this);
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d("Location Updates",
                    "Google Play services is available.");
            // Continue
            return true;
        // Google Play services was not available for some reason
        } else {
            // Get the error code
            int errorCode = connectionResult.getErrorCode();
            // Get the error dialog from Google Play services
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                    errorCode,
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);

            // If Google Play services can provide an error dialog
            if (errorDialog != null) {
                // Create a new DialogFragment for the error dialog
                ErrorDialogFragment errorFragment =
                        new ErrorDialogFragment();
                // Set the dialog in the DialogFragment
                errorFragment.setDialog(errorDialog);
                // Show the error dialog in the DialogFragment
                errorFragment.show(getSupportFragmentManager(),
                        "Location Updates");
            }
        }
    }
    ...
}

    Snippets in the following sections call this method to verify that Google Play services is
    available.

Define Location Services Callbacks

    To get the current location, create a location client, connect it
    to Location Services, and then call its
getLastLocation()
    method. The return value  is the best, most recent location, based on the permissions your
    app requested and the currently-enabled location sensors.

    Before you create the location client, implement the interfaces that Location Services uses to
    communicate with your app:

ConnectionCallbacks

        Specifies methods that Location Services calls when a location client is connected or
        disconnected.

OnConnectionFailedListener

        Specifies a method that Location Services calls if an error occurs while attempting to
        connect the location client. This method uses the previously-defined showErrorDialog
        method to display an error dialog that attempts to fix the problem using Google Play
        services.

    The following snippet shows how to specify the interfaces and define the methods:

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    ...
    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle dataBundle) {
        // Display the connection status
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();

    }
    ...
    /*
     * Called by Location Services if the connection to the
     * location client drops because of an error.
     */
    @Override
    public void onDisconnected() {
        // Display the connection status
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }
    ...
    /*
     * Called by Location Services if the attempt to
     * Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        this,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            showErrorDialog(connectionResult.getErrorCode());
        }
    }
    ...
}

Connect the Location Client

    Now that the callback methods are in place, create the location client and connect it to
    Location Services.

    You should create the location client in onCreate(), then connect it in
    onStart(), so that Location Services
    maintains the current location while your activity is fully visible. Disconnect the client in
    onStop(), so that when your app is not
    visible, Location Services is not maintaining the current location. Following this pattern of
    connection and disconnection helps save battery power. For example:

    Note: The current location is only maintained while a location client is
    connected to Location Service. Assuming that no other apps are connected to Location Services,
    if you disconnect the client and then sometime later call
getLastLocation(),
    the result may be out of date.

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(this, this, this);
        ...
    }
    ...
    /*
     * Called when the Activity becomes visible.
     */
    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mLocationClient.connect();
    }
    ...
    /*
     * Called when the Activity is no longer visible.
     */
    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mLocationClient.disconnect();
        super.onStop();
    }
    ...
}

Get the Current Location

    To get the current location, call
getLastLocation().
    For example:

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    ...
    // Global variable to hold the current location
    Location mCurrentLocation;
    ...
    mCurrentLocation = mLocationClient.getLastLocation();
    ...
}

    The next lesson, Receiving Location Updates, shows
    you how to receive periodic location updates from Location Services.

            Previous
            Next

          Next class:

  Except as noted, this content is
  licensed under
  Creative Commons Attribution 2.5. For details and
  restrictions, see the Content
  License.

    About Android  |
    Legal  |
    Support


text:
package eu.qualimaster.families.imp;

import eu.qualimaster.families.inf.*;
import eu.qualimaster.observables.IObservable;
import eu.qualimaster.dataManagement.serialization.SerializerRegistry;

/**
 * The implementation for the algorithm family "IFTwitterEventDetection" (GEN).
 */
public class FTwitterEventDetection implements IFTwitterEventDetection {

    /**
     * Provides a default implementation of the data input for the {@link IFTwitterEventDetectionTwitterStreamInput} algorithm.
     * Actual execution system code may also directly wrap the respective tuple concept.
     */
    public static class IFTwitterEventDetectionTwitterStreamInput implements IIFTwitterEventDetectionTwitterStreamInput {

        private Object status;
        private Object stocks;

        @Override
        public Object getStatus(){
            return status;
        }

        @Override
        public void setStatus(Object status){
            this.status = status;
        }
        @Override
        public Object getStocks(){
            return stocks;
        }

        @Override
        public void setStocks(Object stocks){
            this.stocks = stocks;
        }
        static {
            SerializerRegistry.register("IFTwitterEventDetectionTwitterStreamInput", FTwitterEventDetectionSerializers.IFTwitterEventDetectionTwitterStreamInputSerializer.class);
        }
    }

    /**
     * Provides a default implementation of the data output for the {@link IFTwitterEventDetectionTwitterStreamOutput} algorithm.
     * Actual execution system code may also directly wrap the respective tuple concept.
     */
    public static class IFTwitterEventDetectionTwitterStreamOutput extends eu.qualimaster.base.algorithm.AbstractOutputItem<IIFTwitterEventDetectionTwitterStreamOutput> implements IIFTwitterEventDetectionTwitterStreamOutput {

        /**
         * Creates the item.
         */
        public IFTwitterEventDetectionTwitterStreamOutput() {
            this(true);
        }

        /**
         * Creates a sub-item.
         *
         * @param topLevel whether it is a top-level item
         */
        private IFTwitterEventDetectionTwitterStreamOutput(boolean topLevel) {
            super(topLevel);
            setParent(this);
        }

        @Override
        protected IFTwitterEventDetectionTwitterStreamOutput createItem() {
            return new IFTwitterEventDetectionTwitterStreamOutput(false);
        }
        private java.util.List<eu.qualimaster.families.datatypes.events.IFEvent> events;
        private Object status;

        @Override
        public java.util.List<eu.qualimaster.families.datatypes.events.IFEvent> getEvents(){
            return events;
        }

        @Override
        public void setEvents(java.util.List<eu.qualimaster.families.datatypes.events.IFEvent> events){
            this.events = events;
        }
        @Override
        public Object getStatus(){
            return status;
        }

        @Override
        public void setStatus(Object status){
            this.status = status;
        }
        static {
            SerializerRegistry.register("IFTwitterEventDetectionTwitterStreamOutput", FTwitterEventDetectionSerializers.IFTwitterEventDetectionTwitterStreamOutputSerializer.class);
        }
    }

    /**
     * Calculates the actual result for input.
     *
     * @param input the algorithm input taken from the input stream
     * @param result the result calculated by the algorithm
     */
    @Override
    public void calculate(IIFTwitterEventDetectionTwitterStreamInput input, IIFTwitterEventDetectionTwitterStreamOutput result){
    }

    /**
     * Sets the algorithm parameter "hardThreshold".
     *
     * @param value the new value of the algorithm parameter
     */
    public void setParameterHardThreshold(int value) {
    }

    /**
     * Sets the algorithm parameter "percentageThreshold".
     *
     * @param value the new value of the algorithm parameter
     */
    public void setParameterPercentageThreshold(double value) {
    }

    /**
     * Sets the algorithm parameter "lengthOfTimeWindow".
     *
     * @param value the new value of the algorithm parameter
     */
    public void setParameterLengthOfTimeWindow(int value) {
    }

    /**
     * Sets the algorithm parameter "frequenceOfCheckForEvent".
     *
     * @param value the new value of the algorithm parameter
     */
    public void setParameterFrequenceOfCheckForEvent(int value) {
    }

    @Override
    public void switchState(State arg0) {
    }

    @Override
    public Double getMeasurement(IObservable arg0) {
	    return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace ProcessWire\GraphQL\Test\Permissions\Superuser\Create\NotAvaliable;

use ProcessWire\GraphQL\Test\GraphqlTestCase;

class ParentTemplateNoChildrenTest extends GraphqlTestCase
{
  /**
   * + For superuser.
   * + The template is legal.
   * + All the required fields are legal.
   * + The configured parent template is legal.
   * - But the configured parent template has noChildren checked.
   */
  const settings = [
    "login" => "admin",
    "legalTemplates" => ["city", "skyscraper"],
    "legalFields" => ["title"],
    "access" => [
      "templates" => [
        [
          "name" => "city",
          "noChildren" => 1,
        ],
      ],
    ],
  ];

  public function testPermission()
  {
    assertTypePathNotExists(
      ["Mutation", "createSkyscraper"],
      "Create field should not be available if configured parent template has noChildren checked."
    );
  }
}


text:
Essential Reading
=================

* `The TTY demystified <http://www.linusakesson.net/programming/tty/>`_


text:
package org.apache.oozie.util.db;

import java.util.HashSet;
import java.util.Set;

import com.google.common.base.Predicate;

public abstract class DatabaseRetryPredicate implements Predicate<Throwable> {

    @Override
    public abstract boolean apply(Throwable input);

    /*
     * Helper method for subclasses to retrieve all exceptions in a set. "All exceptions" means the exception
     * hierarchy that can be walked by calling getCause() repeatedly.
     *
     * Subclasses either check if a particular exception was raised or not, or need the SQLException to extract the
     * error code. In both cases the exception has to be found.
     */
    protected Set<Class<?>> getAllExceptions(final Throwable t) {
        final Set<Class<?>> exceptions = new HashSet<>();

        exceptions.add(t.getClass());

        Throwable ex = t;
        while (ex.getCause() != null) {
            exceptions.add(ex.getCause().getClass());
            ex = ex.getCause();
        }

        return exceptions;
    }
}


text:
namespace Azure.ResourceManager.Monitor.Models
{
    /// <summary> Settings for text log files. </summary>
    internal partial class LogFileTextSettings
    {
        /// <summary> Initializes a new instance of LogFileTextSettings. </summary>
        /// <param name="recordStartTimestampFormat"> One of the supported timestamp formats. </param>
        public LogFileTextSettings(LogFileTextSettingsRecordStartTimestampFormat recordStartTimestampFormat)
        {
            RecordStartTimestampFormat = recordStartTimestampFormat;
        }

        /// <summary> One of the supported timestamp formats. </summary>
        public LogFileTextSettingsRecordStartTimestampFormat RecordStartTimestampFormat { get; set; }
    }
}


text:
package com.hazelcast.client.impl.spi.impl;

import com.hazelcast.client.config.ClientNetworkConfig;
import com.hazelcast.client.impl.connection.AddressProvider;
import com.hazelcast.client.properties.ClientProperty;
import com.hazelcast.cluster.Address;
import com.hazelcast.config.SSLConfig;
import com.hazelcast.instance.EndpointQualifier;
import com.hazelcast.instance.ProtocolType;
import com.hazelcast.internal.cluster.MemberInfo;
import com.hazelcast.internal.util.AddressUtil;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.properties.HazelcastProperties;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

class TranslateToPublicAddressProvider {
    private static final int REACHABLE_ADDRESS_TIMEOUT_MILLIS = 1000;
    private static final int NON_REACHABLE_ADDRESS_TIMEOUT_MILLIS = 3000;
    private static final int REACHABLE_CHECK_NUMBER = 3;
    private static final EndpointQualifier CLIENT_PUBLIC_ENDPOINT_QUALIFIER =
            EndpointQualifier.resolve(ProtocolType.CLIENT, "public");
    private final ClientNetworkConfig config;
    private final HazelcastProperties properties;
    private final ILogger logger;

    private volatile boolean translateToPublicAddress;

    TranslateToPublicAddressProvider(ClientNetworkConfig config, HazelcastProperties properties, ILogger logger) {
        this.config = config;
        this.properties = properties;
        this.logger = logger;
    }

    void refresh(AddressProvider addressProvider, Collection<MemberInfo> members) {
        translateToPublicAddress = resolve(addressProvider, members);
    }

    private boolean resolve(AddressProvider addressProvider, Collection<MemberInfo> members) {
        if (!(addressProvider instanceof DefaultAddressProvider)) {
            return false;
        }

        // Default value of DISCOVERY_SPI_PUBLIC_IP_ENABLED is `null` intentionally.
        // If DISCOVERY_SPI_PUBLIC_IP_ENABLED is not set to true/false, we don't know the intention of the user,
        // we will try to decide if we should use private/public address automatically in that case.
        String publicIpEnabledProperty = properties.getString(ClientProperty.DISCOVERY_SPI_PUBLIC_IP_ENABLED);
        if (publicIpEnabledProperty == null) {
            SSLConfig sslConfig = config.getSSLConfig();
            if (sslConfig != null && sslConfig.isEnabled()) {
                if (logger.isFineEnabled()) {
                    logger.fine("SSL is configured. The client will use internal addresses to communicate with the cluster. If "
                            + "members are not reachable via private addresses, "
                            + "please set \"hazelcast.discovery.public.ip.enabled\" to true ");
                }
                return false;
            }

            if (memberInternalAddressAsDefinedInClientConfig(members)) {
                if (logger.isFineEnabled()) {
                    logger.fine("There are internal addresses of members used in the config."
                            + " The client will use internal addresses");
                }
                return false;
            }

            return membersReachableOnlyViaPublicAddress(members);
        }
        return properties.getBoolean(ClientProperty.DISCOVERY_SPI_PUBLIC_IP_ENABLED);
    }

    /**
     * Checks if any member has its internal address as configured in ClientConfig.
     *

     * If any member has its internal/private address the same as configured in ClientConfig, then it means that the client is
     * able to connect to members via configured address. No need to use make any address translation.
     */
    boolean memberInternalAddressAsDefinedInClientConfig(Collection<MemberInfo> members) {
        List<String> addresses = config.getAddresses();
        List<String> resolvedHosts = addresses.stream().map(s -> {
            try {
                return InetAddress.getByName(AddressUtil.getAddressHolder(s, -1).getAddress()).getHostAddress();
            } catch (UnknownHostException e) {
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return members.stream()
                .map(memberInfo -> {
                    try {
                        return memberInfo.getAddress().getInetAddress().getHostAddress();
                    } catch (UnknownHostException e) {
                        return null;
                    }
                }).anyMatch(resolvedHosts::contains);
    }

    /**
     * Checks if members are reachable via public addresses, but not reachable via internal addresses.
     *

     * We check only limited number of random members to reduce the slowdown of the startup.
     */
    private boolean membersReachableOnlyViaPublicAddress(Collection<MemberInfo> members) {
        List<MemberInfo> shuffledList = new ArrayList<>(members);
        Collections.shuffle(shuffledList);
        Iterator<MemberInfo> iter = shuffledList.iterator();
        for (int i = 0; i < REACHABLE_CHECK_NUMBER; i++) {
            if (!iter.hasNext()) {
                iter = shuffledList.iterator();
            }
            MemberInfo member = iter.next();
            Address publicAddress = member.getAddressMap().get(CLIENT_PUBLIC_ENDPOINT_QUALIFIER);
            Address internalAddress = member.getAddress();
            if (publicAddress == null) {
                if (logger.isFineEnabled()) {
                    logger.fine("The public address is not available on the member. The client will use internal addresses");
                }
                return false;
            }
            if (isReachable(internalAddress, REACHABLE_ADDRESS_TIMEOUT_MILLIS)) {
                if (logger.isFineEnabled()) {
                    logger.fine("The internal address is reachable. The client will use the internal addresses");
                }
                return false;
            }
            if (!isReachable(publicAddress, NON_REACHABLE_ADDRESS_TIMEOUT_MILLIS)) {
                if (logger.isFineEnabled()) {
                    logger.fine("Public address + " + publicAddress
                            + "  is not reachable. The client will use internal addresses");
                }
                return false;
            }
        }
        if (logger.isFineEnabled()) {
            logger.fine("Members are accessible via only public addresses. The client will use public addresses");
        }
        return true;
    }

    private boolean isReachable(Address address, int timeoutMs) {
        try (Socket s = new Socket()) {
            s.connect(new InetSocketAddress(address.getHost(), address.getPort()), timeoutMs);
        } catch (Exception e) {
            if (logger.isFineEnabled()) {
                logger.fine("TranslateToPublicAddressProvider can not reach to address " + address
                        + " in " + timeoutMs + " millis", e);
            }
            return false;
        }
        return true;
    }

    boolean get() {
        return translateToPublicAddress;
    }
}


text:
\documentclass[twoside,11pt]{article}

%TODO LIST BELOW
% - scikit-learn needs to be formatted correctly, everywhere
% - Description of the algorithm
% - Author affiliations
% - ???

% Any additional packages needed should be included after jmlr2e.
% Note that jmlr2e.sty includes epsfig, amssymb, natbib and graphicx,
% and defines many common macros, such as 'proof' and 'example'.
%
% It also sets the bibliographystyle to plainnat; for more information on
% natbib citation styles, see the natbib documentation, a copy of which
% is archived at http://www.jmlr.org/format/natbib.pdf

\usepackage{jmlr2e}

% Definitions of handy macros can go here

\newcommand{\dataset}{{\cal D}}
\newcommand{\fracpartial}[2]{\frac{\partial #1}{\partial  #2}}

% Heading arguments are {volume}{year}{pages}{submitted}{published}{author-full-names}

\jmlrheading{1}{2000}{1-48}{4/00}{10/00}{Maheshakya Wijewardena, Daniel Vainsencher and Robert Layton}

% Short headings should be running head and authors last names

\ShortHeadings{LSH Forest for scikit-learn}{Wijewardena, Vainsencher and Layton}
\firstpageno{1}

\begin{document}

\title{A Locality Sensitive Hashing Forest for scikit-learn}

\author{\name Maheshakya Wijewardena \email mmp@stat.washington.edu \\
       \addr Department of Statistics\\
       University of Washington\\
       Seattle, WA 98195-4322, USA
       \AND
       \name Daniel Vainsencher \email jordan@cs.berkeley.edu \\
       \addr Division of Computer Science and Department of Statistics\\
       University of California\\
       Berkeley, CA 94720-1776, USA
       \AND Robert Layton \email r.layton@federation.edu.au \\
       \addr Internet Commerce Security Laboratory \\
       Federation University Australia
       }

\editor{Leslie Pack Kaelbling}  %TODO: Don't know editor

\maketitle

\begin{abstract}%   <- trailing '%' for backward compatibility of .sty file
Locality Sensitive Hashing (LSH) is a method for the fast comparison of arbitrary objects.
LSH methods use (often simple) hashing algorithms to create probabilistic models to approximate distance.
This allows for the very efficient comparison of objects in large datasets.
In this paper we describe an implementation of a Locality Sensitive Hashing Forest algorithm, supporting approximate nearest neighbour in the widely used scikit-learn software package.
The implementation is cross-platform and supports the standardised interface common to most scikit-learn models.
\end{abstract}

\begin{keywords}
  Locality Sensitive Hashing, LSH Forest, scikit-learn
\end{keywords}

\section{Introduction}

Even though there are several efficient exact nearest neighbor search
algorithms known for the case when the dimension $d$ is low (eg: up to 50
or 60), they tend to suffer from either space or query time that is exponential
in $`d$.
For large enough $d$, in practice they often provide only a little improvement over the linear time `brute force' algorithm that
compares a query point to each point from the database.
This phenomenon is often called `The Curse of Dimensionality'.
When answers do not have to be exact, various algorithms can provide an approximate nearest
neighbor search which is useful in high dimensional problems.

Approximate nearest neighbor search attempts to overcome the bottleneck
of query running time \citep{andoni2006near}. In certain applications which involve
high dimensional data, it may be acceptable to retrieve a `good guess' for
nearest neighbors. This is also appropriate where it is not as important to
identify the neighbors themselves so much as to characterize the neighborhood,
as in k-nearest neighbors classification and regression.
In such cases, an algorithm which does not guarantee to
return the actual nearest neighbors can be used, in return for improved speed.
Methods for approximate nearest neighbor search include locality
sensitive hashing (LSH), best bin fit and balanced box-decomposition tree based
search.

Locality sensitive hashing and its variants have been successfully
applied to many computational problems in many areas. The key idea of LSH is to
hash the data points using several hash functions to ensure that for each
function, the probability of collision is much higher for the objects that are
close to each other than those that are far apart. Following are the
requirements for a hash function family to be locality sensitive.

A family $H$ of functions from a domain $S$ to a range $U$
is called $(r, e , p1 , p2 )$-sensitive, with $r, e > 0$,
$p_1 > p_2 > 0$, if for any $p, q ∈ S$, the following conditions
hold ($D$ is the distance function):

* If $D(p,q) <= r$ then $P_H[h(p) = h(q)] >= p_1$,
* If $D(p,q) > r(1 + e)$ then $P_H[h(p) = h(q)] <= p_2$.

The definition states that \textit{nearby} points within a distance $r$ of
each other are likely to collide (with probability $p_1$), while
\textit{distant} points more than $r(1 + e)$ apart have only a smaller
probability ($p_2$) of colliding. Assuming that there is some family
of LSH functions $H$ available, LSH index is built as follows:

1. Choose $k$ functions $h_1, h_2, … h_k$ uniformly at
   random (with replacement) from $H$. For any $p ∈ S$, place
   $p$ in the bucket with label
   $g(p) = (h_1(p), h_2(p), … h_k(p))$. Observe that if
   each $h_i$ outputs one `digit', each bucket has a k-digit label.

2. Independently perform step 1 $l$ times to construct $l$
   separate estimators, with hash functions $g_1, g_2, … g_l$.

In step 1, if two distant points had a probability $p_2$ of
collision with one hash function, their collision probability drops to
just $p_2^k$ with the concatenation, which becomes
negligibly small for large $k$. However, a larger value of $k$
has the side-effect of lowering the chances of even nearby points colliding.
Therefore, to ensure enough `good' collisions occur, step 2 constructs
multiple estimators.

\section{Locality Sensitive Hashing Forest}

LSHForest was implemented for the scikit-learn package as part of the 2014 Google Summer of Code.
Logically, a tree in the LSH
forest is a prefix tree, with each leaf corresponding to a point in the data
base \citep{bawa2005lsh}. This data structure simply consists of $l$ such LSH trees, each
constructed with an independently drawn random sequence of hash functions from
$H$. This collection of $l$ trees is the LSH Forest. In our
implementation, the length of the sequence of hash functions is kept fixed at
32. Moreover, a prefix tree is implemented using sorted arrays and binary
search.

A query for the $m$ nearest neighbors of a point $q$ is answered by
traversing the LSH trees in two phases. In the first top-down phase, each LSH
Tree is descended (by binary search) to find the leaf having the largest prefix
match (maximum depth) with $q$'s label after subjecting $q$ to the
same hashing functions.  In the second bottom-up phase, $M >> m$ points
(total candidates) are extracted from the LSH Forest, moving up from maximum
depth towards the root synchronously across all LSH trees. $M$ is set to
$cl$ where $c$, the number of candidates extracted from each tree,
is constant.
Finally , similarity of all $M$ points to point
$q$ are calculated and top $m$ points are returned as the nearest
neighbors of $q$. Since much of the time is spent calculating the
distances to candidates, the speedup compared to brute force search is
approximately $N/M$ where $N$ is the number of points in database.

The query time depends mainly on the parameters $l$ and $c$
(\texttt{n\_estimators} and \texttt{n\_candidates} in our implementation). The behaviour of
query time while varying these parameters are as follows.
%
%.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_001.png
%   :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors.html
%   :align: center
%   :scale: 75
%
%.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_002.png
%   :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors.html
%   :align: center
%   :scale: 75

% Acknowledgements should go at the end, before appendices and references

\acks{
This project was conducted through the support of the Google Summer of Code (GSoC) 2014.
We appreciate the support of Google in assisting the open source community.
We also appreciate the support of the Python Software Foundation in organising scikit-learn's GSoC applications, and the scikit-learn contributors for their support, reviews and organisation.

Dr Layton is supported by the Internet Commerce Security Laboratory (ICSL), a joint venture between Federation University Australia, Westpac and IBM.}

% Manual newpage inserted to improve layout of sample file - not
% needed in general before appendices/bibliography.

\newpage

\vskip 0.2in
\bibliography{references}

\end{document}


text:
.body { padding: 0; margin:0;}

/* Estils de la barra principal */
#barra_principal           { height: 35px; display: block; float: none; }
#barra_principal .logo     { height: 35px; float: left; }
#barra_principal .busqueda { width: 50%; float: left; position: relative; left: 12.5%; top: 12.5%; }
#barra_principal .usuari   { float:right; text-align: right; vertical-align: middle; height: 100%; }
#barra_principal .usuari span { position: relative; top: 25%; right: 20px; font-weight: bold; }

#barra_principal .usuari a { color:#e7e5e5; }
#barra_principal .usuari a:visited { text-decoration: none; }

.menu               { background-color: #255708; color: white; margin: 0;
                      -webkit-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
                      -moz-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
                      box-shadow: rgba(0, 0, 0, 0.4) 0px 1px;
                      height: 35px; color:#e7e5e5;
                    }
.menu ul            { width:100%; margin:0; padding:0; }
.menu ul li         { float:left; position:relative; list-style:none; }
.menu ul li a       { font-weight:bold; color:#e7e5e5; text-decoration:none; display:block; padding:8px 20px;}
.menu ul li a:hover { background-color: #8FDB1C; cursor: pointer; }

#content { margin-top: 25px; padding: 15px; }

h3 { margin-top: 5px; }

/* Estils dels llistats */
.llistat    { border-spacing: 0; }
.llistat th { background: #40941C; color: white; font-weight: bold; padding: 4px; }
.llistat td { padding: 4px; border-bottom: 1px solid #C0C0C0; }
.llistat td a {text-decoration: none;}
.llistat tbody tr { background: #EFFFC9; }
.llistat tbody tr:hover { background: #FFFB80; }

.llistat_afegir { margin-top: 10px; cursor: pointer; }

/* Estils dels formulari d'edició */
.edicio .dalt   { border-top: 1px solid #C0C0C0; }
.edicio .baix   { border-bottom: 1px solid #C0C0C0;  width: 400px; padding: 4px; }
.edicio label { display: inline-block; padding: 3px; background: #40941C; color: white; font-weight: bold; width: 100px; text-align: right; margin-right: 4px; }
.edicio .widgetPregunta { display: block; margin: 5px; }
.edicio span.enllac { font-size: 85%; text-decoration: underline; cursor: pointer; font-weight: bold; }
.edicio .comboBox { width: 455px; }

/* Fitxa */
.fitxa .imatge { float: left; margin: 15px; }


text:
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;

SET default_tablespace = '';

SET default_table_access_method = heap;

--
-- Name: test1; Type: TABLE; Schema: public; Owner: krioweb2
--

CREATE TABLE public.test1 (
    id integer NOT NULL,
    text name
);

ALTER TABLE public.test1 OWNER TO krioweb2;

--
-- Name: test1_id_seq; Type: SEQUENCE; Schema: public; Owner: krioweb2
--

CREATE SEQUENCE public.test1_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER TABLE public.test1_id_seq OWNER TO krioweb2;

--
-- Name: test1_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: krioweb2
--

ALTER SEQUENCE public.test1_id_seq OWNED BY public.test1.id;

--
-- Name: test1 id; Type: DEFAULT; Schema: public; Owner: krioweb2
--

ALTER TABLE ONLY public.test1 ALTER COLUMN id SET DEFAULT nextval('public.test1_id_seq'::regclass);

--
-- Data for Name: test1; Type: TABLE DATA; Schema: public; Owner: krioweb2
--

COPY public.test1 (id, text) FROM stdin;
\.

--
-- Name: test1_id_seq; Type: SEQUENCE SET; Schema: public; Owner: krioweb2
--

SELECT pg_catalog.setval('public.test1_id_seq', 1, false);

--
-- Name: test1 test1_pkey; Type: CONSTRAINT; Schema: public; Owner: krioweb2
--

ALTER TABLE ONLY public.test1
    ADD CONSTRAINT test1_pkey PRIMARY KEY (id);

--
-- PostgreSQL database dump complete
--


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Amsterdam 2014
 - proposals</title>
<meta name="author" content="" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Amsterdam 2014
 - proposals

Gold sponsors

welcome
propose
proposals
program
location
register
sponsor
contact

Call for proposals is now open and will close on May 1, 2014

This is extended on request of a number of people that are submitting

There are three ways to propose a session:

A proposal for a talk/panel during the conference part : these are 30 minutes slots that will have all people's full attention as everybody will be in that one room.

An Ignite talk that will be presented during the Ignite sessions: these are 5 minutes slots with slides changing every 15 seconds (20 slides total) also presented to all attendees in one room

Openspace session : even without a prepared presentation we welcome the discussion and interaction by having people propose a session on the fly during the openspace opening. Check the openspace format for more information

Even if you don't propose, please consider commenting on proposals submitted by others

Our main criteria to make it to the top selection are:

original content: content not yet presented at other conferences, or a new angle to an existing problem

new presenters: people who are new to the space and have insightful stuff to tell, we want to hear everbody's voice

no vendor pitches: as much as we value vendors and sponsors, we just don't think this is the right forum. There is a demo openspace slot where you have 5 minutes to show products.

Some suggestions to get you thinking:

What is the role of QA/Tester in devops, how do we integrate QA in the continuous delivery process

The impact devops has on traditional security/auditing/change control

How does devops co-exist with ITIL, Cobit

How about release management ?

What about configuration management and delivery in Mixed Unix AND Windows environments

Building dashboards because #monitoringsucks

The impact of devops on HR policies, and the hiring process

Help prove that devops can scale beyond the 5-8 person web startups, we love traditional IT enterprise cases

With all the automation, data is still a hard thing to handle, how does it affect, DBA's, backup strategies, ...

How to involve the business in devops

How to get YOUR boss involved, how do you make the business case

And of course any other topic in the realm of Devops

Beyond Configuration Management, about challenges like orchestration, or doing things at large scale

How to make a proposal: Send an email to [proposals-amsterdam-2014@devopsdays.org
] with the following information

Proposal working title (can be changed later)

Type (presentation, panel discussion, moderated general discussion, debate, etc.,ignite)

Description or abstract

Rules:

Be specific... we aren't mind readers (a description of about 20 lines is about right)

Detail is good... but not as important as explaining why your proposal would be interesting

Nominations welcome... if you know someone who has content/experience relevant to the DevOps conversation, please point us in their direction!

Multiple proposals welcome... just follow the other rules

Silver sponsors


text:
var Eventproxy = require('eventproxy');
var Bagpipe = require('bagpipe');
var proxy = require('./proxy');
var fakeuser = require('./fakeuser');
var users = require('./fakeuser');

function get10UserPost(users, callback) {
  var queue = new Bagpipe(10);
  var ep = Eventproxy.create();
  ep.fail(callback);
  ep.after('post', users.length, callback.bind(null, null));
  users.forEach(function (user) {
    proxy.getPosts(user, ep.group('post'));
  });
}

var start = Date.now();
get10UserPost(users, function (err, result) {
  err
  ? console.error(err)
  : console.log(result);

  console.log('total used %d ms', Date.now() - start);
});


text:
;(function(_, Array) {

    // expose internals on the underscore to allow extensibility
    _.array = function(fnName, key, args) {
        var value = this.get(key, []),
            array = Array.isArray(value) ? value : [value],
            ret = array[fnName].apply(array, args);
        if (array.length > 0) {
            this.set(key, array.length > 1 ? array : array[0]);
        } else {
            this.remove(key);
        }
        return ret;
    };
    _.arrayFn = function(fnName) {
        return function(key) {
            return this.array(fnName, key,
                arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null);
        };
    };

    // add function(s) to the store interface
    _.fn('array', _.array);
    Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
        // add Array interface functions w/o existing conflicts
        if (typeof Array.prototype[name] === "function") {
            if (!(name in _.storeAPI)) {
                _.fn(name, _.array[name] = _.arrayFn(name));
            }
        }
    });

})(window.store._, window.Array);


text:
@import UIKit;

@interface SunbeamViewController : UIViewController

@end


text:
package com.google.android.apps.exposurenotification.onboarding;

import static com.google.android.apps.exposurenotification.home.BaseActivity.MAIN_FRAGMENT_TAG;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.apps.exposurenotification.R;
import com.google.android.apps.exposurenotification.common.logging.Logger;
import com.google.android.apps.exposurenotification.databinding.FragmentOnboardingPrivateAnalyticsBinding;
import com.google.android.apps.exposurenotification.home.SinglePageHomeFragment;
import dagger.hilt.android.AndroidEntryPoint;

/**
 * Consent dialog private analytics.
 */
@AndroidEntryPoint
public class OnboardingPrivateAnalyticsFragment extends AbstractOnboardingPrivateAnalyticsFragment {

  private static final Logger logger = Logger.getLogger("OnboardingPrivateAnalyticsFragment");

  private FragmentOnboardingPrivateAnalyticsBinding binding;

  @Override
  public View onCreateView(
      @NonNull LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    binding = FragmentOnboardingPrivateAnalyticsBinding.inflate(inflater, parent, false);
    return binding.getRoot();
  }

  @Override
  public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    onboardingViewModel.isPrivateAnalyticsStateSetLiveData()
        .observe(getViewLifecycleOwner(), hasPrivateAnalyticsSet -> {
          if (hasPrivateAnalyticsSet) {
            // Trigger a one-time submit
            onboardingViewModel.submitPrivateAnalytics();
            SinglePageHomeFragment.transitionToSinglePageHomeFragment(this);
          }
        });
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    binding = null;
  }

  @Override
  void dontSharePrivateAnalytics() {
    onboardingViewModel.setPrivateAnalyticsState(false);
  }

  @Override
  void sharePrivateAnalytics() {
    logger.d("Onboarding complete: private analytics enabled.");
    onboardingViewModel.setPrivateAnalyticsState(true);
  }

  /**
   * Helper to transition from one fragment to {@link OnboardingPrivateAnalyticsFragment}.
   *
   * @param fragment The fragment to transit from
   */
  public static void transitionToOnboardingPrivateAnalyticsFragment(Fragment fragment) {
    // Remove previous fragment from the stack if it is there.
    fragment
        .getParentFragmentManager()
        .popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

    FragmentTransaction fragmentTransaction =
        fragment.getParentFragmentManager().beginTransaction();
    fragmentTransaction
        .replace(R.id.main_fragment, new OnboardingPrivateAnalyticsFragment(), MAIN_FRAGMENT_TAG);
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fragmentTransaction.commit();
  }

}


text:
package ships.controller;

import org.junit.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import ships.exception.ShipGameException;
import ships.view.OpponentMapView;
import ships.view.PlayerMapView;

import static org.junit.Assert.assertTrue;

public class PlayerVsComputerGameTest {

    public PlayerVsComputerGameTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @After
    public void tearDown() {
    }

    @Mock
    PlayerMapView mockedPlayerMapView;

    @Mock
    OpponentMapView mockedOpponentMapView;

    @InjectMocks
    PlayerVsComputerGame sut;

    @Test
    public void shouldRandomlyPlaceComputerShips() throws ShipGameException {
        //given
        //when
        //then
        assertTrue(sut.getOpponentScore() == 20);
    }

}


text:
package net.travel.ejb.data.model;

import java.io.Serializable;
import javax.persistence.*;

/**
 * The primary key class for the tklienciatrakcjehistoria database table.
 *
 */
@Embeddable
public class TklienciatrakcjehistoriaPK implements Serializable {
	// default serial version id, required for serializable classes.
	private static final long serialVersionUID = 1L;

	@Column(insertable = false, updatable = false)
	private int IDAtrakcjiUslugi;

	@Column(insertable = false, updatable = false)
	private int IDOsobyAtrakcji;

	public TklienciatrakcjehistoriaPK() {
	}

	public TklienciatrakcjehistoriaPK(int iDAtrakcjiUslugi, int iDOsobyAtrakcji) {
		super();
		IDAtrakcjiUslugi = iDAtrakcjiUslugi;
		IDOsobyAtrakcji = iDOsobyAtrakcji;
	}

	public int getIDAtrakcjiUslugi() {
		return this.IDAtrakcjiUslugi;
	}

	public void setIDAtrakcjiUslugi(int IDAtrakcjiUslugi) {
		this.IDAtrakcjiUslugi = IDAtrakcjiUslugi;
	}

	public int getIDOsobyAtrakcji() {
		return this.IDOsobyAtrakcji;
	}

	public void setIDOsobyAtrakcji(int IDOsobyAtrakcji) {
		this.IDOsobyAtrakcji = IDOsobyAtrakcji;
	}

	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof TklienciatrakcjehistoriaPK)) {
			return false;
		}
		TklienciatrakcjehistoriaPK castOther = (TklienciatrakcjehistoriaPK) other;
		return (this.IDAtrakcjiUslugi == castOther.IDAtrakcjiUslugi)
				&& (this.IDOsobyAtrakcji == castOther.IDOsobyAtrakcji);
	}

	public int hashCode() {
		final int prime = 31;
		int hash = 17;
		hash = hash * prime + this.IDAtrakcjiUslugi;
		hash = hash * prime + this.IDOsobyAtrakcji;

		return hash;
	}
}


text:
require 'test_helper'

class RemoteOppTest < Test::Unit::TestCase

  def setup
    @gateway = OppGateway.new(fixtures(:opp))
    @amount = 100

    @valid_card = credit_card("4200000000000000", month: 05, year: 2018)
    @invalid_card = credit_card("4444444444444444", month: 05, year: 2018)
    @amex_card = credit_card("377777777777770 ", month: 05, year: 2018, brand: 'amex', verification_value: '1234')

    request_type = 'complete' # 'minimal' || 'complete'
    time = Time.now.to_i
    ip = '101.102.103.104'
    @complete_request_options = {
      order_id: "Order #{time}",
      merchant_transaction_id: "active_merchant_test_complete #{time}",
      address: address,
      description: 'Store Purchase - Books',
#      riskWorkflow: true,
#      testMode: 'EXTERNAL' # or 'INTERNAL', valid only for test system

        billing_address: {
           address1: '123 Test Street',
           city:     'Test',
           state:    'TE',
           zip:      'AB12CD',
           country:  'GB',
         },
         shipping_address: {
           name:     'Muton DeMicelis',
           address1: 'My Street On Upiter, Apt 3.14/2.78',
           city:     'Munich',
           state:    'Bov',
           zip:      '81675',
           country:  'DE',
         },
         customer: {
           merchant_customer_id:  "your merchant/customer id",
           givenName:  'Jane',
           surname:  'Jones',
           birthDate:  '1965-05-01',
           phone:  '(?!?)555-5555',
           mobile:  '(?!?)234-23423',
           email:  'jane@jones.com',
           company_name:  'JJ Ltd.',
           identification_doctype:  'PASSPORT',
           identification_docid:  'FakeID2342431234123',
           ip:  ip,
         },
    }

    @minimal_request_options = {
      order_id: "Order #{time}",
      description: 'Store Purchase - Books',
    }

    @complete_request_options['customParameters[SHOPPER_test124TestName009]'] = 'customParameters_test'
    @complete_request_options['customParameters[SHOPPER_otherCustomerParameter]'] = 'otherCustomerParameter_test'

    @test_success_id = "8a82944a4e008ca9014e1273e0696122"
    @test_failure_id = "8a8294494e0078a6014e12b371fb6a8e"
    @test_wrong_reference_id = "8a8444494a0033a6014e12b371fb6a1e"

    @options = @minimal_request_options if request_type == 'minimal'
    @options = @complete_request_options if request_type == 'complete'
  end

# ****************************************** SUCCESSFUL TESTS ******************************************
  def test_successful_purchase
    @options[:description] = __method__

    response = @gateway.purchase(@amount, @valid_card, @options)
    assert_success response, "Failed purchase"
    assert_match %r{Request successfully processed}, response.message

    assert response.test?
  end

  def test_successful_purchase_sans_options
    response = @gateway.purchase(@amount, @valid_card)
    assert_success response
    assert_match %r{Request successfully processed}, response.message

    assert response.test?
  end

  def test_successful_authorize
    @options[:description] = __method__

    response = @gateway.authorize(@amount, @valid_card, @options)
    assert_success response, "Authorization Failed"
    assert_match %r{Request successfully processed}, response.message

    assert response.test?
  end

  def test_successful_capture
    @options[:description] = __method__
    auth = @gateway.authorize(@amount, @valid_card, @options)
    assert_success auth, "Authorization Failed"
    assert auth.test?

    capt = @gateway.capture(@amount, auth.authorization, @options)
    assert_success capt, "Capture failed"
    assert_match %r{Request successfully processed}, capt.message

    assert capt.test?
  end

  def test_successful_refund
    @options[:description] = __method__
    purchase = @gateway.purchase(@amount, @valid_card, @options)
    assert_success purchase, "Purchase failed"
    assert purchase.test?

    refund = @gateway.refund(@amount, purchase.authorization, @options)
    assert_success refund, "Refund failed"
    assert_match %r{Request successfully processed}, refund.message

    assert refund.test?
  end

  def test_successful_void
    @options[:description] = __method__
    purchase = @gateway.purchase(@amount, @valid_card, @options)
    assert_success purchase, "Purchase failed"
    assert purchase.test?

    void = @gateway.void(purchase.authorization, @options)
    assert_success void, "Void failed"
    assert_match %r{Request successfully processed}, void.message

    assert void.test?
  end

  def test_successful_partial_capture
    @options[:description] = __method__
    auth = @gateway.authorize(@amount, @valid_card, @options)
    assert_success auth

    assert capture = @gateway.capture(@amount-1, auth.authorization)
    assert_success capture
    assert_match %r{Request successfully processed}, capture.message
  end

  def test_successful_partial_refund
    @options[:description] = __method__
    purchase = @gateway.purchase(@amount, @valid_card, @options)
    assert_success purchase

    assert refund = @gateway.refund(@amount-1, purchase.authorization)
    assert_success refund
    assert_match %r{Request successfully processed}, refund.message
  end

  def test_successful_verify
    @options[:description] = __method__
    response = @gateway.verify(@valid_card, @options)
    assert_success response
    assert_match %r{Request successfully processed}, response.message
  end

# ****************************************** FAILURE TESTS ******************************************

  def test_failed_purchase
    @options[:description] = __method__
    response = @gateway.purchase(@amount, @invalid_card, @options)
    assert_failure response
    assert_match %r{invalid creditcard}, response.message
  end

  def test_failed_authorize
    @options[:description] = __method__
    response = @gateway.authorize(@amount, @invalid_card, @options)
    assert_failure response
    assert_match %r{invalid creditcard}, response.message
  end

  def test_failed_capture
    @options[:description] = __method__
    response = @gateway.capture(@amount, @test_wrong_reference_id)
    assert_failure response
    assert_match %r{capture needs at least one successful transaction}, response.message
  end

  def test_failed_refund
    @options[:description] = __method__
    response = @gateway.refund(@amount, @test_wrong_reference_id)
    assert_failure response
    assert_match %r{Invalid payment data}, response.message
  end

  def test_failed_void
    @options[:description] = __method__
    response = @gateway.void(@test_wrong_reference_id, @options)
    assert_failure response
    assert_match %r{reversal needs at least one successful transaction}, response.message
  end

# ************************************** TRANSCRIPT SCRUB ******************************************

  def test_transcript_scrubbing
    assert @gateway.supports_scrubbing?

    transcript = capture_transcript(@gateway) do
      @gateway.purchase(@amount, @valid_card)
    end
    transcript = @gateway.scrub(transcript)

    assert_scrubbed(@valid_card.number, transcript)
    assert_scrubbed(@valid_card.verification_value, transcript)
    assert_scrubbed(@gateway.options[:password], transcript)
  end
end


text:
<?php

namespace app\modules\admin\controllers;

use yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\modules\admin\models\LoginForm;
use app\modules\user\models\Log as LoginLog;
use app\modules\grave\models\search\TombSearch;

class DefaultController extends \app\core\web\BackController
{

	public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['login', 'error', 'signup','logout', 'index'],
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'signup'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'comment' => [
                'class' => 'app\core\widgets\comment\CommentAction',
            ],
            'ue-upload' => [
                'class' => 'app\core\widgets\Ueditor\UploadAction',
            ]
        ];
    }

    /**
     * @name 管理后台首页
     */
    public function actionIndex()
    {
        $searchModel = new TombSearch();
        $params = Yii::$app->request->queryParams;
        $dataProvider = $searchModel->searchWork($params);

        LoginLog::getLast();

        return $this->render('work', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

//        LoginLog::getLast();
//        return $this->render('index');
    }

    /**
     * @name 工作
     */
    public function actionWork()
    {
        $searchModel = new TombSearch();
        $params = Yii::$app->request->queryParams;
        $dataProvider = $searchModel->searchWork($params);
        return $this->render('work', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }

    public function actionTombs()
    {
        $searchModel = new TombSearch();
        $params = Yii::$app->request->queryParams;
        $dataProvider = $searchModel->searchWork($params);
        return $this->renderAjax('tombs', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * @name 工作台
     */
    public function actionWorkbench()
    {
        return $this->render('workbench');
    }

    public function actionLogin()
    {

        $this->layout = "@app/core/views/layouts/single.php";
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            LoginLog::create();
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect(['/']);
    }

    public function actionTest()
    {
        return $this->render('test');
    }

}


text:
module Cities
  class CreateForm < Reform::Form
    property :zone_id, virtual: true
    property :country_id, virtual: true

    property :state_id
    property :name

    validates :name,
              :country_id,
              :state_id,
              presence: true

    def zone_options
      Zone.all.map { |z| [z.name, z.id] }
    end

    def country_options
      scope = zone.countries
      scope.all.map do |zm|
        [zm.name, zm.id]
      end
    end

    def state_options
      scope = country.states
      scope.all.map do |state|
        [state.name, state.id]
      end
    end

    def prepopulate!(options = {})
      super # Calls form + nested prepopulators

      options ||= {}

      self.zone_id    = options[:zone_id]
      self.country_id = options[:country_id]
      self.state_id   = options[:state_id]
      self.name       = options[:name]
    end

    private

    def zone
      Zone.find_by(id: self.zone_id) || Zone.first
    end

    def country
      zone.countries.find_by(id: self.country_id) || zone.countries.first
    end
  end
end


text:
<?php

namespace Concrete\Core\Entity\Attribute\Key\Settings;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="atDurationSettings")
 */
class DurationSettings extends Settings
{
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $akUnitType = '';

    /**
     * @return string
     */
    public function getUnitType(): string
    {
        return $this->akUnitType;
    }

    /**
     * @param string $unitType
     * @return DurationSettings
     */
    public function setUnitType(string $unitType): DurationSettings
    {
        $this->akUnitType = $unitType;
        return $this;
    }

}


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

public class StopNode : MonoBehaviour {

    private GameObject stopNode;
    private GameObject player;

	// Use this for initialization
	void Start () {
        stopNode = this.gameObject;
        player = GameObject.FindGameObjectWithTag("player");
	}

	// Update is called once per frame
	void Update () {

	}

    public void OnTriggerEnter(Collider other)
    {
        SceneManager.LoadScene(0);
    }
}


text:
package org.wso2.jaggery.integration.tests.wsmock;

import javax.xml.ws.Endpoint;

public class MockServicePublisher {

    public static void main(String[] args) {

        Endpoint.publish("http://localhost:9960/ws/mock", new MockServiceImpl());
        System.out.println("Server is published!");
    }
}


text:
#pragma config(UART_Usage, UART2, uartNotUsed, baudRate4800, IOPins, None, None)
#pragma config(I2C_Usage, I2C1, i2cSensors)
#pragma config(Sensor, in1,    zC,             sensorAccelerometer)
#pragma config(Sensor, in2,    xC,             sensorAccelerometer)
#pragma config(Sensor, in3,    yC,             sensorAccelerometer)
#pragma config(Sensor, I2C_1,  backLeftEncoder, sensorQuadEncoderOnI2CPort,    , AutoAssign)
#pragma config(Sensor, I2C_2,  frontLeftEncoder, sensorQuadEncoderOnI2CPort,    , AutoAssign)
#pragma config(Sensor, I2C_3,  frontRightEncoder, sensorQuadEncoderOnI2CPort,    , AutoAssign)
#pragma config(Sensor, I2C_4,  backRightEncoder, sensorQuadEncoderOnI2CPort,    , AutoAssign)
#pragma config(Motor,  port1,           backLeftControl, tmotorVex393_HBridge, openLoop, encoderPort, I2C_1)
#pragma config(Motor,  port3,           backLeftDrive, tmotorVex393_MC29, openLoop, driveLeft)
#pragma config(Motor,  port4,           frontLeftControl, tmotorVex393_MC29, openLoop, encoderPort, I2C_2)
#pragma config(Motor,  port5,           frontLeftDrive, tmotorVex393_MC29, openLoop, driveLeft)
#pragma config(Motor,  port6,           frontRightControl, tmotorVex393_MC29, openLoop, encoderPort, I2C_3)
#pragma config(Motor,  port7,           frontRightDrive, tmotorVex393_MC29, openLoop, driveRight)
#pragma config(Motor,  port9,           backRightDrive, tmotorVex393_MC29, openLoop, driveRight)
#pragma config(Motor,  port10,          backRightControl, tmotorVex393_HBridge, openLoop, encoderPort, I2C_4)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

int encoderInit = 0;

void recoverControlMotor(){
	if(nMotorEncoder[frontRightControl] != encoderInit){
		while(nMotorEncoder[frontRightControl] > encoderInit){
			motor[frontRightControl] = -127;
		}
		while(nMotorEncoder[frontRightControl] < encoderInit){
			motor[frontRightControl] = 127;
		}
	}//frontRight
	if(nMotorEncoder[frontLeftControl] != encoderInit){
		while(nMotorEncoder[frontLeftControl] > encoderInit){
			motor[frontLeftControl] = -127;
		}
		while(nMotorEncoder[frontLeftControl] < encoderInit){
			motor[frontRightControl] = 127;
		}
	}//frontLeft
	if(nMotorEncoder[backRightControl] != encoderInit){
		while(nMotorEncoder[backRightControl] > encoderInit){
			motor[backRightControl] = -127;
		}
		while(nMotorEncoder[backRightControl] < encoderInit){
			motor[backRightControl] = 127;
		}
	}//backRight
	if(nMotorEncoder[backLeftControl] != encoderInit){
		while(nMotorEncoder[backLeftControl] > encoderInit){
			motor[backLeftControl] = -127;
		}
		while(nMotorEncoder[backLeftControl] < encoderInit){
			motor[backLeftControl] = 127;
		}
	}//backLeft
}

task main(){
	while(true){
		if(vexRT[Btn8D] == 1){
			recoverControlMotor();
		}
		//	motor[frontRightControl] = 50;
		//	motor[frontLeftControl] = 50;
		//	motor[backLeftControl] = 50;
		//	motor[backRightControl] = 50;

		//	motor[frontRightDrive] = 50;
		//	motor[frontLeftDrive] = 50;
		//	motor[backLeftDrive] = 50;
		//	motor[backRightDrive] = 50;
		//if(nMotorEncoder[frontRightControl] != 0){
		//while(nMotorEncoder[frontRightControl] > 0){
		//motor[frontRightControl] = -127;
		//}
		//	}
	}
}


text:
This intention moves the code of the else branch after the if statement.

Note that it changes the code semantics.


text:
import { Response } from "express";
import * as HttpStatus from "http-status-codes";

export class ApiResponseRender {

  constructor(protected response: Response) {
  }

  render(payload: any) {
    this.response
      .header("Content-Type", "application/json")
      .json(payload);
  }

  renderValidationError(payload: any) {
    this.response.status(HttpStatus.BAD_REQUEST)
      .header("Content-Type", "application/json")
      .json(payload);
  }
}


text:
using System;
using System.Collections.Generic;
using EQueue.Protocols.Brokers;

namespace EQueue.Protocols.NameServers
{
    [Serializable]
    public class BrokerTopicConsumeInfo
    {
        public BrokerInfo BrokerInfo { get; set; }
        public IList<TopicConsumeInfo> TopicConsumeInfoList { get; set; }

        public BrokerTopicConsumeInfo()
        {
            TopicConsumeInfoList = new List<TopicConsumeInfo>();
        }
    }
}


text:
using namespace OryolTools;

//------------------------------------------------------------------------------
inline const uint8_t* load_file(const std::string& path) {
    // NOTE: this always adds a zero-byte so that the loaded data
    // is also a valid C string
    FILE* fp = fopen(path.c_str(), "rb");
    Log::FailIf(!fp, "Failed to open file '%s'\n", path.c_str());
    fseek(fp, 0, SEEK_END);
    int size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    uint8_t* ptr = (uint8_t*) malloc(size + 1);
    int bytesRead = fread((void*)ptr, 1, size, fp);
    Log::FailIf(bytesRead != size, "Failed reading file '%s' into memory\n", path.c_str());
    fclose(fp);
    ptr[size] = 0;
    return (const uint8_t*) ptr;
}

//------------------------------------------------------------------------------
inline void free_file_data(const uint8_t* ptr) {
    free((void*)ptr);
}

//------------------------------------------------------------------------------
template<typename TYPE> TYPE read(FILE* fp) {
    TYPE val;
    int bytesRead = fread(&val, 1, sizeof(val), fp);
    OryolTools::Log::FailIf(bytesRead != sizeof(val), "File read error.");
    return val;
}

//------------------------------------------------------------------------------
template<> inline std::string read<std::string>(FILE* fp) {
    uint16_t len = read<uint16_t>(fp);
    OryolTools::Log::FailIf(len > 4096, "Long string in file.");
    std::string str;
    str.reserve(len);
    for (uint16_t i = 0; i < len; i++) {
        str.push_back(read<char>(fp));
    }
    return str;
}


text:
MemberDirectory::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Code is not reloaded between requests
  config.eager_load = true
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_files = false

  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline if a precompiled asset is missed
  config.assets.compile = false

  # Generate digests for assets URLs
  config.assets.digest = true

  # Defaults to nil and saved in location specified by config.assets.prefix
  # config.assets.manifest = YOUR_PATH

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # See everything in the log (default is :info)
  # config.log_level = :debug

  # Prepend all log lines with the following tags
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false
  config.action_mailer.default_url_options = { :host => 'directory.theodi.org' }

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  config.action_mailer.smtp_settings = {
    :user_name => ENV["MANDRILL_USERNAME"],
    :password => ENV["MANDRILL_PASSWORD"],
    :domain => "theodi.org",
    :address => "smtp.mandrillapp.com",
    :port => 587,
    :authentication => :plain,
    :enable_starttls_auto => true
  }
end


text:
//
//  RXWeatherView.m
//  NeteaseNews
//
//  Created by 王若曦 on 16/3/30.
//  Copyright © 2016年 wrx. All rights reserved.
//

#import "RXWeatherView.h"
#import "RXWeatherDetail.h"
#import "RXPm2d5.h"
#import "RXBottomView.h"
#import "RXWeatherDetailController.h"

@interface RXWeatherView ()

@property (weak, nonatomic) IBOutlet UILabel *tempLabel;
@property (weak, nonatomic) IBOutlet UILabel *nowTempLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UILabel *pm2d5Label;
@property (weak, nonatomic) IBOutlet UIImageView *weatherImg;
@property (weak, nonatomic) IBOutlet UILabel *climateLabel;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;

- (IBAction)pushBtnDidClick:(id)sender;

@end

@implementation RXWeatherView

+ (instancetype)weatherView{

    return [[NSBundle mainBundle] loadNibNamed:@"RXWeatherView" owner:nil options:nil].firstObject;
}

#pragma mark - 添加底部按钮
- (void)layoutSubviews{

    [super layoutSubviews];

#warning 这里用collectionView开发效率更高
    [self.bottomView bottomView];
}

- (void)setWeatherModel:(RXWeather *)weatherModel{

    _weatherModel = weatherModel;

    /*
     {"北京|北京":[
     {"wind":"3-4级","nongli":"农历二月廿三日","date":"31日","climate":"晴","temperature":"23°C/13°C","week":"星期四"},
     {"wind":"3-4级","nongli":"农历二月廿四日","date":"1日","climate":"多云","temperature":"22°C/10°C","week":"星期五"},
     {"wind":"3-4级","nongli":"农历二月廿五日","date":"2日","climate":"多云","temperature":"20°C/8°C","week":"星期六"},
     {"wind":"微风","nongli":"农历二月廿六日","date":"3日","climate":"多云","temperature":"17°C/7°C","week":"星期日"}],
     "dt":"2016-03-31",
     "rt_temperature":23,
     "pm2d5":
     {"nbg1":"http://img1.cache.netease.com/m/newsapp/weather/TianQi370/QingTian.jpg","nbg2":"http://img1.cache.netease.com/m/newsapp/weather/TianQi1008/QingTian.jpg","aqi":"288","pm2_5":"237"}}
     */

    self.nowTempLabel.text = [NSString stringWithFormat:@"%@",weatherModel.nowTemperature];

//    self.nowTempLabel.text = @"-22";

    //处理今天的数据
    NSDictionary *todayDict = weatherModel.detailArray[0];

    RXWeatherDetail *weatherDetail = [RXWeatherDetail weatherDetailWithDict:todayDict];

    self.tempLabel.text = weatherDetail.temperature;

    self.dateLabel.text = [NSString stringWithFormat:@"%@ %@",weatherModel.date,weatherDetail.week];

    [self weatherImgSetImg:weatherDetail];

    self.climateLabel.text = [NSString stringWithFormat:@"%@ %@",weatherDetail.wind,weatherDetail.climate];

    self.locLabel.text = @"北京";

    //pm2d5模型
    RXPm2d5 *pm2d5 = [RXPm2d5 pm2d5WithDict:weatherModel.pm2d5];

    NSInteger pm2d5Value = pm2d5.pm2_5.integerValue;

    NSString *desc = [NSString string];
    if (pm2d5Value < 50) {
        desc = @"优";
    }else if (pm2d5Value < 100){

        desc = @"良";
    }else{

        desc = @"差";
    }

    self.pm2d5Label.text = [NSString stringWithFormat:@"PM2.5 %tu %@",pm2d5Value,desc];

}

- (void)weatherImgSetImg:(RXWeatherDetail *)weatherDetail{

    if ([weatherDetail.climate isEqualToString:@"雷阵雨"]) {
        self.weatherImg.image = [UIImage imageNamed:@"thunder_mini"];
    }else if ([weatherDetail.climate isEqualToString:@"晴"]){
        self.weatherImg.image = [UIImage imageNamed:@"sun_mini"];
    }else if ([weatherDetail.climate isEqualToString:@"多云"]){
        self.weatherImg.image = [UIImage imageNamed:@"sun_and_cloud_mini"];
    }else if ([weatherDetail.climate isEqualToString:@"阴"]){
        self.weatherImg.image = [UIImage imageNamed:@"nosun_mini"];
    }else if ([weatherDetail.climate hasSuffix:@"雨"]){
        self.weatherImg.image = [UIImage imageNamed:@"rain_mini"];
    }else if ([weatherDetail.climate hasSuffix:@"雪"]){
        self.weatherImg.image = [UIImage imageNamed:@"snow_heavyx_mini"];
    }else{
        self.weatherImg.image = [UIImage imageNamed:@"sand_float_mini"];
    }
}

- (IBAction)pushBtnDidClick:(id)sender {
    //不是控制器不能进行push操作,用通知或者代理监听
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushWeatherDetailVC" object:nil];
}
@end


text:
///////////////////////////////////////////////////////////////////////////////
//
/// \file       filter_decoder.c
/// \brief      Filter ID mapping to filter-specific functions
//
//  Author:     Lasse Collin
//
//  This file has been put into the public domain.
//  You can do whatever you want with this file.
//
///////////////////////////////////////////////////////////////////////////////

#include "filter_encoder.h"
#include "filter_common.h"
#include "lzma_encoder.h"
#include "lzma2_encoder.h"
#include "simple_encoder.h"
#include "delta_encoder.h"

typedef struct {
	/// Filter ID
	lzma_vli id;

	/// Initializes the filter encoder and calls lzma_next_filter_init()
	/// for filters + 1.
	lzma_init_function init;

	/// Calculates memory usage of the encoder. If the options are
	/// invalid, UINT64_MAX is returned.
	uint64_t (*memusage)(const void *options);

	/// Calculates the minimum sane size for Blocks (or other types of
	/// chunks) to which the input data can be split to make
	/// multithreaded encoding possible. If this is NULL, it is assumed
	/// that the encoder is fast enough with single thread.
	lzma_vli (*chunk_size)(const void *options);

	/// Tells the size of the Filter Properties field. If options are
	/// invalid, UINT32_MAX is returned. If this is NULL, props_size_fixed
	/// is used.
	lzma_ret (*props_size_get)(uint32_t *size, const void *options);
	uint32_t props_size_fixed;

	/// Encodes Filter Properties.
	///
	/// \return     - LZMA_OK: Properties encoded successfully.
	///             - LZMA_OPTIONS_ERROR: Unsupported options
	///             - LZMA_PROG_ERROR: Invalid options or not enough
	///               output space
	lzma_ret (*props_encode)(const void *options, uint8_t *out);

} lzma_filter_encoder;

static const lzma_filter_encoder encoders[] = {
#ifdef HAVE_ENCODER_LZMA1
	{
		.id = LZMA_FILTER_LZMA1,
		.init = &lzma_lzma_encoder_init,
		.memusage = &lzma_lzma_encoder_memusage,
		.chunk_size = NULL, // FIXME
		.props_size_get = NULL,
		.props_size_fixed = 5,
		.props_encode = &lzma_lzma_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_LZMA2
	{
		.id = LZMA_FILTER_LZMA2,
		.init = &lzma_lzma2_encoder_init,
		.memusage = &lzma_lzma2_encoder_memusage,
		.chunk_size = NULL, // FIXME
		.props_size_get = NULL,
		.props_size_fixed = 1,
		.props_encode = &lzma_lzma2_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_X86
	{
		.id = LZMA_FILTER_X86,
		.init = &lzma_simple_x86_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_POWERPC
	{
		.id = LZMA_FILTER_POWERPC,
		.init = &lzma_simple_powerpc_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_IA64
	{
		.id = LZMA_FILTER_IA64,
		.init = &lzma_simple_ia64_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_ARM
	{
		.id = LZMA_FILTER_ARM,
		.init = &lzma_simple_arm_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_ARMTHUMB
	{
		.id = LZMA_FILTER_ARMTHUMB,
		.init = &lzma_simple_armthumb_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_SPARC
	{
		.id = LZMA_FILTER_SPARC,
		.init = &lzma_simple_sparc_encoder_init,
		.memusage = NULL,
		.chunk_size = NULL,
		.props_size_get = &lzma_simple_props_size,
		.props_encode = &lzma_simple_props_encode,
	},
#endif
#ifdef HAVE_ENCODER_DELTA
	{
		.id = LZMA_FILTER_DELTA,
		.init = &lzma_delta_encoder_init,
		.memusage = &lzma_delta_coder_memusage,
		.chunk_size = NULL,
		.props_size_get = NULL,
		.props_size_fixed = 1,
		.props_encode = &lzma_delta_props_encode,
	},
#endif
};

static const lzma_filter_encoder *
encoder_find(lzma_vli id)
{
	for (size_t i = 0; i < ARRAY_SIZE(encoders); ++i)
		if (encoders[i].id == id)
			return encoders + i;

	return NULL;
}

extern LZMA_API(lzma_bool)
lzma_filter_encoder_is_supported(lzma_vli id)
{
	return encoder_find(id) != NULL;
}

extern LZMA_API(lzma_ret)
lzma_filters_update(lzma_stream *strm, const lzma_filter *filters)
{
	if (strm->internal->next.update == NULL)
		return LZMA_PROG_ERROR;

	// Validate the filter chain.
	if (lzma_raw_encoder_memusage(filters) == UINT64_MAX)
		return LZMA_OPTIONS_ERROR;

	// The actual filter chain in the encoder is reversed. Some things
	// still want the normal order chain, so we provide both.
	size_t count = 1;
	while (filters[count].id != LZMA_VLI_UNKNOWN)
		++count;

	lzma_filter reversed_filters[LZMA_FILTERS_MAX + 1];
	for (size_t i = 0; i < count; ++i)
		reversed_filters[count - i - 1] = filters[i];

	reversed_filters[count].id = LZMA_VLI_UNKNOWN;

	return strm->internal->next.update(strm->internal->next.coder,
			strm->allocator, filters, reversed_filters);
}

extern lzma_ret
lzma_raw_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
		const lzma_filter *options)
{
	return lzma_raw_coder_init(next, allocator,
			options, (lzma_filter_find)(&encoder_find), true);
}

extern LZMA_API(lzma_ret)
lzma_raw_encoder(lzma_stream *strm, const lzma_filter *options)
{
	lzma_next_strm_init(lzma_raw_coder_init, strm, options,
			(lzma_filter_find)(&encoder_find), true);

	strm->internal->supported_actions[LZMA_RUN] = true;
	strm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;
	strm->internal->supported_actions[LZMA_FINISH] = true;

	return LZMA_OK;
}

extern LZMA_API(uint64_t)
lzma_raw_encoder_memusage(const lzma_filter *filters)
{
	return lzma_raw_coder_memusage(
			(lzma_filter_find)(&encoder_find), filters);
}

/*
extern LZMA_API(lzma_vli)
lzma_chunk_size(const lzma_filter *filters)
{
	lzma_vli max = 0;

	for (size_t i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i) {
		const lzma_filter_encoder *const fe
				= encoder_find(filters[i].id);
		if (fe->chunk_size != NULL) {
			const lzma_vli size
					= fe->chunk_size(filters[i].options);
			if (size == LZMA_VLI_UNKNOWN)
				return LZMA_VLI_UNKNOWN;

			if (size > max)
				max = size;
		}
	}

	return max;
}
*/

extern LZMA_API(lzma_ret)
lzma_properties_size(uint32_t *size, const lzma_filter *filter)
{
	const lzma_filter_encoder *const fe = encoder_find(filter->id);
	if (fe == NULL) {
		// Unknown filter - if the Filter ID is a proper VLI,
		// return LZMA_OPTIONS_ERROR instead of LZMA_PROG_ERROR,
		// because it's possible that we just don't have support
		// compiled in for the requested filter.
		return filter->id <= LZMA_VLI_MAX
				? LZMA_OPTIONS_ERROR : LZMA_PROG_ERROR;
	}

	if (fe->props_size_get == NULL) {
		// No props_size_get() function, use props_size_fixed.
		*size = fe->props_size_fixed;
		return LZMA_OK;
	}

	return fe->props_size_get(size, filter->options);
}

extern LZMA_API(lzma_ret)
lzma_properties_encode(const lzma_filter *filter, uint8_t *props)
{
	const lzma_filter_encoder *const fe = encoder_find(filter->id);
	if (fe == NULL)
		return LZMA_PROG_ERROR;

	if (fe->props_encode == NULL)
		return LZMA_OK;

	return fe->props_encode(filter->options, props);
}


text:
package com.plc.service.impl;

import java.util.List;

import com.plc.domain.VedioTypeRepository;
import com.plc.service.VedioTypeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.plc.model.VedioType;

@Service("VedioTypeService")
public class VedioTypeServiceImpl implements VedioTypeService {
	// Log
	private final Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private VedioTypeRepository vedioTypeRepository;

	@Override
	public List<VedioType> findAll() {
		return vedioTypeRepository.findAll();
	}
}


text:
<?php

declare(strict_types=1);

namespace Dot\Helpers;

use Dot\Helpers\Middleware\MiddlewareName;
use Zend\ServiceManager\Factory\InvokableFactory;

/**
 * Class ConfigProvider
 * @package Dot\Helpers
 */
class ConfigProvider
{
    public function __invoke()
    {
        return [
            'dependencies' => $this->getDependencies(),
        ];
    }

    public function getDependencies()
    {
        return [
            'factories' => [
                MiddlewareName::class => InvokableFactory::class,
            ]
        ];
    }
}


text:
package objektwerks.cats

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

class WriterMonadTest extends AnyFunSuite with Matchers {
  test("writer monad") {
    import cats.data.Writer

    val writer = Writer(Vector("A joke is a very serious thing.", "Winston Churchill"), 1939)
    val (quotes, year) = writer.run
    quotes.size shouldEqual 2
    year shouldEqual 1939
  }
}