text:
//-----------------------------------------------------------------------
// <copyright file="SoundRadiusSlider.cs" company="Google">
//
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;

namespace SIS {
    public interface ISoundRadiusSliderDelegate {
        void SoundRadiusSliderValueChanged(SoundRadiusSlider slider, float sliderPercentage, float adjustedRadius);
    }

    public class SoundRadiusSlider : MonoBehaviour {
        public ISoundRadiusSliderDelegate sliderDelegate = null;

        public bool isInnerOtherwiseOuterRadius = false;
        // public float minDiameter { get; private set; } // Will get set on Awake
        // public float maxDiameter { get; private set; } // Will get set on Awake
        public float minDiameter { get { return isInnerOtherwiseOuterRadius
                ? SingletonData.Instance.InnerRadiusMinDiameter
                : SingletonData.Instance.OuterRadiusMinDiameter; } } // Will get set on Awake
        public float maxDiameter { get { return isInnerOtherwiseOuterRadius
                ? SingletonData.Instance.InnerRadiusMaxDiameter
                : SingletonData.Instance.OuterRadiusMaxDiameter; } } // Will get set on Awake

        public float minRadius { get { return minDiameter * 0.5f; } }
        public float maxRadius { get { return maxDiameter * 0.5f; } }
        protected float minDiameterDelta { get { return 1f - minDiameter; } }

        [SerializeField] bool maxGoesToInfinity = false;

        protected UnityEngine.UI.Slider radiusSlider;
        public float sliderValue { get { return radiusSlider.value; } }
        public float diameterValue { get { return DiameterValueFromPercentage(radiusSlider.value); } }
        public float radiusValue { get { return DiameterValueFromPercentage(radiusSlider.value) * 0.5f; } }

        [SerializeField] UnityEngine.UI.Text radiusText;
        [SerializeField] UnityEngine.UI.Text minRadiusText;
        [SerializeField] UnityEngine.UI.Text maxRadiusText;

        [SerializeField] UnityEngine.UI.Image sliderKnobImage = null;
        [SerializeField] UnityEngine.UI.Image sliderFillImage = null;
        [SerializeField] UnityEngine.UI.Image sliderBorderImage = null;

        bool notifySliderDelegate = true;

        private void Awake() {

        }

        // Start is called before the first frame update
        void Start() {
            radiusSlider = GetComponentInChildren<UnityEngine.UI.Slider>();

        }

        public void SetSliderDiameter(float diameter, bool notifyDelegate = true) {
            if (radiusSlider == null) { radiusSlider = GetComponentInChildren<UnityEngine.UI.Slider>(); }

            notifySliderDelegate = notifyDelegate;
            float sliderPercent = PercentageFromDiameterVal(diameter);
            radiusSlider.value = sliderPercent;
            notifySliderDelegate = true;
        }

        public void SetSliderRadius(float radius, bool notifyDelegate = true) {
            SetSliderDiameter(radius * 2f, notifyDelegate);
        }

        public void SetColorTint(Color newCol) {
            // sliderKnobImage.color = newCol;
            sliderFillImage.color = newCol;
            sliderBorderImage.color = newCol;
        }

        protected float PercentageFromDiameterVal(float diam) {
            if (maxGoesToInfinity && diam < 0) { return 1.0f; }

            float clampedDiameter = Mathf.Max(minDiameter, Mathf.Min(maxDiameter, diam));
            return Mathf.Log(clampedDiameter + minDiameterDelta) / Mathf.Log(maxDiameter + minDiameterDelta);
        }
        protected float DiameterValueFromPercentage(float percent) {
            if (maxGoesToInfinity && percent >= 1.0f) { return -1f; }

            return Mathf.Pow(maxDiameter + minDiameterDelta, percent) - minDiameterDelta;
        }
        // -----------------------------------------
        #region Slider Callback
        // -----------------------------------------
        public void SoundDiameterSliderValueChanged(float percentage) {
            float adjustedDiameter = DiameterValueFromPercentage(percentage);
            if (radiusText != null) {
                if (maxGoesToInfinity && adjustedDiameter < 0) {
                    radiusText.text = "∞m";
                } else {
                    radiusText.text = string.Format("{0:0.0}m", Mathf.Floor(adjustedDiameter * 10f) / 10f);
                }
            }

            // this.soundRadiusChanged(radiusVal, adjustedRadius);
            if (sliderDelegate == null || !notifySliderDelegate) {
                return;
            }
            sliderDelegate.SoundRadiusSliderValueChanged(this, percentage, adjustedDiameter * 0.5f);
        }
        #endregion

    }
}


text:
package br.com.agenciacodeplus.socialcron.facebook;

import facebook4j.Facebook;
import facebook4j.FacebookFactory;
import facebook4j.RawAPIResponse;
import facebook4j.auth.AccessToken;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class FacebookTokenHandler {

  private Logger LOGGER = LoggerFactory.getLogger(FacebookTokenHandler.class);

  // TODO Client id and secret are hardcoded. Get these parameters from facebook4j.properties
  public AccessToken refreshToken(AccessToken currentToken) {
    String clientId = "1052750751465673";
    String clientSecret = "a74c62d2d0037517db79073c52a12183";

    Facebook facebook = new FacebookFactory().getInstance(currentToken);

    Map<String, String> params = new HashMap<String, String>();
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("grant_type", "fb_exchange_token");
    params.put("fb_exchange_token", currentToken.getToken());

    RawAPIResponse apiResponse;

    try {
      apiResponse = facebook.callGetAPI("/oauth/access_token", params);
      String accessToken = apiResponse.asJSONObject().getString("access_token");
      AccessToken newAccessToken = new AccessToken(accessToken);
      LOGGER.debug("Facebook access token generated: " + newAccessToken.getToken());
      LOGGER.debug("Expires at: " + newAccessToken.getExpires());
      return newAccessToken;
    } catch (Exception e) {
      LOGGER.error(e.getMessage());
      return null;
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.mockserver.proxy.socks;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.socksx.v4.DefaultSocks4CommandResponse;
import io.netty.handler.codec.socksx.v4.Socks4CommandRequest;
import io.netty.handler.codec.socksx.v4.Socks4CommandStatus;
import io.netty.handler.codec.socksx.v4.Socks4CommandType;
import org.mockserver.lifecycle.LifeCycle;
import org.mockserver.logging.MockServerLogger;

@ChannelHandler.Sharable
public class Socks4ProxyHandler extends SocksProxyHandler<Socks4CommandRequest> {

    public Socks4ProxyHandler(LifeCycle server, MockServerLogger mockServerLogger) {
        super(server, mockServerLogger);
    }

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, final Socks4CommandRequest commandRequest) {
        if (commandRequest.type().equals(Socks4CommandType.CONNECT)) {
            forwardConnection(ctx, new Socks4ConnectHandler(server, mockServerLogger, commandRequest.dstAddr(), commandRequest.dstPort()), commandRequest.dstAddr(), commandRequest.dstPort());
            ctx.fireChannelRead(commandRequest);
        } else {
            ctx.writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)).addListener(ChannelFutureListener.CLOSE);
        }
    }
}


text:
package com.jiangjg.lib.ThingkingInJava.Th20;

import org.junit.Test;

public class AtUnitExample1 {

	public String methodOne(){
		return "one";
	}
	@Test
	boolean methodOneTest(){
		return methodOne().equals("one");
	}
	public static void main(String[] args) {

	}

}


text:
/**
 * @file   ActionSet.java
 *
 * @brief  This file contains class which provides functions to retrieve ActionSet from plain text.
 *
 */
package org.iotivity.service.tm;

import java.util.StringTokenizer;
import java.util.Vector;

import android.util.Log;

/**
 * This class provides functions to retrieve ActionSet from plain text.
 * An ActionSet is a set of descriptions of actions needed by remote
 * devices as members of a specific group. To create an ActionSet, one
 * needs to know the Delimeter serialization.
 *
 */
public class ActionSet extends Time {
    /**
     * String Tag for Logging
     */
    private static final String LOG_TAG      = "ActionSet";
    /**
     * A first segment before the first asterisk(*) in ActionSet string is an
     * actionset name
     */
    public String               actionsetName;
    /**
     * Action instance stored in listOfAction vector variable.
     */
    public Vector<Action>       listOfAction = new Vector<Action>();

    /**
     * This function generates an ActionSet String which contains ActionSet
     * name, delay in seconds, ActionSetType which can be 0(NONE), 1(SCHEDULED)
     * or 2(RECURSIVE) and a list of actions. (Example: movieTime*10
     * 1*uri=coap://10.251.44.228:49858/a/light|power=
     * OFF*uri=coap://10.251.44.228:49858). The first segment before the first
     * asterisk(*) is an ActionSet name. The second segment goes before the next
     * asterisk. In the above example, 10 is the second segment which signifies
     * time delay in seconds followed by a space and ActionSetType which
     * signifies whether an ActionSet has to be triggered Recursively(2) or
     * Scheduled manner(1) or immediately(0).
     * "uri=coap://10.251.44.228:49858/a/light|power=10" is the third segment.
     * This can be also divided into two sub segments by a vertical bar(|): URI
     * and a pair of attribute key and value.
     *
     * @return String for a specific action.
     *
     */
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();

        // Append action name
        result.append(actionsetName + "*");

        // Append delay and type
        result.append(getDelay() + " " + getType().ordinal() + "*");

        // Append list of actions
        for (int i = 0; i < listOfAction.size(); i++) {
            if (i != 0)
                result.append('*');
            result.append(listOfAction.elementAt(i).toString());
        }

        return result.toString();
    }

    /**
     * This function extracts a list of Actions from plain text and constructs
     * an ActionSet.
     *
     * @param actionsetString
     *            ActionSet in String format. (Example: movieTime*10
     *            1*uri=coap://10.251.44.228:49858/a/light|power=
     *            OFF*uri=coap://10.251.44.228:49858). The first segment before
     *            the first asterisk(*) is an ActionSet name. The second segment
     *            goes before the next asterisk. In the above example, 10 is the
     *            second segment which signifies time delay in seconds followed
     *            by a space and ActionSetType which signifies whether an
     *            ActionSet has to be triggered Recursively(2) or Scheduled
     *            manner(1) or immediately(0).
     *            "uri=coap://10.251.44.228:49858/a/light|power=10" is the third
     *            segment. This can be also divided into two sub segments by a
     *            vertical bar(|): URI and a pair of attribute key and value).
     *
     * @return ActionSet which is a set of descriptions of actions needed by
     *         remote devices as members of a specific group.
     *
     */
    public static ActionSet toActionSet(String actionsetString) {
        if (0 == actionsetString.length()) {
            return null;
        }

        ActionSet result = new ActionSet();
        StringTokenizer tokenizer = new StringTokenizer(actionsetString, "*");
        boolean actionNameFlag = false;
        while (tokenizer.hasMoreTokens()) {
            String segment = tokenizer.nextToken();
            if (false == actionNameFlag) {
                if (true == segment.contains("|")
                        || true == segment.contains("=")) {
                    Log.e(LOG_TAG, "Invalid actionset name string!");
                    return null;
                }

                result.actionsetName = segment;
                actionNameFlag = true;
            } else {
                Action action = Action.toAction(segment);
                if (null == action) {
                    Log.e(LOG_TAG, "Failed to convert string to Action class!");
                    return null;
                }

                result.listOfAction.add(action);
            }
        }

        return result;
    }
}


text:
package com.zhangtielei.demos.async.programming.introduction.servicebinding;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.zhangtielei.demos.async.programming.R;
import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil;
import com.zhangtielei.demos.async.programming.introduction.servicebinding.service.SomeService;

/**
 * 用于演示最普通的Service绑定和解绑.
 */
public class ServiceBindingDemoActivity extends AppCompatActivity implements SomeService.ServiceListener {
    /**
     * 对于Service的引用
     */
    private SomeService someService;
    /**
     * 指示本Activity是否处于running状态:执行过onResume就变为running状态。
     */
    private boolean running;

    private TextView description;
    private TextView logTextView;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            //解除Activity与Service的引用和监听关系
            //...
            if (someService != null) {
                someService.removeListener(ServiceBindingDemoActivity.this);
                someService = null;
            }
            TextLogUtil.println(logTextView, "disconnected to SomeService...");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (running) {
                //建立Activity与Service的引用和监听关系
                //...
                SomeService.ServiceBinder binder = (SomeService.ServiceBinder) service;
                someService = binder.getService();
                someService.addListener(ServiceBindingDemoActivity.this);
                TextLogUtil.println(logTextView, "bound to SomeService...");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_display);

        description = (TextView) findViewById(R.id.description);
        logTextView = (TextView) findViewById(R.id.log_display);

        description.setText(R.string.service_binding_description);

    }

    @Override
    public void onResume() {
        super.onResume();
        running = true;

        Intent intent = new Intent(this, SomeService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        TextLogUtil.println(logTextView, "Requesting bind to SomeService...");
    }

    @Override
    public void onPause() {
        super.onPause();
        running = false;

        //解除Activity与Service的引用和监听关系
        //...
        if (someService != null) {
            someService.removeListener(ServiceBindingDemoActivity.this);
            someService = null;
        }
        unbindService(serviceConnection);
        TextLogUtil.println(logTextView, "unbind to SomeService...");
    }

    @Override
    public void callback() {
        //TODO:
    }
}


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

class Landing_model extends CI_Model {
	function __construct(){
		parent::__construct();
	}

	public function count(){

		$query = $this->db->count_all_results('comentarios');

		return $query;
	}

	public function count_com($id){

		$this->db->where('proyecto =', $id);
		$this->db->from('comentarios');
		return $this->db->count_all_results();
	}

	public function projects()
	{
		$query = $this->db->query("
				SELECT p.idproyectos, p.nombre, c.color
				FROM proyectos as p
				INNER JOIN colores AS c
				ON p.color = c.idcolores
				ORDER BY idproyectos ASC
			");
		if($query->num_rows > 0)
		{
			return $query->result();
		}
	}

	public function all_projects($segment)
	{
		$query = $this->db->query("
			SELECT  p.idproyectos, p.nombre as pnombre, com.comentario, i.color, i.nombre as inombre,
			DATE_FORMAT(com.fecha,'%D %M %Y %r') as fecha, com.file_url
			FROM seguimiento.proyectos p
				INNER JOIN seguimiento.comentarios as com ON p.idproyectos = com.proyecto
				INNER JOIN seguimiento.indicadores as i ON i.idindicador = com.indicador
			ORDER BY com.fecha DESC LIMIT ".$segment.",10
		");

		if($query->num_rows > 0)
		{
			return $query->result();
		}
	}

	public function single_project_com($id, $segment)
	{

		$query = $this->db->query("
			SELECT  p.idproyectos, p.nombre as pnombre, com.comentario, i.color, i.nombre as inombre,
			DATE_FORMAT(com.fecha,'%D %M %Y %r') as fecha, com.file_url
			FROM seguimiento.proyectos p
				INNER JOIN seguimiento.comentarios as com ON p.idproyectos = com.proyecto
				INNER JOIN seguimiento.indicadores as i ON i.idindicador = com.indicador
			WHERE p.idproyectos = ".$id."
			ORDER BY com.fecha DESC LIMIT ".$segment.",10
		");
		if($query->num_rows > 0)
		{
			return $query->result();
		}

	}

	public function single_project_info($id)
	{
		$query = $this->db->query("
			SELECT  p.idproyectos, p.nombre, DATE_FORMAT(p.fecha_inicio,'%D %M %Y') as fecha_inicio,
				DATE_FORMAT(p.fecha_fin,'%D %M %Y') as fecha_fin,
				DATEDIFF(p.fecha_fin, p.fecha_inicio) AS fecha_dif,
				DATE_FORMAT(p.fecha_entrega,'%D %M %Y') as fecha_entrega, e.etapa, c.color
			FROM seguimiento.proyectos p
				INNER JOIN seguimiento.etapas AS e ON p.etapa = e.idetapas
				INNER JOIN seguimiento.colores AS c ON p.color=c.idcolores
			WHERE p.idproyectos = ".$id."
		");
		if($query->num_rows > 0)
		{
			return $query->result();
		}
	}
}


text:
namespace azule
{
	///
	///	\class SharedLibrary
	///
	///	\brief Modeled after boost's boost::dll::shared_library.
	///
	///	This class uses RAII to load and keep loaded a shared library.
	///
	///	\author Aaron Shelley
	///
	///	\date February 8, 2020
	///
	class AZULE_EXPORT SharedLibrary
	{
	public:
		SharedLibrary() = default;
		SharedLibrary(const std::filesystem::path& x);
		~SharedLibrary();

		///
		///	\brief Performing a copy will increment a reference count to this library.
		///
		///	Once all copies have been destroyed, the library will be unloaded.
		///
		SharedLibrary(const SharedLibrary& x);

		///
		///	\brief Performing a copy will increment a reference count to this library.
		///
		///	Once all copies have been destroyed, the library will be unloaded.
		///
		SharedLibrary& operator=(const SharedLibrary& x);

		///
		///	Loads a library by specified path with a specified mode.
		///
		///	Note that if some library is already loaded in this instance, load will
		///	call unload() and then load the new provided library.
		///
		///	\param x Library file name.
		///	\return true if the library was successfully loaded.
		///
		[[maybe_unused]] bool load(const std::filesystem::path& x);

		///
		///	\brief Unloads a shared library.
		///
		///	If library was loaded multiple times by different instances,
		///	the actual DLL / DSO won't be unloaded until there is at least
		///	one instance that references the DLL / DSO.
		///
		void unload();

		///
		///	\brief Check if the library is loaded.
		///
		///	\return true if the library was succesfully loaded.
		///
		bool loaded() const;

		///
		///	\brief Get a function symbol within the library for a give symbol name.
		///
		///	\param x The symbol name to look up in the library.
		///	\return std::function<void()> if the given symbol name exists.
		///
		std::function<void()> symbol(const std::string& x) const;

		///
		///	\return Returns the file path to the loaded library.
		///
		std::filesystem::path location() const;

	private:
		std::filesystem::path loc;
		void* handle{nullptr};
	};
}


text:
package aQute.bnd.service.message;

/**
 * Progress monitor. You can create a progress monitor through
 * {@link Dialogs#createProgress(String)}
 */
public interface Progress extends AutoCloseable {
	/**
	 * Indicate progress
	 *
	 * @param message The subject that is being worked upon
	 * @param percentage Progress in percentage or -1 if unknown
	 * @param timeToFinishInSecs Time to finish the work in seconds or -1 if
	 *            unknown
	 */
	void progress(String message, int percentage, int timeToFinishInSecs);
}


text:
define(["lib-build/tpl!./MapConfigOverlay",
		"lib-build/css!./MapConfigOverlay",
		"dojo/i18n!commonResources/nls/webmap.js?v=" + app.version,
		"dojo/i18n!commonResources/nls/media.js?v=" + app.version,
		"lib-app/arcgis-dijit-table-of-contents/js/TableOfContents",
		"lib-build/css!lib-app/arcgis-dijit-table-of-contents/css/TableOfContents",
		"esri/geometry/Extent",
		"dojo/Deferred",
		"dojo/on",
		"dojo/topic"/*,
		"storymaps/common/utils/CommonHelper"*/],
	function (
		viewTpl,
		viewCss,
		i18n,
		i18n2,
		TableOfContents,
		tableOfContentsCss,
		Extent,
		Deferred,
		on,
		topic/*,
		CommonHelper*/
	){
		var container = $('#mainStagePanel'),
			_viewDeferred = null,
			_media = null,
			// Map extent
			_originalMapExtent = null,
			_extentAtOpening = null,
			_sectionDefineExtent = null,
			_extentDefined = null,
			_extentChangeHandle = null,
			_ignoreNextExtentChange = null,
			_geocoder = null,
			// Map layers
			_tableOfContents = null,
			_sectionDefineLayer = null,
			_layersChanged = null,
			_layersInitial = null,
			_layersOpening = null,
			// Popup
			_popupMapHandlers = null;

		container.append(viewTpl({
			btnReset: i18n.commonWebmap.configure.btnReset,
			btnCancel: i18n.commonWebmap.configure.btnCancel,
			tocTitle: i18n.commonWebmap.configure.tocTitle,
			tocExplain: i18n.commonWebmap.configure.tocExplain + " " + i18n.commonWebmap.configure.hintNavigation,
			tocSave: i18n.commonWebmap.configure.tocSave,
			tocHint: i18n.commonWebmap.configure.hintNavigation,
			extentTitle: i18n.commonWebmap.configure.extentTitle,
			extentExplain: i18n.commonWebmap.configure.extentExplain,
			extentSave: i18n.commonWebmap.configure.extentSave,
			popupTitle: i18n.commonWebmap.configure.popupTitle,
			popupExplain: i18n.commonWebmap.configure.popupExplain + " " + i18n.commonWebmap.configure.hintNavigation,
			popupSave: i18n.commonWebmap.configure.popupSave
		}));

		function present(type, media)
		{
			_viewDeferred = new Deferred();

			_media = media;

			// Init Map Extent
			_extentDefined = false;
			_ignoreNextExtentChange = false;
			_originalMapExtent = app.map._params.extent;
			_extentAtOpening = app.map.extent; //lang.clone(app.map.extent);
			_sectionDefineExtent = media ? !! media.extent : false;
			_extentChangeHandle = on(app.map, "extent-change", onMapExtentChange);
			// If user click the home button that's a reset and there is no way to know that through the API
			//  (the resulting extent is different from the webmap extent because of lods)
			// TODO could use dojo/aspect
			// - aspect.before(app.map, "setExtent", function(extent){}); => extent is the asked extent
			topic.subscribe("CORE_UPDATE_EXTENT", onResetInitialExtent);

			$(".mainMediaContainer.active .mapControls").addClass("hidden");
			//container.find(".toc").addClass("collapsed");

			// Init Map TOC
			_layersChanged = false;
			_layersInitial = app.mapItem ? app.mapItem.itemData.operationalLayers : [];
			_sectionDefineLayer = media ? !! media.layers : false;
			_layersOpening = _layersInitial ? getLayersVisibilityOverride() : [];
			presentTableOfContents();

			if ( _sectionDefineExtent )
				_extentDefined = JSON.stringify(app.lastExtentSet) != JSON.stringify(media.extent);
			else
				_extentDefined = JSON.stringify(app.lastExtentSet) != JSON.stringify(app.map.mapJournalInitExtent) && JSON.stringify(app.lastExtentSet) != JSON.stringify(_originalMapExtent);

			console.log(
				JSON.stringify(app.lastExtentSet) != JSON.stringify(app.map.mapJournalInitExtent),
				JSON.stringify(app.lastExtentSet) != JSON.stringify(_originalMapExtent),
				app.lastExtentSet,
				app.map.mapJournalInitExtent,
				_originalMapExtent,
				_sectionDefineExtent,
				_sectionDefineLayer
			);

			// Init Bottom panel
			//toggleReset(0, _extentDefined, _sectionDefineExtent && JSON.stringify(app.lastExtentSet) != JSON.stringify(media.webmap.extent), ! _sectionDefineExtent || JSON.stringify(app.lastExtentSet) == JSON.stringify(media.webmap.extent));
			//toggleReset(1, false, ! getLayersVisibilityOverride().length, true);

			/*
			container.find(".resetSection").css("visibility", nbSection > 0 ? "visible" : "hidden");
			container.find(".resetWebmap").css("float", nbSection > 0 ? "" : "right");
			container.find(".resetSection").html(mode == "add" ? "Reset to
opening value" : "Reset to
section value");
			*/

			openUI(type);

			return _viewDeferred;
		}

		function close()
		{
			$(".mainMediaContainer.active .mapControls").removeClass("hidden");

			closeUI();
			_extentChangeHandle.remove();

			var layers = getLayersVisibilityOverride();

			_viewDeferred.resolve({
				extent: _extentDefined ? app.map.extent  : null,
				layers: layers && layers.length ? layers : null,
				popup: getSelectedFeatureInfo()
			});
		}

		/*
		 * Events
		 */

		function initEvents()
		{
			container.find(".position .save").click(close);
			container.find(".position .reset").click(onClickResetExtentWebmap);
			container.find(".position .cancel").click(cancelExtent);

			container.find(".toc .save").click(close);
			container.find(".toc .reset").click(onClickResetLayerWebmap);
			container.find(".toc .cancel").click(cancelLayers);

			/*
			container.find(".toc .expandButton").click(function(){
				container.find(".toc").toggleClass("collapsed");
			});
			*/

			container.find(".popup .save").click(close);
			container.find(".popup .reset").click(cancelPopup);
			container.find(".popup .cancel").click(cancelPopup);
		}

		/*
		 * Map location
		 */

		function onClickResetExtentWebmap()
		{
			app.map.setExtent(_originalMapExtent).then(function(){
				_extentDefined = false;
				//toggleReset(0, _extentDefined, true, ! _sectionDefineExtent);
			});
		}

		/*
		function onClickResetExtentSection()
		{
			app.map.setExtent(new Extent(_media.webmap.extent)).then(function(){
				_extentDefined = true;
				toggleReset(0, false, false, true);
			});
		}
		*/

		function cancelExtent()
		{
			app.ignoreNextEvent = true;
			_ignoreNextExtentChange = true;
			app.map.setExtent(_extentAtOpening).then(function(){
				_extentDefined = _sectionDefineExtent;
				close();
			});
		}

		function onResetInitialExtent()
		{
			_ignoreNextExtentChange = true;
			_extentDefined = false;
			//toggleReset(0, _extentDefined, true);
		}

		function onMapExtentChange()
		{
			if ( ! _ignoreNextExtentChange ) {
				_extentDefined = true;
				//toggleReset(0, _extentDefined, false, ! _sectionDefineExtent);
			}
			else
				_ignoreNextExtentChange = false;
		}

		function initGeocoder()
		{
			if ( _geocoder )
				_geocoder.destroy();

			// If map already has a geocoder through viewer config
			if ( $(".mainMediaContainer.active .mapContainer").hasClass("has-geocoder") ) {
				return;
			}

			// Map Series is not ready for the following because there isn't proper rules for the placement of the button
			/*
			$(".mainMediaContainer.active .geocoder")
				.html('

')
				.show();

			try {
				CommonHelper.createGeocoder({
					map: app.map,
					domNode: $(".mainMediaContainer.active .simpleGeocoder")[0],
					enableButtonMode: false,
					placeHolder: i18n2.commonMedia.editorActionGeocode.lblTitle
				}).then(function(geocoder) {
					_geocoder = geocoder;
				});
			} catch(e){
				console.error(e);
			}
			*/
		}

		/*
		 * Map layer
		 */

		function onClickResetLayerWebmap()
		{
			$.each(_layersInitial, function(i, layer){
				if ( layer.layerObject )
					layer.layerObject.setVisibility(layer.visibility);
				else if ( layer.featureCollection ){
					$.each(layer.featureCollection.layers, function(i, l){
						l.layerObject.setVisibility(layer.visibility);
					});
				}
			});

			//toggleReset(1, false, true, ! _sectionDefineLayer || getLayersVisibilityOverride().toString() == _layersOpening.toString());
		}

		/*
		function onClickResetLayerSection()
		{
			onClickResetLayerWebmap();

			$.each(_layersOpening, function(i, l){
				var layerId = l.id,
					layer = $.grep(_layersInitial, function(ll) {
						var lll = ll.featureCollection ? ll.featureCollection.layers[0].id : ll.id;
						return lll == layerId;
					})[0];

				if ( ! layer )
					return;

				if ( layer.layerObject )
					layer.layerObject.setVisibility(_layersOpening.visibility);
				else if ( layer.featureCollection ){
					$.each(layer.featureCollection.layers, function(i, l){
						l.layerObject.setVisibility(_layersOpening.visibility);
					});
				}
			});

			toggleReset(1, false, ! getLayersVisibilityOverride().length, true);
		}
		*/

		function cancelLayers()
		{
			$.each(_layersInitial, function(i, layer){
				var layerObject = layer.layerObject || (layer.featureCollection ? layer.featureCollection.layers[0].layerObject : null),
					overrideAtOpening = $(_layersOpening).filter(function(i, l){ return l.id == layerObject.id; }),
					newVisibility = overrideAtOpening.length ? overrideAtOpening[0].visibility : layer.visibility;

				if ( layer.layerObject )
					layerObject.setVisibility(newVisibility);
				else {
					$.each(layer.featureCollection.layers, function(i, l){
						l.layerObject.setVisibility(newVisibility);
					});
				}
			});
			close();
		}

		function onLayerToggle()
		{
			_layersChanged = getLayersVisibilityOverride().length > 0;
			//toggleReset(1, _layersChanged, ! _layersChanged, ! _media.webmap || ! _media.webmap.layers || ! _media.webmap.layers.length ? true : getLayersVisibilityOverride().toString() == _layersOpening.toString());
		}

		function getLayersVisibilityOverride()
		{
			var visibilityOverrides = [];

			$.each(_layersInitial, function(i, layer){
				var layerObject = layer.layerObject || (layer.featureCollection ? layer.featureCollection.layers[0].layerObject : null);
				if( layerObject && layer.visibility != layerObject.visible )
					visibilityOverrides.push({
						id: layerObject.id,
						visibility: layerObject.visible
					});
			});

			return visibilityOverrides;
		}

		function presentTableOfContents()
		{
			if ( _tableOfContents )
				_tableOfContents.destroy();

			container.find(".tocContainer").html('

');

			_tableOfContents = new TableOfContents({
				map: app.map,
				layers: _layersInitial
			}, container.find(".TableOfContents")[0]);

			if ( ! _layersInitial || ! _layersInitial.length ) {
				container.find(".TableOfContents").html(
					'
'
					+ i18n.commonWebmap.configure.tocNoData
					+ '
'
				);
			}

			on(_tableOfContents, 'toggle', onLayerToggle);
			on(_tableOfContents, 'load', function(){
				container.find(".toc-checkbox").addClass('glyphicon glyphicon-unchecked');
			});

			_tableOfContents.startup();
		}

		/*
		 * Popup
		 */

		function onPopupShow()
		{
			// Should use that to change the status of the save button
		}

		function onPopupHide()
		{
			//
		}

		function cancelPopup()
		{
			/*
			if ( _media && _media.popup ) {

			}
			*/
			app.map.infoWindow.hide();
			app.map.infoWindow.clearFeatures();

			close();
		}

		function getSelectedFeatureInfo()
		{
			var feature = app.map.infoWindow.getSelectedFeature();

			if ( ! feature )
				return null;

			/*
			 * The popup's feature is saved through an attribute and it's value
			 * Try to find an object id through type or field name
			 * Default to the first Integer field
			 */

			// TODO should have an error message if not found

			var layer = feature.getLayer(),
				fields = layer.fields;

			if ( ! fields ) {
				return null;
			}

			var objectIdFields = $.grep(fields, function(field){
				return field.type == "esriFieldTypeOID";
			});

			if ( layer && fields && ! objectIdFields.length ) {
				objectIdFields = $.grep(fields, function(field){
					return field.name == "OBJECTID" || field.name == "FID";
				});

				if ( ! objectIdFields.length ) {
					objectIdFields = $.grep(fields, function(field){
						return field.type == "esriFieldTypeInteger";
					});
				}
			}

			if ( objectIdFields.length ) {
				var fieldName = objectIdFields[0].name;
				return {
					layerId: layer.id,
					fieldName: fieldName,
					fieldValue: feature.attributes[fieldName],
					anchorPoint: app.map.infoWindow.location.toJson()
				};
			}

			return null;
		}

		/*
		 * Common
		 */

		function openUI(type)
		{
			$("body").addClass("has-builder-mask");
			$(".panelEditBtn").fadeOut();

			if( type == "LOCATION"){
				container.find(".mapConfigOverlay.position").show();
				initGeocoder();
			}
			else if( type == "CONTENT")
				container.find(".mapConfigOverlay.toc").show();
			else if( type == "POPUP"){
				container.find(".mapConfigOverlay.popup").show();
				_popupMapHandlers = [
					app.map.infoWindow.on("show", onPopupShow),
					app.map.infoWindow.on("hide", onPopupHide)
				];
			}

			if ( type != "LOCATION" ) {
				app.map.disableMapNavigation();
				$(app.map.__container).parent().find(".esriSimpleSliderTL").hide();
			}
		}

		function closeUI()
		{
			$("body").removeClass("has-builder-mask");
			$(".panelEditBtn").fadeIn();

			container.find(".mapConfigOverlay").hide();
			app.map.enableMapNavigation();
			$(app.map.__container).parent().find(".esriSimpleSliderTL").show();

			$(".mainMediaContainer.active .geocoder").hide();

			if ( _popupMapHandlers ) {
				_popupMapHandlers[0].remove();
				_popupMapHandlers[1].remove();
				_popupMapHandlers = null;
			}
		}

		initEvents();

		return {
			present: present
		};
	}
);


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
        <meta name="generator" content="joDoc">
        <link href="//s3.amazonaws.com/appgyver.assets/global-assets/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">

        <title>AppGyver Steroids API Documentation</title>

        <link type="text/css" rel="stylesheet" href="//fast.fonts.net/cssapi/aa8407d2-1212-415a-8e54-031ff8ee71fe.css">
        <link type="text/css" rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="index.css">
        <link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
        <link rel="stylesheet" type="text/css" href="steroids.css">
        <link rel="stylesheet" type="text/css" href="service_menu.css">
        <link rel="stylesheet" type="text/css" href="prettify/prettify.css">

AppGyver Steroids API Documentation

AppGyver Steroids API Docs

                  <select><optgroup label="English" value="en">
<option value="stable">stable</option>
<option value="edge">edge</option>
<option value="3.5.8">3.5.8</option>
<option value="3.5.7">3.5.7</option>
<option value="3.5.5">3.5.5</option>
<option value="3.5.3">3.5.3</option>
<option value="3.5.12">3.5.12</option>
<option selected value="3.5.1">3.5.1</option>
<option value="3.5.0">3.5.0</option>
<option value="3.1.9">3.1.9</option>
</optgroup></select>

steroids.screen.setAllowedRotations

              <select><option value="steroids.screen.setAllowedRotations">steroids.screen.setAllowedRotations</option>
<option value="steroids.screen.setAllowedRotations_implementation_notes">      - Implementation notes</option>
<option value="steroids.screen.setAllowedRotations_shorthand">      - Shorthand</option>
<option value="steroids.screen.setAllowedRotations_verbose">      - Verbose</option>
<option value="steroids.screen.setAllowedRotations_parameters">      - Parameters</option></select>

Steroids 3.5.1 API Reference

Steroids Analytics and Log

Steroids App and Device

Steroids Config

Steroids Events

Steroids File System

Steroids Media

Steroids Views

Steroids UI Components

Cordova 3.5.0 API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

FileTransfer

Geolocation

Globalization

InAppBrowser

Media

Notification

Guides

Keyword Index

steroids.screen.setAllowedRotations

Determine which of the four possible screen rotations are enabled on your device.

Implementation notes

By default all rotations are allowed, with the exception of custom builds where the build settings have been used to lock the app into a certain rotation scheme.

Modals are not affected by setting allowed rotations in other views and conversely setting allowed rotations in a modal does not affect the rest of the app.

Shorthand

steroids.screen.setAllowedRotations(["landscapeLeft"]);

Verbose

steroids.screen.setAllowedRotations(options, callBacks);

Parameters

Shorthand

orientations [Array]: possible values ("portrait", "portraitUpsideDown", "landscapeLeft", "landscapeRight")

Verbose

The verbose call accepts two objects: options and callBacks, which have the following properties:

options

allowedRotations: Array of accepted rotations.

callBacks

onSuccess: called if updating allowedRotations is succesful.

onFailure: called if updating allowedRotatins fails.


text:
require 'dp'
require 'optim'
require 'nngraph'

model_dir = arg[1]

print("rels classifier")
xp = torch.load(model_dir .. "/actions.dat")
train_loss = xp:optimizer():report()["loss"]
train_acc = xp:optimizer():report()["feedback"]["confusion"]["accuracy"]
valid_acc = xp:validator():report()["feedback"]["confusion"]["accuracy"]
print("Training loss: " .. train_loss)
print("Training accuracy: " .. train_acc)
print("Validation accuracy: " .. valid_acc)
print("Confusion matrix:")
print(xp:validator():report()["feedback"]["confusion"]["matrix"])
perclass = xp:validator():report()["feedback"]["confusion"]["per_class"]["accuracy"]
print("Accuracy SHIFT: " .. perclass[1])
print("Accuracy REDUCE: " .. perclass[2])
print("Accuracy LARC1: " .. perclass[3])
print("Accuracy RARC1: " .. perclass[4])
print("")

print("labels classifier")
xp = torch.load(model_dir .. "/labels.dat")
train_loss = xp:optimizer():report()["loss"]
train_acc = xp:optimizer():report()["feedback"]["confusion"]["accuracy"]
valid_acc = xp:validator():report()["feedback"]["confusion"]["accuracy"]
print("Training loss: " .. train_loss)
print("Training accuracy: " .. train_acc)
print("Validation accuracy: " .. valid_acc)
print("")

print("reentr classifier")
xp = torch.load(model_dir .. "/reentrancies.dat")
train_loss = xp:optimizer():report()["loss"]
train_acc = xp:optimizer():report()["feedback"]["confusion"]["accuracy"]
valid_acc = xp:validator():report()["feedback"]["confusion"]["accuracy"]
print("Training loss: " .. train_loss)
print("Training accuracy: " .. train_acc)
print("Validation accuracy: " .. valid_acc)
print("Confusion matrix:")
print(xp:validator():report()["feedback"]["confusion"]["matrix"])
perclass = xp:validator():report()["feedback"]["confusion"]["per_class"]["accuracy"]
print("Accuracy REENTR: " .. perclass[1])
print("Accuracy NONREENTR: " .. perclass[2])
print("")


text:
using Shouldly.Tests.TestHelpers;
using System;

namespace Shouldly.Tests.ShouldNotContain
{
    public class PredicateObjectScenario : ShouldlyShouldTestScenario
    {
        protected override void ShouldThrowAWobbly()
        {
            var a = new Object();
            var b = new Object();
            var c = new Object();
            new[] { a, b, c }.ShouldNotContain(o => o.GetType().FullName.Equals("System.Object"));
        }

        protected override string ChuckedAWobblyErrorMessage
        {
            get { return @"
    new[] { a, b, c }
        should not contain an element satisfying the condition
    o.GetType().FullName.Equals(""System.Object"")
        but does"; }

        }

        protected override void ShouldPass()
        {
            var a = new Object();
            var b = new Object();
            var c = new Object();
            new[] { a, b, c }.ShouldNotContain(o => o.GetType().FullName.Equals(""));

        }
    }
}


text:
<?php

namespace Zend\Feed\Writer\Extension\ITunes\Renderer;

use DOMDocument;
use DOMElement;
use Zend\Feed\Writer\Extension;

/**
*/
class Entry extends Extension\AbstractRenderer
{
    /**
     * Set to TRUE if a rendering method actually renders something. This
     * is used to prevent premature appending of a XML namespace declaration
     * until an element which requires it is actually appended.
     *
     * @var bool
     */
    protected $called = false;

    /**
     * Render entry
     *
     * @return void
     */
    public function render()
    {
        $this->_setAuthors($this->dom, $this->base);
        $this->_setBlock($this->dom, $this->base);
        $this->_setDuration($this->dom, $this->base);
        $this->_setExplicit($this->dom, $this->base);
        $this->_setKeywords($this->dom, $this->base);
        $this->_setSubtitle($this->dom, $this->base);
        $this->_setSummary($this->dom, $this->base);
        if ($this->called) {
            $this->_appendNamespaces();
        }
    }

    /**
     * Append namespaces to entry root
     *
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _appendNamespaces()
    {
        // @codingStandardsIgnoreEnd
        $this->getRootElement()->setAttribute(
            'xmlns:itunes',
            'http://www.itunes.com/dtds/podcast-1.0.dtd'
        );
    }

    /**
     * Set entry authors
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setAuthors(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $authors = $this->getDataContainer()->getItunesAuthors();
        if (! $authors || empty($authors)) {
            return;
        }
        foreach ($authors as $author) {
            $el = $dom->createElement('itunes:author');
            $text = $dom->createTextNode($author);
            $el->appendChild($text);
            $root->appendChild($el);
            $this->called = true;
        }
    }

    /**
     * Set itunes block
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setBlock(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $block = $this->getDataContainer()->getItunesBlock();
        if ($block === null) {
            return;
        }
        $el = $dom->createElement('itunes:block');
        $text = $dom->createTextNode($block);
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }

    /**
     * Set entry duration
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setDuration(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $duration = $this->getDataContainer()->getItunesDuration();
        if (! $duration) {
            return;
        }
        $el = $dom->createElement('itunes:duration');
        $text = $dom->createTextNode($duration);
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }

    /**
     * Set explicit flag
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setExplicit(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $explicit = $this->getDataContainer()->getItunesExplicit();
        if ($explicit === null) {
            return;
        }
        $el = $dom->createElement('itunes:explicit');
        $text = $dom->createTextNode($explicit);
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }

    /**
     * Set entry keywords
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setKeywords(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $keywords = $this->getDataContainer()->getItunesKeywords();
        if (! $keywords || empty($keywords)) {
            return;
        }
        $el = $dom->createElement('itunes:keywords');
        $text = $dom->createTextNode(implode(',', $keywords));
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }

    /**
     * Set entry subtitle
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setSubtitle(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $subtitle = $this->getDataContainer()->getItunesSubtitle();
        if (! $subtitle) {
            return;
        }
        $el = $dom->createElement('itunes:subtitle');
        $text = $dom->createTextNode($subtitle);
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }

    /**
     * Set entry summary
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    // @codingStandardsIgnoreStart
    protected function _setSummary(DOMDocument $dom, DOMElement $root)
    {
        // @codingStandardsIgnoreEnd
        $summary = $this->getDataContainer()->getItunesSummary();
        if (! $summary) {
            return;
        }
        $el = $dom->createElement('itunes:summary');
        $text = $dom->createTextNode($summary);
        $el->appendChild($text);
        $root->appendChild($el);
        $this->called = true;
    }
}


text:
{{'my-students.title' | translate}}

{{'my-students.table.fullName' | translate}}

{{'my-students.table.email' | translate}}

{{'my-students.table.complete' | translate}}

{{'my-students.table.points' | translate}}

{{'my-students.table.time' | translate}}

{{student.fullName}}

{{student.email}}

{{student.complete}}

{{student.points}}

{{student.time}}

          <button class="btn-my-all btn-my-size-main" (click)="export()"> {{'my-students.export' | translate}}</button>


text:
package com.sri.ai.util.livesets.core.lazy.memoryless;

import static com.sri.ai.util.livesets.core.lazy.memoryless.ExtensionalLiveSet.liveSet;

import java.util.List;

import com.google.common.base.Predicate;
import com.sri.ai.util.livesets.api.LiveSet;

public class RedirectingLiveSet<T> implements LiveSet<T> {

	private LiveSet<T> liveSet;

	public RedirectingLiveSet(LiveSet<T> liveSet) {
		this.liveSet = liveSet;
	}

	public RedirectingLiveSet(List<T> elements) {
		this(liveSet(elements));
	}

	public void redirectTo(LiveSet<T> liveSet) {
		this.liveSet = liveSet;
	}

	public boolean contains(T element) {
		boolean result = liveSet.contains(element);
		return result;
	}

	public static <T> RedirectingLiveSet<T> redirectingTo(LiveSet<T> liveSet) {
		return new RedirectingLiveSet<T>(liveSet);
	}

	@Override
	public boolean thereIsAnElementSatisfying(Predicate<T> predicate) {
		boolean result = liveSet.thereIsAnElementSatisfying(predicate);
		return result;
	}
}


text:
require 'erb'

module Ticard
  class Serializer
    def initialize(card)
      @card = card
    end

    def serialize
      erb_path = File.join(File.dirname(File.expand_path(__FILE__)), 'card.md.erb')
      template = ERB.new(File.read(erb_path))
      template.result(@card.instance_eval { binding })
    end
  end
end


text:
What linguistic features are unique to discussions of nonmedical substance use?

### Background

 Social media (Twitter, Facebook, websites like CrazyMeds) can provide us with information on how the general population uses substances for nonmedical purposes. Social media may, in fact, provide a more accurate picture of usage than data from surveys or emergency rooms. Surveys ask a small sample of the population to remember (sometimes) illicit activities and report them to a federal authority under the promise of anonymynity. Emergency rooms only see the part of the story when substance use goes wrong.

### Methodology

  _overdosed 0.1_ uses latent semantic analysis to identify the words or phrases that distinguish tweets discussing the use of substances from other substances. There are two phases:

   Phase 1

1. **Sample** two streams from Twitter gardenhose (1% sampler).

Stream 1: Unfiltered.

Stream 2: Filtered for keywords describing substance of interest.

1. **Develop** the classifier.

 Sensitive (rule-in) component: Identify words present in both streams.

 Specific (rule-out) component: Identify words present in filtered stream but not unfiltered stream. (Filtered stream - unfiltered stream)

1. **Analyze** the classifier.

 Identify groups of semantically related words in the rule-in component.

 Same for rule-out component. (_i.e._ Taxonomize)

1. **Test** the classifier.

 Curate new samples from the two streams

 Adjust the words needed to be present or absent in a tweet to achieve an acceptable sensitivity and specificity

Phase 2

1. **Sample** the unfiltered Twitter gardenhose (1% sampler)

 Cannot calculate valid sample statistics if you combine streams

2. **Partition** the unfiltered Twitter stream into

 All tweets discussing use of the substance

 All other tweets

3. **Calculate** the relative abundance of each component of the metadata, _e.g._

 Are the geographic distributions the same?

 What latent attributes differ?

### Quickstart

     git clone https://github.com/mac389/overdosed.git
     cd overdosed
     sh setup.sh

### Dependencies
1. [Tweepy (3.3.0)](https://github.com/tweepy/tweepy)
1. [Gensim (0.10.3)](https://github.com/piskvorky/gensim.git)
1. [Seaborn (0.6dev, for visualization, also requires pandas)](http://stanford.edu/~mwaskom/software/seaborn/installing.html)
1. NumPy (1.9.1)
1. Matplotlib
1. SciPy


text:
import { Component, OnInit } from '@angular/core';
import {
    FormBuilder, FormGroup, Validators
} from '@angular/forms';
import { Response } from '@angular/http';

import { CourseEntry, Institution } from '../common/api-models';
import { PLACEHOLDER_COURSE } from '../core/constants';
import { EquivalencyService } from '../core/equivalency.service';
import { PatternService } from '../core/pattern.service';

import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'simple-preview',
    templateUrl: 'simple-preview.pug',
    styleUrls: [ 'simple-preview.scss' ],
    providers: [ EquivalencyService ]
})
export class SimplePreviewComponent implements OnInit {

    public form: FormGroup;
    public entry: CourseEntry;

    public institutions: Institution[];
    public placeholderCourse: string;

    public constructor(
        private equivService: EquivalencyService,
        private pattern: PatternService,
        private fb: FormBuilder,
    ) {
        this.placeholderCourse = PLACEHOLDER_COURSE;

        this.form = this.fb.group({
            course: ['', [Validators.required, pattern.get('course').validator()]],
            institution: ['', [Validators.required]]
        });

        this.form.valueChanges
            .filter(() => this.form.valid)
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap(async (raw: InputForm) => {
                const course = pattern.get('course').parse(raw.course);
                try {
                    const inst = raw.institution.trim();

                    return await this.equivService.entry(course, inst);
                } catch (ex) {
                    if (ex instanceof Response) {
                        return null;
                    }

                    throw ex;
                }
            })
            .subscribe((val: CourseEntry) => {
                this.entry = val;
            });
    }

    public ngOnInit(): void {
        this.equivService.institutions().then((institutions: Institution[]) => {
            this.institutions = institutions;
        });
    }
}

interface InputForm {
    course: string;
    institution: string;
}


text:
package org.basex.util;

import java.io.*;

/**
 * This is an interface for classes with main methods and command-line arguments.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
public abstract class Main {
  /** Command-line arguments. */
  private final String[] args;

  /**
   * Constructor.
   * @param args command-line arguments
   */
  protected Main(final String[] args) {
    this.args = args;
  }

  /**
   * Returns the command-line arguments.
   * @return arguments
   */
  String[] args() {
    return args;
  }

  /**
   * Returns a header string for command-line information.
   * @return header string
   */
  public abstract String header();

  /**
   * Returns a usage string for command-line information.
   * @return usage string
   */
  public abstract String usage();

  /**
   * Parses the command-line arguments, specified by the user.
   * @throws IOException I/O exception
   */
  protected abstract void parseArgs() throws IOException;
}


text:
<BroadcastMonitor>
  <updated>2015-08-07T18:40:12</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T18:40:12</startTime>
    <itemId>1000080589:0</itemId>
    <titleId>216050552</titleId>
    <itemCode>MS1422</itemCode>
    <itemReference></itemReference>
    <titleName>Teach Me Tonight (Hootenanny)</titleName>
    <artistName>Amy Winehouse</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>190</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T18:43:17</startTime>
    <itemId>1000080589:1243257</itemId>
    <titleId>216044095</titleId>
    <itemCode>MS682</itemCode>
    <itemReference></itemReference>
    <titleName>Cornbread, Fish & Collard Greens</titleName>
    <artistName>Anthony Hamilton</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>273</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
'use strict'

var Util = require('util')
var Assert = require('assert')

var _ = require('lodash')

var Common = require('./common')

module.exports = {
  closed: inward_closed,
  act_cache: inward_act_cache,
  act_default: inward_act_default,
  act_not_found: inward_act_not_found,
  validate_msg: inward_validate_msg,
  warnings: inward_warnings,
  msg_meta: inward_msg_meta,
  limit_msg: inward_limit_msg,
  msg_modify: inward_msg_modify,
  act_stats: inward_act_stats,
  prepare_delegate: inward_prepare_delegate,
  announce: inward_announce
}

function inward_limit_msg(ctxt, data) {
  var so = ctxt.options
  var meta = data.meta

  if (meta.parents && so.limits.maxparents < meta.parents.length) {
    return {
      kind: 'error',
      code: 'maxparents',
      info: {
        maxparents: so.limits.maxparents,
        numparents: meta.parents.length,
        parents: _.map(meta.parents, p => p[0]),
        args: Util.inspect(Common.clean(data.msg)).replace(/\n/g, '')
      }
    }
  }
}

function inward_announce(ctxt, data) {
  if (!ctxt.actdef) return

  if (_.isFunction(ctxt.seneca.on_act_in)) {
    ctxt.seneca.on_act_in(ctxt.actdef, data.msg, data.meta)
  }

  ctxt.seneca.emit('act-in', data.msg, null, data.meta)
}

function inward_closed(ctxt, data) {
  if (ctxt.seneca.closed && !data.meta.closing) {
    return {
      kind: 'error',
      code: 'closed',
      info: {
        args: Util.inspect(Common.clean(data.msg)).replace(/\n/g, '')
      }
    }
  }
}

function inward_act_stats(ctxt) {
  if (!ctxt.actdef) {
    return
  }

  var private$ = ctxt.seneca.private$
  ++private$.stats.act.calls

  var pattern = ctxt.actdef.pattern

  var actstats = (private$.stats.actmap[pattern] = private$.stats.actmap[
    pattern
  ] || {})

  ++actstats.calls
}

function inward_act_default(ctxt, data) {
  var so = ctxt.options
  var msg = data.msg
  var meta = data.meta

  // TODO: existence of pattern action needs own indicator flag
  if (!ctxt.actdef) {
    var default$ = meta.dflt || (!so.strict.find ? {} : meta.dflt)

    if (_.isPlainObject(default$) || _.isArray(default$)) {
      return {
        kind: 'result',
        result: default$,
        log: {
          level: 'debug',
          data: {
            kind: 'act',
            case: 'DEFAULT'
          }
        }
      }
    } else if (null != default$) {
      return {
        kind: 'error',
        code: 'act_default_bad',
        info: {
          args: Util.inspect(Common.clean(msg)).replace(/\n/g, ''),
          xdefault: Util.inspect(default$)
        }
      }
    }
  }
}

function inward_act_not_found(ctxt, data) {
  var so = ctxt.options
  var msg = data.msg

  if (!ctxt.actdef) {
    return {
      kind: 'error',
      code: 'act_not_found',
      info: { args: Util.inspect(Common.clean(msg)).replace(/\n/g, '') },
      log: {
        level: so.trace.unknown ? 'warn' : 'debug',
        data: {
          kind: 'act',
          case: 'UNKNOWN'
        }
      }
    }
  }
}

function inward_validate_msg(ctxt, data) {
  var so = ctxt.options
  var msg = data.msg

  Assert(ctxt.actdef)

  if (!_.isFunction(ctxt.actdef.validate)) {
    return
  }

  var err = null

  // FIX: this is assumed to be synchronous
  // seneca-parambulator and seneca-joi need to be updated
  ctxt.actdef.validate(msg, function(verr) {
    err = verr
  })

  if (err) {
    return {
      kind: 'error',
      code: so.legacy.error_codes ? 'act_invalid_args' : 'act_invalid_msg',
      info: {
        pattern: ctxt.actdef.pattern,
        message: err.message,
        msg: Common.clean(msg),
        error: err
      },
      log: {
        level: so.trace.invalid ? 'warn' : null,
        data: {
          kind: 'act',
          case: 'INVALID'
        }
      }
    }
  }
}

// Check if actid has already been seen, and if action cache is active,
// then provide cached result, if any. Return true in this case.
function inward_act_cache(ctxt, data) {
  var so = ctxt.options
  var meta = data.meta

  var actid = meta.id
  var private$ = ctxt.seneca.private$

  if (actid != null && so.history.active) {
    var actdetails = private$.history.get(actid)

    if (actdetails) {
      private$.stats.act.cache++

      var latest = actdetails.result[actdetails.result.length - 1] || {}

      var out = {
        kind: latest.err ? 'error' : 'result',
        result: latest.res || null,
        error: latest.err || null,
        log: {
          level: 'debug',
          data: {
            kind: 'act',
            case: 'CACHE',
            cachetime: latest.when
          }
        }
      }

      ctxt.cached$ = true

      return out
    }
  }
}

function inward_warnings(ctxt, data) {
  var so = ctxt.options
  var msg = data.msg

  Assert(ctxt.actdef)

  if (so.debug.deprecation && ctxt.actdef.deprecate) {
    ctxt.seneca.log.warn({
      kind: 'act',
      case: 'DEPRECATED',
      msg: msg,
      pattern: ctxt.actdef.pattern,
      notice: ctxt.actdef.deprecate,
      callpoint: ctxt.callpoint
    })
  }
}

function inward_msg_meta(ctxt, data) {
  var meta = data.meta

  meta.pattern = ctxt.actdef.pattern
  meta.action = ctxt.actdef.id
  meta.plugin = _.extend(meta.plugin, ctxt.actdef.plugin)
  meta.start = null == meta.start ? ctxt.start : meta.start
  meta.parents = meta.parents || []
  meta.trace = meta.trace || []

  var parent = ctxt.seneca.private$.act && ctxt.seneca.private$.act.parent

  if (parent) {
    meta.parents = meta.parents.concat(parent.parents || [])
    meta.parents.unshift(Common.make_trace_desc(parent))
  }
}

// TODO: remove
function inward_msg_modify() {
  //Common.setmeta(data.msg, data.meta)
}

function inward_prepare_delegate(ctxt, data) {
  Assert(data.reply)

  ctxt.seneca.fixedargs.tx$ = data.meta.tx

  data.reply = data.reply.bind(ctxt.seneca)
  data.reply.seneca = ctxt.seneca

  var reply = data.reply

  // DEPRECATE
  ctxt.seneca.good = function good(out) {
    reply(null, out)
  }

  // DEPRECATE
  ctxt.seneca.bad = function bad(err) {
    reply(err)
  }

  ctxt.seneca.reply = function reply(err, out) {
    reply(err, out)
  }
}


text:
require 'test_helper'
require 'pp'

class TestNodes < Minitest::Test
  def setup
    VCR.insert_cassette 'nodes', record: :new_episodes
    @drain = ::Elasticsearch::Drain.new(
      'localhost:9250',
      'esuilogs-razor-d0prod-r01-v000',
      'us-west-2'
    )
    @nodes = ::Elasticsearch::Drain::Nodes.new(@drain.client, @drain.asg)
  end

  def teardown
    VCR.eject_cassette
  end

  def test_has_nodes
    assert_respond_to @nodes, :client
  end

  def test_nodes_is_array
    assert_respond_to @nodes.nodes, :each
  end

  def test_has_info
    assert_respond_to @nodes, :info
  end

  def test_info_has_value
    assert_respond_to @nodes.info, :each
  end

  def test_has_stats
    assert_respond_to @nodes, :stats
  end

  def test_stats_has_value
    assert_respond_to @nodes.stats, :each
  end
end


text:
package water.fvec;

import water.AutoBuffer;
import water.Key;
import water.DKV;
import water.parser.ValueString;

/** A vector transforming values of given vector according to given domain
 *  mapping - currently only used to transform Enum columns but in theory would
 *  work for any dense-packed Int column.  Expected usage is to map from a new
 *  dataset to the domain-mapping expected by a model (which will match the
 *  dataset it was trained on).
 *
 *
The Vector's domain is the union of the Test and Train domains.
 *
 *
The mapping is defined by int[] array, size is input Test.domain.length.
 *  Contents refer to values in the Train.domain.  Extra values in the Test
 *  domain are sorted after the Train.domain - so mapped values have to be
 *  range-checked (note that returning some flag for NA, say -1, would also
 *  need to be checked for).
 */
public class StrWrappedVec extends WrappedVec {
  /** Main constructor: convert from enum to string */
  public StrWrappedVec(Key key, long[] espc, Key masterVecKey) {
    super(key, espc, masterVecKey);
    _type = T_STR;
    DKV.put(this);
  }

  @Override public Chunk chunkForChunkIdx(int cidx) {
    return new StrWrappedChunk(masterVec().chunkForChunkIdx(cidx), this);
  }

  static class StrWrappedChunk extends Chunk {
    final Chunk _c;             // Test-set map

    StrWrappedChunk(Chunk c, StrWrappedVec vec) {
      _c  = c; set_len(_c._len); _start = _c._start; _vec = vec; _cidx = _c._cidx;
    }

    @Override public double atd_impl(int idx) { throw new IllegalArgumentException("Operation not allowed on string vector.");}
    @Override public long at8_impl(int idx) { throw new IllegalArgumentException("Operation not allowed on string vector.");}
    @Override public ValueString atStr_impl(ValueString vstr, int idx) {
      return isNA_impl(idx) ? null : vstr.setTo(((StrWrappedVec)_vec).masterVec().factor(_c.at8_impl(idx)));
    }

    @Override protected boolean isNA_impl(int idx) { return _c.isNA_impl(idx); }
    @Override boolean setNA_impl(int idx)         { throw new IllegalArgumentException("Operation not allowed on string vector."); }
    @Override boolean set_impl(int idx, long l)   { throw new IllegalArgumentException("Operation not allowed on string vector."); }
    @Override boolean set_impl(int idx, double d) { throw new IllegalArgumentException("Operation not allowed on string vector."); }
    @Override boolean set_impl(int idx, float f)  { throw new IllegalArgumentException("Operation not allowed on string vector."); }
    @Override boolean set_impl(int idx, String str) { return false; }

    @Override public NewChunk inflate_impl(NewChunk nc) {
      nc.set_sparseLen(nc.set_len(0));
      for( int i=0; i< _len; i++ )
        if(isNA(i))nc.addNA();
        else nc.addNum(at8(i),0);
      return nc;
    }
    @Override public AutoBuffer write_impl(AutoBuffer bb) { throw water.H2O.fail(); }
    @Override public Chunk read_impl(AutoBuffer bb)       { throw water.H2O.fail(); }
  }
}


text:
test_description='git rebase --merge test'

. ./test-lib.sh

T="A quick brown fox
jumps over the lazy dog."
for i in 1 2 3 4 5 6 7 8 9 10
do
	echo "$i $T"
done >original

test_expect_success setup '
	git add original &&
	git commit -m"initial" &&
	git branch side &&
	echo "11 $T" >>original &&
	git commit -a -m"master updates a bit." &&

	echo "12 $T" >>original &&
	git commit -a -m"master updates a bit more." &&

	git checkout side &&
	(echo "0 $T" ; cat original) >renamed &&
	git add renamed &&
	git update-index --force-remove original &&
	git commit -a -m"side renames and edits." &&

	tr "[a-z]" "[A-Z]" <original >newfile &&
	git add newfile &&
	git commit -a -m"side edits further." &&

	tr "[a-m]" "[A-M]" <original >newfile &&
	rm -f original &&
	git commit -a -m"side edits once again." &&

	git branch test-rebase side &&
	git branch test-rebase-pick side &&
	git branch test-reference-pick side &&
	git checkout -b test-merge side
'

test_expect_success 'reference merge' '
	git merge -s recursive "reference merge" HEAD master
'

PRE_REBASE=$(git rev-parse test-rebase)
test_expect_success rebase '
	git checkout test-rebase &&
	GIT_TRACE=1 git rebase --merge master
'

test_expect_success 'test-rebase@{1} is pre rebase' '
	test $PRE_REBASE = $(git rev-parse test-rebase@{1})
'

test_expect_success 'merge and rebase should match' '
	git diff-tree -r test-rebase test-merge >difference &&
	if test -s difference
	then
		cat difference
		(exit 1)
	else
		echo happy
	fi
'

test_expect_success 'rebase the other way' '
	git reset --hard master &&
	git rebase --merge side
'

test_expect_success 'rebase -Xtheirs' '
	git checkout -b conflicting master~2 &&
	echo "AB $T" >> original &&
	git commit -mconflicting original &&
	git rebase -Xtheirs master &&
	grep AB original &&
	! grep 11 original
'

test_expect_success 'merge and rebase should match' '
	git diff-tree -r test-rebase test-merge >difference &&
	if test -s difference
	then
		cat difference
		(exit 1)
	else
		echo happy
	fi
'

test_expect_success 'picking rebase' '
	git reset --hard side &&
	git rebase --merge --onto master side^^ &&
	mb=$(git merge-base master HEAD) &&
	if test "$mb" = "$(git rev-parse master)"
	then
		echo happy
	else
		git show-branch
		(exit 1)
	fi &&
	f=$(git diff-tree --name-only HEAD^ HEAD) &&
	g=$(git diff-tree --name-only HEAD^^ HEAD^) &&
	case "$f,$g" in
	newfile,newfile)
		echo happy ;;
	*)
		echo "$f"
		echo "$g"
		(exit 1)
	esac
'

test_expect_success 'rebase -s funny -Xopt' '
	test_when_finished "rm -fr test-bin funny.was.run" &&
	mkdir test-bin &&
	cat >test-bin/git-merge-funny <<-EOF &&
	#!$SHELL_PATH
	case "\$1" in --opt) ;; *) exit 2 ;; esac
	shift &&
	>funny.was.run &&
	exec git merge-recursive "\$@"
	EOF
	chmod +x test-bin/git-merge-funny &&
	git reset --hard &&
	git checkout -b test-funny master^ &&
	test_commit funny &&
	(
		PATH=./test-bin:$PATH
		git rebase -s funny -Xopt master
	) &&
	test -f funny.was.run
'

test_done


text:
<?php

namespace Bukoli\Response;

use Bukoli\Model\Response\IntegrationResultInfo;

class OrderInsertResponse
{
    /**
     * @var IntegrationResultInfo
     */
    public $OrderInsertResult;
}


text:
[![Build Status](https://travis-ci.org/thtrieu/darkflow.svg?branch=master)](https://travis-ci.org/thtrieu/darkflow) [![codecov](https://codecov.io/gh/thtrieu/darkflow/branch/master/graph/badge.svg)](https://codecov.io/gh/thtrieu/darkflow)

Real-time object detection and classification. Paper: [version 1](https://arxiv.org/pdf/1506.02640.pdf), [version 2](https://arxiv.org/pdf/1612.08242.pdf).

Read more about YOLO (in darknet) and download weight files [here](http://pjreddie.com/darknet/yolo/). In case the weight file cannot be found, I uploaded some of mine [here](https://drive.google.com/drive/folders/0B1tW_VtY7onidEwyQ2FtQVplWEU), which include `yolo-full` and `yolo-tiny` of v1.0, `tiny-yolo-v1.1` of v1.1 and `yolo`, `tiny-yolo-voc` of v2.

Click on this image to see demo from yolov2:

[![img](preview.png)](http://i.imgur.com/EyZZKAA.gif)

## Dependencies

Python3, tensorflow 1.0, numpy, opencv 3.

### Getting started

You can choose _one_ of the following three ways to get started with darkflow.

1. Just build the Cython extensions in place. NOTE: If installing this way you will have to use `./flow` in the cloned darkflow directory instead of `flow` as darkflow is not installed globally.
    ```
    python3 setup.py build_ext --inplace
    ```

2. Let pip install darkflow globally in dev mode (still globally accessible, but changes to the code immediately take effect)
    ```
    pip install -e .
    ```

3. Install with pip globally
    ```
    pip install .
    ```

## Update

**Android demo on Tensorflow's** [here](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowYoloDetector.java)

**I am looking for help:**
 - `help wanted` labels in issue track

## Parsing the annotations

Skip this if you are not training or fine-tuning anything (you simply want to forward flow a trained net)

For example, if you want to work with only 3 classes `tvmonitor`, `person`, `pottedplant`; edit `labels.txt` as follows

```
tvmonitor
person
pottedplant
```

And that's it. `darkflow` will take care of the rest.

## Design the net

Skip this if you are working with one of the original configurations since they are already there. Otherwise, see the following example:

```python
...

[convolutional]
batch_normalize = 1
size = 3
stride = 1
pad = 1
activation = leaky

[maxpool]

[connected]
output = 4096
activation = linear

...
```

## Flowing the graph using `flow`

```bash
# Have a look at its options
flow --h
```

First, let's take a closer look at one of a very useful option `--load`

```bash
# 1. Load yolo-tiny.weights
flow --model cfg/yolo-tiny.cfg --load bin/yolo-tiny.weights

# 2. To completely initialize a model, leave the --load option
flow --model cfg/yolo-new.cfg

# 3. It is useful to reuse the first identical layers of tiny for `yolo-new`
flow --model cfg/yolo-new.cfg --load bin/yolo-tiny.weights
# this will print out which layers are reused, which are initialized
```

All input images from default folder `sample_img/` are flowed through the net and predictions are put in `sample_img/out/`. We can always specify more parameters for such forward passes, such as detection threshold, batch size, images folder, etc.

```bash
# Forward all images in sample_img/ using tiny yolo and 100% GPU usage
flow --imgdir sample_img/ --model cfg/yolo-tiny.cfg --load bin/yolo-tiny.weights --gpu 1.0
```
json output can be generated with descriptions of the pixel location of each bounding box and the pixel location. Each prediction is stored in the `sample_img/out` folder by default. An example json array is shown below.
```bash
# Forward all images in sample_img/ using tiny yolo and JSON output.
flow --imgdir sample_img/ --model cfg/yolo-tiny.cfg --load bin/yolo-tiny.weights --json
```
JSON output:
```json
[{"label":"person", "confidence": 0.56, "topleft": {"x": 184, "y": 101}, "bottomright": {"x": 274, "y": 382}},
{"label": "dog", "confidence": 0.32, "topleft": {"x": 71, "y": 263}, "bottomright": {"x": 193, "y": 353}},
{"label": "horse", "confidence": 0.76, "topleft": {"x": 412, "y": 109}, "bottomright": {"x": 592,"y": 337}}]
```
 - label: self explanatory
 - confidence: somewhere between 0 and 1 (how confident yolo is about that detection)
 - topleft: pixel coordinate of top left corner of box.
 - bottomright: pixel coordinate of bottom right corner of box.

## Training new model

Training is simple as you only have to add option `--train`. Training set and annotation will be parsed if this is the first time a new configuration is trained. To point to training set and annotations, use option `--dataset` and `--annotation`. A few examples:

```bash
# Initialize yolo-new from yolo-tiny, then train the net on 100% GPU:
flow --model cfg/yolo-new.cfg --load bin/yolo-tiny.weights --train --gpu 1.0

# Completely initialize yolo-new and train it with ADAM optimizer
flow --model cfg/yolo-new.cfg --train --trainer adam
```

During training, the script will occasionally save intermediate results into Tensorflow checkpoints, stored in `ckpt/`. To resume to any checkpoint before performing training/testing, use `--load [checkpoint_num]` option, if `checkpoint_num < 0`, `darkflow` will load the most recent save by parsing `ckpt/checkpoint`.

```bash
# Resume the most recent checkpoint for training
flow --train --model cfg/yolo-new.cfg --load -1

# Test with checkpoint at step 1500
flow --model cfg/yolo-new.cfg --load 1500

# Fine tuning yolo-tiny from the original one
flow --train --model cfg/yolo-tiny.cfg --load bin/yolo-tiny.weights
```

Example of training on Pascal VOC 2007:
```bash
# Download the Pascal VOC dataset:
curl -O https://pjreddie.com/media/files/VOCtest_06-Nov-2007.tar
tar xf VOCtest_06-Nov-2007.tar

# An example of the Pascal VOC annotation format:
vim VOCdevkit/VOC2007/Annotations/000001.xml

# Train the net on the Pascal dataset:
flow --model cfg/yolo-new.cfg --train --dataset "~/VOCdevkit/VOC2007/JPEGImages" --annotation "~/VOCdevkit/VOC2007/Annotations"
```

## Camera/video file demo

For a demo that entirely runs on the CPU:

```bash
flow --model cfg/yolo-new.cfg --load bin/yolo-new.weights --demo videofile.avi
```

For a demo that runs 100% on the GPU:

```bash
flow --model cfg/yolo-new.cfg --load bin/yolo-new.weights --demo videofile.avi --gpu 1.0
```

To use your webcam/camera, simply replace `videofile.avi` with keyword `camera`.

To save a video with predicted bounding box, add `--saveVideo` option.

## Using darkflow from another python application

Please note that `return_predict(img)` must take an `numpy.ndarray`. Your image must be loaded beforehand and passed to `return_predict(img)`. Passing the file path won't work.

Result from `return_predict(img)` will be a list of dictionaries representing each detected object's values in the same format as the JSON output listed above.

```python
from darkflow.net.build import TFNet
import cv2

options = {"model": "cfg/yolo.cfg", "load": "bin/yolo.weights", "threshold": 0.1}

tfnet = TFNet(options)

imgcv = cv2.imread("./sample_img/dog.jpg")
result = tfnet.return_predict(imgcv)
print(result)
```

## Save the built graph to a protobuf file (`.pb`)

```bash
## Saving the lastest checkpoint to protobuf file
flow --model cfg/yolo-new.cfg --load -1 --savepb

## Saving graph and weights to protobuf file
flow --model cfg/yolo.cfg --load bin/yolo.weights --savepb
```
When saving the `.pb` file, a `.meta` file will also be generated alongside it. This `.meta` file is a JSON dump of everything in the `meta` dictionary that contains information nessecary for post-processing such as `anchors` and `labels`. This way, everything you need to make predictions from the graph and do post processing is contained in those two files - no need to have the `.cfg` or any labels file tagging along.

The created `.pb` file can be used to migrate the graph to mobile devices (JAVA / C++ / Objective-C++). The name of input tensor and output tensor are respectively `'input'` and `'output'`. For further usage of this protobuf file, please refer to the official documentation of `Tensorflow` on C++ API [_here_](https://www.tensorflow.org/versions/r0.9/api_docs/cc/index.html). To run it on, say, iOS application, simply add the file to Bundle Resources and update the path to this file inside source code.

Also, darkflow supports loading from a `.pb` and `.meta` file for generating predictions (instead of loading from a `.cfg` and checkpoint or `.weights`).
```bash
## Forward images in sample_img for predictions based on protobuf file
flow --pbLoad built_graph/yolo.pb --metaLoad built_graph/yolo.meta --imgdir sample_img/
```
If you'd like to load a `.pb` and `.meta` file when using `return_predict()` you can set the `"pbLoad"` and `"metaLoad"` options in place of the `"model"` and `"load"` options you would normally set.

That's all.


text:
package pl.npe.lpp.directive;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import pl.npe.lpp.preprocessor.source.CannotReadFromFileException;
import pl.npe.lpp.preprocessor.source.ProcessingContext;

import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: tomek
 * Date: 01.11.13
 * Time: 10:43
 */
public class HttpGetRequestExpander extends AbstractExpander{

    @Override
    protected void validateParams(List<String> params, ProcessingContext context) throws ExpanderException {
        if(params.size() != 1){
            throw new ExpanderException(context, "HttpGetRequestExpander directive requires one parameter");
        }

        validateURL(params.get(0), context);
    }

    @Override
    protected String expandDirective(List<String> params, ProcessingContext context) throws CannotReadFromFileException, UnknownDirectiveException, ExpanderException {
        String url = params.get(0);
        HttpGet get = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        try{
            HttpResponse response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != 200){
                throw new ExpanderException(context, "Making GET request to " + url + " returned error status code: " + statusCode);
            }else {
                return getResponse(response);
            }
        }catch (IOException e){
            throw new ExpanderException(context, "Cannot make GET request to: " + url);
        }
    }

    String getResponse(HttpResponse response) throws IOException {
        StringWriter writer = new StringWriter();
        HttpEntity httpEntity = response.getEntity();
        IOUtils.copy(httpEntity.getContent(), writer, getCharset(httpEntity).name());
        return writer.toString();
    }

    Charset getCharset(HttpEntity httpEntity){
        ContentType contentType = ContentType.getOrDefault(httpEntity);
        Charset charset = contentType.getCharset();
        return charset != null ? charset : Charset.defaultCharset();
    }

    void validateURL(String value, ProcessingContext context) throws ExpanderException {
        try {
            new URL(value);
        } catch (MalformedURLException e) {
            throw new ExpanderException(context, "HttpGetRequestExpander directive requires valid url passed as parameter");
        }
    }

}


text:
package com.netflix.evcache.pool;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import net.spy.memcached.MemcachedNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;

public class DIEVCacheKetamaNodeLocatorConfiguration extends EVCacheKetamaNodeLocatorConfiguration {

    private static final Logger log = LoggerFactory.getLogger(DIEVCacheKetamaNodeLocatorConfiguration.class);
    private final EurekaClient eurekaClient;

    public DIEVCacheKetamaNodeLocatorConfiguration(EVCacheClient client, EurekaClient eurekaClient) {
        super(client);
        this.eurekaClient = eurekaClient;
    }

    /**
     * Returns the socket address of a given MemcachedNode.
     *
     * @param node - The MemcachedNode which we're interested in
     * @return The socket address of the given node format is of the following
     * format "publicHostname/privateIp:port" (ex -
     ec2-174-129-159-31.compute-1.amazonaws.com/10.125.47.114:11211)
     */
    @Override
    public String getKeyForNode(MemcachedNode node, int repetition) {
        String result = socketAddresses.get(node);
        if(result == null) {
            final SocketAddress socketAddress = node.getSocketAddress();
            if(socketAddress instanceof InetSocketAddress) {
                final InetSocketAddress isa = (InetSocketAddress)socketAddress;
                if(eurekaClient != null ) {
                    final Application app = eurekaClient.getApplication(client.getAppName());
                    if(app != null) {
                        final List<InstanceInfo> instances = app.getInstances();
                        for(InstanceInfo info : instances) {
                            final String hostName = info.getHostName();
                            if(hostName.equalsIgnoreCase(isa.getHostName())) {
                                final String ip = info.getIPAddr();
                                result = hostName + '/' + ip + ":11211";
                                break;
                            }
                        }
                    } else {
                        result = ((InetSocketAddress)socketAddress).getHostName() + '/' + ((InetSocketAddress)socketAddress).getAddress().getHostAddress() + ":11211";
                    }
                } else {
                    result = isa.getHostName() + '/' + isa.getAddress().getHostAddress() + ":11211";
                }
            } else {
                result=String.valueOf(socketAddress);
                if (result.startsWith("/")) {
                    result = result.substring(1);
                }
            }
            socketAddresses.put(node, result);
        }
        if(log.isDebugEnabled()) log.debug("Returning : " + (result + "-" + repetition));
        return result + "-" + repetition;
    }

    @Override
    public String toString() {
        return "DIEVCacheKetamaNodeLocatorConfiguration [" + super.toString() + ", EurekaClient=" + eurekaClient + "]";
    }
}


text:
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace ExternalProcessing {

using Http::Headers;
using Http::LowerCaseString;

using envoy::config::core::v3::HeaderValueOption;
using envoy::service::ext_proc::v3::BodyMutation;
using envoy::service::ext_proc::v3::BodyResponse;
using envoy::service::ext_proc::v3::CommonResponse;
using envoy::service::ext_proc::v3::HeaderMutation;
using envoy::service::ext_proc::v3::HeadersResponse;

void MutationUtils::headersToProto(const Http::HeaderMap& headers_in,
                                   envoy::config::core::v3::HeaderMap& proto_out) {
  headers_in.iterate([&proto_out](const Http::HeaderEntry& e) -> Http::HeaderMap::Iterate {
    auto* new_header = proto_out.add_headers();
    new_header->set_key(std::string(e.key().getStringView()));
    new_header->set_value(std::string(e.value().getStringView()));
    return Http::HeaderMap::Iterate::Continue;
  });
}

void MutationUtils::applyCommonHeaderResponse(const HeadersResponse& response,
                                              Http::HeaderMap& headers) {
  if (response.has_response()) {
    const auto& common_response = response.response();
    if (common_response.has_header_mutation()) {
      applyHeaderMutations(common_response.header_mutation(), headers,
                           common_response.status() == CommonResponse::CONTINUE_AND_REPLACE);
    }
  }
}

void MutationUtils::applyHeaderMutations(const HeaderMutation& mutation, Http::HeaderMap& headers,
                                         bool replacing_message) {
  for (const auto& remove_header : mutation.remove_headers()) {
    if (Http::HeaderUtility::isRemovableHeader(remove_header)) {
      ENVOY_LOG(trace, "Removing header {}", remove_header);
      headers.remove(LowerCaseString(remove_header));
    } else {
      ENVOY_LOG(debug, "Header {} is not removable", remove_header);
    }
  }

  for (const auto& sh : mutation.set_headers()) {
    if (!sh.has_header()) {
      continue;
    }
    if (!isSettableHeader(sh, replacing_message)) {
      // Log the failure to set the header here, but don't log the value in case it's
      // something sensitive like the Authorization header.
      ENVOY_LOG(debug, "Ignorning improper attempt to set header {}", sh.header().key());
    } else {
      // Make "false" the default. This is logical and matches the ext_authz
      // filter. However, the router handles this same protobuf and uses "true"
      // as the default instead.
      const bool append = PROTOBUF_GET_WRAPPED_OR_DEFAULT(sh, append, false);
      const LowerCaseString lcKey(sh.header().key());
      if (append && !headers.get(lcKey).empty() && !isAppendableHeader(lcKey)) {
        ENVOY_LOG(debug, "Ignoring duplicate value for header {}", sh.header().key());
      } else {
        ENVOY_LOG(trace, "Setting header {} append = {}", sh.header().key(), append);
        if (append) {
          headers.addCopy(lcKey, sh.header().value());
        } else {
          headers.setCopy(lcKey, sh.header().value());
        }
      }
    }
  }
}

void MutationUtils::applyCommonBodyResponse(const BodyResponse& response,
                                            Http::RequestOrResponseHeaderMap* headers,
                                            Buffer::Instance& buffer) {
  if (response.has_response()) {
    const auto& common_response = response.response();
    if (headers != nullptr && common_response.has_header_mutation()) {
      applyHeaderMutations(common_response.header_mutation(), *headers,
                           common_response.status() == CommonResponse::CONTINUE_AND_REPLACE);
    }
    if (common_response.has_body_mutation()) {
      if (headers != nullptr) {
        // Always clear content length if we can before modifying body
        headers->removeContentLength();
      }
      applyBodyMutations(common_response.body_mutation(), buffer);
    }
  }
}

void MutationUtils::applyBodyMutations(const BodyMutation& mutation, Buffer::Instance& buffer) {
  switch (mutation.mutation_case()) {
  case BodyMutation::MutationCase::kClearBody:
    if (mutation.clear_body()) {
      ENVOY_LOG(trace, "Clearing HTTP body");
      buffer.drain(buffer.length());
    }
    break;
  case BodyMutation::MutationCase::kBody:
    ENVOY_LOG(trace, "Replacing body of {} bytes with new body of {} bytes", buffer.length(),
              mutation.body().size());
    buffer.drain(buffer.length());
    buffer.add(mutation.body());
    break;
  default:
    // Nothing to do on default
    break;
  }
}

bool MutationUtils::isValidHttpStatus(int code) { return (code >= 200); }

// Ignore attempts to set certain sensitive headers that can break later processing.
// We may re-enable some of these after further testing. This logic is specific
// to the ext_proc filter so it is not shared with HeaderUtils.
bool MutationUtils::isSettableHeader(const HeaderValueOption& header, bool replacing_message) {
  const auto& key = header.header().key();
  const auto& headers = Headers::get();
  if (absl::EqualsIgnoreCase(key, headers.HostLegacy.get()) ||
      absl::EqualsIgnoreCase(key, headers.Host.get()) ||
      (absl::EqualsIgnoreCase(key, headers.Method.get()) && !replacing_message) ||
      absl::EqualsIgnoreCase(key, headers.Scheme.get()) ||
      absl::StartsWithIgnoreCase(key, headers.prefix())) {
    return false;
  }
  if (absl::EqualsIgnoreCase(key, headers.Status.get())) {
    const auto& value = header.header().value();
    uint32_t status;
    if (!absl::SimpleAtoi(value, &status)) {
      ENVOY_LOG(debug, "Invalid value {} for HTTP status code", value);
      return false;
    }
    if (!isValidHttpStatus(status)) {
      ENVOY_LOG(debug, "Invalid HTTP status code {}", status);
      return false;
    }
  }
  return true;
}

// Ignore attempts to append a second value to any system header, as in general those
// were never designed to support multiple values.
bool MutationUtils::isAppendableHeader(absl::string_view key) {
  return !key.empty() && key[0] != ':';
}

} // namespace ExternalProcessing
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy


text:
package reseau.ressources;

import io.IO;
import map.Map;
import perso.Perso;
import perso.PersoIO;
import reseau.paquets.jeu.PaquetSpawn;
import exceptions.HorsLimiteException;

public class RessourcePerso extends RessourceReseau<Perso> {
    private Perso perso;

    public RessourcePerso(int id, Perso perso) {
	super(id);
	this.perso = perso;
    }

    public RessourcePerso(IO io) {
	super(io);
	perso = PersoIO.get(io);
    }

    public RessourcePerso(IO io, Map map) {
	this(io);
	perso.setMap(map);
	if(io.aByte()) try {
	    PaquetSpawn.setPos(io, perso);
	} catch(HorsLimiteException e) {
	    e.printStackTrace();
	}
    }

    public Perso getPerso() {
	return perso;
    }

    public void setPerso(Perso perso) {
	this.perso = perso;
    }

    @Override
    public TypeRessource getType() {
	return TypeRessource.PERSO;
    }

    @Override
    public void ecrireDonnees(IO io) {
	perso.ecrireDonnees(io);
	if(perso.estDansMap())
	    PaquetSpawn.ecrire(io, perso);
    }

    @Override
    public Perso getRessource() {
	return getPerso();
    }

    @Override
    public void affecteRessource(Perso ressource) {
	setPerso(ressource);
    }

}


text:
static char const * const kActivityIndicatorAttachmentKey = "kActivityIndicatorAttachment";

@implementation UIView (UIActivityIndicatorView)

@dynamic activityIndicatorView;

- (void)setActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
{
	objc_setAssociatedObject(self, kActivityIndicatorAttachmentKey, activityIndicatorView, OBJC_ASSOCIATION_RETAIN);
}

- (UIActivityIndicatorView*)activityIndicatorView
{
	return objc_getAssociatedObject(self, kActivityIndicatorAttachmentKey);
}

-(void)startLoadingWithStyle:(UIActivityIndicatorViewStyle)style{
    if(self.activityIndicatorView==nil){
        self.activityIndicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
        self.activityIndicatorView.hidesWhenStopped=YES;
    }
    self.activityIndicatorView.frame=self.frame;
    [self.superview insertSubview:self.activityIndicatorView aboveSubview:self];
    self.activityIndicatorView.hidden=NO;
    [self.activityIndicatorView startAnimating];
    self.hidden=YES;
}

-(void)startLoading{
    [self startLoadingWithStyle:UIActivityIndicatorViewStyleGray];
}

-(void)stopLoading{
    self.activityIndicatorView.hidden=YES;
    [self.activityIndicatorView removeFromSuperview];
    self.hidden=NO;
}

@end