text:
<?php

namespace Codebot;

/**
 * Handles all API REST calls, instantiating the correct class to answer the
 * the requested method.
 */
class Router {
	private $mHandlers;
	private static $mTerms = array('_API_ENPOINT', '_API_CLASS_FILE', '_API_CLASS_NAME');

	function __construct() {
		$mHandlers = array();
	}

	private function includeFileAndApiEndpoint($theIncludes) {
		$aDir = dirname(__FILE__) . '/../../../../';

		foreach($theIncludes as $aOwner => $aTool) {
			foreach(self::$mTerms as $aTerm) {
				if(!isset($aTool[$aTerm])) {
					throw new \Exception('API "' . $aOwner . '" in config file is missing info ' . $aOwner . $aTerm . '.');
				}
			}

			$aFile = $aDir . $aTool['_API_CLASS_FILE'];

			if(file_exists($aFile)) {
				require_once($aFile);
				$this->add($aTool['_API_ENPOINT'], $aTool['_API_CLASS_NAME']);

			} else {
				throw new \Exception('Class file (informed in ' . $aOwner . $aTerm . ') does not exist: ' . $aFile);
			}
		}
	}

	private function invokeMethod($theClass, $theObj, $theMethod, $theParams) {
		$aReflection = new \ReflectionMethod($theClass, $theMethod);
		$aRet = $aReflection->invoke($theObj, $theParams);

		return $aRet;
	}

	public function add($theAlias, $theClassHandler) {
		$this->mHandlers[$theAlias] = $theClassHandler;
	}

	public function addConfigDefinedEndpoints() {
		$aConstants = get_defined_constants(true);
		$aConfig = $aConstants['user'];
		$aMatches = array();
		$aInclude = array();

		foreach ($aConfig as $aName => $aValue) {
			if(preg_match_all('/(.*)('.implode('|', self::$mTerms).')/', $aName, $aMatches) != 0) {
				$aOwner = $aMatches[1][0];
				$aType  = $aMatches[2][0];

				$aInclude[$aOwner][$aType] = $aValue;
			}
		}

		$this->includeFileAndApiEndpoint($aInclude);
	}

	public function run($theRequest) {
		$aRet 		= '';

		$aAlias 	= isset($theRequest['class']) ? $theRequest['class'] : '';
		$aMethod 	= isset($theRequest['method']) ? $theRequest['method'] : '';

		unset($theRequest['class']);
		unset($theRequest['method']);

		// Do we have the handler to process this method?
		if(!isset($this->mHandlers[$aAlias])) {
			// No, we dont. It's a no show.
			throw new \Exception('Unknown API class named "'.$aAlias.'".');
		}

		$aClass = $this->mHandlers[$aAlias];
		$aRet 	= array('out' => '', 'mime' => '');

		$aObj 	= new $aClass;
		$aOut 	= $this->invokeMethod($aClass, $aObj, $aMethod, $theRequest);

		// Decide which content-type the class wants for its content type.
		// If none is provided, we use json.
		$aMime 	= isset($aClass::$contentType) && isset($aClass::$contentType[$aMethod]) ? $aClass::$contentType[$aMethod] : 'application/json';

		// If content-type is json, we do the convertion here in the router.
		$aRet['mime'] = $aMime;
		$aRet['out']  = $aMime == 'application/json' ? json_encode($aOut) : $aOut;

		return $aRet;
	}
}

?>


text:
NS_ASSUME_NONNULL_BEGIN

@interface IndexState (CoreDataProperties)

@property (nullable, nonatomic, retain) NSMutableOrderedSet *deleteIdentifiers;
@property (nullable, nonatomic, retain) NSMutableOrderedSet *insertIdentifiers;
@property (nullable, nonatomic, retain) NSMutableOrderedSet *updateIdentifiers;
@property (nullable, nonatomic, retain) NSMutableOrderedSet *moveIdentifiers;
@property (nullable, nonatomic, retain) NSDate *lastChangeDate;
@property (nullable, nonatomic, retain) NSNumber *numberOfIdentifiers;
@property (nullable, nonatomic, retain) NSString *objectType;

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
package com.MisterBlock11.MagicCraft.proxy;

import java.util.HashMap;
import java.util.Map;

import com.MisterBlock11.MagicCraft.armor.ModArmor;
import com.MisterBlock11.MagicCraft.blocks.ModBlocks;
import com.MisterBlock11.MagicCraft.items.ModItems;
import com.MisterBlock11.MagicCraft.tileentity.TileEntityAlchemicalCircle;
import com.MisterBlock11.MagicCraft.tool.ModTools;
import com.MisterBlock11.MagicCraft.util.LogHelper;
import com.MisterBlock11.MagicCraft.util.MagicCraftEventHandler;
import com.MisterBlock11.MagicCraft.util.ModCraftingRecipies;
import com.MisterBlock11.MagicCraft.util.ModVillagerTrades;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.MinecraftForge;

public class CommonProxy {

	private static final Map<String, NBTTagCompound> extendedEntityData = new HashMap<String, NBTTagCompound>();

	public void preInit(FMLPreInitializationEvent event) {
		ModBlocks.preInit();
		ModItems.preInit();
		ModCraftingRecipies.preInit();
		ModVillagerTrades.preInit();
		ModArmor.preInit();
		ModTools.preInit();
		registerTileEntities();

		LogHelper.info("PreInit Finished");
	}

	public void init(FMLInitializationEvent event) {
		LogHelper.info("Init Finished");
	}

	public void postInit(FMLPostInitializationEvent event) {
		MinecraftForge.EVENT_BUS.register(new MagicCraftEventHandler());

		LogHelper.info("PostInit Finished");
	}

	public void registerTileEntities() {

        GameRegistry.registerTileEntity(TileEntityAlchemicalCircle.class, "TileEntityAlchemicalCircle");
    }

	public static void storeEntityData(String name, NBTTagCompound compound) {
		extendedEntityData.put(name, compound);
	}

	public static NBTTagCompound getEntityData(String name) {
		return extendedEntityData.remove(name);
	}

}


text:
package com.example.mobilesafe;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mobilesafe.db.dao.ApplockDao;
import com.example.mobilesafe.domain.AppInfo;
import com.example.mobilesafe.engine.AppInfoProvider;
import com.example.mobilesafe.utils.DensityUtil;

import org.w3c.dom.Text;

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

/**
 * Created by abc on 2016/2/14.
 */
public class AppManagerActivity extends Activity implements View.OnClickListener {
    private TextView tv_avail_rom;
    private TextView tv_avail_sd;
    private ListView lv_app_manager;
    private LinearLayout ll_loading;
    private AppAdapter adapter;
    private List<AppInfo> infos;
    /**
     * 用户软件集合
     */
    private List<AppInfo> userAppinfos;
    /**
     * 系统软件集合
     */
    private List<AppInfo> systemAppinfos;

    /**
     * 当前程序信息状态
     */
    private TextView tv_status;

    /**
     * 弹出的悬浮窗体
     */
    private PopupWindow popupWindow;
    //卸载
    private LinearLayout ll_uninstall;
    //开启
    private LinearLayout ll_start;
    //分享
    private LinearLayout ll_share;

    private AppInfo info;

    private ApplockDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_manager);
        tv_status = (TextView) findViewById(R.id.tv_status);
        tv_avail_rom = (TextView) findViewById(R.id.tv_avail_rom);
        tv_avail_sd = (TextView) findViewById(R.id.tv_avail_sd);
        lv_app_manager = (ListView) findViewById(R.id.lv_app_manager);
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        long sdSize = getAvailSpace(Environment.getExternalStorageDirectory().getAbsolutePath());
        long romSize = getAvailMemory();//获取内存
        tv_avail_sd.setText("SD卡可用空间:" + Formatter.formatFileSize(this, sdSize)); //formatFileSize()将内存空间转换格式
        tv_avail_rom.setText("内存可用空间:" + Formatter.formatFileSize(this, romSize));
        //避免主进程阻塞 infos= AppInfoProvider.getAppInfos(this);
        ll_loading.setVisibility(View.VISIBLE);
        dao=new ApplockDao(this);
        fillData();
        lv_app_manager.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            /**
             *
             * @param view
             * @param firstVisibleItem 第一个可见条目在listView集合的位置
             * @param visibleItemCount
             * @param totalItemCount
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                dismissPopupWindow();

                //进行判断防止子线程还没加载完数据
                if (userAppinfos != null && systemAppinfos != null) {
                    if (firstVisibleItem > userAppinfos.size()) {
                        tv_status.setText("系统程序:" + systemAppinfos.size() + "个");
                    } else {
                        tv_status.setText("用户程序" + userAppinfos.size() + "个");
                    }
                }
            }
        });

        lv_app_manager.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    return;
                } else if (position == userAppinfos.size() + 1) {
                    return;
                } else if (position <= userAppinfos.size()) {
                    //用户程序
                    int newPosition = position - 1;
                    info = userAppinfos.get(newPosition);
                } else {
                    //系统程序
                    int newPosition = position - 2 - userAppinfos.size();
                    info = systemAppinfos.get(newPosition);
                }
                dismissPopupWindow();

                View contentView = View.inflate(getApplicationContext(), R.layout.popup_app_item, null);
                ll_uninstall = (LinearLayout) contentView.findViewById(R.id.ll_uninstall);
                ll_start = (LinearLayout) contentView.findViewById(R.id.ll_start);
                ll_share = (LinearLayout) contentView.findViewById(R.id.ll_share);

                ll_start.setOnClickListener(AppManagerActivity.this);
                ll_uninstall.setOnClickListener(AppManagerActivity.this);
                ll_share.setOnClickListener(AppManagerActivity.this);

                popupWindow = new PopupWindow(contentView, -2, DensityUtil.dip2px(getApplicationContext(), 70));
                //动画效果的播放必须要求窗体有背景颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                //透明颜色也是颜色
                int[] location = new int[2];
                view.getLocationInWindow(location);
                popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, DensityUtil.dip2px(getApplicationContext(), 150), location[1]);

                ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa.setDuration(300);

                AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
                aa.setDuration(300);
                AnimationSet set = new AnimationSet(false);
                set.addAnimation(sa);
                set.addAnimation(aa);
                contentView.startAnimation(set);

            }
        });
        /**
         * 程序锁 设置条目 长点击事件监听器
         */

        lv_app_manager.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return true;
                } else if (position == userAppinfos.size() + 1) {
                    return true;
                } else if (position <= userAppinfos.size()) {
                    //用户程序
                    int newPosition = position - 1;
                    info = userAppinfos.get(newPosition);
                } else {
                    //系统程序
                    int newPosition = position - 2 - userAppinfos.size();
                    info = systemAppinfos.get(newPosition);
                }
                ViewHolder viewHolder = (ViewHolder) view.getTag();
                //判断条目是否存在数据库锁里面
                if(dao.find(info.getPackname())){
                    //被锁定的程序,解除锁定,并且改变图标
                    dao.delete(info.getPackname());
                    viewHolder.iv_status.setImageResource(R.drawable.unlock);
                }else{
                    //增加条目,改变图标
                    dao.add(info.getPackname());
                    viewHolder.iv_status.setImageResource(R.drawable.lock);
                }

                return true;
            }
        });

    }

    /**
     * 初始化数据
     */

    private void fillData() {
        new Thread() {
            public void run() {
                infos = AppInfoProvider.getAppInfos(AppManagerActivity.this);
                systemAppinfos = new ArrayList<AppInfo>();
                userAppinfos = new ArrayList<AppInfo>();
                for (AppInfo info : infos) {
                    if (info.isUserApp()) {
                        userAppinfos.add(info);
                    } else {
                        systemAppinfos.add(info);
                    }

                }
                //加载ListView数据适配器
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (adapter == null) {
                            adapter = new AppAdapter();
                            lv_app_manager.setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        ll_loading.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }.start();
    }

    /**
     * 清除popuowindow
     */
    private void dismissPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_uninstall:
                if(info.isUserApp()) {
                    uninstallApplication();
                }else {
                    Toast.makeText(this,"系统应用需要获取root权限才能卸载",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.ll_share:
                shareApplication();
                break;
            case R.id.ll_start:
                //开启应用程序
                startApplication();
                break;
            default:
                break;
        }
    }

    /**
     * 分享程序
     */
    private void shareApplication() {
             Intent intent = new Intent();
        intent.setAction("android.intent.action.SEND");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款软件,名称叫:"+info.getName());
        startActivity(intent);
    }

    /**
     * 卸载应用
     */
    private void uninstallApplication() {
        // <action android:name="android.intent.action.VIEW" />
        // <action android:name="android.intent.action.DELETE" />
        // <category android:name="android.intent.category.DEFAULT" />
        // <data android:scheme="package" />
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setAction("android.intent.action.DELETE");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("package:" + info.getPackname()));
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新界面
        fillData();
    }

    /**
     * 开启应用
     */
    private void startApplication() {
        //查询这个应用程序入口actvity
        PackageManager pm = getPackageManager();
       /* Intent intent=new Intent();
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
      查询出来手机所有具有启动能力的activity
       List<ResolveInfo> resolveInfos= pm.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);*/
        Intent intent = pm.getLaunchIntentForPackage(info.getPackname());
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(), "不能启动当前应用", Toast.LENGTH_SHORT).show();
        }
    }

    private class AppAdapter extends BaseAdapter {

        //控制listView 的条目
        @Override
        public int getCount() {
            //return infos.size();
            return userAppinfos.size() + 1 + systemAppinfos.size() + 1;//增加的两条标签
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == 0) {
                //显示系统程序有多少个的小标签
                TextView tv = new TextView(getApplicationContext());
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("用户程序" + userAppinfos.size() + "个");
                return tv;
            } else if (position == userAppinfos.size() + 1) {
                //显示用户程序有多少个的小标签
                TextView tv = new TextView(getApplicationContext());
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("系统程序" + systemAppinfos.size() + "个");
                return tv;
            }

            View view;
            ViewHolder viewHolder;
            AppInfo info;
            if (position <= userAppinfos.size()) {
                info = userAppinfos.get(position - 1);
            } else {
                info = systemAppinfos.get(position - 2 - userAppinfos.size());
            }

            //不仅检查是否为空并且要判断是否能被复用
            if (convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(getApplicationContext(), R.layout.list_item_appinfo, null);
                viewHolder = new ViewHolder();
                viewHolder.icon = (ImageView) view.findViewById(R.id.iv_app_icon);
                viewHolder.tv_name = (TextView) view.findViewById(R.id.tv_app_name);
                viewHolder.tv_location = (TextView) view.findViewById(R.id.tv_app_location);
                viewHolder.iv_status= (ImageView) view.findViewById(R.id.iv_status);
                view.setTag(viewHolder);
            }
            viewHolder.tv_name.setText(info.getName());
            viewHolder.icon.setImageDrawable(info.getIcon());
            if (info.isInRom()) {
                viewHolder.tv_location.setText("手机内存"+"uid"+info.getUid());
            } else {
                viewHolder.tv_location.setText("外部存储"+"uid"+info.getUid());
            }
            if(dao.find(info.getPackname())){
                viewHolder.iv_status.setImageResource(R.drawable.lock);
            }else {
                viewHolder.iv_status.setImageResource(R.drawable.unlock);
            }

            return view;
        }
    }

    static class ViewHolder {
        TextView tv_name;
        TextView tv_location;
        ImageView icon;
        ImageView iv_status;
    }

    /**
     * 获取某个目录的可用空间
     *
     * @param path 路径
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)  //要求最低版本
    private long getAvailSpace(String path) {
        StatFs statFs = new StatFs(path);
        long size = statFs.getBlockSizeLong();//获取分区的大小
        long count = statFs.getAvailableBlocksLong();//获取可用分区的个数
        statFs.getBlockCountLong();//获取所有的分区
        return size * count;
    }

    /**
     * 获取可用内存
     *
     * @return
     */
    public long getAvailMemory() {
        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        manager.getMemoryInfo(outInfo);
        return outInfo.availMem;
    }

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

    }
}


text:
package org.radargun.stages.lifecycle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import org.radargun.DistStageAck;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.utils.TimeConverter;
import org.radargun.stages.helpers.RoleHelper;

/**
 * The stage start and kills some nodes concurrently (without waiting for each other).
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
@Stage(doc = "The stage start and stops some nodes concurrently (without waiting for each other).")
public class ParallelStartStopStage extends AbstractServiceStartStage {

   @Property(doc = "Set of slaves which should be stopped in this stage. Default is empty.")
   private Collection<Integer> stop = new ArrayList<Integer>();

   @Property(converter = TimeConverter.class, doc = "Delay before the slaves are stopped. Default is 0.")
   private long stopDelay = 0;

   @Property(doc = "If set to false, the node crash should be simulated. By default node should be shutdown gracefully.")
   private boolean graceful = true;

   @Property(doc = "Set of slaves which should be started in this stage. Default is empty.")
   private Collection<Integer> start = new ArrayList<Integer>();

   @Property(converter = TimeConverter.class, doc = "Delay before the slaves are started. Default is 0.")
   private long startDelay = 0;

   @Property(doc = "Applicable only for cache wrappers with Partitionable feature. Set of slaves that should be" +
         "reachable from the new node. Default is all slaves.")
   private Set<Integer> reachable = null;

   @Override
   public DistStageAck executeOnSlave() {
      if (lifecycle == null) {
         log.warn("No lifecycle for service " + slaveState.getServiceName());
         return successfulResponse();
      }
      boolean stopMe = stop.contains(slaveState.getSlaveIndex()) || RoleHelper.hasAnyRole(slaveState, roles);
      boolean startMe = start.contains(slaveState.getSlaveIndex());
      if (!(stopMe || startMe)) {
         log.info("Nothing to kill or start...");
      }
      while (stopMe || startMe) {
         if (startMe) {
            if (lifecycle.isRunning()) {
               if (!stopMe) {
                  log.info("Wrapper already set on this slave, not starting it again.");
                  startMe = false;
                  return successfulResponse();
               }
            } else {
               if (startDelay > 0) {
                  try {
                     Thread.sleep(startDelay);
                  } catch (InterruptedException e) {
                     log.error("Starting delay was interrupted.", e);
                  }
               }
               try {
                  LifecycleHelper.start(slaveState, false, null, 0, reachable);
               } catch (RuntimeException e) {
                  return errorResponse("Issues while instantiating/starting cache wrapper", e);
               }
               startMe = false;
            }
         }
         if (stopMe) {
            if (!lifecycle.isRunning()) {
               if (!startMe) {
                  log.info("Wrapper is dead, nothing to kill");
                  stopMe = false;
                  return successfulResponse();
               }
            } else {
               try {
                  Thread.sleep(stopDelay);
               } catch (InterruptedException e) {
                  log.error("Killing delay was interrupted.", e);
               }
               try {
                  LifecycleHelper.stop(slaveState, graceful, false);
               } catch (RuntimeException e) {
                  return errorResponse("Failed to kill the service", e);
               }
               stopMe = false;
            }
         }
      }
      return successfulResponse();
   }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: dg
 * Date: 01.6.2018
 * Time: 09:20
 */

namespace SmartOptim\Responses;

class Profile {

	/**
	 * The plain response
	 * @var string
	 */
	private $raw = false;

	/**
	 * The error code
	 * @var int
	 */
	private $code = null;

	/**
	 * Array of errors, if any.
	 * @var array
	 */
	private $errors = array();

	/**
	 * The response status
	 * @var string (ok|error)
	 */
	private $status = '';

	/**
	 * Tokens left
	 * @var int
	 */
	private $tokens = null;

	/**
	 * The profile name
	 * @var string
	 */
	private $name = null;

	/**
	 * The profile email
	 * @var null
	 */
	private $email = null;

	/**
	 * Profile constructor.
	 *
	 * @param $response
	 */
	public function __construct( $response = null ) {

		if ( ! is_null( $response ) ) {
			$this->raw = $response;
			$response  = json_decode( $response );
			if ( isset( $response->status ) ) {
				$this->status = $response->status;
			}
			if ( isset( $response->code ) ) {
				$this->code = $response->code;
			}
			if ( isset( $response->errors ) ) {
				$this->errors = $response->errors;
			}
			if ( isset( $response->result->name ) ) {
				$this->name = $response->result->name;
			}
			if ( isset( $response->result->email ) ) {
				$this->email = $response->result->email;
			}
			if ( isset( $response->result->tokens ) ) {
				$this->tokens = $response->result->tokens;
			}
		}
	}

	/**
	 * Returns the response code
	 * @return int
	 */
	public function getCode() {
		return $this->code;
	}

	/**
	 * Returns array of errors
	 * @return array
	 */
	public function getErrors() {
		return $this->errors;
	}

	/**
	 * Raw response
	 * @return string
	 */
	public function getRawResponse() {
		return $this->raw;
	}

	/**
	 * Returns the status
	 * @return string
	 */
	public function getStatus() {
		return $this->status;
	}

	/**
	 * Returns the tokens left
	 * @return int
	 */
	public function getTokens() {
		return $this->tokens;
	}

	/**
	 * Returns the profile name
	 * @return string
	 */
	public function getName() {
		return $this->name;
	}

	/**
	 * Returns email
	 * @return null
	 */
	public function getEmail() {
		return $this->email;
	}

	/**
	 * Set the tokens left
	 *
	 * @param $tokens
	 */
	public function setTokens( $tokens ) {
		$this->tokens = $tokens;
	}

	/**
	 * Set the profile name
	 *
	 * @param $name
	 */
	public function setName( $name ) {
		$this->name = $name;
	}

	/**
	 * Set email
	 *
	 * @param $email
	 */
	public function setEmail( $email ) {
		$this->email = $email;
	}

	/**
	 * Set the code
	 *
	 * @param $code
	 */
	public function setCode( $code ) {
		$this->code = $code;
	}

	/**
	 * Set the status
	 *
	 * @param $status
	 */
	public function setStatus( $status ) {
		$this->status = $status;
	}
}


text:
/**
 * Created by saltfactory on 7/21/14.
 */
var assert = require("assert");

/**
 * Post BDD
 */
describe('Tistory Category API', function () {
  var Category = require('../lib/tistory/category.js');
  var category;

  /**
   * before run test method
   */
  before(function () {
    category = new Category(require('../examples/example-options'));
  });

  /**
   * test settings category.options.baseUrl
   */
  describe('set baseUrl to Category property', function () {
    it('should return -1 when the value is not present', function (done) {
      assert.equal(category.options.baseUrl, 'https://www.tistory.com/apis', 'not equal');
      done();
    });
  });

  /**
   * test Tistory Category list API
   */
  describe('#list()', function () {
    it('sould return tistory json', function (done) {

      category.list(function (err, body) {
        var json = JSON.parse(body);

        console.log(body);

        assert.equal(json.tistory.status, '200', 'post failed!');
        assert.equal(json.tistory.item.categories.category[0].name, 'Ruby', 'not equal');

        done();
      });
    });
  });

  /**
   * test Tistory Category list API
   */
  describe('#find()', function () {
    it('sould return tistory json', function (done) {
      var params = {
        name:'Ruby'
      };

      category.find(params, function (err, body) {
        console.log(body);
        var json = JSON.parse(body);
        assert.equal(json.name, 'Ruby', 'not equal');
        assert.equal(json.id, '224060', 'not equal');

        done();
      });
    });
  });

});


text:
(function(Browser) {

	Browser.Views = Browser.Views || {};
	Browser.Views.FancyBox = Browser.Views.FancyBox || {};

	Browser.Views.FancyBox.Article = Browser.Views._Fancybox.extend({

		initialize: function()
		{
			Browser.Views._Fancybox.prototype.initialize.call(this); //This is like calling super()
		},

		/* Pass in the element that the user clicked on from fancybox. */
		render: function(obj)
		{

			sessionStorage.setItem('currentItemId', this.model.id);
			//console.log('this model id is'+this.model.id);
			//Call parent class to do captioning and metadata
			Browser.Views._Fancybox.prototype.render.call(this, obj); //This is like calling super()

			//Fill in image-specific stuff
			var blanks = {
			    src: this.model.get('thumbnail_url'),
			    title : this.model.get('title')
			};

			//use template to clone the database items into
			var template = _.template( this.getMediaTemplate() );

			//copy the cloned item into the el
			var imageHTML =  template( blanks ) ;

			$(this.el).find('.fancybox-media-item').html(imageHTML);

			//set fancybox content
			obj.content = $(this.el);

			return this;
		},
		getMediaTemplate : function()
		{

			var html =	'<img src="<%=src%>" title="<%=title%>" alt="<%=title%>"/>';
			return html;
		}
	});

})(jda.module("browser"));


text:
import { localize } from 'vs/nls';
import { IKeyMods, IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IRange } from 'vs/editor/common/core/range';
import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess';
import { Registry } from 'vs/platform/registry/common/platform';
import { IQuickAccessRegistry, Extensions as QuickaccesExtensions } from 'vs/platform/quickinput/common/quickAccess';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchEditorConfiguration } from 'vs/workbench/common/editor';
import { Action2, registerAction2 } from 'vs/platform/actions/common/actions';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IQuickAccessTextEditorContext } from 'vs/editor/contrib/quickAccess/editorNavigationQuickAccess';

export class GotoLineQuickAccessProvider extends AbstractGotoLineQuickAccessProvider {

	protected readonly onDidActiveTextEditorControlChange = this.editorService.onDidActiveEditorChange;

	constructor(
		@IEditorService private readonly editorService: IEditorService,
		@IConfigurationService private readonly configurationService: IConfigurationService
	) {
		super();
	}

	private get configuration() {
		const editorConfig = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench?.editor;

		return {
			openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview
		};
	}

	protected get activeTextEditorControl() {
		return this.editorService.activeTextEditorControl;
	}

	protected override gotoLocation(context: IQuickAccessTextEditorContext, options: { range: IRange, keyMods: IKeyMods, forceSideBySide?: boolean, preserveFocus?: boolean }): void {

		// Check for sideBySide use
		if ((options.keyMods.alt || (this.configuration.openEditorPinned && options.keyMods.ctrlCmd) || options.forceSideBySide) && this.editorService.activeEditor) {
			context.restoreViewState?.(); // since we open to the side, restore view state in this editor

			this.editorService.openEditor(this.editorService.activeEditor, {
				selection: options.range,
				pinned: options.keyMods.ctrlCmd || this.configuration.openEditorPinned,
				preserveFocus: options.preserveFocus
			}, SIDE_GROUP);
		}

		// Otherwise let parent handle it
		else {
			super.gotoLocation(context, options);
		}
	}
}

Registry.as<IQuickAccessRegistry>(QuickaccesExtensions.Quickaccess).registerQuickAccessProvider({
	ctor: GotoLineQuickAccessProvider,
	prefix: AbstractGotoLineQuickAccessProvider.PREFIX,
	placeholder: localize('gotoLineQuickAccessPlaceholder', "Type the line number and optional column to go to (e.g. 42:5 for line 42 and column 5)."),
	helpEntries: [{ description: localize('gotoLineQuickAccess', "Go to Line/Column"), needsEditor: true }]
});

class GotoLineAction extends Action2 {

	constructor() {
		super({
			id: 'workbench.action.gotoLine',
			title: { value: localize('gotoLine', "Go to Line/Column..."), original: 'Go to Line/Column...' },
			f1: true,
			keybinding: {
				weight: KeybindingWeight.WorkbenchContrib,
				when: null,
				primary: KeyMod.CtrlCmd | KeyCode.KEY_G,
				mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_G }
			}
		});
	}

	async run(accessor: ServicesAccessor): Promise<void> {
		accessor.get(IQuickInputService).quickAccess.show(GotoLineQuickAccessProvider.PREFIX);
	}
}

registerAction2(GotoLineAction);


text:
import select
from paramiko import RSAKey, SSHClient, AutoAddPolicy
from os.path import exists
from .securefile import SecureFileStorage

class Transport(object):
    """ Base transport protocol class
    """
    def __init__(self, server):
        self.server = server
        self.callback = lambda out: None

    def set_stdout_callback(self, callback):
        self.callback = callback

class SSHTransport(Transport):
    """ SSH connection
    """
    output_timeout = 0.5
    output_buffer = 1024

    def __init__(self, server):
        super(SSHTransport, self).__init__(server)
        self.secure_files = SecureFileStorage(self.server.environment_id)
        self.client = self.create_client()
        self.channel = None

    def run(self, command):
        """ Execute command in current connection

        Handle output using attached callback function
        """
        self.channel = self.client.get_transport().open_session()
        self.channel.get_pty()
        self.channel.exec_command(command)
        while True:
            rl, _, _ = select.select([self.channel], [], [], self.output_timeout)
            if len(rl) > 0:
                output = self.channel.recv(self.output_buffer)
                if output:
                    self.callback(output)
                else:
                    break
        return self.channel.recv_exit_status()

    def create_client(self):
        """ Create and configure SSHClient
        """
        private = RSAKey(filename=self.get_private_key_file())
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy())
        client.load_host_keys(self.get_host_keys_file())
        if self.server.authentication_method == self.server.OPENSSH_PASSWORD:
            client.connect(self.server.host, password=self.server.password,
                           look_for_keys=False, port=self.server.port, username=self.server.user)
        elif self.server.authentication_method == self.server.OPENSSH_CERTIFICATE:
            client.connect(self.server.host, pkey=private,
                           look_for_keys=False, port=self.server.port, username=self.server.user)
        return client

    def close_client(self):
        """ Close SSHClient
        """
        self.client.save_host_keys(self.get_host_keys_file())
        if self.channel:
            self.channel.close()
        self.client.close()

    def kill(self):
        """ Alias for close_client method
        """
        self.close_client()

    def get_host_keys_file(self):
        """ Return path to known hosts file
        """
        filename = self.secure_files.known_hosts.get_file_name()
        if not exists(filename):
            raise RuntimeError('Known hosts file not found')
        return filename

    def get_private_key_file(self):
        """ Return path to private key file
        """
        filename = self.secure_files.private_key.get_file_name()
        if not exists(filename):
            raise RuntimeError('Private key file not found')
        return filename

class Server(object):
    """ Server model
    """
    OPENSSH_PASSWORD = 1
    OPENSSH_CERTIFICATE = 2

    def __init__(self):
        self.environment_id = None
        self.host = None
        self.port = None
        self.user = None
        self.authentication_method = 'key'
        self.password = None

    @staticmethod
    def from_model(model):
        instance = Server()
        instance.environment_id = model.environment_id
        instance.host = model.host
        instance.port = model.port
        instance.user = model.user
        instance.password = model.serverauthentication.password
        instance.authentication_method = model.method
        return instance


text:
Tracks the equipped player of a tool

View docs →

## Installation
```
npm install @quenty/equippedtracker --save
```


text:
copyright:
  years: 2017
lastupdated: "2017-04-13"

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Eigene APIs
{: #manage_api}

Auf der Registerkarte **Verwaltete APIs anzeigen** können Sie den Gesamtstatus der verwalteten APIs und der APIs anzeigen, die zuvor verwaltet, aber momentan nicht bereitgestellt werden. Auf der Registerkarte **Gemeinsam genutzte APIs** werden alle APIs angezeigt, die über die API-Verwaltung oder den {{site.data.keyword.apiconnect_short}}-Service mit Ihrer {{site.data.keyword.Bluemix_notm}}-Organisation gemeinsam genutzt werden.

Im Dashboard für APIs können alle APIs angezeigt werden, die über die API-Verwaltung verwaltet werden.

## Verwaltete APIs anzeigen
{: #view_api}

Hier können APIs angezeigt werden, die für {{site.data.keyword.openwhisk_short}}-Aktionen und andere externe Quellen erstellt wurden.

1. Wählen Sie im {{site.data.keyword.Bluemix_notm}}-Dashboard **Menü** > **Services** > **APIs** aus.
2. Klicken Sie auf **APIs verwalten**, um die Quelle auszuwählen. Daraufhin wird eine Liste der momentan verwalteten APIs angezeigt. Die folgenden API-Typen sind verfügbar:
    * Benutzerdefinierte Endpunkte - Diese Einträge stellen APIs dar, die sich außerhalb der {{site.data.keyword.Bluemix_notm}}-Umgebung befinden und über den zugehörigen URL-Endpunkt überwacht werden.
    * {{site.data.keyword.openwhisk_short}}-Apps - Diese Einträge stellen {{site.data.keyword.openwhisk_short}}-Aktionen dar, die in eine API eingeschlossen sind.

Wählen Sie den Namen einer API aus, um weitere Details zu dieser API anzuzeigen.

## Verwaltete APIs erstellen
{: #create_mgd_api}

Sie können eine API zur Liste der verwalteten APIs hinzufügen, ohne die Liste verlassen zu müssen. Wählen Sie dazu **Verwaltete API erstellen** aus.

Wählen Sie aus, ob Sie eine {{site.data.keyword.openwhisk_short}}-API oder einen API-Proxy (externe API) erstellen möchten, und geben Sie die Informationen für die neue API ein.

API-Proxys (externe APIs) können nur hier hinzugefügt werden. Eine externe API ist eine API, die nicht im {{site.data.keyword.Bluemix_notm}}-Organisationsbereich erstellt oder gespeichert wurde. Die Verwaltung einer externen API erfolgt durch Angabe der URL des externen Endpunkts. Dies ist nützlich, wenn Sie testen möchten, ob die API-Verwaltung Ihre Anforderungen erfüllt, oder wenn Sie bereits über APIs mit vorhandenen URLs verfügen, die Sie nicht unterbrechen möchten.

Weitere Informationen zu den erforderlichen Einstellungen für die API-Erstellung finden Sie in [APIs verwalten](manage_apis.html).

## Mit gemeinsam genutzten APIs arbeiten
{: #share_api}

Auf der Registerkarte **Gemeinsam genutzte APIs erkunden** können Sie APIs anzeigen, die von anderen Benutzern erstellt wurden und gemeinsam genutzt werden. Ferner können für die APIs, die {{site.data.keyword.openwhisk_short}}-Aktionen und dem {{site.data.keyword.appconserviceshort}}-Service zugeordnet sind, API-Schlüssel erstellt werden.

1. Klicken Sie im {{site.data.keyword.Bluemix_notm}}-Dashboard auf **Menü** > **Services** > **APIs**.
2. Wählen Sie in der Navigation **Gemeinsam genutzte APIs erkunden** aus. Hier werden alle APIs angezeigt, die Sie nutzen können.
3. Wählen Sie eine API aus, um das zugehörige Entwicklerportal zu öffnen, in dem Sie einen Plan für die Nutzung subskribieren können.
4. Lesen Sie nach Auswahl einer API die Informationen im Abschnitt [APIs verwalten](manage_apis.html), um die folgenden Tasks auszuführen:
    * API-Nutzung anzeigen
    * API-Schlüssel erstellen
    * API-Explorer zum Anzeigen von Dokumentation und Testen der API verwenden


text:
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.

using CommandLine.Core;
using CommandLine.Tests.Fakes;
using FluentAssertions;
using Xunit;

namespace CommandLine.Tests.Unit.Infrastructure
{
    public class ReflectionHelperTests
    {
        [Fact]
        public static void Class_with_public_set_properties_or_fields_is_ranked_mutable()
        {
            typeof(FakeOptions).IsMutable().Should().BeTrue();
        }

        [Fact]
        public static void Class_without_public_set_properties_or_fields_is_ranked_immutable()
        {
            typeof(FakeImmutableOptions).IsMutable().Should().BeFalse();
        }
    }
}


text:
import asyncRoute from './AsyncRoute';

export const App = asyncRoute(() => import('./App'));
export const Page = asyncRoute(() => import('./Page'));
export const Signin = asyncRoute(() => import('./Signin'));

if (process.env.NODE_ENV === 'development') {
  require('./App');
  require('./Page');
  require('./Signin');
}


text:
package org.acegisecurity.providers.dao;

import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.UserDetails;

/**
 * @deprecated use {@link org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider}
 */
@Deprecated
public abstract class AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider {

    private final org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider delegate = new org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider() {
        @Override
        protected void additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails userDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken authentication) throws org.springframework.security.core.AuthenticationException {
            try {
                AbstractUserDetailsAuthenticationProvider.this.additionalAuthenticationChecks(UserDetails.fromSpring(userDetails), new UsernamePasswordAuthenticationToken(authentication));
            } catch (AcegiSecurityException x) {
                throw x.toSpring();
            }
        }
        @Override
        protected org.springframework.security.core.userdetails.UserDetails retrieveUser(String username, org.springframework.security.authentication.UsernamePasswordAuthenticationToken authentication) throws org.springframework.security.core.AuthenticationException {
            try {
                return AbstractUserDetailsAuthenticationProvider.this.retrieveUser(username, new UsernamePasswordAuthenticationToken(authentication)).toSpring();
            } catch (AcegiSecurityException x) {
                throw x.toSpring();
            }
        }
    };

    protected abstract void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException;

    protected abstract UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            return Authentication.fromSpring(delegate.authenticate(authentication.toSpring()));
        } catch (org.springframework.security.core.AuthenticationException x) {
            throw AuthenticationException.fromSpring(x);
        }
    }

    @Override
    public boolean supports(Class authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

    // TODO other methods as needed: createSuccessAuthentication, getUserCache, etc.

}


text:
import numpy as np

def generateMFile(resultFilename, gridDim, resDim, timeLevel):
    # MFile refers to typical MATLAB file extension (.m file)

    MFile = open(resultFilename+"-visualize-t%s-usingMRST.m" %(timeLevel), "w")
    resultFile = open(resultFilename+"-results.txt", "r")

    specString = """
[nx,ny,nz] = deal( %s, %s, %s);
[Lx,Ly,Lz] = deal( %s, %s, %s);
G = cartGrid([nx, ny, nz], [Lx, Ly, Lz ]);
G = computeGeometry(G);

""" %(gridDim[2], gridDim[1], gridDim[0], resDim[2], resDim[1], resDim[0])

    pressureData = np.loadtxt(resultFile)

    pressureArr = pressureData[timeLevel].reshape(gridDim)
    newPressureArr = np.zeros(gridDim, dtype='float').reshape(gridDim)

    for zIndx in range(gridDim[0]):
        newPressureArr[zIndx] = pressureArr[gridDim[0]-zIndx-1]

    newPressureArrStr = generatePresArr(newPressureArr.reshape(gridDim[0]*gridDim[1]*gridDim[2]))

    otherSpecString = """

pressure = reshape(pressure, [], 1);

show = true(G.cells.num,1);

plotCellData(G, pressure, show, ...
'EdgeColor','k' );

view(3), camproj perspective, colorbar
"""

    print(specString+newPressureArrStr+otherSpecString, file=MFile)

    resultFile.close()
    MFile.close()

def generatePresArr(pressureDist):
    pressureArrStr = "pressure = ["

    for indx in range(len(pressureDist)):
        pressureArrStr += str(pressureDist[indx])
        if(indx < len(pressureDist)-1):
            pressureArrStr += ", "

    pressureArrStr += "];"

    return pressureArrStr

if(__name__ == '__main__'):
    generateMFile('example-6', (1, 171, 171), (75, 2500, 2500), 31)


text:
(function() {
	var dataAccess = ['$http', function($http) {
		var getAllApplications = function() {
			return $http.get('../api/applications')
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error retrieving applications: ' + err.data);
						});
		};

		var getApplicationsByStatus = function(status) {
			return $http.get('../api/applications/status/' + status)
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error retrieving applications: ' + err.data);
						});
		};

		var getApplicationsStatusById = function(id) {
			return $http.get('../api/applications/status/id/' + id)
						.then(function(response) {
							return response.data.AppStatus;
						}, function(err) {
							console.log('Error retrieving application status: ' + err.data);
						});
		};

		var getApplicationById = function(appId) {
			return $http.get('../api/applications/id/' + appId)
						.then(function(response) {
							var unformattedDate = response.RequestDate;
							return response.data;
						}, function(err) {
							console.log('Error retrieving application by ID: ' + err.data);
						});
		}

		var login = function(email, pass) {
			return $http.post('../api/user', { email: email, password: pass })
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error logging user in: ' + err.data);
						});
		}

		var submitApplication = function(application) {
			return $http.post('../api/applications/submit', application)
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error approving application: ' + err.data);
						});
		}

		var approveApplication = function(appId) {
			return $http.post('../api/applications/approve/id/' + appId)
						.then(function(response) {
							return response.data.newStatus;
						}, function(err) {
							console.log('Error approving application: ' + err.data);
						});
		}

		var rejectApplication = function(appId) {
			return $http.post('../api/applications/reject/id/' + id)
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error rejecting application: ' + err.data);
						});
		};

		var completeApplication = function(appId, extendedFrm) {
			return $http.post('../api/applications/complete/id/' + appId, extendedFrm)
						.then(function(response) {
							return response.data.newStatus;
						}, function(err) {
							console.log('Error rejecting application: ' + err.data);
						});
					};

		var finalizeApplication = function(appId) {
			return $http.post('../api/applications/finalize/id/' + appId)
						.then(function(response) {
							return response.data.newStatus;
						}, function(err) {
							console.log('Error finalizing application: ' + err.data);
						});
		};

		var registerUser = function(user) {
			return $http.post('../api/user/register', user)
						.then(function(response) {
							return response.data;
						}, function(err) {
							console.log('Error registering user: ' + err.data);
						});
		};

		return {
			getAllApplications:        getAllApplications,
			getApplicationsByStatus:   getApplicationsByStatus,
			getApplicationById:        getApplicationById,
			login: 					   login,
			approveApplication: 	   approveApplication,
			submitApplication: 		   submitApplication,
			registerUser: 			   registerUser,
			getApplicationsStatusById: getApplicationsStatusById,
			completeApplication: 	   completeApplication,
			finalizeApplication:       finalizeApplication
		};
	}];

	var module = angular.module('MyApp.Dashboard');
	module.factory('dataAccess', dataAccess);
}());


text:
package com.schibstedspain.leku.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;

import androidx.annotation.NonNull;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;

public class LastKnownLocationObservableOnSubscribe extends BaseLocationObservableOnSubscribe<Location> {

    public static Observable<Location> createObservable(Context ctx) {
        return Observable.create(new LastKnownLocationObservableOnSubscribe(ctx));
    }

    private LastKnownLocationObservableOnSubscribe(Context ctx) {
        super(ctx);
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onLocationProviderClientReady(FusedLocationProviderClient locationProviderClient,
                                                 final ObservableEmitter<? super Location> emitter) {
        locationProviderClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (emitter.isDisposed()) return;
                        if (location != null) {
                            emitter.onNext(location);
                        }
                        emitter.onComplete();
                    }
                })
                .addOnFailureListener(new BaseFailureListener<>(emitter));
    }

    public static class BaseFailureListener<T> implements OnFailureListener {

        private final ObservableEmitter<? super T> emitter;

        public BaseFailureListener(ObservableEmitter<? super T> emitter) {
            this.emitter = emitter;
        }

        @Override
        public void onFailure(@NonNull Exception exception) {
            if (emitter.isDisposed()) return;
            emitter.onError(exception);
            emitter.onComplete();
        }
    }
}


text:
<?php namespace CupOfTea\TwoStream\Contracts\Exceptions;

use Exception;
use Psr\Log\LoggerInterface;
use CupOfTea\TwoStream\Console\Output;

interface Handler
{
    /**
     * Create a new exception handler instance.
     *
     * @param  \Psr\Log\LoggerInterface  $log
     * @param  \CupOfTea\TwoStream\Console\Output  $ouput
     * @return void
     */
    public function __construct(LoggerInterface $log, Output $output);

    /**
     * Report an Exception.
     *
     * @param  Exception  $e
     * @return null|string|array
     */
    public function report(Exception $e);

    /**
     * Report an Exception.
     *
     * @param  Exception  $e
     * @return null|string|array
     */
    public function render(Exception $e);
}


text:
/**
 * Created by Fine on 2016/12/13.
 */
JamesBoard.service('chartMapService', function (dataService) {
    this.render = function (containerDom, option, scope) {
        var height;
        scope ? height = scope.myheight - 20 : null;
        return new CBoardMapRender(containerDom, option).do(height);
    };

    this.parseOption = function (chartData, chartConfig) {
        var mapOption = null;
        dataService.castRawData2Series(chartData, chartConfig, function (casted_keys, casted_values, aggregate_data, newValuesConfig) {
            var keysList = casted_keys,
                keyArr = [],
                emptyList = [],
                keyLength = chartConfig.keys.length;
            Array.matrix = function (numrows, numcols, initial) {
                var arr = [];
                for (var a = 0; a < numrows; ++a) {
                    var columns = [];
                    for (var s = 0; s < numcols; ++s) {
                        columns[s] = initial;
                    }
                    arr[a] = columns;
                }
                return arr;
            };
            var map_data = Array.matrix(keysList.length, keysList[0].length, 0);
            for (var h = 0; h < keysList[0].length; h++) {
                for (var k = 0; k < keysList.length; k++) {
                    map_data[k][h] = {
                        property: 'row_key',
                        data: keysList[k][h]
                    };
                }
            }
            for (var i = 0; i < casted_values.length; i++) {
                for (var j = 0; j < casted_keys.length; j++) {
                    if (!_.isUndefined(aggregate_data[i][j])) {
                        map_data[j][i + keyLength] = {
                            property: 'data',
                            data: aggregate_data[i][j]
                        };
                    } else {
                        map_data[j][i + keyLength] = {
                            property: 'data',
                            data: 'N/A'
                        };
                    }
                }
            }
            var column_header = Array.matrix(chartConfig.groups.length + 1, casted_values.length, 0);
            for (var n = 0; n < casted_values.length; n++) {
                for (var m = 0; m < casted_values[n].length; m++) {
                    column_header[m][n] = {
                        property: 'column_key',
                        data: casted_values[n][m]
                    };
                }
            }
            for (var y = 0; y < keyLength; y++) {
                keyArr.push({
                    property: 'row_key',
                    data: chartConfig.keys[y].col
                });
                emptyList.push({
                    property: 'header_empty',
                    data: null
                });
            }
            for (var j = 0; j < column_header.length; j++) {
                j == column_header.length - 1 ?
                    column_header[j] = keyArr. concat(column_header[j]) :
                    column_header[j] = emptyList.concat(column_header[j]);
            }
            mapOption = {
                chartConfig: chartConfig,
                data: column_header.concat(map_data)
            };
            map_data = null;
            column_header = null;
        });
        return mapOption;
    };
});


text:
var React = require('react');

module.exports = React.createClass({
    render() {
        return (
            <li className="item-divider">
                {this.props.children}
            </li>
        );
    }
});


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// <include src="post_message_channel.js">
// <include src="webview_event_manager.js">
// <include src="saml_password_attributes.js">

// clang-format off
// #import {Channel} from './channel.m.js';
// #import {PostMessageChannel} from './post_message_channel.m.js';
// #import {WebviewEventManager} from './webview_event_manager.m.js';
// #import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js'
// #import {PasswordAttributes, readPasswordAttributes} from './saml_password_attributes.m.js';
// clang-format on

/**
 * @fileoverview Saml support for webview based auth.
 */

cr.define('cr.login', function() {
  /* #ignore */ 'use strict';

  /**
   * The lowest version of the credentials passing API supported.
   * @type {number}
   */
  const MIN_API_VERSION_VERSION = 1;

  /**
   * The highest version of the credentials passing API supported.
   * @type {number}
   */
  const MAX_API_VERSION_VERSION = 1;

  /**
   * The key types supported by the credentials passing API.
   * @type {Array} Array of strings.
   */
  const API_KEY_TYPES = [
    'KEY_TYPE_PASSWORD_PLAIN',
  ];

  /** @const */
  const SAML_HEADER = 'google-accounts-saml';

  /** @const */
  const SAML_VERIFIED_ACCESS_CHALLENGE_HEADER = 'x-verified-access-challenge';
  /** @const */
  const SAML_VERIFIED_ACCESS_RESPONSE_HEADER =
      'x-verified-access-challenge-response';

  /** @const */
  const BEGIN_CERTIFICATE = '-----BEGIN CERTIFICATE-----';

  /** @const */
  const END_CERTIFICATE = '-----END CERTIFICATE-----';

  /** @const */
  const injectedScriptName = 'samlInjected';

  /**
   * The script to inject into webview and its sub frames.
   * @type {string}
   */
  const injectedJs = String.raw`
      // <include src="webview_saml_injected.js">
  `;

  /**
   * @typedef {{
   *   method: string,
   *   requestedVersion: number,
   *   keyType: string,
   *   token: string,
   *   passwordBytes: string
   * }}
   */
  let ApiCallMessageCall;

  /**
   * @typedef {{
   *   name: string,
   *   call: ApiCallMessageCall
   * }}
   */
  let ApiCallMessage;

  /**
   * Details about the request.
   * @typedef {{
   *   method: string,
   *   requestBody: Object,
   *   url: string
   * }}
   * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest#details
   */
  /* #export */ let OnBeforeRequestDetails;

  /**
   * Details of the request.
   * @typedef {{
   *   responseHeaders: Array<HttpHeader>,
   *   statusCode: number,
   *   url: string,
   * }}
   * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived#details
   */
  /* #export */ let OnHeadersReceivedDetails;

  /**
   * Creates a new URL by striping all query parameters.
   * @param {string} url The original URL.
   * @return {string} The new URL with all query parameters stripped.
   */
  function stripParams(url) {
    return url.substring(0, url.indexOf('?')) || url;
  }

  /**
   * A handler to provide saml support for the given webview that hosts the
   * auth IdP pages.
   */
  /* #export */ class SamlHandler extends cr.EventTarget {
    /**
     * @param {!WebView} webview
     * @param {boolean} startsOnSamlPage - whether initial URL is already SAML
     *                  page
     * */
    constructor(webview, startsOnSamlPage) {
      super();

      /**
       * Device attestation flow stages.
       * @enum {number}
       * @private
       */
      SamlHandler.DeviceAttestationStage = {
        // No device attestation in progress.
        NONE: 1,
        // A Redirect was received with a HTTP header that contained a device
        // attestation challenge.
        CHALLENGE_RECEIVED: 2,
        // The Redirect has been canceled and a device attestation challenge
        // response is being computed.
        ORIGINAL_REDIRECT_CANCELED: 3,
        // The device attestation challenge response is available and the
        // original Redirect is being followed with the response included in a
        // HTTP header.
        NAVIGATING_TO_REDIRECT_PAGE: 4,
      };

      /**
       * The webview that serves IdP pages.
       * @private {!WebView}
       */
      this.webview_ = webview;

      /**
       * Whether a Saml page is in the webview from the start.
       * @private {boolean}
       */
      this.startsOnSamlPage_ = startsOnSamlPage;

      /**
       * Whether a Saml IdP page is display in the webview.
       * @private {boolean}
       */
      this.isSamlPage_ = this.startsOnSamlPage_;

      /**
       * Pending Saml IdP page flag that is set when a SAML_HEADER is received
       * and is copied to |isSamlPage_| in loadcommit.
       * @private {boolean}
       */
      this.pendingIsSamlPage_ = this.startsOnSamlPage_;

      /**
       * The last aborted top level url. It is recorded in loadabort event and
       * used to skip injection into Chrome's error page in the following
       * loadcommit event.
       * @private {?string}
       */
      this.abortedTopLevelUrl_ = null;

      /**
       * Scraped password stored in an id to password field value map.
       * @private {!Object<string, string>}
       */
      this.passwordStore_ = {};

      /**
       * Whether Saml API is initialized.
       * @private {boolean}
       */
      this.apiInitialized_ = false;

      /**
       * Saml API version to use.
       * @private {number}
       */
      this.apiVersion_ = 0;

      /**
       * Saml API tokens received.
       * @private {!Object}
       */
      this.apiTokenStore_ = {};

      /**
       * Saml API confirmation token. Set by last 'confirm' call.
       * @private {?string}
       */
      this.confirmToken_ = null;

      /**
       * Saml API password bytes set by last 'add' call. Needed to not break
       * existing behavior.
       * @private {?string}
       */
      this.lastApiPasswordBytes_ = null;

      /**
       * Whether to abort the authentication flow and show an error message
       * when content served over an unencrypted connection is detected.
       * @type {boolean}
       */
      this.blockInsecureContent = false;

      /**
       * Whether to attempt to extract password attributes from the SAMLResponse
       * XML. See saml_password_attributes.js
       * @type {boolean}
       */
      this.extractSamlPasswordAttributes = false;

      /**
       * Current stage of device attestation flow.
       * @private {!SamlHandler.DeviceAttestationStage}
       */
      this.deviceAttestationStage_ = SamlHandler.DeviceAttestationStage.NONE;

      /**
       * Challenge from IdP to perform device attestation.
       * @private {?string}
       */
      this.verifiedAccessChallenge_ = null;

      /**
       * Response for a device attestation challenge.
       * @private {?string}
       */
      this.verifiedAccessChallengeResponse_ = null;

      /**
       * Certificate that were extracted from the SAMLResponse.
       * @public {?string}
       */
      this.x509certificate = null;

      /**
       * The password-attributes that were extracted from the SAMLResponse, if
       * any. (Doesn't contain the password itself).
       * @private {!PasswordAttributes}
       */
      this.passwordAttributes_ =
          samlPasswordAttributes.PasswordAttributes.EMPTY;

      this.webviewEventManager_ = WebviewEventManager.create();

      this.webviewEventManager_.addEventListener(
          this.webview_, 'contentload', this.onContentLoad_.bind(this));
      this.webviewEventManager_.addEventListener(
          this.webview_, 'loadabort', this.onLoadAbort_.bind(this));
      this.webviewEventManager_.addEventListener(
          this.webview_, 'permissionrequest',
          this.onPermissionRequest_.bind(this));

      this.webviewEventManager_.addWebRequestEventListener(
          this.webview_.request.onBeforeRequest,
          this.onInsecureRequest.bind(this),
          {urls: ['http://*/*', 'file://*/*', 'ftp://*/*']}, ['blocking']);

      this.webviewEventManager_.addWebRequestEventListener(
          this.webview_.request.onBeforeRequest,
          this.onMainFrameWebRequest.bind(this),
          {urls: ['http://*/*', 'https://*/*'], types: ['main_frame']},
          ['requestBody']);

      if (!this.startsOnSamlPage_) {
        this.webviewEventManager_.addEventListener(
            this.webview_, 'loadcommit', this.onLoadCommit_.bind(this));

        this.webviewEventManager_.addWebRequestEventListener(
            this.webview_.request.onBeforeRequest,
            this.onBeforeRequest_.bind(this),
            {urls: ['<all_urls>'], types: ['main_frame', 'xmlhttprequest']},
            ['blocking']);

        this.webviewEventManager_.addWebRequestEventListener(
            this.webview_.request.onBeforeSendHeaders,
            this.onBeforeSendHeaders_.bind(this),
            {urls: ['<all_urls>'], types: ['main_frame', 'xmlhttprequest']},
            ['blocking', 'requestHeaders']);

        this.webviewEventManager_.addWebRequestEventListener(
            this.webview_.request.onHeadersReceived,
            this.onHeadersReceived_.bind(this),
            {urls: ['<all_urls>'], types: ['main_frame', 'xmlhttprequest']},
            ['blocking', 'responseHeaders']);
      }

      this.webview_.addContentScripts([{
        name: injectedScriptName,
        matches: ['http://*/*', 'https://*/*'],
        js: {code: injectedJs},
        all_frames: true,
        run_at: 'document_start'
      }]);

      PostMessageChannel.runAsDaemon(this.onConnected_.bind(this));
    }

    /**
     * Whether Saml API is used during auth.
     * @return {boolean}
     */
    get samlApiUsed() {
      return !!this.lastApiPasswordBytes_;
    }

    /**
     * Returns the Saml API password bytes.
     * @return {?string}
     */
    get apiPasswordBytes() {
      if (this.confirmToken_ != null &&
          typeof (this.apiTokenStore_[this.confirmToken_]) == 'object' &&
          typeof (this.apiTokenStore_[this.confirmToken_]['passwordBytes']) ==
              'string') {
        return this.apiTokenStore_[this.confirmToken_]['passwordBytes'];
      }
      return this.lastApiPasswordBytes_;
    }

    /**
     * Returns the first scraped password if any, or an empty string otherwise.
     * @return {string}
     */
    get firstScrapedPassword() {
      const scraped = this.getConsolidatedScrapedPasswords_();
      return scraped.length ? scraped[0] : '';
    }

    /**
     * Returns the number of scraped passwords.
     * @return {number}
     */
    get scrapedPasswordCount() {
      return this.getConsolidatedScrapedPasswords_().length;
    }

    /**
     * Gets the list of passwords which have matching passwordProperty and
     * are scraped exactly |times| times.
     * @return {Array<string>}
     */
    getPasswordsWithPropertyScrapedTimes(times, passwordProperty) {
      const passwords = {};
      for (const property in this.passwordStore_) {
        if (passwordProperty && !property.match(passwordProperty)) {
          continue;
        }
        const key = this.passwordStore_[property];
        passwords[key] = (passwords[key] + 1) || 1;
      }
      return Object.keys(passwords).filter(key => passwords[key] == times);
    }

    /**
     * Gets the de-duped scraped passwords.
     * @return {Array<string>}
     * @private
     */
    getConsolidatedScrapedPasswords_() {
      const passwords = {};
      for (const property in this.passwordStore_) {
        passwords[this.passwordStore_[property]] = true;
      }
      return Object.keys(passwords);
    }

    /**
     * Gets the password attributes extracted from SAML Response.
     * @return {Object}
     */
    get passwordAttributes() {
      return this.passwordAttributes_;
    }

    /**
     * Sets the startsOnSamlPage attribute of the SAML handler.
     * @param {boolean} value
     */
    set startsOnSamlPage(value) {
      this.startsOnSamlPage_ = value;
      this.reset();
    }

    /**
     * Removes the injected content script and unbinds all listeners from the
     * webview passed to the constructor. This SAMLHandler will be unusable
     * after this function returns.
     */
    unbindFromWebview() {
      this.webview_.removeContentScripts([injectedScriptName]);
      this.webviewEventManager_.removeAllListeners();
    }

    /**
     * Resets all auth states
     */
    reset() {
      this.isSamlPage_ = this.startsOnSamlPage_;
      this.pendingIsSamlPage_ = this.startsOnSamlPage_;
      this.passwordStore_ = {};

      this.deviceAttestationStage_ = SamlHandler.DeviceAttestationStage.NONE;
      this.verifiedAccessChallenge_ = null;
      this.verifiedAccessChallengeResponse_ = null;

      this.apiInitialized_ = false;
      this.apiVersion_ = 0;
      this.apiTokenStore_ = {};
      this.confirmToken_ = null;
      this.lastApiPasswordBytes_ = null;
      this.passwordAttributes_ =
          samlPasswordAttributes.PasswordAttributes.EMPTY;
      this.x509certificate = null;
    }

    /**
     * Check whether the given |password| is in the scraped passwords.
     * @return {boolean} True if the |password| is found.
     */
    verifyConfirmedPassword(password) {
      return this.getConsolidatedScrapedPasswords_().indexOf(password) >= 0;
    }

    /**
     * Check that last navigation was aborted intentionally. It will be
     * continued later, so the abort event can be ignored.
     * @return {boolean}
     */
    isIntentionalAbort() {
      return this.deviceAttestationStage_ ==
          SamlHandler.DeviceAttestationStage.ORIGINAL_REDIRECT_CANCELED;
    }

    /**
     * Invoked on the webview's contentload event.
     * @private
     */
    onContentLoad_(e) {
      // |this.webview_.contentWindow| may be null after network error screen
      // is shown. See crbug.com/770999.
      if (this.webview_.contentWindow) {
        PostMessageChannel.init(this.webview_.contentWindow);
      } else {
        console.error('SamlHandler.onContentLoad_: contentWindow is null.');
      }
    }

    /**
     * Invoked on the webview's loadabort event.
     * @private
     */
    onLoadAbort_(e) {
      if (this.isIntentionalAbort()) {
        return;
      }

      if (e.isTopLevel) {
        this.abortedTopLevelUrl_ = e.url;
      }
    }

    /**
     * Invoked on the webview's loadcommit event for both main and sub frames.
     * @private
     */
    onLoadCommit_(e) {
      // Skip this loadcommit if the top level load is just aborted.
      if (e.isTopLevel && e.url === this.abortedTopLevelUrl_) {
        this.abortedTopLevelUrl_ = null;
        return;
      }

      // Skip for none http/https url.
      if (!e.url.startsWith('https://') && !e.url.startsWith('http://')) {
        return;
      }

      this.isSamlPage_ = this.pendingIsSamlPage_;
    }

    /**
     * Handler for webRequest.onBeforeRequest, invoked when content served over
     * an unencrypted connection is detected. Determines whether the request
     * should be blocked and if so, signals that an error message needs to be
     * shown.
     * @param {Object} details
     * @return {!Object} Decision whether to block the request.
     */
    onInsecureRequest(details) {
      if (!this.blockInsecureContent) {
        return {};
      }
      const strippedUrl = stripParams(details.url);
      this.dispatchEvent(new CustomEvent(
          'insecureContentBlocked', {detail: {url: strippedUrl}}));
      return {cancel: true};
    }

    /**
     * Set x509certificate in pem-format which is extracted from samlResponse
     * and will be used to record SAML provider
     * @param {string} samlResponse SAML response which is received from SAML
     *     page.
     * @private
     */
    setX509certificate_(samlResponse) {
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(samlResponse, 'text/xml');
      let certificate = xmlDoc.getElementsByTagName('ds:X509Certificate');
      if (!certificate || certificate.length == 0) {
        // tag 'ds:X509Certificate' doesn't exist
        certificate = xmlDoc.getElementsByTagName('X509Certificate');
      }

      if (certificate && certificate.length > 0 && certificate[0].childNodes &&
          certificate[0].childNodes[0] &&
          certificate[0].childNodes[0].nodeValue) {
        certificate = certificate[0].childNodes[0].nodeValue;
        this.x509certificate = BEGIN_CERTIFICATE + '\n' + certificate.trim() +
            '\n' + END_CERTIFICATE + '\n';
      }
    }

    /**
     * Handler for webRequest.onBeforeRequest that looks for the Base64
     * encoded SAMLResponse in the POST-ed formdata sent from the SAML page.
     * Non-blocking.
     * @param {OnBeforeRequestDetails} details The web-request details.
     */
    onMainFrameWebRequest(details) {
      if (!this.extractSamlPasswordAttributes) {
        return;
      }
      if (!this.isSamlPage_ || details.method != 'POST') {
        return;
      }

      const formData = details.requestBody.formData;
      let samlResponse = (formData && formData.SAMLResponse);
      if (!samlResponse) {
        samlResponse = new URL(details.url).searchParams.get('SAMLResponse');
      }
      if (!samlResponse) {
        return;
      }

      try {
        // atob means asciiToBinary, which actually means base64Decode:
        samlResponse = window.atob(samlResponse);
      } catch (decodingError) {
        console.warn('SAMLResponse is not Base64 encoded');
        return;
      }

      this.setX509certificate_(samlResponse);

      this.passwordAttributes_ =
          samlPasswordAttributes.readPasswordAttributes(samlResponse);
    }

    /**
     * Receives a response for a device attestation challenge and navigates to
     * saved redirect page.
     * @param {string} url Url from canceled redirect.
     * @param {{success: boolean, response: string}} challengeResponse Response
     *     for device attestation challenge. If |success| is true, |response|
     *     contains challenge response. Otherwise |response| contains empty
     *     string.
     * @private
     */
    continueDelayedRedirect_(url, challengeResponse) {
      if (this.deviceAttestationStage_ !=
          SamlHandler.DeviceAttestationStage.ORIGINAL_REDIRECT_CANCELED) {
        console.error(
            'SamlHandler.continueDelayedRedirect_: incorrect attestation stage');
        return;
      }

      // Save response only if it is successful.
      if (challengeResponse.success) {
        this.verifiedAccessChallengeResponse_ = challengeResponse.response;
      }

      // Navigate to the saved destination from the canceled redirect.
      this.deviceAttestationStage_ =
          SamlHandler.DeviceAttestationStage.NAVIGATING_TO_REDIRECT_PAGE;
      this.webview_.src = url;
    }

    /**
     * Invoked before sending a web request. If a challenge for the remote
     * attestation was found in a previous request, cancel the current one. It
     * will be continued (reinitiated) later when a challenge response is ready.
     * @param {Object} details The web-request details.
     * @return {BlockingResponse} Allows the event handler to modify network
     *     requests.
     * @private
     */
    onBeforeRequest_(details) {
      // Default case without Verified Access.
      if (this.deviceAttestationStage_ ==
          SamlHandler.DeviceAttestationStage.NONE) {
        return {};
      }

      if (this.deviceAttestationStage_ ==
          SamlHandler.DeviceAttestationStage.NAVIGATING_TO_REDIRECT_PAGE) {
        return {};
      }

      if ((this.deviceAttestationStage_ ==
           SamlHandler.DeviceAttestationStage.CHALLENGE_RECEIVED) &&
          (this.verifiedAccessChallenge_ !== null)) {
        // Ask backend to compute response for device attestation challenge.
        this.dispatchEvent(new CustomEvent('challengeMachineKeyRequired', {
          detail: {
            url: details.url,
            challenge: this.verifiedAccessChallenge_,
            callback: this.continueDelayedRedirect_.bind(this, details.url)
          }
        }));

        this.verifiedAccessChallenge_ = null;

        // Cancel redirect by changing destination to javascript:void(0).
        // That will produce 'loadabort' event that should be ignored.
        this.deviceAttestationStage_ =
            SamlHandler.DeviceAttestationStage.ORIGINAL_REDIRECT_CANCELED;
        return {redirectUrl: 'javascript:void(0)'};
      }

      // Reset state in case of unexpected requests during device attestation.
      this.deviceAttestationStage_ = SamlHandler.DeviceAttestationStage.NONE;
      console.error(
          'SamlHandler.onBeforeRequest_: incorrect attestation stage');
      return {};
    }

    /**
     * Attaches challenge response during device attestation flow.
     * @param {Object} details The web-request details.
     * @return {BlockingResponse} Allows the event handler to modify network
     *     requests.
     * @private
     */
    onBeforeSendHeaders_(details) {
      // Default case without Verified Access.
      if (this.deviceAttestationStage_ ==
          SamlHandler.DeviceAttestationStage.NONE) {
        return {};
      }

      if (this.deviceAttestationStage_ ==
          SamlHandler.DeviceAttestationStage.NAVIGATING_TO_REDIRECT_PAGE) {
        // Send extra header only if no error was encountered during challenge
        // key procedure.
        if (this.verifiedAccessChallengeResponse_ === null) {
          this.deviceAttestationStage_ =
              SamlHandler.DeviceAttestationStage.NONE;
          return {};
        }

        details.requestHeaders.push({
          'name': SAML_VERIFIED_ACCESS_RESPONSE_HEADER,
          'value': this.verifiedAccessChallengeResponse_
        });

        this.verifiedAccessChallengeResponse_ = null;
        this.deviceAttestationStage_ = SamlHandler.DeviceAttestationStage.NONE;

        return {requestHeaders: details.requestHeaders};
      }

      // Reset state in case of unexpected navigation during device attestation.
      this.deviceAttestationStage_ = SamlHandler.DeviceAttestationStage.NONE;
      console.error(
          'SamlHandler.onBeforeSendHeaders_: incorrect attestation stage');
      return {};
    }

    /**
     * Invoked when headers are received for the main frame.
     * @private
     */
    onHeadersReceived_(details) {
      const headers = details.responseHeaders;

      // Check whether GAIA headers indicating the start or end of a SAML
      // redirect are present.
      for (let i = 0; headers && i < headers.length; ++i) {
        const header = headers[i];
        const headerName = header.name.toLowerCase();

        if (headerName == SAML_HEADER) {
          const action = header.value.toLowerCase();
          if (action == 'start') {
            this.pendingIsSamlPage_ = true;
          } else if (action == 'end') {
            this.pendingIsSamlPage_ = false;
          }
        }

        // If true, IdP tries to perform a device attestation.
        // 300 <= .. <= 399 means it is a redirect to a page that will verify
        // device response. HTTP header with
        // |SAML_VERIFIED_ACCESS_CHALLENGE_HEADER| name contains challenge from
        // Verified Access Web API.
        if ((details.statusCode >= 300) && (details.statusCode <= 399) &&
            (headerName == SAML_VERIFIED_ACCESS_CHALLENGE_HEADER)) {
          this.deviceAttestationStage_ =
              SamlHandler.DeviceAttestationStage.CHALLENGE_RECEIVED;
          this.verifiedAccessChallenge_ = header.value;
        }
      }

      return {};
    }

    /**
     * Invoked when the injected JS makes a connection.
     */
    onConnected_(port) {
      if (port.targetWindow != this.webview_.contentWindow) {
        return;
      }

      const channel = Channel.create();
      channel.init(port);

      channel.registerMessage('apiCall', this.onAPICall_.bind(this, channel));
      channel.registerMessage(
          'updatePassword', this.onUpdatePassword_.bind(this, channel));
      channel.registerMessage(
          'pageLoaded', this.onPageLoaded_.bind(this, channel));
      channel.registerMessage(
          'getSAMLFlag', this.onGetSAMLFlag_.bind(this, channel));
      channel.registerMessage(
          'scrollInfo', this.onScrollInfo_.bind(this, channel));
    }

    sendInitializationSuccess_(channel) {
      channel.send({
        name: 'apiResponse',
        response: {
          result: 'initialized',
          version: this.apiVersion_,
          keyTypes: API_KEY_TYPES
        }
      });
    }

    sendInitializationFailure_(channel) {
      channel.send(
          {name: 'apiResponse', response: {result: 'initialization_failed'}});
    }

    /**
     * Handlers for channel messages.
     * @param {Channel} channel A channel to send back response.
     * @param {ApiCallMessage} msg Received message.
     * @private
     */
    onAPICall_(channel, msg) {
      const call = msg.call;
      if (call.method == 'initialize') {
        if (!Number.isInteger(call.requestedVersion) ||
            call.requestedVersion < MIN_API_VERSION_VERSION) {
          this.sendInitializationFailure_(channel);
          return;
        }

        this.apiVersion_ =
            Math.min(call.requestedVersion, MAX_API_VERSION_VERSION);
        this.apiInitialized_ = true;
        this.sendInitializationSuccess_(channel);
        return;
      }

      if (call.method == 'add') {
        if (API_KEY_TYPES.indexOf(call.keyType) == -1) {
          console.error('SamlHandler.onAPICall_: unsupported key type');
          return;
        }
        // Not setting |email_| and |gaiaId_| because this API call will
        // eventually be followed by onCompleteLogin_() which does set it.
        this.apiTokenStore_[call.token] = call;
        this.lastApiPasswordBytes_ = call.passwordBytes;

        this.dispatchEvent(new CustomEvent('apiPasswordAdded'));
      } else if (call.method == 'confirm') {
        if (!(call.token in this.apiTokenStore_)) {
          console.error('SamlHandler.onAPICall_: token mismatch');
        } else {
          this.confirmToken_ = call.token;
        }
      } else {
        console.error('SamlHandler.onAPICall_: unknown message');
      }
    }

    onUpdatePassword_(channel, msg) {
      if (this.isSamlPage_) {
        this.passwordStore_[msg.id] = msg.password;
      }
    }

    onPageLoaded_(channel, msg) {
      this.dispatchEvent(new CustomEvent(
          'authPageLoaded', {detail: {isSAMLPage: this.isSamlPage_}}));
    }

    onScrollInfo_(channel, msg) {
      const scrollTop = msg.scrollTop;
      const scrollHeight = msg.scrollHeight;
      const clientHeight = this.webview_.clientHeight;

      if (scrollTop === undefined || scrollHeight === undefined) {
        return;
      }

      this.webview_.classList.toggle('can-scroll', clientHeight < scrollHeight);
      this.webview_.classList.toggle('is-scrolled', scrollTop > 0);
      const scrolledToBottom = (scrollTop > 0) /*is-scrolled*/ &&
          (Math.ceil(scrollTop + clientHeight) >= scrollHeight);
      this.webview_.classList.toggle('scrolled-to-bottom', scrolledToBottom);
    }

    onPermissionRequest_(permissionEvent) {
      if (permissionEvent.permission === 'media') {
        // The actual permission check happens in
        // WebUILoginView::RequestMediaAccessPermission().
        this.dispatchEvent(new CustomEvent('videoEnabled'));
        permissionEvent.request.allow();
      }
    }

    onGetSAMLFlag_(channel, msg) {
      return this.isSamlPage_;
    }
  }

  // #cr_define_end
  return {SamlHandler: SamlHandler};
});


text:
"""Ingestion function that fetches data from one file and simply copies it to another."""

import argparse
import time
from pathlib import Path

def parse_args():
  """Parse ingestion arguments."""
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "--ingested-dataset-path",
      type=str,
      help="Path to save the ingested dataset to.",
      required=True)
  parser.add_argument(
      "--base-artifact-path",
      type=str,
      help="Base path to store pipeline artifacts.",
      required=True)
  return parser.parse_args()

def ingest_data(ingested_dataset_path: str, base_artifact_path: str):
  """Data ingestion step that returns an uri
  to the data it has 'ingested' as jsonlines.

  Args:
    data_ingestion_target (str): uri to the data that was scraped and
    ingested by the component"""
  # timestamp as unique id for the component execution
  timestamp = int(time.time())

  # create directory to store the actual data
  target_path = f"{base_artifact_path}/ingestion/ingested_dataset_{timestamp}.jsonl"
  # if the target path is a google cloud storage path convert the path to the gcsfuse path
  target_path_gcsfuse = target_path.replace("gs://", "/gcs/")
  Path(target_path_gcsfuse).parent.mkdir(parents=True, exist_ok=True)

  with open(target_path_gcsfuse, 'w') as f:
    f.writelines([
        """{"image_id": 318556, "id": 255, "caption": "An angled view of a beautifully decorated bathroom.", "image_url": "http://farm4.staticflickr.com/3133/3378902101_3c9fa16b84_z.jpg", "image_name": "COCO_train2014_000000318556.jpg", "image_license": "Attribution-NonCommercial-ShareAlike License"}\n""",
        """{"image_id": 476220, "id": 314, "caption": "An empty kitchen with white and black appliances.", "image_url": "http://farm7.staticflickr.com/6173/6207941582_b69380c020_z.jpg", "image_name": "COCO_train2014_000000476220.jpg", "image_license": "Attribution-NonCommercial License"}\n""",
        """{"image_id": 134754, "id": 425, "caption": "Two people carrying surf boards on a beach.", "image_url": "http://farm9.staticflickr.com/8500/8398513396_b6a1f11a4b_z.jpg", "image_name": "COCO_train2014_000000134754.jpg", "image_license": "Attribution-NonCommercial-NoDerivs License"}"""
    ])

  # the directory where the output file is created may or may not exists
  # so we have to create it.
  # KFP v1 components can only write output to files. The output of this
  # component is written to ingested_dataset_path and contains the path
  # of the actual ingested data
  Path(ingested_dataset_path).parent.mkdir(parents=True, exist_ok=True)
  with open(ingested_dataset_path, 'w') as f:
    f.write(target_path)

if __name__ == "__main__":
  args = parse_args()
  ingest_data(**vars(args))


text:
module LibCUFFT
using Compat

import Base.Sys: WORD_SIZE

include("cufft_h.jl")
import CUDArt.rt.cudaStream_t

@windows? (
begin
    const libcufft = Libdl.find_library([string("cufft", WORD_SIZE, "_75"),
      string("cufft", WORD_SIZE, "_70"), string("cufft", WORD_SIZE, "_65")],
      [joinpath(ENV["CUDA_PATH"], "bin")])
end
: # linux or mac
begin
    const libcufft = Libdl.find_library(["libcufft", "cufft"], ["/usr/lib", "/usr/local/cuda"])
end)

isempty(libcufft) && error("Cannot load libcufft")

function checkerror(code::cufftResult)
    if code == CUFFT_SUCCESS
        return nothing
    end
    println("An error was triggered:")
    Base.show_backtrace(STDOUT, backtrace())
    throw(cufft_errors[uint8(code)])
end

cufft_errors = @compat Dict(
    CUFFT_INVALID_PLAN   => "Invalid plan",
    CUFFT_ALLOC_FAILED   => "Allocation failed",
    CUFFT_INVALID_TYPE   => "Invalid type",
    CUFFT_INVALID_VALUE  => "Invalid value",
    CUFFT_INTERNAL_ERROR => "Internal error",
    CUFFT_EXEC_FAILED    => "Execution failed",
    CUFFT_SETUP_FAILED   => "Setup failed",
    CUFFT_INVALID_SIZE   => "Invalid size",
    CUFFT_UNALIGNED_DATA => "Unaligned data"
)

function cufftPlan1d(plan, nx, _type, batch)
  checkerror(ccall( (:cufftPlan1d, libcufft), cufftResult, (Ptr{cufftHandle}, Cint, cufftType, Cint), plan, nx, _type, batch))
end
function cufftPlan2d(plan, nx, ny, _type)
  checkerror(ccall( (:cufftPlan2d, libcufft), cufftResult, (Ptr{cufftHandle}, Cint, Cint, cufftType), plan, nx, ny, _type))
end
function cufftPlan3d(plan, nx, ny, nz, _type)
  checkerror(ccall( (:cufftPlan3d, libcufft), cufftResult, (Ptr{cufftHandle}, Cint, Cint, Cint, cufftType), plan, nx, ny, nz, _type))
end
function cufftPlanMany(plan, rank, n, inembed, istride, idist, onembed, ostride, odist, _type, batch)
  checkerror(ccall( (:cufftPlanMany, libcufft), cufftResult, (Ptr{cufftHandle}, Cint, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Ptr{Cint}, Cint, Cint, cufftType, Cint), plan, rank, n, inembed, istride, idist, onembed, ostride, odist, _type, batch))
end
function cufftDestroy(plan)
  checkerror(ccall( (:cufftDestroy, libcufft), cufftResult, (cufftHandle,), plan))
end
function cufftExecC2C(plan, idata, odata, direction)
  checkerror(ccall( (:cufftExecC2C, libcufft), cufftResult, (cufftHandle, Ptr{cufftComplex}, Ptr{cufftComplex}, Cint), plan, idata, odata, direction))
end
function cufftExecR2C(plan, idata, odata)
  checkerror(ccall( (:cufftExecR2C, libcufft), cufftResult, (cufftHandle, Ptr{cufftReal}, Ptr{cufftComplex}), plan, idata, odata))
end
function cufftExecC2R(plan, idata, odata)
  checkerror(ccall( (:cufftExecC2R, libcufft), cufftResult, (cufftHandle, Ptr{cufftComplex}, Ptr{cufftReal}), plan, idata, odata))
end
function cufftExecZ2Z(plan, idata, odata, direction)
  checkerror(ccall( (:cufftExecZ2Z, libcufft), cufftResult, (cufftHandle, Ptr{cufftDoubleComplex}, Ptr{cufftDoubleComplex}, Cint), plan, idata, odata, direction))
end
function cufftExecD2Z(plan, idata, odata)
  checkerror(ccall( (:cufftExecD2Z, libcufft), cufftResult, (cufftHandle, Ptr{cufftDoubleReal}, Ptr{cufftDoubleComplex}), plan, idata, odata))
end
function cufftExecZ2D(plan, idata, odata)
  checkerror(ccall( (:cufftExecZ2D, libcufft), cufftResult, (cufftHandle, Ptr{cufftDoubleComplex}, Ptr{cufftDoubleReal}), plan, idata, odata))
end
function cufftSetStream(plan, stream)
  checkerror(ccall( (:cufftSetStream, libcufft), cufftResult, (cufftHandle, cudaStream_t), plan, stream))
end
function cufftSetCompatibilityMode(plan, mode)
  checkerror(ccall( (:cufftSetCompatibilityMode, libcufft), cufftResult, (cufftHandle, cufftCompatibility), plan, mode))
end
function cufftGetVersion(version)
  checkerror(ccall( (:cufftGetVersion, libcufft), cufftResult, (Ptr{Cint},), version))
end

end


text:
import sure
from django.test import TestCase
from tasks.const import STATUS_SUCCESS, STATUS_FAILED
from ..jslint import jslint_violation
from .base import get_content

class JSlintViolationCase(TestCase):
    """JSlint violation case"""

    def test_success(self):
        """Test success result"""
        data = {'raw': ''}
        result = jslint_violation(data)
        result['status'].should.be.equal(STATUS_SUCCESS)
        result['plot']['count'].should.be.equal(0)

    def test_fail_on_real(self):
        """Test fail on real data"""
        data = {
            'raw': get_content('jslint.out'),
        }
        result = jslint_violation(data)
        result['status'].should.be.equal(STATUS_FAILED)
        result['plot']['count'].should.be.equal(131)


text:
module Main where

data Fix f = Fix (f (Fix f))

--
-- Base AST template
--

data Expression binOp expr =
    ExprInt   { exprInt :: Int
              }
  | ExprBinOp { exprLeft  :: expr
              , exprBinOp :: binOp
              , exprRight :: expr
              }
--

data BinOp = Add | Sub

--
-- Extending with more binary operations
--

data BinOpExt = Mul | Div | BinOpBase BinOp

--
-- Extending with unary operations
--

data ExpressionExt uniOp binOp expr =
    ExprUniOp { exprUniOp :: uniOp
              , exprArg   :: expr
              }
  | ExprBase (Expression binOp expr)
--

data UniOp = Fac | Log

--
-- Instantiation of the base AST.
--

type SimpleExpr = Fix (Expression BinOp)

evalSimpleExpr :: SimpleExpr -> Int
evalSimpleExpr (Fix (ExprInt i))        = i
evalSimpleExpr (Fix (ExprBinOp l op r)) = evalL `evalOp` evalR
  where evalL = evalSimpleExpr l
        evalR = evalSimpleExpr r
        evalOp = case op of
                   Add -> (+)
                   Sub -> (-)
--

simple01 :: SimpleExpr
simple01 = Fix (ExprBinOp (Fix (ExprInt 5)) Add (Fix (ExprInt 5)))

--
-- Instantiation of the extended AST.
--

type ExtendedExpr = Fix (ExpressionExt UniOp BinOpExt)

evalExtendedExpr :: ExtendedExpr -> Int
evalExtendedExpr (Fix (ExprUniOp op arg)) = evalOp evalArg
  where evalOp = case op of
                   Fac -> product . flip take [1..]
                   Log -> floor . log . fromIntegral
        evalArg = evalExtendedExpr arg
evalExtendedExpr (Fix (ExprBase (ExprInt i))) = i
evalExtendedExpr (Fix (ExprBase (ExprBinOp l op r))) = evalL `evalOp` evalR
  where evalL = evalExtendedExpr l
        evalR = evalExtendedExpr r
        evalOp = case op of
                   Mul -> (*)
                   Div -> div
                   BinOpBase Add -> (+)
                   BinOpBase Sub -> (-)
--

extended01 :: ExtendedExpr
extended01 = Fix (ExprUniOp Fac (Fix (ExprBase (ExprBinOp (Fix (ExprBase (ExprInt 3))) Mul (Fix (ExprBase (ExprInt 2)))))))

-- This is to make the compiler happy.

main :: IO ()
main = putStrLn "Hello World"


text:
webpackJsonp([1],{

/***/ 5:
/***/ function(module, exports, __webpack_require__) {

	angular.module('prettyUrl')
	    .component('screen1', {
	        template: __webpack_require__(6),
	        controller: Screen1Controller,
	        controllerAs: 'vm'
	    });

	Screen1Controller.$inject = [];
	function Screen1Controller(){
		var vm = this;
	}

/***/ },

/***/ 6:
/***/ function(module, exports) {

	module.exports = "
Screen 1
\r\nGo to Screen 2";

/***/ }

});


text:
package org.develnext.jphp.core.tokenizer.token.stmt;

import org.develnext.jphp.core.tokenizer.TokenType;
import org.develnext.jphp.core.tokenizer.TokenMeta;

abstract public class LogicStmtToken extends StmtToken {

    public ExprStmtToken condition;
    public ExprStmtToken nextExpression;

    public LogicStmtToken(TokenMeta meta) {
        super(meta, TokenType.T_J_CUSTOM);
    }

    public ExprStmtToken getCondition() {
        return condition;
    }

    public void setCondition(ExprStmtToken condition) {
        this.condition = condition;
    }

    public ExprStmtToken getNextExpression() {
        return nextExpression;
    }

    public void setNextExpression(ExprStmtToken nextExpression) {
        this.nextExpression = nextExpression;
    }
}


text:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

// https://www.hackerrank.com/challenges/java-negative-subarray
public class Solution {
    public static int countNegativeSubarrays(int n, int[] arr) {
        int counter = 0;

        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
                sum += arr[j];
                if (sum < 0)
                    counter++;
            }
        }

        return counter;
    }

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] arr = new int[n];

        for (int i = 0; i < n; i++)
            arr[i] = scan.nextInt();

        System.out.println(countNegativeSubarrays(n, arr));
    }
}


text:
CREATE TABLE IF NOT EXISTS `apilog` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned DEFAULT NULL,
`token` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`apikey` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`appkey` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`zoneid` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`url` varchar(2000) CHARACTER SET utf8mb4,
`method` varchar(200) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`header` mediumtext CHARACTER SET utf8mb4,
`headerlen` int(10) unsigned DEFAULT NULL,
`body` mediumtext CHARACTER SET utf8mb4,
`bodylen` int(10) unsigned DEFAULT NULL,
`datesend` timestamp NULL DEFAULT NULL,
`pagestatus` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`resultstatus` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`responseheader` mediumtext CHARACTER SET utf8mb4,
`responsebody` mediumtext CHARACTER SET utf8mb4,
`dateresponse` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


text:
var jwt = require('../index');

var expect = require('chai').expect;
var assert = require('chai').assert;

describe('HS256', function() {

  describe('when signing a token', function() {
    var secret = 'shhhhhh';

    var token = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' });

    it('should be syntactically valid', function() {
      expect(token).to.be.a('string');
      expect(token.split('.')).to.have.length(3);
    });

    it('should validate with secret', function(done) {
      jwt.verify(token, secret, function(err, decoded) {
        assert.ok(decoded.foo);
        assert.equal('bar', decoded.foo);
        done();
      });
    });

    it('should throw with invalid secret', function(done) {
      jwt.verify(token, 'invalid secret', function(err, decoded) {
        assert.isUndefined(decoded);
        assert.isNotNull(err);
        done();
      });
    });

    it('should throw with secret and token not signed', function(done) {
      var signed = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'none' });
      var unsigned = signed.split('.')[0] + '.' + signed.split('.')[1] + '.';
      jwt.verify(unsigned, 'secret', function(err, decoded) {
        assert.isUndefined(decoded);
        assert.isNotNull(err);
        done();
      });
    });

  });
});