text:
/**
 * Place your JS-code here.
 *
 * I main.js görs ett antal Ajax-frågor för att hantera när nya saker läggs till
 * kundvagnen och när den töms. Man kan se det som ett API som erbjuds av shop.php.
 */
$(document).ready(function(){
  'use strict';

  // Init the shopping cart
  var initCart = function() {
    $.ajax({
      type: 'post',
      url: 'bookstore/shopping-cart-using-jquery-ajax/shop.php',
      dataType: 'json',
      success: function(data){
        updateCart(data);
        console.log('Ajax request returned successfully. Shopping cart initiated.');
      },
      error: function(jqXHR, textStatus, errorThrown){
        console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
      }
    });
  };
  initCart();

  // Function to update shopping cart
  var updateCart = function(data) {
    $('#content')
    .html(data.content);
    $('#numitems')
    .html(data.numitems);
    $('#sum')
    .html(data.sum);
    $('#status')
    .html('Shopping cart refreshed.');

    $.each(data.items, function(){
      console.log('item.');
    });

    setTimeout(function(){
      $('#status')
      .fadeOut(function(){
        $('#status')
        .html('')
        .fadeIn();
      });
    }, 1000);
    console.log('Shopping cart updated.');
  };

  // Callback when making a purchase
  $('.purchase').click(function() {
    var id = $(this).attr('id');
    $.ajax({
      type: 'post',
      url: 'bookstore/shopping-cart-using-jquery-ajax/shop.php?action=add',
      data: {
        itemid: id
      },
      dataType: 'json',
      success: function(data){
        updateCart(data);
        console.log('Ajax request returned successfully.');
      },
      error: function(jqXHR, textStatus, errorThrown){
        console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
      },
    });
    console.log('Clicked to buy id: ' + id);
  });

  // Callback to clear all values in shopping cart
  $("#clear").click(function() {
    $.ajax({
      type: 'post',
      url: 'bookstore/shopping-cart-using-jquery-ajax/shop.php?action=clear',
      dataType: 'json',
      success: function(data){
        updateCart(data);
        console.log('Ajax request returned successfully.');
      },
      error: function(jqXHR, textStatus, errorThrown){
        console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
      },
    });
    console.log('Clearing shopping cart.');
  });

  $('#checkout').click(function(){
//	  $('#lessAjax').attr('href', 'bookstore/one-page-checkout-using-ajax/style.less');
//	  $('#jsAjax').attr('src','bookstore/one-page-checkout-using-ajax/main.js');
	  var sum = $('#sum').text();
	  console.log(sum);
	  $.ajax({
		type: 'get',
		url: 'bookstore/one-page-checkout-using-ajax/index.php',
		data: 'sum=' + sum,
	    dataType: 'json',
	    success: function(data){
    	  $('#main').children().remove();
    	  $('#main').append(data.html);
//	    	  $('body').append(data.js);
//	    	  $('head').append(data.css);
    	  console.log('Ajax request returned successfully.');
	    }
	 });

//	  var path = 'bookstore/one-page-checkout-using-ajax/style.less';
//	    $.ajax({
//	        url: path,
//	        type:'HEAD',
//	        error: function()
//	        {
//	            alert("failure");
//	        },
//	        success: function(result)
//	        {
//	            alert("success");
//	        }
//	    });
//	 var myStylesLocation = "bookstore/one-page-checkout-using-ajax/style.less";
//	 $('<link href="'+myStylesLocation+'" type="text/css" rel="stylesheet/less">')
//	  .appendTo("head");

//	 $('<style type="text/css rel="stylesheet/less"></style>')
//	    .html('bookstore/one-page-checkout-using-ajax/style.less')
//	    .appendTo("head");

	 $.getScript('bookstore/one-page-checkout-using-ajax/main.js');
//	 $('head').append('<link rel="stylesheet" type="text/css" href="bookstore/one-page-checkout-using-ajax/style.less">');
//	 $('#lessAjax').attr('href', 'bookstore/one-page-checkout-using-ajax/style.less');
//	 $('#jsAjax').attr('src','bookstore/one-page-checkout-using-ajax/main.js');
  });

  console.log('Ready to roll.');
});


text:
from common import calculate_prime_factors

def solve():
    n = 647
    numbers = []
    while True:
        factors = calculate_prime_factors(n)
        if len(set(factors)) == 4:
            numbers.append(n)
        else:
            numbers = []
        if len(numbers) == 4:
            return numbers[0]
        n += 1

if __name__ == '__main__':
    print(__file__ + ": %s" % solve())

redpajama_set_name: RedPajamaGithub


text:
package org.pm4j.deprecated.core.pm;

import static junit.framework.Assert.assertEquals;

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

import org.junit.Before;
import org.junit.Test;
import org.pm4j.core.pm.PmAttrString;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.annotation.PmBeanCfg;
import org.pm4j.core.pm.annotation.PmFactoryCfg;
import org.pm4j.core.pm.impl.PmAttrStringImpl;
import org.pm4j.core.pm.impl.PmBeanBase;
import org.pm4j.core.pm.impl.PmConversationImpl;
import org.pm4j.deprecated.core.pm.DeprPmTableCol;
import org.pm4j.deprecated.core.pm.filter.DeprFilterBase;
import org.pm4j.deprecated.core.pm.impl.DeprPmTableColImpl;
import org.pm4j.deprecated.core.pm.impl.DeprPmTableImpl;
import org.pm4j.deprecated.core.pm.pageable.DeprPageablePmsForBeans;

public class PmTableTest {

  private MyTablePm myTablePm;
  private List<Item> editedRowBeanList;

  @Before
  public void setUp() {
    ItemPm.numOfCtorCalls = 0;

    editedRowBeanList = new ArrayList<PmTableTest.Item>(Arrays.asList(
        new Item("a", "an 'a'"),
        new Item("b", "a 'b'"),
        new Item("c", "a 'c'")
    ));

    myTablePm = new MyTablePm(new PmConversationImpl());
    myTablePm.setPageableCollection(new DeprPageablePmsForBeans<ItemPm, Item>(myTablePm, editedRowBeanList), false);
  }

  @Test
  public void testTable() {
    assertEquals("The table displays 3 rows for 3 beans.", 3, myTablePm.getRows().size());
  }

  @Test
  public void testTableWithFixFilter() {
    assertEquals("The unfiltered table has 3 rows.", 3, myTablePm.getRows().size());
    assertEquals(3, ItemPm.numOfCtorCalls);

    myTablePm.setFixFilter("f", new ItemNameStartsWithFilter("a"));
    assertEquals("There is only one item that starts with 'a'.", 1, myTablePm.getRows().size());
    // TODO olaf: is unstable. Fails if the whole test suite is started from eclipse.
    //   assertEquals(3, ItemPm.numOfCtorCalls);
  }

  public static class Item {
    public String name;
    public String description;

    public Item(String name, String description) {
      this.name = name;
      this.description = description;
    }
  }

  @PmBeanCfg(beanClass=Item.class)
  public static class ItemPm extends PmBeanBase<Item> {
    private static int numOfCtorCalls;
    public final PmAttrString name = new PmAttrStringImpl(this);
    public final PmAttrString description = new PmAttrStringImpl(this);

    public ItemPm() {
      ++numOfCtorCalls;
    }
  }

  @PmFactoryCfg(beanPmClasses=ItemPm.class)
  public static class MyTablePm extends DeprPmTableImpl<ItemPm> {
    public MyTablePm(PmObject pmParent) {
      super(pmParent);
    }

    public final DeprPmTableCol name = new DeprPmTableColImpl(this);
    public final DeprPmTableCol description = new DeprPmTableColImpl(this);
  }

  public static class ItemNameStartsWithFilter extends DeprFilterBase<ItemPm> {

    private String name;

    public ItemNameStartsWithFilter(String name) {
      super(FilterKind.ITEM_FILTER);
      this.name = name;
    }

    @Override
    protected boolean doesItemMatchImpl(ItemPm item) {
      return item.name.getValue().startsWith(name);
    }

  }
}


text:
package arms

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Integration is a nested struct in arms response
type Integration struct {
	IntegrationId              int64                    `json:"IntegrationId" xml:"IntegrationId"`
	DuplicateKey               string                   `json:"DuplicateKey" xml:"DuplicateKey"`
	InitiativeRecoverValue     string                   `json:"InitiativeRecoverValue" xml:"InitiativeRecoverValue"`
	Liveness                   string                   `json:"Liveness" xml:"Liveness"`
	IntegrationName            string                   `json:"IntegrationName" xml:"IntegrationName"`
	RecoverTime                int64                    `json:"RecoverTime" xml:"RecoverTime"`
	ShortToken                 string                   `json:"ShortToken" xml:"ShortToken"`
	InitiativeRecoverField     string                   `json:"InitiativeRecoverField" xml:"InitiativeRecoverField"`
	ApiEndpoint                string                   `json:"ApiEndpoint" xml:"ApiEndpoint"`
	State                      bool                     `json:"State" xml:"State"`
	AutoRecover                bool                     `json:"AutoRecover" xml:"AutoRecover"`
	IntegrationProductType     string                   `json:"IntegrationProductType" xml:"IntegrationProductType"`
	Description                string                   `json:"Description" xml:"Description"`
	ExtendedFieldRedefineRules []map[string]interface{} `json:"ExtendedFieldRedefineRules" xml:"ExtendedFieldRedefineRules"`
	FieldRedefineRules         []map[string]interface{} `json:"FieldRedefineRules" xml:"FieldRedefineRules"`
	Stat                       []int64                  `json:"Stat" xml:"Stat"`
}


text:
const fetch = require('node-fetch');
const Promise = require('bluebird');
const _ = require('lodash');
const writeFile = Promise.promisify(require('fs').writeFile);

const input = require('./input');
const output = require('./output');

const regionCollector = persons => _.mapValues(_.reduce(persons, (result, person) => {
  if (!result[person.r]) {
    result[person.r] = [person.d];
  } else {
    result[person.r].push(person.d);
  }
  return result;
}, {}),
    _.uniq,
  );

/**
 *
 * @param {Array} judges
 * @param {Array} prosecutors
 * @returns {Promise<Array>}
 */
module.exports = (judges, prosecutors) => Promise.all([
  regionCollector(judges),
  regionCollector(prosecutors),
])
    .spread((judges, prosecutors) => Promise.all([
      judges,
      prosecutors,
      writeFile(output.regionDepartmentMapping, JSON.stringify(judges)),
      writeFile(output.prosecutorsRegionDepartmentMapping, JSON.stringify(prosecutors)),
    ]));


text:
module NewRelicPluginsHive

  class Configuration
    attr_accessor :plugins

    def initialize
      config_file = File.expand_path('config/newrelic_hive.yml')
      raise "Can't find configuration file: #{config_file}" unless File.exists? config_file

      configuration = symbolize_keys(YAML.load_file(config_file))

      @plugins = configuration[:plugins]
    end

    private

    def symbolize_keys(hash)
      hash.inject({}) do |res, (key, val)|
        key = key.to_sym
        val = symbolize_keys(val) if val.is_a? Hash

        res[key] = val
        res
      end
    end
  end

end


text:
package com.intellij.uiDesigner.make;

import com.intellij.uiDesigner.lw.LwComponent;

/**
 * @author yole
 */
public class ToolBarLayoutSourceGenerator extends LayoutSourceGenerator {
  public void generateComponentLayout(final LwComponent component,
                                      final FormSourceCodeGenerator generator,
                                      final String variable,
                                      final String parentVariable) {
    generator.startMethodCall(parentVariable, "add");
    generator.pushVar(variable);
    generator.endMethod();
  }
}


text:
<resources>

    <!--global-->
    <string name="app_name">Bugtags-Demo</string>
    <string name="global_yes">是</string>
    <string name="global_no">否</string>
    <string name="global_set">设置</string>
    <string name="global_back">返回</string>
    <string name="global_send">提交</string>

    <!--main-->
    <string name="main_feedback">发送反馈</string>
    <string name="main_custom">自定义继承</string>
    <string name="main_config">快速配置</string>
    <string name="main_functions">功能介绍</string>
    <string name="main_born">移动时代首选 Bug 管理系统</string>

    <!--config-->
    <string name="config_user_step">设置是否记录用户操作步骤</string>
    <string name="config_console_log">设置是否收集控制台日志</string>
    <string name="config_crash_log">设置是否收集Crash信息</string>
    <string name="config_feedback">发送意见反馈</string>
    <string name="config_set_user_data">设置自定义数据</string>
    <string name="config_btg_log">Bugtags日志工具(不会将日志写入控制台)</string>
    <string name="config_user_step_code">Bugtags.setTrackingUserSteps(true|false);</string>
    <string name="config_console_log_code">Bugtags.setTrackingConsoleLog(true|false);</string>
    <string name="config_crash_log_code">Bugtags.setTrackingCrashes(true|false);</string>
    <string name="config_feedback_code">Bugtags.sendFeedback(\"xxx\");</string>
    <string name="config_set_user_data_code">Bugtags.setUserData(\"key\", \"value\");</string>
    <string name="config_btg_log_code">Bugtags.log(\"xxx\");</string>

    <!--custom-->
    <string name="custom_hint">参照BaseActivity,在你的Activity基类的如下3个方法中添加回调,就可以正常使用:Bugtags:\nonResume();\nonPause();\ndispatchTouchEvent();</string>

    <!--function-->
    <string name="functions_intro">Bugtags是新一代的、专为移动测试而生的缺陷发现及管理工具。我们致力于改善移动App的测试流程,连接发现缺陷与提交缺陷之间的用户体验,提高测试及解决缺陷的效率。</string>
    <string name="functions_slogan">Improve your app anytime, anywhere.</string>

    <!--feedback-->
    <string name="feedback_hint">请输入反馈内容</string>
    <string name="feedback_text_empty">请输入内容</string>
    <string name="feedback_send_succeed">反馈已发布</string>
    <string name="main_crash">产生一个闪退</string>
</resources>


text:
angular.module('custom-filters', []).filter('unique', function() {
   return function(collection, keyname) {
      var output = [],
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item;
          if ( keyname ) {
              var key = item[keyname];
          }

          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});


text:
module.exports = {
  modal: require('./uiModal'),
  dialog: require('./uiDialog'),
  modalHeader: require('./uiModalHeader'),
  modalFooter: require('./uiModalFooter')
}


text:
Ludosonica
========

#### Web sound- and 3d editor ####

Published under http://playfulmedia.cs.technik.fhnw.ch/play


text:
                             View Site

                             Toggle Fullscreen

                             Sign out

    <form role="form" method="GET" id="search" name="search" action="{{ route('admin.search.index') }}">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">

                <input type="text" placeholder="Search" name="search">

    </form>


text:
/**
* splitJSON takes a JSON array and splits it into arrays with length count.
**/

function splitJSON(jsonArray,count) {
  var processed = [];
  var length = jsonArray.length;
  for(var i = 0 ; i < length ; i = i + count) {
    processed.push(jsonArray.slice(i , i + count));
  }

  return processed;
}

module.exports = splitJSON;


text:
from pyramid.config import Configurator
from pyramid.tweens import INGRESS

def includeme(config: Configurator) -> None:  # pragma: no cover
    """
    :type config: :class:`pyramid.config.Configurator`
    """
    config.add_tween('pyramid_zipkin.tween.zipkin_tween', under=INGRESS)


text:
require 'rails/generators/migration'

class ImageGenerator < Rails::Generators::Base
  include Rails::Generators::Migration

  def self.source_root
    @_acts_as_imageable_source_root ||= File.expand_path('../templates', __FILE__)
  end

  def self.next_migration_number(_path)
    Time.now.utc.strftime('%Y%m%d%H%M%S')
  end

  def create_model_file
    template 'image.rb', 'app/models/image.rb'
    template 'file_uploader.rb', 'app/uploaders/acts_as_imageable/file_uploader.rb'
    template 'images_attribute.rb', 'app/models/concerns/acts_as_imageable/images_attribute.rb'
    # this is optional
    # template "image_serializer.rb", "app/serializers/acts_as_imageable/image_serializer.rb"
    migration_template 'create_images.rb', 'db/migrate/create_images.rb'
  end
end


text:
var express = require('express');
var bodyParser = require('body-parser');
var portRouter = express.Router();
var Ports = require('../models/ports');
var verify = require('../verify');
var config = require('../config');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    service: config.mailService,
    auth: {
        user: config.nodeEmail,
        pass: config.nodeEmailPassword
    }
});

portRouter.use(bodyParser.json());

portRouter.route('/')
    .get(function (req, res, next) {
        Ports.find({}, function (err, resp) {
            if (err) throw err;
            res.json(resp);
        });
    })

    .post(function (req, res, next) {
        const decReq = JSON.parse(Buffer.from(req.body.payload, 'base64').toString());
        Ports.find({
            query: (decReq.query || decReq.ip)
        }, function (err, resp) {
            if (err) throw err;
            if (resp.length) {
                if (decReq.userMessage && decReq.userMessage.message) {

                    var mailOptions = {
                        from: decReq.userMessage.email || 'anonymoususer@mail.com',
                        to: config.mailTo,
                        subject: decReq.userMessage.email + ' ' + decReq.userMessage.name + ' ' + decReq.userMessage.reason,
                        text: decReq.userMessage.message + ' -sent from ' + decReq.city
                    };
                    transporter.sendMail(mailOptions, function (error, info) {
                        if (error) {
                            console.log(error);
                        } else {
                            console.log('Email sent: ' + info.response);
                        }
                    });

                    if (resp[0].userMessage && resp[0].userMessage.length) {
                        decReq.userMessage = resp[0].userMessage.concat(decReq.userMessage);
                    } else {
                        decReq.userMessage = [decReq.userMessage];
                    }
                    Ports.findByIdAndUpdate(resp[0]._id, {
                        $set: decReq
                    }, {
                        new: true
                    }, function (err, resp) {
                        if (err) throw err;
                        res.end('port updated!');
                    });
                } else {
                    res.end('port already exists!');
                }
            } else {
                Ports.create({ ...decReq, query: (decReq.query || decReq.ip) }, function (err, resp) {
                    if (err) throw err;
                    var id = resp._id;

                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.end('Added the port!');
                });
            }
        });
    })

    .delete(verify.verifyOrdinaryUser, verify.verifyAdmin, function (req, res, next) {
        Ports.remove({}, function (err, resp) {
            if (err) throw err;
            res.json(resp);
        });
    });

portRouter.route('/:respId')
    .get(verify.verifyOrdinaryUser, function (req, res, next) {
        Ports.findById(req.params.respId, function (err, resp) {
            if (err) throw err;
            res.json(resp);
        });
    })

    .put(verify.verifyOrdinaryUser, verify.verifyAdmin, function (req, res, next) {
        Ports.findByIdAndUpdate(req.params.respId, {
            $set: req.body
        }, {
            new: true
        }, function (err, resp) {
            if (err) throw err;
            res.json(resp);
        });
    })

    .delete(verify.verifyOrdinaryUser, verify.verifyAdmin, function (req, res, next) {
        Ports.findByIdAndRemove(req.params.respId, function (err, resp) {
            if (err) throw err;
            res.json(resp);
        });
    });

module.exports = portRouter;


text:
a,
.navbar-nav > li:hover > a,
.dropdown-menu-category-title,
.dropdown-menu-category-list > li > a:hover,
.dropdown-menu-shipping-cart-price,
.dropdown-menu-items-list > li > a:hover,
.category-selections-icon.active,
.category-selections-icon.active:hover,
.category-pagination > li > a,
.blog-post-title > a:hover,
.product-page-product-rating.product-rating-big > li.count,
.product-page-qa-question:before,
.product-page-qa-answer:before,
.product-review-thumb-product-title > a:hover,
.btn-ghost.btn-primary,
.comment comment-review-rate {
  color: #0ebcf2;
}
.box-highlight {
  box-shadow: 0 1px 2px rgba(0,0,0,0.25) , 0 0 8px rgba(14,188,242,0.55);
}
.navbar-main {
  background: #0a8db6;
}
.navbar-nav > li.open > a {
  background: #087192 !important;
}
.navbar-main .navbar-border > li {
  border-right: 1px solid #24364c;
}
.navbar-main .navbar-border > li:last-child {
  border-right: none;
}
.navbar-before-inverse,
.navbar-main-white .navbar-nav > li:hover > a,
.navbar-main-white .navbar-main-search-submit,
.navbar-main-white .navbar-main-search-submit:hover,
.dropdown-menu-category > li:hover > a,
.main-header-input-center-btn,
.category-pagination > li.last > a,
.category-tabs .nav-pills li.active > a,
.blog-sidebar-tags > li > a:hover,
.product-icon-quick-view,
.product-plus,
.product-quick-view:hover,
.product-labels > li,
.product-review-rate:hover,
.btn-ghost.btn-primary:hover,
.i-check.i-check-stroke.checked:before,
.irs-slider {
  background: #0ebcf2;
}
.navbar-main-white .dropdown-menu {
  border-top: 2px solid #0ebcf2;
}
.main-header {
  background: #0a8db6;
  border-bottom: 1px solid #0984aa;
}
.main-footer {
  border-top: 2px solid #0ebcf2;
}
.category-filters-color {
  background: #0a8db6;
}
.category-filters-color .category-filters-section {
  border-color: #087192;
}
.category-pagination > li > a:hover,
.category-pagination > li.last > a,
.blog-sidebar-tags > li > a:hover {
  border-color: #0ebcf2;
}
.product-icon-quick-view:hover {
  background: #0cb3e7;
}
.product-plus:hover {
  background: #0ba0ce;
}
.btn-primary {
  background: #0ebcf2;
  border-color: #0caadb;
}
.btn-primary:hover {
  background: #0caadb;
  border-color: #0a97c2;
}
.btn-primary:focus {
  background: #0caadb;
  border-color: #0a97c2;
}
.i-check.hover,
.i-radio.hover {
  border: 1px solid #0ebcf2;
}
.i-check.checked,
.i-radio.checked {
  border: 1px solid #0ebcf2;
  background: #0ebcf2;
}
.jqzoom-list > li > a.zoomThumbActive > img {
  box-shadow: 0 0 0 2px rgba(14,188,242,0.75);
}


text:
package org.sbuild.plugins.aether.impl

import java.io.File
import scala.collection.JavaConverters._
import org.apache.maven.repository.internal.MavenRepositorySystemUtils
import org.apache.maven.wagon.Wagon
import org.eclipse.aether.RepositorySystem
import org.eclipse.aether.artifact.DefaultArtifact
import org.eclipse.aether.collection.CollectRequest
import org.eclipse.aether.connector.file.FileRepositoryConnectorFactory
import org.eclipse.aether.connector.wagon.WagonProvider
import org.eclipse.aether.connector.wagon.WagonRepositoryConnectorFactory
import org.eclipse.aether.graph.Dependency
import org.eclipse.aether.repository.LocalRepository
import org.eclipse.aether.repository.RemoteRepository
import org.eclipse.aether.resolution.DependencyRequest
import org.eclipse.aether.spi.connector.RepositoryConnectorFactory
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator
import org.sonatype.maven.wagon.AhcWagon
import org.sbuild.plugins.aether.AetherSchemeHandlerWorker
import org.sbuild.plugins.aether.Repository
import org.sbuild.plugins.aether.ArtifactDependency
import org.sbuild.plugins.aether.Exclude
import org.eclipse.aether.graph.Exclusion
import org.sbuild.plugins.aether.Exclude

object AetherSchemeHandlerWorkerImpl {

  class ManualWagonProvider extends WagonProvider {
    override def lookup(roleHint: String): Wagon = roleHint match {
      case "http" => new AhcWagon()
      // case "file" => new FileWagon()
      // case "scp" => new ScpWagon()
      // case "sftp" => new SftpWagon()
      case _ => null
    }
    override def release(wagon: Wagon) {}
  }

}

class AetherSchemeHandlerWorkerImpl(localRepoDir: File, remoteRepos: Seq[Repository]) extends AetherSchemeHandlerWorker {
  import AetherSchemeHandlerWorkerImpl._

  private[impl] def newRepositorySystem() = {
    val locator = MavenRepositorySystemUtils.newServiceLocator()
    locator.setServices(classOf[WagonProvider], new ManualWagonProvider())
    locator.setService(classOf[RepositoryConnectorFactory], classOf[FileRepositoryConnectorFactory])
    locator.setService(classOf[RepositoryConnectorFactory], classOf[WagonRepositoryConnectorFactory])
    val system = locator.getService(classOf[RepositorySystem])
    assert(system != null)
    system
  }

  private[impl] def newSession(system: RepositorySystem) = {
    val session = MavenRepositorySystemUtils.newSession()
    val localRepo = new LocalRepository(localRepoDir)
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo))
    session
  }

  lazy val repoSystem = newRepositorySystem()
  lazy val session = newSession(repoSystem)

  override def resolve(requestedArtifacts: Seq[ArtifactDependency]): Seq[File] = {

    def exclusion(exclude: Seq[Exclude]) = exclude.map {
      case Exclude(groupId, artifactId, classifier, extension) =>
        new Exclusion(groupId, artifactId, classifier.getOrElse("*"), extension.getOrElse("*"))
    }.asJavaCollection

    println("About to resolve deps: " + requestedArtifacts)

    // create Maven dependencies from it
    val deps = requestedArtifacts.map {
      case ArtifactDependency(g, a, v, None, exclude) =>
        new Dependency(new DefaultArtifact(g, a, "jar", v), "compile", false, exclusion(exclude))
      case ArtifactDependency(g, a, v, Some(c), exclude) =>
        new Dependency(new DefaultArtifact(g, a, c, "jar", v), "compile", false, exclusion(exclude))
    }

    val collectRequest = new CollectRequest()
    deps.foreach { d => collectRequest.addDependency(d) }
    remoteRepos.map { repo =>
      collectRequest.addRepository(new RemoteRepository.Builder(repo.name, repo.layout, repo.url).build())
    }

    val node = repoSystem.collectDependencies(session, collectRequest).getRoot()

    val dependencyRequest = new DependencyRequest()
    dependencyRequest.setRoot(node)

    repoSystem.resolveDependencies(session, dependencyRequest)

    val nlg = new PreorderNodeListGenerator()
    node.accept(nlg)

    val files = nlg.getNodes().asScala.toSeq.map { node =>
      val dep = node.getDependency()
      val artifact = if (dep != null) dep.getArtifact() else null
      val file = if (artifact != null) artifact.getFile() else null
      if (file != null) file.getAbsoluteFile() else null
    }.filter(_ != null)

    files

  }

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using Microsoft.Fx.Portability;

namespace Microsoft.Fx.Portability.Cci.Tests
{
    internal class TestAssemblyFile : IAssemblyFile
    {
        internal FileInfo FileInfo { get; }

        public TestAssemblyFile(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            else if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("Cannot be empty", nameof(path));
            }

            FileInfo = new FileInfo(path);
        }

        public bool Exists { get { return FileInfo.Exists; } }

        public string Name { get { return FileInfo.FullName; } }

        public string Version
        {
            get { return "1.0.0.0"; }
        }

        public Stream OpenRead()
        {
            return Exists ? FileInfo.OpenRead() : null;
        }
    }
}


text:
/**
 * @author effine
 * @Date 2015年8月13日  下午2:20:52
 * @email iballader#gmail.com
 * @site http://www.effine.cn
 */

package cn.effine.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * @author effine
 * @Date 2017-10-15 20:37
 * 二维码操作类
 */
public class QrCodeUtils {

    private static Logger logger = LoggerFactory.getLogger(QrCodeUtils.class);

    private QrCodeUtils() {
    }

    /**
     * 生成二维码图片
     *
     * @param width    宽度
     * @param height   高度
     * @param content  二维码内容
     * @param filePath 二维码生成路径
     * @return 二维码图片URL
     */
    public static String generateQRCode(int width, int height, String content, String filePath) {
        if (width <= 0 || height <= 0) {
            return "二维码图片尺寸错误";
        }
        if (StringUtils.isBlank(content)) {
            return "二维码内容为空";
        }

        // 图片类型
        String format = "png";
        // 文件名
        String fileName = System.currentTimeMillis() + "." + format;

        Map<EncodeHintType, String> hints = new HashMap<>(1);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        Path fullName = FileSystems.getDefault().getPath(filePath, fileName);
        try {
            // 生成矩阵二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 输出图像
            MatrixToImageWriter.writeToPath(bitMatrix, format, fullName);
        } catch (IOException | WriterException e) {
            logger.error(e.getMessage());
        }
        return fileName;
    }

    /**
     * 解析二维码图片
     *
     * @param fullName 图片网站文件名
     * @return 二维码图片内容
     */
    public static String parseQRCode(String fullName) {
        if (StringUtils.isBlank(fullName)) {
            return "二维码图片地址为空";
        }

        BufferedImage image = null;
        try {
            image = ImageIO.read(new File(fullName));
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, String> hints = new HashMap<>(1);
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result;
        try {
            // 对图像进行解码
            result = new MultiFormatReader().decode(binaryBitmap, hints);
            return result.getText();
        } catch (NotFoundException e) {
            logger.error(e.getMessage());
        }
        return null;
    }
}


text:
module Phrase
  module Formats
    class Csv < Phrase::Formats::Base
      def self.filename_for_locale(locale)
        "phrase.#{locale.name}.csv"
      end

      def self.locale_aware?
        false
      end

      def self.extensions
        [:csv]
      end
    end
  end
end


text:
package com.smarthouse.app;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity{

	private List<Device> deviceList=new ArrayList<Device>();

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);

		initDevices();
		DeviceAdapter adapter=new DeviceAdapter(MainActivity.this, R.layout.device_item, deviceList);
		ListView listView=(ListView) findViewById(R.id.list_view);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MainActivity.this,RecognitionActivity.class);
				startActivity(intent);

			}
		});
	}

	private void initDevices() {
		// TODO Auto-generated method stub
		Device item1=new Device("ÕÕÃ÷Æ÷¾ß", R.drawable.item_1);
		deviceList.add(item1);
		Device item2=new Device("¿Õµ÷Æ÷¾ß", R.drawable.item_2);
		deviceList.add(item2);
		Device item3=new Device("Çå½àÆ÷¾ß", R.drawable.item_3);
		deviceList.add(item3);
		Device item4=new Device("³ø·¿Æ÷¾ß", R.drawable.item_4);
		deviceList.add(item4);
		Device item5=new Device("µç×ÓÆ÷¾ß", R.drawable.item_5);
		deviceList.add(item5);
		Device item6=new Device("½¡ÉíÆ÷¾ß", R.drawable.item_6);
		deviceList.add(item6);
		Device item7=new Device("ÖÆÀäÆ÷¾ß", R.drawable.item_7);
		deviceList.add(item7);
		Device item8=new Device("ȡůÆ÷¾ß", R.drawable.item_8);
		deviceList.add(item8);
	}
}


text:
var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var busboy = require('connect-busboy')
var path = require('path')
var fs = require('fs-extra')
var multer = require('multer')

var upload = multer({ dest: 'uploads/' })

var Employee = mongoose.model('Employee')
var Company = mongoose.model('Company')
var Assignment = mongoose.model('Assignment')
var Payment = mongoose.model('Payment')

function isAuthenticated (req, res, next) {
  // if user is authenticated in the session, call the next() to call the next request handler
  // Passport adds this method to request object. A middleware is allowed to add properties to
  // request and response objects
  console.log('Check if user is authenticated')
  // allow all get request methods
  if (req.method === 'GET') {
    return next()
  }
  if (req.isAuthenticated()) {
    return next()
  }

  // if the user is not authenticated then redirect him to the login page
  return res.redirect('/#/login')
}

router.use('/v1/employees', isAuthenticated)

/* GET home page. */
router.route('/v1/employees')

  .get(function (req, res, next) {
    console.log('Trying to get employees')
    Employee.find(function (err, employees) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.status(200).send(employees)
    })

  })

  .post(function (req, res, next) {
    console.log('Saving new employee values in object')
    var employee = new Employee()
    employee.firstName = req.body.firstName
    employee.lastName = req.body.lastName
    employee.identifier = req.body.identifier
    employee.jobTitle = req.body.jobTitle
    employee.basicSalary = req.body.basicSalary
    employee.startDate = req.body.startDate
    employee.endDate = req.body.endDate
    employee.companyId = req.body.companyId
    employee.aliquotVacationBonus = req.body.aliquotVacationBonus
    employee.antiquityDays = req.body.antiquityDays
    employee.created_by = req.body.created_by
    console.log('Trying to save employee' + employee + ' in db')
    employee.save(function (err, employee) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.status(200).send(employee)
    })
  })

router.route('/v1/employees/:id')

  .get(function (req, res, next) {
    console.log('Trying to get employee with id: ' + req.params.id)
    Employee.findById(req.params.id, function (err, employee) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.status(200).send(employee)
    })
  })

  .put(function (req, res, next) {
    console.log('Trying to put employee with id: ' + req.params.id)
    Employee.findById(req.params.id, function (err, employee) {
      if (err) {
        return res.status(500).send(err)
      }
      employee.identifier = req.body.identifier
      employee.firstName = req.body.firstName
      employee.lastName = req.body.lastName
      employee.jobTitle = req.body.jobTitle
      employee.basicSalary = req.body.basicSalary
      employee.startDate = req.body.startDate
      employee.endDate = req.body.endDate
      employee.companyId = req.body.companyId
      employee.aliquotVacationBonus = req.body.aliquotVacationBonus
      employee.antiquityDays = req.body.antiquityDays
      employee.created_by = req.body.created_by

      employee.save(function (err, employee) {
        if (err) {
          console.log(err)
          return res.status(500).send(err)
        }
        return res.json(employee)
      })
    })
  })

  .delete(function (req, res, next) {
    Employee.remove({
      _id: req.params.id
    }, function (err) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.json('deleted')
    })
  })

router.use('/v1/companies', isAuthenticated)

/* GET home page. */
router.route('/v1/companies')

  .get(function (req, res, next) {
    console.log('Trying to get companies')
    Company.find(function (err, companies) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.status(200).send(companies)
    })
  })

  .post(function (req, res, next) {
    console.log('Trying to add a company')
    var company = new Company()
    company.name = req.body.name
    company.logo = req.body.logo
    company.utilityDays = req.body.utilityDays
    company.interest = req.body.interest
    company.created_by = req.body.created_by
    company.save(function (err, company) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.json(company)
    })
  })

router.route('/v1/companies/:id')

  .get(function (req, res, next) {
    console.log('Trying to get company with id: ' + req.params.id)
    Company.findById(req.params.id, function (err, company) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.status(200).send(company)
    })
  })

  .put(function (req, res, next) {
    Company.findById(req.params.id, function (err, company) {
      if (err) {
        return res.status(500).send(err)
      }

      company.name = req.body.name
      company.logo = req.body.logo
      company.utilityDays = req.body.utilityDays
      company.interest = req.body.interest
      company.created_at = req.body.created_at
      company.created_by = req.body.created_by
      company.save(function (err, employee) {
        if (err) {
          return res.status(500).send(err)
        }
      })
      return res.status(200).send(company)
    })
  })

  .delete(function (req, res, next) {
    Company.remove({
      _id: req.params.id
    }, function (err) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.json('deleted')
    })
  })

router.use('/v1/assignments', isAuthenticated)

/* GET home page. */
router.route('/v1/assignments')

  .get(function (req, res, next) {
    console.log('Trying to get assignments')
    Assignment.find(function (err, assignments) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.status(200).send(assignments)
    })
  })

  .post(function (req, res, next) {
    console.log('Trying to add a assignment')
    var assignment = new Assignment()

    assignment.averageDailySalary = req.body.averageDailySalary,
    assignment.aliquotUtility = req.body.aliquotUtility,
    assignment.integralSalary = req.body.integralSalary,
    assignment.antiquityAmount = req.body.antiquityAmount,
    assignment.employeeId = req.body.employeeId,
    assignment.created_at = req.body.created_at,
    assignment.created_by = req.body.created_by
    assignment.save(function (err, assignment) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.json(assignment)
    })
  })

router.route('/v1/assignments/:id')

  .get(function (req, res, next) {
    console.log('Trying to get assignment with id: ' + req.params.id)
    Assignment.findById(req.params.id, function (err, assignment) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.status(200).send(assignment)
    })
  })

  .put(function (req, res, next) {
    Assignment.findById(req.params.id, function (err, assignment) {
      if (err) {
        return res.status(500).send(err)
      }

      assignment.averageDailySalary = req.body.averageDailySalary,
      assignment.aliquotUtility = req.body.aliquotUtility,
      assignment.integralSalary = req.body.integralSalary,
      assignment.antiquityAmount = req.body.antiquityAmount,
      assignment.employeeId = req.body.employeeId,
      assignment.assignment.created_at = req.body.created_at,
      assignment.assignment.created_by = req.body.created_by
      assignment.save(function (err, employee) {
        if (err) {
          return res.status(500).send(err)
        }
      })
      return res.status(200).send(assignment)
    })
  })

  .delete(function (req, res, next) {
    Assignment.remove({
      _id: req.params.id
    }, function (err) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.json('deleted')
    })
  })

router.use('/v1/payments', isAuthenticated)

/* GET home page. */
router.route('/v1/payments')

  .get(function (req, res, next) {
    console.log('Trying to get payments')
    Payment.find(function (err, payments) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.status(200).send(payments)
    })
  })

  .post(function (req, res, next) {
    console.log('Trying to add a payment')
    var payment = new Payment()

    payment.salary = req.body.salary,
    payment.startDate = req.body.startDate,
    payment.endDate = req.body.endDate,
    payment.deduction = req.body.deduction,
    payment.employeeId = req.body.employeeId,
    payment.created_at = req.body.created_at,
    payment.created_by = req.body.created_by
    payment.save(function (err, payment) {
      if (err) {
        console.log(err)
        return res.status(500).send(err)
      }
      return res.json(payment)
    })
  })

router.route('/v1/payments/:id')

  .get(function (req, res, next) {
    console.log('Trying to get payment with id: ' + req.params.id)
    Payment.findById(req.params.id, function (err, payment) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.status(200).send(payment)
    })
  })

  .put(function (req, res, next) {
    Payment.findById(req.params.id, function (err, payment) {
      if (err) {
        return res.status(500).send(err)
      }

      payment.salary = req.body.salary,
      payment.startDate = req.body.startDate,
      payment.endDate = req.body.endDate,
      payment.deduction = req.body.deduction,
      payment.employeeId = req.body.employeeId,
      payment.created_at = req.body.created_at,
      payment.created_by = req.body.created_by
      payment.save(function (err, employee) {
        if (err) {
          return res.status(500).send(err)
        }
      })
      return res.status(200).send(payment)
    })
  })

  .delete(function (req, res, next) {
    Payment.remove({
      _id: req.params.id
    }, function (err) {
      if (err) {
        return res.status(500).send(err)
      }
      return res.json('deleted')
    })
  })

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])

router.route('/upload')
  //.post('/cool-profile', cpUpload, function (req, res, next) {
    // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
    //
    // e.g.
    //  req.files['avatar'][0] -> File
    //  req.files['gallery'] -> Array
    //
    // req.body will contain the text fields, if there were any
  //})

module.exports = router


text:
============================
Getting Started With AWS EC2
============================

Amazon EC2 is a very widely used public cloud platform and one of the core
platforms Salt Cloud has been built to support.

Previously, the suggested driver for AWS EC2 was the ``aws`` driver. This
has been deprecated in favor of the ``ec2`` driver. Configuration using the
old ``aws`` driver will still function, but that driver is no longer in
active development.

Dependencies
============
This driver requires the Python ``requests`` library to be installed.

Configuration
=============
The following example illustrates some of the options that can be set. These
parameters are discussed in more detail below.

.. code-block:: yaml

    # Note: This example is for /etc/salt/cloud.providers or any file in the
    # /etc/salt/cloud.providers.d/ directory.

    my-ec2-southeast-public-ips:
      # Set up the location of the salt master
      #
      minion:
        master: saltmaster.example.com

      # Set up grains information, which will be common for all nodes
      # using this provider
      grains:
        node_type: broker
        release: 1.0.1

      # Specify whether to use public or private IP for deploy script.
      #
      # Valid options are:
      #     private_ips - The salt-cloud command is run inside the EC2
      #     public_ips - The salt-cloud command is run outside of EC2
      #
      ssh_interface: public_ips

      # Optionally configure the Windows credential validation number of
      # retries and delay between retries.  This defaults to 10 retries
      # with a one second delay betwee retries
      win_deploy_auth_retries: 10
      win_deploy_auth_retry_delay: 1

      # Set the EC2 access credentials (see below)
      #
      id: 'use-instance-role-credentials'
      key: 'use-instance-role-credentials'

      # Make sure this key is owned by root with permissions 0400.
      #
      private_key: /etc/salt/my_test_key.pem
      keyname: my_test_key
      securitygroup: default

      # Optionally configure default region
      # Use salt-cloud --list-locations <provider> to obtain valid regions
      #
      location: ap-southeast-1
      availability_zone: ap-southeast-1b

      # Configure which user to use to run the deploy script. This setting is
      # dependent upon the AMI that is used to deploy. It is usually safer to
      # configure this individually in a profile, than globally. Typical users
      # are:
      #
      # Amazon Linux -> ec2-user
      # RHEL         -> ec2-user
      # CentOS       -> ec2-user
      # Ubuntu       -> ubuntu
      #
      ssh_username: ec2-user

      # Optionally add an IAM profile
      iam_profile: 'arn:aws:iam::123456789012:instance-profile/ExampleInstanceProfile'

      driver: ec2

    my-ec2-southeast-private-ips:
      # Set up the location of the salt master
      #
      minion:
        master: saltmaster.example.com

      # Specify whether to use public or private IP for deploy script.
      #
      # Valid options are:
      #     private_ips - The salt-master is also hosted with EC2
      #     public_ips - The salt-master is hosted outside of EC2
      #
      ssh_interface: private_ips

      # Optionally configure the Windows credential validation number of
      # retries and delay between retries.  This defaults to 10 retries
      # with a one second delay betwee retries
      win_deploy_auth_retries: 10
      win_deploy_auth_retry_delay: 1

      # Set the EC2 access credentials (see below)
      #
      id: 'use-instance-role-credentials'
      key: 'use-instance-role-credentials'

      # Make sure this key is owned by root with permissions 0400.
      #
      private_key: /etc/salt/my_test_key.pem
      keyname: my_test_key

      # This one should NOT be specified if VPC was not configured in AWS to be
      # the default. It might cause an error message which says that network
      # interfaces and an instance-level security groups may not be specified
      # on the same request.
      #
      securitygroup: default

      # Optionally configure default region
      #
      location: ap-southeast-1
      availability_zone: ap-southeast-1b

      # Configure which user to use to run the deploy script. This setting is
      # dependent upon the AMI that is used to deploy. It is usually safer to
      # configure this individually in a profile, than globally. Typical users
      # are:
      #
      # Amazon Linux -> ec2-user
      # RHEL         -> ec2-user
      # CentOS       -> ec2-user
      # Ubuntu       -> ubuntu
      #
      ssh_username: ec2-user

      # Optionally add an IAM profile
      iam_profile: 'my other profile name'

      driver: ec2

.. note::
    .. versionchanged:: 2015.8.0

    The ``provider`` parameter in cloud provider definitions was renamed to ``driver``. This
    change was made to avoid confusion with the ``provider`` parameter that is used in cloud profile
    definitions. Cloud provider definitions now use ``driver`` to refer to the Salt cloud module that
    provides the underlying functionality to connect to a cloud host, while cloud profiles continue
    to use ``provider`` to refer to provider configurations that you define.

Access Credentials
==================
The ``id`` and ``key`` settings may be found in the Security Credentials area
of the AWS Account page:

https://portal.aws.amazon.com/gp/aws/securityCredentials

Both are located in the Access Credentials area of the page, under the Access
Keys tab. The ``id`` setting is labeled Access Key ID, and the ``key`` setting
is labeled Secret Access Key.

Note: if either ``id`` or ``key`` is set to 'use-instance-role-credentials' it is
assumed that Salt is running on an AWS instance, and the instance role
credentials will be retrieved and used.  Since both the ``id`` and ``key`` are
required parameters for the AWS ec2 provider, it is recommended to set both
to 'use-instance-role-credentials' for this functionality.

A "static" and "permanent" Access Key ID and Secret Key can be specified,
but this is not recommended.  Instance role keys are rotated on a regular
basis, and are the recommended method of specifying AWS credentials.

Windows Deploy Timeouts
=======================
For Windows instances, it may take longer than normal for the instance to be
ready.  In these circumstances, the provider configuration can be configured
with a ``win_deploy_auth_retries`` and/or a ``win_deploy_auth_retry_delay``
setting, which default to 10 retries and a one second delay between retries.
These retries and timeouts relate to validating the Administrator password
once AWS provides the credentials via the AWS API.

Key Pairs
=========
In order to create an instance with Salt installed and configured, a key pair
will need to be created. This can be done in the EC2 Management Console, in the
Key Pairs area. These key pairs are unique to a specific region. Keys in the
us-east-1 region can be configured at:

https://console.aws.amazon.com/ec2/home?region=us-east-1#s=KeyPairs

Keys in the us-west-1 region can be configured at

https://console.aws.amazon.com/ec2/home?region=us-west-1#s=KeyPairs

...and so on. When creating a key pair, the browser will prompt to download a
pem file. This file must be placed in a directory accessible by Salt Cloud,
with permissions set to either 0400 or 0600.

Security Groups
===============
An instance on EC2 needs to belong to a security group. Like key pairs, these
are unique to a specific region. These are also configured in the EC2
Management Console. Security groups for the us-east-1 region can be configured
at:

https://console.aws.amazon.com/ec2/home?region=us-east-1#s=SecurityGroups

...and so on.

A security group defines firewall rules which an instance will adhere to. If
the salt-master is configured outside of EC2, the security group must open the
SSH port (usually port 22) in order for Salt Cloud to install Salt.

IAM Profile
===========
Amazon EC2 instances support the concept of an `instance profile`_, which
is a logical container for the IAM role. At the time that you launch an EC2
instance, you can associate the instance with an instance profile, which in
turn corresponds to the IAM role. Any software that runs on the EC2 instance
is able to access AWS using the permissions associated with the IAM role.

Scaffolding the profile is a 2-step configuration process:

1. Configure an IAM Role from the `IAM Management Console`_.
2. Attach this role to a new profile. It can be done with the `AWS CLI`_:

    .. code-block:: bash

        > aws iam create-instance-profile --instance-profile-name PROFILE_NAME
        > aws iam add-role-to-instance-profile --instance-profile-name PROFILE_NAME --role-name ROLE_NAME

Once the profile is created, you can use the **PROFILE_NAME** to configure
your cloud profiles.

.. _`IAM Management Console`: https://console.aws.amazon.com/iam/home?#roles
.. _`AWS CLI`: http://docs.aws.amazon.com/cli/latest/index.html
.. _`instance profile`: http://docs.aws.amazon.com/IAM/latest/UserGuide/instance-profiles.html

Cloud Profiles
==============
Set up an initial profile at ``/etc/salt/cloud.profiles``:

.. code-block:: yaml

    base_ec2_private:
      provider: my-ec2-southeast-private-ips
      image: ami-e565ba8c
      size: t2.micro
      ssh_username: ec2-user

    base_ec2_public:
      provider: my-ec2-southeast-public-ips
      image: ami-e565ba8c
      size: t2.micro
      ssh_username: ec2-user

    base_ec2_db:
      provider: my-ec2-southeast-public-ips
      image: ami-e565ba8c
      size: m1.xlarge
      ssh_username: ec2-user
      volumes:
        - { size: 10, device: /dev/sdf }
        - { size: 10, device: /dev/sdg, type: io1, iops: 1000 }
        - { size: 10, device: /dev/sdh, type: io1, iops: 1000 }
        - { size: 10, device: /dev/sdi, tags: {"Environment": "production"} }
      # optionally add tags to profile:
      tag: {'Environment': 'production', 'Role': 'database'}
      # force grains to sync after install
      sync_after_install: grains

    base_ec2_vpc:
      provider: my-ec2-southeast-public-ips
      image: ami-a73264ce
      size: m1.xlarge
      ssh_username: ec2-user
      script:  /etc/salt/cloud.deploy.d/user_data.sh
      network_interfaces:
        - DeviceIndex: 0
          PrivateIpAddresses:
            - Primary: True
          #auto assign public ip (not EIP)
          AssociatePublicIpAddress: True
          SubnetId: subnet-813d4bbf
          SecurityGroupId:
            - sg-750af413
      del_root_vol_on_destroy: True
      del_all_vol_on_destroy: True
      volumes:
        - { size: 10, device: /dev/sdf }
        - { size: 10, device: /dev/sdg, type: io1, iops: 1000 }
        - { size: 10, device: /dev/sdh, type: io1, iops: 1000 }
      tag: {'Environment': 'production', 'Role': 'database'}
      sync_after_install: grains

The profile can now be realized with a salt command:

.. code-block:: bash

    # salt-cloud -p base_ec2 ami.example.com
    # salt-cloud -p base_ec2_public ami.example.com
    # salt-cloud -p base_ec2_private ami.example.com

This will create an instance named ``ami.example.com`` in EC2. The minion that
is installed on this instance will have an ``id`` of ``ami.example.com``. If
the command was executed on the salt-master, its Salt key will automatically be
signed on the master.

Once the instance has been created with salt-minion installed, connectivity to
it can be verified with Salt:

.. code-block:: bash

    # salt 'ami.example.com' test.ping

Required Settings
=================
The following settings are always required for EC2:

.. code-block:: yaml

    # Set the EC2 login data
    my-ec2-config:
      id: HJGRYCILJLKJYG
      key: 'kdjgfsgm;woormgl/aserigjksjdhasdfgn'
      keyname: test
      securitygroup: quick-start
      private_key: /root/test.pem
      driver: ec2

Optional Settings
=================

EC2 allows a userdata file to be passed to the instance to be created. This
functionality was added to Salt in the 2015.5.0 release.

.. code-block:: yaml

    my-ec2-config:
      # Pass userdata to the instance to be created
      userdata_file: /etc/salt/my-userdata-file

EC2 allows a location to be set for servers to be deployed in. Availability
zones exist inside regions, and may be added to increase specificity.

.. code-block:: yaml

    my-ec2-config:
      # Optionally configure default region
      location: ap-southeast-1
      availability_zone: ap-southeast-1b

EC2 instances can have a public or private IP, or both. When an instance is
deployed, Salt Cloud needs to log into it via SSH to run the deploy script.
By default, the public IP will be used for this. If the salt-cloud command is
run from another EC2 instance, the private IP should be used.

.. code-block:: yaml

    my-ec2-config:
      # Specify whether to use public or private IP for deploy script
      # private_ips or public_ips
      ssh_interface: public_ips

Many EC2 instances do not allow remote access to the root user by default.
Instead, another user must be used to run the deploy script using sudo. Some
common usernames include ec2-user (for Amazon Linux), ubuntu (for Ubuntu
instances), admin (official Debian) and bitnami (for images provided by
Bitnami).

.. code-block:: yaml

    my-ec2-config:
      # Configure which user to use to run the deploy script
      ssh_username: ec2-user

Multiple usernames can be provided, in which case Salt Cloud will attempt to
guess the correct username. This is mostly useful in the main configuration
file:

.. code-block:: yaml

    my-ec2-config:
      ssh_username:
        - ec2-user
        - ubuntu
        - admin
        - bitnami

Multiple security groups can also be specified in the same fashion:

.. code-block:: yaml

    my-ec2-config:
      securitygroup:
        - default
        - extra

Your instances may optionally make use of EC2 Spot Instances. The
following example will request that spot instances be used and your
maximum bid will be $0.10. Keep in mind that different spot prices
may be needed based on the current value of the various EC2 instance
sizes. You can check current and past spot instance pricing via the
EC2 API or AWS Console.

.. code-block:: yaml

    my-ec2-config:
      spot_config:
        spot_price: 0.10

By default, the spot instance type is set to 'one-time', meaning it will
be launched and, if it's ever terminated for whatever reason, it will not
be recreated. If you would like your spot instances to be relaunched after
a termination (by your or AWS), set the ``type`` to 'persistent'.

NOTE: Spot instances are a great way to save a bit of money, but you do
run the risk of losing your spot instances if the current price for the
instance size goes above your maximum bid.

The following parameters may be set in the cloud configuration file to
control various aspects of the spot instance launching:

* ``wait_for_spot_timeout``: seconds to wait before giving up on spot instance
  launch (default=600)
* ``wait_for_spot_interval``: seconds to wait in between polling requests to
  determine if a spot instance is available (default=30)
* ``wait_for_spot_interval_multiplier``: a multiplier to add to the interval in
  between requests, which is useful if AWS is throttling your requests
  (default=1)
* ``wait_for_spot_max_failures``: maximum number of failures before giving up
  on launching your spot instance (default=10)

If you find that you're being throttled by AWS while polling for spot
instances, you can set the following in your core cloud configuration
file that will double the polling interval after each request to AWS.

.. code-block:: yaml

    wait_for_spot_interval: 1
    wait_for_spot_interval_multiplier: 2

See the `AWS Spot Instances`_ documentation for more information.

Block device mappings enable you to specify additional EBS volumes or instance
store volumes when the instance is launched. This setting is also available on
each cloud profile. Note that the number of instance stores varies by instance
type.  If more mappings are provided than are supported by the instance type,
mappings will be created in the order provided and additional mappings will be
ignored. Consult the `AWS documentation`_ for a listing of the available
instance stores, and device names.

.. code-block:: yaml

    my-ec2-config:
      block_device_mappings:
        - DeviceName: /dev/sdb
          VirtualName: ephemeral0
        - DeviceName: /dev/sdc
          VirtualName: ephemeral1

You can also use block device mappings to change the size of the root device at the
provisioning time. For example, assuming the root device is '/dev/sda', you can set
its size to 100G by using the following configuration.

.. code-block:: yaml

    my-ec2-config:
      block_device_mappings:
        - DeviceName: /dev/sda
          Ebs.VolumeSize: 100
          Ebs.VolumeType: gp2
          Ebs.SnapshotId: dummy0
        - DeviceName: /dev/sdb
          # required for devices > 2TB
          Ebs.VolumeType: gp2
          Ebs.VolumeSize: 3001

Existing EBS volumes may also be attached (not created) to your instances or
you can create new EBS volumes based on EBS snapshots. To simply attach an
existing volume use the ``volume_id`` parameter.

.. code-block:: yaml

    device: /dev/xvdj
    volume_id: vol-12345abcd

Or, to create a volume from an EBS snapshot, use the ``snapshot`` parameter.

.. code-block:: yaml

    device: /dev/xvdj
    snapshot: snap-abcd12345

Note that ``volume_id`` will take precedence over the ``snapshot`` parameter.

Tags can be set once an instance has been launched.

.. code-block:: yaml

    my-ec2-config:
        tag:
            tag0: value
            tag1: value

.. _`AWS documentation`: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html
.. _`AWS Spot Instances`: http://aws.amazon.com/ec2/purchasing-options/spot-instances/

Modify EC2 Tags
===============
One of the features of EC2 is the ability to tag resources. In fact, under the
hood, the names given to EC2 instances by salt-cloud are actually just stored
as a tag called Name. Salt Cloud has the ability to manage these tags:

.. code-block:: bash

    salt-cloud -a get_tags mymachine
    salt-cloud -a set_tags mymachine tag1=somestuff tag2='Other stuff'
    salt-cloud -a del_tags mymachine tag1,tag2,tag3

It is possible to manage tags on any resource in EC2 with a Resource ID, not
just instances:

.. code-block:: bash

    salt-cloud -f get_tags my_ec2 resource_id=af5467ba
    salt-cloud -f set_tags my_ec2 resource_id=af5467ba tag1=somestuff
    salt-cloud -f del_tags my_ec2 resource_id=af5467ba tag1,tag2,tag3

Rename EC2 Instances
====================
As mentioned above, EC2 instances are named via a tag. However, renaming an
instance by renaming its tag will cause the salt keys to mismatch. A rename
function exists which renames both the instance, and the salt keys.

.. code-block:: bash

    salt-cloud -a rename mymachine newname=yourmachine

Rename on Destroy
=================
When instances on EC2 are destroyed, there will be a lag between the time that
the action is sent, and the time that Amazon cleans up the instance. During
this time, the instance still retails a Name tag, which will cause a collision
if the creation of an instance with the same name is attempted before the
cleanup occurs. In order to avoid such collisions, Salt Cloud can be configured
to rename instances when they are destroyed. The new name will look something
like:

.. code-block:: bash

    myinstance-DEL20f5b8ad4eb64ed88f2c428df80a1a0c

In order to enable this, add rename_on_destroy line to the main
configuration file:

.. code-block:: yaml

    my-ec2-config:
      rename_on_destroy: True

Listing Images
==============
Normally, images can be queried on a cloud provider by passing the
``--list-images`` argument to Salt Cloud. This still holds true for EC2:

.. code-block:: bash

    salt-cloud --list-images my-ec2-config

However, the full list of images on EC2 is extremely large, and querying all of
the available images may cause Salt Cloud to behave as if frozen. Therefore,
the default behavior of this option may be modified, by adding an ``owner``
argument to the provider configuration:

.. code-block:: yaml

    owner: aws-marketplace

The possible values for this setting are ``amazon``, ``aws-marketplace``,
``self``, ``<AWS account ID>`` or ``all``. The default setting is ``amazon``.
Take note that ``all`` and ``aws-marketplace`` may cause Salt Cloud to appear
as if it is freezing, as it tries to handle the large amount of data.

It is also possible to perform this query using different settings without
modifying the configuration files. To do this, call the ``avail_images``
function directly:

.. code-block:: bash

    salt-cloud -f avail_images my-ec2-config owner=aws-marketplace

EC2 Images
==========
The following are lists of available AMI images, generally sorted by OS. These
lists are on 3rd-party websites, are not managed by Salt Stack in any way. They
are provided here as a reference for those who are interested, and contain no
warranty (express or implied) from anyone affiliated with Salt Stack. Most of
them have never been used, much less tested, by the Salt Stack team.

* `Arch Linux`__

.. __: https://wiki.archlinux.org/index.php/Arch_Linux_AMIs_for_Amazon_Web_Services

* `FreeBSD`__

.. __: http://www.daemonology.net/freebsd-on-ec2/

* `Fedora`__

.. __: https://fedoraproject.org/wiki/Cloud_images

* `CentOS`__

.. __: http://wiki.centos.org/Cloud/AWS

* `Ubuntu`__

.. __: http://cloud-images.ubuntu.com/locator/ec2/

* `Debian`__

.. __: https://wiki.debian.org/Cloud/AmazonEC2Image

* `OmniOS`__

.. __: http://omnios.omniti.com/wiki.php/Installation#IntheCloud

* `All Images on Amazon`__

.. __: https://aws.amazon.com/marketplace

show_image
==========
This is a function that describes an AMI on EC2. This will give insight as to
the defaults that will be applied to an instance using a particular AMI.

.. code-block:: bash

    $ salt-cloud -f show_image ec2 image=ami-fd20ad94

show_instance
=============
This action is a thin wrapper around ``--full-query``, which displays details on a
single instance only. In an environment with several machines, this will save a
user from having to sort through all instance data, just to examine a single
instance.

.. code-block:: bash

    $ salt-cloud -a show_instance myinstance

ebs_optimized
=============
This argument enables switching of the EbsOptimized setting which default
to 'false'. Indicates whether the instance is optimized for EBS I/O. This
optimization provides dedicated throughput to Amazon EBS and an optimized
configuration stack to provide optimal Amazon EBS I/O performance. This
optimization isn't available with all instance types. Additional usage
charges apply when using an EBS-optimized instance.

This setting can be added to the profile or map file for an instance.

If set to True, this setting will enable an instance to be EbsOptimized

.. code-block:: yaml

   ebs_optimized: True

This can also be set as a cloud provider setting in the EC2 cloud
configuration:

.. code-block:: yaml

   my-ec2-config:
     ebs_optimized: True

del_root_vol_on_destroy
=======================
This argument overrides the default DeleteOnTermination setting in the AMI for
the EBS root volumes for an instance. Many AMIs contain 'false' as a default,
resulting in orphaned volumes in the EC2 account, which may unknowingly be
charged to the account. This setting can be added to the profile or map file
for an instance.

If set, this setting will apply to the root EBS volume

.. code-block:: yaml

    del_root_vol_on_destroy: True

This can also be set as a cloud provider setting in the EC2 cloud
configuration:

.. code-block:: yaml

    my-ec2-config:
      del_root_vol_on_destroy: True

del_all_vols_on_destroy
=======================
This argument overrides the default DeleteOnTermination setting in the AMI for
the not-root EBS volumes for an instance. Many AMIs contain 'false' as a
default, resulting in orphaned volumes in the EC2 account, which may
unknowingly be charged to the account. This setting can be added to the profile
or map file for an instance.

If set, this setting will apply to any (non-root) volumes that were created
by salt-cloud using the 'volumes' setting.

The volumes will not be deleted under the following conditions
* If a volume is detached before terminating the instance
* If a volume is created without this setting and attached to the instance

.. code-block:: yaml

    del_all_vols_on_destroy: True

This can also be set as a cloud provider setting in the EC2 cloud
configuration:

.. code-block:: yaml

    my-ec2-config:
      del_all_vols_on_destroy: True

The setting for this may be changed on all volumes of an existing instance
using one of the following commands:

.. code-block:: bash

    salt-cloud -a delvol_on_destroy myinstance
    salt-cloud -a keepvol_on_destroy myinstance
    salt-cloud -a show_delvol_on_destroy myinstance

The setting for this may be changed on a volume on an existing instance
using one of the following commands:

.. code-block:: bash

    salt-cloud -a delvol_on_destroy myinstance device=/dev/sda1
    salt-cloud -a delvol_on_destroy myinstance volume_id=vol-1a2b3c4d
    salt-cloud -a keepvol_on_destroy myinstance device=/dev/sda1
    salt-cloud -a keepvol_on_destroy myinstance volume_id=vol-1a2b3c4d
    salt-cloud -a show_delvol_on_destroy myinstance device=/dev/sda1
    salt-cloud -a show_delvol_on_destroy myinstance volume_id=vol-1a2b3c4d

EC2 Termination Protection
==========================

EC2 allows the user to enable and disable termination protection on a specific
instance. An instance with this protection enabled cannot be destroyed. The EC2
driver adds a show_term_protect action to the regular EC2 functionality.

.. code-block:: bash

    salt-cloud -a show_term_protect mymachine
    salt-cloud -a enable_term_protect mymachine
    salt-cloud -a disable_term_protect mymachine

Alternate Endpoint
==================
Normally, EC2 endpoints are build using the region and the service_url. The
resulting endpoint would follow this pattern:

.. code-block:: bash

    ec2.<region>.<service_url>

This results in an endpoint that looks like:

.. code-block:: bash

    ec2.us-east-1.amazonaws.com

There are other projects that support an EC2 compatibility layer, which this
scheme does not account for. This can be overridden by specifying the endpoint
directly in the main cloud configuration file:

.. code-block:: yaml

    my-ec2-config:
      endpoint: myendpoint.example.com:1138/services/Cloud

Volume Management
=================
The EC2 driver has several functions and actions for management of EBS volumes.

Creating Volumes
----------------
A volume may be created, independent of an instance. A zone must be specified.
A size or a snapshot may be specified (in GiB). If neither is given, a default
size of 10 GiB will be used. If a snapshot is given, the size of the snapshot
will be used.

The following parameters may also be set (when providing a snapshot OR size):

* ``type``: choose between standard (magnetic disk), gp2 (SSD), or io1 (provisioned IOPS).
  (default=standard)
* ``iops``: the number of IOPS (only applicable to io1 volumes) (default varies on volume size)
* ``encrypted``: enable encryption on the volume (default=false)

.. code-block:: bash

    salt-cloud -f create_volume ec2 zone=us-east-1b
    salt-cloud -f create_volume ec2 zone=us-east-1b size=10
    salt-cloud -f create_volume ec2 zone=us-east-1b snapshot=snap12345678
    salt-cloud -f create_volume ec2 size=10 type=standard
    salt-cloud -f create_volume ec2 size=10 type=gp2
    salt-cloud -f create_volume ec2 size=10 type=io1 iops=1000

Attaching Volumes
-----------------
Unattached volumes may be attached to an instance. The following values are
required; name or instance_id, volume_id, and device.

.. code-block:: bash

    salt-cloud -a attach_volume myinstance volume_id=vol-12345 device=/dev/sdb1

Show a Volume
-------------
The details about an existing volume may be retrieved.

.. code-block:: bash

    salt-cloud -a show_volume myinstance volume_id=vol-12345
    salt-cloud -f show_volume ec2 volume_id=vol-12345

Detaching Volumes
-----------------
An existing volume may be detached from an instance.

.. code-block:: bash

    salt-cloud -a detach_volume myinstance volume_id=vol-12345

Deleting Volumes
----------------
A volume that is not attached to an instance may be deleted.

.. code-block:: bash

    salt-cloud -f delete_volume ec2 volume_id=vol-12345

Managing Key Pairs
==================
The EC2 driver has the ability to manage key pairs.

Creating a Key Pair
-------------------
A key pair is required in order to create an instance. When creating a key pair
with this function, the return data will contain a copy of the private key.
This private key is not stored by Amazon, will not be obtainable past this
point, and should be stored immediately.

.. code-block:: bash

    salt-cloud -f create_keypair ec2 keyname=mykeypair

Importing a Key Pair
--------------------

.. code-block:: bash

    salt-cloud -f import_keypair ec2 keyname=mykeypair file=/path/to/id_rsa.pub

Show a Key Pair
---------------
This function will show the details related to a key pair, not including the
private key itself (which is not stored by Amazon).

.. code-block:: bash

    salt-cloud -f show_keypair ec2 keyname=mykeypair

Delete a Key Pair
-----------------
This function removes the key pair from Amazon.

.. code-block:: bash

    salt-cloud -f delete_keypair ec2 keyname=mykeypair

Launching instances into a VPC
==============================

Simple launching into a VPC
---------------------------

In the amazon web interface, identify the id of the subnet into which your
image should be created. Then, edit your cloud.profiles file like so:-

.. code-block:: yaml

    profile-id:
      provider: provider-name
      subnetid: subnet-XXXXXXXX
      image: ami-XXXXXXXX
      size: m1.medium
      ssh_username: ubuntu
      securitygroupid:
        - sg-XXXXXXXX

Specifying interface properties
-------------------------------

.. versionadded:: 2014.7.0

Launching into a VPC allows you to specify more complex configurations for
the network interfaces of your virtual machines, for example:-

.. code-block:: yaml

    profile-id:
      provider: provider-name
      image: ami-XXXXXXXX
      size: m1.medium
      ssh_username: ubuntu

      # Do not include either 'subnetid' or 'securitygroupid' here if you are
      # going to manually specify interface configuration
      #
      network_interfaces:
        - DeviceIndex: 0
          SubnetId: subnet-XXXXXXXX
          SecurityGroupId:
            - sg-XXXXXXXX

          # Uncomment this line if you would like to set an explicit private
          # IP address for the ec2 instance
          #
          # PrivateIpAddress: 192.168.1.66

          # Uncomment this to associate an existing Elastic IP Address with
          # this network interface:
          #
          # associate_eip: eipalloc-XXXXXXXX

          # You can allocate more than one IP address to an interface. Use the
          # 'ip addr list' command to see them.
          #
          # SecondaryPrivateIpAddressCount: 2

          # Uncomment this to allocate a new Elastic IP Address to this
          # interface (will be associated with the primary private ip address
          # of the interface
          #
          # allocate_new_eip: True

          # Uncomment this instead to allocate a new Elastic IP Address to
          # both the primary private ip address and each of the secondary ones
          #
          allocate_new_eips: True

          # Uncomment this if you're creating NAT instances. Allows an instance
          # to accept IP packets with destinations other than itself.
          # SourceDestCheck: False

Note that it is an error to assign a 'subnetid' or 'securitygroupid' to a
profile where the interfaces are manually configured like this. These are both
really properties of each network interface, not of the machine itself.


text:
angular.module('starter.countries',[])
.factory('Countries', function($http){
  var theMessage = 'Lista de paises';
  var savedCountries = {};
  var selectedCountry = {};

  return{
    getMessage: function(){
      return theMessage;
    },
    all: function(){
      return savedCountries;
    },
    selectCountry: function(country){
      selectedCountry = country;
      console.log("El país seleccionado es "+ selectedCountry.name)
    },
    getSelectedCountry: function(){
      return selectedCountry;
    }

  }
});


text:
<?php

namespace Predis\Command;

/**
 * @link http://redis.io/commands/unsubscribe
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class PubSubUnsubscribe extends AbstractCommand implements PrefixableCommandInterface
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'UNSUBSCRIBE';
    }

    /**
     * {@inheritdoc}
     */
    protected function filterArguments(Array $arguments)
    {
        return self::normalizeArguments($arguments);
    }

    /**
     * {@inheritdoc}
     */
    public function prefixKeys($prefix)
    {
        PrefixHelpers::all($this, $prefix);
    }
}


text:
<!DOCTYPE html>

  <meta name="project_path" value="/web/tools/workbox/_project.yaml" />
  <meta name="book_path" value="/web/tools/workbox/_book.yaml" />
  <meta name="gtm_var" data-key="docType" data-value="reference">
  <title>Source: workbox-strategies/NetworkOnly.mjs</title>
  <link href="jsdoc.css" rel="stylesheet">

Source: workbox-strategies/NetworkOnly.mjs

import {assert} from 'workbox-core/_private/assert.mjs';
import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
import {logger} from 'workbox-core/_private/logger.mjs';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';

import {messages} from './utils/messages.mjs';
import './_version.mjs';

/**
 * An implementation of a
 * [network-only]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#network-only}
 * request strategy.
 *
 * This class is useful if you want to take advantage of any
 * [Workbox plugins]{@link /web/tools/workbox/guides/using-plugins}.
 *
 * If the network request fails, this will throw a `WorkboxError` exception.
 *
 * @memberof workbox.strategies
 */
class NetworkOnly {
  /**
   * @param {Object} options
   * @param {string} options.cacheName Cache name to store and retrieve
   * requests. Defaults to cache names provided by
   * [workbox-core]{@link workbox.core.cacheNames}.
   * @param {Array&lt;Object>} options.plugins [Plugins]{@link /web/tools/workbox/guides/using-plugins}
   * to use in conjunction with this caching strategy.
   * @param {Object} options.fetchOptions Values passed along to the
   * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
   * of all fetch() requests made by this strategy.
   */
  constructor(options = {}) {
    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    this._plugins = options.plugins || [];
    this._fetchOptions = options.fetchOptions || null;
  }

  /**
   * This method will perform a request strategy and follows an API that
   * will work with the
   * [Workbox Router]{@link workbox.routing.Router}.
   *
   * @param {Object} options
   * @param {Request} options.request The request to run this strategy for.
   * @param {Event} [options.event] The event that triggered the request.
   * @return {Promise&lt;Response>}
   */
  async handle({event, request}) {
    return this.makeRequest({
      event,
      request: request || event.request,
    });
  }

  /**
   * This method can be used to perform a make a standalone request outside the
   * context of the [Workbox Router]{@link workbox.routing.Router}.
   *
   * See "[Advanced Recipes](/web/tools/workbox/guides/advanced-recipes#make-requests)"
   * for more usage information.
   *
   * @param {Object} options
   * @param {Request|string} options.request Either a
   *     [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
   *     object, or a string URL, corresponding to the request to be made.
   * @param {FetchEvent} [options.event] If provided, `event.waitUntil()` will
   *     be called automatically to extend the service worker's lifetime.
   * @return {Promise&lt;Response>}
   */
  async makeRequest({event, request}) {
    if (typeof request === 'string') {
      request = new Request(request);
    }

    if (process.env.NODE_ENV !== 'production') {
      assert.isInstance(request, Request, {
        moduleName: 'workbox-strategies',
        className: 'NetworkOnly',
        funcName: 'handle',
        paramName: 'request',
      });
    }

    let error;
    let response;
    try {
      response = await fetchWrapper.fetch({
        request,
        event,
        fetchOptions: this._fetchOptions,
        plugins: this._plugins,
      });
    } catch (err) {
      error = err;
    }

    if (process.env.NODE_ENV !== 'production') {
      logger.groupCollapsed(
          messages.strategyStart('NetworkOnly', request));
      if (response) {
        logger.log(`Got response from network.`);
      } else {
        logger.log(`Unable to get a response from the network.`);
      }
      messages.printFinalResponse(response);
      logger.groupEnd();
    }

    if (!response) {
      throw new WorkboxError('no-response', {url: request.url, error});
    }
    return response;
  }
}

export {NetworkOnly};


text:
Translations are stored in the database through the admin panel (/admin/translations).
You can get DB translations with ``` Lang::get('db.Key') ```, ``` trans('db.Key') ``` or ``` @lang('db.Key') ```.

This module is part of [TypiCMS](https://github.com/TypiCMS/Base), a multilingual CMS based on Laravel 5.


text:
var ctrl = new Meteoris.SiteController();

Template.meteoris_siteIndex.onCreated(function(){
    console.log(Meteoris.User.isExist());
})

/**
In the template helper section we are using index() method to get object return value from controller. It's because index was the action and also the file name suffix. This structure will make You easier to get jobs done, when your team getting bigger and the code getting bigger.
*/
Template.meteoris_siteIndex.helpers({
    myName: function () {
        return ctrl.index().myName;
    },
    myHobby: function () {
        return ctrl.index().myHobby;
    },
    counter: function () {
      return ctrl.index().counter;
    }
  });

/**
in the template events, we don't need to use index() method to call any action. Because it just simply method calling through controller.
*/
Template.meteoris_siteIndex.events({
    'click button': function () {
      //increment the counter when button is clicked
      ctrl.setCounter();
    }
});


text:
namespace angle
{

namespace pp
{

Macro::Macro() : predefined(false), disabled(false), expansionCount(0), type(kTypeObj) {}

Macro::~Macro() {}

bool Macro::equals(const Macro &other) const
{
    return (type == other.type) && (name == other.name) && (parameters == other.parameters) &&
           (replacements == other.replacements);
}

void PredefineMacro(MacroSet *macroSet, const char *name, int value)
{
    Token token;
    token.type = Token::CONST_INT;
    token.text = ToString(value);

    std::shared_ptr<Macro> macro = std::make_shared<Macro>();
    macro->predefined            = true;
    macro->type                  = Macro::kTypeObj;
    macro->name                  = name;
    macro->replacements.push_back(token);

    (*macroSet)[name] = macro;
}

}  // namespace pp

}  // namespace angle


text:
'use strict';

(function() {

    angular
        .module('HangmanApp')
        .controller('MainController', ['$firebaseObject', MainController]);

    function MainController($firebaseObject) {
        var vm = this,
        	ref = new Firebase("https://gdg-cola-web-codelab.firebaseio.com/");

        console.dir(ref);
    }
})();


text:
require("../shader/OscFragment");

import dat from "dat.gui";
import THREE from "../ThreeLight";
import Particle from "./Particle-alt";

// Render Class Object //
export default class Render {
  constructor() {
    this.frames = 360;
    this.size = 5;
    this.speed = 5.0;
    this.amps = 500;
    this.scale = 1.0;
    this.ratio = 1024;
    this.angle = 255.0;
    this.dec = 26.0;
    this.mirror = 4;

    // Camera Stuff and Viewport //
    this.width = window.innerWidth;
    this.height = window.innerHeight;
    this.aspect = this.width / this.height;
    this.devicePixelRatio = window.devicePixelRatio;
    this.viewAngle = 45;
    this.aspect = this.width / this.height;
    this.near = 1;
    this.far = 20000;
    // Particles Stuff //

    this.particles = [];
    this.particleColor = 360;
    this.background = 0x333333;
    this.camPosition = {
      x: -1500.0,
      y: -90.0,
      z: -200.0
    };
    this.trsPosition = {
      x: -1500.0,
      y: -90.0,
      z: -200.0
    };
    this.emitter = {
      x: 0,
      y: 0,
      z: -1200
    };
    const bsize = 6000;
    this.box = {
      top: bsize,
      left: -bsize,
      bottom: -bsize,
      right: bsize
    };
    this.settings = {
      gravity: 0.0,
      bounce: 0.35
    };
    this.threshold = 0.6;
    this.strength = 1.7;
    this.radius = 0.65;
    this.camTimeoutx = true;
    this.camTimeouty = true;
    this.camTimeoutz = true;
    setTimeout(() => {
      this.camTimeoutx = false;
      this.camTimeouty = false;
      this.camTimeoutz = false;
    }, 3000 + 600 * Math.random() * 10);
    window.addEventListener("resize", this.resize, true);
    window.addEventListener(
      "click",
      () => {
        console.log(this.camera.position);
      },
      true
    );
    this.setRender();
    this.setEffects();
    // this.createGUI();
    this.renderLoop();
    // this.music();
  }

  resize = () => {
    this.width = window.innerWidth;
    this.height = window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(this.width, this.height);
  };

  createGUI = () => {
    this.options = {
      gravity: this.settings.gravity * 100,
      bounce: this.settings.bounce * 100,
      amps: this.amps
    };
    this.gui = new dat.GUI();
    const folderRender = this.gui.addFolder("Particle Options");
    // folderRender.add(this.options, 'gravity', 0, 100).step(1)
    //   .onFinishChange((value) => {
    //     this.settings.gravity = value * 0.01;
    //   });
    // folderRender.add(this.options, 'bounce', 0, 100).step(1)
    //   .onFinishChange((value) => {
    //     this.settings.bounce = value * 0.01;
    //   });
    folderRender
      .add(this.options, "amps", 0, 800)
      .step(1)
      .onFinishChange(value => {
        this.amps = value;
      });
  };

  setRender = () => {
    // Set Render and Scene //
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(this.width, this.height);
    this.renderer.setPixelRatio(this.devicePixelRatio);
    document.body.appendChild(this.renderer.domElement);

    this.scene = new THREE.Scene();
    this.scene.fog = new THREE.FogExp2(this.background, 0.0006);
    this.scene.background = new THREE.Color(this.background);

    this.camera = new THREE.PerspectiveCamera(
      this.viewAngle,
      this.aspect,
      this.near,
      this.far
    );

    this.camera.position.set(0, 0, 1200);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));

    this.controls = new THREE.OrbitControls(this.camera);
    this.controls.maxDistance = 2500;
    this.controls.minDistance = 0;

    // Set Lights //
    let pointLight = new THREE.PointLight(0xdddddd);
    pointLight.position.set(450, 450, -800);
    this.scene.add(pointLight);
    pointLight = new THREE.PointLight(0xeeeeee);
    pointLight.position.set(-250, -850, 800);
    this.scene.add(pointLight);
    let ambient = new THREE.AmbientLight(0x9f9f9f);
    ambient.position.set(1, 200, -200);
    this.scene.add(ambient);
  };

  music = () => {
    const youtube = document.createElement("iframe");
    youtube.width = 1;
    youtube.height = 1;
    const videoid = "3vnZnuqgh7U";
    youtube.wmode = "transparent";
    const html = "https://www.youtube.com/embed/n6tVkGsaE94?rel=0&autoplay=1";
    youtube.src = encodeURI(html); // 'data:text/html;charset=utf-8,' + // e4GJsV3PzsI // gkyFQTUR-rA
    youtube.frameborder = 0;
    document.body.appendChild(youtube);
    const overlay = document.createElement("div");
    const link = document.createElement("a");
    const image = document.createElement("img");
    image.src = "https://img.youtube.com/vi/n6tVkGsaE94/sddefault.jpg";
    image.width = 60;
    image.height = 45;
    image.style.float = "left";
    image.style.margin = "0 0 0 15px";
    link.href = html;
    link.innerHTML = "Music by Lorn | Shelter";
    overlay.style.position = "absolute";
    overlay.style.bottom = "15px";
    overlay.style.left = "0";
    overlay.style.lineHeight = "45px";
    overlay.style.zIndex = "9999";
    link.style.color = "#FFF";
    link.style.padding = "15px";
    overlay.appendChild(image);
    overlay.appendChild(link);
    document.body.appendChild(overlay);
  };

  setEffects = () => {
    // this.effect = new THREE.AnaglyphEffect(this.renderer);
    // this.effect.setSize(this.width, this.height);
    this.composer = new THREE.EffectComposer(this.renderer);
    this.composer.addPass(new THREE.RenderPass(this.scene, this.camera));

    const renderPass = new THREE.RenderPass(this.scene, this.camera);
    this.composer.addPass(renderPass);

    this.bloomPass = new THREE.UnrealBloomPass(
      new THREE.Vector2(window.innerWidth, window.innerHeight),
      this.strength,
      this.radius,
      1.0 - this.threshold
    );
    this.composer.addPass(this.bloomPass);

    // const copyEffect = new THREE.ShaderPass(THREE.CopyShader);
    // copyEffect.renderToScreen = true;
    // this.composer.addPass(copyEffect);
    this.rfrag = new THREE.ShaderPass(THREE.RenderFragment);
    // this.rfrag.uniforms.scale.value = this.scale;
    // this.rfrag.uniforms.ratio.value = this.ratio;
    // this.rfrag.uniforms.time.value = this.frames;
    this.rfrag.renderToScreen = true;
    this.composer.addPass(this.rfrag);
  };

  hitRnd = () => {
    const { x, y, z } = this.emitter;
    this.frames++;
    let iter = 2.0;
    let amps =
      40 + Math.abs(this.amps * Math.cos((this.frames * 0.2 * Math.PI) / 180));
    let sVar = amps * Math.sin((this.frames * iter * Math.PI) / 180);
    let cVar = amps * Math.cos((this.frames * iter * Math.PI) / 180);
    let dVar = amps * Math.cos((this.frames * 0.4 * 8 * Math.PI) / 180);
    this.makeParticle(x + sVar, y + cVar, z + dVar);
    this.makeParticle(x - sVar, y - cVar, z + dVar);
  };

  makeParticle = (mx, my, mz) => {
    const geometry = new THREE.BoxBufferGeometry(
      this.size / 2,
      this.size * 3,
      this.size * 8
    );
    const sphere = new THREE.Mesh(
      geometry,
      new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x999999 })
    );
    sphere.castShadow = true;
    sphere.receiveShadow = true;

    const point = new Particle({
      size: this.size,
      x: mx,
      y: my,
      z: mz,
      vx: -(0.0 - mx) * 0.005,
      vy: -(0.0 - my) * 0.005,
      vz: this.speed,
      box: this.box,
      settings: this.settings,
      ref: sphere,
      decay: 0.000015
    });

    sphere.position.set(mx, my, mz);
    sphere.scale.x = this.size;
    sphere.scale.y = this.size;
    sphere.scale.z = this.size;
    const ex = this.emitter.x;
    const ey = this.emitter.y;
    const ry = (Math.atan2(my - ey, mx - ex) * Math.PI) / 180;

    sphere.rotateZ(((15 + ry) * 180) / Math.PI);

    // const cRed = Math.sin(this.frames * 0.25 * Math.PI / 180);
    // const cGreen = Math.cos(this.frames * 0.25 * Math.PI / 180);
    // const cBlue = 0.9 - Math.sin(this.frames * 0.25 * Math.PI / 180);
    // sphere.material.color.setRGB(cRed, cGreen ,cBlue);
    // const particleColor = Math.abs(Math.sin(this.frames * 0.25 * Math.PI / 180) * 0.75);
    const offsetColor =
      0.85 - Math.abs(Math.cos((this.frames * 0.25 * Math.PI) / 180));
    sphere.material.color.setRGB(offsetColor, offsetColor, offsetColor);
    // sphere.material.color.setHSL(particleColor,1,0.5);

    this.particles.push(point);
    this.scene.add(sphere);
  };

  checkParticles = () => {
    for (let i = 0; i < this.particles.length; i++) {
      const part = this.particles[i];
      part.update();
      part.ref.position.set(part.x, part.y, part.z);
      part.ref.scale.x = part.size;
      part.ref.scale.y = part.size;
      part.ref.scale.z = part.size;
      if (part.life > 800 || part.size < 0.0) {
        part.ref.geometry.dispose();
        part.ref.material.dispose();
        this.scene.remove(part.ref);
        part.ref = undefined;
        this.particles.splice(i, 1);
      }
    }
  };

  cameraLoop = () => {
    const damp = 0.01;
    this.camPosition.x =
      this.camPosition.x - (this.camPosition.x - this.trsPosition.x) * damp;
    this.camPosition.y =
      this.camPosition.y - (this.camPosition.y - this.trsPosition.y) * damp;
    this.camPosition.z =
      this.camPosition.z - (this.camPosition.z - this.trsPosition.z) * 0.004;

    this.camera.position.set(
      this.camPosition.x,
      this.camPosition.y,
      this.camPosition.z
    );
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));

    if (!this.camTimeoutx && Math.random() * 260 > 250) {
      const tempRand = 100 + Math.random() * 1000;
      this.trsPosition.x =
        Math.random() * 255 > 200
          ? Math.random() * 250 > 100
            ? -tempRand
            : tempRand
          : 0;
      this.camTimeoutx = true;
      setTimeout(() => {
        this.camTimeoutx = false;
      }, 6000 + 1000 * Math.random() * 20);
    }
    if (!this.camTimeouty && Math.random() * 260 > 240) {
      const tempRand = 100 + Math.random() * 1000;
      this.trsPosition.y =
        Math.random() * 255 > 170
          ? Math.random() * 250 > 100
            ? tempRand
            : -tempRand
          : 0;
      this.camTimeouty = true;
      setTimeout(() => {
        this.camTimeouty = false;
      }, 6000 + 1000 * Math.random() * 20);
    }
    if (!this.camTimeoutz && Math.random() * 255 > 253) {
      this.trsPosition.z =
        Math.random() * 200 > 150
          ? 100 + Math.random() * 100
          : -(100 + Math.random() * 100);
      this.camTimeoutz = true;
      setTimeout(() => {
        this.camTimeoutz = false;
      }, 18000 + 1100 * Math.random() * 7);
    }
    if (this.camPosition.x == 0 && this.camPosition.y == 0) {
      this.camera.rotationZ((this.frames * 0.1 * Math.PI) / 180);
    }
  };

  dist = (a, b, c, d) => {
    return Math.sqrt((a - c) * (a - c) + (b - d) * (b - d));
  };
  renderScene = () => {
    this.composer.render();
    // this.renderer.render(this.scene, this.camera);
    // this.effect.render(this.scene, this.camera);
  };

  renderLoop = () => {
    this.checkParticles();

    if (Math.random() * 255 > 245) {
      this.speed = 5.0 + Math.random() * 10;
    }

    if (this.particles.length < 1800 && this.frames % 3 == 0) {
      this.hitRnd();
    }

    this.cameraLoop();
    this.renderScene();
    this.frames++;
    this.rfrag.uniforms.time.value = this.frames * 0.01;
    window.requestAnimationFrame(this.renderLoop);
  };
}


text:
This is a fullstack vue project that be generated by generator-fullstack-vue.

# a fullstack web project, use vue2.0 + vue-router + vuex + vue-router + express

> A fullstack Vue.js project
> use mockjs to split  FE develop & BE develop
> unit test

## Build Setup

``` bash
# install dependencies
npm install

FE:
    # serve with hot reload at localhost:8080
    npm run dev

    # build for production with minification
    npm run build

    # run unit tests
    npm run unit

    # run e2e tests
    npm run e2e

BE:
    # serve with hot reload at localhost:9000
    grunt server

    # build for production, when package project must be run after FE build
    grunt build

    #run unit tests
    grunt test

    #if you have a cms to publish a zip package, you can use grunt upload here

FE & BE

    when you are developing both side, you can anntate mockjs in src/main.js, and
    config the request url in  config/index.js  proxyTable

License

<%- project_license %> © <%- project_author %> (You Website)