text:
package hu.petabyte.redflags.engine.gear.parser.hu;

import hu.petabyte.redflags.engine.gear.AbstractGear;
import hu.petabyte.redflags.engine.gear.parser.RawValueParser;
import hu.petabyte.redflags.engine.model.Notice;
import hu.petabyte.redflags.engine.model.noticeparts.Lot;
import hu.petabyte.redflags.engine.model.noticeparts.ObjOfTheContract;
import hu.petabyte.redflags.engine.util.StrUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Zsolt Jurányi
 */
@Component
public class EstimatedValueParser extends AbstractGear {

	protected static final Pattern ESTIM_VAL_PATTERN = Pattern
			.compile("^((Becsült( nettó)? érték( áfa nélkül)?|Áfa nélkül):?( nettó)?|.*?becsült.*? (összérték|nettó).*?) (?<v>[0-9 ,]+ )(?<c>[A-Z]{2,})[^\\/]*$|^(?<min>[0-9 ,]+ )és (?<max>[0-9 ,]+ )között (?<c2>[A-Z]+)$");
	protected static final Pattern EXCL_PATTERN = Pattern
			.compile("beruházás|építés|kivitelezés|projekt|tartalékkeretet tartalmaz|tartalék(kal|kerettel) együtt|[Ee]lszámolható|tartalékkeret|támogatott feladat|szolgáltatás|rekonstrukció|feladat|eszköz");
	private static final Logger LOG = LoggerFactory
			.getLogger(EstimatedValueParser.class);

	private @Autowired RawValueParser rvp;

	/**
	 * Experimental feature. It made a lot of wrong decisions and results.
	 *
	 * @param notice
	 */
	@Deprecated
	private void fixFromTotalQ(Notice notice) {
		for (ObjOfTheContract obj : notice.getObjs()) {

			if (notice.getObjs().get(0).getEstimatedValueMin() < notice
					.getObjs().get(0).getEstimatedValue()) {
				LOG.trace(
						"Estimated value fix skipped, we found minimum earlier: {}",
						notice.getObjs().get(0).getEstimatedValueMin());
				return;
			}

			StringBuilder sb = new StringBuilder();
			sb.append(obj.getTotalQuantity());

			List<Long> evs = new ArrayList<Long>();

			for (String line : sb.toString().split("\n")) {
				if (EXCL_PATTERN.matcher(line).find()) {
					continue;
				}
				Matcher m = ESTIM_VAL_PATTERN.matcher(line);
				while (m.find()) {
					String v = m.group("v");
					String c = m.group("c");
					String min = m.group("min");
					String max = m.group("max");
					String c2 = m.group("c2");
					LOG.trace("Fixer method found: " + v + "," + c + "," + min
							+ "," + max + "," + c2);
					evs.add(rvp.parseLong(null == max ? v : max));
				}
			}

			long sum = 0;
			long last = 0;
			for (Long ev : evs) {
				sum += ev;
				last = ev;
			}
			if (0 < sum) {
				if (2 < evs.size() && sum / 2 == last) {
					// if SUM(a[1..N-1]) == a[N]
					obj.setEstimatedValue(last);
					LOG.trace("Notice {}, estimated value fixed: last = {}",
							notice.getId().toString(), last);
				} else if (1 < evs.size()) {
					obj.setEstimatedValue(sum);
					LOG.trace("Notice {}, estimated value fixed: sum = {}",
							notice.getId().toString(), sum);
				}
			}
		}
	}

	public RawValueParser getRvp() {
		return rvp;
	}

	private boolean parseFromLots(Notice notice) {
		for (Lot lot : notice.getLots()) {
			String q = lot.getQuantity();
			if (null != q) {
				String r = StrUtils.lastLineOf(q);
				Matcher m = ESTIM_VAL_PATTERN.matcher(r);
				long ev = 0, em = 0;
				String ec = null;
				while (m.find()) {
					String v = m.group("v");
					String c = m.group("c");
					String min = m.group("min");
					String max = m.group("max");
					String c2 = m.group("c2");
					LOG.trace("Lot parser method found: " + v + "," + c + ","
							+ min + "," + max + "," + c2);
					ev = rvp.parseLong(null == max ? v : max);
					em = rvp.parseLong(null == min ? v : min);
					ec = null == c ? c2 : c;
				}
				if (!notice.getObjs().isEmpty()) {
					ev += notice.getObjs().get(0).getEstimatedValue();
					em += notice.getObjs().get(0).getEstimatedValueMin();
					notice.getObjs().get(0).setEstimatedValue(ev);
					notice.getObjs().get(0).setEstimatedValueMin(em);
					notice.getObjs().get(0).setEstimatedValueCurr(ec);
				} // currency is dirty...
			}
		}
		return !notice.getObjs().isEmpty()
				&& notice.getObjs().get(0).getEstimatedValue() > 0;
	}

	private void parseFromObj(Notice notice) {
		for (ObjOfTheContract obj : notice.getObjs()) {
			StringBuilder sb = new StringBuilder();
			sb.append(obj.getTotalQuantity());
			sb.append("\n");
			sb.append(obj.getShortDescription());
			sb.append("\n");
			sb.append(obj.getFrameworkAgreement());

			String s = sb.toString();
			if (null != s) {
				long ev = 0, em = 0;
				for (String line : s.split("\n")) {
					if (EXCL_PATTERN.matcher(line).find()) {
						continue;
					}
					Matcher m = ESTIM_VAL_PATTERN.matcher(line);
					while (m.find()) {
						String v = m.group("v");
						String c = m.group("c");
						String min = m.group("min");
						String max = m.group("max");
						String c2 = m.group("c2");
						LOG.trace("Obj parser method found: " + v + "," + c
								+ "," + min + "," + max + "," + c2);
						ev = Math.max(ev, rvp.parseLong(null == max ? v : max));
						em = Math.max(em, rvp.parseLong(null == min ? v : min));
						obj.setEstimatedValueCurr(null == c ? c2 : c);

					}
				}
				obj.setEstimatedValue(ev);
				obj.setEstimatedValueMin(em);

				// VAT? examples?
			}
		}
	}

	private void parseFromObjIn201424EU(Notice notice) {
		for (ObjOfTheContract o : notice.getObjs()) {
			if (0 == o.getEstimatedValue()) { // parseAwards can calculate it
				rvp.parseLong(o, "rawEstimatedValue", "estimatedValue");
			}
			rvp.parseLong(o, "rawLotEstimatedValue", "lotEstimatedValue");
		}
		// TODO sum lot values?
	}

	@Override
	protected Notice processImpl(Notice notice) throws Exception {
		String di = notice.getData().getDirective();
		if (null != di && di.matches(".*2014/24/EU.*")) {
			parseFromObjIn201424EU(notice);
			return notice;
		}

		boolean foundInLots = parseFromLots(notice);
		if (!foundInLots) {
			parseFromObj(notice);
			if (!notice.getObjs().isEmpty()) {
				LOG.trace("Notice {}, estimated before fix: {}", notice.getId()
						.toString(), notice.getObjs().get(0)
						.getEstimatedValue());
			}
			fixFromTotalQ(notice); // experimental
		}
		return notice;
	}

	public void setRvp(RawValueParser rvp) {
		this.rvp = rvp;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		 version="3.0">

    <display-name>jehan</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:jehan-rest.xml
            classpath:jehan-service.xml
        </param-value>
    </context-param>

	<filter>
		<filter-name>CorsFilter</filter-name>
		<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CorsFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <!-- Servlets -->
	<servlet>
		<servlet-name>com.github.jehan.rest.JehanApplication</servlet-name>
        <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>com.github.jehan.rest.JehanApplication</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from './components/common/header/Header.component';
import Welcome from './components/welcome/Welcome.component';
import Details from './components/details/Details.component';
import DetailsSunday from './components/details/DetailsSunday.component';
import Travel from './components/travel/Travel.component';
import Accommodation from './components/accommodation/Accommodation.component';
import Registry from './components/registry/Registry.component';
import Extras from './components/extras/Extras.component';
import Footer from './components/common/footer/Footer.component';
import Rsvp from './components/rsvp/Rsvp.container';

class App extends Component {
    componentDidMount() {
        const { updateGuest, guest_id } = this.props;
        if (guest_id) {
            updateGuest();
        }
    }

    render() {
        const { guest } = this.props;
        return (
            <div>
                <Header guest={guest} />
                <Welcome guest={guest} />
                <Details />
                <Travel />
                {guest.type === 'family' && <DetailsSunday />}
                {!guest.rsvp && <Rsvp />}
                <Accommodation />
                <Registry />
                <Extras />
                <Footer />
            </div>
        );
    }
}

App.propTypes = {
    guest: PropTypes.object,
    guest_id: PropTypes.string,
};

App.defaultProps = {
    guest: {},
    guest_id: '',
};

export default App;


text:
Pliers API Reference
--------------------

This is the full API reference for all user-facing classes and functions in the pliers package.

Converters (:mod:`pliers.converters`)
-------------------------------------

.. automodule:: pliers.converters
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.converters

.. autosummary::
	:toctree: generated/
  :template: _class.rst

	ComplexTextIterator
  ExtractorResultToSeriesConverter
	IBMSpeechAPIConverter
	GoogleSpeechAPIConverter
	GoogleVisionAPITextConverter
  MicrosoftAPITextConverter
  RevAISpeechAPIConverter
	TesseractConverter
	VideoFrameCollectionIterator
	VideoFrameIterator
	VideoToAudioConverter
	VideoToComplexTextConverter
	VideoToTextConverter
  WitTranscriptionConverter

**Functions**:

.. currentmodule:: pliers.converters

.. autosummary::
  :toctree: generated/
  :template: _function.rst

  get_converter

Dataset utilities (:mod:`pliers.datasets`)
------------------------------------------

.. automodule:: pliers.datasets
	:no-members:
	:no-inherited-members:

**Functions**:

.. currentmodule:: pliers.datasets

.. autosummary::
  :toctree: generated/
  :template: _function.rst

  fetch_dictionary

Diagnostic utilities (:mod:`pliers.diagnostics`)
------------------------------------------------

.. automodule:: pliers.diagnostics
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.diagnostics

.. autosummary::
	:toctree: generated/
  :template: _class.rst

  Diagnostics

**Functions**:

.. currentmodule:: pliers.diagnostics

.. autosummary::
   :toctree: generated/
   :template: _function.rst

   correlation_matrix
   eigenvalues
   condition_indices
   variance_inflation_factors
   mahalanobis_distances
   variances

Extractors (:mod:`pliers.extractors`)
-------------------------------------

.. automodule:: pliers.extractors
	:no-members:
	:no-inherited-members:

.. currentmodule:: pliers.extractors

**Classes**:

*Base extractors and associated objects*

.. autosummary::
	:toctree: generated/
	:template: _class.rst

	Extractor
	ExtractorResult

*Audio feature extractors*

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  AudiosetLabelExtractor
  BeatTrackExtractor
  ChromaCENSExtractor
  ChromaCQTExtractor
  ChromaSTFTExtractor
  HarmonicExtractor
  MeanAmplitudeExtractor
  MelspectrogramExtractor
  MFCCExtractor
  OnsetDetectExtractor
  OnsetStrengthMultiExtractor
  PercussiveExtractor
  PolyFeaturesExtractor
  RMSExtractor
  SpectralCentroidExtractor
  SpectralBandwidthExtractor
  SpectralContrastExtractor
  SpectralFlatnessExtractor
  SpectralRolloffExtractor
  STFTAudioExtractor
  TempogramExtractor
  TempoExtractor
  TonnetzExtractor
  ZeroCrossingRateExtractor

*Image feature extractors*

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  BrightnessExtractor
  ClarifaiAPIImageExtractor
  ClarifaiAPIVideoExtractor
  FaceRecognitionFaceEncodingsExtractor
  FaceRecognitionFaceLandmarksExtractor
  FaceRecognitionFaceLocationsExtractor
  GoogleVisionAPIFaceExtractor
  GoogleVisionAPILabelExtractor
  GoogleVisionAPIPropertyExtractor
  GoogleVisionAPISafeSearchExtractor
  GoogleVisionAPIWebEntitiesExtractor
  MicrosoftAPIFaceExtractor
  MicrosoftAPIFaceEmotionExtractor
  MicrosoftVisionAPIExtractor
  MicrosoftVisionAPITagExtractor
  MicrosoftVisionAPICategoryExtractor
  MicrosoftVisionAPIImageTypeExtractor
  MicrosoftVisionAPIColorExtractor
  MicrosoftVisionAPIAdultExtractor
  SaliencyExtractor
  SharpnessExtractor
  TFHubExtractor
  VibranceExtractor

*Text feature extractors*

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  BertExtractor
  BertSequenceEncodingExtractor
  BertLMExtractor
  BertSentimentExtractor
  ComplexTextExtractor
  DictionaryExtractor
  LengthExtractor
  NumUniqueWordsExtractor
  PartOfSpeechExtractor
  PredefinedDictionaryExtractor
  SpaCyExtractor
  TextVectorizerExtractor
  VADERSentimentExtractor
  WordCounterExtractor
  WordEmbeddingExtractor

*Video feature extractors*

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  FarnebackOpticalFlowExtractor

** Deep Learning Models ***

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  TensorFlowKerasApplicationExtractor
  TFHubImageExtractor
  TFHubTextExtractor
  TFHubExtractor

** Misc-type Extractors ***

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  MetricExtractor

**Functions**:

.. currentmodule:: pliers.extractors

.. autosummary::
  :toctree: generated/
  :template: _function.rst

  merge_results

Filters (:mod:`pliers.filters`)
-------------------------------

.. automodule:: pliers.filters
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.filters

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  FrameSamplingFilter
  ImageCroppingFilter
  PillowImageFilter
  PunctuationRemovalFilter
  TokenizingFilter
  TokenRemovalFilter
  WordStemmingFilter
  AudioResamplingFilter

Graph construction (:mod:`pliers.graph`)
----------------------------------------

.. automodule:: pliers.graph
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.graph

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

	Graph
	Node

Stimuli (:mod:`pliers.stimuli`)
-------------------------------

.. automodule:: pliers.stimuli
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.stimuli

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

  AudioStim
  ComplexTextStim
  CompoundStim
  ImageStim
  TextStim
  TweetStimFactory
  TweetStim
  TranscribedAudioCompoundStim
  VideoFrameCollectionStim
  VideoFrameStim
  VideoStim

**Functions**:

.. currentmodule:: pliers.stimuli

.. autosummary::
   :toctree: generated/
   :template: _function.rst

    load_stims

Transformers (:mod:`pliers.transformers`)
-----------------------------------------

.. automodule:: pliers.transformers
	:no-members:
	:no-inherited-members:

**Classes**:

.. currentmodule:: pliers.transformers

.. autosummary::
	:toctree: generated/
 	:template: _class.rst

	BatchTransformerMixin
	GoogleAPITransformer
	GoogleVisionAPITransformer
	Transformer

**Functions**:

.. currentmodule:: pliers.transformers

.. autosummary::
   :toctree: generated/
   :template: _function.rst

   get_transformer


text:
namespace chromeos {

namespace {

user_manager::UserType ConvertUserType(LoggedInUserMixin::LogInType type) {
  switch (type) {
    case LoggedInUserMixin::LogInType::kChild:
      return user_manager::USER_TYPE_CHILD;
    case LoggedInUserMixin::LogInType::kRegular:
      return user_manager::USER_TYPE_REGULAR;
  }
}

std::vector<LoginManagerMixin::TestUserInfo> GetInitialUsers(
    const LoginManagerMixin::TestUserInfo& user,
    bool include_initial_user) {
  if (include_initial_user)
    return {user};
  return {};
}

}  // namespace

LoggedInUserMixin::LoggedInUserMixin(
    InProcessBrowserTestMixinHost* mixin_host,
    LogInType type,
    net::EmbeddedTestServer* embedded_test_server,
    InProcessBrowserTest* test_base,
    bool should_launch_browser,
    base::Optional<AccountId> account_id,
    bool include_initial_user)
    : InProcessBrowserTestMixin(mixin_host),
      user_(account_id.value_or(
                AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kFakeUserEmail,
                                               FakeGaiaMixin::kFakeUserGaiaId)),
            ConvertUserType(type)),
      login_manager_(mixin_host, GetInitialUsers(user_, include_initial_user)),
      local_policy_server_(mixin_host),
      user_policy_(mixin_host, user_.account_id, &local_policy_server_),
      user_policy_helper_(user_.account_id.GetUserEmail(),
                          &local_policy_server_),
      embedded_test_server_setup_(mixin_host, embedded_test_server),
      fake_gaia_(mixin_host, embedded_test_server),
      test_base_(test_base) {
  // By default, LoginManagerMixin will set up user session manager not to
  // launch browser as part of user session setup - use this to override that
  // behavior.
  login_manager_.set_should_launch_browser(should_launch_browser);
}

LoggedInUserMixin::~LoggedInUserMixin() = default;

void LoggedInUserMixin::SetUpOnMainThread() {
  // By default, browser tests block anything that doesn't go to localhost, so
  // account.google.com requests would never reach fake GAIA server without
  // this.
  test_base_->host_resolver()->AddRule("*", "127.0.0.1");
}

void LoggedInUserMixin::LogInUser(bool issue_any_scope_token,
                                  bool wait_for_active_session,
                                  bool request_policy_update) {
  UserContext user_context = LoginManagerMixin::CreateDefaultUserContext(user_);
  user_context.SetRefreshToken(FakeGaiaMixin::kFakeRefreshToken);
  if (user_.user_type == user_manager::USER_TYPE_CHILD) {
    fake_gaia_.SetupFakeGaiaForChildUser(
        user_.account_id.GetUserEmail(), user_.account_id.GetGaiaId(),
        FakeGaiaMixin::kFakeRefreshToken, issue_any_scope_token);
  } else {
    fake_gaia_.SetupFakeGaiaForLogin(user_.account_id.GetUserEmail(),
                                     user_.account_id.GetGaiaId(),
                                     FakeGaiaMixin::kFakeRefreshToken);
  }
  if (request_policy_update) {
    // Set up policy, which prevents the call to LoginAndWaitForActiveSession()
    // below from hanging indefinitely in some test scenarios.
    GetUserPolicyMixin()->RequestPolicyUpdate();
  }
  if (wait_for_active_session) {
    login_manager_.LoginAndWaitForActiveSession(user_context);
    // Set the private |browser_| member in InProcessBrowserTest.
    // Otherwise calls to InProcessBrowserTest::browser() returns null and leads
    // to segmentation faults.
    // Note: |browser_| is only non-null if should_launch_browser was set to
    // true in the constructor.
    test_base_->SelectFirstBrowser();
  } else {
    login_manager_.AttemptLoginUsingAuthenticator(
        user_context, std::make_unique<StubAuthenticatorBuilder>(user_context));
  }
}

}  // namespace chromeos


text:
typedef enum {
    TURN, MOVE, DRAW, END, NONE
} command_t;

// To be implemented in 'scanner.c'
void init_transtab(void);
command_t next(FILE *input);

// Control and command emission, implemented in 'pencil.c'
void turn(void);
void move(void);
void draw(void);
void emit_instruction(command_t word);


text:
/**
 * @file gpu_integration_defs.h
 * DDK porting layer.
 */

#ifndef _SEC_INTEGRATION_H_
#define _SEC_INTEGRATION_H_

#include <mali_kbase.h>
#include <mali_kbase_mem_linux.h>
#include "mali_kbase_platform.h"
#include "gpu_dvfs_handler.h"

#ifdef MALI_SEC_HWCNT
#include "gpu_hwcnt_sec.h"
#endif

/* kctx initialized with zero from vzalloc, so initialized value required only */
#define CTX_UNINITIALIZED 0x0
#define CTX_INITIALIZED 0x1
#define CTX_DESTROYED 0x2
#define CTX_NAME_SIZE 32

/* MALI_SEC_SECURE_RENDERING */
#define SMC_GPU_CRC_REGION_NUM		8

/* MALI_SEC_INTEGRATION */
#define KBASE_PM_TIME_SHIFT			8

/* MALI_SEC_INTEGRATION */
#define MEM_FREE_LIMITS 16384
#define MEM_FREE_DEFAULT 16384

uintptr_t gpu_get_callbacks(void);
int gpu_vendor_dispatch(struct kbase_context *kctx, void * const args, u32 args_size);
void gpu_cacheclean(struct kbase_device *kbdev);
void kbase_mem_free_list_cleanup(struct kbase_context *kctx);
void kbase_mem_set_max_size(struct kbase_context *kctx);

#ifdef MALI_SEC_FENCE_INTEGRATION
void kbase_fence_del_timer(void *atom);
#endif

struct kbase_vendor_callbacks {
	void (* create_context)(void *ctx);
	void (* destroy_context)(void *ctx);
	void (* pm_metrics_init)(void *dev);
	void (* pm_metrics_term)(void *dev);
	void (* cl_boost_init)(void *dev);
	void (* cl_boost_update_utilization)(void *dev, void *atom, u64 microseconds_spent);
	void (* fence_timer_init)(void *atom);
	void (* fence_del_timer)(void *atom);
	int (* get_core_mask)(void *dev);
	int (* init_hw)(void *dev);
	void (* hwcnt_attach)(void *dev);
	void (* hwcnt_update)(void *dev);
	void (* hwcnt_detach)(void *dev);
	void (* hwcnt_enable)(void *dev);
	void (* hwcnt_disable)(void *dev);
	void (* hwcnt_force_start)(void *dev);
	void (* hwcnt_force_stop)(void *dev);
	void (* set_poweron_dbg)(bool enable_dbg);
	bool (* get_poweron_dbg)(void);
	void (* debug_pagetable_info)(void *ctx, u64 vaddr);
	void (* update_status)(void *dev, char *str, u32 val);
	bool (* mem_profile_check_kctx)(void *ctx);
	void (* pm_record_state)(void *kbdev, bool is_active);
	int (* register_dump)(void);
#ifdef CONFIG_MALI_DVFS_USER
	bool (* dvfs_process_job)(void *atom);
#endif
};

#endif /* _SEC_INTEGRATION_H_ */


text:
package com.vishnu.solotraveller.ui.main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.vishnu.solotraveller.R;
import com.vishnu.solotraveller.accessibility.AccessService;
import com.vishnu.solotraveller.data.model.BudgetFlight;
import com.vishnu.solotraveller.data.model.Example;
import com.vishnu.solotraveller.data.model.Flight;
import com.vishnu.solotraveller.ui.base.BaseActivity;

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import timber.log.Timber;

public class MainActivity extends BaseActivity implements MainMvpView {

    @Inject
    com.vishnu.solotraveller.ui.main.MainPresenter mMainPresenter;

    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;
    @BindView(R.id.recommended_destinations)ViewPager mRecommendedDestViewPager;
RecommendedDestAdapter recommendedDestAdapter;
    List<Flight> flights = new ArrayList<>();
    List<BudgetFlight> budgetFlights = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityComponent().inject(this);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
checkPermission();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mMainPresenter.attachView(this);
        mMainPresenter.loadRecommendedDestinations();

        if (!isAccessibilitySettingsOn(getApplicationContext())) {
            startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
        }
        recommendedDestAdapter = new RecommendedDestAdapter(this);
        mRecommendedDestViewPager.setAdapter(recommendedDestAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mMainPresenter.detachView();
    }
    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1);
            }
        }
    }

    @Override
    public void showRecommendedDestinations(Example example) {
       flights = example.data.flight;
        budgetFlights= example.data.budgetFlight;
    }

    @Override
    public void hideViewPager() {

    }

    /***** MVP View methods implementation *****/

    private static class RecommendedDestAdapter extends PagerAdapter{

        private int count;

        private Context mContext;
        private LayoutInflater mLayoutInflater;
        public RecommendedDestAdapter(Context context)
        {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return count;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return mLayoutInflater.inflate(R.layout.recommended_destination_layout,container,false);
        }

        private void setCount(int count)
        {
            this.count= count;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = getPackageName() + "/" + AccessService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
            Timber.d( "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Timber.d( "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Timber.d( "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    Timber.d( "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Timber.d( "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Timber.d( "***ACCESSIBILITY IS DISABLED***");
        }

        return false;
    }

}


text:
require_relative "test_helper"

class InterceptorTest < MiniTest::Test
  context "With a Base Interceptor" do
    setup do
      @interceptor = SmsSafe::Interceptor.new
      @message = SmsSafe::Message.new(from: EXTERNAL_PHONE_NUMBERS.first, to: EXTERNAL_PHONE_NUMBERS.first, text: "Foo")
    end

    should "raise an exception if calling convert_message" do
      assert_raises(RuntimeError) do
        @interceptor.convert_message(@message)
      end
    end

    should "raise an exception if calling redirect" do
      assert_raises(RuntimeError) do
        @interceptor.redirect(@message)
      end
    end
  end

  context "With a Test Interceptor" do
    setup do
      @interceptor = TestInterceptor.new

      SmsSafe.configure do |config|
        config.internal_phone_numbers = INTERNAL_PHONE_NUMBERS
        config.intercept_mechanism = :redirect
        config.redirect_target = DEFAULT_INTERNAL_PHONE_NUMBER
      end

      @internal_message = SmsSafe::Message.new(from: INTERNAL_PHONE_NUMBERS.first, to: INTERNAL_PHONE_NUMBERS.last, text: "Foo") # Doesn't get intercepted
      @external_message = SmsSafe::Message.new(from: INTERNAL_PHONE_NUMBERS.first, to: EXTERNAL_PHONE_NUMBERS.last, text: "Bar") # Gets intercepted
    end

    context "intercepting by String" do
      setup do
        SmsSafe.configure { |config| config.internal_phone_numbers = DEFAULT_INTERNAL_PHONE_NUMBER }
      end

      should "choose to intercept message for non-matching numbers" do
        check_interception_rules(@interceptor, EXTERNAL_PHONE_NUMBERS, true)
      end

      should "not choose to intercept message for internal number" do
        check_interception_rules(@interceptor, [DEFAULT_INTERNAL_PHONE_NUMBER], false)
      end
    end

    context "intercepting by Regex" do
      setup do
        SmsSafe.configure { |config| config.internal_phone_numbers = INTERNAL_PHONE_NUMBERS_REGEX }
      end

      should "choose to intercept message for non-matching number" do
        check_interception_rules(@interceptor, EXTERNAL_PHONE_NUMBERS, true)
      end

      should "not choose to intercept message for internal number" do
        check_interception_rules(@interceptor, INTERNAL_PHONE_NUMBERS, false)
      end
    end

    context "intercepting by Proc" do
      setup do
        SmsSafe.configure { |config| config.internal_phone_numbers = INTERNAL_PHONE_NUMBERS_PROC }
      end

      should "choose to intercept message for non-matching number" do
        check_interception_rules(@interceptor, EXTERNAL_PHONE_NUMBERS, true)
      end

      should "not choose to intercept message for internal number" do
        check_interception_rules(@interceptor, INTERNAL_PHONE_NUMBERS, false)
      end
    end

    context "intercepting by Mixture of methods" do
      setup do
        SmsSafe.configure { |config| config.internal_phone_numbers = [DEFAULT_INTERNAL_PHONE_NUMBER, INTERNAL_PHONE_NUMBERS_REGEX, INTERNAL_PHONE_NUMBERS_PROC] }
      end

      should "choose to intercept message for non-matching number" do
        check_interception_rules(@interceptor, EXTERNAL_PHONE_NUMBERS, true)
      end

      should "not choose to intercept message for internal number" do
        check_interception_rules(@interceptor, INTERNAL_PHONE_NUMBERS, false)
      end
    end

    context "intercepting by Invalid Comparison Method" do
      setup do
        SmsSafe.configure { |config| config.internal_phone_numbers = 5 } # An Integer is not a valid rule for comparison
      end

      should "raise exception" do
        assert_raises(SmsSafe::InvalidConfigSettingError) do
          check_interception_rules(@interceptor, INTERNAL_PHONE_NUMBERS, false)
        end
      end
    end

    context "intercepting by Redirecting" do
      # The logic inside redirect is tested within each of the interceptors, not here
      should "return an intercepted message if intercepting" do
        original_message = @external_message.clone
        result = @interceptor.process_message(@external_message)
        refute_nil result
        assert_equal SmsSafe::Message, result.class
        assert_operator original_message.text.length, :<, result.text.length # Message length must have increased
        assert_match original_message.text, result.text # New message must include the original one
        refute_equal original_message.to, result.to # Recipient must have changed
        assert_equal SmsSafe.configuration.redirect_target, result.to # Recipient must be redirect target
      end

      should "return an identical message if not intercepting" do
        process_and_assert_identical_message(@interceptor, @internal_message)
      end
    end

    context "intercepting by Emailing" do
      setup do
        SmsSafe.configure do |config|
          config.intercept_mechanism = :email
          config.email_target = 'blah@blah.com'
        end
      end

      should "send an email and return nil if intercepting" do
        original_message = @external_message.clone
        assert_difference "Mail::TestMailer.deliveries.length", +1 do
          result = @interceptor.process_message(@external_message)
          assert_nil result
        end

        mail = Mail::TestMailer.deliveries.last

        assert have_sent_email.from('blah@blah.com').matches?(mail)
        assert have_sent_email.to('blah@blah.com').matches?(mail)
        assert_match original_message.text, mail.body.to_s # Email must contain original SMS text, from and to
        assert_match original_message.from, mail.body.to_s
        assert_match original_message.to, mail.body.to_s
      end

      should "return an identical message if not intercepting" do
        process_and_assert_identical_message(@interceptor, @internal_message)
      end
    end

    context "intercepting by Discarding" do
      setup do
        SmsSafe.configure do |config|
          config.intercept_mechanism = :discard
          config.discard_delay = 0
        end
      end

      should "return immediately and return nil if intercepting without delay" do
        time_to_run = Benchmark.realtime do
          result = @interceptor.process_message(@external_message)
          assert_nil result
        end
        assert_operator 20, :>=, time_to_run * 1000 # Must take less than 20ms (arbitrary number picked to show there's no delay)
      end

      context "with delay" do
        setup do
          SmsSafe.configure { |config| config.discard_delay = 100 } # Delay by 100ms
          end
        should "delay and return nil if intercepting with delay" do
          time_to_run = Benchmark.realtime do
            result = @interceptor.process_message(@external_message)
            assert_nil result
          end
          assert_operator 100, :<=, time_to_run * 1000 # Must take at least 100ms
        end
      end

      should "return an identical message if not intercepting" do
        process_and_assert_identical_message(@interceptor, @internal_message)
      end
    end

    context "intercepting by Invalid Mechanism" do
      setup do
        SmsSafe.configure { |config| config.intercept_mechanism = :invalid }
      end

      should "raise an exception if intercepting" do
        assert_raises(SmsSafe::InvalidConfigSettingError) do
          @interceptor.process_message(@external_message)
        end
      end
    end

    context "resolving target phone number by Proc" do
      setup do
        SmsSafe.configure { |config| config.redirect_target = Proc.new { |m| "#{m.to}#123" } }
      end
      should "redirect to the appropriate phone number" do
        result = @interceptor.redirect_phone_number(@external_message)
        assert_equal @external_message.to + "#123", result
      end
    end

    context "resolving target phone number by Invalid Method" do
      setup do
        SmsSafe.configure { |config| config.redirect_target = /5/ } # A regex is not a valid target
      end
      should "raise an exception if redirecting" do
        assert_raises(SmsSafe::InvalidConfigSettingError) do
          @interceptor.redirect_phone_number(@external_message)
        end
      end
    end

    context "resolving target email by Proc" do
      setup do
        SmsSafe.configure { |config| config.email_target = Proc.new { |m| "#{m.to}@blah.com" } }
      end
      should "email to the appropriate address" do
        result = @interceptor.email_recipient(@external_message)
        assert_equal @external_message.to + "@blah.com", result
      end
    end

    context "resolving target email by Invalid Method" do
      setup do
        SmsSafe.configure { |config| config.email_target = /5/ } # A regex is not a valid target
      end
      should "raise an exception if redirecting" do
        assert_raises(SmsSafe::InvalidConfigSettingError) do
          @interceptor.email_recipient(@external_message)
        end
      end
    end
  end # context "With a base Interceptor"
end


text:
(function() {
    'use strict';

    angular
        .module('app.benefitsMaster')
        .service('benefitsMasterService', benefitsMasterService);

    function benefitsMasterService($q,$http) {
    	var url = "http://192.168.1.114:8080/api/BenefitsMasterDatas";

        this.getAll = function() {
        	var defer = $q.defer();
            var params = {};
            $http({
                method: 'GET',
                url: url
            }).then(function successCallback(response) {
            	defer.resolve(response);
            }, function errorCallback(response) {
                defer.reject(response);
            });

            // $http.get('app/data/employee/benefitsData.json')
            // .success(function(data){
            // 	defer.resolve(data);
            // })
            // .error(function(err){
            // 	defer.reject(err);
            // });

            return defer.promise;
        }

        this.post = function(benefitsMaster){
        	var defer = $q.defer();
        	$http.post(url,benefitsMaster).success(function(response){
        		defer.resolve(response);
        	})
        	.error(function(response){
        		defer.reject(response);
        	});
        	return defer.promise;
        }

        this.put = function(benefitsMaster){
        	var defer = $q.defer();
        	$http.put(url +'/'+benefitsMaster.BnID,benefitsMaster).success(function(response){
        		defer.resolve(response);
        	})
        	.error(function(response){
        		defer.reject(response);
        	});
        	return defer.promise;
        }

        this.delete = function(benefitsMaster){
            var defer = $q.defer();
            $http.delete(url +'/'+benefitsMaster.BnID,benefitsMaster).success(function(response){
                defer.resolve(response);
            })
            .error(function(response){
                defer.reject(response);
            });
            return defer.promise;
        }
    }
})();


text:
export class SuperheroUiPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('superhero-ui-app h1')).getText();
  }
}


text:
using System.Collections.Generic;
using VkNet.Abstractions;
using VkNet.Model;
using VkNet.Model.RequestParams.Notifications;
using VkNet.Model.Results.Notifications;
using VkNet.Utils;

namespace VkNet.Categories;

/// <inheritdoc />
public partial class NotificationsCategory : INotificationsCategory
{
	/// <summary>
	/// API.
	/// </summary>
	private readonly IVkApiInvoke _vk;

	/// <summary>
	/// api vk.com
	/// </summary>
	/// <param name="vk">
	/// Api vk.com
	/// </param>
	public NotificationsCategory(VkApi vk = null) => _vk = vk;

	/// <inheritdoc />
	public NotificationGetResult Get(ulong? count = null
									, string startFrom = null
									, IEnumerable<string> filters = null
									, long? startTime = null
									, long? endTime = null) => _vk.Call<NotificationGetResult>("notifications.get",
		new()
		{
			{
				"count", count
			},
			{
				"start_from", startFrom
			},
			{
				"filters", filters
			},
			{
				"start_time", startTime
			},
			{
				"end_time", endTime
			}
		});

	/// <inheritdoc />
	public bool MarkAsViewed() => _vk.Call<bool>("notifications.markAsViewed", VkParameters.Empty);

	/// <inheritdoc />
	public IEnumerable<NotificationsSendMessageResult> SendMessage(NotificationsSendMessageParams sendMessageParams) =>
		_vk.Call<IEnumerable<NotificationsSendMessageResult>>("notifications.sendMessage",
			new()
			{
				{
					"user_ids", sendMessageParams.UserIds
				},
				{
					"message", sendMessageParams.Message
				},
				{
					"fragment", sendMessageParams.Fragment
				},
				{
					"sending_mode", sendMessageParams.SendingMode
				},
				{
					"group_id", sendMessageParams.GroupId
				},
				{
					"random_id", sendMessageParams.RandomId
				}
			});
}


text:
Using Web Hooks
===============

You can use khan's web hooks to send detailed event information to other servers. The use cases for this are plenty, since the need for integrating micro-services is very common.

One possible use case would be to notify the chat channel for your game with information about people joining/leaving the clan or for new applications.

## Webhook Workers

Khan uses [GoWorkers](https://github.com/jrallison/go-workers) workers to send webhooks. This means that you need to run the `khan worker` command to start as many workers as you want.

## Webhook Specific Configuration

Khan has some configuration entries specific to webhooks:

* `redis.host` - Redis server host used for [GoWorkers](https://github.com/jrallison/go-workers);
* `redis.port` - Redis server port used for [GoWorkers](https://github.com/jrallison/go-workers);
* `redis.database` - Redis server database used for [GoWorkers](https://github.com/jrallison/go-workers);
* `redis.pool` - Redis connection pool size used for [GoWorkers](https://github.com/jrallison/go-workers);
* `redis.password` - Redis password used for [GoWorkers](https://github.com/jrallison/go-workers);
* `webhooks.timeout` - Timeout for webhook HTTP connections;
* `webhooks.workers` - Number of [GoWorkers](https://github.com/jrallison/go-workers) to start with each instance of Khan worker;
* `webhooks.runStats` - Will the [GoWorkers](https://github.com/jrallison/go-workers) stats server run in each Khan worker instance?;
* `webhooks.statsPort` - Port that the stats server of [GoWorkers](https://github.com/jrallison/go-workers) will run in.

## Registering a Web Hook

Registering a web hook is done using the [Create Web Hook Route](API.html#create-hook). A hook can also be removed using the [Remove Web Hook Route](API.html#remove-hook). Just make sure you keep the PublicID that was returned by the Create Hook route as it is required to remove a hook.

## How do Web Hooks work?

When an event happen in Khan, it will look for all the hooks registered for the game that the event happened in.

It will then do a POST request to all of them with the payload relevant to the event (more about the payloads in the Events section). The payload for the events is just a JSON object in the body of the request.

Let's say we want to keep track of all the clans that are created in our game. We could create a web hook for the `ClanCreated` event and Khan would call our hook with this payload:

    {
      gameID: "my-game",
      publicID: "clan-public-id",
      name: "My Fancy Clan"
    }

We could then use this information to store this clan in our Database, to integrate with a chat channel, to provision some third-party system for clans, etc.

## URL Format and Flexibility

When registering a new URL, Khan allows you to specify the URL as a Template.

Let's assume you need to use the clan public ID in your URL to store a newly created clan at `http://my-system.com:3030/clans/some-clan/`. Instead of some-clan, we need to use the clan's public ID.

This is very easy to do with Khan. You can interpolate any of the keys in the payload using `{{key}}`. Bear in mind that only two types of keys can be used:

* top-level keys - if you use a key that's in the first level of depth in the payload, you are good with any type of key;
* dot separated keys - this type of key will only work if all the keys in the path are objects (except the last one).

Let's try with the payload for the player created event:

```
    {
        "success": true,
        "gameID":  "some-game",
        "publicID": "playerPublicID",
        "name": "Player Name",
        "metadata": {
            "score": 1200,
            "league": {
                ranking: "diamond",
                position: 30
            }
        }
    }
```

Now imagine we want the player to be included in the league he belongs to. We could use an URL like `http://my-server.com:3030/players/{{publicID}}/leagues/{{metadata.league.ranking}}/`. This would be translated by Khan to `http://my-server.com:3030/players/playerPublicID/leagues/diamond/`.

## Event Types

So what types of events can you [create Web Hooks for](http://khan-api.readthedocs.io/en/latest/API.html#create-hook)?

### Game Hooks

#### Game Updated

Event Type: `0`

Payload:

    {
        "success": true,
        "type": 0,                                  // Event Type
        "publicID": [string],                       // Game ID
        "name": [string],                           // Game Name
        "metadata": [JSON],                         // JSON Object containing game metadata.
        "membershipLevels": [JSON],                 // JSON Object mapping membership levels
        "minLevelToAcceptApplication": [int],       // Minimum level of membership required
                                                    // to accept players into clan
        "minLevelToCreateInvitation": [int],        // Minimum level of membership required
                                                    // to invite players into clan
        "minLevelToRemoveMember": [int],            // Minimum level of membership required
                                                    // to remove players from clan
        "minLevelOffsetToRemoveMember": [int],      // A player must be at least this offset
                                                    // higher than the player being removed.
        "minLevelOffsetToPromoteMember": [int],     // A player must be at least this offset
                                                    // higher than the player being promoted
        "minLevelOffsetToDemoteMember": [int],      // A player must be at least this offset
                                                    // higher than the player being demoted
        "maxMembers": [int],                        // Maximum number of players in the clan
        "maxClansPerPlayer": [int]                  // Maximum number of clans the player can be
                                                    // member of
    }

### Player Hooks

#### Player Created

Event Type: `1`

Payload:

    {
        "gameID":  [string],                        // Game ID
        "type": 1,                                  // Event Type
        "publicID": [string],                       // Created Player PublicID This id should
                                                    // be used when referring to the player in
                                                    // future operations.
        "name": [string],                           // Player Name
        "metadata": [JSON],                         // JSON Object containing player metadata
        "membershipCount": [int],                   // Number of clans this player is a member of
        "ownershipCount":  [int],                   // Number of clans this player is an owner of
        "id": [UUID],                               // unique id that identifies the hook
        "timestamp": [timestamp]                    // timestamp in the RFC3339 format
    }

#### Player Updated

Event Type: `2`

Payload:

    {
        "gameID":  [string],                        // Game ID
        "type": 2,                                  // Event Type
        "publicID": [string],                       // Created Player PublicID This id should
                                                    // be used when referring to the player in
                                                    // future operations.
        "name": [string],                           // Player Name
        "metadata": [JSON],                         // JSON Object containing player metadata
        "membershipCount": [int],                   // Number of clans this player is a member of
        "ownershipCount":  [int],                   // Number of clans this player is an owner of
        "id": [UUID],                               // unique id that identifies the hook
        "timestamp": [timestamp]                    // timestamp in the RFC3339 format
    }

### Clan Hooks

#### Clan Created

Event Type: `3`

Payload:

    {
        "gameID":  [string],                        // Game ID
        "type": 3,                                  // Event Type
        "clan": {
          "publicID": [string],                     // Created Clan PublicID This id should
                                                    // be used when referring to the clan in
                                                    // future operations.
          "name": [string],                         // Clan Name
          "metadata": [JSON],                       // JSON Object containing clan's metadata
          "allowApplication": [bool],               // Indicates whether this clan acceps applications
          "autoJoin": [bool]                        // Indicates whether this clan automatically
                                                    // accepts applications
        }
        "id": [UUID],                               // unique id that identifies the hook
        "timestamp": [timestamp]                    // timestamp in the RFC3339 format
    }

#### Clan Updated

Event Type: `4`

Payload:

    {
        "gameID":  [string],                        // Game ID
        "type": 4,                                  // Event Type
        "clan": {
          "publicID": [string],                     // Updated Clan PublicID This id should
                                                    // be used when referring to the clan in
                                                    // future operations.
          "name": [string],                         // Clan Name
          "metadata": [JSON],                       // JSON Object containing clan's metadata
          "allowApplication": [bool],               // Indicates whether this clan acceps applications
          "autoJoin": [bool]                        // Indicates whether this clan automatically
                                                    // accepts applications
        }
        "id": [UUID],                               // unique id that identifies the hook
        "timestamp": [timestamp]                    // timestamp in the RFC3339 format
    }

**WARNING**: This event may be skipped if the game's `clanHookFieldsWhitelist` field is not empty and none of the fields that actually changed is in the whitelist. Imagine you have a document like this:

```
{
    "trophies": 30,
    "country": "US",
}
```

The game is configured with `clanHookFieldsWhitelist = "country"`. That means that changing the number of trophies won't dispatch hooks, but changing the country (or any other clan property) will.

#### Clan Owner Left

Event Type: `5`

Payload:

    {
        "gameID": [string],
        "type": 5,                                      // Event Type
        "isDeleted": [bool],                            //Indicates whether the clan was deleted
                                                        //because there were no members left
        "clan": {
            "publicID": [string],                       // Updated Clan PublicID
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "previousOwner": {                              // The owner that left
            "publicID": [string],                       // Previous Owner PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "newOwner": {                                   // After the owner left, this is the new owner
            "publicID": [string],                       // New Owner PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Clan Ownership Transferred to Another Player

Event Type: `6`

Payload:

    {
        "gameID": [string],
        "type": 6,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Updated Clan PublicID
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "previousOwner": {                                   // The previous owner
            "publicID": [string],                       // Previous Owner PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "newOwner": {                                   // Player that the owner transferred ownership to
            "publicID": [string],                       // New Owner PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

### Membership Hooks

#### Membership Created

This event occurs if a player applies to a clan (player == requestor) or if a player is invited to a clan (player != requestor).

Event Type: `7`

Payload:

    {
        "gameID": [string],
        "type": 7,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that player is applying to
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that is applying/being invited to the clan
            "publicID": [string],                       // Applicant PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int],                   // Number of clans this player is an owner of
            "membershipLevel":  [string]                // The level of the player's membership
        },
        "requestor": {                                  // Player that requested this membership application/invite
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Membership Approved

This event occurs if an application or an invite to a clan gets approved. If the membership that was approved was an invitation into the clan, the requestor and the player will be the same Player. Otherwise, the requestor will be whomever approved the membership.

Event Type: `8`

Payload:

    {
        "gameID": [string],
        "type": 8,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that membership was approved
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that was approved into the clan
            "publicID": [string],                       // Player PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int],                   // Number of clans this player is an owner of
            "membershipLevel":  [string]                // The level of the player's membership
        },
        "requestor": {                                  // Player that approved the membership
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "creator": {                                    // Player that created the membership (invited or applied)
            "publicID": [string],                       // Creator PublicID
            "name": [string],                           // Creator Name
            "metadata": [JSON],                         // JSON Object containing creator metadata
            "membershipCount": [int],                   // Number of clans this creator is a member of
            "ownershipCount":  [int]                    // Number of clans this creator is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Membership Denied

This event occurs if an application or an invite to a clan gets denied. If the membership that was denied was an invitation into the clan, the requestor and the player will be the same Player. Otherwise, the requestor will be whomever denied the membership.

Event Type: `9`

Payload:

    {
        "gameID": [string],
        "type": 9,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that membership was denied
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that was denied into the clan
            "publicID": [string],                       // Player PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int],                   // Number of clans this player is an owner of
            "membershipLevel":  [string]                // The level of the player's membership
        },
        "requestor": {                                  // Player that denied the membership
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "creator": {                                    // Player that created the membership (invited or applied)
            "publicID": [string],                       // Creator PublicID
            "name": [string],                           // Creator Name
            "metadata": [JSON],                         // JSON Object containing creator metadata
            "membershipCount": [int],                   // Number of clans this creator is a member of
            "ownershipCount":  [int]                    // Number of clans this creator is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Member Promoted

Event Type: `10`

Payload:

    {
        "gameID": [string],
        "type": 10,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that member was promoted
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that was promoted
            "publicID": [string],                       // Player PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int],                   // Number of clans this player is an owner of
            "membershipLevel":  [string]                // The new level of the player's membership
        },
        "requestor": {                                  // Player that promoted this member
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Member Demoted

Event Type: `11`

Payload:

    {
        "gameID": [string],
        "type": 11,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that member was demoted
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that was demoted
            "publicID": [string],                       // Player PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of,
            "membershipLevel":  [string]                // The new level of the player's membership
        },
        "requestor": {                                  // Player that demoted this member
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }

#### Member Left

Event Type: `12`

Payload:

    {
        "gameID": [string],
        "type": 12,                                  // Event Type
        "clan": {
            "publicID": [string],                       // Clan that member left
            "name": [string],                           // Clan Name
            "metadata": [JSON],                         // JSON Object containing clan's metadata
            "allowApplication": [bool]                  // Indicates whether this clan acceps applications
            "autoJoin": [bool],                         // Indicates whether this clan automatically
                                                        // accepts applications
            "membershipCount":  [int],                  // Number of members in clan
        },
        "player": {                                     // Player that left
            "publicID": [string],                       // Player PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int],                   // Number of clans this player is an owner of
            "membershipLevel":  [string]                // The level of the player's membership
        },
        "requestor": {                                  // Player that removed leaving player (if they left
                                                        // on their own, then this is the same as player)
            "publicID": [string],                       // Requestor PublicID
            "name": [string],                           // Player Name
            "metadata": [JSON],                         // JSON Object containing player metadata
            "membershipCount": [int],                   // Number of clans this player is a member of
            "ownershipCount":  [int]                    // Number of clans this player is an owner of
        },
        "id": [UUID],                                   // unique id that identifies the hook
        "timestamp": [timestamp]                        // timestamp in the RFC3339 format
    }


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// tile_group.h
//
// Identification: src/include/codegen/tile_group.h
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include "codegen/codegen.h"
#include "codegen/value.h"

namespace peloton {

namespace catalog {
class Schema;
}  // namespace catalog

namespace codegen {

class ScanCallback;

//===----------------------------------------------------------------------===//
// Like codegen::Table, this class is the main entry point for code generation
// for tile groups. An instance of this class should exist for each instance of
// codegen::Table (in fact, this should be a member variable).  The schema of
// the tile group is that of the whole table. We abstract away the fact that
// each _individual_ tile group by have a different layout.
//===----------------------------------------------------------------------===//
class TileGroup {
 public:
  // Constructor
  explicit TileGroup(const catalog::Schema &schema);

  /// This class cannot be copy or move-constructed
  DISALLOW_COPY_AND_MOVE(TileGroup);

  // Generate code that performs a sequential scan over the provided tile group
  void GenerateTidScan(CodeGen &codegen, llvm::Value *tile_group_ptr,
                       llvm::Value *column_layouts, uint32_t batch_size,
                       ScanCallback &consumer) const;

  llvm::Value *GetNumTuples(CodeGen &codegen, llvm::Value *tile_group) const;

  llvm::Value *GetTileGroupId(CodeGen &codegen, llvm::Value *tile_group) const;

 private:
  // A struct to capture enough information to perform strided accesses
  struct ColumnLayout {
    uint32_t col_id;
    llvm::Value *col_start_ptr;
    llvm::Value *col_stride;
    llvm::Value *is_columnar;
  };

  /*
  //===--------------------------------------------------------------------===//
  // A convenience class to access to a column
  //===--------------------------------------------------------------------===//
  class ColumnAccess {
   public:
    ColumnAccess(CodeGen &codegen, llvm::Value *column_layout, oid_t column_id);

    // Load a vector of columns starting at the provided TID
    llvm::Value *LoadVector(llvm::Value *tid, uint32_t vector_size);

    // Get the pointer to the first value of the column
    llvm::Value *GetColumnPtr();

    // Get the column's stride in the tile group
    llvm::Value *GetStride();

    // Is the column stored in columnar form?
    llvm::Value *IsColumnar();

   private:
    CodeGen &codegen_;
    llvm::Value *column_layout_;

    oid_t column_id_;
    llvm::Value *col_ptr_;
    llvm::Value *col_stride_;
    llvm::Value *is_columnar_;
  };
  */

  std::vector<TileGroup::ColumnLayout> GetColumnLayouts(
      CodeGen &codegen, llvm::Value *tile_group_ptr,
      llvm::Value *column_layout_infos) const;

  // Access a given column for the row with the given tid
  codegen::Value LoadColumn(CodeGen &codegen, llvm::Value *tid,
                            const TileGroup::ColumnLayout &layout) const;

 public:
  //===--------------------------------------------------------------------===//
  // A convenience class that allows generic access (i.e., either row-oriented
  // or column-oriented) to the tile group.
  //===--------------------------------------------------------------------===//
  class TileGroupAccess {
   public:
    // Constructor
    TileGroupAccess(const TileGroup &tile_group,
                    const std::vector<ColumnLayout> &tile_group_layout);

    //===------------------------------------------------------------------===//
    // A row in this tile group
    //===------------------------------------------------------------------===//
    class Row {
     public:
      // Constructor
      Row(const TileGroup &tile_group,
          const std::vector<ColumnLayout> &tile_group_layout, llvm::Value *tid);

      // Load the column at the given index
      codegen::Value LoadColumn(CodeGen &codegen, uint32_t col_idx) const;

      llvm::Value *GetTID() const { return tid_; }

     private:
      // The tile group this row belongs to
      const TileGroup &tile_group_;
      // The layout of the tile group
      const std::vector<ColumnLayout> &layout_;
      // The tid of the row
      llvm::Value *tid_;
    };

    // Load a specific row from the batch
    Row GetRow(llvm::Value *tid) const;

    //===------------------------------------------------------------------===//
    // ACCESSORS
    //===------------------------------------------------------------------===//

    const TileGroup &GetTileGroup() const { return tile_group_; }

    const ColumnLayout &GetLayout(uint32_t col_idx) const {
      return layout_[col_idx];
    }

   private:
    // The tile group
    const TileGroup &tile_group_;
    // The layout of all columns in the tile group
    const std::vector<ColumnLayout> &layout_;
  };

 private:
  // The schema for all tile groups. Each tile group may have a different
  // configuration of tiles (that each have a different schema), but at this
  // level, we do not care.
  const catalog::Schema &schema_;
};

}  // namespace codegen
}  // namespace peloton


text:
Sequel.migration do
  up do
    run "create index series_register_id_doy_idx on series(register_id, date_part('doy', time))"
  end

  down do
    alter_table(:series) do
      drop_index name: 'series_register_id_doy_idx'
    end
  end
end


text:
var _ = require('lodash');

// Project imports
var utils = require('./utils');

function onLoad() {
    // Do something
}

window.onload = onLoad;


text:
package util.upload.enntity.imp;

import java.io.File;
import java.io.IOException;

import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import util.image.ImageUtil;
import util.upload.ContentTypeUtil;
import util.upload.UploadUtil;
import util.upload.enntity.UploadEntity;

/**
  基于spring mvc 的文件上传实体类

  内部包含MultipartFile

  示例:

   @RequestMapping(value = "/testUpload.html", method = RequestMethod.POST)
   public ModelAndView testUploadAction(
  		@RequestParam(value = "photo", required = false) MultipartFile file,
  		ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    if( !UploadUtil.isNull(file) ) {
  		UploadEntity uploadEntity = new UploadEntityImp(file);

  		try {
  			System.out.println(uploadEntity.savePhoto(true));
  			System.out.println(uploadEntity.getSmallPhoto(160, 160));
  		} catch (Exception e) {
  			e.printStackTrace();
  			printLog(e);
  		}
    }
  	return createModelAndView("WeCharTest/testUpload", modelMap);
   }

  数组方式:
  1. @RequestParam(value = "files", required = false) List<MultipartFile> files,
  2. @RequestParam(value = "photos", required = false) MultipartFile[] files,
  3. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 	  List<MultipartFile> files = multipartRequest.getFiles("files");

  @RequestMapping(value = "/testUpload.html", method = RequestMethod.POST)
  public ModelAndView testUploadAction(
  		@RequestParam(value = "photos", required = false) MultipartFile[] files,
  		ModelMap modelMap,
  		HttpServletRequest request, HttpServletResponse response) {

  	try {
  		UploadEntity uploadEntity = null;
 		for (MultipartFile file : files) {
  			if (!UploadUtil.isNull(file)) {
  				uploadEntity = new UploadEntityImp(file);
  				System.out.println(uploadEntity.savePhoto(true));
  				System.out.println(uploadEntity.getSmallPhoto(160, 160));
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}

  	return createModelAndView("WeCharTest/testUpload", modelMap);
  }

   	删除图片:
   	1. UploadUtil.deleteFile( str );
   	2. 兼容旧版:
		if( !UploadUtil.deleteFile( str ) ) {
			UploadUtil.deleteWebFile(request, str);
		}

 *
 * @author ziry 2016-11-01 10:05
 */
public class UploadEntityImp extends UploadEntity{

	private MultipartFile file;

	public UploadEntityImp(MultipartFile file) {

		this.file = file;

		if (file == null) {
			throw new NullPointerException("MultipartFil 不能为空!");
		}

		fileSizeByKB = file.getSize() / 1024;

		// 获取该文件的文件名
		originalFilename = file.getOriginalFilename();

		// 获取文件后缀
		fileSuffix = UploadUtil.getFileSuffix(originalFilename);
		if (fileSuffix == null || fileSuffix.length() == 0) {
			// 通过Mime类型获取文件类型
			fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType());
		}

		// 创建文件名
		filename = UploadUtil.getFileName();
	}

	/**
	 * 带文件大小限制的构造
	 *
	 * @param file
	 *            MultipartFile
	 * @param maxSize2KB
	 *            限制文件大小
	 * @throws IOException
	 */
	public UploadEntityImp(MultipartFile file, long maxSizeByKB) throws MaxUploadSizeExceededException {

		this.file = file;

		if (file == null) {
			throw new NullPointerException("MultipartFil 不能为空!");
		}

		fileSizeByKB = file.getSize() / 1024;

		if (fileSizeByKB > maxSizeByKB) {
			throw new MaxUploadSizeExceededException(maxSizeByKB * 1024);
		}

		// 获取该文件的文件名
		originalFilename = file.getOriginalFilename();

		// 获取文件后缀
		fileSuffix = UploadUtil.getFileSuffix(originalFilename);
		if (fileSuffix == null || fileSuffix.length() == 0) {
			// 通过Mime类型获取文件类型
			fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType());
		}

		// 创建文件名
		filename = UploadUtil.getFileName();

	}

	/**
	 * 上传文件
	 *
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	protected void save() throws IllegalStateException, IOException {

		// 实际文件路径
		filePath = path + filename + "." + fileSuffix;

		File targetFile = new File(filePath);

		// 保存
		file.transferTo(targetFile);

		isUpload = true;

	}

	/**
	 * 上传图片文件
	 *
	 * @param isCompress
	 *            是否压缩
	 * @return 可供web访问的路径(/xxx/xxx.jpg)
	 * @throws Exception
	 */
	public String savePhoto(boolean isCompress) throws Exception {

		if( UploadUtil.isPhoto(file) == false ) {
			throw new ClassFormatError("非图片格式("+UploadUtil.PhotoSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getPhotoPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getPhotoURL() + filename + "." + fileSuffix;

		// 判断图片是否压缩
		if (isCompress && !fileSuffix.toLowerCase().equals("gif") && !fileSuffix.toLowerCase().equals("png")) {
			try {
				ImageUtil.scaleCompress(filePath, filePath, comBase, 1d);
			}catch (Exception e) {
				logger.error("压缩图片失败!filePath="+filePath);
				logger.error(e);
			}
		}

		return webURL;
	}

	/**
	 * 上传图片文件
	 *
	 * @param isCompress
	 *            是否压缩
	 * @param cropMiddle
	 *            是否取正方型
	 * @return 可供web访问的路径(/xxx/xxx.jpg)
	 * @throws Exception
	 */
	public String savePhoto(boolean isCompress, boolean cropMiddle) throws Exception {

		if( UploadUtil.isPhoto(file) == false ) {
			throw new ClassFormatError("非图片格式("+UploadUtil.PhotoSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getPhotoPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getPhotoURL() + filename + "." + fileSuffix;

		// 判断图片是否压缩
		if (isCompress) {

			try {
				ImageUtil.scaleCompress(filePath, filePath, comBase, 1d);
			}catch (Exception e) {
				logger.error("压缩图片失败!filePath="+filePath);
				logger.error(e);
			}

		}

		// 判断图片是否取正方型
		if (cropMiddle) {
			try {
				ImageUtil.cropMiddle(filePath, filePath);
			}catch (Exception e) {
				logger.error("图片取正方型失败!filePath="+filePath);
				logger.error(e);
			}
		}

		return webURL;
	}

	/**
	 * 上传图片文件
	 *
	 * @param isCompress
	 *            是否压缩
	 * @param cropMiddle
	 *            是否取正方型
	 * @param width
	 *            压缩宽度
	 * @param height
	 *            压缩高度
	 * @return 可供web访问的路径(/xxx/xxx.jpg)
	 * @throws Exception
	 */
	public String savePhoto(boolean isCompress, boolean cropMiddle, int width, int height) throws Exception {

		if( UploadUtil.isPhoto(file) == false ) {
			throw new ClassFormatError("非图片格式("+UploadUtil.PhotoSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getPhotoPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getPhotoURL() + filename + "." + fileSuffix;

		// 判断图片是否压缩
		if (isCompress) {
			try {
				ImageUtil.scaleCompress(filePath, filePath, comBase, 1d);
			}catch (Exception e) {
				logger.error("压缩图片失败!filePath="+filePath);
				logger.error(e);
			}
		}

		// 判断图片是否取正方型
		if (cropMiddle) {
			try {
				ImageUtil.cropMiddle(filePath, filePath);
			}catch (Exception e) {
				logger.error("图片取正方型失败!filePath="+filePath);
				logger.error(e);
			}
		}

		// 按比例压缩
		try {
			ImageUtil.doCompress(filePath, width, height);
		}catch (Exception e) {
			logger.error("按比例压缩失败!filePath="+filePath);
			logger.error(e);
		}

		return webURL;
	}

	/**
	 * 上传图片文件
	 *
	 * @param isCompress
	 *            是否压缩
	 * @param cropMiddle
	 *            是否取正方型
	 * @param x
	 *            截取起始坐标X点
	 * @param y
	 *            截取起始坐标X点
	 * @param width
	 *            压缩宽度
	 * @param height
	 *            压缩高度
	 * @return 可供web访问的路径(/xxx/xxx.jpg)
	 *
	 * @throws Exception
	 */
	@Override
	public String savePhoto(boolean isCompress, int x, int y, int width, int height) throws Exception {
		if( UploadUtil.isPhoto(file) == false ) {
			throw new ClassFormatError("非图片格式("+UploadUtil.PhotoSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getPhotoPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getPhotoURL() + filename + "." + fileSuffix;

		// 判断图片是否压缩
		if (isCompress) {
			try {
				ImageUtil.scaleCompress(filePath, filePath, comBase, 1d);
			}catch (Exception e) {
				logger.error("压缩图片失败!filePath="+filePath);
				logger.error(e);
			}
		}

		// 按比例截取
		try {
			ImageUtil.crop(filePath, x, y, x+width, y+height);
		}catch (Exception e) {
			logger.error("按比例压缩失败!filePath="+filePath);
			logger.error(e);
		}

		return webURL;
	}

	/**
	 * 上传视频文件
	 *
	 * @return 可供web访问的路径(/xxx/xxx.mp4)
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public String saveVideo() throws IllegalStateException, IOException {

		if( UploadUtil.isVideo(file) == false ) {
			throw new ClassFormatError("非视频格式("+UploadUtil.VideoSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getVideoPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getVideoURL() + filename + "." + fileSuffix;

		return webURL;
	}

	/**
	 * 上传音频文件
	 *
	 * @return 可供web访问的路径(/xxx/xxx.mp3)
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public String saveAudio() throws IllegalStateException, IOException {

		if( UploadUtil.isAudio(file) == false ) {
			throw new ClassFormatError("非音频格式("+UploadUtil.AudioSuffix+")");
		}

		// 创建你要保存的文件的路径
		path = UploadUtil.getAudioPath(true);

		save();

		// 可供web访问的路径
		webURL = UploadUtil.getAudioURL() + filename + "." + fileSuffix;

		return webURL;
	}

}


text:
module SData
  module ControllerMixin
    module SDataInstance

    protected

      def sdata_instance
        if params[:condition] == "$linked"
          linked_sdata_instance
        elsif params.key?(:predicate)
          sdata_instance_by_predicate
        else
          non_linked_sdata_instance
        end
      end

      def sdata_instance_by_predicate
        predicate = SData::Predicate.parse(sdata_resource.payload_map.baze_fields, params[:predicate])
        scope = sdata_resource.all(:conditions => predicate.to_conditions)
        if scope.count != 1
          raise Sage::BusinessLogic::Exception::IncompatibleDataException, "Conditions scope must contain exactly one entry"
        end
        scope.first
      end

      def linked_sdata_instance
        SData::SdUuid.find_by_virtual_model_owner_and_uuid(sdata_resource, target_user, Predicate.strip_quotes(params[:instance_id]))
      end

      def non_linked_sdata_instance
        sdata_resource.find_by_sdata_instance_id(Predicate.strip_quotes(params[:instance_id]))
      end
    end
  end
end


text:
make-image-map
==============

Command-line scripts for chopping up images into map tiles.

by Geoffrey Roberts

What the script does
====================

This script takes a large image and chops it up into tiles that can be used within a map library such as [Leaflet][leaflet]. Along the way, it will scale the image up so that its widest axis is rounded up to the next highest power of 2. This allows scalable tiles to be generated consistently.

Any transparent areas of the image will be converted to white. All output tiles are in JPEG format.

[leaflet]: http://leafletjs.com

Requires
========

 * [ImageMagick][im]
 * [GDAL][gdal]

[im]: http://www.imagemagick.org/script/index.php
[gdal]: http://www.gdal.org/

Usage
=====

```
chmod u+x make-image-map.sh
./make-image-map.sh (name of input image) (name of output folder)
```

TODO
====

 * Render in other formats
 * Modified transparency handling
 * Cropping
 * Anything else? Feel free to make some suggestions.


text:
var util = require('util');
var utils = require('../utils');
var PluginBase = require('../plugin-base');
var debug = require('debug')('loopback:boot:datasource');

module.exports = function(options) {
  return new DataSource(options);
};

function DataSource(options) {
  PluginBase.call(this, options, 'dataSources', 'datasources');
}

util.inherits(DataSource, PluginBase);

DataSource.prototype.getRootDir = function() {
  return this.options.dsRootDir;
};

DataSource.prototype.start = function(context) {
  var app = context.app;
  var self = this;
  var lazyConnect = process.env.LB_LAZYCONNECT_DATASOURCES;
  utils.forEachKeyedObject(context.instructions[this.name], function(key, obj) {
    obj = self.getUpdatedConfigObject(context, obj, { useEnvVars: true });
    debug('Registering data source %s %j', key, obj);
    if (lazyConnect) {
      obj.lazyConnect =
        lazyConnect === 'false' || lazyConnect === '0' ? false : true;
    }
    app.dataSource(key, obj);
  });
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<title>Visualization Related Resources</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <link rel="stylesheet" href="../keshif.css"/ type="text/css">
        <link rel="stylesheet" href="../font-awesome/css/font-awesome.min.css">

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

            Data from VisualizinData.com resources.

            All rights for the technique images belong to their respective owners.


text:
using System;

namespace CurioExchangeService.Entities
{
    public class AspNetUser
    {
        public string Id { get; set; }

        public string Email { get; set; }

        public bool EmailConfirmed { get; set; }

        public string PasswordHash { get; set; }

        public string SecurityStamp { get; set; }

        public string  PhoneNumber { get; set; }

        public bool PhoneNumberConfirmed { get; set; }

        public bool TwoFactorEnabled { get; set; }

        public Nullable<DateTime> LockoutEndDateUtc { get; set; }

        public bool LockoutEnabled { get; set; }

        public int AccessFailedCount { get; set; }

        public string UserName { get; set; }
    }
}


text:
Backbone.Wreqr = (function(Backbone, Marionette, _){
  "option strict";
  var Wreqr = {};

  // Handlers
  // --------
  // A registry of functions to call, given a name

  Wreqr.Handlers = (function(Backbone, _){
    "option strict";

    // Constructor
    // -----------

    var Handlers = function(){
      "use strict";
      this._handlers = {};
    };

    Handlers.extend = Backbone.Model.extend;

    // Instance Members
    // ----------------

    _.extend(Handlers.prototype, {

      // Add a handler for the given name, with an
      // optional context to run the handler within
      addHandler: function(name, handler, context){
        var config = {
          callback: handler,
          context: context
        };

        this._handlers[name] = config;
      },

      // Get the currently registered handler for
      // the specified name. Throws an exception if
      // no handler is found.
      getHandler: function(name){
        var config = this._handlers[name];

        if (!config){
          throw new Error("Handler not found for '" + name + "'");
        }

        return function(){
          var args = Array.prototype.slice.apply(arguments);
          return config.callback.apply(config.context, args);
        };
      },

      // Remove a handler for the specified name
      removeHandler: function(name){
        delete this._handlers[name];
      },

      // Remove all handlers from this registry
      removeAllHandlers: function(){
        this._handlers = {};
      }
    });

    return Handlers;
  })(Backbone, _);

  // Wreqr.Commands
  // --------------
  //
  // A simple command pattern implementation. Register a command
  // handler and execute it.
  Wreqr.Commands = (function(Wreqr){
    "option strict";

    return Wreqr.Handlers.extend({
      execute: function(){
        var name = arguments[0];
        var args = Array.prototype.slice.call(arguments, 1);

        this.getHandler(name).apply(this, args);
      }
    });

  })(Wreqr);

  // Wreqr.RequestResponse
  // ---------------------
  //
  // A simple request/response implementation. Register a
  // request handler, and return a response from it
  Wreqr.RequestResponse = (function(Wreqr){
    "option strict";

    return Wreqr.Handlers.extend({
      request: function(){
        var name = arguments[0];
        var args = Array.prototype.slice.call(arguments, 1);

        return this.getHandler(name).apply(this, args);
      }
    });

  })(Wreqr);

  // Event Aggregator
  // ----------------
  // A pub-sub object that can be used to decouple various parts
  // of an application through event-driven architecture.

  Wreqr.EventAggregator = (function(Backbone, _){
    "option strict";
    var EA = function(){};

    // Copy the `extend` function used by Backbone's classes
    EA.extend = Backbone.Model.extend;

    // Copy the basic Backbone.Events on to the event aggregator
    _.extend(EA.prototype, Backbone.Events);

    return EA;
  })(Backbone, _);

  return Wreqr;
})(Backbone, Backbone.Marionette, _);


text:
/*
 * Document.cpp
 *
 *  Created on: Feb 14, 2015
 *      Author: pfurtado
 */

#include "Document.h"

#include <cmath>

Document::Document() {
	TF = 0;
	magnitude = 0;
	dotProduct = 0;
}

const std::string& Document::getId() const {
	return id;
}

void Document::setId(const std::string& id) {
	this->id = id;
}

const std::string& Document::getName() const {
	return name;
}

void Document::setName(const std::string& name) {
	this->name = name;
}

int Document::getTF() const {
	return TF;
}

void Document::setTF(int tf) {
	TF = tf;
}

double Document::getMagnitude() const {
	return magnitude;
}

void Document::setMagnitude(double magnitude) {
	this->magnitude = magnitude;
}

double Document::getDotProduct() const {
	return dotProduct;
}

void Document::setDotProduct(double dotProduct) {
	this->dotProduct = dotProduct;
}

double Document::calculateTF(void) const {
	if (this->TF == 0)
        return 0;

    return 1 + log(this->TF);
}

void Document::increaseTF() const {
	this->TF++;
}

Document::~Document() {

}