text:
/** @constant
 * @description Prefix for all actions within library
 * @type {String}
 * @example
 * import { constants } from 'react-redux-firebase'
 * constants.actionsPrefix === '@@reactReduxFirebase' // true
*/
export const actionsPrefix = '@@reactReduxFirebase/'

/** @constant
 * @description Object containing all action types
 * @type {Object}
 * @example
 * import { actionTypes } from 'react-redux-firebase'
 * actionTypes.SET === '@@reactReduxFirebase/SET' // true
 * @example
 * import { constants } from 'react-redux-firebase'
 * constants.actionTypes.SET === '@@reactReduxFirebase/SET' // true
*/
export const actionTypes = {
  START: `${actionsPrefix}START`,
  SET: `${actionsPrefix}SET`,
  SET_PROFILE: `${actionsPrefix}SET_PROFILE`,
  LOGIN: `${actionsPrefix}LOGIN`,
  LOGOUT: `${actionsPrefix}LOGOUT`,
  LOGIN_ERROR: `${actionsPrefix}LOGIN_ERROR`,
  NO_VALUE: `${actionsPrefix}NO_VALUE`,
  UNAUTHORIZED_ERROR: `${actionsPrefix}UNAUTHORIZED_ERROR`,
  ERROR: `${actionsPrefix}ERROR`,
  INIT_BY_PATH: `${actionsPrefix}INIT_BY_PATH`,
  AUTHENTICATION_INIT_STARTED: `${actionsPrefix}AUTHENTICATION_INIT_STARTED`,
  AUTHENTICATION_INIT_FINISHED: `${actionsPrefix}AUTHENTICATION_INIT_FINISHED`,
  FILE_UPLOAD_START: `${actionsPrefix}FILE_UPLOAD_START`,
  FILE_UPLOAD_ERROR: `${actionsPrefix}FILE_UPLOAD_ERROR`,
  FILE_UPLOAD_PROGRESS: `${actionsPrefix}FILE_UPLOAD_PROGRESS`,
  FILE_UPLOAD_COMPLETE: `${actionsPrefix}FILE_UPLOAD_COMPLETE`,
  FILE_DELETE_START: `${actionsPrefix}FILE_DELETE_START`,
  FILE_DELETE_ERROR: `${actionsPrefix}FILE_DELETE_ERROR`,
  FILE_DELETE_COMPLETE: `${actionsPrefix}FILE_DELETE_COMPLETE`
}

/** @constant
 * @description List of all external auth providers that are supported (firebase's email/anonymous included by default)
 * @type {Array}
 * @private
*/
export const supportedAuthProviders = [
  'google',
  'github',
  'twitter',
  'facebook'
]

/** @constant
 * @description Default keys returned within JSON Web Token recieved when authenticating
 * @type {Array}
 * @private
*/
export const defaultJWTKeys = [
  'aud',
  'auth_time',
  'exp',
  'firebase',
  'iat',
  'iss',
  'sub',
  'user_id'
]

export default {
  defaultJWTKeys,
  actionTypes,
  supportedAuthProviders
}

module.exports = {
  defaultJWTKeys,
  actionTypes,
  supportedAuthProviders
}


text:
import subprocess
import os
import time
import utils
import socket
import threading

import agent
import rpc_server
from galaxy import sdk
from nose import tools

CASE_TMP_FOLDER = os.sep.join([os.environ.get("GALAXY_CASE_FOLDER"),"case_node_test"])
MASTER_BIN_PATH = os.environ.get("MASTER_BIN_PATH")
MASTER_PORT = 11059
AGENT_PORT = 13460
def setup():
    global master_ctrl
    global package
    global server
    master_ctrl = utils.MasterCtrl(MASTER_BIN_PATH,CASE_TMP_FOLDER,MASTER_PORT)
    ret = master_ctrl.start()
    if not ret :
        print "fail to start master"
        assert False
    time.sleep(1)
    mock_agent = agent.AgentImpl(8.0,1024*1024*1024*10,AGENT_PORT,"127.0.0.1:%d"%MASTER_PORT)
    heartbeat_t = threading.Thread(target=mock_agent.HeartBeat)
    heartbeat_t.daemon = True
    heartbeat_t.start()
    server = rpc_server.RpcServer(AGENT_PORT,host="0.0.0.0")
    server.add_service(mock_agent)
    server_t = threading.Thread(target=server.start)
    server_t.daemon = True
    server_t.start()
    time.sleep(2)

def test_list_node():
    client = sdk.GalaxySDK("127.0.0.1:%d"%MASTER_PORT)
    node_list = client.list_all_node()
    assert len(node_list) == 1

def teardown():
    status,output,stderr = master_ctrl.stop()
    server.stop()
    if os.path.exists(CASE_TMP_FOLDER):
        utils.ShellHelper.run_with_returncode("rm -rf %s"%CASE_TMP_FOLDER)

redpajama_set_name: RedPajamaGithub


text:
TypingTest
==========

Custom typing test


text:
import { fetchHTTP, debounce, getPosition } from '../core/common.js';
import { isEmpty } from '../core/codemirror/tools.js';
import { isNormalBlock, isColorBlock, getAddressSceneContent, getKeysFromAddress, getAddressFromKeys } from '../core/codemirror/yaml-tangram.js';

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

// Debounced event after user stop doing something
var stopAction = debounce(function(cm) {
    cm.widgets_manager.rebuild();
    if (cm.glsl_sandbox.active) {
        cm.glsl_sandbox.update_changes(cm.getCursor().line);
    }
}, 1000);

export default class GlslSandbox {
    constructor (tangram_play, configFile ) {

    	//  Make link to this manager inside codemirror obj to be excecuted from CM events
        tangram_play.editor.glsl_sandbox = this;

        //  private variables
        this.tangram_play = tangram_play;

        //	used variables
        this.active = false;
        this.sandbox = undefined;
        this.line = -1;
        this.animated = false;
        this.color = [1,0,0];

        this.element = document.createElement('div');
        this.element.id = 'tp-a-sandbox';
        this.element.setAttribute("width","130");
        this.element.setAttribute("height","130");

        this.canvas = document.createElement('canvas');
        this.canvas.id = 'tp-a-sandbox-canvas';
        this.canvas.className = 'glsl_sandbox';
        this.canvas.setAttribute("width","130");
        this.canvas.setAttribute("height","130");
        this.canvas.setAttribute("data-fragment","void main() {\ngl_FragColor = vec4(1.0,0.0,1.0,1.0);\n}");
        this.element.appendChild(this.canvas);

        let el = document.createElement('div');
        el.id = 'tp-a-sandbox-colorpicker';
        el.style.background = '#FF0000';
        el.addEventListener('click', function (e) {
            let picker = new thistle.Picker(el.style.background);
            let pos = getPosition(el);

            picker.presentModal(pos.x+20,
                                tangram_play.editor.heightAtLine( tangram_play.editor.glsl_sandbox.line )-16);

            picker.on('changed', function() {
                el.style.background = picker.getCSS();
                let color = picker.getRGB();
                tangram_play.editor.tangram_play.addons.glsl_sandbox.setColor([color.r,color.g,color.b]);
            });
        });
        this.element.appendChild(el);

        // Suggestions are trigged by the folowing CM events
        tangram_play.editor.on("cursorActivity", function(cm) {
            cm.glsl_sandbox.update();
        });

        tangram_play.editor.on("changes", function(cm, changesObj) {
            stopAction(cm);
        });
    }

    update() {
    	let pos = this.tangram_play.editor.getCursor();
        if (pos.ch < 16) {
            if (this.active) {
                this.disable();
            }
        } else if (pos.line !== this.line) {
    		this.line = pos.line;
    		this.update_changes(pos.line);
    	}
    }

    update_changes(nLine) {

        if (!isEmpty(this.tangram_play.editor,nLine)){
            let keys = this.tangram_play.getKeysOnLine(nLine);
            if (keys && keys[0]){
                let address = keys[0].address;
                let shaderObj = this._getShaderObj(address);

                if (shaderObj===undefined) {
                    if (this.active) this.element.parentNode.removeChild(this.element);
                    this.active = false;
                    return;
                }

                this.animated = shaderObj.animated;

                if (isNormalBlock(address)){
                    this.tangram_play.editor.addWidget( {line: nLine, ch: 0} , this.element);

                    if (!this.active) {
                        this.sandbox = new GlslCanvas(this.canvas);
                    }

                    let fragmentCode =  this._getHeaderTemplate(address) +
                                        // this._getBlockUntilLine(address, nLine) +
                                        getAddressSceneContent(this.tangram_play.scene, address) +
                                        this._getNormalEnding();

                    this.sandbox.load(fragmentCode, this._getVertex(address));

                    if (!this.active) {
                        this.active = true;
                        this._frame();
                    }
                } else if (isColorBlock(address)){
                    this.tangram_play.editor.addWidget( {line: nLine, ch: 0} , this.element);

                    if (!this.active) {
                        this.sandbox = new GlslCanvas(this.canvas);
                    }

                    let block_normal = "\n"
                    if (shaderObj.shaders.blocks.normal) {
                        for (let i = 0; i < shaderObj.shaders.blocks.normal.length; i++){
                            block_normal += shaderObj.shaders.blocks.normal[i] + "\n";
                        }
                    }

                    let fragmentCode =  this._getHeaderTemplate(address) +
                                        block_normal +
                                        // this._getBlockUntilLine(address, line) +
                                        getAddressSceneContent(this.tangram_play.scene, address) +
                                        this._getColorEnding();

                    this.sandbox.load(fragmentCode, this._getVertex(address));

                    if (!this.active) {
                        this.active = true;
                        this._frame();
                    }
                } else {
                    this.disable();
                }

                if (this.active) {
                    if (shaderObj.material) {
                        for (let el in shaderObj.material) {
                            if (!Array.isArray(shaderObj.material[el]) && shaderObj.material[el].texture ){
                                this.sandbox.setUniform("u_material_"+el+"_texture", shaderObj.material[el].texture);
                                this.sandbox.setUniform("u_material."+el+"Scale",shaderObj.material[el].scale);
                            }
                        }
                    }
                }
            }
        } else {
            this.disable();
        }
    }

    setColor(colorArray) {
        this.color = colorArray;
    }

    disable() {
        if (this.active) {
            this.element.parentNode.removeChild(this.element);
        }
        this.active = false;
    }

    _frame() {
    	if (this.active) { // && this.animated) {
			this.sandbox.setUniform("u_meters_per_pixel",this.tangram_play.scene.meters_per_pixel);
			this.sandbox.setUniform("u_device_pixel_ratio",window.devicePixelRatio);
			this.sandbox.setUniform("u_map_position", [this.tangram_play.scene.center_meters.x, this.tangram_play.scene.center_meters.y, this.tangram_play.scene.zoom]);
			this.sandbox.setUniform("u_tile_origin", [this.tangram_play.scene.center_tile.x, this.tangram_play.scene.center_tile.y, this.tangram_play.scene.center_tile.z]);
			this.sandbox.setUniform("u_vanishing_point", this.tangram_play.scene.camera.vanishing_point);
            this.sandbox.setUniform("u_color",this.color);

			this.sandbox.render();
			requestAnimationFrame(function(){
				tangramPlay.editor.glsl_sandbox._frame();
			}, 1000 / 30);
    	}
    }

    _getBlockUntilLine(address, nLine) {
        let from = this.tangram_play.getKeyForAddress(address).pos.line+1;
        let to = nLine+1;

        let block = "\n";
        for (let i = from; i < to; i++) {
            block += this.tangram_play.editor.getLine(i);
        }

        let nP = getNumberOfOpenParentesis(block);
        for (let i = 0; i < nP; i++) {
            block += "}\n";
        }
        return block;
    }

    _getShaderObj(address) {
    	let keysToShader = getKeysFromAddress(address);
		return this.tangram_play.scene.styles[keysToShader[1]];
    }

    _getVertex(address) {
    	let header = `
    	#ifdef GL_ES
    	precision mediump float;
    	#endif

		uniform vec2 u_resolution;
		uniform vec2 u_mouse;
		uniform float u_time;
		uniform float u_meters_per_pixel;
		uniform float u_device_pixel_ratio;

		uniform vec3 u_map_position;
		uniform vec3 u_tile_origin;

        uniform vec3 u_color;

		vec3 u_eye = vec3(1.0);
		uniform vec2 u_vanishing_point;

		attribute vec3 a_position;
		attribute vec2 a_texcoord;

		varying vec2 v_texcoord;
		varying vec3 v_world_position;
		`

		let shaderObj = this._getShaderObj(address);

		let block_global = "\n";
		if (shaderObj.shaders.blocks.global) {
			for (let i = 0; i < shaderObj.shaders.blocks.global.length; i++){
				block_global += shaderObj.shaders.blocks.global[i] + "\n";
			}
		}

		let core = `
		void main() {
			vec4 position = vec4(a_position.xy, 0.0, 1.0);
		 	v_texcoord = a_texcoord;
		 	v_world_position = u_map_position*0.001;
		 	v_world_position.xy += (a_texcoord*u_meters_per_pixel);
		 	v_world_position.xy *= 100.;
		 `;

		let block_position = "\n";
		if (shaderObj.shaders.blocks.position) {
			for (let i = 0; i < shaderObj.shaders.blocks.position.length; i++){
				block_position += shaderObj.shaders.blocks.position[i] + "\n";
			}
		}

		let ending = `
			gl_Position = position;
		}
    	`;

    	return header + block_global + core + block_position + ending;
    }

    _getHeaderTemplate(address) {
    	let shaderObj = this._getShaderObj(address);

    	let defines = "\n";
    	for(let name in shaderObj.defines){
    		if (shaderObj.defines[name]) {
    			defines += "#define " + name + (shaderObj.defines[name] === true ? "\n" : " " + shaderObj.defines[name] + "\n");
    		}
    	}

    	// if (shaderObj.base && shaderObj.base === "polygons"){
    	// 	defines += "#define SPHERE\n";
    	// }

    	let block_material = "\n";
		if (shaderObj.shaders.blocks.material) {
			for (let i = 0; i < shaderObj.shaders.blocks.material.length; i++){
				block_material += shaderObj.shaders.blocks.material[i] + "\n";
			}
		}

		let header = `
			#ifdef GL_ES
			precision mediump float;
			#endif

			uniform vec2 u_resolution;
			uniform vec2 u_mouse;
			uniform float u_time;
			uniform float u_meters_per_pixel;
			uniform float u_device_pixel_ratio;

			uniform vec3 u_map_position;
			uniform vec3 u_tile_origin;

            uniform vec3 u_color;

			varying vec2 v_texcoord;
			varying vec3 v_world_position;

			vec3 u_eye = vec3(1.0);
			uniform vec2 u_vanishing_point;

			vec3 v_normal = vec3(0.0,0.0,1.0);
			vec4 v_color = vec4(1.0,0.0,1.0,1.0);

			vec3 hsb2rgb( in vec3 c ){
			    vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0),
			                             6.0)-3.0)-1.0,
			                     0.0,
			                     1.0 );
			    rgb = rgb*rgb*(3.0-2.0*rgb);
			    return c.z * mix( vec3(1.0), rgb, c.y);
			}

			#ifdef SPHERE
			vec3 sphereNormal(vec2 uv) {
			    uv = fract(uv)*2.0-1.0;
			    vec3 ret;
			    ret.xy = sqrt(uv * uv) * sign(uv);
			    ret.z = sqrt(abs(1.0 - dot(ret.xy,ret.xy)));
			    return ret * 0.5 + 0.5;
			}

			vec2 sphereCoords(vec2 _st, float _scale){
			    float maxFactor = sin(1.570796327);
			    vec2 uv = vec2(0.0);
			    vec2 xy = 2.0 * _st.xy - 1.0;
			    float d = length(xy);
			    if (d < (2.0-maxFactor)){
			        d = length(xy * maxFactor);
			        float z = sqrt(1.0 - d * d);
			        float r = atan(d, z) / 3.1415926535 * _scale;
			        float phi = atan(xy.y, xy.x);

			        uv.x = r * cos(phi) + 0.5;
			        uv.y = r * sin(phi) + 0.5;
			    } else {
			        uv = _st.xy;
			    }
			    return uv;
			}
			#endif
		`;

		let block_global = "\n";
		if (shaderObj.shaders.blocks.global) {
			for (let i = 0; i < shaderObj.shaders.blocks.global.length; i++){
				block_global += shaderObj.shaders.blocks.global[i] + "\n";
			}
		}

		let pre = `
			void main() {
				#ifdef SPHERE
				v_normal = sphereNormal(v_texcoord);
				#endif

				vec3 normal = v_normal;

				#ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE
			        calculateNormal(normal);
			    #endif

				vec2 TEMPLATE_ST = v_texcoord.xy;

				#ifdef SPHERE
				TEMPLATE_ST = sphereCoords(TEMPLATE_ST,1.0);
				#endif

                v_color.rgb = u_color;
			    //v_color.rgb = hsb2rgb(vec3(fract(u_time*0.01),1.,1.));

			    #ifdef SPHERE
				v_color = mix(v_color, vec4(0.),
							  step(.25,dot(vec2(0.5)-v_texcoord,vec2(0.5)-v_texcoord)) );
				#endif

				vec4 color = v_color;
			`;

		return defines + header + block_material + block_global + pre;
    }

    _getNormalEnding() {
    	return `
			gl_FragColor = vec4(normal,1.0);
		}
		`;
	}

    _getColorEnding() {
	    return `
			gl_FragColor = color;
		}
		`;
    }
}

function getNumberOfOpenParentesis(str) {
    let counter = 0;
    for (let i = 0; i < str.length; i++){
        if ( str[i] === "{" ){
            counter++;
        } else if ( str[i] === "}" ){
            counter--;
        }
    }
    return counter;
};


text:
from selenium import webdriver
from bs4 import BeautifulSoup
import pygal

__author__ = "Laird Streak"

def fetch_WH_dailies():
    url = "http://www.wowhead.com/world-quests/na"
    driver = webdriver.PhantomJS()#(executable_path="./driver/phantomjs")
    driver.get(url)
    content_data = driver.page_source
    soup = BeautifulSoup(content_data, "html.parser")
    print(soup.prettify())

if __name__ == '__main__':
    fetch_WH_dailies()


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

<title>Using the GNU Compiler Collection (GCC): Epiphany Function Attributes</title>

<meta name="description" content="Using the GNU Compiler Collection (GCC): Epiphany Function Attributes">
<meta name="keywords" content="Using the GNU Compiler Collection (GCC): Epiphany Function Attributes">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Function-Attributes.html#Function-Attributes" rel="up" title="Function Attributes">
<link href="H8_002f300-Function-Attributes.html#H8_002f300-Function-Attributes" rel="next" title="H8/300 Function Attributes">
<link href="CR16-Function-Attributes.html#CR16-Function-Attributes" rel="prev" title="CR16 Function Attributes">

Next: H8/300 Function Attributes, Previous: CR16 Function Attributes, Up: Function Attributes   [Contents][Index]

6.31.8 Epiphany Function Attributes

These function attributes are supported by the Epiphany back end:

disinterrupt

This attribute causes the compiler to emit
instructions to disable interrupts for the duration of the given
function.

forwarder_section

This attribute modifies the behavior of an interrupt handler.
The interrupt handler may be in external memory which cannot be
reached by a branch instruction, so generate a local memory trampoline
to transfer control.  The single parameter identifies the section where
the trampoline is placed.

interrupt

Use this attribute to indicate
that the specified function is an interrupt handler.  The compiler generates
function entry and exit sequences suitable for use in an interrupt handler
when this attribute is present.  It may also generate
a special section with code to initialize the interrupt vector table.

On Epiphany targets one or more optional parameters can be added like this:

void __attribute__ ((interrupt ("dma0, dma1"))) universal_dma_handler ();

Permissible values for these parameters are: reset,
software_exception, page_miss,
timer0, timer1, message,
dma0, dma1, wand and swi.
Multiple parameters indicate that multiple entries in the interrupt
vector table should be initialized for this function, i.e. for each
parameter <var>name</var>, a jump to the function is emitted in
the section ivt_entry_<var>name</var>.  The parameter(s) may be omitted
entirely, in which case no interrupt vector table entry is provided.

Note that interrupts are enabled inside the function
unless the disinterrupt attribute is also specified.

The following examples are all valid uses of these attributes on
Epiphany targets:

void __attribute__ ((interrupt)) universal_handler ();
void __attribute__ ((interrupt ("dma1"))) dma1_handler ();
void __attribute__ ((interrupt ("dma0, dma1")))
  universal_dma_handler ();
void __attribute__ ((interrupt ("timer0"), disinterrupt))
  fast_timer_handler ();
void __attribute__ ((interrupt ("dma0, dma1"),
                     forwarder_section ("tramp")))
  external_dma_handler ();

long_call

short_call

These attributes specify how a particular function is called.
These attributes override the
<samp>-mlong-calls</samp> (see Adapteva Epiphany Options)
command-line switch and #pragma long_calls settings.

Next: H8/300 Function Attributes, Previous: CR16 Function Attributes, Up: Function Attributes   [Contents][Index]


text:
package com.amazonaws.services.keyspaces.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.keyspaces.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * PointInTimeRecoverySummaryMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class PointInTimeRecoverySummaryMarshaller {

    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();
    private static final MarshallingInfo<java.util.Date> EARLIESTRESTORABLETIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("earliestRestorableTimestamp").timestampFormat("unixTimestamp").build();

    private static final PointInTimeRecoverySummaryMarshaller instance = new PointInTimeRecoverySummaryMarshaller();

    public static PointInTimeRecoverySummaryMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(PointInTimeRecoverySummary pointInTimeRecoverySummary, ProtocolMarshaller protocolMarshaller) {

        if (pointInTimeRecoverySummary == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(pointInTimeRecoverySummary.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(pointInTimeRecoverySummary.getEarliestRestorableTimestamp(), EARLIESTRESTORABLETIMESTAMP_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
import os
import tempfile
import requests

try:
    # pylint: disable=E0611
    from urlparse import urlunsplit
    from urllib import urlencode
except ImportError:
    # pylint: disable=E0611
    from urllib.parse import urlunsplit, urlencode

from talkey.base import AbstractTTSEngine, register
from talkey.utils import check_network_connection

@register
class MaryTTS(AbstractTTSEngine):
    """
    Uses the MARY Text-to-Speech System (MaryTTS)
    MaryTTS is an open-source, multilingual Text-to-Speech Synthesis platform
    written in Java.
    Please specify your own server instead of using the demonstration server
    (http://mary.dfki.de:59125/) to save bandwidth and to protect your privacy.
    """

    SLUG = "mary"

    @classmethod
    def _get_init_options(cls):
        return {
            'enabled': {
                'description': 'Is enabled?',
                'type': 'bool',
                'default': False,
            },
            'scheme': {
                'description': 'HTTP schema',
                'type': 'enum',
                'default': 'http',
                'values': ['http', 'https'],
            },
            'host': {
                'description': 'Mary server address',
                'type': 'str',
                'default': '127.0.0.1',
            },
            'port': {
                'description': 'Mary server port',
                'type': 'int',
                'default': 59125,
                'min': 1,
                'max': 65535,
            }
        }

    def _makeurl(self, path, query={}):
        query_s = urlencode(query)
        urlparts = (self.ioptions['scheme'], self.ioptions['host'] + ':' + str(self.ioptions['port']), path, query_s, '')
        return urlunsplit(urlparts)

    def _is_available(self):
        return check_network_connection(self.ioptions['host'], self.ioptions['port'])

    def _get_options(self):
        return {}

    def _get_languages(self):
        res = requests.get(self._makeurl('voices'), timeout=5).text
        langs = {}
        for voice in [row.split() for row in res.split('\n') if row]:
            lang = voice[1].split('_')[0]
            langs.setdefault(lang, {'default': voice[0], 'voices': {}})
            langs[lang]['voices'][voice[0]] = {
                'gender': voice[2],
                'locale': voice[1]
            }
        return langs

    def _say(self, phrase, language, voice, voiceinfo, options):
        query = {'OUTPUT_TYPE': 'AUDIO',
                 'AUDIO': 'WAVE_FILE',
                 'INPUT_TYPE': 'TEXT',
                 'INPUT_TEXT': phrase,
                 'LOCALE': voiceinfo['locale'],
                 'VOICE': voice}

        res = requests.get(self._makeurl('/process', query=query), timeout=5)
        with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
            f.write(res.content)
            tmpfile = f.name
        self.play(tmpfile)
        os.remove(tmpfile)


text: gXMLBuffer="<?xml version=\"1.0\" encoding=\"utf-8\" ?><MasterProject/>";


text:
package de.micromata.jira.rest.core.domain;

import com.google.gson.annotations.Expose;

public class AggregateprogressBean {

    @Expose
    private Integer percent;
    @Expose
    private Integer progress;
    @Expose
    private Integer total;

    public Integer getPercent() {
        return percent;
    }

    public void setPercent(Integer percent) {
        this.percent = percent;
    }

    public Integer getProgress() {
        return progress;
    }

    public void setProgress(Integer progress) {
        this.progress = progress;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}


text:
class CfgWeapons {
    class ACE_adenosine;
    class GVAR(vital): ACE_adenosine {
        author = "diwako";
        displayName = "Vital Autoinjector";
        descriptionShort = "Used to revive people quickly";
        descriptionUse = "A drug to push someone's vitals to acceptable levels for them to wake up";
    };
};


text:
from django.db.models.query_utils import Q
from django.core.cache import cache
from django.db import models
import operator
import random
from datetime import timedelta
from django_facebook.utils import compatible_datetime as datetime
from django.contrib.contenttypes.models import ContentType
import logging
from open_facebook.exceptions import OAuthException, UnsupportedDeleteRequest
logger = logging.getLogger(__name__)

class FacebookUserManager(models.Manager):

    def find_users(self, queries, base_queryset=None):
        '''
        Queries, a list of search queries
        Base Queryset, the base queryset in which we are searching
        '''
        if base_queryset is None:
            base_queryset = self.all()
        filters = []
        for query in queries:
            match = Q(
                name__istartswith=query) | Q(name__icontains=' %s' % query)
            filters.append(match)

        users = base_queryset.filter(reduce(operator.and_, filters))

        return users

    def random_facebook_friends(self, user, gender=None, limit=3):
        '''
        Returns a random sample of your FB friends

        Limit = Number of friends
        Gender = None, M or F
        '''
        assert gender in (
            None, 'M', 'F'), 'Gender %s wasnt recognized' % gender

        from django_facebook.utils import get_profile_model
        facebook_cache_key = 'facebook_users_%s' % user.id
        non_members = cache.get(facebook_cache_key)
        profile_class = get_profile_model()
        if not non_members:
            facebook_users = list(
                self.filter(user_id=user.id, gender=gender)[:50])
            facebook_ids = [u.facebook_id for u in facebook_users]
            members = list(profile_class.objects.filter(
                facebook_id__in=facebook_ids).select_related('user'))
            member_ids = [p.facebook_id for p in members]
            non_members = [
                u for u in facebook_users if u.facebook_id not in member_ids]

            cache.set(facebook_cache_key, non_members, 60 * 60)

        random_limit = min(len(non_members), 3)
        random_facebook_users = []
        if random_limit:
            random_facebook_users = random.sample(non_members, random_limit)

        return random_facebook_users

class OpenGraphShareManager(models.Manager):

    def failed(self):
        qs = self.filter(completed_at__isnull=True)
        return qs

    def recently_failed(self):
        from django_facebook import settings as facebook_settings
        now = datetime.now()
        recent_delta = timedelta(
            days=facebook_settings.FACEBOOK_OG_SHARE_RETRY_DAYS)
        recent = now - recent_delta
        failed = self.failed()
        recently_failed = failed.filter(created_at__gte=recent)
        return recently_failed

    def shares_for_instance(self, instance, user):
        content_type = ContentType.objects.get_for_model(instance)
        shares = self.filter(
            user=user,
            object_id=instance.id,
            content_type=content_type,
            completed_at__isnull=False,
            removed_at__isnull=True,
        )
        return shares

    def remove_shares_for_instance(self, content_object, user):
        '''
        Removes all shares for this content_object and user combination
        '''
        shares = self.shares_for_instance(content_object, user)
        shares = shares.filter(
            completed_at__isnull=False, removed_at__isnull=True)
        shares = list(shares[:1000])
        logger.info('found %s shares to remove', len(shares))
        for share in shares:
            logger.info('removed share %s', share)
            try:
                share.remove()
            except (OAuthException, UnsupportedDeleteRequest) as e:
                # oauth exceptions happen when tokens are removed
                # unsupported delete requests when the resource is already
                # removed
                logger.info('removing share failed, got error %s', e)


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

namespace Backlog4net.Api
{
    using Option;

    /// <summary>
    /// Executes Backlog Watch APIs.
    /// </summary>
    public interface WatchingMethods
    {
        /// <summary>
        /// Returns the Watch.
        /// </summary>
        /// <param name="watchingId">watchingId</param>
        /// <returns>the Watch</returns>
        Task<Watch> GetWatchAsync(long watchingId, CancellationToken? token = null);

        /// <summary>
        /// Adds a watching to the issue.
        /// </summary>
        /// <param name="issueIdOrKey">the issue identifier</param>
        /// <param name="note">note</param>
        /// <returns></returns>
        Task<Watch> AddWatchToIssueAsync(IdOrKey issueIdOrKey, String note, CancellationToken? token = null);

        /// <summary>
        /// Updates the existing watching.
        /// </summary>
        /// <param name="params">the updating project parameters</param>
        /// <returns>the updated Watching</returns>
        Task<Watch> UpdateWatchAsync(UpdateWatchParams @params, CancellationToken? token = null);

        /// <summary>
        /// Deletes the existing watching.
        /// </summary>
        /// <param name="watchingId">the watching identifier</param>
        /// <returns>the deleted watching</returns>
        Task<Watch> DeleteWatchAsync(long watchingId, CancellationToken? token = null);

        /// <summary>
        /// Marks the watching as already read.
        /// </summary>
        /// <param name="numericUserId">Marks the watching as already read.</param>
        Task MarkAsCheckedUserWatchesAsync(long numericUserId, CancellationToken? token = null);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectCodeStyleSettingsManager">
    <option name="PER_PROJECT_SETTINGS">
      <value>
        <option name="RIGHT_MARGIN" value="80" />
        <option name="WRAP_COMMENTS" value="true" />
        <XML>
          <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
        </XML>
        <codeStyleSettings language="JAVA">
          <option name="KEEP_LINE_BREAKS" value="false" />
          <option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false" />
          <option name="ALIGN_MULTILINE_THROWS_LIST" value="true" />
          <option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
          <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
          <option name="CALL_PARAMETERS_WRAP" value="5" />
          <option name="CALL_PARAMETERS_LPAREN_ON_NEXT_LINE" value="true" />
          <option name="CALL_PARAMETERS_RPAREN_ON_NEXT_LINE" value="true" />
          <option name="METHOD_PARAMETERS_WRAP" value="1" />
          <option name="EXTENDS_LIST_WRAP" value="1" />
          <option name="THROWS_LIST_WRAP" value="1" />
          <option name="EXTENDS_KEYWORD_WRAP" value="1" />
          <option name="THROWS_KEYWORD_WRAP" value="1" />
          <option name="METHOD_CALL_CHAIN_WRAP" value="5" />
          <option name="BINARY_OPERATION_WRAP" value="1" />
          <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
          <option name="TERNARY_OPERATION_WRAP" value="5" />
          <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
          <option name="FOR_STATEMENT_WRAP" value="5" />
          <option name="ARRAY_INITIALIZER_WRAP" value="5" />
          <option name="ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE" value="true" />
          <option name="ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE" value="true" />
          <option name="ASSERT_STATEMENT_WRAP" value="1" />
          <option name="ASSERT_STATEMENT_COLON_ON_NEXT_LINE" value="true" />
          <option name="WRAP_LONG_LINES" value="true" />
          <option name="ENUM_CONSTANTS_WRAP" value="2" />
        </codeStyleSettings>
      </value>
    </option>
    <option name="PREFERRED_PROJECT_CODE_STYLE" value="Ethan" />
  </component>
</project>


text:
The compilation process is described on the official Angular2 website here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

Note that you also have to include bootstrap CSS from the official Bootrstrap site or Bootstrap CDN in your index.html HEAD section.

#### 1) Install `ng2-bootstrap`

```bash
npm install ng2-bootstrap bootstrap --save
```

#### 2) Edit Angular 2 module

Open the module file where you want to include ng2-bootstrap (most probably `app.module.ts`) and import either specific ng2-bootstrap modules by listing them in the import statement and then in the import array of the Angular 2 module

```typescript
import { AlertModule, ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
...

@NgModule({
   ...
   imports: [AlertModule, ModalModule, ... ],
   ...
})
```

 or use Ng2BootstrapModule to import all of the modules at once:

```typescript
import { Ng2BootstrapModule } from 'ng2-bootstrap/ng2-bootstrap';
...

@NgModule({
   ...
   imports: [Ng2BootstrapModule, ... ],
   ...
})
```

#### 3) Edit rollup configuration (rollup-config.js)

You have to use CommonJS rollup plugin, which you should be using anyway due to RxJS. If for some reason not, install it:

```bash
npm install rollup-plugin-commonjs --save --dev
```

Then you have to import the CommonJS plugin, include it in the plugins array and add ng2-bootstrap to the list of modules:

```javascript
...
import commonjs from 'rollup-plugin-commonjs';
...

//paths are relative to the execution path
export default {
	...
	plugins: [
		...
		commonjs({
			include: [
				'node_modules/rxjs/**',
				'node_modules/ng2-bootstrap/**'
			]
		}),
		...
	]
}
```

#### 4) Run compilation the standard way

e.g.

```bash
ngc -p tsconfig-aot.json
rollup -c rollup-config.js
```


text:
using namespace chrono;

void ChConstraintBilateral::Build_b() {
    std::vector<ChConstraint*>& mconstraints = data_manager->system_descriptor->GetConstraintsList();

#pragma omp parallel for
    for (int index = 0; index < (signed)data_manager->num_bilaterals; index++) {
        int cntr = data_manager->host_data.bilateral_mapping[index];
        ChConstraintTwoBodies* mbilateral = (ChConstraintTwoBodies*)(mconstraints[cntr]);
        data_manager->host_data.b[index + data_manager->num_unilaterals] = mbilateral->Get_b_i();
    }
}

void ChConstraintBilateral::Build_E() {
#pragma omp parallel for
    for (int index = 0; index < (signed)data_manager->num_bilaterals; index++) {
        data_manager->host_data.E[index + data_manager->num_unilaterals] = 0;
    }
}

void ChConstraintBilateral::Build_D() {
    LOG(INFO) << "ChConstraintBilateral::Build_D";
    // Grab the list of all bilateral constraints present in the system
    // (note that this includes possibly inactive constraints)
    std::vector<ChConstraint*>& mconstraints = data_manager->system_descriptor->GetConstraintsList();

    // Loop over the active constraints and fill in the rows of the Jacobian,
    // taking into account the type of each constraint.
    SubMatrixType D_b_T = _DBT_;

    const CompressedMatrix<real>& M_inv = data_manager->host_data.M_inv;

    //#pragma omp parallel for
    for (int index = 0; index < (signed)data_manager->num_bilaterals; index++) {
        int cntr = data_manager->host_data.bilateral_mapping[index];
        int type = data_manager->host_data.bilateral_type[cntr];
        int row = index;

        switch (type) {
            case BilateralType::BODY_BODY: {
                ChConstraintTwoBodies* mbilateral = (ChConstraintTwoBodies*)(mconstraints[cntr]);

                int idA = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_a()))->GetUserData())->GetId();
                int idB = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_b()))->GetUserData())->GetId();
                int colA = idA * 6;
                int colB = idB * 6;

                D_b_T(row, colA + 0) = mbilateral->Get_Cq_a()->GetElementN(0);
                D_b_T(row, colA + 1) = mbilateral->Get_Cq_a()->GetElementN(1);
                D_b_T(row, colA + 2) = mbilateral->Get_Cq_a()->GetElementN(2);

                D_b_T(row, colA + 3) = mbilateral->Get_Cq_a()->GetElementN(3);
                D_b_T(row, colA + 4) = mbilateral->Get_Cq_a()->GetElementN(4);
                D_b_T(row, colA + 5) = mbilateral->Get_Cq_a()->GetElementN(5);

                D_b_T(row, colB + 0) = mbilateral->Get_Cq_b()->GetElementN(0);
                D_b_T(row, colB + 1) = mbilateral->Get_Cq_b()->GetElementN(1);
                D_b_T(row, colB + 2) = mbilateral->Get_Cq_b()->GetElementN(2);

                D_b_T(row, colB + 3) = mbilateral->Get_Cq_b()->GetElementN(3);
                D_b_T(row, colB + 4) = mbilateral->Get_Cq_b()->GetElementN(4);
                D_b_T(row, colB + 5) = mbilateral->Get_Cq_b()->GetElementN(5);
            } break;

            case BilateralType::SHAFT_SHAFT: {
                ChConstraintTwoGeneric* mbilateral = (ChConstraintTwoGeneric*)(mconstraints[cntr]);

                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();

                int colA = data_manager->num_rigid_bodies * 6 + idA;
                int colB = data_manager->num_rigid_bodies * 6 + idB;

                D_b_T(row, colA) = mbilateral->Get_Cq_a()->GetElementN(0);
                D_b_T(row, colB) = mbilateral->Get_Cq_b()->GetElementN(0);
            } break;

            case BilateralType::SHAFT_BODY: {
                ChConstraintTwoGeneric* mbilateral = (ChConstraintTwoGeneric*)(mconstraints[cntr]);

                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_b()))->GetUserData())->GetId();

                int colA = data_manager->num_rigid_bodies * 6 + idA;
                int colB = idB * 6;

                D_b_T(row, colA) = mbilateral->Get_Cq_a()->GetElementN(0);

                D_b_T(row, colB + 0) = mbilateral->Get_Cq_b()->GetElementN(0);
                D_b_T(row, colB + 1) = mbilateral->Get_Cq_b()->GetElementN(1);
                D_b_T(row, colB + 2) = mbilateral->Get_Cq_b()->GetElementN(2);

                D_b_T(row, colB + 3) = mbilateral->Get_Cq_b()->GetElementN(3);
                D_b_T(row, colB + 4) = mbilateral->Get_Cq_b()->GetElementN(4);
                D_b_T(row, colB + 5) = mbilateral->Get_Cq_b()->GetElementN(5);
            } break;

            case BilateralType::SHAFT_SHAFT_SHAFT: {
                ChConstraintThreeGeneric* mbilateral = (ChConstraintThreeGeneric*)(mconstraints[cntr]);
                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();
                int idC = ((ChVariablesShaft*)(mbilateral->GetVariables_c()))->GetShaft()->GetId();

                int colA = data_manager->num_rigid_bodies * 6 + idA;
                int colB = data_manager->num_rigid_bodies * 6 + idB;
                int colC = data_manager->num_rigid_bodies * 6 + idC;

                D_b_T(row, colA) = mbilateral->Get_Cq_a()->GetElementN(0);
                D_b_T(row, colB) = mbilateral->Get_Cq_b()->GetElementN(0);
                D_b_T(row, colC) = mbilateral->Get_Cq_c()->GetElementN(0);
            } break;

            case BilateralType::SHAFT_SHAFT_BODY: {
                ChConstraintThreeGeneric* mbilateral = (ChConstraintThreeGeneric*)(mconstraints[cntr]);
                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();
                int idC = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_c()))->GetUserData())->GetId();

                int colA = data_manager->num_rigid_bodies * 6 + idA;
                int colB = data_manager->num_rigid_bodies * 6 + idB;
                int colC = idC * 6;

                D_b_T(row, colA) = mbilateral->Get_Cq_a()->GetElementN(0);
                D_b_T(row, colB) = mbilateral->Get_Cq_b()->GetElementN(0);

                D_b_T(row, colC + 0) = mbilateral->Get_Cq_c()->GetElementN(0);
                D_b_T(row, colC + 1) = mbilateral->Get_Cq_c()->GetElementN(1);
                D_b_T(row, colC + 2) = mbilateral->Get_Cq_c()->GetElementN(2);

                D_b_T(row, colC + 3) = mbilateral->Get_Cq_c()->GetElementN(3);
                D_b_T(row, colC + 4) = mbilateral->Get_Cq_c()->GetElementN(4);
                D_b_T(row, colC + 5) = mbilateral->Get_Cq_c()->GetElementN(5);
            } break;
        }
    }
}

void ChConstraintBilateral::GenerateSparsity() {
    LOG(INFO) << "ChConstraintBilateral::GenerateSparsity";
    // Grab the list of all bilateral constraints present in the system
    // (note that this includes possibly inactive constraints)

    std::vector<ChConstraint*>& mconstraints = data_manager->system_descriptor->GetConstraintsList();

    // Loop over the active constraints and fill in the sparsity pattern of the
    // Jacobian, taking into account the type of each constraint.
    // Note that the data for a Blaze compressed matrix must be filled in increasing
    // order of the column index for each row. Recall that body states are always
    // before shaft states.

    CompressedMatrix<real>& D_b_T = data_manager->host_data.D_T;
    int off = data_manager->num_unilaterals;
    for (int index = 0; index < (signed)data_manager->num_bilaterals; index++) {
        int cntr = data_manager->host_data.bilateral_mapping[index];
        int type = data_manager->host_data.bilateral_type[cntr];
        int row = off + index;

        int col1;
        int col2;
        int col3;

        switch (type) {
            case BilateralType::BODY_BODY: {
                ChConstraintTwoBodies* mbilateral = (ChConstraintTwoBodies*)(mconstraints[cntr]);

                int idA = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_a()))->GetUserData())->GetId();
                int idB = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_b()))->GetUserData())->GetId();

                if (idA < idB) {
                    col1 = idA * 6;
                    col2 = idB * 6;
                } else {
                    col1 = idB * 6;
                    col2 = idA * 6;
                }

                D_b_T.append(row, col1 + 0, 1);
                D_b_T.append(row, col1 + 1, 1);
                D_b_T.append(row, col1 + 2, 1);
                D_b_T.append(row, col1 + 3, 1);
                D_b_T.append(row, col1 + 4, 1);
                D_b_T.append(row, col1 + 5, 1);

                D_b_T.append(row, col2 + 0, 1);
                D_b_T.append(row, col2 + 1, 1);
                D_b_T.append(row, col2 + 2, 1);
                D_b_T.append(row, col2 + 3, 1);
                D_b_T.append(row, col2 + 4, 1);
                D_b_T.append(row, col2 + 5, 1);
            } break;

            case BilateralType::SHAFT_SHAFT: {
                ChConstraintTwoGeneric* mbilateral = (ChConstraintTwoGeneric*)(mconstraints[cntr]);

                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();

                if (idA < idB) {
                    col1 = data_manager->num_rigid_bodies * 6 + idA;
                    col2 = data_manager->num_rigid_bodies * 6 + idB;
                } else {
                    col1 = data_manager->num_rigid_bodies * 6 + idB;
                    col2 = data_manager->num_rigid_bodies * 6 + idA;
                }

                D_b_T.append(row, col1, 1);
                D_b_T.append(row, col2, 1);
            } break;

            case BilateralType::SHAFT_BODY: {
                ChConstraintTwoGeneric* mbilateral = (ChConstraintTwoGeneric*)(mconstraints[cntr]);

                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_b()))->GetUserData())->GetId();

                col1 = idB * 6;
                col2 = data_manager->num_rigid_bodies * 6 + idA;

                D_b_T.append(row, col1 + 0, 1);
                D_b_T.append(row, col1 + 1, 1);
                D_b_T.append(row, col1 + 2, 1);
                D_b_T.append(row, col1 + 3, 1);
                D_b_T.append(row, col1 + 4, 1);
                D_b_T.append(row, col1 + 5, 1);

                D_b_T.append(row, col2, 1);
            } break;

            case BilateralType::SHAFT_SHAFT_SHAFT: {
                ChConstraintThreeGeneric* mbilateral = (ChConstraintThreeGeneric*)(mconstraints[cntr]);
                std::vector<int> ids(3);
                ids[0] = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                ids[1] = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();
                ids[2] = ((ChVariablesShaft*)(mbilateral->GetVariables_c()))->GetShaft()->GetId();

                std::sort(ids.begin(), ids.end());
                col1 = data_manager->num_rigid_bodies * 6 + ids[0];
                col2 = data_manager->num_rigid_bodies * 6 + ids[1];
                col3 = data_manager->num_rigid_bodies * 6 + ids[2];

                D_b_T.append(row, col1, 1);
                D_b_T.append(row, col2, 1);
                D_b_T.append(row, col3, 1);
            } break;

            case BilateralType::SHAFT_SHAFT_BODY: {
                ChConstraintThreeGeneric* mbilateral = (ChConstraintThreeGeneric*)(mconstraints[cntr]);
                int idA = ((ChVariablesShaft*)(mbilateral->GetVariables_a()))->GetShaft()->GetId();
                int idB = ((ChVariablesShaft*)(mbilateral->GetVariables_b()))->GetShaft()->GetId();
                int idC = ((ChBody*)((ChVariablesBody*)(mbilateral->GetVariables_c()))->GetUserData())->GetId();

                col1 = idC * 6;
                if (idA < idB) {
                    col2 = data_manager->num_rigid_bodies * 6 + idA;
                    col3 = data_manager->num_rigid_bodies * 6 + idB;
                } else {
                    col2 = data_manager->num_rigid_bodies * 6 + idB;
                    col3 = data_manager->num_rigid_bodies * 6 + idA;
                }

                D_b_T.append(row, col1 + 0, 1);
                D_b_T.append(row, col1 + 1, 1);
                D_b_T.append(row, col1 + 2, 1);
                D_b_T.append(row, col1 + 3, 1);
                D_b_T.append(row, col1 + 4, 1);
                D_b_T.append(row, col1 + 5, 1);

                D_b_T.append(row, col2, 1);
                D_b_T.append(row, col3, 1);
            } break;
        }

        D_b_T.finalize(row);
    }
}


text:
package com.intellij.psi.impl.source.tree;

import com.intellij.lang.Language;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.TokenType;
import org.jetbrains.annotations.NotNull;

public class PsiWhiteSpaceImpl extends LeafPsiElement implements PsiWhiteSpace {
  public PsiWhiteSpaceImpl(CharSequence text) {
    super(TokenType.WHITE_SPACE, text);
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor){
    visitor.visitWhiteSpace(this);
  }

  @Override
  public String toString(){
    return "PsiWhiteSpace";
  }

  @Override
  @NotNull
  public Language getLanguage() {
    PsiElement master = getParent();
    return master != null ?  master.getLanguage() : Language.ANY;
  }
}


text:
"""
Test the scalar contructors, which also do type-coercion
"""
from __future__ import division, absolute_import, print_function

import sys
import platform
import numpy as np

from numpy.testing import (
    run_module_suite,
    assert_equal, assert_almost_equal, assert_raises, assert_warns,
    dec
)

class TestFromString(object):
    def test_floating(self):
        # Ticket #640, floats from string
        fsingle = np.single('1.234')
        fdouble = np.double('1.234')
        flongdouble = np.longdouble('1.234')
        assert_almost_equal(fsingle, 1.234)
        assert_almost_equal(fdouble, 1.234)
        assert_almost_equal(flongdouble, 1.234)

    def test_floating_overflow(self):
        """ Strings containing an unrepresentable float overflow """
        fhalf = np.half('1e10000')
        assert_equal(fhalf, np.inf)
        fsingle = np.single('1e10000')
        assert_equal(fsingle, np.inf)
        fdouble = np.double('1e10000')
        assert_equal(fdouble, np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '1e10000')
        assert_equal(flongdouble, np.inf)

        fhalf = np.half('-1e10000')
        assert_equal(fhalf, -np.inf)
        fsingle = np.single('-1e10000')
        assert_equal(fsingle, -np.inf)
        fdouble = np.double('-1e10000')
        assert_equal(fdouble, -np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000')
        assert_equal(flongdouble, -np.inf)

    @dec.knownfailureif((sys.version_info[0] >= 3) or
                        (sys.platform == "win32" and
                         platform.architecture()[0] == "64bit"),
                        "numpy.intp('0xff', 16) not supported on Py3, "
                        "as it does not inherit from Python int")
    def test_intp(self):
        # Ticket #99
        i_width = np.int_(0).nbytes*2 - 1
        np.intp('0x' + 'f'*i_width, 16)
        assert_raises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16)
        assert_raises(ValueError, np.intp, '0x1', 32)
        assert_equal(255, np.intp('0xFF', 16))

class TestFromInt(object):
    def test_intp(self):
        # Ticket #99
        assert_equal(1024, np.intp(1024))

    def test_uint64_from_negative(self):
        assert_equal(np.uint64(-2), np.uint64(18446744073709551614))

if __name__ == "__main__":
    run_module_suite()


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

namespace IDT.TaskActions
{
    public class MefExportFactory<T> : ExportFactory<T>
    {
        public MefExportFactory(Func<CompositionContainer> exportLifetimeContextCreator)
            : base(() => ConvertToTuple<T>(exportLifetimeContextCreator()))
        {
        }

        private static Tuple<TAction, Action> ConvertToTuple<TAction>(CompositionContainer container)
        {
            var item = container.GetExportedValue<TAction>();
            return new Tuple<TAction, Action>(item,container.Dispose);
        }
    }
}


text:
import Base, { BaseOptions, Headers } from './base'
import Request, { PopsicleError } from './request'

export interface ResponseOptions extends BaseOptions {
  body: any
  status: number
}

export interface ResponseJSON {
  headers: Headers
  body: any
  url: string
  status: number
}

export default class Response extends Base {
  status: number
  body: any
  request: Request

  constructor (options: ResponseOptions) {
    super(options)

    this.body = options.body
    this.status = options.status
  }

  statusType () {
    return ~~(this.status / 100)
  }

  error (message: string, type: string, error?: Error) {
    return this.request.error(message, type, error)
  }

  toJSON (): ResponseJSON {
    return {
      url: this.fullUrl(),
      headers: this.get(),
      body: this.body,
      status: this.status
    }
  }

}


text:
require 'settingslogic'
require 'sprockets/railtie'

module Tufts
  module MediaPlayerMethods
  include Sprockets::Helpers::RailsHelper

    def self.show_audio_player(pid, withTranscript)
      result = "
\n"
      result += "
\n"
      result += "          This div will be replaced by the JW Player.\n"
      result += "
\n"
      result += "

\n"
      result += "
\n"
      result += "      \n"

      return result
    end

    def self.show_video_player(pid, withTranscript,primary="html5")
       result = "
\n"
       result += "
\n"
       result += "          This div will be replaced by the JW Player.\n"
       result += "
\n"
       result += "

\n"
       result += "
\n"
       result += "      \n"

       return result
     end

    def self.show_participants(fedora_obj, datastream="ARCHIVAL_XML")
        result = ""
        participant_number = 0
        node_sets = fedora_obj.datastreams[datastream].find_by_terms(:participants)

        node_sets.each do |node|
          node.children.each do |child|
            unless child.attributes.empty?
              participant_number += 1
              id = child.attributes["id"]
              role = child.attributes["role"]
              sex = child.attributes["sex"].to_s
              result << "
\n"
              result << "
" + (id.nil? ? "" : id) + "
\n"
              result << "
" + child.text + "" + (role.nil? ? "" : ", " + role) + (sex.empty? ? "" : " (" + (sex == "f" ? "female" : (sex == "m" ? "male" : sex)) + ")") + "
\n"
              result << "
 \n"
            end
          end
        end

        if result.length > 0
          result = "
\n" + result + "
 \n"
        end

        return result
      end

    # convert fedora transcript object to html
    def self.show_transcript(fedora_obj, active_timestamps, datastream="ARCHIVAL_XML")
      chunks = TranscriptChunk.parse(fedora_obj, datastream)
      html = format_transcript(chunks, active_timestamps, fedora_obj.pid)
      return html
    end

    def self.get_time_table(fedora_obj, datastream="ARCHIVAL_XML")
      chunks = TranscriptChunk.parse(fedora_obj, datastream)
      table = extract_time_table(chunks)
      table
    end

    def self.extract_time_table(chunks)
      table = {}
      chunks.each do |chunk|
          milliseconds = chunk.start_in_milliseconds
          string_minutes, string_just_seconds, string_total_seconds = displayable_time(milliseconds)
          table[chunk.name.to_s] = {:time => milliseconds, :display_time => string_minutes + ":" + string_just_seconds}
      end
      table
    end

    # return html string of the transcript
    # iterate over chunks and create appropriate divs with classes, links, etc.
    def self.format_transcript(chunks, active_timestamps, pid)
      result = "
\n"
      chunks.each do |chunk|
        milliseconds = chunk.start_in_milliseconds
        string_minutes, string_just_seconds, string_total_seconds = displayable_time(milliseconds)
        div_id = chunk.name

        result << "
\n"

        unless (milliseconds.nil?)
          result << "
\n"
          result << "
\n"
          #https://corpora.tufts.edu/catalog/tufts:MS025.006.008.00004.00003?timestamp/0:00
          if (active_timestamps)
            result << "                      " + string_minutes + ":" + string_just_seconds + "\n"
          else
            result << "                      " + string_minutes + ":" + string_just_seconds + "\n"
          end

          result << "
 \n"
          result << "

\n"
          result << "
 \n"
        end
        utterances = chunk.utterances
        utterances.each do |utterance|
          who = utterance.speaker_initials
          text = utterance.text
          timepoint_id = utterance.timepoint_id
          if (who)
            result << "
\n"
            result << "
"+ (who.nil? ? "" : who) + "
\n"
            result << "
"+ (text.nil? ? "" : text) + "
\n"
            result << "
 \n"
          else
            unless text.nil?
              result << "
\n"
              result << "
" "
\n"
              result << "
["+ text + "]
\n"
              result << "
 \n"
            end
          end
        end
        result << "
 \n"

      end
      result << "
 \n"

      return result
    end

    def self.parse_notations(node)
         result = ""

         node.children.each do |child|
           childName = child.name

           if (childName == "text")
             result += child.text
           elsif (childName == "unclear")
             result += "[" + child.text + "]"
           elsif (childName == "event" || childName == "gap" || childName == "vocal" || childName == "kinesic")
             unless child.attributes.empty?
               desc = child.attributes["desc"]
               unless desc.nil?
                 result += "[" + desc + "]"
               end
             end
           end
         end

         return result
       end

    private # all methods that follow will be made private: not accessible for outside objects

    # convert a transcript time in milliseconds into displayable strings for UI
    def self.displayable_time(milliseconds)
      int_total_seconds = milliseconds.to_i / 1000 # truncated to the second
      int_minutes = int_total_seconds / 60
      int_just_seconds = int_total_seconds - (int_minutes * 60) # the seconds for seconds:minutes (0:00) display
      string_minutes = int_minutes.to_s
      string_just_seconds = int_just_seconds.to_s
      if (int_just_seconds < 10)
        string_just_seconds = "0" + string_just_seconds
      end
      return string_minutes, string_just_seconds, int_total_seconds.to_s
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="b2375fdc-2501-45c0-a34c-b434a54ced7d" name="Default" comment="">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
    </list>
    <ignored path="sparse-coding-theano.iws" />
    <ignored path=".idea/workspace.xml" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="sparse-coding-theano" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="sparse_coding.py" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/sparse_coding.py">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.0">
              <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
              <folding>
                <element signature="e#15#24#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="example.py" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/example.py">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.0">
              <caret line="29" column="14" selection-start-line="29" selection-start-column="14" selection-end-line="60" selection-end-column="35" />
              <folding>
                <element signature="e#15#28#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/example.py" />
        <option value="$PROJECT_DIR$/sparse_coding.py" />
      </list>
    </option>
  </component>
  <component name="NamedScopeManager">
    <order />
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="516" />
    <option name="width" value="976" />
    <option name="height" value="1038" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
    </navigator>
    <panes>
      <pane id="Scratches" />
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="sparse-coding-theano" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="sparse-coding-theano" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="sparse-coding-theano" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="recentsLimit" value="5" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$/../pythonGUI-learn" />
    <property name="restartRequiresConfirmation" value="true" />
    <property name="settings.editor.selected.configurable" value="vcs.Git" />
    <property name="settings.editor.splitter.proportion" value="0.2" />
    <property name="FullScreen" value="false" />
  </component>
  <component name="RunManager" selected="Python.example">
    <configuration default="true" type="PythonConfigurationType" factoryName="Python">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="D:\develop_kits\Python\WinPython27\python-2.7.10.amd64\python.exe" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="$PROJECT_DIR$/example.py" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Attests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Doctests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Nosetests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="PARAMS" value="" />
      <option name="USE_PARAM" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Unittests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="PUREUNITTEST" value="true" />
      <option name="PARAMS" value="" />
      <option name="USE_PARAM" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="py.test">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="testToRun" value="" />
      <option name="keywords" value="" />
      <option name="params" value="" />
      <option name="USE_PARAM" value="false" />
      <option name="USE_KEYWORD" value="false" />
      <method />
    </configuration>
    <configuration default="false" name="example" type="PythonConfigurationType" factoryName="Python">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="D:\develop_kits\Python\WinPython27\python-2.7.10.amd64\python.exe" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="sparse-coding-theano" />
      <option name="SCRIPT_NAME" value="$PROJECT_DIR$/example.py" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="Python.example" />
    </list>
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="SvnConfiguration">
    <configuration />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="b2375fdc-2501-45c0-a34c-b434a54ced7d" name="Default" comment="" />
      <created>1443618921425</created>
      <option name="number" value="Default" />
      <updated>1443618921425</updated>
    </task>
    <task id="LOCAL-00001" summary="添加中文注释">
      <created>1443620807397</created>
      <option name="number" value="00001" />
      <option name="project" value="LOCAL" />
      <updated>1443620807397</updated>
    </task>
    <task id="LOCAL-00002" summary="添加中文注释">
      <created>1443620884435</created>
      <option name="number" value="00002" />
      <option name="project" value="LOCAL" />
      <updated>1443620884435</updated>
    </task>
    <task id="LOCAL-00003" summary="继续添加中文注释,让代码可以运行">
      <created>1443623151413</created>
      <option name="number" value="00003" />
      <option name="project" value="LOCAL" />
      <updated>1443623151413</updated>
    </task>
    <task id="LOCAL-00004" summary="继续添加中文注释,让代码可以运行">
      <created>1443624428972</created>
      <option name="number" value="00004" />
      <option name="project" value="LOCAL" />
      <updated>1443624428972</updated>
    </task>
    <option name="localTasksCounter" value="5" />
    <servers />
  </component>
  <component name="TodoView">
    <todo-panel id="selected-file">
      <is-autoscroll-to-source value="true" />
    </todo-panel>
    <todo-panel id="all">
      <are-packages-shown value="true" />
      <is-autoscroll-to-source value="true" />
    </todo-panel>
  </component>
  <component name="ToolWindowManager">
    <frame x="516" y="0" width="976" height="1038" extended-state="0" />
    <editor active="false" />
    <layout>
      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.2658092" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32912844" sideWeight="0.49604222" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.44495413" sideWeight="0.507124" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32912844" sideWeight="0.49815303" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.51261467" sideWeight="0.4939314" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32912844" sideWeight="0.4939314" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.44495413" sideWeight="0.492876" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="Vcs.Log.UiProperties">
    <option name="RECENTLY_FILTERED_USER_GROUPS">
      <collection />
    </option>
    <option name="RECENTLY_FILTERED_BRANCH_GROUPS">
      <collection />
    </option>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <MESSAGE value="添加中文注释" />
    <MESSAGE value="继续添加中文注释,让代码可以运行" />
    <option name="LAST_COMMIT_MESSAGE" value="继续添加中文注释,让代码可以运行" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/featuresign.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="39" column="26" selection-start-line="39" selection-start-column="26" selection-end-line="39" selection-end-column="26" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/featuresign.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="39" column="26" selection-start-line="39" selection-start-column="26" selection-end-line="39" selection-end-column="26" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/featuresign.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="39" column="26" selection-start-line="39" selection-start-column="26" selection-end-line="39" selection-end-column="26" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/featuresign.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="39" column="26" selection-start-line="39" selection-start-column="26" selection-end-line="39" selection-end-column="26" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/featuresign.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-3.0154867">
          <caret line="62" column="13" selection-start-line="62" selection-start-column="13" selection-end-line="62" selection-end-column="13" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/sparse_coding.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
          <folding>
            <element signature="e#15#24#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/example.py">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0">
          <caret line="29" column="14" selection-start-line="29" selection-start-column="14" selection-end-line="60" selection-end-column="35" />
          <folding>
            <element signature="e#15#28#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
import os
import sys
import glob

# add python module logger to path
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'logger'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'device_files'))

from logger import Logger

from dfg.device import Device
from dfg.merger import DeviceMerger
from dfg.avr.avr_reader import AVRDeviceReader
from dfg.avr.avr_writer import AVRDeviceWriter

if __name__ == "__main__":
	"""
	Some test code
	"""
	level = 'info'
	logger = Logger(level)
	devices = []

	for arg in sys.argv[1:]:
		if arg in ['error', 'warn', 'info', 'debug', 'disabled']:
			level = arg
			logger.setLogLevel(level)
			continue
		xml_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'AVR_devices', (arg + '*'))
		files = glob.glob(xml_path)
		for file in files:
			# deal with this here, rather than rewrite half the name merging
			if os.path.basename(file) != "ATtiny28.xml":
				part = AVRDeviceReader(file, logger)
				device = Device(part, logger)
				devices.append(device)

	merger = DeviceMerger(devices, logger)
	merger.mergedByPlatform('avr')

	folder = os.path.join(os.path.dirname(__file__), '..', '..', 'src', 'xpcc', 'architecture', 'platform', 'devices', 'avr')

	for dev in merger.mergedDevices:
		writer = AVRDeviceWriter(dev, logger)
		writer.write(folder)


text:
package com.mc.hibernate.memcached;

import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.hibernate.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Wrapper around MemcachedClient instance to provide the bridge between Hibernate and Memcached.
 * Uses the regionName given by Hibernate via the {@link MemcachedRegionFactory}
 * when generating cache keys.
 * All cache operations rely on using a {@link KeyStrategy}
 * to generate cache keys for use in memcached.
 *

 * Support for the {@link #clear()} operation is disabled by default.

 * There is no way for this instance of MemcachedCache to know what cache values to "clear" in a given Memcached instance.
 * Clear functionality is implemented by incrementing a "clearIndex" value that is always included in the cache-key generation.
 * When clear is called the memcached increment function is used to increment the global clean index. When clear is enabled,
 * every cache action taken starts with a call to memcached to 'get' the clearIndex counter. That value is then
 * applied to the cache key for the cache operation being taken. When the clearIndex is incremented this causes
 * the MemcachedCache to generate different cache-keys than it was before. This results in previously cached data being
 * abandoned in the cache, and left for memcached to deal with.
 *

 * For these reasons it is not recommended to rely on clear() as a regular production functionality,
 * it is very expensive and generally not very useful anyway.
 *

 * The MemcachedCache treats Hibernate cache regions as namespaces in Memcached. For more information see the
 * memcached FAQ.
 *
 * @author Ray Krueger
 */
public class MemcachedCache {

    private final Logger log = LoggerFactory.getLogger(MemcachedCache.class);

    private final String regionName;
    private final Memcache memcache;
    private final String clearIndexKey;
    private int cacheTimeSeconds = 300;
    private boolean clearSupported = false;
    private KeyStrategy keyStrategy = new Sha1KeyStrategy();
    private boolean dogpilePreventionEnabled = false;
    private double dogpilePreventionExpirationFactor = 2;

    public static final Integer DOGPILE_TOKEN = 0;

    public MemcachedCache(String regionName, Memcache memcachedClient, Config config) {
        this.regionName = (regionName != null) ? regionName : "default";
        this.memcache = memcachedClient;
        clearIndexKey = this.regionName.replaceAll("\\s", "") + ":index_key";

        configureInstance(config);
    }

    private void configureInstance(Config config) {

        this.cacheTimeSeconds = config.getCacheTimeSeconds(this.regionName);

        this.clearSupported = config.isClearSupported(this.regionName);

        this.dogpilePreventionEnabled = config.isDogpilePreventionEnabled(this.regionName);
        if (this.dogpilePreventionEnabled) {
            this.dogpilePreventionExpirationFactor = config.getDogpilePreventionExpirationFactor(this.regionName);
        }

        this.keyStrategy = config.getKeyStrategy(this.regionName);
    }

    public int getCacheTimeSeconds() {
        return cacheTimeSeconds;
    }

    public void setCacheTimeSeconds(int cacheTimeSeconds) {
        this.cacheTimeSeconds = cacheTimeSeconds;
    }

    public boolean isClearSupported() {
        return clearSupported;
    }

    public void setClearSupported(boolean clearSupported) {
        this.clearSupported = clearSupported;
    }

    public boolean isDogpilePreventionEnabled() {
        return dogpilePreventionEnabled;
    }

    public void setDogpilePreventionEnabled(boolean dogpilePreventionEnabled) {
        this.dogpilePreventionEnabled = dogpilePreventionEnabled;
    }

    public double getDogpilePreventionExpirationFactor() {
        return dogpilePreventionExpirationFactor;
    }

    public void setDogpilePreventionExpirationFactor(double dogpilePreventionExpirationFactor) {
        if (dogpilePreventionExpirationFactor < 1.0) {
            throw new IllegalArgumentException("dogpilePreventionExpirationFactor must be greater than 1.0");
        }
        this.dogpilePreventionExpirationFactor = dogpilePreventionExpirationFactor;
    }

    private String dogpileTokenKey(String objectKey) {
        return objectKey + ".dogpileTokenKey";
    }

    private Object memcacheGet(Object key) {
        String objectKey = toKey(key);

        if (dogpilePreventionEnabled) {
            return getUsingDogpilePrevention(objectKey);

        } else {
            log.debug("Memcache.get({})", objectKey);
            return memcache.get(objectKey);
        }
    }

    private Object getUsingDogpilePrevention(String objectKey) {
        Map<String, Object> multi;

        String dogpileKey = dogpileTokenKey(objectKey);
        log.debug("Checking dogpile key: [{}]", dogpileKey);

        log.debug("Memcache.getMulti({}, {})", objectKey, dogpileKey);
        multi = memcache.getMulti(dogpileKey, objectKey);

        if ((multi == null) || (multi.get(dogpileKey) == null)) {
            log.debug("Dogpile key ({}) not found updating token and returning null", dogpileKey);
            memcache.set(dogpileKey, cacheTimeSeconds, DOGPILE_TOKEN);
            return null;
        }

        return multi.get(objectKey);
    }

    private void memcacheSet(Object key, Object o) {
        String objectKey = toKey(key);

        int cacheTime = cacheTimeSeconds;

        if (dogpilePreventionEnabled) {
            String dogpileKey = dogpileTokenKey(objectKey);
            log.debug("Dogpile prevention enabled, setting token and adjusting object cache time. Key: [{}]", dogpileKey);
            memcache.set(dogpileKey, cacheTimeSeconds, DOGPILE_TOKEN);
            cacheTime = (int) (cacheTimeSeconds * dogpilePreventionExpirationFactor);
        }

        log.debug("Memcache.set({})", objectKey);

        memcache.set(objectKey, cacheTime, o);
    }

    private String toKey(Object key) {
        return keyStrategy.toKey(regionName, getClearIndex(), key);
    }

    public Object read(Object key) throws CacheException {
        return memcacheGet(key);
    }

    public Object get(Object key) throws CacheException {
        return memcacheGet(key);
    }

    public void put(Object key, Object value) throws CacheException {
        memcacheSet(key, value);
    }

    public void update(Object key, Object value) throws CacheException {
        put(key, value);
    }

    public void remove(Object key) throws CacheException {
        memcache.delete(toKey(key));
    }

    /**
     * Clear functionality is disabled by default.
     * Read this class's javadoc for more detail.
     *
     * @see MemcachedCache
     */
    public void clear() throws CacheException {
        if (clearSupported) {
            memcache.incr(clearIndexKey, 1, 1);
        }
    }

    public void destroy() throws CacheException {
        //the client is shared by default with all cache instances, so don't shut it down.
    }

    public void lock(Object key) throws CacheException {
    }

    public void unlock(Object key) throws CacheException {
    }

    public String getRegionName() {
        return regionName;
    }

    public long getSizeInMemory() {
        return -1;
    }

    public long getElementCountInMemory() {
        return -1;
    }

    public long getElementCountOnDisk() {
        return -1;
    }

    public Map<?, ?> toMap() {
        throw new UnsupportedOperationException();
    }

    public String toString() {
        return "Memcached (" + regionName + ")";
    }

    private long getClearIndex() {
        Long index = null;

        if (clearSupported) {
            Object value = memcache.get(clearIndexKey);
            if (value != null) {
                if (value instanceof String) {
                    index = Long.valueOf((String) value);
                } else if (value instanceof Long) {
                    index = (Long) value;
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported type [" + value.getClass() + "] found for clear index at cache key [" + clearIndexKey + "]");
                }
            }

            if (index != null) {
                return index;
            }
        }

        return 0L;
    }

    public KeyStrategy getKeyStrategy() {
        return keyStrategy;
    }

    public void setKeyStrategy(KeyStrategy keyStrategy) {
        this.keyStrategy = keyStrategy;
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Bridge.Translator.Tests.TestProject")]
[assembly: AssemblyProduct("Bridge.Translator.Tests.TestProject")]
//[assembly: AssemblyDescription("Bridge Test library.")]
[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("Object.NET, Inc.")]
//[assembly: AssemblyCopyright("Copyright 2008-2015 Object.NET, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("F53B0152-FEAD-485B-AFDF-1D6CFE321549")]

//[assembly: AssemblyVersion("1.0")]
//[assembly: AssemblyFileVersion("1.0.0-beta")]

// #2262
[assembly: Bridge.ExternalInterface(true)]


text:
/// <reference path="../../ng4c/scope.ts" />
module sap.sbo.ui.attrs {

    import Scope = sap.sbo.ng4c.Scope;

    export function ScrollDirective(): Object {
        return {
            restrict: "A",
            priority: 0,
            //replace: true,
            scope: true,
            transclude: true,
            //templateUrl: 'resources/sap/sbo/ui/controls/Button.html',
            compile: function ($element, $attrs, $transclude) {
                return {
                    pre: function ($scope, $element, $attrs, $controller) {
                        console.log("Directive Pre");
                    },
                    post: function ($scope, $element, $attrs, $controller) {
                        console.log("Directive Post");
                    }

                }
            },
            link: function ($scope, $element, $attrs, $controller): void {
                angular.element(window).bind("scroll", function () {
                    $scope.scroll();
                    $scope.$applyAsync();
                });
            }
        };
    }
}