text:
package com.googlecode.mp4parser.authoring.builder;

import com.coremedia.iso.boxes.OriginalFormatBox;
import com.coremedia.iso.boxes.sampleentry.AudioSampleEntry;
import com.coremedia.iso.boxes.sampleentry.SampleEntry;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.util.Path;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import static com.googlecode.mp4parser.util.Math.lcm;

/**
 * This FragmentIntersectionFinder cuts the input movie video tracks in
 * fragments of the same length exactly before the sync samples. Audio tracks are cut
 * into pieces of similar length.
 */
public class SyncSampleIntersectFinderImpl implements FragmentIntersectionFinder {

    private static Logger LOG = Logger.getLogger(SyncSampleIntersectFinderImpl.class.getName());
    private static Map<CacheTuple, long[]> getTimesCache = new ConcurrentHashMap<CacheTuple, long[]>();
    private static Map<CacheTuple, long[]> getSampleNumbersCache = new ConcurrentHashMap<CacheTuple, long[]>();

    private final int minFragmentDurationSeconds;
    private Movie movie;
    private Track referenceTrack;

    /**
     * Creates a SyncSampleIntersectFinderImpl that will not create any fragment
     * smaller than the given minFragmentDurationSeconds
     *
     * @param minFragmentDurationSeconds the smallest allowable duration of a fragment.
     */
    public SyncSampleIntersectFinderImpl(Movie movie, Track referenceTrack, int minFragmentDurationSeconds) {
        this.movie = movie;
        this.referenceTrack = referenceTrack;
        this.minFragmentDurationSeconds = minFragmentDurationSeconds;
    }

    static String getFormat(Track track) {
        SampleEntry se = track.getSampleDescriptionBox().getSampleEntry();
        String type = se.getType();
        if (type.equals("encv") || type.equals("enca") || type.equals("encv")) {
            OriginalFormatBox frma = (OriginalFormatBox) Path.getPath(se, "sinf/frma");
            type = frma.getDataFormat();
        }
        return type;
    }

    /**
     * Gets an array of sample numbers that are meant to be the first sample of each
     * chunk or fragment.
     *
     * @param track concerned track
     * @return an array containing the ordinal of each fragment's first sample
     */
    public long[] sampleNumbers(Track track) {
        final CacheTuple key = new CacheTuple(track, movie);
        final long[] result = getSampleNumbersCache.get(key);
        if (result != null) {
            return result;
        }

        if ("vide".equals(track.getHandler())) {
            if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
                List<long[]> times = getSyncSamplesTimestamps(movie, track);
                final long[] commonIndices = getCommonIndices(track.getSyncSamples(), getTimes(track, movie), track.getTrackMetaData().getTimescale(), times.toArray(new long[times.size()][]));
                getSampleNumbersCache.put(key, commonIndices);
                return commonIndices;
            } else {
                throw new RuntimeException("Video Tracks need sync samples. Only tracks other than video may have no sync samples.");
            }
        } else if ("soun".equals(track.getHandler())) {
            if (referenceTrack == null) {
                for (Track candidate : movie.getTracks()) {
                    if (candidate.getSyncSamples() != null && "vide".equals(candidate.getHandler()) && candidate.getSyncSamples().length > 0) {
                        referenceTrack = candidate;
                    }
                }
            }
            if (referenceTrack != null) {

                // Gets the reference track's fra
                long[] refSyncSamples = sampleNumbers(referenceTrack);

                int refSampleCount = referenceTrack.getSamples().size();

                long[] syncSamples = new long[refSyncSamples.length];
                long minSampleRate = 192000;
                for (Track testTrack : movie.getTracks()) {
                    if (getFormat(track).equals(getFormat(testTrack))) {
                        AudioSampleEntry ase = (AudioSampleEntry) testTrack.getSampleDescriptionBox().getSampleEntry();
                        if (ase.getSampleRate() < minSampleRate) {
                            minSampleRate = ase.getSampleRate();
                            long sc = testTrack.getSamples().size();
                            double stretch = (double) sc / refSampleCount;

                            long samplesPerFrame = testTrack.getSampleDurations()[0]; // Assuming all audio tracks have the same number of samples per frame, which they do for all known types

                            for (int i = 0; i < syncSamples.length; i++) {
                                long start = (long) Math.ceil(stretch * (refSyncSamples[i] - 1) * samplesPerFrame);
                                syncSamples[i] = start;
                                // The Stretch makes sure that there are as much audio and video chunks!
                            }
                            break;
                        }
                    }
                }
                AudioSampleEntry ase = (AudioSampleEntry) track.getSampleDescriptionBox().getSampleEntry();

                long samplesPerFrame = track.getSampleDurations()[0]; // Assuming all audio tracks have the same number of samples per frame, which they do for all known types
                double factor = (double) ase.getSampleRate() / (double) minSampleRate;
                if (factor != Math.rint(factor)) { // Not an integer
                    throw new RuntimeException("Sample rates must be a multiple of the lowest sample rate to create a correct file!");
                }
                for (int i = 0; i < syncSamples.length; i++) {
                    syncSamples[i] = (long) (1 + syncSamples[i] * factor / (double) samplesPerFrame);
                }
                getSampleNumbersCache.put(key, syncSamples);
                return syncSamples;
            }
            throw new RuntimeException("There was absolutely no Track with sync samples. I can't work with that!");
        } else {
            // Ok, my track has no sync samples - let's find one with sync samples.
            for (Track candidate : movie.getTracks()) {
                if (candidate.getSyncSamples() != null && candidate.getSyncSamples().length > 0) {
                    long[] refSyncSamples = sampleNumbers(candidate);
                    int refSampleCount = candidate.getSamples().size();

                    long[] syncSamples = new long[refSyncSamples.length];
                    long sc = track.getSamples().size();
                    double stretch = (double) sc / refSampleCount;

                    for (int i = 0; i < syncSamples.length; i++) {
                        long start = (long) Math.ceil(stretch * (refSyncSamples[i] - 1)) + 1;
                        syncSamples[i] = start;
                        // The Stretch makes sure that there are as much audio and video chunks!
                    }
                    getSampleNumbersCache.put(key, syncSamples);
                    return syncSamples;
                }
            }
            throw new RuntimeException("There was absolutely no Track with sync samples. I can't work with that!");
        }

    }

    /**
     * Calculates the timestamp of all tracks' sync samples.
     *
     * @param movie track is located in this movie
     * @param track get this track's samples timestamps
     * @return a list of timestamps
     */
    public static List<long[]> getSyncSamplesTimestamps(Movie movie, Track track) {
        List<long[]> times = new LinkedList<long[]>();
        for (Track currentTrack : movie.getTracks()) {
            if (currentTrack.getHandler().equals(track.getHandler())) {
                long[] currentTrackSyncSamples = currentTrack.getSyncSamples();
                if (currentTrackSyncSamples != null && currentTrackSyncSamples.length > 0) {
                    final long[] currentTrackTimes = getTimes(currentTrack, movie);
                    times.add(currentTrackTimes);
                }
            }
        }
        return times;
    }

    public long[] getCommonIndices(long[] syncSamples, long[] syncSampleTimes, long timeScale, long[]... otherTracksTimes) {
        List<Long> nuSyncSamples = new LinkedList<Long>();
        List<Long> nuSyncSampleTimes = new LinkedList<Long>();

        for (int i = 0; i < syncSampleTimes.length; i++) {
            boolean foundInEveryRef = true;
            for (long[] times : otherTracksTimes) {
                foundInEveryRef &= (Arrays.binarySearch(times, syncSampleTimes[i]) >= 0);
            }

            if (foundInEveryRef) {
                // use sample only if found in every other track.
                nuSyncSamples.add(syncSamples[i]);
                nuSyncSampleTimes.add(syncSampleTimes[i]);
            }
        }
        // We have two arrays now:
        // nuSyncSamples: Contains all common sync samples
        // nuSyncSampleTimes: Contains the times of all sync samples

        // Start: Warn user if samples are not matching!
        if (nuSyncSamples.size() < (syncSamples.length * 0.25)) {
            String log = "";
            log += String.format("%5d - Common:  [", nuSyncSamples.size());
            for (long l : nuSyncSamples) {
                log += (String.format("%10d,", l));
            }
            log += ("]");
            LOG.warning(log);
            log = "";

            log += String.format("%5d - In    :  [", syncSamples.length);
            for (long l : syncSamples) {
                log += (String.format("%10d,", l));
            }
            log += ("]");
            LOG.warning(log);
            LOG.warning("There are less than 25% of common sync samples in the given track.");
            throw new RuntimeException("There are less than 25% of common sync samples in the given track.");
        } else if (nuSyncSamples.size() < (syncSamples.length * 0.5)) {
            LOG.fine("There are less than 50% of common sync samples in the given track. This is implausible but I'm ok to continue.");
        } else if (nuSyncSamples.size() < syncSamples.length) {
            LOG.finest("Common SyncSample positions vs. this tracks SyncSample positions: " + nuSyncSamples.size() + " vs. " + syncSamples.length);
        }
        // End: Warn user if samples are not matching!

        List<Long> finalSampleList = new LinkedList<Long>();

        if (minFragmentDurationSeconds > 0) {
            // if minFragmentDurationSeconds is greater 0
            // we need to throw away certain samples.
            long lastSyncSampleTime = -1;
            Iterator<Long> nuSyncSamplesIterator = nuSyncSamples.iterator();
            Iterator<Long> nuSyncSampleTimesIterator = nuSyncSampleTimes.iterator();
            while (nuSyncSamplesIterator.hasNext() && nuSyncSampleTimesIterator.hasNext()) {
                long curSyncSample = nuSyncSamplesIterator.next();
                long curSyncSampleTime = nuSyncSampleTimesIterator.next();
                if (lastSyncSampleTime == -1 || (curSyncSampleTime - lastSyncSampleTime) / timeScale >= minFragmentDurationSeconds) {
                    finalSampleList.add(curSyncSample);
                    lastSyncSampleTime = curSyncSampleTime;
                }
            }
        } else {
            // the list of all samples is the final list of samples
            // since minFragmentDurationSeconds ist not used.
            finalSampleList = nuSyncSamples;
        }

        // transform the list to an array
        long[] finalSampleArray = new long[finalSampleList.size()];
        for (int i = 0; i < finalSampleArray.length; i++) {
            finalSampleArray[i] = finalSampleList.get(i);
        }
        return finalSampleArray;

    }

    private static long[] getTimes(Track track, Movie m) {
        long[] syncSamples = track.getSyncSamples();
        long[] syncSampleTimes = new long[syncSamples.length];

        int currentSample = 1;  // first syncsample is 1
        long currentDuration = 0;
        int currentSyncSampleIndex = 0;

        final long scalingFactor = calculateTracktimesScalingFactor(m, track);

        while (currentSample < syncSamples[syncSamples.length - 1]) {
            if (currentSample == syncSamples[currentSyncSampleIndex]) {
                syncSampleTimes[currentSyncSampleIndex++] = currentDuration * scalingFactor;
            }
            currentDuration += track.getSampleDurations()[currentSample++];
        }
        return syncSampleTimes;
    }

    private static long calculateTracktimesScalingFactor(Movie m, Track track) {
        long timeScale = 1;
        for (Track track1 : m.getTracks()) {
            if (track1.getHandler().equals(track.getHandler())) {
                if (track1.getTrackMetaData().getTimescale() != track.getTrackMetaData().getTimescale()) {
                    timeScale = lcm(timeScale, track1.getTrackMetaData().getTimescale());
                }
            }
        }
        return timeScale;
    }

    public static class CacheTuple {
        Track track;
        Movie movie;

        public CacheTuple(Track track, Movie movie) {
            this.track = track;
            this.movie = movie;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CacheTuple that = (CacheTuple) o;

            if (movie != null ? !movie.equals(that.movie) : that.movie != null) return false;
            if (track != null ? !track.equals(that.track) : that.track != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = track != null ? track.hashCode() : 0;
            result = 31 * result + (movie != null ? movie.hashCode() : 0);
            return result;
        }
    }
}


text:
<?php

namespace CachetHQ\Cachet\Events\Subscriber;

use CachetHQ\Cachet\Models\Subscriber;

class SubscriberHasUnsubscribedEvent
{
    /**
     * The subscriber who has unsubscribed.
     *
     * @var \CachetHQ\Cachet\Models\Subscriber
     */
    public $subscriber;

    /**
     * Create a new subscriber has unsubscribed event instance.
     *
     * @return void
     */
    public function __construct(Subscriber $subscriber)
    {
        $this->subscriber = $subscriber;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'erb'
require_relative 'template_processor'

module Compiler
  class DjangoProcessor < TemplateProcessor

    def self.block_for(key, default_value="")
      "{% block #{key} %}#{default_value}{% endblock %}"
    end

    def self.statement_tag_for(key, default_value)
      "{{ #{key}|default:'#{default_value}' }}"
    end

    @@yield_hash = {
      after_header:         block_for(:after_header),
      body_classes:         block_for(:body_classes),
      body_start:           block_for(:body_start),
      body_end:             block_for(:body_end),
      content:              block_for(:content),
      cookie_message:       block_for(:cookie_message),
      footer_support_links: block_for(:footer_support_links),
      footer_top:           block_for(:footer_top),
      homepage_url:         statement_tag_for(:homepage_url, 'https://www.gov.uk'),
      global_header_text:   statement_tag_for(:global_header_text, 'GOV.UK'),
      head:                 block_for(:head),
      header_class:         block_for(:header_class),
      html_lang:            statement_tag_for(:html_lang, 'en'),
      inside_header:        block_for(:inside_header),
      page_title:           block_for(:page_title, "GOV.UK - The best place to find government services and information"),
      proposition_header:   block_for(:proposition_header),
      top_of_page:          "{% load staticfiles %}" + block_for(:top_of_page),
      skip_link_message:    statement_tag_for(:skip_link_message, 'Skip to main content'),
      logo_link_title:      statement_tag_for(:logo_link_title, 'Go to the GOV.UK homepage'),
      licence_message:      block_for(:licence_message, '
All content is available under the Open Government Licence v3.0, except where otherwise stated
'),
      crown_copyright_message: statement_tag_for(:crown_copyright_message, '© Crown copyright'),
    }

    def handle_yield(section = :layout)
      @@yield_hash[section]
    end

    def asset_path(file, options={})
      query_string = GovukTemplate::VERSION
      return "#{file}?#{query_string}" if @is_stylesheet
      case File.extname(file)
      when '.css'
        "{% static 'stylesheets/#{file}' %}"
      when '.js'
        "{% static 'javascripts/#{file}' %}"
      else
        "{% static 'images/#{file}' %}"
      end
    end
  end
end


text:
class GURL;
class Profile;

namespace base {
class CommandLine;
class FilePath;
}

namespace content {
class WebContents;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

// This namespace contains the chrome first-run installation actions needed to
// fully test the custom installer. It also contains the opposite actions to
// execute during uninstall. When the first run UI is ready we won't
// do the actions unconditionally. Currently the only action is to create a
// desktop shortcut.
//
// The way we detect first-run is by looking at a 'sentinel' file.
// If it does not exist we understand that we need to do the first time
// install work for this user. After that the sentinel file is created.
namespace first_run {

enum AutoImportState {
  AUTO_IMPORT_NONE = 0,
  AUTO_IMPORT_CALLED = 1 << 0,
  AUTO_IMPORT_PROFILE_IMPORTED = 1 << 1,
  AUTO_IMPORT_BOOKMARKS_FILE_IMPORTED = 1 << 2,
};

enum ProcessMasterPreferencesResult {
  FIRST_RUN_PROCEED = 0,  // Proceed with first run.
  EULA_EXIT_NOW,          // Should immediately exit due to EULA flow.
};

// See ProcessMasterPreferences for more info about this structure.
struct MasterPrefs {
  MasterPrefs();
  ~MasterPrefs();

  // TODO(macourteau): as part of the master preferences refactoring effort,
  // remove items from here which are being stored temporarily only to be later
  // dumped into local_state. Also see related TODO in chrome_browser_main.cc.

  bool make_chrome_default_for_user = false;
  std::vector<GURL> new_tabs;
  std::vector<GURL> bookmarks;
  std::string import_bookmarks_path;
  std::string suppress_default_browser_prompt_for_version;
};

void RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry);

// Returns true if Chrome should behave as if this is the first time Chrome is
// run for this user.
bool IsChromeFirstRun();

#if defined(OS_MACOSX)
// Returns true if |command_line|'s switches explicitly specify that first run
// should be suppressed in the current run.
bool IsFirstRunSuppressed(const base::CommandLine& command_line);
#endif

// Returns whether metrics reporting is currently opt-in. This is used to
// determine if the enable metrics reporting checkbox on first-run should be
// initially checked. Opt-in means it is not initially checked, opt-out means it
// is. This is not guaranteed to be correct outside of the first-run situation,
// as the default may change over time. For that, use
// GetMetricsReportingDefaultState in
// chrome/browser/metrics/metrics_reporting_state.h, which gives a value that
// was stored during first-run.
bool IsMetricsReportingOptIn();

// Creates the first run sentinel if needed. This should only be called after
// the process singleton has been grabbed by the current process
// (http://crbug.com/264694).
void CreateSentinelIfNeeded();

// Returns the first run sentinel creation time. This only requires I/O
// permission on the sequence it is first called on.
base::Time GetFirstRunSentinelCreationTime();

// Resets the first run status and cached first run sentinel creation time.
// This is needed for unit tests which are runned in the same process.
void ResetCachedSentinelDataForTesting();

// Sets a flag that will cause ShouldShowWelcomePage to return true
// exactly once, so that the browser loads the welcome tab once the
// message loop gets going.
void SetShouldShowWelcomePage();

// Returns true if the welcome page should be shown.
//
// This will return true only once: The first time it is called after
// SetShouldShowWelcomePage() is called.
bool ShouldShowWelcomePage();

// Returns true if |contents| hosts one of the welcome pages.
bool IsOnWelcomePage(content::WebContents* contents);

// Iterates over the given tabs, replacing "magic words" designated for
// use in Master Preferences files with corresponding URLs.
std::vector<GURL> ProcessMasterPrefsTabs(const std::vector<GURL>& tabs);

// Sets a flag that will cause ShouldDoPersonalDataManagerFirstRun()
// to return true exactly once, so that the browser loads
// PersonalDataManager once the main message loop gets going.
void SetShouldDoPersonalDataManagerFirstRun();

// Returns true if the autofill personal data manager first-run action
// should be taken.
//
// This will return true only once, the first time it is called after
// SetShouldDoPersonalDataManagerFirstRun() is called.
bool ShouldDoPersonalDataManagerFirstRun();

// Automatically imports items requested by |profile|'s configuration (sum of
// policies and master prefs). Also imports bookmarks from file if
// |import_bookmarks_path| is not empty.
void AutoImport(Profile* profile,
                const std::string& import_bookmarks_path);

// Does remaining first run tasks. This can pop the first run consent dialog on
// linux. |make_chrome_default_for_user| is the value of
// kMakeChromeDefaultForUser in master_preferences which contributes to the
// decision of making chrome default browser in post import tasks.
void DoPostImportTasks(Profile* profile, bool make_chrome_default_for_user);

// Returns the current state of AutoImport as recorded in a bitfield formed from
// values in AutoImportState.
uint16_t auto_import_state();

// Set a master preferences file path that overrides platform defaults.
void SetMasterPrefsPathForTesting(const base::FilePath& master_prefs);

// Loads master preferences from the master preference file into the installer
// master preferences. Returns the pointer to installer::MasterPreferences
// object if successful; otherwise, returns nullptr.
std::unique_ptr<installer::MasterPreferences> LoadMasterPrefs();

// The master_preferences is a JSON file with the same entries as the
// 'Default\Preferences' file. This function locates this file from a standard
// location, processes it, and uses its content to initialize the preferences
// for the profile pointed to by |user_data_dir|. After processing the file,
// this function returns a value from the ProcessMasterPreferencesResult enum,
// indicating whether the first run flow should be shown, skipped, or whether
// the browser should exit.
//
// This function overwrites any existing Preferences file and is only meant to
// be invoked on first run.
//
// See chrome/installer/util/master_preferences.h for a description of
// 'master_preferences' file.
ProcessMasterPreferencesResult ProcessMasterPreferences(
    const base::FilePath& user_data_dir,
    std::unique_ptr<installer::MasterPreferences> install_prefs,
    MasterPrefs* out_prefs);

}  // namespace first_run

#endif  // CHROME_BROWSER_FIRST_RUN_FIRST_RUN_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>VM Infrastructure: Main Page</title>
<link href="hydoxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Packages

Classes

Files

Related Pages

VM Infrastructure Documentation

unknown

<address style="text-align: center;">

Genereated on Tue Mar 11 19:25:55 2008 by Doxygen.

(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable.

</address>


text:
package edu.coldserenity.tij.ch09.ex08;

/**
 * Exercise 8: (2)
 *

 * Determine whether an outer class has access to the private elements of
 * its inner class.
 *

 * =======================
 * Yes it has access to private members of instances of inner classes.
 */
public class OuterAccessesPrivateMembersOfInner {
    public static void main(String[] args) {
        new Outer().testMethod();
    }
}

class Outer {
    class Inner {
        private int privateField = 300;

        private void privateMethod() {
            System.out.println("Outer.Inner.privateMethod() triggered");
        }

        @Override
        public String toString() {
            return "Inner{" +
                    "privateField=" + privateField +
                    '}';
        }
    }

    public void testMethod() {
        Inner inner = new Inner();
        System.out.println("New Inner created:");
        System.out.println(inner);
        inner.privateField = 100;
        inner.privateMethod();
        System.out.println("\nAfter direct field access:");
        System.out.println(inner);
    }
}


text:
namespace ppapi {
namespace proxy {

class BrokerResource
    : public PluginResource,
      public thunk::PPB_Broker_Instance_API {
 public:
  BrokerResource(Connection connection, PP_Instance instance);
  ~BrokerResource() override;

  // Resource override.
  thunk::PPB_Broker_Instance_API* AsPPB_Broker_Instance_API() override;

  // thunk::PPB_Broker_Instance_API implementation.
  PP_Bool IsAllowed() override;

 private:
  DISALLOW_COPY_AND_ASSIGN(BrokerResource);
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_BROKER_RESOURCE_H_


text:
<?php
/**
 * Calculates the shipping cost of an order, by taking the products
 * and calculating the shipping weight, based on an array set in _config
 *
 * ASSUMPTION: The total order weight can be at maximum the last item
 * in the $shippingCosts array.
 *
 * @package shop
 * @subpackage modifiers
 */
class WeightShippingModifier extends ShippingModifier {

	protected static $weight_cost = array(
		0.5 => 10,
		1 => 20,
		999 => 50
	);
	protected $weight = 0;

	public static function set_weight_costs($costs){
		self::$weight_cost = $costs;
	}

	/**
	* Calculates shipping cost based on Product Weight.
	*/
	public function value($subtotal = 0){
		$totalWeight = $this->Weight();
		if(!$totalWeight){
			return $this->Amount = 0;
		}
		$amount = 0;

		foreach(self::$weight_cost as $weight => $cost) {
			if($totalWeight <= $weight){
				$amount =  $cost;
				break;
			}
		}
		return $this->Amount = $amount;
	}

	public function TableTitle(){
		return  sprintf(_t("WeightShippingModifier.TABLETITLE","Shipping (%f kg)"),$this->Weight());
	}

	/**
	 * Calculate the total weight of the order
	 * @return number
	 */
	public function Weight(){
		if($this->weight){
			return $this->weight;
		}
		$weight = 0;
		$order = $this->Order();
		if($order && $orderItems = $order->Items()) {
			foreach($orderItems as $orderItem){
				if($product = $orderItem->Product()){
					$weight = $weight + ($product->Weight * $orderItem->Quantity);
				}
			}
		}
		return $this->weight = $weight;
	}

}


text:
package io.realm.entities;

import io.realm.RealmObject;
import io.realm.annotations.Required;

// This class is used for the pre-null testing. Before 0.83.0, without nullable support, String is required by default.
// To use the Realm file created before 0.83.0 without migration, @Required has to be added to the String field.
public class StringOnlyRequired extends RealmObject {
    @Required
    private String chars;

    public String getChars() {
        return chars;
    }

    public void setChars(String chars) {
        this.chars = chars;
    }
}


text:
<?php

/**
 * This file is part of the mo4-coding-standard (phpcs standard)
 *
 * @author  Xaver Loppenstedt <xaver@loppenstedt.de>
 *
 * @license http://spdx.org/licenses/MIT MIT License
 *
 * @link    https://github.com/mayflower/mo4-coding-standard
 */

declare(strict_types=1);

namespace MO4\Sniffs\Arrays;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

/**
 * Multi Line Array sniff.
 *
 * @author    Xaver Loppenstedt <xaver@loppenstedt.de>
 *
 * @copyright 2013-2017 Xaver Loppenstedt, some rights reserved.
 *
 * @license   http://spdx.org/licenses/MIT MIT License
 *
 * @link      https://github.com/mayflower/mo4-coding-standard
 */
class MultiLineArraySniff implements Sniff
{
    /**
     * Define all types of arrays.
     *
     * @var array
     */
    protected $arrayTokens = [
        // @phan-suppress-next-line PhanUndeclaredConstant
        T_OPEN_SHORT_ARRAY,
        T_ARRAY,
    ];

    /**
     * Registers the tokens that this sniff wants to listen for.
     *
     * @return array<int, int>
     *
     * @see    Tokens.php
     */
    public function register(): array
    {
        return $this->arrayTokens;
    }

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint
     *
     * @param File $phpcsFile The file being scanned.
     * @param int  $stackPtr  The position of the current token in
     *                        the stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr): void
    {
        $tokens  = $phpcsFile->getTokens();
        $current = $tokens[$stackPtr];

        if (T_ARRAY === $current['code']) {
            $arrayType = 'parenthesis';
            $start     = $current['parenthesis_opener'];
            $end       = $current['parenthesis_closer'];
        } else {
            $arrayType = 'bracket';
            $start     = $current['bracket_opener'];
            $end       = $current['bracket_closer'];
        }

        if ($tokens[$start]['line'] === $tokens[$end]['line']) {
            return;
        }

        if ($tokens[($start + 2)]['line'] === $tokens[$start]['line']) {
            $fixable = $phpcsFile->addFixableError(
                \sprintf(
                    'opening %s of multi line array must be followed by newline',
                    $arrayType
                ),
                $start,
                'OpeningMustBeFollowedByNewline'
            );

            if (true === $fixable) {
                $phpcsFile->fixer->beginChangeset();
                $phpcsFile->fixer->addNewline($start);
                $phpcsFile->fixer->endChangeset();
            }
        }

        if ($tokens[($end - 2)]['line'] !== $tokens[$end]['line']) {
            return;
        }

        $fixable = $phpcsFile->addFixableError(
            \sprintf(
                'closing %s of multi line array must in own line',
                $arrayType
            ),
            $end,
            'ClosingMustBeInOwnLine'
        );

        if (true !== $fixable) {
            return;
        }

        $phpcsFile->fixer->beginChangeset();
        $phpcsFile->fixer->addNewlineBefore($end);
        $phpcsFile->fixer->endChangeset();
    }
}


text:
require "chef/event_dispatch/base"
require "chef/audit/control_group_data"
require "time"

class Chef
  class Audit
    class AuditReporter < EventDispatch::Base

      attr_reader :rest_client, :audit_data, :ordered_control_groups, :run_status
      private :rest_client, :audit_data, :ordered_control_groups, :run_status

      PROTOCOL_VERSION = "0.1.1"

      def initialize(rest_client)
        @rest_client = rest_client
        # Ruby 1.9.3 and above "enumerate their values in the order that the corresponding keys were inserted."
        @ordered_control_groups = Hash.new
        @audit_phase_error = nil
      end

      def run_context
        run_status.run_context
      end

      def audit_phase_start(run_status)
        Chef::Log.debug("Audit Reporter starting")
        @audit_data = AuditData.new(run_status.node.name, run_status.run_id)
        @run_status = run_status
      end

      def audit_phase_complete(audit_output)
        Chef::Log.debug("Audit Reporter completed successfully without errors.")
        ordered_control_groups.each_value do |control_group|
          audit_data.add_control_group(control_group)
        end
      end

      # If the audit phase failed, its because there was some kind of error in the framework
      # that runs tests - normal errors are interpreted as EXAMPLE failures and captured.
      # We still want to send available audit information to the server so we process the
      # known control groups.
      def audit_phase_failed(error, audit_output)
        # The stacktrace information has already been logged elsewhere
        @audit_phase_error = error
        Chef::Log.debug("Audit Reporter failed.")
        ordered_control_groups.each_value do |control_group|
          audit_data.add_control_group(control_group)
        end
      end

      def run_completed(node)
        post_auditing_data
      end

      def run_failed(error)
        # Audit phase errors are captured when audit_phase_failed gets called.
        # The error passed here isn't relevant to auditing, so we ignore it.
        post_auditing_data
      end

      def control_group_started(name)
        if ordered_control_groups.has_key?(name)
          raise Chef::Exceptions::AuditControlGroupDuplicate.new(name)
        end
        metadata = run_context.audits[name].metadata
        ordered_control_groups.store(name, ControlGroupData.new(name, metadata))
      end

      def control_example_success(control_group_name, example_data)
        control_group = ordered_control_groups[control_group_name]
        control_group.example_success(example_data)
      end

      def control_example_failure(control_group_name, example_data, error)
        control_group = ordered_control_groups[control_group_name]
        control_group.example_failure(example_data, error.message)
      end

      # If @audit_enabled is nil or true, we want to run audits
      def auditing_enabled?
        Chef::Config[:audit_mode] != :disabled
      end

      private

      def post_auditing_data
        unless auditing_enabled?
          Chef::Log.debug("Audit Reports are disabled. Skipping sending reports.")
          return
        end

        unless run_status
          Chef::Log.debug("Run failed before audit mode was initialized, not sending audit report to server")
          return
        end

        audit_data.start_time = iso8601ify(run_status.start_time)
        audit_data.end_time = iso8601ify(run_status.end_time)

        audit_history_url = "controls"
        Chef::Log.debug("Sending audit report (run-id: #{audit_data.run_id})")
        run_data = audit_data.to_hash

        if @audit_phase_error
          error_info = "#{@audit_phase_error.class}: #{@audit_phase_error.message}"
          error_info << "\n#{@audit_phase_error.backtrace.join("\n")}" if @audit_phase_error.backtrace
          run_data[:error] = error_info
        end

        Chef::Log.debug "Audit Report:\n#{Chef::JSONCompat.to_json_pretty(run_data)}"
        begin
          rest_client.post(audit_history_url, run_data, headers)
        rescue StandardError => e
          if e.respond_to? :response
            # 404 error code is OK. This means the version of server we're running against doesn't support
            # audit reporting. Don't alarm failure in this case.
            if e.response.code == "404"
              Chef::Log.debug("Server doesn't support audit reporting. Skipping report.")
              return
            else
              # Save the audit report to local disk
              error_file = "failed-audit-data.json"
              Chef::FileCache.store(error_file, Chef::JSONCompat.to_json_pretty(run_data), 0640)
              if Chef::Config.chef_zero.enabled
                Chef::Log.debug("Saving audit report to #{Chef::FileCache.load(error_file, false)}")
              else
                Chef::Log.error("Failed to post audit report to server. Saving report to #{Chef::FileCache.load(error_file, false)}")
              end
            end
          else
            Chef::Log.error("Failed to post audit report to server (#{e})")
          end

          if Chef::Config[:enable_reporting_url_fatals]
            Chef::Log.error("Reporting fatals enabled. Aborting run.")
            raise
          end
        end
      end

      def headers(additional_headers = {})
        options = { "X-Ops-Audit-Report-Protocol-Version" => PROTOCOL_VERSION }
        options.merge(additional_headers)
      end

      def encode_gzip(data)
        "".tap do |out|
          Zlib::GzipWriter.wrap(StringIO.new(out)) { |gz| gz << data }
        end
      end

      def iso8601ify(time)
        time.utc.iso8601.to_s
      end
    end
  end
end


text:
package com.microsoft.windowsazure.services.media.implementation.templates.tokenrestriction;

public final class ErrorMessages {

    public static final String PRIMARY_VERIFICATIONKEY_AND_OPENIDCONNECTDISCOVERYDOCUMENT_ARE_NULL
        = "Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null.";

    public static final String OPENIDDISCOVERYURI_STRING_IS_NULL_OR_EMPTY
        = "OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri string value is null or empty.";

    public static final String OPENIDDISCOVERYURI_STRING_IS_NOT_ABSOLUTE_URI
        = "String representation of OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri is not valid absolute Uri.";

    private ErrorMessages() {
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Font label
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoodocCharLabel extends com.google.api.client.json.GenericJson {

  /**
   * The shift of a character from the base line of the string in pixels
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("BaseLine")
  private java.lang.Integer baseLine;

  /**
   * Height of small characters in pixels on the source image
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("CharacterHeight")
  private java.lang.Integer characterHeight;

  /**
   * The foreground color of the symbol; the default color is 0 (black)
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("Color")
  private java.lang.Integer color;

  /**
   * Symbol recognition confidence from OCR. Range depends upon OCR Engine.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("Confidence")
  private java.lang.Integer confidence;

  /**
   * The font ID refers to the fonts table in the document header
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("FontId")
  private java.lang.Integer fontId;

  /**
   * Size in points (JFYI: point is 1/72"). This is rounded to the nearest whole number.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("FontSize")
  private java.lang.Integer fontSize;

  /**
   * Size in points represented as float.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("FontSizeFloat")
  private java.lang.Float fontSizeFloat;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("FontType")
  private java.lang.Integer fontType;

  /**
   * If CharacterHeight is defined uncertainly
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("HasUncertainHeight")
  private java.lang.Boolean hasUncertainHeight;

  /**
   * The horizontal scaling for a character, in percents. The default value for this property is
   * 100, which corresponds to no scaling.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("HorizontalScale")
  private java.lang.Integer horizontalScale;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsBold")
  private java.lang.Boolean isBold;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsItalic")
  private java.lang.Boolean isItalic;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsSmallCaps")
  private java.lang.Boolean isSmallCaps;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsStrikeout")
  private java.lang.Boolean isStrikeout;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsSubscript")
  private java.lang.Boolean isSubscript;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsSuperscript")
  private java.lang.Boolean isSuperscript;

  /**
   * If OCR Engine marked the character as "suspicious" (this character is likely to be recognized
   * incorrectly).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsSuspicious")
  private java.lang.Boolean isSuspicious;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("IsUnderlined")
  private java.lang.Boolean isUnderlined;

  /**
   * True if a QA operator has marked this as not OCRable. This is used for complex equations,
   * scripts that the operator can't type, or handwriting.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("NotOcrablePerQA")
  private java.lang.Boolean notOcrablePerQA;

  /**
   * Symbol-level penalty from the garbage text detector. Lower is better; range = [0,100].
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("Penalty")
  private java.lang.Integer penalty;

  /**
   * The probability that a character is written with a Serif font
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("SerifProbability")
  private java.lang.Integer serifProbability;

  /**
   * The shift of a character from the base line of the string in pixels
   * @return value or {@code null} for none
   */
  public java.lang.Integer getBaseLine() {
    return baseLine;
  }

  /**
   * The shift of a character from the base line of the string in pixels
   * @param baseLine baseLine or {@code null} for none
   */
  public GoodocCharLabel setBaseLine(java.lang.Integer baseLine) {
    this.baseLine = baseLine;
    return this;
  }

  /**
   * Height of small characters in pixels on the source image
   * @return value or {@code null} for none
   */
  public java.lang.Integer getCharacterHeight() {
    return characterHeight;
  }

  /**
   * Height of small characters in pixels on the source image
   * @param characterHeight characterHeight or {@code null} for none
   */
  public GoodocCharLabel setCharacterHeight(java.lang.Integer characterHeight) {
    this.characterHeight = characterHeight;
    return this;
  }

  /**
   * The foreground color of the symbol; the default color is 0 (black)
   * @return value or {@code null} for none
   */
  public java.lang.Integer getColor() {
    return color;
  }

  /**
   * The foreground color of the symbol; the default color is 0 (black)
   * @param color color or {@code null} for none
   */
  public GoodocCharLabel setColor(java.lang.Integer color) {
    this.color = color;
    return this;
  }

  /**
   * Symbol recognition confidence from OCR. Range depends upon OCR Engine.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getConfidence() {
    return confidence;
  }

  /**
   * Symbol recognition confidence from OCR. Range depends upon OCR Engine.
   * @param confidence confidence or {@code null} for none
   */
  public GoodocCharLabel setConfidence(java.lang.Integer confidence) {
    this.confidence = confidence;
    return this;
  }

  /**
   * The font ID refers to the fonts table in the document header
   * @return value or {@code null} for none
   */
  public java.lang.Integer getFontId() {
    return fontId;
  }

  /**
   * The font ID refers to the fonts table in the document header
   * @param fontId fontId or {@code null} for none
   */
  public GoodocCharLabel setFontId(java.lang.Integer fontId) {
    this.fontId = fontId;
    return this;
  }

  /**
   * Size in points (JFYI: point is 1/72"). This is rounded to the nearest whole number.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getFontSize() {
    return fontSize;
  }

  /**
   * Size in points (JFYI: point is 1/72"). This is rounded to the nearest whole number.
   * @param fontSize fontSize or {@code null} for none
   */
  public GoodocCharLabel setFontSize(java.lang.Integer fontSize) {
    this.fontSize = fontSize;
    return this;
  }

  /**
   * Size in points represented as float.
   * @return value or {@code null} for none
   */
  public java.lang.Float getFontSizeFloat() {
    return fontSizeFloat;
  }

  /**
   * Size in points represented as float.
   * @param fontSizeFloat fontSizeFloat or {@code null} for none
   */
  public GoodocCharLabel setFontSizeFloat(java.lang.Float fontSizeFloat) {
    this.fontSizeFloat = fontSizeFloat;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Integer getFontType() {
    return fontType;
  }

  /**
   * @param fontType fontType or {@code null} for none
   */
  public GoodocCharLabel setFontType(java.lang.Integer fontType) {
    this.fontType = fontType;
    return this;
  }

  /**
   * If CharacterHeight is defined uncertainly
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getHasUncertainHeight() {
    return hasUncertainHeight;
  }

  /**
   * If CharacterHeight is defined uncertainly
   * @param hasUncertainHeight hasUncertainHeight or {@code null} for none
   */
  public GoodocCharLabel setHasUncertainHeight(java.lang.Boolean hasUncertainHeight) {
    this.hasUncertainHeight = hasUncertainHeight;
    return this;
  }

  /**
   * The horizontal scaling for a character, in percents. The default value for this property is
   * 100, which corresponds to no scaling.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getHorizontalScale() {
    return horizontalScale;
  }

  /**
   * The horizontal scaling for a character, in percents. The default value for this property is
   * 100, which corresponds to no scaling.
   * @param horizontalScale horizontalScale or {@code null} for none
   */
  public GoodocCharLabel setHorizontalScale(java.lang.Integer horizontalScale) {
    this.horizontalScale = horizontalScale;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsBold() {
    return isBold;
  }

  /**
   * @param isBold isBold or {@code null} for none
   */
  public GoodocCharLabel setIsBold(java.lang.Boolean isBold) {
    this.isBold = isBold;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsItalic() {
    return isItalic;
  }

  /**
   * @param isItalic isItalic or {@code null} for none
   */
  public GoodocCharLabel setIsItalic(java.lang.Boolean isItalic) {
    this.isItalic = isItalic;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsSmallCaps() {
    return isSmallCaps;
  }

  /**
   * @param isSmallCaps isSmallCaps or {@code null} for none
   */
  public GoodocCharLabel setIsSmallCaps(java.lang.Boolean isSmallCaps) {
    this.isSmallCaps = isSmallCaps;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsStrikeout() {
    return isStrikeout;
  }

  /**
   * @param isStrikeout isStrikeout or {@code null} for none
   */
  public GoodocCharLabel setIsStrikeout(java.lang.Boolean isStrikeout) {
    this.isStrikeout = isStrikeout;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsSubscript() {
    return isSubscript;
  }

  /**
   * @param isSubscript isSubscript or {@code null} for none
   */
  public GoodocCharLabel setIsSubscript(java.lang.Boolean isSubscript) {
    this.isSubscript = isSubscript;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsSuperscript() {
    return isSuperscript;
  }

  /**
   * @param isSuperscript isSuperscript or {@code null} for none
   */
  public GoodocCharLabel setIsSuperscript(java.lang.Boolean isSuperscript) {
    this.isSuperscript = isSuperscript;
    return this;
  }

  /**
   * If OCR Engine marked the character as "suspicious" (this character is likely to be recognized
   * incorrectly).
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsSuspicious() {
    return isSuspicious;
  }

  /**
   * If OCR Engine marked the character as "suspicious" (this character is likely to be recognized
   * incorrectly).
   * @param isSuspicious isSuspicious or {@code null} for none
   */
  public GoodocCharLabel setIsSuspicious(java.lang.Boolean isSuspicious) {
    this.isSuspicious = isSuspicious;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsUnderlined() {
    return isUnderlined;
  }

  /**
   * @param isUnderlined isUnderlined or {@code null} for none
   */
  public GoodocCharLabel setIsUnderlined(java.lang.Boolean isUnderlined) {
    this.isUnderlined = isUnderlined;
    return this;
  }

  /**
   * True if a QA operator has marked this as not OCRable. This is used for complex equations,
   * scripts that the operator can't type, or handwriting.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getNotOcrablePerQA() {
    return notOcrablePerQA;
  }

  /**
   * True if a QA operator has marked this as not OCRable. This is used for complex equations,
   * scripts that the operator can't type, or handwriting.
   * @param notOcrablePerQA notOcrablePerQA or {@code null} for none
   */
  public GoodocCharLabel setNotOcrablePerQA(java.lang.Boolean notOcrablePerQA) {
    this.notOcrablePerQA = notOcrablePerQA;
    return this;
  }

  /**
   * Symbol-level penalty from the garbage text detector. Lower is better; range = [0,100].
   * @return value or {@code null} for none
   */
  public java.lang.Integer getPenalty() {
    return penalty;
  }

  /**
   * Symbol-level penalty from the garbage text detector. Lower is better; range = [0,100].
   * @param penalty penalty or {@code null} for none
   */
  public GoodocCharLabel setPenalty(java.lang.Integer penalty) {
    this.penalty = penalty;
    return this;
  }

  /**
   * The probability that a character is written with a Serif font
   * @return value or {@code null} for none
   */
  public java.lang.Integer getSerifProbability() {
    return serifProbability;
  }

  /**
   * The probability that a character is written with a Serif font
   * @param serifProbability serifProbability or {@code null} for none
   */
  public GoodocCharLabel setSerifProbability(java.lang.Integer serifProbability) {
    this.serifProbability = serifProbability;
    return this;
  }

  @Override
  public GoodocCharLabel set(String fieldName, Object value) {
    return (GoodocCharLabel) super.set(fieldName, value);
  }

  @Override
  public GoodocCharLabel clone() {
    return (GoodocCharLabel) super.clone();
  }

}


text:
var DataParentNTD = function() {
  this.Extends = ParentNTD;

	this.initialize = function() {
	  this.parent(DataParentNTD.ID);
	};
};
DataParentNTD = new Class(new DataParentNTD());
DataParentNTD.ID = "dataParentNTD";
//DataParentNTD.HEADER_ID = DataParentNTD.ID+ParentNTD.HEADER_ID;


text:
namespace blink {

// The origin and importance criteria are evaluated together [1], hence we
// encode both into a single integer which will do the right thing when compared
// to another such encoded integer. See CascadeOrigin for more information on
// how that works.
//
// [1] https://www.w3.org/TR/css-cascade-3/#cascade-origin
inline uint32_t EncodeOriginImportance(CascadeOrigin origin, bool important) {
  uint8_t important_xor = (static_cast<uint8_t>(!important) - 1) & 0xF;
  return static_cast<uint32_t>(origin) ^ important_xor;
}

// Tree order bits are flipped for important declarations to reverse the
// priority [1].
//
// [1] https://drafts.csswg.org/css-scoping/#shadow-cascading
inline uint32_t EncodeTreeOrder(uint16_t tree_order, bool important) {
  uint16_t important_xor = static_cast<uint16_t>(!important) - 1;
  return static_cast<uint32_t>(tree_order) ^ important_xor;
}

// Layer order bits are flipped for important declarations to reverse the
// priority [1].
//
// [1] https://drafts.csswg.org/css-cascade-5/#cascade-layering
inline uint64_t EncodeLayerOrder(uint16_t layer_order, bool important) {
  uint16_t important_xor = static_cast<uint16_t>(!important) - 1;
  return static_cast<uint64_t>(layer_order) ^ important_xor;
}

// The CascadePriority class encapsulates a subset of the cascading criteria
// described by css-cascade [1], and provides a way to compare priorities
// quickly by encoding all the information in a single integer.
//
// It encompasses, from most significant to least significant:
// Origin/importance; tree order, which is a number representing the
// shadow-including tree order [2]; inline style, which is a boolean incidating
// whether the declaration is in the style attribute [3]; layer order, which is
// a number representing the cascade layer order in the origin and tree scope
// [4]; position, which contains the index (or indices) required to lookup a
// declaration in the underlying structure (e.g. a MatchResult); and finally
// generation, which is a monotonically increasing number generated by
// StyleCascade for each call to StyleCascade::Apply.
//
// [1] https://drafts.csswg.org/css-cascade/#cascading
// [2] https://drafts.csswg.org/css-scoping/#shadow-cascading
// [3] https://drafts.csswg.org/css-cascade/#style-attr
// [4] https://drafts.csswg.org/css-cascade-5/#layer-ordering
class CORE_EXPORT CascadePriority {
 public:
  // The declaration is important if this bit is set on the encoded priority.
  static constexpr uint64_t kImportantBit = 19;            // of high_bits_
  static constexpr uint64_t kOriginImportanceOffset = 16;  // of high_bits_
  static constexpr uint64_t kIsInlineStyleOffset = 52;     // of low_bits
  static constexpr uint64_t kLayerOrderOffset = 36;        // of low_bits_
  static constexpr uint64_t kPositionOffset = 4;           // of low_bits_

  static constexpr uint32_t kOriginImportanceMask =
      0xF << kOriginImportanceOffset;                 // of high_bits_
  static constexpr uint32_t kTreeOrderMask = 0xFFFF;  // of high_bits_
  static constexpr uint64_t kLayerOrderMask =
      static_cast<uint64_t>(0xFFFF) << kLayerOrderOffset;  // of low_bits_
  static constexpr uint64_t kPositionMask = static_cast<uint64_t>(0xFFFFFFFF)
                                            << kPositionOffset;  // of low_bits_
  static constexpr uint64_t kGenerationMask = 0xF;               // of low_bits_

  CascadePriority() : low_bits_(0), high_bits_(0) {}
  CascadePriority(CascadeOrigin origin)
      : CascadePriority(origin, false, 0, false, 0, 0) {}
  CascadePriority(CascadeOrigin origin, bool important)
      : CascadePriority(origin, important, 0, false, 0, 0) {}
  CascadePriority(CascadeOrigin origin, bool important, uint16_t tree_order)
      : CascadePriority(origin, important, tree_order, false, 0, 0) {}

  // For an explanation of 'tree_order', see css-scoping:
  // https://drafts.csswg.org/css-scoping/#shadow-cascading
  CascadePriority(CascadeOrigin origin,
                  bool important,
                  uint16_t tree_order,
                  bool is_inline_style,
                  uint16_t layer_order,
                  uint32_t position)
      : CascadePriority(
            static_cast<uint64_t>(position) << kPositionOffset |
                EncodeLayerOrder(layer_order, important) << kLayerOrderOffset |
                static_cast<uint64_t>(is_inline_style) << kIsInlineStyleOffset,
            EncodeTreeOrder(tree_order, important) |
                EncodeOriginImportance(origin, important)
                    << kOriginImportanceOffset) {}
  // See StyleCascade.generation_.
  CascadePriority(CascadePriority o, uint8_t generation)
      : CascadePriority((o.low_bits_ & ~kGenerationMask) | generation,
                        o.high_bits_) {
    DCHECK_LE(generation, kGenerationMask);
  }

  bool IsImportant() const { return (high_bits_ >> kImportantBit) & 1; }
  CascadeOrigin GetOrigin() const {
    uint64_t important_xor =
        (((~high_bits_ >> kImportantBit) & 1) - 1) & kOriginImportanceMask;
    return static_cast<CascadeOrigin>((high_bits_ ^ important_xor) >>
                                      kOriginImportanceOffset);
  }
  bool HasOrigin() const { return GetOrigin() != CascadeOrigin::kNone; }
  uint32_t GetPosition() const {
    return (low_bits_ & kPositionMask) >> kPositionOffset;
  }
  uint8_t GetGeneration() const { return low_bits_ & kGenerationMask; }
  bool IsInlineStyle() const { return (low_bits_ >> kIsInlineStyleOffset) & 1; }

  // Returns a CascadePriority that ignores the importance and all sorting
  // criteria below layer order, which allows us to compare if two
  // CascadePriorities belong to the same cascade layer.
  CascadePriority ForLayerComparison() const {
    uint64_t important_xor =
        (((~static_cast<uint64_t>(high_bits_) >> kImportantBit) & 1) - 1);
    uint32_t high_important_xor =
        important_xor & (kOriginImportanceMask | kTreeOrderMask);
    uint32_t high_bits_without_importance = high_bits_ ^ high_important_xor;
    uint64_t low_important_xor = important_xor & kLayerOrderMask;
    uint64_t low_bits_without_importance_position_and_generation =
        (low_bits_ ^ low_important_xor) & ~(kGenerationMask | kPositionMask);
    return CascadePriority(low_bits_without_importance_position_and_generation,
                           high_bits_without_importance);
  }

  bool operator>=(const CascadePriority& o) const {
    return high_bits_ > o.high_bits_ ||
           (high_bits_ == o.high_bits_ && low_bits_ >= o.low_bits_);
  }
  bool operator<(const CascadePriority& o) const {
    return high_bits_ < o.high_bits_ ||
           (high_bits_ == o.high_bits_ && low_bits_ < o.low_bits_);
  }
  bool operator==(const CascadePriority& o) const {
    return high_bits_ == o.high_bits_ && low_bits_ == o.low_bits_;
  }
  bool operator!=(const CascadePriority& o) const {
    return high_bits_ != o.high_bits_ || low_bits_ != o.low_bits_;
  }

 private:
  friend class StyleCascade;
  friend class StyleCascadeTest;

  CascadePriority(uint64_t low_bits, uint32_t high_bits)
      : low_bits_(low_bits), high_bits_(high_bits) {}

  //  Bit  0-3 : generation
  //  Bit  4-35: position
  //  Bit 36-51: layer_order (encoded)
  //  Bit    52: is_inline_style
  uint64_t low_bits_;

  //  Bit  0-15: tree_order (encoded)
  //  Bit 16-23: origin/importance (encoded)
  uint32_t high_bits_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CASCADE_PRIORITY_H_


text:
package java.rmi;

/**
 * @ar.org.fitc.spec_ref
 *
 */
@Deprecated
public class RMISecurityException extends SecurityException {

    /**
     *
     */
    private static final long serialVersionUID = -8433406075740433514L;

    /**
     * @ar.org.fitc.spec_ref
     *
     */
    @Deprecated
    public RMISecurityException(String name) {
        super(name);
    }

    /**
     * @ar.org.fitc.spec_ref
     *
     */
    @Deprecated
    public RMISecurityException(String name, String arg1) {
        // Constructor
        super(name);
        // arg1 ignored
    }
}


text:
React components for [Async Google Maps](https://github.com/zpratt/async-google-maps)

[![Build Status](https://travis-ci.org/zpratt/idle-maps.svg)](https://travis-ci.org/zpratt/idle-maps)
[![npm](https://img.shields.io/npm/v/idle-maps.svg)](https://www.npmjs.com/package/idle-maps)

### Not fully baked yet

I am still working out some things with the overlay mixin.

## Running tests

This module is 100% test-driven. Please feel free to run the tests and critique them.

1. `git clone` ...
2. Install io.js (needed for jsdom)
3. `npm i`
4. `npm test`

## Usage

Take a look at the examples directory for a few samples of how to use the mixins.

### Running examples locally

1. `npm i`
2. `npm start`
3. Navigate to [http://localhost:8080/](http://localhost:8080/)

## Documentation

Coming soon.


text:
<?php
/**
 * Created by PhpStorm.
 * User: martijn
 * Date: 27-6-14
 * Time: 14:27
 */

namespace PhpGrade\Formatters;

use PhpGrade\Message;
use Symfony\Component\Yaml\Yaml;

class YamlFormatter extends BaseFormatter
{
    public function format($messages)
    {
        foreach ($messages as &$file) {
            foreach ($file as &$line) {
                foreach ($line as &$message) {
                    $message = $this->messageToArray($message);
                }
            }
        }
        echo Yaml::dump($messages, 10, 4, false, true);
    }

    private function messageToArray(Message $message)
    {
        return array(
            'tool' => $message->getTool(),
            'level' => $message->getErrorLevel(),
            'message' => $message->getMessage()
        );
    }
}


text:
import {JWT} from "./sessions/jwt"
import {Cookie} from "./sessions/cookies"

export default {
    JWT,
    Cookie
};


text:
namespace Go2.Architecture.Specifications.NHibernate.Mappings.Conventions
{
    using FluentNHibernate.Conventions;

    public class HasManyConvention : IHasManyConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IOneToManyCollectionInstance instance)
        {
            instance.Key.Column(instance.EntityType.Name + "Id");
            instance.Cascade.AllDeleteOrphan();
            instance.Inverse();
        }
    }
}


text:
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
  echo -e "Build Pull Request #$TRAVIS_PULL_REQUEST => Branch ['$TRAVIS_BRANCH']"
  ./gradlew build --scan
else
  # Only publish when using JDK8
  if [[ "$TRAVIS_JDK_VERSION" == *"jdk8" ]]; then
    if [ "$TRAVIS_TAG" == "" ]; then
      echo -e 'Build Branch with Snapshot => Branch ['$TRAVIS_BRANCH']'
      # snapshot
      ./gradlew -Prelease.travisci=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build snapshot --info --scan
    else
      echo -e 'Build Branch for Release => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG']'
      if [[ "$TRAVIS_TAG" == *"rc."* ]]; then
        # candidate
        ./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" candidate
      else
        # final
        ./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" final
      fi
    fi
  else
    echo -e "Build Branch without publishing => Branch ['$TRAVIS_BRANCH'] JDK ['$TRAVIS_JDK_VERSION']"
    ./gradlew build --scan
  fi
fi


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>Resource (Apache Log4j 1.2.17 API)</title>
<meta name="date" content="2015-08-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.apache.log4j.lf5.util

类 Resource

java.lang.Object

org.apache.log4j.lf5.util.Resource

public class Resource
extends java.lang.Object

Resource encapsulates access to Resources via the Classloader.

作者:

Michael J. Sikorsky, Robert Shaw

字段概要

字段

限定符和类型
字段和说明

protected java.lang.String
_name

构造器概要

构造器

构造器和说明

Resource()

Default, no argument constructor.

Resource(java.lang.String name)

Construct a Resource given a name.

方法概要

方法

限定符和类型
方法和说明

java.io.InputStream
getInputStream()

Get the InputStream for this Resource.

java.io.InputStreamReader
getInputStreamReader()

Get the InputStreamReader for this Resource.

java.lang.String
getName()

Get the name of the resource.

java.net.URL
getURL()

Get the URL of the Resource.

void
setName(java.lang.String name)

Set the name of the resource.

从类继承的方法 java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细资料

_name

protected java.lang.String _name

构造器详细资料

Resource

public Resource()

Default, no argument constructor.

Resource

public Resource(java.lang.String name)

Construct a Resource given a name.

另请参阅:

setName(String)

方法详细资料

setName

public void setName(java.lang.String name)

Set the name of the resource.

 A resource is some data (images, audio, text, etc) that can be accessed
 by class code in a way that is independent of the location of the code.

 The name of a resource is a "/"-separated path name that identifies
 the resource.

另请参阅:

getName()

getName

public java.lang.String getName()

Get the name of the resource.  Set setName() for a description of
 a resource.

另请参阅:

setName(java.lang.String)

getInputStream

public java.io.InputStream getInputStream()

Get the InputStream for this Resource.  Uses the classloader
 from this Resource.

另请参阅:

getInputStreamReader(),
ResourceUtils

getInputStreamReader

public java.io.InputStreamReader getInputStreamReader()

Get the InputStreamReader for this Resource. Uses the classloader from
 this Resource.

另请参阅:

getInputStream(),
ResourceUtils

getURL

public java.net.URL getURL()

Get the URL of the Resource.  Uses the classloader from this Resource.

另请参阅:

ResourceUtils

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

Copyright © 1999-2015 Apache Software Foundation. All Rights Reserved.


text:
require 'spec_helper'
require 'flapjack/gateways/email'

describe Flapjack::Gateways::Email, :logger => true do

  let(:client) { double('client') }
  let(:redis) { double('redis') }

  it "can have a custom from email address" do
    expect(EM::P::SmtpClient).to receive(:send).with(
      hash_including(host: 'localhost',
                     port: 25,
                     from: "from@example.org")
    ).and_return(client)

    response = double(response)
    expect(response).to receive(:"respond_to?").with(:code).and_return(true)
    expect(response).to receive(:code).and_return(250)

    expect(EM::Synchrony).to receive(:sync).with(client).and_return(response)

    notification = {'notification_type'   => 'recovery',
                    'contact_first_name'  => 'John',
                    'contact_last_name'   => 'Smith',
                    'state'               => 'ok',
                    'state_duration'      => 2,
                    'summary'             => 'smile',
                    'last_state'          => 'problem',
                    'last_summary'        => 'frown',
                    'time'                => Time.now.to_i,
                    'event_id'            => 'example.com:ping'}

    config = {"smtp_config" => {'from' => 'from@example.org'}}

    EM.synchrony do
      expect(Flapjack::RedisPool).to receive(:new).and_return(redis)

      alert = Flapjack::Data::Alert.new(notification, :logger => @logger)
      email = Flapjack::Gateways::Email.new(:config => config, :logger => @logger)
      email.deliver(alert)
      EM.stop
    end
  end

  it "can have a full name in custom from email address" do
    expect(EM::P::SmtpClient).to receive(:send).with(
      hash_including(host: 'localhost',
                     port: 25,
                     from: "from@example.org")
    ).and_return(client)

    response = double(response)
    expect(response).to receive(:"respond_to?").with(:code).and_return(true)
    expect(response).to receive(:code).and_return(250)

    expect(EM::Synchrony).to receive(:sync).with(client).and_return(response)

    notification = {'notification_type'   => 'recovery',
                    'contact_first_name'  => 'John',
                    'contact_last_name'   => 'Smith',
                    'state'               => 'ok',
                    'state_duration'      => 2,
                    'summary'             => 'smile',
                    'last_state'          => 'problem',
                    'last_summary'        => 'frown',
                    'time'                => Time.now.to_i,
                    'event_id'            => 'example.com:ping'}

    config = {"smtp_config" => {'from' => 'Full Name <from@example.org>'}}

    EM.synchrony do
      expect(Flapjack::RedisPool).to receive(:new).and_return(redis)

      alert = Flapjack::Data::Alert.new(notification, :logger => @logger)
      email = Flapjack::Gateways::Email.new(:config => config, :logger => @logger)
      email.deliver(alert)
      EM.stop
    end
  end

  it "can have a custom reply-to address" do
    expect(EM::P::SmtpClient).to receive(:send) { |message|
      # NOTE No access to headers directly. Must be determined from message content
      expect( message[:content] ).to include("Reply-To: reply-to@example.com")
      # NOTE Ensure we haven't trashed any other arguments
      expect( message[:host] ).to eql('localhost')
      expect( message[:port] ).to eql(25)
      expect( message[:from] ).to eql('from@example.org')
    }.and_return(client)

    response = double(response)
    expect(response).to receive(:"respond_to?").with(:code).and_return(true)
    expect(response).to receive(:code).and_return(250)

    expect(EM::Synchrony).to receive(:sync).with(client).and_return(response)

    notification = {'notification_type'   => 'recovery',
                    'contact_first_name'  => 'John',
                    'contact_last_name'   => 'Smith',
                    'state'               => 'ok',
                    'state_duration'      => 2,
                    'summary'             => 'smile',
                    'last_state'          => 'problem',
                    'last_summary'        => 'frown',
                    'time'                => Time.now.to_i,
                    'event_id'            => 'example.com:ping'}

    config = {"smtp_config" => {'from' => 'from@example.org', 'reply_to' => 'reply-to@example.com'}}

    EM.synchrony do
      expect(Flapjack::RedisPool).to receive(:new).and_return(redis)

      alert = Flapjack::Data::Alert.new(notification, :logger => @logger)
      email = Flapjack::Gateways::Email.new(:config => config, :logger => @logger)
      email.deliver(alert)
      EM.stop
    end
  end

  it "must default to from address if no reply-to given" do
    expect(EM::P::SmtpClient).to receive(:send) { |message|
      # NOTE No access to headers directly. Must be determined from message content
      expect( message[:content] ).to include("Reply-To: from@example.org")
    }.and_return(client)

    response = double(response)
    expect(response).to receive(:"respond_to?").with(:code).and_return(true)
    expect(response).to receive(:code).and_return(250)

    expect(EM::Synchrony).to receive(:sync).with(client).and_return(response)

    notification = {'notification_type'   => 'recovery',
                    'contact_first_name'  => 'John',
                    'contact_last_name'   => 'Smith',
                    'state'               => 'ok',
                    'state_duration'      => 2,
                    'summary'             => 'smile',
                    'last_state'          => 'problem',
                    'last_summary'        => 'frown',
                    'time'                => Time.now.to_i,
                    'event_id'            => 'example.com:ping'}

    config = {"smtp_config" => {'from' => 'from@example.org'}}

    EM.synchrony do
      expect(Flapjack::RedisPool).to receive(:new).and_return(redis)

      alert = Flapjack::Data::Alert.new(notification, :logger => @logger)
      email = Flapjack::Gateways::Email.new(:config => config, :logger => @logger)
      email.deliver(alert)
      EM.stop
    end
  end

  it "sends a mail with text, html parts and default from address" do
    entity_check = double(Flapjack::Data::EntityCheck)

    # TODO better checking of what gets passed here
    expect(EM::P::SmtpClient).to receive(:send).with(
      hash_including(:host    => 'localhost',
                     :port    => 25,
                     :from    => "flapjack@example.com"
                    )).and_return(client)

    response = double(response)
    expect(response).to receive(:"respond_to?").with(:code).and_return(true)
    expect(response).to receive(:code).and_return(250)

    expect(EM::Synchrony).to receive(:sync).with(client).and_return(response)

    notification = {'notification_type'   => 'recovery',
                    'contact_first_name'  => 'John',
                    'contact_last_name'   => 'Smith',
                    'state'               => 'ok',
                    'state_duration'      => 2,
                    'summary'             => 'smile',
                    'last_state'          => 'problem',
                    'last_summary'        => 'frown',
                    'time'                => Time.now.to_i,
                    'event_id'            => 'example.com:ping'}

    EM.synchrony do
      expect(Flapjack::RedisPool).to receive(:new).and_return(redis)

      alert = Flapjack::Data::Alert.new(notification, :logger => @logger)
      email = Flapjack::Gateways::Email.new(:config => {}, :logger => @logger)
      email.instance_variable_set('@fqdn', "example.com")
      email.deliver(alert)
      EM.stop
    end
  end

end


text:
package com.example.android.sunshine.app;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.sunshine.app.R;
import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.data.WeatherContract;

public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String LOG_TAG = DetailFragment.class.getSimpleName();
    private static final int DETAIL_LOADER = 0;
    static final String DETAIL_URI = "URI";
    private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
    private String mForecastStr;
    private ShareActionProvider mShareActionProvider;
    private Uri mUri;

    private static final String[] DETAIL_COLUMNS = {
            WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
            WeatherContract.WeatherEntry.COLUMN_DATE,
            WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
            WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
            WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.WeatherEntry.COLUMN_HUMIDITY,
            WeatherContract.WeatherEntry.COLUMN_PRESSURE,
            WeatherContract.WeatherEntry.COLUMN_WIND_SPEED,
            WeatherContract.WeatherEntry.COLUMN_DEGREES,
            WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
    };

    static final int COL_WEATHER_ID = 0;
    static final int COL_WEATHER_DATE = 1;
    static final int COL_WEATHER_DESC = 2;
    static final int COL_WEATHER_MAX_TEMP = 3;
    static final int COL_WEATHER_MIN_TEMP = 4;
    static final int COL_WEATHER_HUMIDITY = 5;
    static final int COL_WEATHER_PRESSURE = 6;
    static final int COL_WEATHER_WIND_SPEED = 7;
    static final int COL_WEATHER_DEGREES = 8;
    static final int COL_WEATHER_CONDITION_ID = 9;

    private ImageView mIconView;
    private TextView mFriendlyDateView;
    private TextView mDateView;
    private TextView mDescView;
    private TextView mHighView;
    private TextView mLowView;
    private TextView mHumidityView;
    private TextView mWindView;
    private TextView mPressureView;

    public DetailFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle args = getArguments();
        if (args != null) {
            mUri = args.getParcelable(DETAIL_URI);
        }

        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

        mDateView = (TextView)rootView.findViewById(R.id.detail_date_textview);
        mFriendlyDateView = (TextView)rootView.findViewById(R.id.detail_day_textview);
        mHighView = (TextView)rootView.findViewById(R.id.detail_high_textview);
        mLowView = (TextView)rootView.findViewById(R.id.detail_low_textview);
        mHumidityView = (TextView)rootView.findViewById(R.id.detail_humidity_textview);
        mWindView = (TextView)rootView.findViewById(R.id.detail_wind_textview);
        mPressureView = (TextView)rootView.findViewById(R.id.detail_pressure_textview);
        mDescView = (TextView)rootView.findViewById(R.id.detail_forecast_textview);
        mIconView = (ImageView)rootView.findViewById(R.id.detail_icon);

        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.detailfragment, menu);

        // Retrieve the share menu item
        MenuItem menuItem = menu.findItem(R.id.action_share);

        // Get the provider and hold onto it to set/change the share intent.
        mShareActionProvider =
                (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        // Attach an intent to this ShareActionProvider.  You can update this at any time,
        // like when the user selects a new piece of data they might like to share.
        if (mForecastStr != null ) {
            mShareActionProvider.setShareIntent(createShareForecastIntent());
        } else {
            Log.d(LOG_TAG, "Share Action Provider is null?");
        }
    }

    private Intent createShareForecastIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        // placeholder string for now
        shareIntent.putExtra(Intent.EXTRA_TEXT,
                "Forecast" + FORECAST_SHARE_HASHTAG);
        return shareIntent;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        if (null != mUri) {
            return new CursorLoader(
                    getActivity(),
                    mUri,
                    DETAIL_COLUMNS,
                    null,
                    null,
                    null
            );
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null && data.moveToFirst()) {

            int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
            // set placeholder image
            int weatherIcon = Utility.getArtResourceForWeatherCondition(data.getInt(COL_WEATHER_CONDITION_ID));
            mIconView.setImageResource(weatherIcon);
            // set dates
            long date = data.getLong(COL_WEATHER_DATE);
            String dayString = Utility.getDayName(getActivity(), date);
            String dateString = Utility.getFormattedMonthDay(getActivity(), date);
            mFriendlyDateView.setText(dayString);
            mDateView.setText(dateString);

            String weatherDesc = data.getString(COL_WEATHER_DESC);
            mDescView.setText(weatherDesc);

            boolean isMetric = Utility.isMetric(getActivity());

            double high = data.getDouble(COL_WEATHER_MAX_TEMP);
            String highString = Utility.formatTemperature(getActivity(), high, isMetric);
            mHighView.setText(highString);

            double low = data.getDouble(COL_WEATHER_MIN_TEMP);
            String lowString = Utility.formatTemperature(getActivity(), low, isMetric);
            mLowView.setText(lowString);

            float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
            mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));

            float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
            float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
            mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));

            float pressure = data.getFloat(COL_WEATHER_PRESSURE);
            mPressureView.setText(getActivity().getString(R.string.format_pressure, pressure));

            mForecastStr = String.format("%s - %s - %s/%s", dateString, weatherDesc, high, low);
        }
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(createShareForecastIntent());
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    public void onLocationChanged(String location) {
        Uri uri = mUri;
        if (null != uri) {
            long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
            Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(location, date);
            mUri = updatedUri;
            getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
        }
    }
}


text:
package com.google.gwt.sample.dynatablemvp.shared;

public class TimeTools {

	private static final transient String[] DAYS = new String[] { "Sun", "Mon",
			"Tues", "Wed", "Thurs", "Fri", "Sat" };

	private int endMinutes;

	private int startMinutes;

	public TimeTools(int zeroBasedDayOfWeek, int startMinutes,int endMinutes ) {
		super();
		this.endMinutes = endMinutes;
		this.startMinutes = startMinutes;
		this.zeroBasedDayOfWeek = zeroBasedDayOfWeek;
	}

	private int zeroBasedDayOfWeek;

	public String getDescription() {
		return DAYS[zeroBasedDayOfWeek] + " " + getHrsMins(startMinutes) + "-"
				+ getHrsMins(endMinutes);
	}
/*
	public void setDescription(String description) {
		Pattern pattern = Pattern.compile("(\\w+) (\\w+)-(\\w+)",
				Pattern.CASE_INSENSITIVE);
		Matcher m = pattern.matcher(description);
		if (m.matches()) {
			for (int d = 0; d < DAYS.length; d++)
				if (DAYS[d].equalsIgnoreCase(m.group(1))) {
					zeroBasedDayOfWeek = d;
					break;
				}
			for (int m1 = 0; m1 < 60; m1++)
				if (getHrsMins(m1).equalsIgnoreCase(m.group(2))) {
					startMinutes = m1;
					break;
				}
			for (int e = 0; e < 24; e++)
				if (getHrsMins(e).equalsIgnoreCase(m.group(3))) {
					endMinutes = e;
					break;
				}
		}
	}
*/

	private String getHrsMins(int mins) {
		int hrs = mins / 60;
		if (hrs > 12) {
			hrs -= 12;
		}

		int remainder = mins % 60;

		return hrs
				+ ":"
				+ (remainder < 10 ? "0" + remainder : String.valueOf(remainder));
	}

	@Override
	public int hashCode() {
		return endMinutes + 7 * startMinutes + 31 * zeroBasedDayOfWeek;
	}

	public int getEndMinutes() {
		return endMinutes;
	}

	public void setEndMinutes(int endMinutes) {
		this.endMinutes = endMinutes;
	}

	public int getStartMinutes() {
		return startMinutes;
	}

	public void setStartMinutes(int startMinutes) {
		this.startMinutes = startMinutes;
	}

	public int getZeroBasedDayOfWeek() {
		return zeroBasedDayOfWeek;
	}

	public void setZeroBasedDayOfWeek(int zeroBasedDayOfWeek) {
		this.zeroBasedDayOfWeek = zeroBasedDayOfWeek;
	}

}


text:
<?php

namespace Warp\Helper;

/**
 * Template helper class, render layouts.
 */
class TemplateHelper extends AbstractHelper
{
    /**
     * @var array
     */
    protected $slots = array();

    /**
     * Render a layout file.
     *
     * @param string $resource
     * @param array  $args
     *
     * @return string
     */
    public function render($resource, $args = array())
    {
        // default namespace
        if (strpos($resource, ':') === false) {
            $resource = 'layouts:'.$resource;
        }

        // trigger event
        $this['event']->trigger('render.'.$resource, array(&$resource, &$args));

        // set resource and layout file
        $__resource = $resource;
        $__layout   = $this['path']->path($__resource.'.php');

        // render layout
        if ($__layout != false) {

            // import vars and get content
            extract($args);
            ob_start();
            include($__layout);
            return ob_get_clean();
        }

        trigger_error('<b>'.$__resource.'</b> not found in paths: ['.implode(', ', $this['path']->_paths['layouts']).']');

        return null;
    }

    /**
     * Slot exists ?
     *
     * @param string $name
     *
     * @return boolean
     */
    public function has($name)
    {
        return isset($this->slots[$name]);
    }

    /**
     * Retrieve a slot.
     *
     * @param string $name
     * @param mixed  $default
     *
     * @return mixed
     */
    public function get($name, $default = false)
    {
        return isset($this->slots[$name]) ? $this->slots[$name] : $default;
    }

    /**
     * Set a slot.
     *
     * @param string $name
     * @param string $content
     */
    public function set($name, $content)
    {
        $this->slots[$name] = $content;
    }

    /**
     * Outputs slot content.
     *
     * @param string $name
     * @param mixed  $default
     *
     * @return boolean
     */
    public function output($name, $default = false)
    {
        if (!isset($this->slots[$name])) {

            if (false !== $default) {
                echo $default;
                return true;
            }

            return false;
        }

        echo $this->slots[$name];
        return true;
    }
}