text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"

/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void TimingDelay_Decrement(void);

#endif /* __MAIN_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

redpajama_set_name: RedPajamaGithub


text:
 MusicSurf

Surajnath Sidh

U101114FCS146

NIIT University

## Idea
### Why MusicSurf ?

MusicSurf is built to solve the problem of searching in your music collection, not just by title, not just by Artist name because those things can be done using Existing Music players, It does way more then that

It let's you do a full text search on attributes(ID3 Tags) for your music collection, in natural language.
It is able to find your music if you only remember that single phrase from lyrics or if you want to listen songs that are "single" or maybe you want to listen all the "Radio edit" or maybe you remember that song you are looking for had 'Draft Punk' as Feat. Artist, It can find that too.
After that you got your song, it let's you export search results as a playlist so you can play all those songs in your favorite music player

## Features

- Natural Language Querying
- Filters
- Export search results as playlist

## Design and Architecture
MusicSurf is built using Flask and Elasticsearch, They both were chosen for very specific reasons.

#### MusicSurf Architecture
![MusicSurf Architecture Diagram](http://i.imgur.com/XIkWNUY.png)

#### Flask
Written in Python, Highly Modular, Let's you Build APIs with minimum effort, Can be integrated with any other python modules without any hassle

#### Elasticsearch
Provides Full text search and have a nice API to index and query data, it is distributed, Highly scalable and best about it is that it is Open Source (Apache 2.0)

##### Elasticsearch features that we used in our Project

- RESTful API hence easy to integrate with any web service in our case being the Flask
- Query Boosting to implement  filters
- Built in Analyzer here analyser is component that does
    - First, tokenizing a block of text into individual terms suitable for use in an inverted index,
    - Then normalizing these terms into a standard form to improve their "searchability," or recall
- Built in Scoring Function to evaluate and see behavior of system
- Full Text search(This is possible by using inverted index as indexing mechanism)

## Contribution

## During Architecture (Early Stage)

During out first meeting we had few ideas in our mind first one being the **Building Search server on our own**
that takes care of indexing and querying (as it can be seen in architecture Diagram)
And plug it with Flask to build the Web Frontend

During the later stage we realized that build and evaluating a search server will a lot of work which can not
accomplished by us in time span we have in our hands, the we started looking for OpenSource projects that can help
us out in this task, at the end we settled with Elasticsearch.
Using an off-the-self Production grade system means we have time to understand a real system that is used in real products, rather then reinventing the wheel and building our own toy system

It also gives us the time and opportunity to understand a production grade system

## Design and implementation process

My Primary contribution was extracting and providing the document object for music collection.
I Wrote the id3 module that takes the root folder and crawls the folder recursively, building an JSON list of
document objects which then used to index the music.

My document list is indexed by using elasticsearch module written by my team member Rajdeep.

After Indexing is done our system is ready for querying, Which is done using the Web Interface Built by Raghav,
Web Interface and Query engine is built using Flask and UI it Built using Google MDL(Material Design Library )

We choose Python as our Programming language to build the system because it is Higher level, Team is familiar with
language and availability of Libraries.

### ID3 Module
ID3 module utilities the mutagen library to get ID3 data from music files, along with glob to recursively crawl the music directory and JSON library to build the final document list for indexing purposes

ID3 have multiple tags that stores metadata, we used only few of them for our indexing need
These are the official ID3 tags used to build this document object

**ID3 standard tags Mapping to document object**
```
- title --> [TIT2]
- artist --> [TPE1] + [TPE2] + [TSOP]
- album --> [TALB]
- year --> [TDRC]
- lyrics --> [USLT::eng]
- path --> [file-path]
```

**Document object for a music file**
```
{
    "title": "A Head Full Of Dreams",
    "artist": "Coldplay Coldplay Coldplay",
    "album": "A Head Full Of Dreams",
    "year": "2015",
    "lyrics": "",
    "path": "C:\\Users\\Electron\\Music\\test_music\\Coldplay\\A Head Full Of Dreams\\Coldplay - A Head Full Of Dreams.mp3"
}
```
*This music files does not have lyrics in it hence the lyrics block is empty*

ID3 Module is responsible for building a JSON list of these document objects for all the music files.

### Elasticsearch internals and configurations

#### Indexing
Elasticsearch indexes documents in the form of inverted index, which is designed to allow very fast full-text searches.
[More on Inverted index & how Elasticsearch index documents](https://www.elastic.co/guide/en/elasticsearch/guide/current/inverted-index.html)

#### Analysis process
When we index a document, its full-text fields are analyzed into terms that are used to create the inverted index.
However, when we search on a full-text field, we need to pass the query string through the same analysis process,
to ensure that we are searching for terms in the same form as those that exist in the index.

Analysis process is responsible for tokenizing a block of text into individual terms suitable for use in an inverted index,
Then normalizing these terms into a standard form to improve their "searchability," or recall.

We configured Elasticsearch to use `Standard analyzer`, It splits the text on word boundaries, as defined by the Unicode Consortium, and removes most punctuation

**Before analysis**
`"Set the shape to semi-transparent by calling set_trans(5)"`
**After Analysis**
`set, the, shape, to, semi, transparent, by, calling, set_trans, 5`

#### Querying

When Elasticsearch gets an query it goes thorough same analysis process as documents went during indexing process,
to ensure that we are searching for terms in the same form as those that exist in the index.

## Contribution Graph

Contributions can be verified [on GitHub](https://github.com/electron0zero/MusicSurf/commits?author=electron0zero)
and can be seen in [Contribution graph](https://github.com/electron0zero/MusicSurf/graphs/contributors)

GitHub Repository of project is located at [https://github.com/electron0zero/MusicSurf](https://github.com/electron0zero/MusicSurf)

**My Contribution**

![My contri](http://i.imgur.com/OxbvzYp.png)

**Project Progress**

![Project Progress](http://i.imgur.com/eSPfIg6.png)


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\ProfessionalServices;

use Piwik\ProfessionalServices\Advertising;

class Promo
{
    protected $linkTitles = array('Read more', 'Learn more');

    protected $content = array();

    public function __construct()
    {
        $this->content = array(
            // A/B Testing
            array(
                'campaignContent' => 'abTesting',
                'url' => 'https://piwik.org/recommends/ab-testing-learn-more',
                'text' => 'Ever wondered what A/B testing is and why it is so important? Check out how you can increase conversions and sales on your website and app.'
            ),
            array(
                'campaignContent' => 'abTesting',
                'url' => ' https://piwik.org/recommends/ab-testing-website',
                'text' => 'Increase revenue and conversions by comparing different versions of your websites or apps, ad detect the winning variation that will grow your business!'
            ),

            // Media Analytics
            array(
                'campaignContent' => 'mediaAnalytics',
                'url' => 'https://piwik.org/recommends/media-analytics-website',
                'text' => 'Ever wondered how people interact and engage with videos or audios on your website? Well now you can, and it integrates perfectly into your Piwik.',
            ),

            array(
                'campaignContent' => 'mediaAnalytics',
                'url' => 'https://piwik.org/recommends/media-analytics',
                'text' => 'Get powerful insights into how your audience watches your videos and listens to your audio. Media Analytics is now available on the Marketplace.',
            ),

            // Funnels
            array(
                'campaignContent' => 'funnels',
                'url' => 'https://piwik.org/recommends/conversion-funnels',
                'text' => 'Increase your conversions, sales and revenue by understanding your conversion funnels and where your visitors drop off with Funnels for Piwik.'
            ),

            // Piwik training
            array(
                'campaignContent' => 'userTraining',
                'url' => 'https://piwik.org/training/?pk_campaign=' . Advertising::CAMPAIGN_NAME_PROFESSIONAL_SERVICES . '&pk_source=Piwik_App',
                'text' => 'Want to know how to use all the exciting features in Piwik? Try a User training to be up to speed with working with Piwik.'
            ),

            // Piwik PRO
            // https://piwik.org/recommends/piwik-pro-from-app
            array(
                'campaignContent' => 'discoverPower',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Discover the power of open-source combined with enterprise-grade support and premium functionalities.'
            ),
            array(
                'campaignContent' => 'bringEnterpriseLevel',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Bring your analytics to enterprise level. Upgrade your Piwik platform and receive access to numerous premium features and assistance from experts.'
            ),
            array(
                'campaignContent' => 'monitoringAndIncident',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Do you need 24/7 Monitoring and Incident Handling for your Piwik? Get Premium features and enterprise-grade support.'
            ),
            array(
                'campaignContent' => 'slowingDown',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Is your Piwik slowing down? Piwik experts can help with your server setup!'
            ),
            array(
                'campaignContent' => 'whiteLabel',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Did you know you can adjust the look and feel of Piwik to your brand, and even replace "Piwik" with your product name? Try the White Label product!',
            ),
            array(
                'campaignContent' => 'metaSites',
                'url' => 'https://piwik.org/recommends/piwik-pro-from-app',
                'text' => 'Did you know you can aggregate the collected data across hundreds of sites and display it in a single dashboard? Get Premium features and enterprise-grade support.',
            )
        );
    }

    public function getLinkTitle()
    {
        $titles = $this->linkTitles;
        shuffle($titles);

        return array_shift($titles);
    }

    public function getContent()
    {
        $content = $this->content;
        shuffle($content);

        return array_shift($content);
    }
}


text:
import unittest

from biicode.common.model.symbolic.block_version import BlockVersion
from biicode.common.model.brl.brl_block import BRLBlock
from biicode.common.model.cells import Cell
from biicode.common.model.resource import Resource
from biicode.common.deps.closure import Closure, ClosureItem
from biicode.common.output_stream import OutputStream

class ClosureTest(unittest.TestCase):

    def test_add_item(self):
        c1 = Closure()
        r1 = Cell('user/block/name1')
        version = BlockVersion(BRLBlock('owner/user/block/branch'), 13)
        biiout = OutputStream()
        resource = Resource(r1, None)
        c1.add_item(resource, version, biiout)
        r2 = Cell('user/block/name1')
        r2.hasMain = True
        resource2 = Resource(r2, None)
        version2 = BlockVersion(BRLBlock('owner/user/block/branch'), 14)
        c1.add_item(resource2, version2, biiout)

        self.assertEqual(ClosureItem(resource, version), c1['user/block/name1'])
        self.assertIn('Incompatible dependency', str(biiout))

if __name__ == "__main__":
    # import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
package io.fastjson.bnsf.holders.array;

import io.fastjson.bnsf.WireValueType;
import io.fastjson.bnsf.holders.WireValueHolder;

/**
 * Created by Richard on 9/25/14.
 */
public class UintArrayHolder implements WireValueHolder {

    private char [] value;

    @Override
    public WireValueType type() {
        return WireValueType.INT_ARRAY;
    }

    public char[] getValue() {
        return value;
    }

    public void setValue(char[] value) {
        this.value = value;
    }
}


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

class Selected extends CI_Controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->model('selected_model');
	}

	public function index()
	{
		$data = $this->selected_model->get_post();
		$data['is_adminlogged_in'] = $this->session->userdata('is_adminlogged_in');
		$data['is_logged_in'] = $this->session->userdata('is_logged_in');
		$data['landing'] = 'landing';
		$data['page_title'] = '';

		$data['main_content'] = 'article/selected';

		$this->load->view('includes/template', $data);
	}
}

/* End of file selected.php */
/* Location: ./application/controllers/selected.php */


text:
!!! missing "Obsolete"
    `.bce` command is removed in newer versions.  If you're on version 2.39.0 or later, use [config guide][CONFIG GUIDE]

`.bce` allows you to conveniently set many of the bot-wide settings that Nadeko has, such as what the currency looks like, what people get when they use `.help`, and so on.
Below is a list of all the settings that can be set, with a quick instruction on how to use them, and their default value.

## BetflipMultiplier

The reward multiplier for correctly guessing a `.bf` (betflip) bet. Keep in mind you can't change the chance to guess the correct flip. It's always 50%.
**Default is 1.95 (in other words, if you bet 100 and guess, you will get 195 as a reward)**

## Betroll100Multiplier

The reward multiplier for rolling 100 on `.br`.
**Default is 10.0**

## Betroll67Multiplier

The reward multiplier for rolling 67 or higher on `.br`.
**Default is 2.0**

## Betroll91Multiplier

The reward multiplier for rolling 91 or higher on `.br`.
**Default is 4.0**

## GroupGreets

Toggles whether your bot will group greet/bye messages into a single message every 5 seconds.
1st user who joins will get greeted immediately
If more users join within the next 5 seconds, they will be greeted in groups of 5. This will cause %user.mention% and other placeholders to be replaced with multiple users. Keep in mind this might break some of your embeds - for example if you have %user.avatar% in the thumbnail, it will become invalid, as it will resolve to a list of avatars of grouped users.

## CurrencyGenerationPassword

Either `true` or `false` value on whether the currency spawned with `.gc` command will have a random password associated with it in the top left corner. This helps prevent people who lurk in the chat and just spam `.pick` to gain flowers.
**Default is `false`**

## CurrencyGenerationChance

A number between 0.0 and 1.0 which represents the chance that a message sent to a channel where `.gc` is enabled will spawn currency. 0 is 0% and 1.0 is 100%.
**Default is 0.02. (That's 2% chance)**

## CurrencyGenerationCooldown

A number of seconds that the bot is guaranteed not to spawn any flowers again after doing so in a channel where `.gc` is enabled. This is useful if you have a pretty high chance of the flowers spawning in the channel (for whatever stupid reason) and don't want the chat to be flooded with currency spawn messages.
**Default is 10**

## CurrencyName

Name of your currency. Mostly people aren't creative with this and just call them "Credit" or "Dollar". You can do better :^)
**Default is NadekoFlower**

## CurrencySign

Emoji of your currency. You can use server emojis, though occasionally it will fail to send it correctly on other servers.
**Default is 🌸**

## DmHelpString

The string which will be sent whenever someone DMs the bot. Supports embeds. How it looks: [https://puu.sh/B0BLV.png](https://puu.sh/B0BLV.png)
**Default is "Use `.h` for help"**

## HelpString

The strings which will be sent whenever someone types `.h`. Supports embeds. You can also use {0} placeholder which will be replaced with your bot's client id, and {1} placeholder which will be replaced with your bot's prefix. How it looks: [https://puu.sh/B0BMa.png](https://puu.sh/B0BMa.png)
**Default is too long to type out (check the screenshot)**

## CurrencyDropAmount

The amount of currency which will drop when `.gc` spawn is triggered. This will be the minimum amount of currency to be spawned if CurrencyDropAmountMax is also specified.
**Default is 1**

## CurrencyDropAmountMax

Setting this value will make currency generation spawn a random amount of currency between CurrencyDropAmount and CurrencyDropAmountMax, inclusive.
**Default is 0**

## TriviaCurrencyReward

The amount of currency awarded to the winner of the trivia game.
**Default is 0**

## XpPerMessage

The amount of XP the user receives when they send a message (which is not too short).
**Default is 3**

## XpMinutesTimeout

This value represents how often the user can receive XP from sending messages.
**Default is 5**

## MinWaifuPrice

Minimum price the users can pay to claim a waifu with `.claim`.
**Default is 50**

## WaifuGiftMultiplier

The multiplier applied to the price of waifu gifts, making them more or less expensive.
**Default is 1**

## MinimumTriviaWinReq

Users can't start trivia games which have smaller win requirement than specified by this setting.
**Default is 0**

## MinBet

Minimum amount of currency a user can gamble with in a single gamble. Set 0 to disable.
**Default is 0**

## MaxBet

Maximum amount of currency a user can gamble with in a single gamble. Set 0 to disable.
**Default is 0**

## OkColor

Hex of the color which will show on the left side of the bot's response when a command succesfully executes. Example: [https://puu.sh/B0BXd.png](https://puu.sh/B0BXd.png)
**Default is 00e584**

## ErrorColor

Hex of the color which will show on the left side of the bot's response when a command either errors, or you can't perform some action. Example: [https://puu.sh/B0BXs.png](https://puu.sh/B0BXs.png)
**Default is ee281f**

## ConsoleOutputType

2 values, either 'Simple' or 'Normal'. Normal is the usual amount, and the simple one shows only basic info about the executed commands in the console. Here is a comparison: [https://puu.sh/B0Chn.png](https://puu.sh/B0Chn.png)
**Default is 'Normal'**

## DailyCurrencyDecay

The percentage of currency all users will lose every 24 hours. The value goes between 0 and 1.0 (0 being 0% to 1.0 being 100%). This is a useful tool to control the inflation :)
**Default is 0**

## CheckForUpdates

Whether the bot will see if there are updates available. The patch notes will be sent to Bot Owner's DM. The bot checks for updates once every 8 hours. There are 3 available values:

- None: The bot will not check for updates
- Commit: This is useful for linux self-hosters - the bot will check for any new commit on the NadekoBot repository.
- Release: This is useful for windows self-hosters - the bot will check for any new releases published on the NadekoBot repository. This setting is also useful for linux self-hosters who only want to update when it's pretty safe to do so :)
**Default is Release**

## PatreonCurrencyPerCent

You need this only if you have a patreon page, and you've specified the PatreonCampaignId and PatreonAccessToken in credentials.json. This value is the amount of currency the users will get with `.clparew` for each cent they've pledged. Also make sure your patreon is set to charge upfront, otherwise people will be able to pledge, claim reward and unpledge without getting charged.
**Default is 1**

## VoiceXpPerMinute

The average amount of xp added every minute to a user connected to a voice channel.
**Default is 3**

## MaxXpMinutes

The maximum amount of time, in minutes, a user can earn xp in a voice channel. This exists mainly to clear entries out of Redis.
**Default is 720**

[CONFIG GUIDE]: config-guide.md


text:
cask 'screensteps' do
  version '4.0.9'
  sha256 'aeebc28a6e29914f99679a3198cb3a1701a98df909ede0ba49205407b3b85e23'

  # bluemangolearning.com was verified as official when first introduced to the cask
  url "https://www.bluemangolearning.com/download/screensteps/#{version.major_minor.dots_to_underscores}/release/ScreenSteps.dmg"
  name 'ScreenSteps'
  homepage 'http://www.screensteps.com/'

  app 'ScreenSteps.app'
end


text:
package com.sunnyface.popularmovies.data;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by Kiko Seijo on 17/01/2017.
 * by The Sunnyface.com.
 */

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    private int previousTotal = 0; // The total number of items in the dataset after the last load
    private boolean loading = true; // True if we are still waiting for the last set of data to load.

    private int current_page = 1;

    private final LinearLayoutManager mLinearLayoutManager;

    protected EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        int visibleItemCount = recyclerView.getChildCount();
        int totalItemCount = mLinearLayoutManager.getItemCount();
        int firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        int visibleThreshold = 5;
        if (!loading && (totalItemCount - visibleItemCount)
                <= (firstVisibleItem + visibleThreshold)) {
            // End has been reached

            // Do something
            current_page++;

            onLoadMore(current_page);

            loading = true;
        }
    }

    public abstract void onLoadMore(int current_page);
}


text:
@interface FTWebViewController : UIViewController

@property (nonatomic,strong) UIWebView *webView;

@end


text:
<?php

// GENERAL SETTINGS
define('PF_SITE_NAME', '%%PHING_PROTEAN_LONGNAME%%');
define('PF_DATABASE_NAME', '%%PHING_PROTEAN_DATABASE_NAME%%');

define('PF_SCRIPT_TIMEOUT', 30);
define('PF_TIMEZONE', 'America/Los_Angeles');

// BUILD SETTINGS
define('PF_VERSION','4.1');
define('PF_ENVIRONMENT', 'development');

// FILE PATHS AND URL SETTINGS
define('PF_URL', '%%PHING_PROTEAN_URL%%');
define('PF_URL_SECURE', '%%PHING_PROTEAN_SECUREURL%%');
define('PF_SHORT_URLS', true);

define('PF_USE_LOCAL_PEAR', false);
define('PF_PEAR_BASE', '/usr/local/php5/lib/php');

define('PF_TEMP_PATH', '%%PHING_PROTEAN_BASEDIR%%/tmp');

define('PF_DEFAULT_URI', '/content/default');

// DEBUG SETTINGS
define('PF_PROFILER', true);
define('PF_PROFILER_RUNS_PATH', '%%PHING_PROTEAN_BASEDIR%%/tmp/profiler');

define('PF_DEBUG_EMAIL', false);
define('PF_DEBUG_EMAIL_ADDRESS', '%%PHING_PROTEAN_DEBUG_EMAIL%%');

define('PF_DEBUG_VERBOSE', true);
define('PF_DEBUG_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_error.log');

define('PF_QUERY_DEBUG', true);
define('PF_QUERY_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_query.log');

define('PF_AJAX_DEBUG', false);
define('PF_AJAX_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_ajax.log');

define('PF_APP_ROUTER_DEBUG', false);
define('PF_APP_CONTROLLER_DEBUG', false);
define('PF_ERROR_WORDWRAP_COUNT', 0);

define('PF_TEMPLATE_DEBUG', false);
define('PF_MULTI_LANGUAGE_DEBUG', false);

// TEMPLATE/FORM SETTINGS
define('PF_TEMPLATE_FORCE_RECOMPILE', false);
define('PF_FORM_FIELD_ERROR_HIGHLIGHTING', true);

// SESSION SETTINGS
define('PF_SESSION_NAME', 'id');
define('PF_SESSION_PERSIST_NAME', 'persist');
define('PF_SESSION_STORE', 'file');
define('PF_SESSION_PATH', PF_TEMP_PATH);
define('PF_SESSION_EXPIRE', 31536000);
define('PF_SESSION_AUTH_EXPIRE', 31536000);
define('PF_SESSION_UNIQUE_KEY', 'as33#)(J**a3SS:DJLSDFU}*&W');
define('PF_SESSION_PASSWORD_HASH_COST', 8);

// CACHE SETTINGS
define('PF_CACHE_ENABLED', true);
define('PF_CACHE_USER_TTL', 3600);
define('PF_CACHE_CONTROLLER_MAP', false);
define('PF_CACHE_TEMPLATES', false);

define('PF_CACHE_MEMCACHE_SERVER_HOST_1', false);
define('PF_CACHE_MEMCACHE_SERVER_HOST_2', false);
define('PF_CACHE_MEMCACHE_SERVER_HOST_3', false);
define('PF_CACHE_MEMCACHE_SERVER_HOST_4', false);

define('PF_CDN_URL', '%%PHING_PROTEAN_URL%%');

// JOB QUEUE SETTINGS
define('PF_JOBQUEUE_HOST', '127.0.0.1');
define('PF_JOBQUEUE_PORT', 11300);
define('PF_JOBQUEUE_CONN_TIMEOUT', null);

// MAILER SETTINGS
define('PF_EMAIL_USE_SMTP', false);
define('PF_DEFAULT_FROM_EMAIL_NAME', 'Somename');
define('PF_DEFAULT_FROM_EMAIL_ADDRESS', 'me@here.com');
define('PF_EMAIL_SERVER', 'mail.loopshot.com');
define('PF_EMAIL_SERVER_USERNAME', 'me@here.com');
define('PF_EMAIL_SERVER_PASSWORD', '');
define('PF_EMAIL_DB_USERNAME', '');
define('PF_EMAIL_DB_PASSWORD', '');
define('PF_EMAIL_DEBUG', false);
define('PF_EMAIL_DEBUG_LOG', '%%PHING_PROTEAN_BASEDIR%%b/logs/pf_mailer.log');
define('PF_ADD_NEW_USER_TO_MAILINGLIST', false);

// SMS TEXT SETTINGS
define('PF_SMS_TWILIO_CLIENT_ID', 'aaa');
define('PF_SMS_TWILIO_AUTH_TOKEN', 'aaa');
define('PF_SMS_FROM_NUMBER', '555-555-1234');
define('PF_SMS_DEBUG', true);
define('PF_SMS_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_sms_message.log');

// THIRD-PARTY INCLUDES SETTINGS
define('PF_INCLUDE_GA_TRACKING', false);
define('PF_INCLUDE_SNAPENGAGE', false);
define('PF_INCLUDE_GET_SATISFACTION', false);

// SHOP MODULE SETTINGS
define('PF_SHOP_CHECK_INVENTORY', false);
define('PF_SHOP_DEFAULT_PRODUCT_ITEM', 1);
define('PF_SHOP_SAVE_CREDITCARD_NUMBER', false);
define('PF_SHOP_FLAT_SHIPPING_FEE', false);
define('PF_SHOP_HANDLING_FEE', false);
define('PF_SHOP_EMAIL_ADMINS', false);

define('PF_SHOP_GATEWAY_DEBUG', true);
define('PF_SHOP_GATEWAY_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_gateway.log');

define('PF_SHOP_GATEWAY_AUTHNET_TEST_REQUEST', true);
define('PF_SHOP_GATEWAY_AUTHNET_LOGIN', 'abc');
define('PF_SHOP_GATEWAY_AUTHNET_TRAN_KEY', 'abc');
define('PF_SHOP_GATEWAY_AUTHNET_TEST_LOGIN', 'abc');
define('PF_SHOP_GATEWAY_AUTHNET_TEST_TRAN_KEY', 'abc');
define('PF_SHOP_GATEWAY_AUTHNET_CIM_HOST_PRODUCTION', 'api.authorize.net');
define('PF_SHOP_GATEWAY_AUTHNET_CIM_HOST_TEST', 'apitest.authorize.net');
define('PF_SHOP_GATEWAY_AUTHNET_CIM_PORT', '443');
define('PF_SHOP_GATEWAY_AUTHNET_CIM_PATH', '/xml/v1/request.api');

define('PF_SHOP_GATEWAY_STRIPE_TEST_REQUEST', true);
define('PF_SHOP_GATEWAY_STRIPE_TEST_SECRET_KEY', '');
define('PF_SHOP_GATEWAY_STRIPE_TEST_PUBLISH_KEY', '');
define('PF_SHOP_GATEWAY_STRIPE_LIVE_SECRET_KEY', '');
define('PF_SHOP_GATEWAY_STRIPE_LIVE_PUBLISH_KEY', '');
define('PF_SHOP_GATEWAY_STRIPE_SCRIPT', 'https://js.stripe.com/v1/');

define('PF_SHOP_GATEWAY_PAYPAL_TEST_REQUEST', true);
define('PF_SHOP_GATEWAY_PAYPAL_LOG', '%%PHING_PROTEAN_BASEDIR%%/logs/pf_paypal.log');
define('PF_SHOP_GATEWAY_PAYPAL_SELLER_EMAIL', '');

define('PF_USPS_RATECALCULATOR_USERNAME', '');

define('PF_ES_HOST_1', 'localhost');
define('PF_ES_HOST_2', false);
define('PF_ES_HOST_3', false);
define('PF_ES_HOST_4', false);

// SITE SPECIFIC DEFINES

require_once 'modules/api/lib/common.php';
?>


text:
package org.jbb.security.web;

import org.jbb.lib.restful.RestConfig;
import org.jbb.lib.test.MockCommonsConfig;
import org.junit.runner.RunWith;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {SecurityWebConfig.class, RestConfig.class, MockSecurityWebConfig.class,
    MockCommonsConfig.class})
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class,
        WithSecurityContextTestExecutionListener.class})
public abstract class BaseIT {

}


text:
Order: 9
Area: languages
TOCTitle: Python
ContentId: c2cb770d-571d-4edf-9eb9-b5b8977c21a0
PageTitle: Python with Visual Studio Code
DateApproved: 6/8/2017
MetaDescription: Learn about Visual Studio Code editor features (code completion, debugging, snippets, linting) for Python.
---
# Python on Visual Studio Code

Python is fully supported in Visual Studio Code through [extensions](/docs/userguide/extension-gallery.md). Popular extensions in the [Marketplace](https://marketplace.visualstudio.com) provide code completion, linting, debugging, code formatting, snippets, and more.

> [Download VS Code](/download) - If you haven't downloaded VS Code yet, quickly install for your platform (Windows, Mac, Linux).

## Install Python Extension

VS Code is a fast editor and ships with only the basic features. Add Python language support to VS Code by installing one of the popular Python extensions.

1. Select an extension.
2. Install the extension by typing `ext install` into the Command Palette `kb(workbench.action.showCommands)`.

> Tip: The extensions shown above are dynamically queried. Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the [Marketplace](https://marketplace.visualstudio.com/vscode).

The examples in this document will use Don Jayamanne's popular and full featured [Python Extension](https://marketplace.visualstudio.com/items?itemName=donjayamanne.python).

## Code Completion

Python extensions support code completion and Intellisense. [Intellisense](/docs/userguide/intellisense.md) is a general term for a number of features, including intelligent code completion (in-context method and variable suggestions) across all your files and for built-in and thirty-party modules.

Quickly see methods, class members, and documentation.

<video id="python-code-completion-video" src="https://az754404.vo.msecnd.net/public/python-intellisense.mp4" poster="/images/python_python-intellisense-placeholder.png" autoplay loop controls muted></video>

> Tip: Trigger code completion with `kb(editor.action.triggerSuggest)`.

## Linting

Linting is the analysis of your Python code for potential errors. Use Visual Studio Code to quickly navigate to the errors and warnings in your code.

<video id="python-linting-video" src="https://az754404.vo.msecnd.net/public/python-linting.mp4" poster="/images/python_python-linting-placeholder.png" autoplay loop controls muted></video>

> Tip: [Don Jayamanne's Python extension](https://marketplace.visualstudio.com/items?itemName=donjayamanne.python) gives you the option of using three different linters - [Pylint](https://www.pylint.org/), [Pep8](https://pypi.python.org/pypi/pep8), and [Flake8](https://flake8.readthedocs.io/en/latest/). See the [wiki](https://github.com/DonJayamanne/pythonVSCode/wiki/Linting) for more details.

## Debugging

No more `print` statement debugging! Set breakpoints, inspect data, and use the debug console. Debug a number of different type of Python applications, including multi-threaded, web, and remote applications.

<video id="python-debugging-video" src="https://az754404.vo.msecnd.net/public/python-debugging.mp4" poster="/images/python_python-debugging-placeholder.png" autoplay loop controls muted></video>

> Tip: Follow the instructions in the [wiki](https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging) for getting started with debugging, including setting up your `launch.json` debugging configuration and troubleshooting common issues.

> Tip: Read more about general information about debugging in Visual Studio Code in the [debugging document](/docs/userguide/debugging.md).

## Snippets

Snippets will take productivity to the next level. You can configure [your own snippets](/docs/userguide/userdefinedsnippets.md) and use snippets provided by an extension.

<video id="python-snippets-video" src="https://az754404.vo.msecnd.net/public/python-snippets.mp4" poster="/images/python_python-snippets-placeholder.png" autoplay loop controls muted></video>

> Tip: Snippets appear in the same way as code completion `kb(editor.action.triggerSuggest)`.

## Configuration

You will need an [extension](/docs/languages/python.md#install-python-extension) and [Python](https://www.python.org/downloads/) installed. Other dependencies are optional and depend on the features you want to use. Read through the requirements on the [extension's README](https://marketplace.visualstudio.com/items?itemName=donjayamanne.python#requirements).

## Next Steps

* [Install an Extension](/docs/userguide/extension-gallery.md) - Python extension are available in the [Marketplace](https://marketplace.visualstudio.com/vscode).
* [Basic Editing](/docs/userguide/codebasics.md) - Learn about the powerful VS Code editor.
* [Code Navigation](/docs/userguide/editingevolved.md) - Move quickly through your source code.

## Common Questions

**Q: Why won't linting work for me?**

**A:** First make sure you have installed an extension. Next, many extensions have a dependency on an external package. Install the [required packages](https://marketplace.visualstudio.com/items?itemName=donjayamanne.python#requirements) using a Python package manager like [pip](https://pypi.python.org/pypi/pip) or [easy_install](http://peak.telecommunity.com/DevCenter/EasyInstall). You can read more about troubleshooting linting issues [here](https://github.com/DonJayamanne/pythonVSCode/wiki/Autocomplete-Intellisense).


text:
package controlador;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dto.DTO_Consulta;
import logicaDeNegocio.Voz;

/**
 * Servlet implementation class ServletTraducir
 */
@WebServlet("/ServletTraducir")
public class ServletTraducir extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletTraducir() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

    	String pregunta = request.getParameter("pregunta");
    	String respuestas =  request.getParameter("respuestas");

    	String preguntaIngles = ControladorWeb.solicitudTraducirAIngles(pregunta);
    	String respuestaIngles = ControladorWeb.solicitudTraducirAIngles(respuestas);

 	    DTO_Consulta nuevaConsulta = new DTO_Consulta();

    	nuevaConsulta.getRespuestas().add(respuestaIngles);
    	nuevaConsulta.setPreguntaTexto(preguntaIngles);

        request.setAttribute("DTO_Consulta", nuevaConsulta);
        request.getRequestDispatcher("respuestaConsulta.jsp").forward(request, response);

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}


text:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="UnitCorrespondentMaintenanceDocument" parent="UnitCorrespondentMaintenanceDocument-parentBean" />
    <bean id="UnitCorrespondentMaintenanceDocument-parentBean" abstract="true" parent="KcMaintenanceDocumentEntry">
        <property name="businessObjectClass" value="org.kuali.coeus.common.framework.unit.crrspndnt.UnitCorrespondent" />
	    <property name="maintainableClass" value="org.kuali.coeus.common.impl.unit.crrspndnt.UnitCorrespondentMaintainableImpl"/>
        <property name="maintainableSections" >
            <list>
                <ref bean="UnitCorrespondentMaintenanceDocument-EditUnitCorrespondent" />
            </list>
        </property>
        <property name="lockingKeys" >
            <list>
                <value>unitNumber</value>
                <value>correspondentTypeCode</value>
		        <value>personId</value>
            </list>
        </property>
        <property name="allowsRecordDeletion" value="true" />
        <property name="documentTypeName" value="UnitCorrespondentMaintenanceDocument" />
        <property name="documentAuthorizerClass" value="org.kuali.rice.kns.document.authorization.MaintenanceDocumentAuthorizerBase" />
    </bean>

    <!-- Maintenance Section Definitions -->

    <bean id="UnitCorrespondentMaintenanceDocument-EditUnitCorrespondent" parent="UnitCorrespondentMaintenanceDocument-EditUnitCorrespondent-parentBean" />
    <bean id="UnitCorrespondentMaintenanceDocument-EditUnitCorrespondent-parentBean" abstract="true" parent="MaintainableSectionDefinition">
        <property name="id" value="Edit Unit Correspondent" />
        <property name="title" value="Edit Unit Correspondent" />
        <property name="maintainableItems" >
            <list>
                <bean parent="MaintainableFieldDefinition" p:name="personId" p:required="true" />
 		        <bean parent="MaintainableFieldDefinition" p:name="person.userName" p:required="false" />
                <bean parent="MaintainableFieldDefinition" p:name="unitNumber" p:required="true" />
                <bean parent="MaintainableFieldDefinition" p:name="correspondentTypeCode" p:required="true" />
                <bean parent="MaintainableFieldDefinition" p:name="nonEmployeeFlag" p:required="true" />
                <bean parent="MaintainableFieldDefinition" p:name="description" />
            </list>
        </property>
    </bean>
</beans>


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

namespace OfficeStuff
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
package com.intellij.structuralsearch;

import com.intellij.psi.PsiElement;
import com.intellij.structuralsearch.plugin.util.SmartPsiPointer;
import org.jetbrains.annotations.NonNls;

import java.util.List;

/**
 * Class describing the match result
 */
public abstract class MatchResult {
  @NonNls public static final String LINE_MATCH = "__line__";
  @NonNls public static final String MULTI_LINE_MATCH = "__multi_line__";

  public abstract String getMatchImage();

  public abstract SmartPsiPointer getMatchRef();
  public abstract PsiElement getMatch();
  public abstract int getStart();
  public abstract int getEnd();

  public abstract String getName();

  public abstract List<MatchResult> getAllSons();
  public abstract boolean hasSons();
  public abstract boolean isScopeMatch();
  public abstract boolean isMultipleMatch();
  public abstract boolean isTarget();
}


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

<title>SMCImageHelper</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

app.utils.image

类 SMCImageHelper

java.lang.Object

app.utils.image.SMCImageHelper

public class SMCImageHelper
extends java.lang.Object

图片帮助类

作者:

SiuJiYung create at 2013-12-9 上午10:56:29

字段概要

字段

限定符和类型
字段和说明

static java.io.File
FILE_LOCAL

static java.io.File
FILE_PIC_SCREENSHOT

static java.io.File
FILE_SDCARD

static java.io.File
filePath

static int
FLAG_CHOOSE_PHONE

static java.lang.String
localTempImageFileName

方法概要

All Methods Static Methods Instance Methods Concrete Methods

限定符和类型
方法和说明

void
addBitmapToMemoryCache(java.lang.String imgName,
                      Bitmap img)

static java.lang.String
addWatermarkToPhoto(Context context,
                   java.lang.String pathName,
                   java.util.HashMap<java.lang.String,java.lang.String> info,
                   java.util.List<java.lang.String> sortList,
                   java.lang.String newPath)

添加文字水印到指定图片

static Bitmap
canvasWatermark(Context context,
               Bitmap src,
               java.util.HashMap<java.lang.String,java.lang.String> map,
               float textSize,
               int textColor)

添加水印

static byte[]
compressImag(Bitmap image)

压缩照片

static Bitmap
createWaterBitmap(java.util.HashMap<java.lang.String,java.lang.String> waterString,
                 java.util.List<java.lang.String> sortList,
                 float textSize,
                 int picMaxWidth,
                 int textColor)

Bitmap
getBitmapFromMemoryCache(java.lang.String imgName)

static java.lang.String
getFileMd5(java.lang.String pathName)

static SMCImageHelper
getInstance()

static Rect
getTextRect(java.lang.String text,
           Paint paint)

计算文字所在矩形,可以得到宽高

Bitmap
loadBitmapWithResId(int resId)

static boolean
openCamera(Context context)

static Bitmap
PicZoom(Bitmap bmp,
       int width,
       int height)

static Bitmap
readBitmap(java.lang.String photoPath,
          int width,
          int height)

读照片出来

static int
reckonThumbnail(int oldWidth,
               int oldHeight,
               int newWidth,
               int newHeight)

static boolean
saveBitmapToPath(Bitmap bmp,
                java.lang.String filePath)

保存bitmap到文件

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

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

字段详细资料

FILE_SDCARD

public static final java.io.File FILE_SDCARD

FILE_LOCAL

public static final java.io.File FILE_LOCAL

FILE_PIC_SCREENSHOT

public static final java.io.File FILE_PIC_SCREENSHOT

filePath

public static final java.io.File filePath

localTempImageFileName

public static java.lang.String localTempImageFileName

FLAG_CHOOSE_PHONE

public static final int FLAG_CHOOSE_PHONE

另请参阅:

常量字段值

方法详细资料

getInstance

public static SMCImageHelper getInstance()

addBitmapToMemoryCache

public void addBitmapToMemoryCache(java.lang.String imgName,
                                   Bitmap img)

getBitmapFromMemoryCache

public Bitmap getBitmapFromMemoryCache(java.lang.String imgName)

loadBitmapWithResId

public Bitmap loadBitmapWithResId(int resId)

reckonThumbnail

public static int reckonThumbnail(int oldWidth,
                                  int oldHeight,
                                  int newWidth,
                                  int newHeight)

PicZoom

public static Bitmap PicZoom(Bitmap bmp,
                             int width,
                             int height)

createWaterBitmap

public static Bitmap createWaterBitmap(java.util.HashMap<java.lang.String,java.lang.String> waterString,
                                       java.util.List<java.lang.String> sortList,
                                       float textSize,
                                       int picMaxWidth,
                                       int textColor)

canvasWatermark

public static Bitmap canvasWatermark(Context context,
                                     Bitmap src,
                                     java.util.HashMap<java.lang.String,java.lang.String> map,
                                     float textSize,
                                     int textColor)

添加水印

参数:

context -

src -

info -

返回:

readBitmap

public static Bitmap readBitmap(java.lang.String photoPath,
                                int width,
                                int height)

读照片出来

参数:

photoPath -

返回:

getTextRect

public static Rect getTextRect(java.lang.String text,
                               Paint paint)

计算文字所在矩形,可以得到宽高

参数:

text -

paint -

返回:

addWatermarkToPhoto

public static java.lang.String addWatermarkToPhoto(Context context,
                                                   java.lang.String pathName,
                                                   java.util.HashMap<java.lang.String,java.lang.String> info,
                                                   java.util.List<java.lang.String> sortList,
                                                   java.lang.String newPath)
                                            throws java.lang.Exception

添加文字水印到指定图片

参数:

pathName -

info -

返回:

抛出:

java.lang.Exception

getFileMd5

public static java.lang.String getFileMd5(java.lang.String pathName)

compressImag

public static byte[] compressImag(Bitmap image)

压缩照片

参数:

image -

返回:

字节byte[]

saveBitmapToPath

public static boolean saveBitmapToPath(Bitmap bmp,
                                       java.lang.String filePath)
                                throws java.lang.Exception

保存bitmap到文件

参数:

bmp -

filePath -

返回:

抛出:

java.lang.Exception

openCamera

public static boolean openCamera(Context context)

跳过导航链接

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法


text:
use {VRGamepad, VRGamepadButton, VRGamepadData, VRGamepadHand, VRGamepadState};
use ovr_mobile_sys as ovr;
use ovr_mobile_sys::ovrButton::*;
use ovr_mobile_sys::ovrControllerCapabilties::*;
use ovr_mobile_sys::ovrControllerType::*;
use std::cell::{Cell, RefCell};
use std::mem;
use std::ptr;
use std::sync::Arc;
use super::display::{ovr_quat_to_array, ovr_vec3_to_array};
use rust_webvr_api::utils;

pub type OculusVRGamepadPtr = Arc<RefCell<OculusVRGamepad>>;

pub struct OculusVRGamepad {
    ovr: *mut ovr::ovrMobile,
    ovr_id: ovr::ovrDeviceID,
    ovr_type: ovr::ovrControllerType,
    connected: bool,
    capabilities: InputCapabilities,
    gamepad_id: u32,
    display_id: u32,
    predicted_display_time: Cell<f64>,
}

unsafe impl Send for OculusVRGamepad {}
unsafe impl Sync for OculusVRGamepad {}

impl OculusVRGamepad {
    pub fn new(ovr: *mut ovr::ovrMobile,
               ovr_id: ovr::ovrDeviceID,
               ovr_type: ovr::ovrControllerType,
               display_id: u32)
               -> Arc<RefCell<OculusVRGamepad>>
    {
        let capabilities = InputCapabilities::from_ovr(ovr, ovr_type, ovr_id);

        let gamepad = Self {
            ovr: ovr,
            ovr_id: ovr_id,
            ovr_type: ovr_type,
            connected: true,
            capabilities: capabilities.unwrap_or_default(),
            gamepad_id: utils::new_id(),
            display_id: display_id,
            predicted_display_time: Cell::new(0.0),
        };

        Arc::new(RefCell::new(gamepad))
    }

    pub fn refresh_available_gamepads(ovr: *mut ovr::ovrMobile,
                                      display_id: u32,
                                      out: &mut Vec<OculusVRGamepadPtr>) {
        let mut index = 0;
        // Reset connected status
        for gamepad in out.iter() {
            gamepad.borrow_mut().connected = false;
        }

        loop {
            let mut caps: ovr::ovrInputCapabilityHeader = unsafe { mem::uninitialized() };

            if unsafe { ovr::vrapi_EnumerateInputDevices(ovr, index, &mut caps) } < 0 {
                // No more input devices to enumerate
                break;
            }

            index += 1;

            if caps.Type != ovrControllerType_TrackedRemote && caps.Type != ovrControllerType_Headset  {
                // Not interested in this kind of input device
                continue;
            }

            // Update if the controller type already exists
            if let Some(gamepad) = out.iter().find(|g| g.borrow().ovr_type == caps.Type).as_ref() {
                let mut gamepad = gamepad.borrow_mut();
                gamepad.ovr = ovr;
                gamepad.ovr_id = caps.DeviceID;
                gamepad.connected = true;
                gamepad.update_capabilities();
                continue;
            }

            // Create new Gamepad instance
            let gamepad = OculusVRGamepad::new(ovr, caps.DeviceID, caps.Type, display_id);
            out.push(gamepad);
        }
    }

    pub fn update_capabilities(&mut self) {
        if let Ok(capabilities) = InputCapabilities::from_ovr(self.ovr, self.ovr_type, self.ovr_id) {
            self.capabilities = capabilities;
        }
    }

    // Sensor input is only available while in VR mode.
    pub fn on_exit_vrmode(&mut self) {
        self.connected = false;
        self.ovr = ptr::null_mut();
    }

    fn fetch_axes(&self, touching: bool, pos: &ovr::ovrVector2f, out: &mut VRGamepadState) {
        // Axes
        // Touchpad: (0,0) is the top-left corner.
        // Map to -1 1 for each axis.
        let x = pos.x / self.capabilities.trackpad_max_x as f32;
        let y = pos.y / self.capabilities.trackpad_max_y as f32;
        out.axes = if touching {
            [x as f64 * 2.0 - 1.0,
             y as f64 * 2.0 - 1.0].to_vec()
        } else {
            [0.0, 0.0].to_vec()
        };
    }

    fn fetch_remote_controller_state(&self, out: &mut VRGamepadState) {
        let mut state: ovr::ovrInputStateTrackedRemote = unsafe { mem::zeroed() };
        state.Header.ControllerType = ovrControllerType_TrackedRemote;
        unsafe {
            ovr::vrapi_GetCurrentInputState(self.ovr, self.ovr_id, &mut state.Header);
        }
        let touching_trackpad = state.TrackpadStatus > 0;

        // Axes
        self.fetch_axes(touching_trackpad, &state.TrackpadPosition, out);

        // 0 - Trackpad
        out.buttons.push(VRGamepadButton::new(touching_trackpad));

        // 1 - Trigger A
        out.buttons.push(VRGamepadButton::new(state.Buttons & (ovrButton_A as u32) > 0));
    }

    fn fetch_headset_controller_state(&self, out: &mut VRGamepadState) {
        let mut state: ovr::ovrInputStateHeadset = unsafe { mem::zeroed() };
        state.Header.ControllerType = ovrControllerType_Headset;
        unsafe {
            ovr::vrapi_GetCurrentInputState(self.ovr, self.ovr_id, &mut state.Header);
        }
        let touching_trackpad = state.TrackpadStatus > 0;

        // Axes
        self.fetch_axes(touching_trackpad, &state.TrackpadPosition, out);

        // 0 - Trackpad
        out.buttons.push(VRGamepadButton::new(touching_trackpad));

        // 1 - Trigger A
        out.buttons.push(VRGamepadButton::new(state.Buttons & (ovrButton_A as u32) > 0));
    }

    fn fetch_tracking_state(&self, out: &mut VRGamepadState) {
        let mut tracking: ovr::ovrTracking = unsafe { mem::uninitialized() };
        let status = unsafe {
             ovr::vrapi_GetInputTrackingState(self.ovr,
                                              self.ovr_id,
                                              self.predicted_display_time.get(),
                                              &mut tracking)
        };

        if status != ovr::ovrSuccessResult::ovrSuccess as i32 {
            out.connected = false;
            return;
        }

        if self.capabilities.controller_capabilities & (ovrControllerCaps_HasOrientationTracking as u32) > 0 {
            out.pose.orientation = Some(ovr_quat_to_array(&tracking.HeadPose.Pose.Orientation));
        }

        if self.capabilities.controller_capabilities & (ovrControllerCaps_HasPositionTracking as u32) > 0 {
            out.pose.position = Some(ovr_vec3_to_array(&tracking.HeadPose.Pose.Position));
        }
    }

    pub fn set_predicted_display_time(&self, time: f64) {
        self.predicted_display_time.set(time);
    }
}

impl VRGamepad for OculusVRGamepad {
    fn id(&self) -> u32 {
        self.gamepad_id
    }

    fn data(&self) -> VRGamepadData {
        let name = if self.ovr_type == ovrControllerType_TrackedRemote {
            "Gear VR Remote Controller"
        } else {
            "Gear VR Headset Controller"
        };

        let hand = if self.capabilities.controller_capabilities & (ovrControllerCaps_RightHand as u32) > 0 {
            VRGamepadHand::Right
        } else if self.capabilities.controller_capabilities & (ovrControllerCaps_LeftHand as u32) > 0 {
            VRGamepadHand::Left
        } else {
            VRGamepadHand::Unknown
        };

        VRGamepadData {
            display_id: self.display_id,
            name: name.into(),
            hand: hand,
        }
    }

    fn state(&self) -> VRGamepadState {
        let mut out = VRGamepadState::default();

        out.gamepad_id = self.gamepad_id;
        out.connected = self.connected && !self.ovr.is_null();

        if out.connected {
            if self.ovr_type == ovrControllerType_TrackedRemote {
                self.fetch_remote_controller_state(&mut out);
            } else {
                self.fetch_headset_controller_state(&mut out);
            }
            self.fetch_tracking_state(&mut out);
        }

        out
    }
}

struct InputCapabilities {
    controller_capabilities: u32,
    trackpad_max_x: u16,
    trackpad_max_y: u16,
}

impl InputCapabilities {
    pub fn from_ovr(ovr: *mut ovr::ovrMobile,
                    ovr_type: ovr::ovrControllerType,
                    ovr_id: ovr::ovrDeviceID) -> Result<InputCapabilities,()> {
        if ovr_type == ovrControllerType_TrackedRemote {
            let mut caps: ovr::ovrInputTrackedRemoteCapabilities = unsafe { mem::uninitialized() };
            caps.Header.DeviceID = ovr_id;
            caps.Header.Type = ovr_type;

            let status = unsafe {
                ovr::vrapi_GetInputDeviceCapabilities(ovr, &mut caps.Header)
            };

            if status != ovr::ovrSuccessResult::ovrSuccess as i32 {
                return Err(());
            }

            Ok(Self {
                controller_capabilities: caps.ControllerCapabilities,
                trackpad_max_x: caps.TrackpadMaxX,
                trackpad_max_y: caps.TrackpadMaxY,
            })

        } else {
            let mut caps: ovr::ovrInputHeadsetCapabilities = unsafe { mem::uninitialized() };
            caps.Header.DeviceID = ovr_id;
            caps.Header.Type = ovr_type;

            let status = unsafe {
                ovr::vrapi_GetInputDeviceCapabilities(ovr, &mut caps.Header)
            };

            if status != ovr::ovrSuccessResult::ovrSuccess as i32 {
                return Err(());
            }

            Ok(Self {
                controller_capabilities: caps.ControllerCapabilities,
                trackpad_max_x: caps.TrackpadMaxX,
                trackpad_max_y: caps.TrackpadMaxY,
            })
        }
    }
}

impl Default for InputCapabilities {
    fn default() -> InputCapabilities {
        InputCapabilities {
            controller_capabilities: 0,
            trackpad_max_x: 299,
            trackpad_max_y: 199,
        }
    }
}


text:
EMAIL="yongjie.ren@dianping.com"
WARN_MSG=""

# alert when free memory is less than 50 MB
function mem_free()
{
	threshold=50  # 50 MB free memory
	free_mem=$(free -m | grep "buffers/cache" | awk '{print $4}')
	if [ $free_mem -lt $threshold ]; then
		WARN_MSG=$WARN_MSG"Free memeory is less than $threshold MB.\n"
		return 1
	fi
	return 0
}

# alert when load (5min) is larger than 4
function load_avg()
{
	threshold=4  # load is 4
	load_5min=$(cat /proc/loadavg | awk '{print $2}')
	if [ $(echo "$load_5min > $threshold" | bc) -eq 1 ]; then
        	WARN_MSG=$WARN_MSG"5min average load is larger than $threshold.\n"
		return 1
	fi
	return 0
}

# alert when CPU idle% is less than 20%
function cpu_idle()
{
	threshold=20  # CPU idle% 20%
	cpu_idle=$(sar 1 5 | grep -i 'Average' | awk '{print $NF}')
	if [ $(echo "$cpu_idle < $threshold" | bc) -eq 1 ]; then
		# in printf cmd, %% represents a single %
		WARN_MSG=$WARN_MSG"CPU idle%% is less than $threshold%%.\n"
		return 1
	fi
	return 0
}

# alert when networking tx speed is larger than 80 kB/s
function network_tx()
{
	threshold=80  # TX speed 80 kB/s
	interface=eth0
	tx_speed=$(sar -n DEV 10 5 | grep "Average" | grep "$interface" | awk '{print $6}')
	if [ $(echo "$tx_speed > $threshold" | bc) -eq 1 ]; then
		WARN_MSG=$WARN_MSG"networking TX speed is larger than $threshold kB/s.\n"
		return 1
	fi
	return 0
}

# alert when httpd/nginx or mysqld or php-fpm process doesn't exist
function web_mysqld()
{
	web_server='nginx'  # or 'httpd'
	php_fpm='php-fpm'   # nginx works with php-fpm to run wordpress
	fail=0
	ps -ef | grep "$web_server" | grep -v 'grep'
	if [ $? -ne 0 ]; then
		WARN_MSG=$WARN_MSG"$web_server process doesn't exist.\n"
		fail=1
	else
		if [ "x$web_server" = "xnginx" ]; then
			ps -ef | grep "$php_fpm" | grep -v 'grep'
			if [ $? -ne 0 ]; then
				WARN_MSG=$WARN_MSG"$php_fpm process doesn't exist.\n"
				fail=1
			fi
		fi
		ps -ef | grep 'mysqld' | grep -v 'grep'
		if [ $? -ne 0 ]; then
			WARN_MSG=$WARN_MSG"mysqld process doesn't exist.\n"
			fail=1
		fi
	fi
	if [ $fail -eq 1 ]; then
		return 1
	else
		return 0
	fi
}

# alert when 'Stay hungry' doesn't exist in the home page http://smilejay.com/
function home_page()
{
	url=http://smilejay.com/
	keywords="Stay hungry"
	curl -sL $url | grep -i "$keywords"
	if [ $? -ne 0 ]; then
		WARN_MSG=$WARN_MSG"keywords '$keywords' doesn't exist on link $url.\n"
		return 1
	fi
	return 0
}

# use flag to mark if any function return error
flag=0
mem_free
flag=$(($flag + $?))
load_avg
flag=$(($flag + $?))
cpu_idle
flag=$(($flag + $?))
network_tx
flag=$(($flag + $?))
web_mysqld
flag=$(($flag + $?))
home_page
flag=$(($flag + $?))

# send warning email to the web master if any of the check fails.
if [ $flag -ne 0 ]; then
	printf "$WARN_MSG" | mailx -s "Warning from smilejay.com" $EMAIL
	exit 1
fi


text:
typedef int TURIPdataType;

#endif


text:
@interface CustomCellTitleView : UIView

@end


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/asset/v1beta1/assets.proto

namespace Google\Cloud\Asset\V1beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Representation of a cloud resource.
 *
 * Generated from protobuf message google.cloud.asset.v1beta1.Resource
 */
class Resource extends \Google\Protobuf\Internal\Message
{
    /**
     * The API version. Example: "v1".
     *
     * Generated from protobuf field string version = 1;
     */
    private $version = '';
    /**
     * The URL of the discovery document containing the resource's JSON schema.
     * For example:
     * `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`.
     * It will be left unspecified for resources without a discovery-based API,
     * such as Cloud Bigtable.
     *
     * Generated from protobuf field string discovery_document_uri = 2;
     */
    private $discovery_document_uri = '';
    /**
     * The JSON schema name listed in the discovery document.
     * Example: "Project". It will be left unspecified for resources (such as
     * Cloud Bigtable) without a discovery-based API.
     *
     * Generated from protobuf field string discovery_name = 3;
     */
    private $discovery_name = '';
    /**
     * The REST URL for accessing the resource. An HTTP GET operation using this
     * URL returns the resource itself.
     * Example:
     * `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`.
     * It will be left unspecified for resources without a REST API.
     *
     * Generated from protobuf field string resource_url = 4;
     */
    private $resource_url = '';
    /**
     * The full name of the immediate parent of this resource. See
     * [Resource
     * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name)
     * for more information.
     * For GCP assets, it is the parent resource defined in the [Cloud IAM policy
     * hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy).
     * For example:
     * `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`.
     * For third-party assets, it is up to the users to define.
     *
     * Generated from protobuf field string parent = 5;
     */
    private $parent = '';
    /**
     * The content of the resource, in which some sensitive fields are scrubbed
     * away and may not be present.
     *
     * Generated from protobuf field .google.protobuf.Struct data = 6;
     */
    private $data = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $version
     *           The API version. Example: "v1".
     *     @type string $discovery_document_uri
     *           The URL of the discovery document containing the resource's JSON schema.
     *           For example:
     *           `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`.
     *           It will be left unspecified for resources without a discovery-based API,
     *           such as Cloud Bigtable.
     *     @type string $discovery_name
     *           The JSON schema name listed in the discovery document.
     *           Example: "Project". It will be left unspecified for resources (such as
     *           Cloud Bigtable) without a discovery-based API.
     *     @type string $resource_url
     *           The REST URL for accessing the resource. An HTTP GET operation using this
     *           URL returns the resource itself.
     *           Example:
     *           `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`.
     *           It will be left unspecified for resources without a REST API.
     *     @type string $parent
     *           The full name of the immediate parent of this resource. See
     *           [Resource
     *           Names](https://cloud.google.com/apis/design/resource_names#full_resource_name)
     *           for more information.
     *           For GCP assets, it is the parent resource defined in the [Cloud IAM policy
     *           hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy).
     *           For example:
     *           `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`.
     *           For third-party assets, it is up to the users to define.
     *     @type \Google\Protobuf\Struct $data
     *           The content of the resource, in which some sensitive fields are scrubbed
     *           away and may not be present.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Asset\V1Beta1\Assets::initOnce();
        parent::__construct($data);
    }

    /**
     * The API version. Example: "v1".
     *
     * Generated from protobuf field string version = 1;
     * @return string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * The API version. Example: "v1".
     *
     * Generated from protobuf field string version = 1;
     * @param string $var
     * @return $this
     */
    public function setVersion($var)
    {
        GPBUtil::checkString($var, True);
        $this->version = $var;

        return $this;
    }

    /**
     * The URL of the discovery document containing the resource's JSON schema.
     * For example:
     * `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`.
     * It will be left unspecified for resources without a discovery-based API,
     * such as Cloud Bigtable.
     *
     * Generated from protobuf field string discovery_document_uri = 2;
     * @return string
     */
    public function getDiscoveryDocumentUri()
    {
        return $this->discovery_document_uri;
    }

    /**
     * The URL of the discovery document containing the resource's JSON schema.
     * For example:
     * `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`.
     * It will be left unspecified for resources without a discovery-based API,
     * such as Cloud Bigtable.
     *
     * Generated from protobuf field string discovery_document_uri = 2;
     * @param string $var
     * @return $this
     */
    public function setDiscoveryDocumentUri($var)
    {
        GPBUtil::checkString($var, True);
        $this->discovery_document_uri = $var;

        return $this;
    }

    /**
     * The JSON schema name listed in the discovery document.
     * Example: "Project". It will be left unspecified for resources (such as
     * Cloud Bigtable) without a discovery-based API.
     *
     * Generated from protobuf field string discovery_name = 3;
     * @return string
     */
    public function getDiscoveryName()
    {
        return $this->discovery_name;
    }

    /**
     * The JSON schema name listed in the discovery document.
     * Example: "Project". It will be left unspecified for resources (such as
     * Cloud Bigtable) without a discovery-based API.
     *
     * Generated from protobuf field string discovery_name = 3;
     * @param string $var
     * @return $this
     */
    public function setDiscoveryName($var)
    {
        GPBUtil::checkString($var, True);
        $this->discovery_name = $var;

        return $this;
    }

    /**
     * The REST URL for accessing the resource. An HTTP GET operation using this
     * URL returns the resource itself.
     * Example:
     * `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`.
     * It will be left unspecified for resources without a REST API.
     *
     * Generated from protobuf field string resource_url = 4;
     * @return string
     */
    public function getResourceUrl()
    {
        return $this->resource_url;
    }

    /**
     * The REST URL for accessing the resource. An HTTP GET operation using this
     * URL returns the resource itself.
     * Example:
     * `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`.
     * It will be left unspecified for resources without a REST API.
     *
     * Generated from protobuf field string resource_url = 4;
     * @param string $var
     * @return $this
     */
    public function setResourceUrl($var)
    {
        GPBUtil::checkString($var, True);
        $this->resource_url = $var;

        return $this;
    }

    /**
     * The full name of the immediate parent of this resource. See
     * [Resource
     * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name)
     * for more information.
     * For GCP assets, it is the parent resource defined in the [Cloud IAM policy
     * hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy).
     * For example:
     * `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`.
     * For third-party assets, it is up to the users to define.
     *
     * Generated from protobuf field string parent = 5;
     * @return string
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * The full name of the immediate parent of this resource. See
     * [Resource
     * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name)
     * for more information.
     * For GCP assets, it is the parent resource defined in the [Cloud IAM policy
     * hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy).
     * For example:
     * `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`.
     * For third-party assets, it is up to the users to define.
     *
     * Generated from protobuf field string parent = 5;
     * @param string $var
     * @return $this
     */
    public function setParent($var)
    {
        GPBUtil::checkString($var, True);
        $this->parent = $var;

        return $this;
    }

    /**
     * The content of the resource, in which some sensitive fields are scrubbed
     * away and may not be present.
     *
     * Generated from protobuf field .google.protobuf.Struct data = 6;
     * @return \Google\Protobuf\Struct
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * The content of the resource, in which some sensitive fields are scrubbed
     * away and may not be present.
     *
     * Generated from protobuf field .google.protobuf.Struct data = 6;
     * @param \Google\Protobuf\Struct $var
     * @return $this
     */
    public function setData($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Struct::class);
        $this->data = $var;

        return $this;
    }

}


text:
import Groupe = require('../../../src/data/domain/groupe');
//
describe('Groupe Tests', () => {
    //
    var type:string = 'groupe';
    var colname:string = 'groupes';
  // empty constructor
  describe(" empty constructor", () => {
    var data: Groupe;
    beforeEach(() => {
      data = new Groupe();
    });
    it(" id property ", () => {
      expect(data.id).toBeDefined();
      expect(data.id).toBeNull();
      expect(data.has_id).toBeDefined();
      expect(data.has_id).toEqual(false);
    });
    it(" rev property ", () => {
      expect(data.rev).toBeDefined();
      expect(data.rev).toBeNull();
      expect(data.has_rev).toBeDefined();
      expect(data.has_rev).toEqual(false);
    });
    it(" remarks property ", () => {
      expect(data.remarks).toBeDefined();
      expect(data.remarks).toBeNull();
      expect(data.has_remarks).toBeDefined();
      expect(data.has_remarks).toEqual(false);
    });
    it(" avatarid property ", () => {
      expect(data.avatarid).toBeDefined();
      expect(data.avatarid).toBeNull();
      expect(data.has_avatarid).toBeDefined();
      expect(data.has_avatarid).toEqual(false);
    });
    it(" departementid property ", () => {
      expect(data.departementid).toBeDefined();
      expect(data.departementid).toBeNull();
      expect(data.has_departementid).toBeDefined();
      expect(data.has_departementid).toEqual(false);
    });
    it(" sigle property ", () => {
      expect(data.sigle).toBeDefined();
      expect(data.sigle).toBeNull();
      expect(data.has_sigle).toBeDefined();
      expect(data.has_sigle).toEqual(false);
    });
    it(" name property ", () => {
      expect(data.name).toBeDefined();
      expect(data.name).toBeNull();
      expect(data.has_name).toBeDefined();
      expect(data.has_name).toEqual(false);
    });
    it(" type property ", () => {
      expect(data.type).toEqual(type);
      expect(data.has_type).toEqual(true);
    });
    it(" collection_name property ", () => {
      expect(data.collection_name).toEqual(colname);
      expect(data.has_collection_name).toEqual(true);
    });
    it(" is_storeable property ", () => {
      expect(data.is_storeable).toBeDefined();
      expect(data.is_storeable).toEqual(false);
    });
    it(" to_insert_map ", () => {
      expect(data.to_insert_map).toBeDefined();
      var oMap: any = {};
      data.to_insert_map(oMap);
      expect(oMap.type).toEqual(type);
      expect(oMap.remarks).not.toBeDefined();
      expect(oMap.avatarid).not.toBeDefined();
      expect(oMap.departementid).not.toBeDefined();
      expect(oMap.sigle).not.toBeDefined();
      expect(oMap.name).not.toBeDefined();
    });
    it(" to_fetch_map ", () => {
      expect(data.to_fetch_map).toBeDefined();
      var oMap: any = {};
      data.to_fetch_map(oMap);
     expect(oMap.type).toEqual(type);
      expect(oMap._id).not.toBeDefined();
      expect(oMap._rev).not.toBeDefined();
      expect(oMap.remarks).not.toBeDefined();
      expect(oMap.avatarid).not.toBeDefined();
      expect(oMap.departementid).not.toBeDefined();
      expect(oMap.sigle).not.toBeDefined();
      expect(oMap.name).not.toBeDefined();
    });
    //
  });
  // normal constructor
  describe(" normal constructor", () => {
    var data: Groupe;
    //
    var id:any = 100;
    var rev:any = 3;
    var remarks: string = 'rem';
    var avatarid: any = 235;
    var departementid = 1000;
    var sigle:string = 'testsigle';
    var name:string = 'testname';
    //
    beforeEach(function() {
      var oMap: any = { _id: id, _rev: rev, remarks: remarks,
      avatarid : avatarid, departementid: departementid,
      sigle: sigle, name:name };
      data = new Groupe(oMap);
    });
    it(" id property ", () => {
      expect(data.id).toEqual(id);
      expect(data.has_id).toEqual(true);
    });
    it(" rev property ", () => {
      expect(data.rev).toEqual(rev);
      expect(data.has_rev).toEqual(true);
    });
    it(" remarks property ", () => {
      expect(data.remarks).toEqual(remarks);
      expect(data.has_remarks).toEqual(true);
    });
    it(" avatarid property ", () => {
      expect(data.avatarid).toEqual(avatarid);
      expect(data.has_avatarid).toEqual(true);
    });
    it(" departementid property ", () => {
      expect(data.departementid).toEqual(departementid);
      expect(data.has_departementid).toEqual(true);
    });
    it(" sigle property ", () => {
      expect(data.sigle).toEqual(sigle);
      expect(data.has_sigle).toEqual(true);
    });
     it(" name property ", () => {
      expect(data.name).toEqual(name);
      expect(data.has_name).toEqual(true);
    });
    it(" type property ", () => {
      expect(data.type).toEqual(type);
      expect(data.has_type).toEqual(true);
    });
    it(" collection_name property ", () => {
      expect(data.collection_name).toEqual(colname);
      expect(data.has_collection_name).toEqual(true);
    });
    it(" is_storeable property ", () => {
      expect(data.is_storeable).toEqual(true);
    });
    it(" to_insert_map ", () => {
      expect(data.to_insert_map).toBeDefined();
      var oMap: any = {};
      data.to_insert_map(oMap);
      expect(oMap.type).toEqual(type);
      expect(oMap._id).not.toBeDefined();
      expect(oMap._rev).not.toBeDefined();
      expect(oMap.remarks).toEqual(remarks);
      expect(oMap.avatarid).toEqual(avatarid);
      expect(oMap.departementid).toEqual(departementid);
      expect(oMap.sigle).toEqual(sigle);
      expect(oMap.name).toEqual(name);
    });
    it(" to_fetch_map ", () => {
      expect(data.to_fetch_map).toBeDefined();
      var oMap: any = {};
      data.to_fetch_map(oMap);
      expect(oMap.type).toEqual(type);
      expect(oMap._id).toEqual(id);
      expect(oMap._rev).toEqual(rev);
      expect(oMap.remarks).toEqual(remarks);
      expect(oMap.avatarid).toEqual(avatarid);
      expect(oMap.departementid).toEqual(departementid);
      expect(oMap.sigle).toEqual(sigle);
      expect(oMap.name).toEqual(name);
    });
    //
  });

});


text:
    <!-- Standard Action Servlet Configuration -->
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>


text:
package io.gravitee.repository.elasticsearch;

import io.gravitee.repository.analytics.query.tabular.TabularResponse;
import io.gravitee.repository.elasticsearch.spring.AnalyticsRepositoryTestConfiguration;
import io.gravitee.repository.log.api.LogRepository;
import io.gravitee.repository.log.model.ExtendedLog;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

import static io.gravitee.repository.analytics.query.DateRangeBuilder.lastDays;
import static io.gravitee.repository.analytics.query.IntervalBuilder.hours;
import static io.gravitee.repository.analytics.query.QueryBuilders.tabular;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(
        listeners = { ElasticsearchNodeListener.class,
                DependencyInjectionTestExecutionListener.class })
@ContextConfiguration(
        classes = AnalyticsRepositoryTestConfiguration.class,
        initializers = PropertySourceRepositoryInitializer.class)
@Ignore
public class ElasticLogRepositoryTest {

    @Autowired
    private LogRepository logRepository;

    @Test
    public void testFindById() throws Exception {
        ExtendedLog log = logRepository.findById("eb61a902-6ea6-4d8a-a1a9-026ea64d8a33");

        Assert.assertNotNull(log);
    }

    @Test
    public void testTabular() throws Exception {
        TabularResponse response = logRepository.query(
                tabular()
                        .timeRange(lastDays(30), hours(1))
                        .query("api:4e0db366-f772-4489-8db3-66f772b48989")
                        .page(1)
                        .size(20)
                        .build());

        Assert.assertNotNull(response);
    }
}


text:
Stocks Chart project for Freecodecamp

See demo.

Technologies Used:

Socket.io for real-time updates

Express.js for backend

AngularJS for frontend

Bootstrap for styling

[Highstock chart](http://www.highcharts.com/stock/demo) for chart

[Markit API](http://dev.markitondemand.com/MODApis/) for stock market data


text:
//
//  DCHBubbleImageView.m
//  Kaleidoscope-of-500px
//
//  Created by Derek Chen on 5/21/15.
//  Copyright (c) 2015 Derek Chen. All rights reserved.
//

#import "DCHBubbleImageView.h"

@interface DCHBubbleImageView ()

@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeRecognizer;

- (void)activeForUserInteraction;
- (void)_swiped:(UISwipeGestureRecognizer *)swipeRecognizer;

@end

@implementation DCHBubbleImageView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc {
    do {
        self.swipeDelegate = nil;
        self.tapDelegate = nil;

        [self removeGestureRecognizer:self.leftSwipeRecognizer];
        self.leftSwipeRecognizer = nil;
        [self removeGestureRecognizer:self.rightSwipeRecognizer];
        self.rightSwipeRecognizer = nil;
    } while (NO);
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self activeForUserInteraction];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self activeForUserInteraction];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self activeForUserInteraction];
    }
    return self;
}

- (instancetype)initWithImage:(UIImage *)image {
    self = [super initWithImage:image];
    if (self) {
        [self activeForUserInteraction];
    }
    return self;
}

- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage {
    self = [super initWithImage:image highlightedImage:highlightedImage];
    if (self) {
        [self activeForUserInteraction];
    }
    return self;
}

- (void)activeForUserInteraction {
    do {
        self.userInteractionEnabled = YES;

        if (self.leftSwipeRecognizer) {
            [self removeGestureRecognizer:self.leftSwipeRecognizer];
            self.leftSwipeRecognizer = nil;
        }

        self.leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(_swiped:)];
        self.leftSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:self.leftSwipeRecognizer];

        if (self.rightSwipeRecognizer) {
            [self removeGestureRecognizer:self.rightSwipeRecognizer];
            self.rightSwipeRecognizer = nil;
        }

        self.rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(_swiped:)];
        self.rightSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:self.rightSwipeRecognizer];
    } while (NO);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    do {
        UITouch *touch = [touches anyObject];
        if (!touch) {
            break;
        }
        NSUInteger tapCount = touch.tapCount;
        if (tapCount > 0) {
            if (self.tapDelegate && [self.tapDelegate respondsToSelector:@selector(view:tapDetected:)]) {
                [self.tapDelegate view:self tapDetected:touch];
            }
        }
    } while (NO);
    [[self nextResponder] touchesEnded:touches withEvent:event];
}

- (void)_swiped:(UISwipeGestureRecognizer *)swipeRecognizer {
    do {
        if (swipeRecognizer != self.leftSwipeRecognizer && swipeRecognizer != self.rightSwipeRecognizer) {
            break;
        }
        if (self.swipeDelegate && [self.swipeDelegate respondsToSelector:@selector(view:swipeDetected:)]) {
            [self.swipeDelegate view:self swipeDetected:swipeRecognizer];
        }
    } while (NO);
}

@end


text:
require "constantinopolis/version"
require "constantinopolis/rails_reloader"
require "yaml"
require "erb"
require "json"

module Constantinopolis
  class Fort
    private_class_method :new

    class << self

      def yml(path = nil)
        return @yml unless path
        Constantinopolis::RailsReloader.register(self, path) if defined? Rails
        @yml = path
      end

      def namespace(namespace = nil)
        @namespace ||= namespace
      end

      def build!
        instance.build_methods!
        instance.build_js!
      end

      def reload!
        @instance = nil
        build!
      end

      def js_code
        instance.js_code
      end

      private

      def instance
        return @instance if @instance
        @instance = new
      end
    end

    # --- Instance methods

    def build_methods!
      @constants.each do |key, value|
        self.class.define_singleton_method key, ->() { value }
      end
    end

    def build_js!
      @js_code = "#{self.class.name}=#{JSON.generate(@constants)};"
    end

    def js_code
      @js_code
    end

    private

    def initialize
      raise "Must locate yaml file!" unless self.class.yml
      file = open(self.class.yml).read
      hash = set_accessor(YAML.unsafe_load(ERB.new(file).result))
      @constants = self.class.namespace ? hash[self.class.namespace.to_s] : hash
    end

    def set_accessor(hash)
      hash.each do |key, value|
        if value.is_a? Hash
          value.extend AccessableHash
          set_accessor value
        end
      end
    end
  end

  module AccessableHash
    def method_missing(name, *args, &block)
      key = name.to_s
      self.has_key?(key) ? self[key] : super
    end
  end
end


text:
using boost::move_detail::cpu_timer;
using boost::move_detail::nanosecond_type;

#include "order_type.hpp"
#include "random_shuffle.hpp"

//#define BOOST_MOVE_ADAPTIVE_SORT_STATS
//#define BOOST_MOVE_ADAPTIVE_SORT_INVARIANTS
void print_stats(const char *str, boost::ulong_long_type element_count)
{
   std::printf("%sCmp:%7.03f Cpy:%8.03f\n", str, double(order_perf_type::num_compare)/element_count, double(order_perf_type::num_copy)/element_count );
}

#include <boost/move/algo/adaptive_sort.hpp>
#include <boost/move/algo/detail/merge_sort.hpp>
#include <boost/move/algo/detail/pdqsort.hpp>
#include <boost/move/algo/detail/heap_sort.hpp>
#include <boost/move/core.hpp>

template<class T>
void generate_elements(boost::container::vector<T> &elements, std::size_t L, std::size_t NK)
{
   elements.resize(L);
   boost::movelib::unique_ptr<std::size_t[]> key_reps(new std::size_t[NK ? NK : L]);

   std::srand(0);
   for (std::size_t i = 0; i < (NK ? NK : L); ++i) {
      key_reps[i] = 0;
   }
   for (std::size_t i = 0; i < L; ++i) {
      std::size_t  key = NK ? (i % NK) : i;
      elements[i].key = key;
   }
   ::random_shuffle(elements.data(), elements.data() + L);
   ::random_shuffle(elements.data(), elements.data() + L);

   for (std::size_t i = 0; i < L; ++i) {
      elements[i].val = key_reps[elements[i].key]++;
   }
}

template<class T, class Compare>
void adaptive_sort_buffered(T *elements, std::size_t element_count, Compare comp, std::size_t BufLen)
{
   boost::movelib::unique_ptr<char[]> mem(new char[sizeof(T)*BufLen]);
   boost::movelib::adaptive_sort(elements, elements + element_count, comp, reinterpret_cast<T*>(mem.get()), BufLen);
}

template<class T, class Compare>
void std_like_adaptive_stable_sort_buffered(T *elements, std::size_t element_count, Compare comp, std::size_t BufLen)
{
   boost::movelib::unique_ptr<char[]> mem(new char[sizeof(T)*BufLen]);
   boost::movelib::stable_sort_adaptive_ONlogN2(elements, elements + element_count, comp, reinterpret_cast<T*>(mem.get()), BufLen);
}

template<class T, class Compare>
void merge_sort_buffered(T *elements, std::size_t element_count, Compare comp)
{
   boost::movelib::unique_ptr<char[]> mem(new char[sizeof(T)*((element_count+1)/2)]);
   boost::movelib::merge_sort(elements, elements + element_count, comp, reinterpret_cast<T*>(mem.get()));
}

enum AlgoType
{
   MergeSort,
   StableSort,
   PdQsort,
   StdSort,
   AdaptiveSort,
   SqrtHAdaptiveSort,
   SqrtAdaptiveSort,
   Sqrt2AdaptiveSort,
   QuartAdaptiveSort,
   InplaceStableSort,
   StdSqrtHAdpSort,
   StdSqrtAdpSort,
   StdSqrt2AdpSort,
   StdQuartAdpSort,
   SlowStableSort,
   HeapSort,
   MaxSort
};

const char *AlgoNames [] = { "MergeSort      "
                           , "StableSort     "
                           , "PdQsort        "
                           , "StdSort        "
                           , "AdaptSort      "
                           , "SqrtHAdaptSort "
                           , "SqrtAdaptSort  "
                           , "Sqrt2AdaptSort "
                           , "QuartAdaptSort "
                           , "InplStableSort "
                           , "StdSqrtHAdpSort"
                           , "StdSqrtAdpSort "
                           , "StdSqrt2AdpSort"
                           , "StdQuartAdpSort"
                           , "SlowSort       "
                           , "HeapSort       "
                           };

BOOST_STATIC_ASSERT((sizeof(AlgoNames)/sizeof(*AlgoNames)) == MaxSort);

template<class T>
bool measure_algo(T *elements, std::size_t element_count, std::size_t alg, nanosecond_type &prev_clock)
{
   std::printf("%s ", AlgoNames[alg]);
   order_perf_type::num_compare=0;
   order_perf_type::num_copy=0;
   order_perf_type::num_elements = element_count;
   cpu_timer timer;
   timer.resume();
   switch(alg)
   {
      case MergeSort:
         merge_sort_buffered(elements, element_count, order_type_less());
      break;
      case StableSort:
         std::stable_sort(elements,elements+element_count,order_type_less());
      break;
      case PdQsort:
         boost::movelib::pdqsort(elements,elements+element_count,order_type_less());
      break;
      case StdSort:
         std::sort(elements,elements+element_count,order_type_less());
      break;
      case AdaptiveSort:
         boost::movelib::adaptive_sort(elements, elements+element_count, order_type_less());
      break;
      case SqrtHAdaptiveSort:
         adaptive_sort_buffered( elements, element_count, order_type_less()
                            , boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count)/2+1);
      break;
      case SqrtAdaptiveSort:
         adaptive_sort_buffered( elements, element_count, order_type_less()
                            , boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count));
      break;
      case Sqrt2AdaptiveSort:
         adaptive_sort_buffered( elements, element_count, order_type_less()
                            , 2*boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count));
      break;
      case QuartAdaptiveSort:
         adaptive_sort_buffered( elements, element_count, order_type_less()
                            , (element_count-1)/4+1);
      break;
      case InplaceStableSort:
         boost::movelib::inplace_stable_sort(elements, elements+element_count, order_type_less());
      break;
      case StdSqrtHAdpSort:
         std_like_adaptive_stable_sort_buffered( elements, element_count, order_type_less()
                                              , boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count)/2+1);
      break;
      case StdSqrtAdpSort:
         std_like_adaptive_stable_sort_buffered( elements, element_count, order_type_less()
                                               , boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count));
      break;
      case StdSqrt2AdpSort:
         std_like_adaptive_stable_sort_buffered( elements, element_count, order_type_less()
                                               , 2*boost::movelib::detail_adaptive::ceil_sqrt_multiple(element_count));
      break;
      case StdQuartAdpSort:
         std_like_adaptive_stable_sort_buffered( elements, element_count, order_type_less()
                                               , (element_count-1)/4+1);
      break;
      case SlowStableSort:
         boost::movelib::detail_adaptive::slow_stable_sort(elements, elements+element_count, order_type_less());
      break;
      case HeapSort:
         boost::movelib::heap_sort(elements, elements+element_count, order_type_less());
         boost::movelib::heap_sort((order_move_type*)0, (order_move_type*)0, order_type_less());

      break;
   }
   timer.stop();

   if(order_perf_type::num_elements == element_count){
      std::printf(" Tmp Ok ");
   } else{
      std::printf(" Tmp KO ");
   }
   nanosecond_type new_clock = timer.elapsed().wall;

   //std::cout << "Cmp:" << order_perf_type::num_compare << " Cpy:" << order_perf_type::num_copy;   //for old compilers without ll size argument
   std::printf("Cmp:%7.03f Cpy:%8.03f", double(order_perf_type::num_compare)/element_count, double(order_perf_type::num_copy)/element_count );

   double time = double(new_clock);

   const char *units = "ns";
   if(time >= 1000000000.0){
      time /= 1000000000.0;
      units = " s";
   }
   else if(time >= 1000000.0){
      time /= 1000000.0;
      units = "ms";
   }
   else if(time >= 1000.0){
      time /= 1000.0;
      units = "us";
   }

   std::printf(" %6.02f%s (%6.02f)\n"
              , time
              , units
              , prev_clock ? double(new_clock)/double(prev_clock): 1.0);
   prev_clock = new_clock;
   bool res = is_order_type_ordered(elements, element_count, alg != HeapSort && alg != PdQsort && alg != StdSort);
   return res;
}

template<class T>
bool measure_all(std::size_t L, std::size_t NK)
{
   boost::container::vector<T> original_elements, elements;
   generate_elements(original_elements, L, NK);
   std::printf("\n - - N: %u, NK: %u - -\n", (unsigned)L, (unsigned)NK);

   nanosecond_type prev_clock = 0;
   nanosecond_type back_clock;
   bool res = true;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,MergeSort, prev_clock);
   back_clock = prev_clock;
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,StableSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,PdQsort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,StdSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,HeapSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,QuartAdaptiveSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L, StdQuartAdpSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,Sqrt2AdaptiveSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L, StdSqrt2AdpSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,SqrtAdaptiveSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L, StdSqrtAdpSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,SqrtHAdaptiveSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L, StdSqrtHAdpSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,AdaptiveSort, prev_clock);
   //
   prev_clock = back_clock;
   elements = original_elements;
   res = res && measure_algo(elements.data(), L,InplaceStableSort, prev_clock);
   //
   //prev_clock = back_clock;
   //elements = original_elements;
   //res = res && measure_algo(elements.data(), L,SlowStableSort, prev_clock);

   if(!res)
      std::abort();
   return res;
}

//Undef it to run the long test
#define BENCH_SORT_SHORT
#define BENCH_SORT_UNIQUE_VALUES

int main()
{
   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(101,1);
   measure_all<order_perf_type>(101,7);
   measure_all<order_perf_type>(101,31);
   #endif
   measure_all<order_perf_type>(101,0);

   //
   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(1101,1);
   measure_all<order_perf_type>(1001,7);
   measure_all<order_perf_type>(1001,31);
   measure_all<order_perf_type>(1001,127);
   measure_all<order_perf_type>(1001,511);
   #endif
   measure_all<order_perf_type>(1001,0);
   //
   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(10001,65);
   measure_all<order_perf_type>(10001,255);
   measure_all<order_perf_type>(10001,1023);
   measure_all<order_perf_type>(10001,4095);
   #endif
   measure_all<order_perf_type>(10001,0);

   //
   #ifdef NDEBUG
   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(100001,511);
   measure_all<order_perf_type>(100001,2047);
   measure_all<order_perf_type>(100001,8191);
   measure_all<order_perf_type>(100001,32767);
   #endif
   measure_all<order_perf_type>(100001,0);

   //
   #ifndef BENCH_SORT_SHORT
   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(1000001, 8192);
   measure_all<order_perf_type>(1000001, 32768);
   measure_all<order_perf_type>(1000001, 131072);
   measure_all<order_perf_type>(1000001, 524288);
   #endif
   measure_all<order_perf_type>(1000001,0);

   #ifndef BENCH_SORT_UNIQUE_VALUES
   measure_all<order_perf_type>(10000001, 65536);
   measure_all<order_perf_type>(10000001, 262144);
   measure_all<order_perf_type>(10000001, 1048576);
   measure_all<order_perf_type>(10000001, 4194304);
   #endif
   measure_all<order_perf_type>(1000001,0);
   #endif   //#ifndef BENCH_SORT_SHORT
   #endif   //NDEBUG

   //measure_all<order_perf_type>(100000001,0);

   return 0;
}


text:
package in

import (
	"github.com/Nyarum/barrel"
	"github.com/Nyarum/noterius/network/common"
)

type EnterWorld struct {
	Name string
}

func (e EnterWorld) Opcode() uint16 {
	return common.OP_CLIENT_BGNPLAY
}

func (e *EnterWorld) Unpack(pr *barrel.Processor) {
	pr.ReadString(&e.Name)
}