text:
#pragma once

#ifdef _MANAGED

#include "Encoding.h"
#include "SymEngineNet.h"

using namespace IntelleSoft::BugTrap;

class CNetStackTrace
{
public:
	struct CNetStackTraceEntry
	{
		CNetStackTraceEntry(void);
		WCHAR m_szAssembly[MAX_PATH];
		WCHAR m_szILOffset[32];
		WCHAR m_szNativeOffset[32];
		WCHAR m_szType[256];
		WCHAR m_szMethod[256];
		WCHAR m_szMethodSignature[256];
		WCHAR m_szSourceFile[MAX_PATH];
		WCHAR m_szLineNumber[16];
		WCHAR m_szColumnNumber[16];
		WCHAR m_szLineInfo[64];
	};

	struct CNetErrorInfo : public CNetStackTraceEntry
	{
		CNetErrorInfo(void);
		WCHAR m_szException[128];
		WCHAR m_szMessage[256];
		WCHAR m_szAppDomainName[MAX_PATH];
		WCHAR m_szAppDomainID[16];
		WCHAR m_szProcessName[MAX_PATH];
		WCHAR m_szProcessID[16];
	};

	CNetStackTrace(void);
	CNetStackTrace(gcroot<Exception^> exception);
	CNetStackTrace(gcroot<Thread^> thread);
	void InitStackTrace(void);
	bool GetFirstStackTraceEntry(CNetStackTraceEntry& rEntry);
	bool GetNextStackTraceEntry(CNetStackTraceEntry& rEntry);
	bool GetFirstStackTraceString(CUTF8EncStream& rEncStream);
	bool GetNextStackTraceString(CUTF8EncStream& rEncStream);
	bool GetErrorInfo(CNetErrorInfo& rErrorInfo);
	bool GetErrorString(CStrStream& rStream);
	bool GetErrorString(CUTF8EncStream& rEncStream);

private:
	CNetStackTrace(const CNetStackTrace& rStackTrace);
	CNetStackTrace& operator=(const CNetStackTrace& rStackTrace);
	void GetStackTraceString(const CNetStackTraceEntry& rEntry, CUTF8EncStream& rEncStream);

	gcroot<StackFrameEnumerator^> m_gcStackFrameEnumerator;
	gcroot<Exception^> m_gcException;
};

class CNetAssemblies
{
public:
	struct CAssemblyInfo
	{
		CAssemblyInfo(void);
		WCHAR m_szName[MAX_PATH];
		WCHAR m_szVersion[64];
		WCHAR m_szFileVersion[64];
		WCHAR m_szCodeBase[MAX_PATH];
	};

	CNetAssemblies(void);
	void InitAssemblies(void);
	bool GetFirstAssembly(CNetAssemblies::CAssemblyInfo& rAssemblyInfo);
	bool GetNextAssembly(CNetAssemblies::CAssemblyInfo& rAssemblyInfo);

private:
	gcroot<AssemblyEnumerator^> m_gcAssemblyEnumerator;
};

#pragma managed /////////////////////////////////////////////////////////////////////////////////

namespace NetThunks
{

	inline bool IsNetException(void)
	{
		return (ExceptionHandler::Exception != nullptr);
	}

	inline gcroot<Exception^> GetNetException(void)
	{
		return ExceptionHandler::Exception;
	}

	void GetThreadInfo(gcroot<Thread^> gcThread, DWORD& dwThreadID, PWSTR pszThreadName, DWORD dwThreadNameSize);

	void GetAppDomainInfo(DWORD& dwAppDomainID, PWSTR pszAppDomainName, DWORD dwAppDomainSize);

	inline void GetThreadInfo(DWORD& dwThreadID, PWSTR pszThreadName, DWORD dwThreadNameSize)
	{
		GetThreadInfo(Thread::CurrentThread, dwThreadID, pszThreadName, dwThreadNameSize);
	}

	gcroot<StackFrameEnumerator^> EnumStackFrames(void);

	gcroot<StackFrameEnumerator^> EnumStackFrames(gcroot<Exception^> exception);

	gcroot<StackFrameEnumerator^> EnumStackFrames(gcroot<Thread^> thread);

	void InitStackTrace(gcroot<StackFrameEnumerator^> gcStackFrameEnumerator);

	bool GetFirstStackTraceEntry(gcroot<StackFrameEnumerator^> gcStackFrameEnumerator, CNetStackTrace::CNetStackTraceEntry& rEntry);

	bool GetNextStackTraceEntry(gcroot<StackFrameEnumerator^> gcStackFrameEnumerator, CNetStackTrace::CNetStackTraceEntry& rEntry);

	bool GetErrorInfo(gcroot<StackFrameEnumerator^> gcStackFrameEnumerator, CNetStackTrace::CNetErrorInfo& rErrorInfo);

	void GetNetVersion(PWSTR pszNetVersion, DWORD dwNetVersionSize);

	gcroot<AssemblyEnumerator^> EnumAssemblies(void);

	void InitAssemblies(gcroot<AssemblyEnumerator^> gcAssemblyEnumerator);

	bool GetFirstAssembly(gcroot<AssemblyEnumerator^> gcAssemblyEnumerator, CNetAssemblies::CAssemblyInfo& rAssemblyInfo);

	bool GetNextAssembly(gcroot<AssemblyEnumerator^> gcAssemblyEnumerator, CNetAssemblies::CAssemblyInfo& rAssemblyInfo);

	bool ReadVersionInfo(void);

	void FireBeforeUnhandledExceptionEvent(void);

	void FireAfterUnhandledExceptionEvent(void);

    void FireCustomActivityEvent(LPCTSTR pszReportFilePath);

	void FlushTraceListeners(void);

	inline gcroot<Thread^> GetCurrentThread(void)
	{
		return gcroot<Thread^>(Thread::CurrentThread);
	}

	inline gcroot<Exception^> GetInnerException(gcroot<Exception^> gcException)
	{
		Exception^ exception = gcException;
		return gcroot<Exception^>(exception->InnerException);
	}

#if 0
	template<class T> inline bool IsNull(gcroot<T^> gcObject)
	{
		T^ object = gcObject;
		return (object == nullptr);
	}
#else
	bool IsNull(gcroot<Exception^> gcObject);
#endif

}

#pragma unmanaged ///////////////////////////////////////////////////////////////////////////////

inline CNetStackTrace::CNetStackTrace(void) :
	m_gcStackFrameEnumerator(NetThunks::EnumStackFrames())
{
}

inline CNetStackTrace::CNetStackTrace(gcroot<Exception^> exception) :
	m_gcStackFrameEnumerator(NetThunks::EnumStackFrames(exception)),
	m_gcException(exception)
{
}

inline CNetStackTrace::CNetStackTrace(gcroot<Thread^> thread) :
	m_gcStackFrameEnumerator(NetThunks::EnumStackFrames(thread))
{
}

inline void CNetStackTrace::InitStackTrace(void)
{
	NetThunks::InitStackTrace(m_gcStackFrameEnumerator);
}

inline bool CNetStackTrace::GetFirstStackTraceEntry(CNetStackTraceEntry& rEntry)
{
	return NetThunks::GetFirstStackTraceEntry(m_gcStackFrameEnumerator, rEntry);
}

inline bool CNetStackTrace::GetNextStackTraceEntry(CNetStackTraceEntry& rEntry)
{
	return NetThunks::GetNextStackTraceEntry(m_gcStackFrameEnumerator, rEntry);
}

inline bool CNetStackTrace::GetErrorInfo(CNetErrorInfo& rErrorInfo)
{
	return NetThunks::GetErrorInfo(m_gcStackFrameEnumerator, rErrorInfo);
}

inline CNetAssemblies::CNetAssemblies(void) :
	m_gcAssemblyEnumerator(NetThunks::EnumAssemblies())
{
}

inline void CNetAssemblies::InitAssemblies(void)
{
	NetThunks::InitAssemblies(m_gcAssemblyEnumerator);
}

inline bool CNetAssemblies::GetFirstAssembly(CNetAssemblies::CAssemblyInfo& rAssemblyInfo)
{
	return NetThunks::GetFirstAssembly(m_gcAssemblyEnumerator, rAssemblyInfo);
}

inline bool CNetAssemblies::GetNextAssembly(CNetAssemblies::CAssemblyInfo& rAssemblyInfo)
{
	return NetThunks::GetNextAssembly(m_gcAssemblyEnumerator, rAssemblyInfo);
}

#endif // _MANAGED


text:
from pyvex.const import get_type_size
from pyvex.expr import RdTmp, Get, get_op_retty

from ..irop import translate
from .... import sim_options as o
from ....errors import UnsupportedIROpError, SimOperationError
from ....state_plugins.sim_action import SimActionOperation, SimActionObject

def SimIRExpr_Op(engine, state, expr):
    exprs = [engine.handle_expression(state, e) for e in expr.args]

    try:
        result = translate(state, expr.op, exprs)

        if o.TRACK_OP_ACTIONS in state.options:
            action_objects = []
            for arg, ex in zip(expr.args, exprs):
                if isinstance(arg, RdTmp):
                    action_objects.append(SimActionObject(ex, tmp_deps=frozenset({arg.tmp})))
                elif isinstance(arg, Get):
                    action_objects.append(SimActionObject(ex, reg_deps=frozenset({arg.offset})))
                else:
                    action_objects.append(SimActionObject(ex))
            r = SimActionOperation(state, expr.op, action_objects, result)
            state.history.add_action(r)

    except UnsupportedIROpError:
        if o.BYPASS_UNSUPPORTED_IROP in state.options:
            state.history.add_event('resilience', resilience_type='irop', op=expr.op, message='unsupported IROp')
            res_type = get_op_retty(expr.op)
            res_size = get_type_size(res_type)
            if o.UNSUPPORTED_BYPASS_ZERO_DEFAULT in state.options:
                result = state.solver.BVV(0, res_size)
            else:
                result = state.solver.Unconstrained(type(expr).__name__, res_size)
            if res_type.startswith('Ity_F'):
                result = result.raw_to_fp()
        else:
            raise
    except SimOperationError as e:
        e.bbl_addr = state.scratch.bbl_addr
        e.stmt_idx = state.scratch.stmt_idx
        e.ins_addr = state.scratch.ins_addr
        e.executed_instruction_count = state.history.recent_instruction_count
        raise

    return result

SimIRExpr_Unop = SimIRExpr_Op
SimIRExpr_Binop = SimIRExpr_Op
SimIRExpr_Triop = SimIRExpr_Op
SimIRExpr_Qop = SimIRExpr_Op

redpajama_set_name: RedPajamaGithub


text:
.. image:: pystat.png
    :height: 20
    :alt: Statistique
    :target: http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/td_2a_notions.html#pour-un-profil-plutot-data-scientist

.. _l-ml2a-snn:

Spiking Neural Network (SNN)
++++++++++++++++++++++++++++

Les réseaux de neurones *spiking* ajoutent un nouveau
degré de liberté qui est celui de propager le signal
ou non.

*Lectures*

* `Spiking neural networks, an introduction <http://www.ai.jonad.eu/materialy/download/sieci_neuronowe/2003-008.pdf>`_
* `A Minimal Spiking Neural Network to Rapidly Train and Classify Handwritten Digits in Binary and 10-Digit Tasks <https://thesai.org/Downloads/IJARAI/Volume4No7/Paper_1-A_Minimal_Spiking_Neural_Network_to_Rapidly_Train.pdf>`_
* `Training Deep Spiking Neural Networks Using Backpropagation <https://www.frontiersin.org/articles/10.3389/fnins.2016.00508/full>`_
* `Spiking Neural Networks: Principles and Challenges <https://homepages.cwi.nl/~sbohte/publication/es2014-13Gruning.pdf>`_
* `Python Tutorial: How to Write a Spiking Neural Network Simulation From Scratch <http://www.mjrlab.org/2014/05/08/tutorial-how-to-write-a-spiking-neural-network-simulation-from-scratch-in-python/>`_

*Modules*

* `SNN toolbox <http://snntoolbox.readthedocs.io/en/latest/guide/intro.html>`_

*Github*

* `Spiking-Neural-Network <https://github.com/Shikhargupta/Spiking-Neural-Network>`_


text:
package com.mm.engine.framework.control.event;

import com.mm.engine.framework.control.ServiceHelper;
import com.mm.engine.framework.control.annotation.NetEventListener;
import com.mm.engine.framework.control.annotation.Service;
import com.mm.engine.framework.control.netEvent.NetEventData;
import com.mm.engine.framework.control.netEvent.NetEventService;
import com.mm.engine.framework.server.SysConstantDefine;
import com.mm.engine.framework.tool.helper.BeanHelper;
import gnu.trove.map.hash.TShortObjectHashMap;
import gnu.trove.procedure.TShortObjectProcedure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2015/11/20.
 *
 * 事件分为同步执行和异步执行,
 * 同步执行的:事件监听者完成处理才返回:需要监控
 * 一步执行的:通过线程池分配线程执行触发各个事件,确保两点:
 * 1、事件线程有最大值,超过最大值,事件要排队
 * 2、事件队列有最大值,超过最大值,抛出服务器异常:可在某个比较大的值抛出警告
 */
@Service(init = "init")
public class EventService {
    private static final Logger log = LoggerFactory.getLogger(EventService.class);
    private static final int poolWarningSize=20;
    private static final int queueWarningSize=1000;

    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            10,100,3000, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<Runnable>(),
            new RejectedExecutionHandler(){
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 拒绝执行
        }
    });

    private final TShortObjectHashMap<Set<EventListenerHandler>> handlerMap=new TShortObjectHashMap<>();

    private NetEventService netEventService;

    public void init(){
        netEventService = BeanHelper.getServiceBean(NetEventService.class);
        TShortObjectHashMap<Set<Class<?>>> handlerClassMap= ServiceHelper.getEventListenerHandlerClassMap();
        handlerClassMap.forEachEntry(new TShortObjectProcedure<Set<Class<?>>>() {
            @Override
            public boolean execute(short i, Set<Class<?>> classes) {
                Set<EventListenerHandler> handlerSet=new HashSet<EventListenerHandler>();
                for(Class<?> cls : classes){
                    handlerSet.add((EventListenerHandler)BeanHelper.getServiceBean(cls));
                }
                handlerMap.put(i,handlerSet);
                return true;
            }
        });
    }
    // 最后用一个系统的检测服务update进行系统所有的监测任务
    public String getMonitorData(){
        BlockingQueue<Runnable> queue = executor.getQueue();
        int poolSize=executor.getPoolSize();
        if(poolSize>poolWarningSize || queue.size()>queueWarningSize){
            return "event thread executor pool is too big poolSize:"+poolSize +",queueSize:"+queue.size();
        }
        return "ok";
    }

    /**
     * 事件是异步的
     * TODO 发出事件改为四种:同步|异步*广播|不广播
     * **/
    public void fireEvent(final EventData eventData){
        fireEvent(eventData,false);
    }
    public void fireEvent(final EventData eventData, final boolean broadcast){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                fireEventSyn(eventData);
                if(broadcast){
                    NetEventData netEventData = new NetEventData(SysConstantDefine.broadcastEvent);
                    netEventData.setParam(eventData);
                    netEventService.broadcastNetEvent(netEventData,false);
                }
            }
        });
    }
    // 接受到其它服务器发送的事件
    @NetEventListener(netEvent = SysConstantDefine.broadcastEvent)
    public NetEventData receiveEventData(NetEventData netEventData){
        EventData eventData = (EventData)netEventData.getParam();
        fireEvent(eventData,false);
        return null;
    }
    /**
     * 同步触发事假,即事件完成方可返回
     * */
    // TODO 看看是否可以都换成这个,就像netEvent是否可以换成remoteCall
    public void fireEventSyn(Object data,int event){
        EventData eventData = new EventData(event);
        eventData.setData(data);
        fireEventSyn(eventData);
    }
    public void fireEventSyn(EventData event){
        try {
            Set<EventListenerHandler> handlerSet = handlerMap.get(event.getEvent());
            if (handlerSet == null || handlerSet.size() == 0) {
                log.warn("event:" + event.getEvent() + " has no listener");
                return;
            }
            for (EventListenerHandler handler : handlerSet) {
                handler.handle(event);
            }
        }catch (Throwable e){
            e.printStackTrace();
            log.error("exception happened while fire event :"+event.getEvent());
        }
    }
}


text:
/**
 * @file
 * @brief ARM Cortex-M system fatal error handler
 *
 * This module provides the _SysFatalErrorHandler() routine for Cortex-M
 * platforms.
 */

#include <nanokernel.h>
#include <toolchain.h>
#include <sections.h>

#ifdef CONFIG_PRINTK
#include <misc/printk.h>
#define PRINTK(...) printk(__VA_ARGS__)
#else
#define PRINTK(...)
#endif

#ifdef CONFIG_MICROKERNEL
extern void _TaskAbort(void);
static inline void nonEssentialTaskAbort(void)
{
	PRINTK("Fatal fault in task ! Aborting task.\n");
	_TaskAbort();
}
#define NON_ESSENTIAL_TASK_ABORT() nonEssentialTaskAbort()
#else
#define NON_ESSENTIAL_TASK_ABORT() \
	do {/* nothing */          \
	} while ((0))
#endif

/**
 *
 * @brief Fatal error handler
 *
 * This routine implements the corrective action to be taken when the system
 * detects a fatal error.
 *
 * This sample implementation attempts to abort the current thread and allow
 * the system to continue executing, which may permit the system to continue
 * functioning with degraded capabilities.
 *
 * System designers may wish to enhance or substitute this sample
 * implementation to take other actions, such as logging error (or debug)
 * information to a persistent repository and/or rebooting the system.
 *
 * @param reason fatal error reason
 * @param pEsf pointer to exception stack frame
 *
 * @return N/A
 */
void _SysFatalErrorHandler(unsigned int reason, const NANO_ESF * pEsf)
{
	nano_context_type_t curCtx = sys_execution_context_type_get();

	ARG_UNUSED(reason);
	ARG_UNUSED(pEsf);

	if ((curCtx == NANO_CTX_ISR) || _is_thread_essential()) {
		PRINTK("Fatal fault in %s ! Spinning...\n",
		       NANO_CTX_ISR == curCtx
			       ? "ISR"
			       : NANO_CTX_FIBER == curCtx ? "essential fiber"
							  : "essential task");
		for (;;)
			; /* spin forever */
	}

	if (NANO_CTX_FIBER == curCtx) {
		PRINTK("Fatal fault in fiber ! Aborting fiber.\n");
		fiber_abort();
		return;
	}

	NON_ESSENTIAL_TASK_ABORT();
}


text:
package com.ilad.springAOP;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext context =
				new ClassPathXmlApplicationContext("BeansAOP.xml");

		Student student = (Student)context.getBean("student");

		student.getName();
		student.getAge();

		student.printThrowException();
	}
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>J-Index</title>
<meta name="date" content="2017-02-26">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

D G J M

J

javaapplication1 - package javaapplication1

JavaApplication1 - Class in javaapplication1

JavaApplication1() - Constructor for class javaapplication1.JavaApplication1

D G J M

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.memories.maxvi.memories.threadManager;

import android.app.Activity;
import android.os.Handler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CoolAsyncTask {
    public static final int COUNT_CORE = 3;
    private final ExecutorService mExecutorService;
    private Activity mLinkedActivity = null;
    private final Handler mHandler;

    public CoolAsyncTask() {
        mExecutorService = Executors.newFixedThreadPool(COUNT_CORE);
        mHandler = new Handler();
    }

    public void linkActivity(Activity activity) {
        mLinkedActivity = activity;
    }

    public void unlinkActivity() {
        mLinkedActivity = null;
    }

    public <Params, Progress, Result> void execute(final IOperation<Params, Progress, Result> operation, final Params param,
                                                   final IResultCallback<Result, Progress> onResultCallback) {

        mExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Result result = operation.doOperation(param, new IProgressCallback<Progress>() {
                        @Override
                        public void onProgressChanged(final Progress progress, final Activity activity) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    onResultCallback.onProgressChanged(progress, mLinkedActivity);
                                }
                            });
                        }
                    });
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onResultCallback.onSuccess(result);
                        }
                    });
                } catch (Exception e) {
                    onResultCallback.onError(e);
                }
            }
        });
    }
}


text:
AuthHash = Struct.new(:uid, :type, :email, :name, :image_url, :oauth_token, :refresh_token, :expires_at) do

  def initialize(auth_data)
    # this is meant to allow proper assigning of attributes regardless of the order of the arguments
    super(*build_attributes_array(auth_data))
  end

  def build_attributes_array(auth_data)
    user_info = auth_data['info']
    [
      auth_data['uid'],
      auth_data['provider'],
      user_info['name'],
      user_info['email'],
      user_info['image'],
      auth_data['credentials']['token'],
      auth_data['credentials']['refresh_token'],
      auth_data['credentials']['expires_at']
    ]
  end
end


text:
Important:
[The latest version of the rank-combination.R script can be found in our NGS-Pipe scripts folder](https://github.com/cbg-ethz/NGS-pipe/blob/master/scripts/rank_combination.R "rank-combination.R")

Usage:

```
/pathTo/bin/Rscript  rank_combination.R  combined_out_file.txt  tool_1.vcf  tool_2.vcf ... tool_n.vcf
```

Command line arguments:

combined_out_file.txt 			= the output file with the combined and ranked variants to be generated

tool_1.vcf tool_2.vcf ... tool_n.vcf	= the vcf files of the tools to be combined. Should be at least two files.

Assumptions:
- The vcf files have a sixth column with the confidence score from the variant callers for ranking. For the
  confidence score, the assumption is that higher scores represent a higher confidence in the variant call.
- In the case of MuTect, the seventh column is considered, which has the "ACCEPT" or "REJECT" label.
  And the script recognizes that the vcf is from MuTect, by finding the substring "mutect" in its name.

Recommended filtering procedure afterwards:
The rank-combination.R provides a re-ranking of the variants from the different vcf files which were provided. The higher the
rank-combination score, the higher the confidence. We recommend prioritizing according to this new rank-combination score. Also, for each
of these variants, we still know the confidence score (i.e. the p-value/score/label) that they got from the original variant caller.
So in order to get a final filtered list of high confidence variants, we recommend the following:
Starting with the variant that got the highest rank-combination score, then the next highest, etc. going down in the descending order of the
rank-combination score taking into the final list those variants that are still within acceptable limits of at least one of the original
variant caller's confidence score. Stop, when none of the original variant callers had an acceptable confidence score any more.
A less stringent but more sensitive variation of this would be, to allow a certain percentage of lower confidence scores in the final
lists (e.g. 5%). If there are questions about the rank-combination.R script or the subsequent filtering,
please E-Mail: ariane.hofmann@bsse.ethz.ch


text:
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('mature_optimization.views',
    url(r'^$', 'dashboard',
         name='mature_optimization_dashboard'),

)


text:
Tour de Flex Mobile
===================

Tour de Flex Mobile is an Apache Flex application that showcases some of the features and capabilities of the Apache Flex and Adobe AIR SDKs.


text:
<?php
/**
 * The Header for our theme.
 *
 * Displays all of the  section and everything up till

 *
 * @package Adaption
 */
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>

	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title><?php wp_title( '|', true, 'right' ); ?></title>
	<link href="<?php echo get_template_directory_uri(); ?>/favicon.ico" rel="shortcut icon">
	<link rel="profile" href="http://gmpg.org/xfn/11">
	<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
	<link href='http://fonts.googleapis.com/css?family=Arimo:400,700,400italic&subset=latin,cyrillic-ext' rel='stylesheet' type='text/css'>
	<?php wp_head(); ?>

<body <?php body_class(); ?>>

	<?php do_action( 'before' ); ?>

		<?php
		if ( has_nav_menu( 'headerok' ) ) : ?>

				<?php wp_nav_menu( array(

				) ); ?>

		<?php endif; ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">Доктор Марина Невдовец

профессиональный косметолог

				<?php _e( 'Skip to content', 'adaption' ); ?>
				<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>

			<?php
			if ( has_nav_menu( 'social' ) ) : ?>

					<?php wp_nav_menu( array(
						'theme_location'  => 'social',
						'container_class' => 'social-links',
						'menu_class'      => 'clear',
						'link_before'     => '',
						'link_after'      => '',
					) ); ?>

			<?php endif; ?>

		<?php if ( is_active_sidebar( 'sidebar-1' ) || is_active_sidebar( 'sidebar-2' ) ) : ?>

					<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>

							<?php dynamic_sidebar( 'sidebar-1' ); ?>

					<?php endif; ?>

					<?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?>

							<?php dynamic_sidebar( 'sidebar-2' ); ?>

					<?php endif; ?>

		<?php endif; ?>

		<?php
		// You can upload a custom header and it'll output in a smaller logo size.
		$header_image = get_header_image();

		if ( ! empty( $header_image ) ) { ?>

				<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">
					<img src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" class="header-image" />

		<?php } else { ?>

		<?php } ?>

			<?php _e( 'Skip to content', 'adaption' ); ?>
			<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>

		<?php
		if ( has_nav_menu( 'social' ) ) : ?>

				<?php wp_nav_menu( array(
					'theme_location'  => 'social',
					'container_class' => 'social-links',
					'menu_class'      => 'clear',
					'link_before'     => '',
					'link_after'      => '',
				) ); ?>

		<?php endif; ?>

		<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>

				<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>

						<?php dynamic_sidebar( 'sidebar-1' ); ?>

				<?php endif; ?>

		<?php endif; ?>

	<?php get_sidebar(); ?>


text:
<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\ORM\Tools\ToolsException;
use Doctrine\Tests\Models\DDC2825\ExplicitSchemaAndTable;
use Doctrine\Tests\Models\DDC2825\SchemaAndTableInTableName;

/**
 * This class makes tests on the correct use of a database schema when entities are stored
 *
 * @group DDC-2825
 */
class DDC2825Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        parent::setUp();

        $platform = $this->_em->getConnection()->getDatabasePlatform();

        if ( ! $platform->supportsSchemas() && ! $platform->canEmulateSchemas()) {
            $this->markTestSkipped("This test is only useful for databases that support schemas or can emulate them.");
        }
    }

    /**
     * @dataProvider getTestedClasses
     *
     * @param string $className
     * @param string $expectedSchemaName
     * @param string $expectedTableName
     */
    public function testClassSchemaMappingsValidity($className, $expectedSchemaName, $expectedTableName)
    {
        $classMetadata   = $this->_em->getClassMetadata($className);
        $platform        = $this->_em->getConnection()->getDatabasePlatform();
        $quotedTableName = $this->_em->getConfiguration()->getQuoteStrategy()->getTableName($classMetadata, $platform);

        // Check if table name and schema properties are defined in the class metadata
        $this->assertEquals($expectedTableName, $classMetadata->table['name']);
        $this->assertEquals($expectedSchemaName, $classMetadata->table['schema']);

        if ($this->_em->getConnection()->getDatabasePlatform()->supportsSchemas()) {
            $fullTableName = sprintf('%s.%s', $expectedSchemaName, $expectedTableName);
        } else {
            $fullTableName = sprintf('%s__%s', $expectedSchemaName, $expectedTableName);
        }

        $this->assertEquals($fullTableName, $quotedTableName);

        // Checks sequence name validity
        $this->assertEquals(
            $fullTableName . '_' . $classMetadata->getSingleIdentifierColumnName() . '_seq',
            $classMetadata->getSequenceName($platform)
        );
    }

    /**
     * @dataProvider getTestedClasses
     *
     * @param string $className
     */
    public function testPersistenceOfEntityWithSchemaMapping($className)
    {
        try {
            $this->_schemaTool->createSchema([$this->_em->getClassMetadata($className)]);
        } catch (ToolsException $e) {
            // table already exists
        }

        $this->_em->persist(new $className());
        $this->_em->flush();
        $this->_em->clear();

        $this->assertCount(1, $this->_em->getRepository($className)->findAll());
    }

    /**
     * Data provider
     *
     * @return string[][]
     */
    public function getTestedClasses()
    {
        return [
            [ExplicitSchemaAndTable::class, 'explicit_schema', 'explicit_table'],
            [SchemaAndTableInTableName::class, 'implicit_schema', 'implicit_table'],
            [DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName::class, 'myschema', 'order'],
        ];
    }
}

/**
 * @Entity
 * @Table(name="myschema.order")
 */
class DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName
{
    /**
     * @Id @GeneratedValue
     * @Column(type="integer")
     *
     * @var integer
     */
    public $id;
}


text:
package co.viewfinder;

import android.app.Activity;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMBroadcastReceiver extends BroadcastReceiver {
  public static final String SENDER_ID = "1068184763319";
  private static final String TAG = "viewfinder.GCMBroadcastReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    String messageType = gcm.getMessageType(intent);

    if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
      Log.d(TAG, "Send error: " + intent.getExtras().toString());
    } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
      Log.d(TAG, "Deleted messages on server: " + intent.getExtras().toString());
    } else {
      Log.d(TAG, "Received: " + intent.getExtras().toString());
    }
    setResultCode(Activity.RESULT_OK);
  }
}


text:
package org.teavm.classlib.java.util.regex;

import static org.junit.Assert.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;

/**
 * TODO Type description
 */
@SuppressWarnings("nls")
@RunWith(TeaVMTestRunner.class)
public class PatternSyntaxExceptionTest {
    @Test
    public void testCase() {
        String regex = "(";
        try {
            Pattern.compile(regex);
            fail("PatternSyntaxException expected");
        } catch (PatternSyntaxException e) {
            // TOFIX: Commented out assertEquals tests...
            // TOFIX: should we match exception strings?
            // assertEquals("Unclosed group", e.getDescription());
            assertEquals(1, e.getIndex());
            // assertEquals("Unclosed group near index 1\n(\n ^",
            // e.getMessage());
            assertEquals(regex, e.getPattern());
        }
    }

    @Test
    public void testCase2() {
        String regex = "[4-";
        try {
            Pattern.compile(regex);
            fail("PatternSyntaxException expected");
        } catch (PatternSyntaxException e) {
            // TOFIX: Commented out assertEquals tests...
            // TOFIX: should we match exception strings?
            // assertEquals("Illegal character range", e.getDescription());
            assertEquals(3, e.getIndex());
            // assertEquals("Illegal character range near index 3\n[4-\n ^",
            // e.getMessage());
            assertEquals(regex, e.getPattern());
        }
    }
}


text:
package org.everit.password.encryptor.pbkdf2;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Objects;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.everit.credential.encryptor.CredentialEncryptor;
import org.everit.credential.encryptor.CredentialMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of {@link CredentialEncryptor} and {@link CredentialMatcher}.
 */
public class PBKDF2PasswordEncryptorImpl implements CredentialEncryptor, CredentialMatcher {

  private static final int ITERATION_COUNT_MIN_VALUE = 1;

  private static final Logger LOGGER = LoggerFactory.getLogger(PBKDF2PasswordEncryptorImpl.class);

  /**
   * The algorithm used to generate random salt.
   */
  private static final String SALT_ALGORITHM = "SHA1PRNG";

  private static final int SALT_BYTE = 8;

  /**
   * End separator character for the encrypted parts of the credential.
   */
  private static final String SEPARATOR_END = "}";

  /**
   * Start separator character for the encrypted parts of the credential.
   */
  private static final String SEPARATOR_START = "{";

  private String algorithm;

  /**
   * Pick an iteration count that works for you. The NIST recommends at least 1,000 iterations:
   * http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf iOS 4.x reportedly uses
   * 10,000: http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-
   * passwords/
   */
  private int iterationCount;

  /**
   * Constructor.
   *
   * @param algorithm
   *          The secure algorithm used to encrypt the passwords.
   * @param iterationCount
   *          the iteration count number. The NIST recommends at least 1,000 iterations:
   *          http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf iOS 4.x
   *          reportedly uses 10,000:
   *          http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-
   *          passwords/
   *
   * @throws NullPointerException
   *           if algorithm is null.
   * @throws IllegalArgumentException
   *           if iterationCount is not between
   *           {@link PBKDF2PasswordEncryptorImpl#ITERATION_COUNT_MIN_VALUE} and
   *           {@link Integer#MAX_VALUE} value. Or the algorithm is not supported.
   */
  public PBKDF2PasswordEncryptorImpl(final String algorithm, final int iterationCount) {
    this.algorithm = Objects.requireNonNull(algorithm, "algorithm cannot be null");
    if (!Algorithm.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS.containsKey(algorithm)) {
      throw new IllegalArgumentException("algorithm value [" + algorithm + "] is not supported, "
          + "supported values are "
          + Algorithm.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS.keySet().toString() + ".");
    }

    if ((iterationCount < ITERATION_COUNT_MIN_VALUE)) {
      throw new IllegalArgumentException("iterationCount value [" + iterationCount + "] must be "
          + "between [" + ITERATION_COUNT_MIN_VALUE + "," + Integer.MAX_VALUE + "]");
    }
    this.iterationCount = iterationCount;
  }

  @Override
  public String encrypt(final String plainPassword) {
    Objects.requireNonNull(plainPassword, "plainPassword cannot be null");
    try {
      byte[] salt = generateSalt();
      return encryptSecure(salt, plainPassword, algorithm);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException("Failed to encrypt password", e);
    } catch (InvalidKeySpecException e) {
      throw new IllegalStateException("Failed to encrypt password", e);
    }
  }

  private String encryptSecure(final byte[] salt, final String plainPassword,
      final String algorithm)
          throws NoSuchAlgorithmException, InvalidKeySpecException {
    int deriverdKeyLenght = Algorithm.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS.get(algorithm);
    KeySpec spec =
        new PBEKeySpec(plainPassword.toCharArray(), salt, iterationCount, deriverdKeyLenght);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
    byte[] passwordDigest = secretKeyFactory.generateSecret(spec).getEncoded();
    byte[] passwordDigestBase64 = Base64.encodeBase64(passwordDigest);
    String passwordDigestBase64StringUTF8 = StringUtils.newStringUtf8(passwordDigestBase64);
    byte[] saltBase64 = Base64.encodeBase64(salt);
    String saltBase64StringUTF8 = StringUtils.newStringUtf8(saltBase64);
    return SEPARATOR_START + algorithm + SEPARATOR_END
        + SEPARATOR_START + saltBase64StringUTF8 + SEPARATOR_END
        + passwordDigestBase64StringUTF8;
  }

  private byte[] generateSalt() throws NoSuchAlgorithmException {
    // VERY important to use SecureRandom instead of just Random
    SecureRandom random;
    random = SecureRandom.getInstance(SALT_ALGORITHM);
    // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
    byte[] salt = new byte[SALT_BYTE];
    random.nextBytes(salt);
    return salt;
  }

  private String getAlgorithmFromEncryptedCredential(final String encryptedPassword) {
    int beginIndex = encryptedPassword.indexOf(SEPARATOR_START);
    int endIndex = encryptedPassword.indexOf(SEPARATOR_END);
    return encryptedPassword.substring(beginIndex + 1, endIndex);
  }

  private String getSaltFromEncryptedCredential(final String encryptedPassword) {
    int beginIndex = encryptedPassword.lastIndexOf(SEPARATOR_START);
    int endIndex = encryptedPassword.lastIndexOf(SEPARATOR_END);
    return encryptedPassword.substring(beginIndex + 1, endIndex);
  }

  @Override
  public boolean match(final String plainPassword, final String encryptedPassword) {
    if ((plainPassword == null) || (encryptedPassword == null)) {
      return false;
    }
    String encryptedAttemptedCredential = null;
    try {
      String algorithm = getAlgorithmFromEncryptedCredential(encryptedPassword);
      String saltBase64 = getSaltFromEncryptedCredential(encryptedPassword);
      byte[] salt = Base64.decodeBase64(saltBase64);
      encryptedAttemptedCredential = encryptSecure(salt, plainPassword, algorithm);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      LOGGER.error("Credential check failed", e);
      return false;
    }
    return encryptedPassword.equals(encryptedAttemptedCredential);
  }

}


text:
module Rack::ActionLogger
  class Context

    def initialize(app)
      @app = app
    end

    def call(env)
      Emitter.new.emit do
        status_code, headers, body = @app.call(env)
        capture_rack_log(env, status_code, headers, body)
        [status_code, headers, body]
      end
    end

    def capture_rack_log(env, status_code, headers, body)
      rack_metrics = Rack::ActionLogger.configuration.rack_metrics.new(env, status_code, headers, body)
      return if rack_metrics.metrics.nil?
      Rack::ActionLogger::Container.set_request_log(rack_metrics.metrics, rack_metrics.tag_suffix)
      Rack::ActionLogger::Container.merge_attributes({ request_id: rack_metrics.request_id })
    end

  end
end


text:
package org.usfirst.frc.team166.robot.commands.autonomous;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

import org.usfirst.frc.team166.robot.Robot;

/**
 *
 */
public class DriveForwardBackwardDistance extends Command {
	private double driveSpeed;
	private double direction;
	private int distance;

	public DriveForwardBackwardDistance(double speed, double angle, int desiredDistance) {
		requires(Robot.drive);
		driveSpeed = speed;
		direction = angle;
		distance = desiredDistance;
	}

	// Called just before this Command runs the first time
	@Override
	protected void initialize() {
		Robot.drive.resetGyro();
		Robot.drive.resetEncoders();
	}

	// Called repeatedly when this Command is scheduled to run
	@Override
	protected void execute() {
		// Robot.drive.driveForwardBackwardDistance(driveSpeed, direction, distance);
		SmartDashboard.putNumber("Distance Traveled Command", Robot.drive.getEncoderDistance());
		Robot.drive.driveAngle(direction, driveSpeed);
	}

	// Make this return true when this Command no longer needs to run execute()
	@Override
	protected boolean isFinished() {
		return (Math.abs(Robot.drive.getEncoderDistance()) > distance);
	}

	// Called once after isFinished returns true
	@Override
	protected void end() {
		Robot.drive.stopMotors();
	}

	// Called when another command which requires one or more of the same
	// subsystems is scheduled to run
	@Override
	protected void interrupted() {
	}
}


text:
'use strict';

const co = require('co');
const RSVP = require('rsvp');
const ember = require('../helpers/ember');
const fs = require('fs-extra');
const replaceFile = require('ember-cli-internal-test-helpers/lib/helpers/file-utils').replaceFile;
let outputFile = RSVP.denodeify(fs.outputFile);
const path = require('path');
let remove = RSVP.denodeify(fs.remove);
let root = process.cwd();
let tmproot = path.join(root, 'tmp');
const mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in');

const Blueprint = require('../../lib/models/blueprint');
const BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint');

const chai = require('../chai');
let expect = chai.expect;
let file = chai.file;

describe('Acceptance: ember destroy pod', function() {
  let tmpdir;

  this.timeout(20000);

  before(function() {
    BlueprintNpmTask.disableNPM(Blueprint);
  });

  after(function() {
    BlueprintNpmTask.restoreNPM(Blueprint);
  });

  beforeEach(co.wrap(function *() {
    tmpdir = yield mkTmpDirIn(tmproot);
    process.chdir(tmpdir);
  }));

  afterEach(function() {
    this.timeout(10000);

    process.chdir(root);
    return remove(tmproot);
  });

  function initApp() {
    return ember([
      'init',
      '--name=my-app',
      '--skip-npm',
      '--skip-bower',
    ]);
  }

  function generate(args) {
    let generateArgs = ['generate'].concat(args);
    return ember(generateArgs);
  }

  function destroy(args) {
    let destroyArgs = ['destroy'].concat(args);
    return ember(destroyArgs);
  }

  function assertFilesExist(files) {
    files.forEach(function(f) {
      expect(file(f)).to.exist;
    });
  }

  function assertFilesNotExist(files) {
    files.forEach(function(f) {
      expect(file(f)).to.not.exist;
    });
  }

  const assertDestroyAfterGenerate = co.wrap(function *(args, files) {
    yield initApp();

    replaceFile('config/environment.js', "(var|let|const) ENV = {", "$1 ENV = {\npodModulePrefix: 'app/pods', \n");

    yield generate(args);
    assertFilesExist(files);

    let result = yield destroy(args);
    expect(result, 'destroy command did not exit with errorCode').to.be.an('object');
    assertFilesNotExist(files);
  });

  const assertDestroyAfterGenerateWithUsePods = co.wrap(function *(args, files) {
    yield initApp();

    replaceFile('.ember-cli', '"disableAnalytics": false', '"disableAnalytics": false,\n"usePods" : true\n');

    yield generate(args);
    assertFilesExist(files);

    let result = yield destroy(args);
    expect(result, 'destroy command did not exit with errorCode').to.be.an('object');
    assertFilesNotExist(files);
  });

  const destroyAfterGenerateWithPodsByDefault = co.wrap(function *(args) {
    yield initApp();

    replaceFile('config/environment.js', "(var|let|const) ENV = {", "$1 ENV = {\nusePodsByDefault: true, \n");

    yield generate(args);
    return yield destroy(args);
  });

  const destroyAfterGenerate = co.wrap(function *(args) {
    yield initApp();

    replaceFile('config/environment.js', "(var|let|const) ENV = {", "$1 ENV = {\npodModulePrefix: 'app/pods', \n");

    yield generate(args);
    return yield destroy(args);
  });

  it('.ember-cli usePods setting destroys in pod structure without --pod flag', function() {
    let commandArgs = ['controller', 'foo'];
    let files = [
      'app/foo/controller.js',
      'tests/unit/foo/controller-test.js',
    ];

    return assertDestroyAfterGenerateWithUsePods(commandArgs, files);
  });

  it('.ember-cli usePods setting destroys in classic structure with --classic flag', function() {
    let commandArgs = ['controller', 'foo', '--classic'];
    let files = [
      'app/controllers/foo.js',
      'tests/unit/controllers/foo-test.js',
    ];

    return assertDestroyAfterGenerateWithUsePods(commandArgs, files);
  });

  it('.ember-cli usePods setting correctly destroys component', function() {
    let commandArgs = ['component', 'x-foo'];
    let files = [
      'app/components/x-foo/component.js',
      'app/components/x-foo/template.hbs',
      'tests/integration/components/x-foo/component-test.js',
    ];

    return assertDestroyAfterGenerateWithUsePods(commandArgs, files);
  });

  it('blueprint foo --pod', function() {
    let commandArgs = ['blueprint', 'foo', '--pod'];
    let files = ['blueprints/foo/index.js'];

    return assertDestroyAfterGenerate(commandArgs, files);
  });

  it('blueprint foo/bar --pod', function() {
    let commandArgs = ['blueprint', 'foo/bar', '--pod'];
    let files = ['blueprints/foo/bar/index.js'];

    return assertDestroyAfterGenerate(commandArgs, files);
  });

  it('http-mock foo --pod', function() {
    let commandArgs = ['http-mock', 'foo', '--pod'];
    let files = ['server/mocks/foo.js'];

    return assertDestroyAfterGenerate(commandArgs, files);
  });

  it('http-proxy foo --pod', function() {
    let commandArgs = ['http-proxy', 'foo', 'bar', '--pod'];
    let files = ['server/proxies/foo.js'];

    return assertDestroyAfterGenerate(commandArgs, files);
  });

  it('deletes files generated using blueprints from the project directory', co.wrap(function *() {
    let commandArgs = ['foo', 'bar', '--pod'];
    let files = ['app/foos/bar.js'];

    yield initApp();

    yield outputFile(
      'blueprints/foo/files/app/foos/__name__.js',
      "import Ember from 'ember';\n\n" +
      'export default Ember.Object.extend({ foo: true });\n'
    );

    yield generate(commandArgs);
    assertFilesExist(files);

    yield destroy(commandArgs);
    assertFilesNotExist(files);
  }));

  it('correctly identifies the root of the project', co.wrap(function *() {
    let commandArgs = ['controller', 'foo', '--pod'];
    let files = ['app/foo/controller.js'];

    yield initApp();

    yield outputFile(
      'blueprints/controller/files/app/__path__/__name__.js',
      "import Ember from 'ember';\n\n" +
      "export default Ember.Controller.extend({ custom: true });\n"
    );

    yield generate(commandArgs);
    assertFilesExist(files);

    process.chdir(path.join(tmpdir, 'app'));
    yield destroy(commandArgs);

    process.chdir(tmpdir);
    assertFilesNotExist(files);
  }));

  // Skip until podModulePrefix is deprecated
  it.skip('podModulePrefix deprecation warning', co.wrap(function *() {
    let result = yield destroyAfterGenerate(['controller', 'foo', '--pod']);

    expect(result.outputStream.join()).to.include("`podModulePrefix` is deprecated and will be" +
      " removed from future versions of ember-cli. Please move existing pods from" +
      " 'app/pods/' to 'app/'.");
  }));

  it('usePodsByDefault deprecation warning', co.wrap(function *() {
    let result = yield destroyAfterGenerateWithPodsByDefault(['controller', 'foo', '--pod']);

    expect(result.outputStream.join()).to.include('`usePodsByDefault` is no longer supported in' +
      ' \'config/environment.js\', use `usePods` in \'.ember-cli\' instead.');
  }));

});


text:
<?php

namespace Com\PaulDevelop\Library\Template;

    //include_once('Com.PaulDevelop.Library/src/class/GenericCollection.class.php');
    //include_once('phar://Com.PaulDevelop.Library.phar/class/GenericCollection.class.php');
//include_once('Attribute.class.php');
use Com\PaulDevelop\Library\Common\GenericCollection;

/**
 * AttributeCollection
 *
 * @package  Com\PaulDevelop\Library\Template
 * @category Template
 * @author   Rüdiger Scheumann <code@pauldevelop.com>
 * @license  http://opensource.org/licenses/MIT MIT
 */
class AttributeCollection extends GenericCollection
{
    #region constructor
    public function __construct()
    {
        parent::__construct('Com\PaulDevelop\Library\Template\Attribute');
    }
    #endregion

    #region methods
    /**
     * Parse raw string containing attributes.
     *
     * @param string $rawAttributes
     *
     * @return AttributeCollection
     */
    public static function parse($rawAttributes = '')
    {
        // init
        $result = new AttributeCollection();

        // action
        $rawAttributes = trim($rawAttributes);
        $keyIsOpen = true;
        $valueIsOpen = false;
        $key = '';
        $value = '';
        for ($i = 0; $i < strlen($rawAttributes); $i++) {
            $prevChar = ($i > 0) ? substr($rawAttributes, $i - 1, 1) : '';
            $currentChar = substr($rawAttributes, $i, 1);

            if ($keyIsOpen) {
                if ($currentChar == '=') {
                    $keyIsOpen = false;
                } else {
                    $key .= $currentChar;
                }
            } else {
                if ($prevChar != '\\' && $currentChar == '"') {
                    if ($valueIsOpen) {
                        $key = trim($key);
                        $value = trim($value);
                        $attribute = Attribute::Parse($key.'='.$value);
                        $result->Add($attribute, $key);

                        // reset
                        $key = '';
                        $value = '';
                        $keyIsOpen = true;
                        $valueIsOpen = false;
                    } else {
                        $valueIsOpen = true;
                    }
                } else {
                    if ($prevChar == '\\') {
                        $value = substr($value, 0, strlen($value) - 1);
                    }
                    $value .= $currentChar;
                }
            }
        }

        // return
        return $result;
    }

    public function toString()
    {
        // init
        $result = '';

        // action
        foreach ($this->collection as $attribute) {
            /* @var $attribute Attribute */
            $result .= (empty($result) ? '' : ' ').$attribute->ToString();
        }

        // return
        return $result;
    }
    #endregion
}


text:
int main(int, char*[])
{
	logger::init();
	logger::setSeverityLevel(DEBUG);
	auto slg = logger::getSLogger();
#ifndef RUN_EDITOR
	Game theGame;
	std::string mapFile;
	std::cout << "Enter map filename: ";
	std::cin >> mapFile;
	theGame.initialize("gameConfig.ini", "resources.xml", "objects.xml", mapFile, "save.xml", 0);
	theGame.begin();	//starts SFML main loop
#else
	Editor theEditor;
	std::string mapFile;
	std::cout << "Enter map filename: ";
	std::cin >> mapFile;
	theEditor.initialize("gameConfig.ini", "resources.xml", "objects.xml", mapFile, "save.xml", 0);
	theEditor.editorInitialize();
	theEditor.editorBegin();
#endif
	BOOST_LOG_SEV(slg, DEBUG) << "Exiting soon";

	return 0;
}

#endif

#ifdef RUN_TESTS

#include "Utility\Logger.hpp"
#include "Utility\UnitTester.hpp"
#include "Utility\Utilities.hpp"

#define TEST_ALL

int main(int, char*[])
{
	logger::init();
	logger::setSeverityLevel(DEBUG);
	auto slg = logger::getSLogger();

	BOOST_LOG_SEV(slg, INFO) << "Starting Unit Tests...";

	testing::UnitTester testObject;
	testObject.runTests();

	BOOST_LOG_SEV(slg, INFO) << "Unit test completed...";
}

#endif


text:
package io.undertow.websockets.jsr;

import io.undertow.servlet.api.InstanceFactory;
import io.undertow.util.PathTemplate;

import javax.websocket.Endpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Stuart Douglas
 */
public class ConfiguredServerEndpoint {

    private final ServerEndpointConfig endpointConfiguration;
    private final InstanceFactory<Endpoint> endpointFactory;
    private final PathTemplate pathTemplate;
    private final EncodingFactory encodingFactory;
    private final Set<Session> openSessions = Collections.newSetFromMap(new ConcurrentHashMap<Session, Boolean>());

    public ConfiguredServerEndpoint(final ServerEndpointConfig endpointConfiguration, final InstanceFactory<Endpoint> endpointFactory, final PathTemplate pathTemplate, final EncodingFactory encodingFactory) {
        this.endpointConfiguration = endpointConfiguration;
        this.endpointFactory = endpointFactory;
        this.pathTemplate = pathTemplate;
        this.encodingFactory = encodingFactory;
    }

    public ServerEndpointConfig getEndpointConfiguration() {
        return endpointConfiguration;
    }

    public InstanceFactory<Endpoint> getEndpointFactory() {
        return endpointFactory;
    }

    public PathTemplate getPathTemplate() {
        return pathTemplate;
    }

    public EncodingFactory getEncodingFactory() {
        return encodingFactory;
    }

    public Set<Session> getOpenSessions() {
        return openSessions;
    }
}


text:
extern "Java"
{
  namespace gnu
  {
    namespace xml
    {
      namespace pipeline
      {
          class EventConsumer;
          class XsltFilter;
      }
    }
  }
}

class gnu::xml::pipeline::XsltFilter : public ::gnu::xml::pipeline::EventFilter
{

public:
  XsltFilter(::java::lang::String *, ::gnu::xml::pipeline::EventConsumer *);
  static ::java::lang::Class class$;
};

#endif // __gnu_xml_pipeline_XsltFilter__


text:
set -e

# This is borrowed from https://github.com/dotnet/cli/blob/18456af5caeae44defc23ad5579c838c1fda3c3d/run.sh
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

# run from directory of launch.sh so artifacts are placed appropriately
pushd "$DIR"

if [[ -z "$FORK" ]]; then
    FORK=PowerShell
fi

if [[ -z "$BRANCH" ]]; then
    BRANCH=master
fi

# Build both sets by default
if [[ -z "$BUILDS" ]]; then
    BUILDS="stable unstable"
fi

# Build specified distributions
if [[ -z $DISTROS ]]; then
    DISTROS="ubuntu14.04 ubuntu16.04 centos7"
fi

for build in $BUILDS; do
    # each distro can be done in parallel; but stable must be done before unstable
    for distro in $DISTROS; do
        logfile="$build-$distro.log"
        if [[ "$TEST" -eq 1 ]]; then logfile="test-$logfile"; fi
        mkdir -p logs
        logfile="logs/$logfile"
        echo "Logging to docker/$logfile"
        (
            image="powershell/powershell:$build-$distro"
            pushd "$build"
            if [[ "$TEST" -eq 1 ]]; then
                echo "LOG: testing $image"
                command="cd PowerShell; Import-Module ./build.psm1; Install-Dotnet -NoSudo; Start-PSPester -powershell powershell -Pester ./src/Modules/Shared/Pester"
                # clone repo for stable images because it's not already done
                if [[ "$build" = stable ]]; then
                    command="git clone --recursive https://github.com/$FORK/PowerShell -b $BRANCH; $command"
                fi
                # run Pester tests inside container
                # RUNARGS can be set in the environment
                docker run $RUNARGS "$image" -c "$command"
            else
                echo "LOG: building $image"
                # copy the common script because it lives outside the docker build context
                if [[ "$build" = unstable ]]; then
                    cp bootstrap.ps1 "$distro"
                    buildargs="--build-arg fork=$FORK --build-arg branch=$BRANCH"
                fi
                # build and tag the image so they can be derived from
                # BUILDARGS can be set in the environment
                docker build $buildargs $BUILDARGS -t "$image" "$distro"
                if [[ "$build" = unstable ]]; then
                    echo "LOG: Saving package to docker/packages"
                    popd
                    mkdir -p packages
                    command='cp -vf /PowerShell/powershell*{deb,rpm} /mnt 2> /dev/null'
                    # override entrypoint to be bash so we can use globbing
                    docker run --rm --volume "$(pwd)/packages:/mnt" --entrypoint bash "$image" -c "$command"
                fi
            fi
        ) &>> "$logfile" &
    done
    echo "Waiting for $build containers to finish; tail the logs for more information."
    wait
done

popd


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>be.c4j.ee.squad.demo</groupId>
    <artifactId>jpa_jms</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>jpa_jms</finalName>
    </build>
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
</project>


text:
package com.msi.tough.utils;

import java.io.File;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.DigestUtils;

import com.msi.tough.cf.AccountType;
import com.msi.tough.cf.ec2.KeyPairType;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.FileUtils;
import com.msi.tough.core.StringHelper;
import com.msi.tough.engine.aws.ec2.KeyPair;
import com.msi.tough.engine.aws.ec2.SecurityGroup;
import com.msi.tough.engine.core.CallStruct;
import com.msi.tough.engine.core.TemplateContext;

public class KeyPairUtils {

    // TODO: record user salt
    private static final String SALT = "d68aba4c2916cc6ffed43168ffb44419";

    public static KeyPairType createKeyPair(final AccountType ac,
            final TemplateContext ctx, final String parentId,
            final String stackId, final String availabilityZone,
            final String name) throws Exception {

        final CallStruct c = new CallStruct();
        c.setAc(ac);
        c.setCtx(ctx);
        c.setParentId(parentId);
        c.setStackId(stackId);
        c.setAvailabilityZone(availabilityZone);
        c.setName(name);
        final Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(Constants.AVAILABILITYZONE, ac.getDefZone());
        c.setProperties(properties);
        c.setType(SecurityGroup.TYPE);
        final KeyPair provider = new KeyPair();
        final KeyPairType kp = (KeyPairType) provider.create(c);
        if (kp != null) {
            final String kdir = Appctx.getConfigurationBean("KEYS_DIR");
            final String kf = kdir + "/" + name + ".pem";
            StringHelper.writeTofile(kp.getMaterial(), kf);
            FileUtils.chmod(kf, "0600");
        }
        return kp;
    }

    public static KeyPairType deleteKeyPair(final AccountType ac,
            final TemplateContext ctx, final String parentId,
            final String stackId, final String availabilityZone,
            final String name) throws Exception {

        final CallStruct c = new CallStruct();
        c.setAc(ac);
        c.setCtx(ctx);
        c.setParentId(parentId);
        c.setStackId(stackId);
        c.setAvailabilityZone(availabilityZone);
        c.setName(name);
        final Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(Constants.AVAILABILITYZONE, ac.getDefZone());
        c.setProperties(properties);
        c.setType(SecurityGroup.TYPE);
        final KeyPair provider = new KeyPair();
        final KeyPairType kp = (KeyPairType) provider.delete(c);

        final String kdir = Appctx.getConfigurationBean("KEYS_DIR");
        final String kf = kdir + "/" + name + ".pem";
        final File fl = new File(kf);
        fl.delete();
        return kp;
    }

    public static String getKeyName(final String uniqueValue) {
        String installId = Appctx.getConfigurationBean("INSTALL_ID");
        try {
            if (installId == null || "".equals(installId)
                    || installId.startsWith("${")) {
                installId = java.net.InetAddress.getLocalHost().getHostName();
            }
        } catch (final UnknownHostException e) {
            installId = "Unknown";
        }
        final String munged = DigestUtils
                .md5DigestAsHex((SALT + installId + uniqueValue).getBytes());
        return "__key_" + munged + "_transcend-key";
    }
}


text:
from seahub.test_utils import BaseTestCase
from seahub.api2.models import TokenV2, TokenV2Manager

class TokenV2ManagerTest(BaseTestCase):
    def setUp(self):
        assert len(TokenV2.objects.all()) == 0

        token = TokenV2(user=self.user.username,
                        platform='ios',
                        device_id='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                        device_name='fake device name',
                        client_version='1.0.0',
                        platform_version='0.0.1',
                        last_login_ip=self.ip_v6)
        token.save()

        assert len(TokenV2.objects.all()) == 1
        self.token = TokenV2.objects.all()[0]

    def test_get_devices(self):
        d = TokenV2.objects.get_devices('', 0, 10)
        assert len(d) == 1

    def test_get_user_devices(self):
        d = TokenV2.objects.get_user_devices(self.user.username)
        assert len(d) == 1

    def test_get_or_create_token(self):
        # get exist token
        t = TokenV2.objects.get_or_create_token(
            self.token.user, self.token.platform, self.token.device_id,
            self.token.device_name, '1.1.1', '0.1.1', self.ip_v6)
        assert t.key == self.token.key

        # create new token
        t = TokenV2.objects.get_or_create_token(
            self.admin.username, self.token.platform, self.token.device_id,
            self.token.device_name, '1.1.1', '0.1.1', self.ip_v6)
        assert len(TokenV2.objects.all()) == 2
        assert TokenV2.objects.all()[1].user == self.admin.username

    def test_delete_device_token(self):
        TokenV2.objects.delete_device_token(
            self.token.user, self.token.platform, self.token.device_id)
        assert len(TokenV2.objects.all()) == 0

    def test_mark_device_to_be_remote_wipted(self):
        assert TokenV2.objects.all()[0].wiped_at is None

        TokenV2.objects.mark_device_to_be_remote_wiped(
            self.token.user, self.token.platform, self.token.device_id)
        assert TokenV2.objects.all()[0].wiped_at is not None

class TokenV2Test(BaseTestCase):
    def test_save(self):
        assert len(TokenV2.objects.all()) == 0

        token = TokenV2(user=self.user.username,
                        platform='ios',
                        device_id='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                        device_name='fake device name',
                        client_version='1.0.0',
                        platform_version='0.0.1',
                        last_login_ip=self.ip_v6)
        token.save()

        assert len(TokenV2.objects.all()) == 1

        t = TokenV2.objects.all()[0]
        assert len(t.key) == 40
        assert t.user == self.user.username
        assert t.created_at is not None
        assert t.last_accessed is not None
        assert t.wiped_at is None

    def test_as_dict(self):
        token = TokenV2(user=self.user.username,
                        platform='ios',
                        device_id='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                        device_name='fake device name',
                        client_version='1.0.0',
                        platform_version='0.0.1',
                        last_login_ip=self.ip_v6)
        token.save()
        t = TokenV2.objects.all()[0]
        assert len(t.as_dict()) == 10


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="actionbar_bg">#80000000</color>
    <color name="actionbar_text">#222222</color>
    <color name="actionbar_tab_text">#F8F8F8</color>
    <color name="imageview_bg">#222222</color>

    <color name="color_white">#FFFFFF</color>
    <color name="color_photogray">#F8F8F8</color>
    <color name="color_transparent">#00000000</color>
    <color name="color_semi_transparent_dark">#80000000</color>
    <color name="color_semi_transparent_light">#80FFFFFF</color>
    <color name="color_darkgray">#222222</color>
    <color name="color_lightgray">#F8F8F8</color>
    <color name="color_gray">#888888</color>

    <color name="app_bg">#F3F1EC</color>
    <color name="settings_view_bg">#F3F1EC</color>
    <color name="action_bar_bg">#E8E5DD</color>
    <color name="pager_title_strip_bg">#222222</color>
    <color name="pager_title_strip_text">#EFEFEF</color>

    <color name="capture_view_banner_bg">#5A1A2D</color>
    <color name="capture_view_banner_bg_highlight">#66A4BD</color>

    <color name="palette_card_bg">#F3F1EC</color>
    <color name="palette_card_border">#222222</color>
    <color name="palette_card_pic_init_bg">#FAFAFA</color>
    <color name="palette_card_title_bg">#222222</color>
    <color name="palette_card_colors_bar_bg">#FAFAFA</color>

    <color name="palette_list_item_bg">#F3F1EC</color>
    <color name="palette_list_item_bg_pressed">#BBDBE7</color>

    <color name="color_info_list_item_bg">#F3F1EC</color>
    <color name="color_info_list_item_bg_pressed">#BBDBE7</color>

    <color name="capture_view_colors_bar_border">#ECECEC</color>

    <color name="button_no_bg_highlight">#BBDBE7</color>
    <color name="button_dark_bg">#80000000</color>
    <color name="button_dark_bg_highlight">#40000000</color>

    <color name="clickable_text">#1F6181</color>
    <color name="clickable_text_pressed">#66A4BD</color>

    <color name="color_bar_text">#EFEFEF</color>
    <color name="color_bar_text_shadow">#222222</color>

    <color name="about_bar_linkedin_bg">#0085AF</color>
    <color name="about_bar_feedback_bg">#9A2715</color>
    <color name="about_bar_rate_bg">#D97345</color>
    <color name="about_bar_project_bg">#4C655F</color>

</resources>


text:
from optparse import make_option

from django.conf import settings
from django.db.models import get_model
from django.utils.translation import ugettext_lazy as _
from django.core.management.base import NoArgsCommand

from oscar_mws.feeds import gateway

Product = get_model('catalogue', 'Product')

class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option(
            '--lookup-asins',
            action='store_true',
            dest='lookup_asins',
            default=False,
            help=_('Updates the ASINs for all products without one.')
        ),
    )

    def handle_noargs(self, **options):
        if options.get('lookup_asins'):
            products = Product.objects.filter(
                amazon_profile__asin=''
            )
            gateway.update_product_identifiers(
                products,
                marketplace_id=settings.MWS_MARKETPLACE_ID
            )


text:
<!DOCTYPE html>

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="description" content="Sitio para desarrolladores de MercadoPago.">
      <meta name="keywords" content="mercadopago,sdk,payment,pagos,braintree,paypal,html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs">
      <title>Soluciones de pago para el negocio que quieras - MercadoPago</title>
      <link href="./css/site.css" rel="stylesheet">
      <link href="./css/prism.css" rel="stylesheet" />

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

               <button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse">

               </button>

Upgrade from 0.9.x

Nuestro Checkout

Tu checkout

Foro de desarrolladores

2.x MercadoPago SDK upgrade

                  ¿Already using our SDK's?

                  If you update to 2.x, you'll need to make some changes to mantain your 0.9.x integration.

                  Please, if you have any problems or find any not-listed incompatibility, open an issue in our Github repository

Changes in...

                         VaultActivity

                         PaymentMethodsActivity

                         IssuersActivity

                         InstallmentsActivity

                         NewCardActivity

                         CongratsActivity

                         CustomerCardsActivity

                         MercadoPago API Calls

                         MercadoPagoUtil

VaultActivity

                      The only change: now it requires Site.

new MercadoPago.StartActivityBuilder()
        .setActivity(this)
        .setPublicKey(ExamplesUtils.DUMMY_MERCHANT_PUBLIC_KEY)
        .setAmount(ExamplesUtils.DUMMY_ITEM_UNIT_PRICE)
        .setSupportedPaymentTypes(mSupportedPaymentTypes)
        .setSite(Sites.ARGENTINA) //Heads up!
        .setShowBankDeals(true)
        .startVaultActivity();

                 <button class="copy-button">

                </button>

              Note: setSupportedPaymentTypes method is deprecated. Replace it for setPaymentPreference. See the docs: customize your components.

PaymentMethodsActivity

                       In 2.x when an error occurs, its result is a MPException (Which may include an ApiException instance).

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == MercadoPago.PAYMENT_METHODS_REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
             // Set message
             PaymentMethod paymentMethod = JsonUtil.getInstance().fromJson(data.getStringExtra("paymentMethod"), PaymentMethod.class);

         } else {
             if ((data != null) && (data.getStringExtra("mpException") != null)) {
                 MPException mpException = JsonUtil.getInstance().fromJson(data.getStringExtra("mpException"), MPException.class);
             }
         }
     }
 }

                     <button class="copy-button">

                    </button>

IssuersActivity

                       When an error occurs its result is a MPException (Which may include an ApiException instance).

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (requestCode == MercadoPago.ISSUERS_REQUEST_CODE) {
              if (resultCode == RESULT_OK) {
                  // Set message
                  Issuer issuer = JsonUtil.getInstance().fromJson(data.getStringExtra("issuer"), Issuer.class);

              } else {
                  if ((data != null) && (data.getStringExtra("mpException") != null)) {
                      MPException mpException = JsonUtil.getInstance().fromJson(data.getStringExtra("mpException"), MPException.class);
                  }
              }
          }
      }

                         <button class="copy-button">

                        </button>

InstallmentsActivity

                       In addition to the list of payer costs, it needs the Amount and the Site.

new MercadoPago.StartActivityBuilder()
        .setActivity(activity)
        .setPayerCosts(payerCosts)
        .setSite(Sites.ARGENTINA)
        .setAmount(amount)
        .startInstallmentsActivity();

                     <button class="copy-button">

                    </button>

                 Also, when an error occurs its result is a MPException (Which may include an ApiException instance).

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MercadoPago.INSTALLMENTS_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Set message
            PayerCost payerCost = JsonUtil.getInstance().fromJson(data.getStringExtra("payerCost"), PayerCost.class);

        } else {
            if ((data != null) && (data.getStringExtra("mpException") != null)) {
                MPException mpException = JsonUtil.getInstance().fromJson(data.getStringExtra("mpException"), MPException.class);
            }
        }
    }
}

                     <button class="copy-button">

                    </button>

NewCardActivity

                   Deprecated. Usage of CardVaultActivity is recommended. See the docs: get card payments.

CongratsActivity

                      CongratsActivity now resolves approved payments only. Change it for PaymentResultActivity:

new MercadoPago.StartActivityBuilder()
            .setPublicKey(publicKey)
            .setActivity(activity)
            .setPayment(payment)
            .setPaymentMethod(paymentMethod)
            .startPaymentResultActivity();

                 <button class="copy-button">

                </button>

CustomerCardsActivity

                      In 2.x, it returns a "Card" object:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MercadoPago.CUSTOMER_CARDS_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Card selectedCard = JsonUtil.getInstance().fromJson(data.getStringExtra("card"), Card.class);
            //Do something...
        } else if ((data != null) && (data.getStringExtra("mpException") != null)) {
            MPException mpException = JsonUtil.getInstance().fromJson(data.getStringExtra("mpException"), MPException.class);
            //Handle error.
        }
    }
}

                 <button class="copy-button">

                </button>

MercadoPago API calls

                      2.x introduces a custom Callback from MercadoPago instead of returning the Retrofit "Call" object.

                    A generic example:

 0.9.x:

callback = new ErrorHandlingCallAdapter.MyCallback<T>() {
            @Override
            public void success(Response<T> response) {
                //Do something...
             }

            @Override
            public void failure(ApiException apiException) {
              //Handle failure.
            }
        }

ErrorHandlingCallAdapter.MyCall<T> call = mercadoPago.getT(parameters);
call.enqueue(callback);

                 <button class="copy-button">

                </button>

 2.x:

//Heads up! Callback from package com.mercadopago.callbacks
callback = new Callback<T>() {
	          @Override
            public void success(T t) {
                //Do something...
             }

            @Override
            public void failure(ApiException apiException) {
              //Handle failure.
            }
}
mercadoPago.getT(parameters, callback);

                   <button class="copy-button">

                  </button>

 Example:

mercadoPago.getPaymentMethods(new Callback<List<PaymentMethod>>() {
          @Override
          public void success(List<PaymentMethod> paymentMethods) {
              //Do something...
          }

          @Override
          public void failure(ApiException apiException) {
              //Handle failure.
          }
      });

                   <button class="copy-button">

                  </button>

MercadoPagoUtil

Minor changes:

                   0.9.x:

 MercadoPagoUtil.isCardPaymentType(String paymentType);

                      <button class="copy-button">

                     </button>

                   2.x:

MercadoPagoUtil.isCard(String paymentType);

                      <button class="copy-button">

                     </button>

                  © 2016 MercadoLibre S.R.L.


text:
var ItemSchema = require('../domain/item-schema');
var logger = require('../support/logger');

module.exports = {
    handle: function(ljsReq, callback) {
        var collectionName = ljsReq.ljsUrl().collectionName;

        ItemSchema.findByCollectionName(collectionName, function(err, itemSchema) {
            if (err) { return callback(err); }

            if (itemSchema === null) {
                return callback(null);
            }

            var model = itemSchema.constructModel();
            ItemSchema.attachModel(model);

            itemSchema.registerModel(model, function(err) {
                if (err) { return callback(err); }
                logger.info('Loopback Model created for JSON Schema collectionName: ', itemSchema.collectionName);
                callback(null);
            });
        });
    }
};


text:
local mnemonic = require("mnemonic")
local arc4random = require("arc4random")
local crypto = require("crypto")
local lru = require("lru")
local yaml = require("yaml")
local ngx = require("ngx")
local urldecode = require("lapis.util").unescape
local encode_with_secret = require("lapis.util.encoding").encode_with_secret
local decode_with_secret = require("lapis.util.encoding").decode_with_secret
local model = require("pasta.models")
local config = require("lapis.config").get()

local view = {}

local cache
if config.pastas_cache then
    cache = lru.new(
        config.pastas_cache.nrecords,
        config.pastas_cache.nbytes
    )
end

local number_of_pastas

local function apiResponse(object)
    return yaml.dump(object), {
        content_type = 'application/yaml',
        layout = false,
    }
end

local function makeMnemonic(nwords)
    local words = mnemonic.randomWords(nwords, arc4random.random)
    return table.concat(words, '-')
end

local function makeToken(nwords)
    return makeMnemonic(nwords)
end

local function makeHash(token)
    local text = config.hash_secret1 .. token .. config.hash_secret2
    return crypto.digest('SHA256', text)
end

local function makePassword()
    return makeMnemonic(config.nwords.password)
end

local function makePasswordHash(password)
    local text = config.password_secret1 .. password .. config.password_secret2
    return crypto.digest('SHA256', text)
end

local function makeSalt()
    return makeMnemonic(config.nwords.salt)
end

local function makeKey(salt, token)
    return salt .. "|" .. token
end

local function deletePasta(p, token)
    p:delete()
    if cache then
        cache:delete(token)
    end
    if number_of_pastas then
        number_of_pastas = number_of_pastas - 1
    end
end

local function loadPasta(request)
    request.token = request.params.token
    request.p = cache and cache:get(request.token)
    if not request.p then
        local hash = makeHash(request.token)
        request.p = model.Pasta:find(hash)
        if request.p and cache then
            cache:set(request.token, request.p, #request.p.content)
        end
    end
    if request.p then
        if request.p.self_burning then
            local key = makeKey(request.p.salt, request.token)
            local info = decode_with_secret(request.p.content, key)
            request.p_content = info.content
            request.p_filename = info.filename
            deletePasta(request.p, request.token)
        else
            request.p_content = request.p.content
            request.p_filename = request.p.filename
        end
    else
        request.token = nil
    end
end

local function isEditable(p)
    return p.password ~= '' and not p.self_burning
end

local function checkFilename(filename)
    if type(filename) ~= 'string' then
        return nil, "Filename must be a string"
    end
    if #filename > config.max_filename then
        return nil, "Filename is too long. Max " .. config.max_filename
    end
    if filename:match('/') then
        return nil, "Filename must not contain /"
    end
    return true
end

local function makePasta(filename, content, pasta_type)
    local filename_ok, message = checkFilename(filename)
    if type(content) ~= 'string' then
        return nil, "Content must be a string"
    end
    if type(pasta_type) ~= 'string' then
        return nil, "pasta_type must be a string"
    end
    if not filename_ok then
        return filename_ok, message
    end
    local password_hash = ''
    local self_burning = false
    local redirect_to = false
    local nwords = config.nwords.short
    local password_plain
    if pasta_type == 'standard' then
    elseif pasta_type == 'editable' then
        password_plain = makePassword()
        password_hash = makePasswordHash(password_plain)
    elseif pasta_type == 'self_burning' then
        self_burning = true
        nwords = config.nwords.long
    elseif pasta_type == 'url_shortener' then
        filename = ''
        redirect_to = true
    else
        return nil, "Unknown pasta type"
    end
    -- try to find a free token
    local p, token
    for i = nwords, nwords * 2 do
        token = makeToken(i)
        local salt = ''
        if pasta_type == 'self_burning' then
            local info = {
                filename = filename,
                content = content,
            }
            filename = ''
            salt = makeSalt()
            local key = makeKey(salt, token)
            content = encode_with_secret(info, key)
        end
        local _, msg = pcall(function()
            p = model.Pasta:create {
                hash = makeHash(token),
                self_burning = self_burning,
                redirect_to = redirect_to,
                filename = filename,
                salt = salt,
                content = content,
                password = assert(password_hash),
            }
        end)
        if p then
            break
        elseif msg:match('invalid message format') then
            return nil, "Failed to create paste"
        end
    end
    if not p then
        return nil, "No free tokens available"
    end
    if number_of_pastas then
        number_of_pastas = number_of_pastas + 1
    end
    if cache then
        cache:set(token, p, #p.content)
    end
    return {
        token = token,
        password_plain = password_plain,
    }
end

local function getExt(filename)
  if not filename then
    return nil
  end
  local ext = filename:match('%.([^.]+)$')
  if ext and #ext < 10 then
    return ext
  end
end

function view.index(request)
    request.no_new_pasta = true
    return {render = true}
end

function view.createPasta(request)
    local pasta, err = makePasta(
        request.params.filename,
        request.params.content,
        request.params.pasta_type
    )
    if not pasta then
        return {status=ngx.HTTP_BAD_REQUEST}, err
    end
    local url = request:url_for("view_pasta", {token=pasta.token})
    request.token = pasta.token
    request.filename = request.params.filename
    request.pasta_url = request:build_url(url)
    if request.params.pasta_type == 'standard' then
        return {redirect_to = url}
    elseif request.params.pasta_type == 'editable' then
        request.password_plain = pasta.password_plain
        return {render = "show_password"}
    elseif request.params.pasta_type == 'self_burning' then
        return {render = "show_self_burning"}
    elseif request.params.pasta_type == 'url_shortener' then
        return {render = "show_url_shortener"}
    end
end

function view.apiCreatePasta(request)
    local pasta, err = makePasta(
        request.params.filename or '',
        request.params.content,
        request.params.pasta_type
    )
    if not pasta then
        return apiResponse({error = err})
    end
    local result = {password = pasta.password_plain, token=pasta.token}
    pasta.filename = request.params.filename
    result.view = request:build_url(request:url_for("view_pasta", pasta))
    result.raw = request:build_url(request:url_for("raw_pasta", pasta))
    return apiResponse(result)
end

function view.viewPasta(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if request.p.redirect_to then
        return {redirect_to = request.p.content}
    end
    request.no_new_pasta = true
    request.ext = getExt(request.p_filename)
    if request.ext ~= 'txt' or request.p_filename == 'CMakeLists.txt' then
        request.highlight = true
    end
    return {render = true}
end

function view.rawPasta(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if request.p_filename ~= urldecode(request.params.filename or '') then
        return {
            redirect_to = request:url_for("raw_pasta", {
                token = request.params.token,
                filename = request.p_filename,
            }),
        }
    end
    request.res.headers["Content-Type"] = "text/plain; charset=utf-8"
    return {layout = false, render = "raw_pasta"}
end

function view.downloadPasta(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if request.p_filename ~= urldecode(request.params.filename or '') then
        return {
            redirect_to = request:url_for("download_pasta", {
                token = request.params.token,
                filename = request.p_filename,
            }),
        }
    end
    request.res.headers["Content-Type"] = "application/octet-stream"
    return {layout = false, render = "raw_pasta"}
end

function view.editPasta(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if not isEditable(request.p) then
        return {status=ngx.HTTP_FORBIDDEN}, "The pasta is not editable"
    end
    request.no_new_pasta = true
    return {render = true}
end

function view.editPasta2(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if not isEditable(request.p) then
        return {status=ngx.HTTP_FORBIDDEN}, "The pasta is not editable"
    end
    if makePasswordHash(request.params.password) ~= request.p.password then
        return {status=ngx.HTTP_FORBIDDEN}, "Wrong password"
    end
    local filename_ok, message = checkFilename(request.params.filename)
    if not filename_ok then
        return {status=ngx.HTTP_BAD_REQUEST}, message
    end
    request.p:update {
        filename = request.params.filename,
        content = request.params.content,
    }
    if cache then
        cache:set(request.token, request.p, #request.p.content)
    end
    local url = request:url_for("view_pasta", {token=request.token})
    return {redirect_to = url}
end

function view.removePasta(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if not isEditable(request.p) then
        return {status=ngx.HTTP_FORBIDDEN}, "The pasta is not removable"
    end
    request.no_new_pasta = true
    return {render = true}
end

function view.removePasta2(request)
    loadPasta(request)
    if not request.p then
        return {status=ngx.HTTP_NOT_FOUND}, "No such pasta"
    end
    if not isEditable(request.p) then
        return {status=ngx.HTTP_FORBIDDEN}, "The pasta is not removable"
    end
    if makePasswordHash(request.params.password) ~= request.p.password then
        return {status=ngx.HTTP_FORBIDDEN}, "Wrong password"
    end
    deletePasta(request.p, request.token)
    return {redirect_to = request:url_for("index")}
end

function view.getNumberOfPastas()
    if not number_of_pastas then
        number_of_pastas = model.Pasta:count()
    end
    return number_of_pastas
end

return view


text:
package com.airbnb.scheduler.api

import java.io.StringWriter
import java.util.logging.{Level, Logger}
import javax.ws.rs.{Consumes, GET, Path, Produces,  WebApplicationException}
import javax.ws.rs.core.{MediaType, Response}
import javax.ws.rs.core.Response.Status
import scala.Array

import com.airbnb.scheduler.config.SchedulerConfiguration
import com.airbnb.scheduler.jobs._
import com.airbnb.scheduler.jobs.graph.Exporter
import com.airbnb.scheduler.graph.JobGraph
import com.google.inject.Inject
import com.codahale.metrics.annotation.Timed

/**
 * The REST API for managing jobs.
 * @author Florian Leibert (flo@leibert.de)
 */
//TODO(FL): Create a case class that removes epsilon from the dependent.
@Path(PathConstants.graphBasePath)
@Consumes(Array(MediaType.APPLICATION_JSON))
class GraphManagementResource @Inject()(
    val jobScheduler: JobScheduler,
    val jobGraph: JobGraph,
    val configuration: SchedulerConfiguration) {

  private val log = Logger.getLogger(getClass.getName)

  @Produces(Array(MediaType.TEXT_PLAIN))
  @Path(PathConstants.jobGraphDotPath)
  @GET
  @Timed
  def dotGraph(): Response = {
    try {
      return Response.ok(jobGraph.makeDotFile()).build
    } catch {
      case ex: Exception => {
        log.log(Level.WARNING, "Exception while serving request", ex)
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR)
      }
    }
  }

  @Produces(Array(MediaType.TEXT_PLAIN))
  @Path(PathConstants.jobGraphCsvPath)
  @GET
  @Timed
  def jsonGraph(): Response = {
    try {
      val buffer = new StringWriter
      Exporter.export(buffer, jobGraph)
      return Response.ok(buffer.toString).build
    } catch {
      case ex: Exception => {
        log.log(Level.WARNING, "Exception while serving request", ex)
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR)
      }
    }
  }
}


text:
<?php

namespace Eloqua\Api\Soap\Service;

class GroupMemberResult {

    /**
     * @var ArrayOfError $Errors
     */
    protected $Errors = null;

    /**
     * @var boolean $Success
     */
    protected $Success = null;

    /**
     * @param boolean $Success
     */
    public function __construct($Success) {
        $this->Success = $Success;
    }

    /**
     * @return ArrayOfError
     */
    public function getErrors() {
        return $this->Errors;
    }

    /**
     * @param ArrayOfError $Errors
     * @return \Eloqua\Api\Soap\Service\GroupMemberResult
     */
    public function setErrors($Errors) {
        $this->Errors = $Errors;
        return $this;
    }

    /**
     * @return boolean
     */
    public function getSuccess() {
        return $this->Success;
    }

    /**
     * @param boolean $Success
     * @return \Eloqua\Api\Soap\Service\GroupMemberResult
     */
    public function setSuccess($Success) {
        $this->Success = $Success;
        return $this;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/bottomsheet_list_item_height"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingEnd="@dimen/bottomsheet_horizontal_margin"
    android:paddingLeft="@dimen/bottomsheet_horizontal_margin"
    android:paddingRight="@dimen/bottomsheet_horizontal_margin"
    android:paddingStart="@dimen/bottomsheet_horizontal_margin">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/imageView"
        android:layout_width="@dimen/bottomsheet_list_icon_width"
        android:layout_height="@dimen/bottomsheet_list_icon_width"
        android:layout_marginEnd="@dimen/bottomsheet_horizontal_margin"
        android:layout_marginRight="@dimen/bottomsheet_horizontal_margin"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/bottomsheet_horizontal_margin"
        android:layout_marginStart="@dimen/bottomsheet_horizontal_margin"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="@color/colorSheetText"
        android:textSize="@dimen/bottomsheet_item_textsize" />

</LinearLayout>


text:
procs=$(cat /proc/cpuinfo |grep processor | wc -l)
sed -i -e "s/worker_processes 5/worker_processes $procs/" /etc/nginx/nginx.conf

exec /usr/sbin/nginx >> /var/log/nginx.log 2>&1