text:
package com.xzy.android.fastvalueholdersample;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.xzy.android.fastvalueholder.ItemAdapter;

/**
 * @author zhengyang.xu
 * @version 0.1
 * @since 2014/09/28
 */
public class MainActivity extends ActionBarActivity {

    private ListView mListView;
    private ItemAdapter mItemAdapter;

    private int[] mDrawableId = {
            R.drawable.animal_0, R.drawable.animal_1,
            R.drawable.animal_2, R.drawable.animal_3, R.drawable.animal_4,
            R.drawable.animal_5, R.drawable.animal_6, R.drawable.animal_7
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) this.findViewById(R.id.listview);
        mItemAdapter = new ItemAdapter(this);
        initItems(this);
        mListView.setAdapter(mItemAdapter);
    }

    private void initItems(Context context) {
        for (int i = 0; i < mDrawableId.length; i++) {
            mItemAdapter.addItem(new PicItem(mDrawableId[i], R.layout.pic_items));
        }
        for (int i = 0; i < 10; i++) {
            TextItemData itemData = new TextItemData();
            itemData.setTitle(String.valueOf(i+100));
            itemData.setComment(String.valueOf(i+1000000));
            mItemAdapter.addItem(new TextItem(itemData));
        }
        for (int i = 0; i < 10; i++) {
            mItemAdapter.addItem(new RatingBarItem(8f, R.layout.ratingbar_item));
        }
        for (int i = 0; i < mDrawableId.length; i++) {
            mItemAdapter.addItem(new PicItem(mDrawableId[i], R.layout.pic_items));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.mitre.mat.core.MATDocumentException
</TITLE>

<META NAME="date" CONTENT="2013-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.mitre.mat.core.MATDocumentException

Uses of MATDocumentException in org.mitre.mat.core

Methods in org.mitre.mat.core that throw MATDocumentException

 Annotation
MATDocument.createAnnotation(Atype atype,
                 int start,
                 int end)

 Annotation
MATDocumentInterface.createAnnotation(Atype atype,
                 int start,
                 int end)

          Create a new spanned annotation

 Annotation
MATDocument.createAnnotation(Atype atype,
                 int start,
                 int end,
                 java.util.List valsList)

 Annotation
MATDocumentInterface.createAnnotation(Atype atype,
                 int start,
                 int end,
                 java.util.List valsList)

          Create a new spanned annotation with attribute values set

 Annotation
MATDocument.createAnnotation(Atype atype,
                 int start,
                 int end,
                 java.util.Map valsMap)

 Annotation
MATDocumentInterface.createAnnotation(Atype atype,
                 int start,
                 int end,
                 java.util.Map valsMap)

          Create a new spanned annotation with attribute values set

 Annotation
MATDocument.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end)

 Annotation
MATDocumentInterface.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end)

          Create a new spanned annotation

 Annotation
MATDocument.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end,
                 java.util.List valsList)

 Annotation
MATDocumentInterface.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end,
                 java.util.List valsList)

          Create a new spanned annotation with attribute values set

 Annotation
MATDocument.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end,
                 java.util.Map valsMap)

 Annotation
MATDocumentInterface.createAnnotation(java.lang.String atypeType,
                 int start,
                 int end,
                 java.util.Map valsMap)

          Create a new spanned annotation with attribute values set

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(Atype atype)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(Atype atype)

          Create a new spanless annotation

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(Atype atype,
                         java.util.List valsList)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(Atype atype,
                         java.util.List valsList)

          Create a new spanless annotation with attribute values set

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(Atype atype,
                         java.util.Map valsMap)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(Atype atype,
                         java.util.Map valsMap)

          Create a new spanless annotation with attribute values set

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(java.lang.String atypeType)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(java.lang.String atypeType)

          Create a new spanless annotation

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(java.lang.String atypeType,
                         java.util.List valsList)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(java.lang.String atypeType,
                         java.util.List valsList)

          Create a new spanless annotation with attribute values set

 SpanlessAnnotation
MATDocument.createSpanlessAnnotation(java.lang.String atypeType,
                         java.util.Map valsMap)

 SpanlessAnnotation
MATDocumentInterface.createSpanlessAnnotation(java.lang.String atypeType,
                         java.util.Map valsMap)

          Create a new spanless annotation with attribute values set

 void
MATDocument.deleteAllAnnotations()

 void
MATDocumentInterface.deleteAllAnnotations()

          Delete ALL annotations from this document

 void
MATDocument.deleteAnnotation(AnnotationCore a)

 void
MATDocumentInterface.deleteAnnotation(AnnotationCore a)

          Delete an annotation from this document

 void
MATDocument.deleteAnnotations(java.util.List<AnnotationCore> annots)

 void
MATDocumentInterface.deleteAnnotations(java.util.List<AnnotationCore> annots)

          Delete a list of annotations

 Atype
DocumentAnnotationTypeRepository.findAnnotationType(Atype atype,
                   boolean hasSpan)

          A version of findAnnotationType that accepts and an atype
 instead of a label; it just checks the hasSpan agreement.

 Atype
DocumentAnnotationTypeRepository.findAnnotationType(java.lang.String label)

          Find the specified Atype for a spanned annotation within the repository,
 or create it if it is not found.

 Atype
DocumentAnnotationTypeRepository.findAnnotationType(java.lang.String label,
                   boolean hasSpan,
                   boolean create)

          Find the specified Atype within the repository.

 Atype
GlobalAnnotationTypeRepository.findAnnotationType(java.lang.String label,
                   DocumentAnnotationTypeRepository docTypeRepository,
                   boolean hasSpan,
                   boolean create)

          Find the specified annotation type in this global repository and copy it
 into the document-level repository provided.

 int
Atype.findOrAddAttribute(java.lang.String attr)

          Finds the index of the specified attribute in this Atype, or adds it.

 int
Atype.findOrAddAttribute(java.lang.String attr,
                   java.lang.String attrtype)

          Finds the index of the specified attribute in this Atype, or adds it.

 int
Atype.findOrAddAttribute(java.lang.String attrName,
                   java.lang.String attrtype,
                   int aggregation)

          Finds the index of the specified attribute in this Atype, or adds it.

 int
Atype.findOrAddAttribute(java.lang.String attrName,
                   java.lang.String attrtype,
                   int aggregation,
                   java.util.Map restrictions)

          Finds the index of the specified attribute in this Atype, or adds it.

 int
Atype.findOrAddAttribute(java.lang.String attrName,
                   java.lang.String attrtype,
                   int aggregation,
                   java.util.Map restrictions,
                   java.lang.Object defaultValue,
                   boolean defaultIsTextSpan)

          Finds the index of the specified attribute in this Atype, or adds it.

 Atype
MATDocument.findOrAddAtype(java.lang.String atypeType)

 Atype
MATDocumentInterface.findOrAddAtype(java.lang.String atypeType)

          Find or add an annotation type (Atype).

 Atype
MATDocument.findOrAddAtype(java.lang.String atypeType,
               boolean hasSpan)

 Atype
MATDocumentInterface.findOrAddAtype(java.lang.String atypeType,
               boolean hasSpan)

          Find or add an annotation type (Atype).

 void
MATDocumentEncoding.fromEncodedString(MATDocumentInterface doc,
                  java.lang.String s)

 void
MATJSONEncoding.fromEncodedString(MATDocumentInterface doc,
                  java.lang.String jsonData)

 void
MATJSONDocument.fromEncodedString(java.lang.String s)

 void
MATDocumentEncoding.fromFile(MATDocumentInterface doc,
         java.lang.String fileName)

 void
MATJSONEncoding.fromFile(MATDocumentInterface doc,
         java.lang.String fileName)

 void
GlobalAnnotationTypeRepository.fromJSONDescriptor(java.lang.String descriptor)

          We don't need to handle a list, just a single string

    public void fromJSONDescriptorList(List<String> jsonData) throws MATDocumentException {
        fromJSONDescriptorList(jsonData, false);
    }

    public void fromJSONDescriptorList(List<String> descriptorList, boolean allAnnotationsKnown) throws MATDocumentException {
        // Now, we can hoover through the descriptors, creating all
        // the annotations.

 void
GlobalAnnotationTypeRepository.fromJSONDescriptor(java.lang.String descriptor,
                   boolean allAnnotationsKnown)

          Populates this repository from a JSON Descriptor.

 void
MATJSONEncoding.fromJsonNode(MATDocumentInterface doc,
             org.codehaus.jackson.JsonNode jsonValues)

 Atype
DocumentAnnotationTypeRepository.importAnnotationType(Atype atype)

          Copies the given Atype to this repository

 void
DocumentAnnotationTypeRepository.importAnnotationTypes(MATDocument doc)

          Copies all the annotation types from the given document to this repository

 java.util.Collection<Atype>
DocumentAnnotationTypeRepository.importAnnotationTypes(MATDocument doc,
                      java.util.Collection<Atype> removeAnnotationTypes)

          Copies all the annotation types, except those in the removeAnnotationTypes
 Collection, from the given document to this repository

 Atype
Atype.maybeCopy(DocumentAnnotationTypeRepository targetRepository)

          Copy this Atype to another repository if necessary.

 void
AnnotationIDCache.registerID(java.lang.String aID,
           AnnotationCore a)

          Register a given annotation ID for a given annotation.

 void
AnnotationIDCache.removeAnnotationIDs(java.util.List<AnnotationCore> aList)

          Removes the IDs of a given list of annotations from the cache

 void
AnnotationCore.setAttributeValue(int index,
                  AnnotationCore value)

          A variant of setAttributeValue meant to be used ONLY with the JSON decoder.

 void
AnnotationCore.setAttributeValue(int index,
                  AttributeValueCollection value)

          A variant of setAttributeValue meant to be used ONLY with the JSON decoder.

 void
AnnotationCore.setAttributeValue(int index,
                  java.lang.String value)

          A variant of setAttributeValue meant to be used ONLY with the JSON decoder.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  AnnotationCore value)

          Sets an attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  AttributeValueList value)

          Sets a List-valued attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  AttributeValueSet value)

          Sets a Set-valued attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  double value)

          Sets an attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  float value)

          Sets an attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  int value)

          Sets an attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  java.lang.Object value)

          Sets an attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  java.lang.String attrtype,
                  AttributeValueList value)

          Sets a List-valued attribute value.

 void
AnnotationCore.setAttributeValue(java.lang.String attr,
                  java.lang.String attrtype,
                  AttributeValueSet value)

          Sets a Set-valued attribute value.

 void
AnnotationCore.setID(java.lang.String id)

          Sets this Annotation's unique ID

Constructors in org.mitre.mat.core that throw MATDocumentException

Atype(AnnotationTypeRepository repository,
      java.lang.String atypeLabel)

          Creates an Atype

Atype(AnnotationTypeRepository repository,
      java.lang.String atypeLabel,
      boolean hasSpan)

          Creates an Atype

Atype(AnnotationTypeRepository repository,
      java.lang.String atypeLabel,
      java.util.List<java.lang.String> attrList)

          Creates an Atype

Atype(AnnotationTypeRepository repository,
      java.lang.String atypeLabel,
      java.util.List<java.lang.String> attrList,
      boolean hasSpan)

          Creates an Atype

SpanlessAnnotation(MATDocument doc,
                   Atype parent)

          Constructor

SpanlessAnnotation(MATDocument doc,
                   Atype parent,
                   java.util.List valsList)

          Constructor

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

redpajama_set_name: RedPajamaGithub


text:
package filter

import (
	"golang.org/x/sys/unix"
	"gvisor.dev/gvisor/pkg/seccomp"
)

// profileFilters returns extra syscalls made by runtime/pprof package.
func profileFilters() seccomp.SyscallRules {
	return seccomp.SyscallRules{
		unix.SYS_OPENAT: []seccomp.Rule{
			{
				seccomp.MatchAny{},
				seccomp.MatchAny{},
				seccomp.EqualTo(unix.O_RDONLY | unix.O_LARGEFILE | unix.O_CLOEXEC),
			},
		},
	}
}


text:
namespace mkt
{
  MKT_DEF_EXCEPTION(echo_error);
}

//This module's static data
namespace
{
  struct echo_data
  {
    mkt::echo_map               _echo_map;
    mkt::mutex                  _echo_map_mutex;
  };
  echo_data                    *_echo_data = 0;
  bool                          _echo_atexit = false;

  void _echo_cleanup()
  {
    _echo_atexit = true;
    delete _echo_data;
    _echo_data = 0;
  }

  echo_data* _get_echo_data()
  {
    if(_echo_atexit)
      throw mkt::echo_error("Already at program exit!");

    if(!_echo_data)
      {
        _echo_data = new echo_data;
        std::atexit(_echo_cleanup);
      }

    if(!_echo_data)
      throw mkt::echo_error("Missing static variable data!");
    return _echo_data;
  }

  mkt::echo_map& echo_map_ref()
  {
    return _get_echo_data()->_echo_map;
  }

  mkt::mutex& echo_map_mutex_ref()
  {
    return _get_echo_data()->_echo_map_mutex;
  }
}

//Echo commands
namespace
{
  void echo(const mkt::argument_vector& args)
  {
    mkt::thread_info ti(BOOST_CURRENT_FUNCTION);
    mkt::argument_vector local_args = args;
    local_args.erase(local_args.begin());

    if(local_args.empty())
      throw mkt::echo_error("Nothing to echo");

    bool newline = true;
    //Check if the first argument is an "-n". If it is, eat it and don't put a newline.
    if(local_args[0] == "-n")
      {
        newline = false;
        local_args.erase(local_args.begin());
      }

    //Check if the first argument is an integer. If it is, make it the echo function id to use.
    int echo_id = -1;
    try
      {
        echo_id = boost::lexical_cast<int>(local_args[0]);
        local_args.erase(local_args.begin());
      }
    catch(boost::bad_lexical_cast&) {}

    std::string echo_str =
      boost::algorithm::join(local_args," ");
    mkt::out(echo_id).stream() << echo_str;
    if(newline) mkt::out(echo_id).stream() << std::endl;
  }
}

//Echo API implementation
namespace mkt
{
  MKT_DEF_SIGNAL(echo_func_map_changed_signal, echo_function_registered);
  MKT_DEF_SIGNAL(echo_func_map_changed_signal, echo_function_unregistered);
  MKT_DEF_SIGNAL(echo_signal, echo_pre_exec);
  MKT_DEF_SIGNAL(echo_signal, echo_post_exec);

  void echo_register(int64 id, const echo_func& f)
  {
    thread_info ti(BOOST_CURRENT_FUNCTION);
    {
      unique_lock lock(echo_map_mutex_ref());
      echo_map_ref()[id] = f;
    }
    echo_function_registered()(id);
  }

  void echo_unregister(int64 id)
  {
    thread_info ti(BOOST_CURRENT_FUNCTION);
    {
      unique_lock lock(echo_map_mutex_ref());
      echo_map_ref()[id] = echo_func();
    }
    echo_function_unregistered()(id);
  }

  void echo(const std::string& str)
  {
    using namespace std;
    using namespace boost;
    using namespace boost::algorithm;

    thread_info ti(BOOST_CURRENT_FUNCTION);

    const mkt_str echo_functions_varname("sys_echo_functions");
    mkt_str echo_functions_value = get_var(echo_functions_varname);
    mkt::argument_vector echo_functions_strings;
    split(echo_functions_strings, echo_functions_value,
          is_any_of(","), token_compress_on);

    //execute each echo function
    for(auto&& echo_function_id_string : echo_functions_strings)
      {
        trim(echo_function_id_string);
        if(echo_function_id_string.empty()) continue;

        try
          {
            uint64 echo_function_id = lexical_cast<uint64>(echo_function_id_string);
            echo(echo_function_id, str);
          }
        catch(const bad_lexical_cast &)
          {
            throw system_error(boost::str(format("Invalid echo_function_id %1%")
                                          % echo_function_id_string));
          }
      }
  }

  void echo(uint64 echo_function_id, const std::string& str)
  {
    using namespace std;
    using namespace boost;

    thread_info ti(BOOST_CURRENT_FUNCTION);

    echo_pre_exec()(echo_function_id, str);
    {
      unique_lock lock(echo_map_mutex_ref());
      if(echo_map_ref()[echo_function_id])
        echo_map_ref()[echo_function_id](str);
    }
    echo_post_exec()(echo_function_id, str);
  }

  //the default echo function
  void do_echo(std::ostream* os, const std::string& str)
  {
    using namespace boost;
    thread_info ti(BOOST_CURRENT_FUNCTION);
    if(os && !get_var<bool>("sys_echo_quiet"))
      {
        (*os) << str;
      }
  }

  out::out(int64 echo_id) :
    _out(boost::iostreams::back_inserter(_result)),
    _id(echo_id)
  {}

  out::~out()
  {
    _out.flush();
    if(_id >= 0)
      echo(_id, _result);
    else echo(_result);
  }

  void init_echo()
  {
    using namespace std;
    using namespace mkt;
    add_command("echo", ::echo,
                "Prints out all arguments after echo to standard out.");

    //setup echo so it outputs to console
    echo_register(0, boost::bind(mkt::do_echo, &std::cout, _1));
    echo_register(1, boost::bind(mkt::do_echo, &std::cerr, _1));
#ifdef MKT_USING_XMLRPC
    echo_register(2, mkt::do_remote_echo);
#endif
    set_var("sys_echo_functions", mkt_str("0, 2"));
  }

  void final_echo()
  {
    // TODO: any cleanup
  }

  bool echo_at_exit() { return _echo_atexit; }
}


text:
import { $, ElementFinder, promise } from 'protractor';

export class ProductDetailPage {
 private get addToCardButton(): ElementFinder {
   return $('#add_to_cart > button > span');
 }

 public goToProductAdded(): promise.Promise<void> {
   return this.addToCardButton.click();
 }
}


text:
echo "Install JDK"
apt-fast install -y default-jdk > /dev/null

echo "Install Spark"
wget -q http://d3kbcqa49mib13.cloudfront.net/spark-2.0.0-bin-hadoop2.7.tgz -O spark.tgz
tar xzf spark.tgz
rm spark.tgz


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

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

	__webpack_require__(1046);
	module.exports = __webpack_require__(1046);

/***/ }),

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

	module.exports = function() { throw new Error("define cannot be used indirect"); };

/***/ }),

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

	module.exports = require("./runtime");

/***/ }),

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

	var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(f, define){
	    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(988) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	})(function(){
	    "use strict";

	    var $ = kendo.jQuery;

	    if (kendo.support.browser.msie && kendo.support.browser.version < 9) {
	        return;
	    }

	    var spreadsheet = kendo.spreadsheet;

	    var exports = {};
	    spreadsheet.validation = exports;
	    var calc = spreadsheet.calc;
	    var Class = kendo.Class;
	    var TRANSPOSE_FORMAT = "_matrix({0})";
	    var DATE_FORMAT = 'DATEVALUE("{0}")';

	    calc.runtime.defineFunction("_matrix", function(m){
	        if (typeof m == "string") {
	            // for constant list validation, Excel includes a string
	            // with comma-separated values — make a Matrix from it.
	            m = this.asMatrix([ m.split(/\s*,\s*/) ]);
	        }
	        return m;
	    }).args([
	        [ "m", [ "or", "matrix", "string" ] ]
	    ]);

	    function compileValidation(sheet, row, col, validation) {
	        var validationHandler;
	        var comparer;
	        var parsedFromDate;
	        var parsedToDate;

	        if (typeof validation === "string") {
	            validation = JSON.parse(validation);
	        }

	        if (validation.from) {
	            if (validation.dataType === "list" && !validation.fromIsListValue) {
	                validation.from = kendo.format(TRANSPOSE_FORMAT, validation.from);
	                validation.fromIsListValue = true;
	            }

	            if (validation.dataType === "date") {
	                parsedFromDate = calc.runtime.parseDate(validation.from);
	                if (parsedFromDate) {
	                    validation.from = kendo.format(DATE_FORMAT, validation.from);
	                    validation.fromIsDateValue = true;
	                }
	            }

	            validation.from = calc.compile(calc.parseFormula(sheet, row, col, validation.from));
	        }

	        if (validation.to) {
	            if (validation.dataType === "date") {
	                parsedToDate = calc.runtime.parseDate(validation.to);
	                if (parsedToDate) {
	                    validation.to = kendo.format(DATE_FORMAT, validation.to);
	                    validation.toIsDateValue = true;
	                }
	            }

	            validation.to = calc.compile(calc.parseFormula(sheet, row, col, validation.to));
	        }

	        if (validation.dataType == "custom") {
	            comparer = exports.validationComparers.custom;
	        } else if (validation.dataType == "list") {
	            comparer = exports.validationComparers.list;
	        } else {
	            comparer = exports.validationComparers[validation.comparerType];
	        }

	        if (!comparer) {
	            throw kendo.format("'{0}' comparer is not implemented.", validation.comparerType);
	        }

	        validationHandler = function (valueToCompare) { //add 'valueFormat' arg when add isDate comparer
	            var toValue = this.to && this.to_value ? this.to_value : undefined;

	            if (valueToCompare === null || valueToCompare === "") {
	                if (this.allowNulls) {
	                    this.value = true;
	                } else {
	                    this.value = false;
	                }
	            } else if (this.dataType == "custom") {
	                this.value = comparer(valueToCompare, this.from_value,  toValue);
	            } else if (this.dataType == "list") {
	                var data = this._getListData();

	                this.value = comparer(valueToCompare, data, toValue);
	            } else {
	                //TODO: TYPE CHECK IS REQUIRED ONLY FOR DATE TYPE WHEN SPECIAL COMPARER (ISDATE) IS USED
	                this.value = comparer(valueToCompare, this.from_value,  toValue);
	            }

	            return this.value;
	        };

	        return new kendo.spreadsheet.validation.Validation($.extend(validation, {
	            handler: validationHandler,
	            sheet: sheet,
	            row: row,
	            col: col
	        }));
	    }

	    var Validation = Class.extend({
	        init: function Validation(options){
	            this.handler = options.handler;
	            this.from = options.from;
	            this.to = options.to;
	            this.dataType = options.dataType; //date, time etc
	            this.comparerType =  options.comparerType; //greaterThan, EqaulTo etc
	            this.type = options.type ? options.type : "warning"; //info, warning, reject
	            this.allowNulls = options.allowNulls ? true : false;
	            this.fromIsDateValue = options.fromIsDateValue ? true : false;
	            this.toIsDateValue = options.toIsDateValue ? true : false;
	            this.showButton = options.showButton;
	            this.fromIsListValue = options.fromIsListValue ? true : false;

	            //TODO: address to be range / cell ref, and adjust it based on it
	            this.sheet = options.sheet;
	            this.row = options.row;
	            this.col = options.col;

	            if (options.tooltipMessageTemplate) {
	                this.tooltipMessageTemplate = options.tooltipMessageTemplate;
	            }

	            if (options.tooltipTitleTemplate) {
	                this.tooltipTitleTemplate = options.tooltipTitleTemplate;
	            }

	            if (options.messageTemplate) {
	                this.messageTemplate = options.messageTemplate;
	            }

	            if (options.titleTemplate) {
	                this.titleTemplate = options.titleTemplate;
	            }
	        },

	        _formatMessages: function(format) {
	            var from = this.from ? this.from_value : "";
	            var to = this.to ? this.to_value : "";

	            var fromFormula = this.from ? this.from.toString() : "";
	            var toFormula = this.to ? this.to.toString() : "";
	            var dataType = this.dataType;
	            var type = this.type;
	            var comparerType = this.comparerType;

	            return kendo.format(format, from, to, fromFormula, toFormula, dataType, type, comparerType);
	        },

	        _setMessages: function() {
	            this.title = "";
	            this.message = "";

	            if (this.tooltipTitleTemplate) {
	                this.tooltipTitle = this._formatMessages(this.tooltipTitleTemplate);
	            }

	            if (this.tooltipMessageTemplate) {
	                this.tooltipMessage = this._formatMessages(this.tooltipMessageTemplate);
	            }

	            if (this.titleTemplate) {
	                this.title = this._formatMessages(this.titleTemplate);
	            }

	            if (this.messageTemplate) {
	                this.message = this._formatMessages(this.messageTemplate);
	            }
	        },

	        _getListData: function() {
	            if (!this.from_value || !this.from_value.data) {
	                return [];
	            }

	            var cube = this.from_value.data;
	            var i;
	            var y;
	            var data = [];

	            for (i = 0; i < cube.length; i++ ) {
	                var array = cube[i];

	                if (array) {
	                    for (y = 0; y < array.length; y++ ) {
	                        data.push(array[y]);
	                    }
	                }
	            }

	            return data;
	        },

	        clone: function(sheet, row, col) {
	            var options = this._getOptions();

	            if (options.from) {
	                options.from = options.from.clone(sheet, row, col);
	            }

	            if (options.to) {
	                options.to = options.to.clone(sheet, row, col);
	            }

	            return new Validation($.extend(options,
	                { handler: this.handler },
	                { sheet: sheet, row: row, col: col }
	            ));
	        },

	        exec: function(ss, compareValue, compareFormat, callback) {
	            var self = this;

	            function getValue(val) {
	                if (val instanceof kendo.spreadsheet.Ref) {
	                    val = ss.getData(val);
	                    if (Array.isArray(val)) {
	                        val = val[0];
	                    }
	                }
	                return val;
	            }

	            var calculateFromCallBack = function(val) {
	                self.from_value = getValue(val);
	                self.value = self.handler.call(self, compareValue, compareFormat);
	                self._setMessages();
	                if (callback) {
	                    callback(self.value);
	                }
	            };

	            if (self.to) {
	                self.to.exec(ss, function(val) {
	                    self.to_value = getValue(val);
	                    self.from.exec(ss, calculateFromCallBack);
	                });
	            } else {
	                self.from.exec(ss, calculateFromCallBack);
	            }
	        },

	        reset: function() {
	            if (this.from) {
	                this.from.reset();
	            }
	            if (this.to) {
	                this.to.reset();
	            }
	            delete this.value;
	        },

	        adjust: function(affectedSheet, operation, start, delta) {
	            if (this.from) {
	                this.from.adjust(affectedSheet, operation, start, delta);
	            }
	            if (this.to) {
	                this.to.adjust(affectedSheet, operation, start, delta);
	            }
	            if (this.sheet.toLowerCase() == affectedSheet.toLowerCase()) {
	                var formulaRow = this.row;
	                var formulaCol = this.col;
	                switch (operation) {
	                  case "row":
	                    if (formulaRow >= start) {
	                        this.row += delta;
	                    }
	                    break;
	                  case "col":
	                    if (formulaCol >= start) {
	                        this.col += delta;
	                    }
	                    break;
	                }
	            }
	        },

	        toJSON: function() {
	            var options = this._getOptions();

	            if (options.from) {
	                options.from = options.from.toString();

	                if (options.dataType === "list") {
	                    options.from = options.from.replace(/^_matrix\((.*)\)$/i, "$1");
	                    delete options.fromIsListValue;
	                }

	                if (options.dataType === "date") {
	                    if (this.fromIsDateValue) {
	                        options.from = options.from.replace(/^DATEVALUE\("(.*)"\)$/i, "$1");
	                        delete options.fromIsDateValue;
	                    }
	                }
	            }

	            if (options.to) {
	                options.to = options.to.toString();

	                if (options.dataType === "date") {
	                    if (this.toIsDateValue) {
	                        options.to = options.to.replace(/^DATEVALUE\("(.*)"\)$/i, "$1");
	                        delete options.toIsDateValue;
	                    }
	                }
	            }

	            return options;
	        },

	        _getOptions: function () {
	            return {
	                from: this.from,
	                to: this.to,
	                dataType: this.dataType,
	                type: this.type,
	                comparerType: this.comparerType,
	                row: this.row,
	                col: this.col,
	                sheet: this.sheet,
	                allowNulls: this.allowNulls,
	                fromIsListValue: this.fromIsListValue,
	                fromIsDateValue: this.fromIsDateValue,
	                toIsDateValue: this.toIsDateValue,
	                tooltipMessageTemplate: this.tooltipMessageTemplate,
	                tooltipTitleTemplate: this.tooltipTitleTemplate,
	                //TODO: export generated messages instead?
	                messageTemplate: this.messageTemplate,
	                titleTemplate: this.titleTemplate,
	                showButton: this.showButton
	            };
	        }
	    });
	    exports.compile = compileValidation;
	    exports.validationComparers = {
	        greaterThan: function (valueToCompare, from) {
	            return valueToCompare > from;
	        },

	        lessThan: function (valueToCompare, from) {
	            return valueToCompare < from;
	        },

	        between: function (valueToCompare, from, to) {
	            return valueToCompare >= from && valueToCompare <= to;
	        },

	        equalTo: function (valueToCompare, from) {
	            return valueToCompare == from;
	        },

	        notEqualTo: function (valueToCompare, from) {
	            return valueToCompare != from;
	        },

	        greaterThanOrEqualTo: function (valueToCompare, from) {
	            return valueToCompare >= from;
	        },

	        lessThanOrEqualTo: function (valueToCompare, from) {
	            return valueToCompare <= from;
	        },

	        notBetween: function (valueToCompare, from, to) {
	            return valueToCompare < from || valueToCompare > to;
	        },

	        custom: function (valueToCompare, from) {
	            return from;
	        },

	        list: function (valueToCompare, data) {
	            return data.indexOf(valueToCompare) > -1;
	        }
	    };

	    exports.Validation = Validation;

	}, __webpack_require__(3));

/***/ })

/******/ });


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>AWS IoT Embedded C Device SDK: aws_iot_shadow_actions.c File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

AWS IoT Embedded C Device SDK

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

src

Functions

aws_iot_shadow_actions.c File Reference

Shadow client Action API definitions.
More...

#include "aws_iot_shadow_actions.h"

#include "aws_iot_log.h"

#include "aws_iot_shadow_json.h"

#include "aws_iot_shadow_records.h"

#include "aws_iot_config.h"

Functions

IoT_Error_t 	aws_iot_shadow_internal_action (const char *pThingName, ShadowActions_t action, const char *pJsonDocumentToBeSent, fpActionCallback_t callback, void *pCallbackContext, uint32_t timeout_seconds, bool isSticky)

<address class="footer">
Generated by

 1.8.10
</address>


text:
export default class Grid {

    constructor ( Client, size ) {
        this.Client      = Client;
        this.enabled     = true;
        this.gridSize    = size;
        this.snap_assets = true;
        this.color       = '#CCCCCC';
        this.grid        = $( '#grid' );
    }

    enable () {
        this.enabled = true;
        this.draw();
    }

    disable () {
        this.enabled = false;
        this.remove();
    }

    draw () {
        console.log( 'Drawing grid' );

        let width  = this.grid.width(),
            height = this.grid.height();

        for ( let i = 0; (this.gridSize.x + i) < (width + this.gridSize.x); i += this.gridSize.x ) {
            for ( let v = 0; (this.gridSize.y + v) < (height + this.gridSize.y); v += this.gridSize.y ) {
                this.grid.append( $( '

' ).css( {
                    width:       this.gridSize.x + 'px',
                    height:      this.gridSize.y + 'px',
                    left:        i + 'px',
                    top:         v + 'px',
                    borderColor: this.color
                } ) );
            }
        }

        return this;
    }

    remove () {
        this.grid.empty();

        return this;
    }

    setSize ( size ) {
        if ( typeof size !== "object" ) {
            throw new Error( 'Invalid size, expecting object received ' + (typeof size) );
        }
        this.gridSize = size;

        // Redraw
        this.remove();
        this.draw();
    }

    getSize () {
        return this.gridSize;
    }

    snapAssets () {
        return this.snap_assets;
    }

    snapToGrid ( position ) {
        if ( !this.snap_assets ) {
            return position;
        }

        return {
            x: position.x - (position.x % this.gridSize.x),
            y: position.y - (position.y % this.gridSize.y)
        };
    }

    editGrid () {
        this.Client.Popup
            .clear()
            .setHeader( 'Edit Grid' )
            .setBody( [
                {label: 'Enable', type: 'checkbox', name: 'grid_enabled', value: this.enabled},
                {label: 'Snap Assets', type: 'checkbox', name: 'grid_snap', value: this.snap_assets},
                {label: 'Width', type: 'text', name: 'grid_width', value: this.gridSize.x},
                {label: 'Height', type: 'text', name: 'grid_height', value: this.gridSize.y},
                {label: 'Color', type: 'text', name: 'grid_color', value: this.color}
            ] )
            .setFooter( null, null, this.saveSettings.bind( this ) )
            .openPopup();
    }

    saveSettings ( settings ) {
        console.log( 'Save grid settings', settings );

        this.enabled     = !!(settings.grid_enabled && settings.grid_enabled == "on");
        this.snap_assets = !!(settings.grid_snap && settings.grid_snap == "on");

        if ( settings.grid_width ) {
            this.gridSize.x = parseInt( settings.grid_width );
        }
        if ( settings.grid_height ) {
            this.gridSize.y = parseInt( settings.grid_height );
        }
        if ( settings.grid_color ) {
            this.color = settings.grid_color;
        }

        this.Client.Assets.snapAssets( this.snapAssets() ? [ this.gridSize.x, this.gridSize.y ] : false );

        // Redraw if grid is enabled
        this.remove();
        if ( this.enabled ) {
            this.draw();
        }
    }

}


text:
angular.module('Chat')

    .controller('indexCtrl', function($scope){
       $scope.message = "Hello"
    });


text:
//  Copyright 2008, 2009 The Apache Software Foundation
//
// 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.

package org.apache.tapestry5.ioc.internal;

import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.ioc.OperationTracker;

/**
 * Minimal implementation used for testing, that does no logging, tracking, or exception catching.
 */
public class QuietOperationTracker implements OperationTracker
{
    public void run(String description, Runnable operation)
    {
        operation.run();
    }

    public <T> T invoke(String description, Invokable<T> operation)
    {
        return operation.invoke();
    }
}


text:
char * const UIBarButtonItemYNActionBlock = "UIBarButtonItemYNActionBlock";
#import "UIBarButtonItem+YNAction.h"
#import <objc/runtime.h>

@implementation UIBarButtonItem (ynAction)

- (void)yn_performActionBlock {

    dispatch_block_t block = self.yn_actionBlock;

    if (block)
        block();

}

- (BarButtonYNActionBlock)yn_actionBlock {
    return objc_getAssociatedObject(self, UIBarButtonItemYNActionBlock);
}

- (void)setYn_actionBlock:(BarButtonYNActionBlock)actionBlock
 {

    if (actionBlock != self.yn_actionBlock) {
        [self willChangeValueForKey:@"yn_actionBlock"];

        objc_setAssociatedObject(self,
                                 UIBarButtonItemYNActionBlock,
                                 actionBlock,
                                 OBJC_ASSOCIATION_COPY);

        // Sets up the action.
        [self setTarget:self];
        [self setAction:@selector(yn_performActionBlock)];

        [self didChangeValueForKey:@"yn_actionBlock"];
    }
}
@end


text:
package com.armadialogcreator.control.impl.utility;

import com.armadialogcreator.canvas.Region;
import com.armadialogcreator.control.ArmaControl;
import com.armadialogcreator.control.ArmaControlRenderer;
import com.armadialogcreator.core.ConfigPropertyLookupConstant;
import com.armadialogcreator.core.sv.SVColor;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.jetbrains.annotations.NotNull;

/**
 @author Kayler
 @since 07/04/2017 */
public class TooltipRenderer implements BasicTextRenderer.UpdateCallback {
	private static final Font TOOLTIP_FONT = Font.font(14);
	private final ArmaControl control;
	private Color backgroundColor = null;
	private Color borderColor = null;

	private final BasicTextRenderer textRenderer;

	public TooltipRenderer(@NotNull ArmaControl control, @NotNull ArmaControlRenderer renderer,
						   @NotNull ConfigPropertyLookupConstant tooltipBackgroundColor,
						   @NotNull ConfigPropertyLookupConstant tooltipTextColor,
						   @NotNull ConfigPropertyLookupConstant tooltipBorderColor,
						   @NotNull ConfigPropertyLookupConstant tooltipText
	) {
		this.control = control;
		textRenderer = new BasicTextRenderer(
				control, renderer, tooltipText, tooltipTextColor, null, null, null,
				false, this
		);
		textRenderer.setFont(TOOLTIP_FONT);
		control.findProperty(tooltipBackgroundColor).getValueObserver().addListener((observer, oldValue, newValue) ->
		{
			if (newValue instanceof SVColor) {
				backgroundColor = ((SVColor) newValue).toJavaFXColor();
			} else {
				backgroundColor = null;
			}
			requestRender();
		});
		control.findProperty(tooltipBorderColor).getValueObserver().addListener((observer, oldValue, newValue) -> {
			if (newValue instanceof SVColor) {
				borderColor = ((SVColor) newValue).toJavaFXColor();
			} else {
				borderColor = null;
			}
			requestRender();
		});
	}

	public void paint(GraphicsContext gc, int tooltipX, int tooltipY) {
		if (backgroundColor == null || borderColor == null || textRenderer.getText().length() == 0) {
			return;
		}
		gc.save();

		int textWidth = textRenderer.getTextWidth();
		int textHeight = textRenderer.getTextLineHeight();
		tooltipY = tooltipY - textHeight * 2;
		int padding = 5;
		int tooltipX2 = tooltipX + textWidth + padding + padding;
		int tooltipHeight = textHeight + padding + padding;
		int tooltipY2 = tooltipY + tooltipHeight;

		gc.setStroke(backgroundColor);
		Region.fillRectangle(gc, tooltipX, tooltipY, tooltipX2, tooltipY2);
		gc.setStroke(borderColor);
		Region.strokeRectangle(gc, tooltipX, tooltipY, tooltipX2, tooltipY2);

		textRenderer.paint(gc, tooltipX + padding, tooltipY + padding);

		gc.restore();
	}

	private void requestRender() {
		control.getRenderer().requestRender();
	}
}


text:
@implementation NSXMLParserRACElement

- (id)init
{
    self = [super init];
    if (self) {
        self.body = [@"" mutableCopy];
    }
    return self;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Computers.UI.Console.Interfaces;

namespace Computers.UI.Console.Components
{
    class Raid:IStorage
    {
      //  private int _capacity;

        public Raid(List<HardDrive> raidDrives)
        {

            HardDrives = new List<HardDrive>();
        }

        public int Capacity
        {

            get
            {
                if (!HardDrives.Any())
                {
                    return 0;
                }
                return this.HardDrives.FirstOrDefault().Capacity;
            }

        }

        public IList<HardDrive> HardDrives { get; private set; }

        public void SaveData(int address, string newData)
        {
            foreach (var hardDrive in HardDrives)
            {
                hardDrive.SaveData(address,newData);
            }
        }

        public string LoadData(int address)
        {
            if (!this.HardDrives.Any())
            {
                throw new OutOfMemoryException("No hard drive in the RAID array!");
            }
            return this.HardDrives.First().LoadData(address);
        }
    }
}


text:
package com.intellij.codeInsight.daemon.impl;

import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.FunctionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Danila Ponomarenko
 */
public class RecursiveCallLineMarkerProvider extends LineMarkerProviderDescriptor {

  @Override
  public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) {
    return null; //do nothing
  }

  @Override
  public void collectSlowLineMarkers(@NotNull List<PsiElement> elements,
                                     @NotNull Collection<LineMarkerInfo> result) {
    final Set<PsiStatement> statements = new HashSet<>();

    for (PsiElement element : elements) {
      ProgressManager.checkCanceled();
      if (element instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element;
        final PsiStatement statement = PsiTreeUtil.getParentOfType(methodCall, PsiStatement.class, true, PsiMethod.class);
        if (!statements.contains(statement) && isRecursiveMethodCall(methodCall)) {
          statements.add(statement);
          ContainerUtil.addIfNotNull(result, RecursiveMethodCallMarkerInfo.create(methodCall));
        }
      }
    }
  }

  public static boolean isRecursiveMethodCall(@NotNull PsiMethodCallExpression methodCall) {
    final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression();
    if (qualifier != null && !(qualifier instanceof PsiThisExpression)) {
      return false;
    }

    final PsiMethod method = PsiTreeUtil.getParentOfType(methodCall, PsiMethod.class, true, PsiLambdaExpression.class, PsiClass.class);
    if (method == null || !method.getName().equals(methodCall.getMethodExpression().getReferenceName())) {
      return false;
    }

    return Comparing.equal(method, methodCall.resolveMethod());
  }

  @NotNull
  @Override
  public String getName() {
    return CodeInsightBundle.message("recursive.call");
  }

  @Nullable
  @Override
  public Icon getIcon() {
    return AllIcons.Gutter.RecursiveMethod;
  }

  private static class RecursiveMethodCallMarkerInfo extends LineMarkerInfo<PsiElement> {
    private static RecursiveMethodCallMarkerInfo create(@NotNull PsiMethodCallExpression methodCall) {
      PsiElement nameElement = methodCall.getMethodExpression().getReferenceNameElement();
      if (nameElement != null) {
        return new RecursiveMethodCallMarkerInfo(nameElement);
      }
      return null;
    }

    private RecursiveMethodCallMarkerInfo(@NotNull PsiElement name) {
      super(name,
            name.getTextRange(),
            AllIcons.Gutter.RecursiveMethod,
            Pass.LINE_MARKERS,
            FunctionUtil.constant("Recursive call"),
            null,
            GutterIconRenderer.Alignment.RIGHT
      );
    }

    @Override
    public GutterIconRenderer createGutterRenderer() {
      if (myIcon == null) return null;
      return new LineMarkerGutterIconRenderer<PsiElement>(this){
        @Override
        public AnAction getClickAction() {
          return null; // to place breakpoint on mouse click
        }
      };
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="images/favicon.ico">

    <title>GSC Brasil - Educação Corporativa</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/carousel.css" rel="stylesheet">
    <link href="css/gsc.css" rel="stylesheet">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>

Home

Empresa

Consultores

Clientes

Parcerias

Imprensa

                  Inscreva-se

Inscrição Online

Cursos in-company

Contato

Agenda

            1º semestre
            2º semestre

Cursos

            Recursos Humanos8
            Logística & Transportes12
            Gestão de Negócios2
            Marketing & Vendas4
            Administrativo5
            Financeiro16
            Setor Público8
            Gestão Empresarial7
            Infra-estrutura7
            Tecnologia da Informação6
            Gestão Ambiental3
            Secretariado4

Treinamentos In-company

Temos um programa de treinamentos In-Company para oferecer treinamentos personalizados, adaptados às necessidades da sua empresa. Solicite uma pré-proposta preenchendo o formulário abaixo.

                <form action="http://www.gscbrasil.com.br/cgi-sys/FormMail.cgi" method="POST">
                  <input type="hidden" name="recipient" value="atendimento@gscbrasil.com.br">
                  <input type="hidden" name="subject" value="In-company">
                  <input type="hidden" name="REPLY-TO" value="atendimento@gscbrasil.com.br">
                  <input type="hidden" name="redirect" value="http://www.gscbrasil.com.br/portal/conf_contato.html">

                    Nome:
                    <input name="nome" type="text" id="nome" class="form-control">

                    Telefone para contato (99) 9999-9999:
                    <input name="telefone" type="text" id="telefone" class="form-control">

                    E-mail:
                    <input name="email" type="text" id="e-mail" class="form-control">

                    Empresa:
                    <input name="empresa" type="text" id="empresa" class="form-control">

                    Utilize o espaço abaixo para fazer comentários sobre as características gerais do curso (Número de pessoas, carga horária, tópicos que devem ser abordados, etc):
                    <textarea name="observacoes" id="observacoes" class="form-control"></textarea>

                    <input name="enviar" type="submit" id="enviar" value="Enviar" class="btn btn-primary">
                    <input name="Limpar" type="reset" id="Limpar" value="Limpar" class="btn btn-default">

                </form>

© 2014 GSC Brasil LTDA · Sobre · Contato


text:
<!DOCTYPE html>

 <link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<meta name="twitter:title" content="Paride">
<meta name="twitter:description" content="">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://archeostickers.com/images/28_paride.png">

  <meta content="ARCHEOSTICKERS" property="og:site_name">

  <meta content="Paride" property="og:title">

  <meta content="article" property="og:type">

  <meta content="Le archeostickers sono un pacchetto di stickers per Telegram e un riuso di immagini libere tratte da Wikipedia. Le archeostickers sono state ideate e realizzate da opensensorsdata in collaborazione con Professione Archeologo e ArcheoPop per promuovere e riusare i dati liberi di arte e archeologia" property="og:description">

  <meta content="http://archeostickers.com/pages/about/" property="og:url">

  <meta content="2015-09-25T12:36:00+02:00" property="article:published_time">
  <meta content="http://archeostickers.com/about/" property="article:author">

  <meta content="http://archeostickers.com/public/images/stickers/28_paride.png" property="og:image">

  <meta content="uomo" property="article:tag">

  <meta content="mitologia" property="article:tag">

  <meta content="1151787705" property="fb:admins"

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

<title>

    Paride · ARCHEOSTICKERS

</title>

<link rel="stylesheet" href="/public/css/archeo_poole.css">
<link rel="stylesheet" href="/public/css/syntax.css">
<link rel="stylesheet" href="/public/css/archeo_hyde.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
<link href='https://fonts.googleapis.com/css?family=Quattrocento:400,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'>

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/images/apple-touch-icon-144-precomposed.png">
<link rel="shortcut icon" href="/public/images/favicon.ico">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                               <link rel="shortcut icon" href="/public/favicon.ico">

<link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

ARCHEOSTICKERS

      Archeologia e arte distillate in sticker

      <a class="sidebar-nav-item"

            About

            Archivio

            Istruzioni

 |  |

credits

 2015 archeostickers crew

 -BY-SA

Paride

    25 Sep 2015 // archeosticker #28

      Attaccala questa #archeosticker su
       Twitter
       Facebook

         uomo,

         mitologia

           Paride su Wikipedia
           Fonte di Paride su   Wikimedia Commons

         assemblata da:
          luca corsato

         idea di:
          luca corsato

 Scarica 28_paride.svg da Github

 Istruzioni per scaricare e riusare i file

Le archeosticker sono distribuite con Licenza Creative Commons Attribuzione - Condividi allo stesso modo 4.0 Internazionale.

  Please enable JavaScript to view the comments powered by Disqus.

Related Posts

              Atlante
              05 Oct 2015

              Tre Grazie
              30 Sep 2015

              Mitra
              29 Sep 2015

 ARCHEOSTICKERS is  brought to you by opensensorsdata under -BY-SA

 2015 opensensorsdata srl VAT IVA 04294660271

 contact@opensensorsdata.it

 pec (certified email only for Italy) opensensorsdata@pec.it

Privacy Policy

cookie policy

site version1.0.0


text:
package org.onosproject.incubator.net.tunnel;

import com.google.common.annotations.Beta;
import org.onosproject.store.StoreDelegate;

/**
 * Tunnel store delegate abstraction.
 */
@Beta
public interface TunnelStoreDelegate extends StoreDelegate<TunnelEvent> {
}


text:
using System;
using System.Threading.Tasks;
using ManneDoForms.Components.VideoView;
using Plugin.Media;
using Xamarin.Forms;

namespace ManneDoForms.Samples
{
    public class RecordAndPlayVideoPage : ContentPage
    {
        private readonly AbsoluteLayout _parentContainer;
        private Button _button;
        private ManneVideoView _videoView;

        public RecordAndPlayVideoPage()
        {
            // Create Container
            _parentContainer = new AbsoluteLayout
            {
                BackgroundColor = Color.White,
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };

            // Create Button
            _button = new Button
            {
                Text = "Record!"
            };

            AbsoluteLayout.SetLayoutFlags(_button, AbsoluteLayoutFlags.PositionProportional);
            AbsoluteLayout.SetLayoutBounds(_button, new Rectangle(0.5f, 0.5f, 100f, AbsoluteLayout.AutoSize));

            _button.Clicked += async (sender, e) =>
            {
                await RecordVideo();
            };

            _parentContainer.Children.Add(_button);

            // Create Video View
            _videoView = new ManneVideoView { IsVisible = false };

            AbsoluteLayout.SetLayoutFlags(_videoView, AbsoluteLayoutFlags.All);
            AbsoluteLayout.SetLayoutBounds(_videoView, new Rectangle(0f, 0f, 1f, 1f));

            _parentContainer.Children.Add(_videoView);

            // Finish
            Content = _parentContainer;
        }

        protected async override void OnAppearing()
        {
            base.OnAppearing();

            await CrossMedia.Current.Initialize();
        }

        private async Task RecordVideo()
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("Recorder", "No camera available", "OK");
                return;
            }

            var filename = $"{Guid.NewGuid().ToString()}.mp4";
            var file = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
            {
                Name = filename
            });

            if (file == null)
            {
                await DisplayAlert("Recorder", "The recording was canceled or an error occured", "OK");
                return;
            }

            PlayVideo(file.Path);
        }

        private void PlayVideo(string localFilePath)
        {
            _button.IsVisible = false;
            _videoView.IsVisible = true;

            _videoView.Url = localFilePath;
        }
    }
}


text:
describe("Names API", function () {

    var namesApi;

    beforeEach(function () {
        var fakeRouter = new FakeRouter();
        namesApi = new ozpIwc.api.names.Api({
            authorization: ozpIwc.wiring.authorization,
            'name': "names.test.api",
            'participant': new TestClientParticipant({
                authorization: ozpIwc.wiring.authorization,
                router: fakeRouter
            }),
            'router': fakeRouter
        });
        namesApi.isRequestQueueing = false;
        namesApi.leaderState = "leader";
    });

    afterEach(function () {
        namesApi = null;
    });

    it("responds with badResource for arbitrary resources", function () {
        var context = new TestPacketContext({
            'leaderState': "leader",
            'packet': {
                'resource': "/doesNotExist",
                'action': "get",
                'msgId': "1234",
                'src': "srcParticipant"
            }
        });
        namesApi.receivePacketContext(context);
        expect(context.responses[0].response).toEqual("badResource");
    });

    [{
        'resource': "/address",
        'contentType': "application/json",
        'entity': []
    }, {
        'resource': "/multicast",
        'contentType': "application/json",
        'entity': []
    }, {
        'resource': "/router",
        'contentType': "application/json",
        'entity': []
    }, {
        'resource': "/api",
        'contentType': "application/json",
        'entity': [
            "/api/data.api",
            "/api/intents.api",
            "/api/names.api",
            "/api/system.api",
            "/api/locks.api"
        ]
    }
    ].forEach(function (r) {
            describe("Resource tree root " + r.resource, function () {
                var contextFor = function (action) {
                    return new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource,
                            'action': action,
                            'msgId': "1234",
                            'src': "srcParticipant"
                        }
                    });
                };

                it("replies to get", function () {
                    var context = contextFor("get");
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("ok");
                    expect(context.responses[0].entity).toEqual(r.entity);
                    expect(context.responses[0].contentType).toEqual(r.contentType);
                });

                it("replies to list", function () {
                    var context = contextFor("list");
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("ok");
                    expect(context.responses[0].entity).toEqual(r.entity);
                    expect(context.responses[0].contentType).toEqual(r.contentType);
                });

                it("replies to bulkGet", function () {
                    var context = contextFor("bulkGet");
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("ok");
                    expect(
                        context.responses[0].entity.map(function (e) {
                            return e.resource;
                        })
                    ).toEqual(r.entity);
                    expect(context.responses[0].contentType).toEqual(r.contentType);
                });

                it("responds with noPermission when attempting to set", function () {
                    var context = new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource,
                            'action': "set",
                            'msgId': "1234",
                            'src': "srcParticipant",
                            'entity': {'foo': 1}
                        }
                    });
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("noPermission");
                });
            });
        });

    [{
        'resource': "/address",
        'contentType': "application/vnd.ozp-iwc-address-v1+json",
        'listContentType': "application/json"
    }, {
        'resource': "/multicast",
        'contentType': "application/vnd.ozp-iwc-multicast-address-v1+json",
        'listContentType': "application/json"
    }, {
        'resource': "/api",
        'contentType': "application/vnd.ozp-iwc-api-v1+json",
        'listContentType': "application/json"
    }, {
        'resource': "/router",
        'contentType': "application/vnd.ozp-iwc-router-v1+json",
        'listContentType': "application/json"
    }
    ].forEach(function (r) {
            describe("Resource tree " + r.resource, function () {

                it("allows  " + r.contentType + " when setting a value in the tree", function () {
                    var context = new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource + "/testValue",
                            'contentType': r.contentType,
                            'action': "set",
                            'msgId': "1234",
                            'src': "srcParticipant",
                            'entity': {'foo': 1}
                        }
                    });
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("ok");

                });

                it("updates the collection when setting a value in the tree", function () {
                    var resourceName = r.resource + "/testValue";
                    namesApi.data[resourceName] = new ozpIwc.api.base.Node({
                        'resource': resourceName,
                        'contentType': r.contentType,
                        'entity': {'foo': 1}
                    });
                    var context = new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource,
                            'action': "get",
                            'msgId': "1234",
                            'src': "srcParticipant"
                        }
                    });
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("ok");
                    expect(context.responses[0].entity).toContain(r.resource + "/testValue");
                    expect(context.responses[0].contentType).toEqual(r.listContentType);
                });

                it("responds with badContent when missing the contentType", function () {
                    var context = new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource + "/testValue",
                            'action': "set",
                            'msgId': "1234",
                            'src': "srcParticipant",
                            'entity': {'foo': 1}
                        }
                    });
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("badContent");

                });

                it("responds with badContent with invalid contentType", function () {
                    var context = new TestPacketContext({
                        'leaderState': "leader",
                        'packet': {
                            'resource': r.resource + "/testValue",
                            'action': "set",
                            'contentType': r.contentType + "+xml",
                            'msgId': "1234",
                            'src': "srcParticipant",
                            'entity': {'foo': 1}
                        }
                    });
                    namesApi.receivePacketContext(context);
                    expect(context.responses[0].response).toEqual("badContent");
                });

            });
        });
});


text:
package org.python.types;

public class Dict_KeyIterator extends org.python.types.Iterator {
    public Dict_KeyIterator(org.python.types.Dict dict) {
        this.iterator = dict.value.keySet().iterator();
    }
}


text:
require 'spec_helper'

describe Player do
  describe '#create' do
    context 'when valid input is given' do
      before do
        @player = build(:player)
      end
      subject { @player }
      it 'should be saved correctly' do
        expect(subject.save).to be_true
      end
    end
    context 'when invalid input is given' do
      it 'should fail if name is empty' do
        expect(build(:player, name: '').save).to be_false
      end
      it 'should fail if password is empty' do
        p = build(:player)
        p.password = ''
        expect(p.save).to be_false
      end
    end
  end

  describe '#register_score' do
    before do
      @player = create(:player)
      @season = create(:season)
      @music = create(:music)
    end
    subject { @score }

    context 'when no scores are registered' do
      before do
        @score = @player.register_score(season: @season, music: @music, difficulty: 'HARD', score: 334, playstyle: 'SP')
        @score.save!
      end
      it 'correctly adds score' do
        expect(subject).not_to be nil
        expect(subject.season).to eq @season
        expect(subject.music).to eq @music
        expect(subject.difficulty).to eq 'HARD'
        expect(subject.playstyle).to eq 'SP'
        expect(subject.score).to eq 334
      end
    end
    context 'when scores for the same music is registered' do
      before do
        @score = @player.register_score(season: @season, music: @music, difficulty: 'HARD', score: 334, playstyle: 'SP')
        @score.save!
      end

      context 'if the score is greater than before' do
        before do
          @score = @player.register_score(season: @season, music: @music, difficulty: 'HARD', score: 668, playstyle: 'SP')
          @score.save!
        end
        it 'updates score' do
          expect(subject.score).to eq 668
        end
      end

      context 'if the score is lower than before' do
        before do
          @score = @player.register_score(season: @season, music: @music, difficulty: 'HARD', score: 1, playstyle: 'SP')
          @score.save!
        end
        it 'does nothing' do
          expect(subject.score).not_to eq 1
        end
      end
    end
  end
end


text:
/* extra data left in internal buffers
   need to give node a "kick" to tell it we're
   interested in more data past the 3 bytes that is read
*/

// simple `.read(0) will do this

process.stdin.on('readable', function() {
	var buf = process.stdin.read(3);
	console.dir(buf);
	process.stdin.read(0);
});

// code works as expected in 3-byte chunks


text:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';
    protected $namespaceapi = "App\Http\Controllers\API";
    protected $namespacelogin = "App\Http\Controllers\Login";

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapLoginRoutes();
        //$this->mapWebRoutes();
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::domain(config("app.url"))
            ->middleware(["web", "api"])
            ->namespace($this->namespaceapi)
            ->group(base_path("routes/api.php"));
    }

    protected
    function mapLoginRoutes()
    {
        Route::domain(config("app.loginUrl"))
            ->namespace($this->namespacelogin)
            ->middleware("web")
            ->group(base_path("routes/login.php"));
    }
}


text:
layout: post
title: "Run Multiple Rails Servers at the Same Time on Your Computer"
date: 2011-06-15 00:16:35
comments: true
categories:
---

Ever wondered how to run multiple instances of rails server? Below is the snippet to do that.

``` ruby
    #rails s -p port number
    rails s -p 3001 #for example
```


text:
#include "ZeroCrossingCounter.h"

namespace GRT{

//Register the ZeroCrossingCounter module with the FeatureExtraction base class
RegisterFeatureExtractionModule< ZeroCrossingCounter > ZeroCrossingCounter::registerModule("ZeroCrossingCounter");

ZeroCrossingCounter::ZeroCrossingCounter(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode){

    classType = "ZeroCrossingCounter";
    featureExtractionType = classType;
    debugLog.setProceedingText("[DEBUG ZeroCrossingCounter]");
    errorLog.setProceedingText("[ERROR ZeroCrossingCounter]");
    warningLog.setProceedingText("[WARNING ZeroCrossingCounter]");

    init(searchWindowSize,deadZoneThreshold,numDimensions,featureMode);
}

ZeroCrossingCounter::ZeroCrossingCounter(const ZeroCrossingCounter &rhs){

    classType = "ZeroCrossingCounter";
    featureExtractionType = classType;
    debugLog.setProceedingText("[DEBUG ZeroCrossingCounter]");
    errorLog.setProceedingText("[ERROR ZeroCrossingCounter]");
    warningLog.setProceedingText("[WARNING ZeroCrossingCounter]");

    //Invoke the equals operator to copy the data from the rhs instance to this instance
    *this = rhs;
}

ZeroCrossingCounter::~ZeroCrossingCounter(){

}

ZeroCrossingCounter& ZeroCrossingCounter::operator=(const ZeroCrossingCounter &rhs){
    if(this!=&rhs){
        this->searchWindowSize = rhs.searchWindowSize;
        this->featureMode = rhs.featureMode;
        this->deadZoneThreshold = rhs.deadZoneThreshold;
        this->derivative = rhs.derivative;
        this->deadZone = rhs.deadZone;
        this->dataBuffer = rhs.dataBuffer;

        copyBaseVariables( (FeatureExtraction*)&rhs );
    }
    return *this;
}

bool ZeroCrossingCounter::deepCopyFrom(const FeatureExtraction *featureExtraction){

    if( featureExtraction == NULL ) return false;

    if( this->getFeatureExtractionType() == featureExtraction->getFeatureExtractionType() ){
        //Invoke the equals operator to copy the data from the rhs instance to this instance
        *this = *(ZeroCrossingCounter*)featureExtraction;
        return true;
    }

    errorLog << "clone(FeatureExtraction *featureExtraction) -  FeatureExtraction Types Do Not Match!" << endl;

    return false;
}

bool ZeroCrossingCounter::computeFeatures(const VectorDouble &inputVector){

    if( !initialized ){
        errorLog << "computeFeatures(const VectorDouble &inputVector) - Not initialized!" << endl;
        return false;
    }

    if( inputVector.size() != numInputDimensions ){
        errorLog << "computeFeatures(const VectorDouble &inputVector) - The size of the inputVector (" << inputVector.size() << ") does not match that of the filter (" << numInputDimensions << ")!" << endl;
        return false;
    }

    update( inputVector );

    return true;
}

bool ZeroCrossingCounter::reset(){
    if( initialized ){
        return init( searchWindowSize, deadZoneThreshold, numInputDimensions, featureMode );
    }
    return false;
}

bool ZeroCrossingCounter::saveModelToFile(string filename) const{

    std::fstream file;
    file.open(filename.c_str(), std::ios::out);

    if( !saveModelToFile( file ) ){
        return false;
    }

    file.close();

    return true;
}

bool ZeroCrossingCounter::loadModelFromFile(string filename){

    std::fstream file;
    file.open(filename.c_str(), std::ios::in);

    if( !loadModelFromFile( file ) ){
        return false;
    }

    //Close the file
    file.close();

    return true;
}

bool ZeroCrossingCounter::saveModelToFile(fstream &file) const{

    if( !file.is_open() ){
        errorLog << "saveModelToFile(fstream &file) - The file is not open!" << endl;
        return false;
    }

    //Write the file header
    file << "GRT_ZERO_CROSSING_COUNTER_FILE_V1.0" << endl;

    //Save the base settings to the file
    if( !saveFeatureExtractionSettingsToFile( file ) ){
        errorLog << "saveFeatureExtractionSettingsToFile(fstream &file) - Failed to save base feature extraction settings to file!" << endl;
        return false;
    }

    //Write the zero crossing counter settings
    file << "SearchWindowSize: " << searchWindowSize << endl;
    file << "FeatureMode: " << featureMode << endl;
    file << "DeadZoneThreshold: " << deadZoneThreshold << endl;

    return true;
}

bool ZeroCrossingCounter::loadModelFromFile(fstream &file){

    if( !file.is_open() ){
        errorLog << "loadModelFromFile(fstream &file) - The file is not open!" << endl;
        return false;
    }

    string word;

    //Load the header
    file >> word;

    if( word != "GRT_ZERO_CROSSING_COUNTER_FILE_V1.0" ){
        errorLog << "loadModelFromFile(fstream &file) - Invalid file format!" << endl;
        return false;
    }

    if( !loadFeatureExtractionSettingsFromFile( file ) ){
        errorLog << "loadFeatureExtractionSettingsFromFile(fstream &file) - Failed to load base feature extraction settings from file!" << endl;
        return false;
    }

    file >> word;
    if( word != "SearchWindowSize:" ){
        errorLog << "loadModelFromFile(fstream &file) - Failed to read SearchWindowSize header!" << endl;
        return false;
    }
    file >> searchWindowSize;

    file >> word;
    if( word != "FeatureMode:" ){
        errorLog << "loadModelFromFile(fstream &file) - Failed to read FeatureMode header!" << endl;
        return false;
    }
    file >> featureMode;

    file >> word;
    if( word != "DeadZoneThreshold:" ){
        errorLog << "loadModelFromFile(fstream &file) - Failed to read DeadZoneThreshold header!" << endl;
        return false;
    }
    file >> deadZoneThreshold;

    //Init the ZeroCrossingCounter module to ensure everything is initialized correctly
    return init(searchWindowSize,deadZoneThreshold,numInputDimensions,featureMode);
}

bool ZeroCrossingCounter::init(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode){

    initialized = false;
    featureDataReady = false;

    if( searchWindowSize == 0 ){
        errorLog << "init(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode) - The searchWindowSize must be greater than zero!" << endl;
        return false;
    }

    if( deadZoneThreshold < 0 ){
        errorLog << "init(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode) - The deadZoneThreshold must be greater than zero!" << endl;
        return false;
    }

    if( numDimensions == 0 ){
        errorLog << "init(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode) - The numDimensions must be greater than zero!" << endl;
        return false;
    }

    if( featureMode != INDEPENDANT_FEATURE_MODE && featureMode != COMBINED_FEATURE_MODE ){
        errorLog << "init(UINT searchWindowSize,double deadZoneThreshold,UINT numDimensions,UINT featureMode) - Unkown feature mode!" << endl;
        return false;
    }

    //Setup the search variables
    this->searchWindowSize = searchWindowSize;
    this->featureMode = featureMode;
    this->deadZoneThreshold = deadZoneThreshold;
    numInputDimensions = numDimensions;
    numOutputDimensions = (featureMode == INDEPENDANT_FEATURE_MODE ? TOTAL_NUM_ZERO_CROSSING_FEATURES * numInputDimensions : TOTAL_NUM_ZERO_CROSSING_FEATURES);
    derivative.init(Derivative::FIRST_DERIVATIVE, 1.0, numInputDimensions, true, 5);
    deadZone.init(-deadZoneThreshold,deadZoneThreshold,numInputDimensions);
    dataBuffer.resize( searchWindowSize, vector< double >(numInputDimensions,NAN) );
    featureVector.resize(numOutputDimensions,0);

    //Flag that the zero crossing counter has been initialized
    initialized = true;

    return true;
}

VectorDouble ZeroCrossingCounter::update(double x){
	return update(VectorDouble(1,x));
}

VectorDouble ZeroCrossingCounter::update(const VectorDouble &x){

    if( !initialized ){
        errorLog << "update(const VectorDouble &x) - Not Initialized!" << endl;
        return vector<double>();
    }

    if( x.size() != numInputDimensions ){
        errorLog << "update(const VectorDouble &x)- The Number Of Input Dimensions (" << numInputDimensions << ") does not match the size of the input vector (" << x.size() << ")!" << endl;
        return vector<double>();
    }

    //Clear the feature vector
    std::fill(featureVector.begin(),featureVector.end(),0);

    //Update the derivative data and
    derivative.computeDerivative( x );

    //Dead zone the derivative data
    deadZone.filter( derivative.getProcessedData() );

    //Add the deadzone data to the buffer
    dataBuffer.push_back( deadZone.getProcessedData() );

    //Search the buffer for the zero crossing features
    for(UINT j=0; j<numInputDimensions; j++){
        UINT colIndex = (featureMode == INDEPENDANT_FEATURE_MODE ? (TOTAL_NUM_ZERO_CROSSING_FEATURES*j) : 0);
        for(UINT i=1; i<dataBuffer.getSize(); i++){
            //Search for a zero crossing
            if( (dataBuffer[i][j] > 0 && dataBuffer[i-1][j] <= 0) || (dataBuffer[i][j] < 0 && dataBuffer[i-1][j] >= 0) ){
                //Update the zero crossing count
                featureVector[ NUM_ZERO_CROSSINGS_COUNTED + colIndex ]++;

                //Update the magnitude, search the last 5 values around the zero crossing to make sure we get the maxima of the peak
                double maxValue = 0;
                UINT searchSize = i > 5 ? 5 : i;
                for(UINT n=0; n<searchSize; n++){
                    double value = fabs( dataBuffer[ i-n ][j] );
                    if( value > maxValue ) maxValue = value;
                }
                featureVector[ ZERO_CROSSING_MAGNITUDE + colIndex ] += maxValue;
            }
        }
    }

    //Flag that the feature data has been computed
    featureDataReady = true;

    return featureVector;
}

bool ZeroCrossingCounter::setSearchWindowSize(UINT searchWindowSize){
    if( searchWindowSize > 0 ){
        this->searchWindowSize = searchWindowSize;
        if( initialized ) return reset();
        return true;
    }
    errorLog << "setSearchWindowSize(UINT searchWindowSize) - The searchWindowSize must be larger than zero!" << endl;
    return false;
}

bool ZeroCrossingCounter::setDeadZoneThreshold(UINT deadZoneThreshold){
    if( deadZoneThreshold > 0 ){
        this->deadZoneThreshold = deadZoneThreshold;
        if( initialized ) return reset();
        return true;
    }
    errorLog << "setDeadZoneThreshold(UINT deadZoneThreshold) - The deadZoneThreshold must be larger than zero!" << endl;
    return false;
}

bool ZeroCrossingCounter::setFeatureMode(UINT featureMode){
    if( featureMode == INDEPENDANT_FEATURE_MODE || featureMode == COMBINED_FEATURE_MODE ){
        this->featureMode = featureMode;
        if( initialized ) return reset();
        return true;
    }
    errorLog << "setFeatureMode(UINT featureMode) - Unkown feature mode!" << endl;
    return false;

}

}//End of namespace GRT


text:
"""
Helper functions used in views.
"""

import csv

from json import dumps

from functools import wraps

from datetime import datetime

from lxml import etree

from flask import Response

from presence_analyzer.main import app

import urllib

import threading

import logging

import time

log = logging.getLogger(__name__)  # pylint: disable-msg=C0103

def jsonify(function):
    """
    Creates a response with the JSON representation of wrapped function result.
    """
    @wraps(function)
    def inner(*args, **kwargs):
        return Response(dumps(function(*args, **kwargs)),
                        mimetype='application/json')
    return inner

def cache(time_in_sek):
    """
    Cache for CSV file
    """
    def inner_cache(function):
        lock = threading.Lock()
        function.inner_cache = {}
        @wraps(function)
        def decorator(*args, **kwargs):
            key = repr(args) + repr(kwargs)
            with lock:
                if key in function.inner_cache:
                    time_result = time.time() - function.inner_cache['time']
                    if time_result < time_in_sek:
                        return function.inner_cache[key]
                result = function(*args, **kwargs)
                function.inner_cache[key] = result
                function.inner_cache['time'] = time.time()
                return result

        return decorator
    return inner_cache

@cache(600)
def get_data():
    """
    Extracts presence data from CSV file and groups it by user_id.

    It creates structure like this:
    data = {
        'user_id': {
            datetime.date(2013, 10, 1): {
                'start': datetime.time(9, 0, 0),
                'end': datetime.time(17, 30, 0),
            },
            datetime.date(2013, 10, 2): {
                'start': datetime.time(8, 30, 0),
                'end': datetime.time(16, 45, 0),
            },
        }
    }
    """
    data = {}
    with open(app.config['DATA_CSV'], 'r') as csvfile:
        presence_reader = csv.reader(csvfile, delimiter=',')
        for i, row in enumerate(presence_reader):
            if len(row) != 4:
                # ignore header and footer lines
                continue

            try:
                user_id = int(row[0])
                date = datetime.strptime(row[1], '%Y-%m-%d').date()
                start = datetime.strptime(row[2], '%H:%M:%S').time()
                end = datetime.strptime(row[3], '%H:%M:%S').time()
            except (ValueError, TypeError):
                log.debug('Problem with line %d: ', i, exc_info=True)

            data.setdefault(user_id, {})[date] = {'start': start, 'end': end}
    return data

def group_by_weekday(items):
    """
    Groups presence entries by weekday.
    """
    result = {i: [] for i in range(7)}
    for date in items:
        start = items[date]['start']
        end = items[date]['end']
        result[date.weekday()].append(interval(start, end))
    return result

def group_times_by_weekday(items):
    """
    Groups times presence entries by weekday.
    """
    result = {i: {'start': [], 'end': []} for i in range(7)}
    for date, times in items.items():
        result[date.weekday()]['start'].append(
            seconds_since_midnight(times['start']))
        result[date.weekday()]['end'].append(
            seconds_since_midnight(times['end']))
    return result

def seconds_since_midnight(time):
    """
    Calculates amount of seconds since midnight.
    """
    return time.hour * 3600 + time.minute * 60 + time.second

def interval(start, end):
    """
    Calculates inverval in seconds between two datetime.time objects.
    """
    return seconds_since_midnight(end) - seconds_since_midnight(start)

def mean(items):
    """
    Calculates arithmetic mean. Returns zero for empty lists.
    """
    return float(sum(items)) / len(items) if len(items) > 0 else 0

def get_data_from_xml():
    """
    Parser get data from users.xml file
    Structure:
    [{
            10: {
            'name': user_name,
            'avatar': url+avatar}
    }]
    """
    with open('runtime/data/users.xml', 'r') as xmlfile:
        tree = etree.parse(xmlfile)
        server = tree.find('./server')
        protocol = server.find('./protocol').text
        host = server.find('./host').text
        additional = '://'
        url = protocol+additional+host
        return {
            user.attrib['id']: {
                'name': user.find('./name').text,
                'avatar': url+user.find('./avatar').text}
            for user in tree.findall('./users/user')}

def download_and_write_xml():
    """
    This script download and write a xml file from url
    """
    URL = app.config['XML_URL']
    webFile = urllib.urlopen("URL")
    print "Downloading file . . . "
    localFile = open.app.config('USER_DATA_XML', 'w')
    localFile.write(webFile.read())
    webFile.close()
    localFile.close()


text:
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

#if UNITY_5_5_OR_NEWER
using NavMeshAgent = UnityEngine.AI.NavMeshAgent;
#endif

namespace NodeCanvas.Tasks.Actions{

	[Name("Seek (GameObject)")]
	[Category("Movement/Pathfinding")]
	public class MoveToGameObject : ActionTask<NavMeshAgent> {

		[RequiredField]
		public BBParameter<GameObject> target;
		public BBParameter<float> speed = 4;
		public float keepDistance = 0.1f;

		private Vector3? lastRequest;

		protected override string info{
			get {return "Seek " + target;}
		}

		protected override void OnExecute(){
			agent.speed = speed.value;
			if ( Vector3.Distance(agent.transform.position, target.value.transform.position) < agent.stoppingDistance + keepDistance ){
				EndAction(true);
				return;
			}
		}

		protected override void OnUpdate(){
			var pos = target.value.transform.position;
			if (lastRequest != pos){
				if ( !agent.SetDestination( pos) ){
					EndAction(false);
					return;
				}
			}

			lastRequest = pos;

			if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance + keepDistance){
				EndAction(true);
			}
		}

		protected override void OnStop(){
			if (lastRequest != null && agent.gameObject.activeSelf){
				agent.ResetPath();
			}
			lastRequest = null;
		}

		protected override void OnPause(){
			OnStop();
		}

		public override void OnDrawGizmos(){
			if (target.value != null){
				Gizmos.DrawWireSphere(target.value.transform.position, keepDistance);
			}
		}
	}
}


text:
You are given an array of `words` where each word consists of lowercase English letters.

`wordA` is a _predecessor_ of `wordB` if and only if we can insert _exactly one_ letter anywhere in `wordA` _without changing the order of the other characters_ to make it equal to `wordB`.

- For example, `"abc"` is a predecessor of `"abac"`, while `"cba"` is not a predecessor of `"bcad"`.

A _word chain_ is a sequence of words `[word_1, word_2, ..., word_k]` with `k >= 1`, where `word_1` is a _predecessor_ of `word_2`, `word_2` is a _predecessor_ of `word_3`, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.

### Example 1:

```
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chain is ["a","ba","bda","bdca"].
```

### Example 2:

```
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
```

Example 3:

```
Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
```

### Constraints:

- `1 <= words.length <= 1000`
- `1 <= words[i].length <= 16`
- `words[i]` only consists of English lowercase letters.

#Array #Hash Table #Two Pointers #String #Dynamic Programming

#GOOGL #TikTok #TwoSigma


text:
<?php

/**
 * Adminhtml grid item renderer concat
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Concat extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{

    /**
     * Renders grid column
     *
     * @param   Varien_Object $row
     * @return  string
     */
    public function render(Varien_Object $row)
    {
        $dataArr = array();
        foreach ($this->getColumn()->getIndex() as $index) {
            if ($data = $row->getData($index)) {
                $dataArr[] = $data;
            }
        }
        $data = join($this->getColumn()->getSeparator(), $dataArr);
        // TODO run column type renderer
        return $data;
    }

}


text:
			<workflow-arrow-buttons on-review-language-change="onReviewLanguageChange(lang)" document="getCleanDocument()" languages="document.header.languages" hide-timer="false" tab="tab"
			 validation-report="validationReport" on-post-close="onPostClose()" on-error="onError(error, errorCode)"
			 on-post-publish="onPostPublishOrRequest(data)" on-pre-publish="onPrePublish()" on-pre-save-draft="onPreSaveDraft()"
			 on-post-save-draft="onPostSaveDraft(data)" on-post-request="onPostPublishOrRequest(data)" on-pre-request="onPreRequest()"
			 data-container="{{container}}" is-dialog="{{isDialog}}" document-type="{{type}}">
				<edit-form>
					<form class="editForm mt-2" name="editForm">

									<legend>{{::('editModifiedOrganismT.generalInfo'|$translate)}}</legend>

									<legend>{{::('editModifiedOrganismT.identityLMO'|$translate)}}</legend>

{{::('editModifiedOrganismT.LMONameInfo'|$translate)}}

{{::('editModifiedOrganismT.transformationEventInfo'|$translate)}}

												<input type="text" class="form-control" name="transformationEvent" required ng-model="document.transformationEvent"/>

{{::('editModifiedOrganismT.hasUniqueIdentificationInfo'|$translate)}} https://bch.cbd.int/en/kb/tags/lmo-gene-orga/LMO-Unique-Identifiers-UIDs-/619c55400c1ff000011c1c28.

												<input type="text" class="form-control" name="uniqueIdentification" required ng-model="document.uniqueIdentification"
													ng-change="lookupDetections()"/>

{{::('editModifiedOrganismT.recipientOrganismsInfo'|$translate)}}

{{::('editModifiedOrganismT.linkedModifiedOrganismsInfo'|$translate)}}

									<legend>{{::('editModifiedOrganismT.modificationProcess'|$translate)}}</legend>

{{::('editModifiedOrganismT.vectorInfo'|$translate)}}

{{::('editModifiedOrganismT.genesInfo'|$translate)}}

													<selected-records>

													</selected-records>

												<lmo-construct ng-model="document.geneConstructs" ng-change="onConstructChange()"></lmo-construct>

									<legend>{{::('editModifiedOrganismT.LMOCharacteristics'|$translate)}}</legend>

													<traits-selector ng-model="document.traits" locales="document.header.languages"></traits-selector>

{{::('editModifiedOrganismT.affectedGenesInfo'|$translate)}}

													<selected-records>

													</selected-records>

{{::('editModifiedOrganismT.commonUsesInfo'|$translate)}}

									<legend>{{::('editModifiedOrganismT.detectionMethod'|$translate)}}</legend>

												{{::('editModifiedOrganismT.detectionMethodInfo'|$translate)}}

									<legend>{{::('editModifiedOrganismT.additionalInformation'|$translate)}}</legend>

{{::('editModifiedOrganismT.relevantInformationInfo'|$translate)}}

													{{::('editModifiedOrganismT.relevantDocumentsInfo'|$translate)}}

							<legend>{{::('editModifiedOrganismT.notes'|$translate)}}</legend>

{{::('editModifiedOrganismT.notesInfo'|$translate)}}

					</form>
				</edit-form>
				<review-form>

				</review-form>
			</workflow-arrow-buttons>


text:
import logging
from pathlib import Path
from typing import Dict, Any

import pytoml as toml

_LOGGER = logging.getLogger(__name__)

CONF_NAME = "sdk_packaging.toml"
_SECTION = "packaging"

# Default conf
_CONFIG = {
    "package_name": "packagename",
    "package_nspkg": "packagenspkg",
    "package_pprint_name": "MyService Management",
    "package_doc_id": "",
    "is_stable": False,
    "is_arm": True,
    "need_msrestazure": False,  # track2 does not need it anymore in setup.py
    "need_azuremgmtcore": True,
    "sample_link": "",
}

def read_conf(folder: Path) -> Dict[str, Any]:
    conf_path = folder / CONF_NAME
    if not conf_path.exists():
        return {}

    with open(conf_path, "rb") as fd:
        return toml.load(fd)[_SECTION]

def build_default_conf(folder: Path, package_name: str) -> None:
    conf_path = folder / CONF_NAME
    if conf_path.exists():
        _LOGGER.info("Skipping default conf since the file exists")
        return

    _LOGGER.info("Build default conf for %s", package_name)
    conf = {_SECTION: _CONFIG.copy()}
    conf[_SECTION]["package_name"] = package_name
    conf[_SECTION]["package_nspkg"] = package_name[: package_name.rindex("-")] + "-nspkg"

    with open(conf_path, "w") as fd:
        toml.dump(conf, fd)