text:
class SubnetsController < ApplicationController
  def index
    @search = Subnet.search params[:search]
    @subnets = @search.paginate(:page => params[:page])
  end

  def new
    @subnet = Subnet.new
  end

  def create
    @subnet = Subnet.new(params[:subnet])
    if @subnet.save
      flash[:foreman_notice] = "Successfully created subnet"
      redirect_to subnets_url
    else
      render :action => 'new'
    end
  end

  def edit
    @subnet = Subnet.find(params[:id])
  end

  def update
    @subnet = Subnet.find(params[:id])
    if @subnet.update_attributes(params[:subnet])
      flash[:foreman_notice] = "Successfully updated subnet"
      redirect_to subnets_url
    else
      render :action => 'edit'
    end
  end

  def destroy
    @subnet = Subnet.find(params[:id])
    @subnet.destroy
    flash[:foreman_notice] = "Successfully destroyed subnet"
    redirect_to subnets_url
  end
end


text:
AS3 override functionality allows you to alter the existing Big-IP configuration using AS3 with a Override configmap without affecting the existing Kubernetes resources. The administrator can modify the existing BIG-IP configuration incrementally without having to overwrite/delete the existing one.

Use AS3 override when you want to manually create a virtual server in a CIS managed partition In order to do this you will need to add a new argument to the deployment file.

## Configuring Override AS3 in CIS
* Add the following deployment parameter to enable AS3 override functionality in CIS:

`--override-as3-declaration=<namespace>/<user_defined_configmap_name>`

    args: [
        "--bigip-username=$(BIGIP_USERNAME)",
        "--bigip-password=$(BIGIP_PASSWORD)",
        "--bigip-url=192.168.200.98",
        "--bigip-partition=AS3",
        "--namespace=default",
        "--pool-member-type=cluster",
        "--flannel-name=fl-vxlan",
        "--log-level=INFO",
        "--override-as3-declaration=<namespace>/<override_as3_configmap_name>"
        "--insecure=true",

    Note: The <namespace> must be CIS managed namespace, from above example deployment, <namespace> must be "default".

* Add label overrideAS3:true in configMap metadata to any override AS3 configmap applied so that CIS knows the data fields is override AS3 and not legacy container connector input data. Please note that CIS will use gojsonschema to validate the AS3 data.

    ```
    metadata:
    name: f5-hello-world-https
    namespace: default
    labels:
        f5type: virtual-server
        overrideAS3: "true"
    ```

redpajama_set_name: RedPajamaGithub


text:
//
//  StackViewSecondViewController.m
//  Refresher-OBJC
//
//  Created by on 11/4/16.
//  Copyright © 2016 Inc. All rights reserved.
//
/* Ref:
https://www.youtube.com/watch?v=O0llR7sfrkc
http://krakendev.io/blog/autolayout-magic-like-harry-potter-but-real
http://www.thinkandbuild.it/introduction-to-uistackview/
https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html#//apple_ref/doc/uid/TP40010853-CH11-SW10
*/
#import "StackViewSecondViewController.h"

@interface StackViewSecondViewController ()

@end

@implementation StackViewSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

@end


text:
// Copyright(C) 1999-2017 National Technology & Engineering Solutions
// of Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
// NTESS, the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
//     * Neither the name of NTESS nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef IOSS_Ioss_IOUtils_h
#define IOSS_Ioss_IOUtils_h

#include <Ioss_CodeTypes.h>
#include <Ioss_Field.h>
#include <algorithm> // for sort, lower_bound, copy, etc
#include <cassert>
#include <cstddef>   // for size_t
#include <cstdint>   // for int64_t
#include <cstdlib>   // for nullptrr
#include <iostream>  // for ostringstream, etcstream, etc
#include <stdexcept> // for runtime_error
#include <string>    // for string
#include <vector>    // for vector
namespace Ioss {
  class Field;
} // namespace Ioss
namespace Ioss {
  class GroupingEntity;
  class Region;
  class SideBlock;
  class PropertyManager;
  struct MeshCopyOptions;
} // namespace Ioss

#if __cplusplus > 199711L
#define TOPTR(x) x.data()
#else
#define TOPTR(x) (x.empty() ? nullptr : &x[0])
#endif

#define IOSS_ERROR(errmsg) throw std::runtime_error(errmsg.str())
#define IOSS_WARNING std::cerr

namespace {
  // SEE: http://lemire.me/blog/2017/04/10/removing-duplicates-from-lists-quickly
  template <typename T> size_t unique(std::vector<T> &out, bool skip_first)
  {
    if (out.empty())
      return 0;
    size_t i    = 1;
    size_t pos  = 1;
    T      oldv = out[0];
    if (skip_first) {
      i    = 2;
      pos  = 2;
      oldv = out[1];
    }
    for (; i < out.size(); ++i) {
      T newv   = out[i];
      out[pos] = newv;
      pos += (newv != oldv);
      oldv = newv;
    }
    return pos;
  }
} // namespace

namespace Ioss {

  /* \brief Utility methods.
   */
  class Utils
  {
  public:
    Utils()  = default;
    ~Utils() = default;

    // Assignment operator
    // Copy constructor

    static void check_dynamic_cast(const void *ptr)
    {
      if (ptr == nullptr) {
        std::cerr << "INTERNAL ERROR: Invalid dynamic cast returned nullptr\n";
        exit(EXIT_FAILURE);
      }
    }

    template <typename T> static void uniquify(std::vector<T> &vec, bool skip_first = false)
    {
      auto it = vec.begin();
      if (skip_first) {
        it++;
      }
      std::sort(it, vec.end());
      vec.resize(unique(vec, skip_first));
      vec.shrink_to_fit();
    }

    template <typename T> static void generate_index(std::vector<T> &index)
    {
      T sum = 0;
      for (size_t i = 0; i < index.size() - 1; i++) {
        T cnt    = index[i];
        index[i] = sum;
        sum += cnt;
      }
      index.back() = sum;
    }

    template <typename T> static T find_index_location(T node, const std::vector<T> &index)
    {
    // 0-based node numbering
    // index[p] = first node (0-based) on processor p

#if 1
      // Assume data coherence.  I.e., a new search will be close to the
      // previous search.
      static size_t prev = 1;

      size_t nproc = index.size();
      if (prev < nproc && index[prev - 1] <= node && index[prev] > node) {
        return prev - 1;
      }

      for (size_t p = 1; p < nproc; p++) {
        if (index[p] > node) {
          prev = p;
          return p - 1;
        }
      }
      std::cerr << "FATAL ERROR: find_index_location. Searching for " << node << " in:\n";
      for (auto idx : index) {
        std::cerr << idx << ", ";
      }
      std::cerr << "\n";
      assert(1 == 0); // Cannot happen...
      return 0;
#else
      return std::distance(index.begin(), std::upper_bound(index.begin(), index.end(), node)) - 1;
#endif
    }

    template <typename T> static void clear(std::vector<T> &vec)
    {
      vec.clear();
      vec.shrink_to_fit();
      assert(vec.capacity() == 0);
    }

    inline static int power_2(int count)
    {
      // Return the power of two which is equal to or greater than 'count'
      // count = 15 -> returns 16
      // count = 16 -> returns 16
      // count = 17 -> returns 32

      // Use brute force...
      int pow2 = 1;
      while (pow2 < count) {
        pow2 *= 2;
      }
      return pow2;
    }

    static int log_power_2(uint64_t value);

    static char **get_name_array(size_t count, int size);
    static void   delete_name_array(char **names, int count);

    // Fill time_string and date_string with current time and date
    // formatted as "HH:MM:SS" for time and "yy/mm/dd" or "yyyy/mm/dd"
    // for date
    static void time_and_date(char *time_string, char *date_string, size_t length);

    static std::string decode_filename(const std::string &filename, int processor,
                                       int num_processors);
    static int         decode_entity_name(const std::string &entity_name);
    static std::string encode_entity_name(const std::string &entity_type, int64_t id);

    // Convert 'name' to lowercase and convert spaces to '_'
    static void fixup_name(char *name);
    static void fixup_name(std::string &name);

    // Check whether property 'prop_name' exists and if so, set 'prop_value'
    // based on the property value.  Either "TRUE", "YES", "ON", or 1 for true;
    // or "FALSE", "NO", "OFF", or not equal to 1 for false.
    // Returns true/false depending on whether property found and value set.
    // Does not set 'prop_val' if 'prop_name' does not exist.
    static bool check_set_bool_property(const Ioss::PropertyManager &properties,
                                        const std::string &prop_name, bool &prop_value);

    // Returns true if the property "omitted" exists on "block"
    static bool block_is_omitted(Ioss::GroupingEntity *block);

    // Process the base element type 'base' which has
    // 'nodes_per_element' nodes and a spatial dimension of 'spatial'
    // into a form that the IO system can (hopefully) recognize.
    // Lowercases the name; converts spaces to '_', adds
    // nodes_per_element at end of name (if not already there), and
    // does some other transformations to remove some exodusII ambiguity.
    static std::string fixup_type(const std::string &base, int nodes_per_element, int spatial);

    static std::string uppercase(std::string name);
    static std::string lowercase(std::string name);

    static int case_strcmp(const std::string &s1, const std::string &s2);

    // Return a string containing information about the current :
    // computing platform. This is used as information data in the
    // created results file to help in tracking when/where/... the file
    // was created.
    static std::string platform_information();

    // Return amount of memory being used on this processor
    static size_t get_memory_info();
    static size_t get_hwm_memory_info();

    static void abort();

    // Return a filename relative to the specified working directory (if any)
    // of the current execution. Working_directory must end with '/' or be empty.
    static std::string local_filename(const std::string &relative_filename, const std::string &type,
                                      const std::string &working_directory);

    static void get_fields(int64_t entity_count, char **names, size_t num_names,
                           Ioss::Field::RoleType fld_role, char suffix_separator, int *local_truth,
                           std::vector<Ioss::Field> &fields);

    static int field_warning(const Ioss::GroupingEntity *ge, const Ioss::Field &field,
                             const std::string &inout);

    static void calculate_sideblock_membership(IntVector &face_is_member, const SideBlock *ef_blk,
                                               size_t int_byte_size, const void *element,
                                               const void *sides, int64_t number_sides,
                                               const Region *region);

    // And yet another idiosyncracy of sidesets...
    // The side of an element (especially shells) can be
    // either a face or an edge in the same sideset.  The
    // ordinal of an edge is (local_edge_number+#faces) on the
    // database, but needs to be (local_edge_number) for
    // Sierra...
    //
    // If the sideblock has a "parent_element_topology" and a
    // "topology", then we can determine whether to offset the
    // side ordinals...
    static int64_t get_side_offset(const Ioss::SideBlock *sb);

    static unsigned int hash(const std::string &name);

    static double timer();

    // Return a vector of strings containing the lines of the input file.
    // Should only be called by a single processor or each processor will
    // be accessing the file at the same time...
    static void input_file(const std::string &file_name, std::vector<std::string> *lines,
                           size_t max_line_length = 0);

    template <class T> static std::string to_string(const T &t) { return std::to_string(t); }

    // Many databases have a maximum length for variable names which can
    // cause a problem with variable name length.
    //
    // This routine tries to shorten long variable names to an acceptable
    // length ('max_var_len' characters max).  If the name is already less than this
    // length, it is returned unchanged...
    //
    // Since there is a (good) chance that two shortened names will match,
    // a 2-letter 'hash' code is appended to the end of the variable name.
    //
    // So, we shorten the name to a maximum of 'max_var_len'-3 characters and append a
    // 2 character hash+separator.
    //
    // It also converts name to lowercase and converts spaces to '_'
    static std::string variable_name_kluge(const std::string &name, size_t component_count,
                                           size_t copies, size_t max_var_len);

    // The model for a history file is a single sphere element (1 node, 1 element)
    // This is needed for some applications that read this file that require a "mesh"
    // even though a history file is just a collection of global variables with no
    // real mesh. This routine will add the mesh portion to a history file.
    static void generate_history_mesh(Ioss::Region *region);

    // Copy the mesh in 'region' to 'output_region'.  Behavior can be controlled
    // via options in 'options'
    static void copy_database(Ioss::Region &region, Ioss::Region &output_region,
                              Ioss::MeshCopyOptions &options);
  };
} // namespace Ioss
#endif


text:
package org.cryptoworkshop.ximix.installer.ui.steps;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
public abstract class AbstractInstallerStep {
    protected String title = null;
    protected String content = null;
    protected List<UserInput> userInputs = new ArrayList<>();

    public abstract String acceptValue(HashMap<String, Object> value);

    public enum InputType {STRING, NUMBER, LIST_SINGLE, LIST_MULTI, STEP_THROUGH, SUMMARY, FILE}

    public AbstractInstallerStep() {

    }

    public abstract Object getDefault();

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<UserInput> getUserInputs() {
        return userInputs;
    }

    public void setUserInputs(List<UserInput> userInputs) {
        this.userInputs = userInputs;
    }

    public static class UserInput {
        String label = null;
        InputType type = null;
        String id = null;
        String toolTip = null;
        UserInputConstraints constraints = null;

        public UserInput() {

        }

        public UserInput(String label, InputType type, String id) {
            this.label = label;
            this.type = type;
            this.id = id;
        }

        public UserInput(String label, InputType type, String id, UserInputConstraints constraints) {
            this.label = label;
            this.type = type;
            this.id = id;
            this.constraints = constraints;
        }

        public String getLabel() {
            return label;
        }

        public UserInput setLabel(String label) {
            this.label = label;
            return this;
        }

        public InputType getType() {
            return type;
        }

        public UserInput setType(InputType type) {
            this.type = type;
            return this;
        }

        public String getId() {
            return id;
        }

        public UserInput setId(String id) {
            this.id = id;
            return this;
        }

        public String getToolTip() {
            return toolTip;
        }

        public UserInput setToolTip(String toolTip) {
            this.toolTip = toolTip;
            return this;
        }

        public UserInputConstraints getConstraints() {
            return constraints;
        }

        public UserInput setConstraints(UserInputConstraints constraints) {
            this.constraints = constraints;
            return this;
        }
    }

    public static interface UserInputConstraints<T> {
        String isValid(T value);
    }

    public static class IntegerInputConstrains implements UserInputConstraints<Integer> {
        private int notBefore = 1;
        private int notAfter = Integer.MAX_VALUE;
        private int incrementValue = 1;
        private boolean allowNull = false;

        public IntegerInputConstrains() {

        }

        public IntegerInputConstrains(int notBefore, int notAfter, int incrementValue) {
            this.notBefore = notBefore;
            this.notAfter = notAfter;
            this.incrementValue = incrementValue;
        }

        @Override
        public String isValid(Integer value) {
            if (allowNull && value == null) {
                return "Value cannot is null;";
            }

            if (value != null) {
                if (notBefore > value) {
                    return "Value must be larger than or equal to " + notAfter;
                }

                if (notAfter < value) {
                    return "Value must be less than or equal to " + notAfter;
                }

            }
            return null;
        }

        public int getNotBefore() {
            return notBefore;
        }

        public void setNotBefore(int notBefore) {
            this.notBefore = notBefore;
        }

        public int getNotAfter() {
            return notAfter;
        }

        public void setNotAfter(int notAfter) {
            this.notAfter = notAfter;
        }

        public int getIncrementValue() {
            return incrementValue;
        }

        public void setIncrementValue(int incrementValue) {
            this.incrementValue = incrementValue;
        }
    }

    public static class FileInputConstraints implements UserInputConstraints<File> {
        private boolean mustBeFile = false;
        private boolean onlyDirectories = true;
        private boolean mustExist = false;
        private File defaultDirectory = new File("./");

        public FileInputConstraints() {

        }

        public FileInputConstraints(boolean mustBeFile, boolean mustExist, File defaultDirectory) {
            this.mustBeFile = mustBeFile;
            this.mustExist = mustExist;
            this.defaultDirectory = defaultDirectory;
        }

        @Override
        public String isValid(File value) {

            return null;
        }

        public boolean isMustBeFile() {
            return mustBeFile;
        }

        public void setMustBeFile(boolean mustBeFile) {
            this.mustBeFile = mustBeFile;
        }

        public boolean isMustExist() {
            return mustExist;
        }

        public void setMustExist(boolean mustExist) {
            this.mustExist = mustExist;
        }

        public File getDefaultDirectory() {
            return defaultDirectory;
        }

        public void setDefaultDirectory(File defaultDirectory) {
            this.defaultDirectory = defaultDirectory;
        }

        public boolean isOnlyDirectories() {
            return onlyDirectories;
        }

        public void setOnlyDirectories(boolean onlyDirectories) {
            this.onlyDirectories = onlyDirectories;
        }
    }

    public static class StringInputConstraints implements UserInputConstraints<String> {
        private String[] passingExpressions = null;
        private String[] failingExpressions = null;

        public StringInputConstraints() {

        }

        @Override
        public String isValid(String value) {

            if (passingExpressions == null && failingExpressions == null) {
                return null;
            }

            if (passingExpressions != null) {
                for (String passing : passingExpressions) {
                    if (value.matches(passing)) {
                        return null;
                    }
                }
            }

            if (failingExpressions != null) {
                for (String failing : failingExpressions) {
                    if (value.matches(failing)) {
                        return "Incorrect format.";
                    }
                }
            }

            return "Invalid string.";
        }

        public String[] getPassingExpressions() {
            return passingExpressions;
        }

        public void setPassingExpressions(String[] passingExpressions) {
            this.passingExpressions = passingExpressions;
        }

        public String[] getFailingExpressions() {
            return failingExpressions;
        }

        public void setFailingExpressions(String[] failingExpressions) {
            this.failingExpressions = failingExpressions;
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;

namespace GlobalcachingApplication.Updater
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string updatePath = System.IO.Path.Combine(new string[] { System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "GlobalcachingApplication", "Update" });

            //step 1: close Globalcaching.Application
            labelInfo.Text = "Stopping application...";
            labelInfo.Refresh();
            Process[] procs = System.Diagnostics.Process.GetProcessesByName("Globalcaching.Application");
            DateTime startWait = DateTime.Now;
            TimeSpan maxWait = new TimeSpan(0, 0, 5);
            while (procs != null && procs.Length > 0 && (DateTime.Now - startWait) <= maxWait)
            {
                System.Threading.Thread.Sleep(1000);
                procs = System.Diagnostics.Process.GetProcessesByName("Globalcaching.Application");
            }
            if (procs != null && procs.Length > 0)
            {
                foreach (Process p in procs)
                {
                    p.Kill();
                }
            }
            System.Threading.Thread.Sleep(1000);
            procs = System.Diagnostics.Process.GetProcessesByName("Globalcaching.Application");
            if (procs != null && procs.Length > 0)
            {
                MessageBox.Show("Unable to close the application", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //step 2: copy all files with subfolders (with override) from AppData\GlobalcachingApplication\Update to exec\
            labelInfo.Text = "Copying files...";
            labelInfo.Refresh();
            string[] updateFiles = Directory.GetFiles(updatePath, "*.zip");
            if (updateFiles != null)
            {
                foreach (string fn in updateFiles)
                {
                    UnZipFiles(fn, exePath, true);
                }
            }

            //step 3: deleting update files AppData\GlobalcachingApplication\Update
            labelInfo.Text = "Deleting update files...";
            labelInfo.Refresh();

            //step 4: start Globalcaching.Application
            labelInfo.Text = "Starting application...";
            labelInfo.Refresh();
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = Path.Combine(exePath, "GlobalcachingApplication.exe");
            psi.WorkingDirectory = exePath;
            Process.Start(psi);

            //step 4: close Updater
            Close();
        }

        public static void UnZipFiles(string zipPathAndFile, string outputFolder, bool deleteZipFile)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile));
            ZipEntry theEntry;
            string tmpEntry = String.Empty;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = outputFolder;
                string fileName = Path.GetFileName(theEntry.Name);
                // create directory
                if (directoryName != "")
                {
                    Directory.CreateDirectory(directoryName);
                }
                if (fileName != String.Empty)
                {
                    if (theEntry.Name.IndexOf("GlobalcachingApplication.Updater", StringComparison.OrdinalIgnoreCase) < 0)
                    {
                        string fullPath = Path.Combine(directoryName , theEntry.Name);
                        fullPath = fullPath.Replace("\\ ", "\\");
                        string fullDirPath = Path.GetDirectoryName(fullPath);
                        if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                        FileStream streamWriter = File.Create(fullPath);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
            }
            s.Close();
            if (deleteZipFile)
                File.Delete(zipPathAndFile);
        }
    }
}


text:
/*
 *
 */
package common;

import java.util.ArrayList;

/**
 *
 * @author JasonRobinson
 */
public class FactorFinder {
    private Long theNumber;
    private ArrayList<Long> factors;
    private boolean isPrime;
    private boolean addSelf;

    public FactorFinder(){
        factors = new ArrayList<Long>();
        addSelf = true;
    }

    public FactorFinder(Long num){
        this.theNumber = num;
        factors = new ArrayList<Long>();
        findTheFactors(num);
    }

    public ArrayList<Long> findTheFactors(Long n){
        factors.clear();
        if(addSelf) factors.add(n);
        factors.add(1L);
        for(long test = n - 1; test >= Math.sqrt(n); test--)
            if(n % test == 0)
            {
                factors.add(test);
                factors.add(n / test);
            }
        return factors;
    }

    public Long getTheNumber() {
        return theNumber;
    }

    public void setTheNumber(Long theNumber) {
        this.theNumber = theNumber;
    }

    public boolean isIsPrime() {
        return isPrime;
    }

    public boolean allowAddSelf() {
        return addSelf;
    }

    public void setAddSelf(boolean addSelf) {
        this.addSelf = addSelf;
    }

}


text:
CC=clang # or gcc

FRAMEWORKS:= -framework Foundation -framework AppKit

SOURCE=src/main.m src/Notifier.m

CFLAGS=-Wall
LDFLAGS= $(FRAMEWORKS)
OUT=-o build/usb-mount-notifier

all:
	$(CC) $(CFLAGS) $(LDFLAGS) $(OUT) $(SOURCE)


text:
from rick.motion_control import euclidian_path_planning_control
from detection.opencv import get_lego_piece
from detection.opencv import get_purple_lego, get_lego_boxes, detect_purple
import time
from .motion_control import euclidian_path_planning_control, kalman_filter
from .utils import *
import cv2
import numpy as np

def wait_for_brick(robot, frame, vel=400):
    lego_coords, center = get_purple_lego(frame)
    if lego_coords:
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}
    else:
        # robot.rotate_right(vel)
        return "WAIT_FOR_BRICK", frame, {}

def wait_for_brick_nn(robot,frame):
    img = frame
    kernel = np.ones((5,5),np.float32)/25
    img = cv2.filter2D(img,-1,kernel)
    res = robot.object_detector.detect_with_threshold(img,threshold=0.95, return_closest=True)
    if res:
        img_res = np.asarray([640,480])
        box, score = res
        cv2.rectangle(frame, (int(box[1]*img_res[0]), int(box[0]*img_res[1])),
                (int(box[3]*img_res[0]), int(box[2]*img_res[1])), (0, 255, 0), thickness=3)
        cv2.putText(frame, str(score) + "%", (int(box[1]*img_res[0]),
         int(box[0]*img_res[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color=(255,0,0))

        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}
    else:
        # robot.rotate_right(vel)
        return "WAIT_FOR_BRICK", frame, {}

def move_to_brick_simple(robot, frame, img_res=(640, 480), atol=5,
                         vel_forward = 100, vel_rot = 50, atol_move_blind=90, fail_counter=0):
    """
    Moves the robot towards the brick.

    :param robot: The robot instance
    :param img_res: The image resolution
    :param atol: The absolute error tolerance
    :return: Direction string
    """
    _, frame = robot.cap.read()

    coords, center = get_lego_piece(frame)

    if not coords and fail_counter==5:
        return "SEARCH", frame, {}
    elif not coords:
        return "MOVE_TO_BRICK", frame, {"fail_counter" : fail_counter+1}

    img_res = np.asarray(img_res)
    img_center = img_res / 2
    error = img_center - coords
    print("Coords: ", coords)
    # Move forward till light sensor detects brick if brick is near the bottom of image
    # and centered
    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=atol_move_blind):
        robot.move_straight(vel_forward, 500)
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}

    if np.isclose(coords[0], img_center[0], atol=atol):
        print("Move straight")
        robot.move_straight(vel_forward)
        return "MOVE_TO_BRICK", frame, {}
    elif error[0] < 0:
        print("Move left")
        robot.rotate_left(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {}
    else:
        # Positive velocity for turning left
        print("Move left")
        robot.rotate_right(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {}

import cv2
import time

def search_v3(robot, frame, vel_rot):
    res = robot.object_detector.detect_with_threshold(frame,threshold=0.9, return_closest=True)

    if len(res) == 0:
        return "SEARCH", frame, {}

    else:
        boxes = map(lambda x: x[0], res)
        #find the purple box

        box = None
        if box:
            robot.reset()
            robot.tracker.init(frame, box)
            tracker = tracker
            return "MOVE_TO_BRICK", frame, {"tracker" : tracker}
        else:
            robot.rotate_right(vel=vel_rot)
            return "SEARCH", frame, {}

def move_to_brick_v3_pid(robot, frame, img_res=np.asarray((640, 480)), atol=5,
                         vel_forward = 299, vel_rot = 50, atol_move_blind=90,
                         fail_counter=0, center_position_error = 10, tracker=None, m=None, trajectory=None):

    ok, bbox = tracker.update(frame)

    vel = np.asarray(vel_forward)
    K1, K2 = 1., 1./280

    if not ok:
        BB_legos=get_lego_boxes(frame)
        # res = robot.object_detector.detect_with_threshold(frame,threshold=0.9, return_closest=False)
        # BB_legos = map(lambda x: x[0], res)
        BB_target = detect_purple(frame,BB_legos)
        if len(BB_target) == 0:
            return "SEARCH_TARGET", frame, {}
        tracker.init(frame, BB_target[0])
        bbox = BB_target[0]

    coords = bbox_center(*bbox)
    img_center = img_res / 2 - center_position_error
    #img_center[0] = 285
    error = img_center - coords
    atol = 10 + coords[1]/480 * 40

    vel = vel/np.abs(coords[1]/400) + np.asarray([vel_rot, -vel_rot]) * error

    print("Errror:", error, "Coords ", coords, " ok ", ok)
    frame = plot_bbox(frame,bbox, 0, (255,0,0))
    img_center = img_res/2.

    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=atol_move_blind):
        robot.reset()
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}

    else:
        robot.left_track.run_forever(speed_sp = vel[0])
        robot.right_track.run_forever(speed_sp = vel[1])
        return "GO_TO_TARGET", frame, {"tracker" : tracker}

def move_to_brick_v3(robot, frame, img_res=np.asarray((640, 480)), atol=5,
                         vel_forward = 299, vel_rot = 50, atol_move_blind=90,
                         fail_counter=0, center_position_error = 10, tracker=None, m=None, trajectory=None):

    ok, bbox = tracker.update(frame)

    if not ok:
        BB_legos=get_lego_boxes(frame)
        # res = robot.object_detector.detect_with_threshold(frame,threshold=0.9, return_closest=False)
        # BB_legos = map(lambda x: x[0], res)
        BB_target = detect_purple(frame,BB_legos)
        if len(BB_target) == 0:
            return "SEARCH_TARGET", frame, {}
        tracker.init(frame, BB_target[0])
        bbox = BB_target[0]

    coords = bbox_center(*bbox)
    img_center = img_res / 2 - center_position_error
    #img_center[0] = 285
    error = img_center - coords
    atol = 10 + coords[1]/480 * 40

    print("Errror:", error, "Coords ", coords, " ok ", ok)
    frame = plot_bbox(frame,bbox, 0, (255,0,0))
    img_center = img_res/2.

    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=atol_move_blind):
        robot.move_straight(vel_forward, 500)
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}

    if np.isclose(coords[0], img_center[0], atol=atol):
        print("Move straight")
        robot.move_straight(vel_forward)
        return "GO_TO_TARGET", frame, {"tracker" : tracker}
    elif error[0] < 0:
        robot.rotate_left(vel=vel_rot)
        return "GO_TO_TARGET", frame, {"tracker" : tracker}
    else:
        # Positive velocity for turning left
        robot.rotate_right(vel=vel_rot)
        return "GO_TO_TARGET", frame, {"tracker" : tracker}

def move_to_brick_nn_v2(robot, frame, img_res=(640, 480), atol=5,
                         vel_forward = 299, vel_rot = 50, atol_move_blind=90,
                         fail_counter=0, center_position_error = 10, tracking=False):

    img_res = np.array(img_res)
    ts = time.time()
    res = robot.object_detector.detect_with_threshold(frame,threshold=0.9, return_closest=True)
    tdet = time.time() - ts
    detected = len(res) > 0
    score = 0
    if not tracking and not detected:
        return "SEARCH", frame, {}
    elif detected:
        color = (0,0,255)
        box, score = res[0]
        dbox = np.asarray((int(box[1]*img_res[0]), int(box[0]*img_res[1]), int(box[3]*img_res[0]), int(box[2]*img_res[1])))
        if tracking:
            ok, tbox = robot.tracker.update(frame)
            if bboxes_are_overlapping(tbox,dbox) or tbox[0]==0:
                robot.tracker.init(frame, dbox)
                bbox = dbox
            else:
                color = (255,0,0)
                bbox = tbox
        else:
            robot.tracker.init(frame, dbox)
            bbox = dbox
    elif tracking:
        color = (255,0,0)
        ok, bbox = robot.tracker.update(frame)
        if not ok:
            return "SEARCH", frame, {}

    tif = time.time() - tdet

    print("Time deteection: ", tdet, "Time if statement: ", tif)

    coords = bbox_center(*bbox)
    img_center = img_res / 2 - center_position_error
    error = img_center - coords

    plot_bbox(frame,bbox, score, color)

    img_center = img_res/2.

    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=atol_move_blind):
        robot.move_straight(vel_forward, 500)
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}

    if np.isclose(coords[0], img_center[0], atol=atol):
        print("Move straight")
        robot.move_straight(vel_forward)
        return "MOVE_TO_BRICK", frame, {"tracking" : True}
    elif error[0] < 0:
        robot.rotate_right(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {"tracking" : True}
    else:
        # Positive velocity for turning left
        robot.rotate_left(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {"tracking" : True}

def move_to_brick_nn_v1(robot, frame, img_res=(640, 480), atol=5,
                         vel_forward = 299, vel_rot = 50, atol_move_blind=90,
                         fail_counter=0, center_position_error = 10):
    """
    Moves the robot towards the brick.

    :param robot: The robot instance
    :param img_res: The image resolution
    :param atol: The absolute error tolerance
    :return: Direction string
    """
    _, frame = robot.cap.read()

    img = frame
    kernel = np.ones((5,5),np.float32)/25
    img = cv2.filter2D(img,-1,kernel)
    res = robot.object_detector.detect_with_threshold(img,threshold=0.7, return_closest=True)
    print("Res: ", res)
    if len(res)==0 and fail_counter==5:
        return "SEARCH", frame, {}
    elif len(res)==0:
        print("Fail: ", fail_counter, res)
        return "MOVE_TO_BRICK", frame, {"fail_counter" : fail_counter+1}
    print("Shape: ", res[0])
    box, score = res[0]
    img_res = np.asarray(img_res)
    coords = bbox_center(box[1], box[0], box[3], box[2]) * img_res
    coords = coords.astype(np.int16)
    atol = 10 + coords[1]/480 * 50
    print("Coords: ", coords)
    cv2.rectangle(frame, (int(box[1]*img_res[0]), int(box[0]*img_res[1])),
            (int(box[3]*img_res[0]), int(box[2]*img_res[1])), (0, 255, 0), thickness=3)
    cv2.putText(frame, str(score) + "%", (int(box[1]*img_res[0]),
     int(box[0]*img_res[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color=(255,0,0))
    cv2.circle(frame,tuple(coords),2,(255,255,255),thickness=2)

    img_center = img_res / 2 - center_position_error
    error = img_center - coords

    # Move forward till light sensor detects brick if brick is near the bottom of image
    # and centered
    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=atol_move_blind):
        robot.move_straight(vel_forward, 500)
        return "MOVE_TO_BRICK_BLIND_AND_GRIP", frame, {}

    if np.isclose(coords[0], img_center[0], atol=atol):
        print("Move straight")
        robot.move_straight(vel_forward)
        return "MOVE_TO_BRICK", frame, {}
    elif error[0] < 0:
        robot.rotate_right(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {}
    else:
        # Positive velocity for turning left
        robot.rotate_left(vel=vel_rot)
        return "MOVE_TO_BRICK", frame, {}

def euclidian_move_to_brick(robot, frame,
                            path=[], iteration=0, ltrack_pos=0, rtrack_pos=0, TIME=0):

    img_res = np.asarray((640,480))

    lego_coords, center = get_purple_lego(frame)
    if lego_coords and np.isclose(lego_coords[1], img_res[1], atol=200):
        return "MOVE_TO_BRICK", frame, {}

    brick_position = robot.map[0]
    t0 = time.time()
    print('t0 ', t0, 'TIME', TIME)
    time_diff = t0 - TIME
    print('time',time_diff)
    new_ltrack_pos = robot.left_track.position
    new_rtrack_pos = robot.right_track.position
    odom_l, odom_r = new_ltrack_pos - ltrack_pos, new_rtrack_pos - rtrack_pos
    estim_rob_pos, vel_wheels, new_path = euclidian_path_planning_control(robot.position,
                                                                          brick_position, robot.sampling_rate,
                                                                          odom_r= odom_r,odom_l=odom_l,
                                                                          iteration=iteration, path=path)

    robot.position = estim_rob_pos
    robot.move(vel_left=vel_wheels[1], vel_right=vel_wheels[0])
    iteration += 1

    # print("Path: ", pat, iteration)
    # print("Robot positij "ffefrobot.position)
    # print("Velocities rl: ", vel_wheels)
    # print("##" *20)

    return "MOVE_BY_MAP", frame, {"iteration" : iteration, "path" : new_path, "ltrack_pos": new_ltrack_pos, "rtrack_pos": new_rtrack_pos, "TIME": t0}

def rotation_search_brick(robot, frame, vel=60):

    res = robot.object_detector.detect_with_threshold(img,threshold=0.7, return_closest=True)
    if len(res) > 0:
        box, score = res[0]
        box = np.asarray((int(box[1]*img_res[0]), int(box[0]*img_res[1]), int(box[3]*img_res[0]), int(box[2]*img_res[1])))
        lego_coords = bbox_center(box)
    else:
        lego_coords = None

    if lego_coords:
        return "MOVE_TO_BRICK", frame, {}
  #  elif len(robot.map) > 0 :
        #return "MOVE_BY_MAP", frame, {"iteration": 0, "path": []}
    else:
        robot.rotate_right(vel)
        return "SEARCH", frame, {}

def rotation_search_brick_nn(robot, frame, vel=60):

    res = robot.object_detector.detect_with_threshold(frame,threshold=0.9, return_closest=True)
    detected = len(res) > 0
    if detected:
        lego_coords, score = res[0]
    else:
        lego_coords = None
    if lego_coords is not None:
        return "MOVE_TO_BRICK", frame, {}
  #  elif len(robot.map) > 0 :
        #return "MOVE_BY_MAP", frame, {"iteration": 0, "path": []}
    else:
        robot.rotate_right(vel)
        return "SEARCH", frame, {}

def move_to_box_simple(robot, frame, img_res=(640, 480), atol=10,
                         vel_forward = 400, vel_rot = 60, vel_forward_slow=60):
    """
        Moves the robot towards the brick.

        :param robot: The robot instance
        :param img_res: The image resolution
        :param atol: The absolute error tolerance
        :return: Direction string
        """
    _, frame = robot.cap.read()

    coords = get_white_box(frame)

    # Did not detect
    if not coords:
        return "SEARCH_BOX", frame, {}

    img_res = np.asarray(img_res)
    coords = np.asarray(coords)

    img_center = img_res / 2

    error = img_center - coords

    # Move forward till light sensor detects brick if brick is near the bottom of image
    # and centered
    if np.isclose(coords[0], img_center[0], atol=atol) and np.isclose(coords[1], img_res[1], atol=10):
        #leave the piece and go little bit backwards
        robot.elevator.down()
        time.sleep(2.5)
        robot.move_straight(vel_forward)
        time.sleep(0.3)
        robot.grip.open()
        robot.elevator_up()
        time.sleep(3)
        robot.move_straight(vel=-200)
        time.sleep(2)

        return "SEARCH", {}

    if np.isclose(coords[0], img_center[0], atol=atol):
        robot.move_straight(vel_forward)
        return "MOVE_TO_BOX", frame, {}
    elif error[0] < 0:
        robot.rotate_right(vel=vel_rot)
        return "MOVE_TO_BOX", frame, {}
    else:
        # Positive velocity for turning left
        robot.rotate_left(vel=vel_rot)
        return "MOVE_TO_BOX", frame, {}

def rotation_search_box(robot, frame, vel=400):

    box_coords = get_white_box(frame)
    if box_coords:
        return "MOVE_TO_BOX", frame, {}
    else:
        robot.rotate(vel)
        return "SEARCH_BOX", frame, {}

def control_PID(robot, coords, img_res=(640, 480),K1=0 ,K2 = 0):

    # Compute the relative position from the image

    relObjPos = pixel_normalized_pos(coords,img_res)

    # Move to circular params
    relObjCir[0] = np.sqrt(np.pow(relObjPos(1),2) + np.pow(relObjPos(2),2));
    relObjCir[1] = np.atan(relObjPos(1)/relObjPos(2))

    # From circular params to wheels vel

    rotationMat = np.matrix([K1/2,K1/2],[K2,K2])

    velWheels = np.matmul(rotationMat,relObjCir)

def move_to_brick_blind_no_sensor(robot, frame, vel=60, time=500):

    robot.elevator.down()
    time.sleep(2.5)
    robot.move_straight(vel, time)
    time.sleep(0.5)
    robot.pick_up()
    time.sleep(2.5)

    return "SEARCH_BOX", frame, {}

def move_to_brick_blind_and_grip(robot, frame, vel=400, t=1700):
    # Make sure the grip is open
    robot.grip.open()
    print("Velocity: ", vel)
    # Make sure the elevator is down
    print(robot.elevator.is_raised)
    print(robot.elevator.position)
    robot.elevator.down()
    robot.elevator.wait_until_not_moving()
    robot.move_straight(vel=vel, time=t)
    robot.wait_until_not_moving()
    robot.pick_up()
    return "FINAL_STATE", frame, {}


text:
FROM tboquet/scikenacuthe7hc3

MAINTAINER Thomas Boquet <thomas.boquet@hec.ca>

RUN conda install -y scikit-image && pip install pydicom

CMD ["/bin/bash"]


text:
Blog Project
=======================

Introduction
------------

Features added:

- Core module with
    - TableGateway implementation
    - PHPUnit tests
    - Entity class
    - Service class
    - AdapterServiceFactory using module-based db configuration

- Skel module

Installation
------------

Using Composer (recommended)
----------------------------
The recommended way to get a working copy of this project is to clone the repository
and use composer to install dependencies:

    php composer.phar install

Virtual Host
------------

	<VirtualHost *:80>
    	ServerName blogproject.dev
	    DocumentRoot /vagrant/blogproject/public
    	SetEnv APPLICATION_ENV "development"
	    SetEnv PROJECT_ROOT "/vagrant/blogproject"
   		<Directory /vagrant/blogproject/public>
        	DirectoryIndex index.php
        	AllowOverride All
        	Order allow,deny
        	Allow from all
    	</Directory>
	</VirtualHost>

# blog-zf2-phpunit


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVLTree
{
    /// <summary>
    /// Node represents a single point within a tree. Each point contains information about other
    /// nodes known as the children nodes (Left, Right) allowing node to be connected and
    /// traversed one to another. There are only two child nodes for each node as this is being
    /// used exclusively by binary trees. The node also contains both a key and value pair, the
    /// idea behind this is to improve search between nodes as it shall allow for fine tune
    /// searching against a key rather than an entire value.
    /// </summary>
    /// <typeparam name="TKey">Type of Key must implemented IComparable.</typeparam>
    /// <typeparam name="TValue">Type of Value must implemented IComparable.</typeparam>
    public class Node<TKey, TValue>
        where TKey : IComparable<TKey>
        where TValue : IComparable<TValue>
    {
        /// <summary>
        /// Node to the left of this node.
        /// </summary>
        public Node<TKey, TValue> Left;

        /// <summary>
        /// Node to the right of this node.
        /// </summary>
        public Node<TKey, TValue> Right;

        /// <summary>
        /// Construct a new node specifying the Key and Value to hold.
        /// </summary>
        /// <param name="Key">Unique key used to identify the node.</param>
        /// <param name="Value">Actual data being stored in the node.</param>
        public Node(TKey Key, TValue Value)
        {
            this.Key = Key;
            this.Value = Value;
            Left = null;
            Right = null;
        }

        /// <summary>
        /// Key used to uniquely identify the node.
        /// </summary>
        public TKey Key { get; set; }

        /// <summary>
        /// Value being stored within the node.
        /// </summary>
        public TValue Value { get; set; }

        /// <summary>
        /// Balance of the node. Determined by height of left minus height of right.
        /// </summary>
        public int BalanceFactor { get; set; }
    }
}


text:
BAREBONES_VERSION = "1.00"

-- Set this to true if you want to see a complete debug output of all events/processes done by barebones
-- You can also change the cvar 'barebones_spew' at any time to 1 or 0 for output/no output
BAREBONES_DEBUG_SPEW = false

if GameMode == nil then
    DebugPrint( '[BAREBONES] creating barebones game mode' )
    _G.GameMode = class({})
end

-- This library allow for easily delayed/timed actions
require('libraries/timers')
-- This library can be used for advancted physics/motion/collision of units.  See PhysicsReadme.txt for more information.
require('libraries/physics')
-- This library can be used for advanced 3D projectile systems.
require('libraries/projectiles')
-- This library can be used for sending panorama notifications to the UIs of players/teams/everyone
require('libraries/notifications')
-- This library can be used for starting customized animations on units from lua
require('libraries/animations')
-- This library can be used for performing "Frankenstein" attachments on units
require('libraries/attachments')
-- This library can be used to synchronize client-server data via player/client-specific nettables
require('libraries/playertables')
-- This library can be used to create container inventories or container shops
require('libraries/containers')
-- This library provides a searchable, automatically updating lua API in the tools-mode via "modmaker_api" console command
require('libraries/modmaker')
-- This library provides an automatic graph construction of path_corner entities within the map
require('libraries/pathgraph')
-- This library (by Noya) provides player selection inspection and management from server lua
require('libraries/selection')

-- These internal libraries set up barebones's events and processes.  Feel free to inspect them/change them if you need to.
require('internal/gamemode')
require('internal/events')

-- settings.lua is where you can specify many different properties for your game mode and is one of the core barebones files.
require('settings')
-- events.lua is where you can specify the actions to be taken when any event occurs and is one of the core barebones files.
require('events')

-- This is a detailed example of many of the containers.lua possibilities, but only activates if you use the provided "playground" map
if GetMapName() == "playground" then
  require("examples/playground")
end

--require("examples/worldpanelsExample")

--[[
  This function should be used to set up Async precache calls at the beginning of the gameplay.

  In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync.  These calls will be made
  after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
  be used to precache dynamically-added datadriven abilities instead of items.  PrecacheUnitByNameAsync will
  precache the precache{} block statement of the unit and all precache{} block statements for every Ability#
  defined on the unit.

  This function should only be called once.  If you want to/need to precache more items/abilities/units at a later
  time, you can call the functions individually (for example if you want to precache units in a new wave of
  holdout).

  This function should generally only be used if the Precache() function in addon_game_mode.lua is not working.
]]
function GameMode:PostLoadPrecache()
  DebugPrint("[BAREBONES] Performing Post-Load precache")
  --PrecacheItemByNameAsync("item_example_item", function(...) end)
  --PrecacheItemByNameAsync("example_ability", function(...) end)

  --PrecacheUnitByNameAsync("npc_dota_hero_viper", function(...) end)
  --PrecacheUnitByNameAsync("npc_dota_hero_enigma", function(...) end)
end

--[[
  This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
  It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
  DebugPrint("[BAREBONES] First Player has loaded")
end

--[[
  This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
  It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
  DebugPrint("[BAREBONES] All Players have loaded into the game")
end

--[[
  This function is called once and only once for every player when they spawn into the game for the first time.  It is also called
  if the player's hero is replaced with a new hero for any reason.  This function is useful for initializing heroes, such as adding
  levels, changing the starting gold, removing/adding abilities, adding physics, etc.

  The hero parameter is the hero entity that just spawned in
]]
function GameMode:OnHeroInGame(hero)
  DebugPrint("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName())

  -- This line for example will set the starting gold of every hero to 500 unreliable gold
  --hero:SetGold(500, false)

  -- These lines will create an item and add it to the player, effectively ensuring they start with the item
  local item = CreateItem("item_example_item", hero, hero)
  hero:AddItem(item)

  --[[ --These lines if uncommented will replace the W ability of any hero that loads into the game
    --with the "example_ability" ability

  local abil = hero:GetAbilityByIndex(1)
  hero:RemoveAbility(abil:GetAbilityName())
  hero:AddAbility("example_ability")]]
end

--[[
  This function is called once and only once when the game completely begins (about 0:00 on the clock).  At this point,
  gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc.  This function
  is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
  DebugPrint("[BAREBONES] The game has officially begun")

  Timers:CreateTimer(30, -- Start this timer 30 game-time seconds later
    function()
      DebugPrint("This function is called 30 seconds after the game begins, and every 30 seconds thereafter")
      return 30.0 -- Rerun this timer every 30 game-time seconds
    end)
end

-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
  GameMode = self
  DebugPrint('[BAREBONES] Starting to load Barebones gamemode...')

  -- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI
  Convars:RegisterCommand( "command_example", Dynamic_Wrap(GameMode, 'ExampleConsoleCommand'), "A console command example", FCVAR_CHEAT )

  DebugPrint('[BAREBONES] Done loading Barebones gamemode!\n\n')
end

-- This is an example console command
function GameMode:ExampleConsoleCommand()
  print( '******* Example Console Command ***************' )
  local cmdPlayer = Convars:GetCommandClient()
  if cmdPlayer then
    local playerID = cmdPlayer:GetPlayerID()
    if playerID ~= nil and playerID ~= -1 then
      -- Do something here for the player who called this command
      PlayerResource:ReplaceHeroWith(playerID, "npc_dota_hero_viper", 1000, 1000)
    end
  end

  print( '*********************************************' )
end


text:
'use strict';

let _ = require('lodash');
let j = require('junify');
let esprima = require('esprima');

let extensions = require('./extensions');

//======
//Public
//======

// common patterns

function identifier(binding) {
  return { type: 'Identifier', name: binding };
}

function type(t) {
  return { type: t, _: j._ };
}

function arrayLength(n) {
  return _.times(n, () => j._);
}

function declarationId(type, binding, others) {
  return _.defaults({ type: type, id: identifier(binding), _: j._ }, others);
}

// predicates

function hasExpression(ast, binding, f) {
  return expressionsOf(ast, binding).some((node) => explore(node, f));
}

function hasDeclaration(ast, f) {
  return declarationsOf(ast).some(f);
}

//=======
//Private
//=======

// low level iteration

function expressionsOf(ast, binding) {
  return declarationsOf(ast).concatMap((node) =>
    j.match(node, [
      j.case({ type: 'FunctionDeclaration', id: identifier(binding), _: j._ }, () => [node.body]),
      j.case({ type: 'VariableDeclarator' , id: identifier(binding), _: j._ }, () => [node.init]),
      j.case(j._, () => [])
    ]));
}

function declarationsOf(ast) {
  return ast.body.concatMap((node) =>
    j.match(node, [
      j.case(type('FunctionDeclaration'), () => [node]),
      j.case(type('VariableDeclaration'), () => node.declarations),
      j.case(j._, () => [])
    ]));
}

// Expressions exploration

function explore(arg, f) {
  return f(arg) || subExpressionsOf(arg).some((subExpression) => explore(subExpression, f));
}

function subExpressionsOf(exp) {
  return j.match(exp, [
    j.case(type('CallExpression')     , () => [exp.callee]),
    j.case(type('BinaryExpression')   , () => [exp.left, exp.right]),
    j.case(type('ReturnStatement')    , () => [exp.argument]),
    j.case(type('ExpressionStatement'), () => [exp.expression]),
    j.case(type('BlockStatement')     , () => exp.body),
    j.case(type('VariableDeclaration'), () => exp.declarations),
    j.case(type('VariableDeclarator') , () => [exp.init]),
    j.case(j._                        , () => [])
  ]);
}

module.exports = {
  identifier: identifier,
  arrayLength: arrayLength,
  declarationId: declarationId,
  hasExpression: hasExpression,
  hasDeclaration: hasDeclaration
};


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "MOZUAppVersion.h"

@protocol MOZUApplicationSummary
@end

/**
	Mozu.AppDev.Contracts.ApplicationSummary ApiType DOCUMENT_HERE
*/
@interface MOZUApplicationSummary : JSONModel<MOZUApplicationSummary>

/**
Unique identifier of an app available in your Mozu tenant or within Mozu Dev Center. This ID is unique across all apps installed, initialized, and enabled in the Mozu Admin and those in development through the Dev Center Console.
*/
@property(nonatomic) NSString * appId;

/**
The AppKey is a runtime type.
*/
@property(nonatomic) NSString * appKey;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationId ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSInteger applicationId;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationNamespace ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSString * applicationNamespace;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationStatusId ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSInteger applicationStatusId;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationStatusName ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSString * applicationStatusName;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationTypeId ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSInteger applicationTypeId;

/**
Mozu.AppDev.Contracts.ApplicationSummary appSchemeVersion ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) unsigned char appSchemeVersion;

/**
Mozu.AppDev.Contracts.ApplicationSummary hasVersions ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) BOOL hasVersions;

/**
The display name of the source product property. For a product field it will be the display name of the field. For a product attribute it will be the Attribute Name.
*/
@property(nonatomic) NSString * name;

/**
The AppKey is a runtime type. This only applies for themes that inherit from another theme.
*/
@property(nonatomic) NSString * parentAppKey;

/**
Mozu.AppDev.Contracts.ApplicationSummary parentName ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSString * parentName;

/**
Mozu.AppDev.Contracts.ApplicationSummary releasePackageId ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSInteger releasePackageId;

/**
Mozu.AppDev.Contracts.ApplicationSummary releasePackageName ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) NSString * releasePackageName;

/**
Mozu.AppDev.Contracts.ApplicationSummary updateAvailable ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) BOOL updateAvailable;

/**
The AppKey is a runtime type. This only applies for themes that inherit from another theme. It shows the most current update available.
*/
@property(nonatomic) NSString * updateParentAppKey;

/**
Mozu.AppDev.Contracts.ApplicationSummary applicationVersion ApiTypeMember DOCUMENT_HERE
*/
@property(nonatomic) MOZUAppVersion *applicationVersion;

@end


text:
/*

package org.apache.taverna.workbench.file;

import java.util.Collections;
import java.util.List;

import org.apache.taverna.workbench.file.exceptions.OpenException;
import org.apache.taverna.workbench.file.exceptions.SaveException;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;

public abstract class AbstractDataflowPersistenceHandler implements
		DataflowPersistenceHandler {
	@Override
	public List<FileType> getOpenFileTypes() {
		return Collections.emptyList();
	}

	@Override
	public List<FileType> getSaveFileTypes() {
		return Collections.emptyList();
	}

	@Override
	public List<Class<?>> getOpenSourceTypes() {
		return Collections.emptyList();
	}

	@Override
	public List<Class<?>> getSaveDestinationTypes() {
		return Collections.emptyList();
	}

	@Override
	public DataflowInfo openDataflow(FileType fileType, Object source)
			throws OpenException {
		throw new UnsupportedOperationException();
	}

	@Override
	public DataflowInfo saveDataflow(WorkflowBundle workflowBundle, FileType fileType,
			Object destination) throws SaveException {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean wouldOverwriteDataflow(WorkflowBundle workflowBundle, FileType fileType,
			Object destination, DataflowInfo lastDataflowInfo) {
		throw new UnsupportedOperationException();
	}
}


text:
package com.j2eecn.fb.model;

import com.liferay.portal.model.PersistedModel;

/**
 * The extended model interface for the FeedBack service. Represents a row in the "fb_FeedBack" database table, with each column mapped to a property of this class.
 *
 * @author Administrator
 * @see FeedBackModel
 * @see com.j2eecn.fb.model.impl.FeedBackImpl
 * @see com.j2eecn.fb.model.impl.FeedBackModelImpl
 * @generated
 */
public interface FeedBack extends FeedBackModel, PersistedModel {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify this interface directly. Add methods to {@link com.j2eecn.fb.model.impl.FeedBackImpl} and rerun ServiceBuilder to automatically copy the method declarations to this interface.
	 */
}


text:
package org.beetl.core.statement;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

import org.beetl.core.Context;
import org.beetl.core.InferContext;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.exception.BeetlParserException;
import org.beetl.core.om.ObjectMethodMatchConf;
import org.beetl.core.om.ObjectUtil;
import org.beetl.core.statement.nat.ClassNode;
import org.beetl.core.statement.nat.InstanceNode;
import org.beetl.core.statement.nat.NativeArrayNode;
import org.beetl.core.statement.nat.NativeAtrributeNode;
import org.beetl.core.statement.nat.NativeMethodNode;
import org.beetl.core.statement.nat.NativeNode;

/**
 * @xxx.xx()[0].xxx
 * @author joelli
 *
 */
public class NativeCallExpression extends Expression
{

	InstanceNode insNode;
	ClassNode clsNode;
	NativeNode[] chain;

	public NativeCallExpression(InstanceNode insNode, NativeNode[] chain, GrammarToken token)
	{
		super(token);
		this.insNode = insNode;
		this.chain = chain;
	}

	public NativeCallExpression(ClassNode clsNode, NativeNode[] chain, GrammarToken token)
	{
		super(token);
		this.clsNode = clsNode;
		this.chain = chain;
	}

	public Object evaluate(Context ctx)
	{
		Class targetCls = null;
		Object targetObj = null;
		NativeNode lastNode = null;
		if (insNode != null)
		{
			targetObj = insNode.ref.evaluate(ctx);
			if (targetObj != null)
			{
				targetCls = targetObj.getClass();
			}

			lastNode = insNode;
		}
		else
		{
			targetCls = ctx.gt.loadClassBySimpleName(this.clsNode.cls);

			if (targetCls == null)
			{
				BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "该类不存在");
				be.pushToken(GrammarToken.createToken(clsNode.cls, token.line));
				throw be;
			}
			lastNode = clsNode;

		}

		for (NativeNode node : chain)
		{

			if (node instanceof NativeAtrributeNode)
			{
				String attr = ((NativeAtrributeNode) node).attribute;
				try
				{
					checkNull(targetCls, lastNode);
					Field f = targetCls.getField(attr);
					if (!Modifier.isStatic(f.getModifiers()))
					{
						checkNull(targetObj, lastNode);
					}
					targetObj = f.get(targetObj);
					targetCls = f.getType();

				}
				catch (SecurityException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用属性", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}
				catch (NoSuchFieldException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无此属性", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}
				catch (IllegalArgumentException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "访问属性出错", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}
				catch (IllegalAccessException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "访问属性出错", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}

			}
			else if (node instanceof NativeArrayNode)
			{
				checkNull(targetCls, lastNode);
				if (!targetCls.isArray())
				{
					BeetlException be = new BeetlException(BeetlException.ARRAY_TYPE_ERROR);
					//最好是把上一个字符显示出来
					be.pushToken(GrammarToken.createToken("[]", token.line));
					throw be;
				}
				Expression exp = ((NativeArrayNode) node).exp;
				Object value = exp.evaluate(ctx);
				if (value instanceof Number)
				{
					int index = ((Number) value).intValue();
					targetObj = ((Object[]) targetObj)[index];
					if (targetObj != null)
					{
						targetCls = targetObj.getClass();
					}
					else
					{
						//todo or component of array
						targetCls = null;
					}
				}
				else
				{
					BeetlException be = new BeetlException(BeetlException.ARRAY_INDEX_ERROR, "数组指针必须是Number类型");
					be.pushToken(GrammarToken.createToken("[]", token.line));
					throw be;
				}
			}
			else if (node instanceof NativeMethodNode)
			{
				NativeMethodNode methodNode = (NativeMethodNode) node;
				String method = methodNode.method;
				Expression[] expList = methodNode.paras;
				this.checkPermit(ctx, targetCls, targetObj, method);

				Object[] args = expList.length == 0 ? ObjectUtil.EMPTY_OBJECT_ARRAY : new Object[expList.length];
				Class[] parameterType = new Class[args.length];
				for (int i = 0; i < expList.length; i++)
				{
					args[i] = expList[i].evaluate(ctx);
					parameterType[i] = args[i] == null ? null : args[i].getClass();

				}
				this.checkNull(targetCls, lastNode);
				ObjectMethodMatchConf mf = ObjectUtil.findMethod(targetCls, method, parameterType);
				if (mf == null)
				{
					BeetlException ex = new BeetlException(BeetlParserException.NATIVE_CALL_INVALID, "根据参数未找到匹配的方法");
					ex.pushToken(GrammarToken.createToken(lastNode.getName(), token.line));
					throw ex;
				}

				if (targetObj == null && !Modifier.isStatic(mf.method.getModifiers()))
				{
					BeetlException ex = new BeetlException(BeetlException.NULL);
					ex.pushToken(GrammarToken.createToken(lastNode.getName(), token.line));
					throw ex;
				}

				try
				{

					targetObj = ObjectUtil.invoke(targetObj, mf, args);

					if (targetObj != null)
					{
						targetCls = targetObj.getClass();
					}
					else
					{
						targetCls = null;
					}

				}
				catch (SecurityException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用方法", e);
					be.pushToken(GrammarToken.createToken(method, token.line));
					throw be;
				}

				catch (IllegalArgumentException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "错误的参数", e);
					be.pushToken(GrammarToken.createToken(method, token.line));
					throw be;
				}
				catch (IllegalAccessException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无法访问方法", e);
					be.pushToken(GrammarToken.createToken(method, token.line));
					throw be;
				}
				catch (InvocationTargetException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "内部调用报错",
							e.getTargetException());
					be.pushToken(GrammarToken.createToken(method, token.line));
					throw be;
				}

			}

			lastNode = node;

		}
		return targetObj;
	}

	@Override
	public void infer(InferContext inferCtx)
	{

		Type type = null;
		if (insNode != null)
		{
			insNode.ref.infer(inferCtx);
			type = insNode.ref.type.copy();
		}
		else
		{
			Class cls = inferCtx.gt.loadClassBySimpleName(this.clsNode.cls);
			if (cls == null)
			{
				BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "该类不存在");
				be.pushToken(GrammarToken.createToken(clsNode.cls, token.line));
				throw be;
			}
			type = new Type(cls);

		}

		for (NativeNode node : chain)
		{
			if (type.cls == Object.class)
			{
				this.type = type;

				// do not infer since it's object,但是有风险,剩下的表达式没有机会推测,对于
				//以后生成代码有问题
				return;
			}
			if (node instanceof NativeAtrributeNode)
			{
				String attr = ((NativeAtrributeNode) node).attribute;
				try
				{
					Field f = type.cls.getField(attr);
					Class c = f.getType();
					type.cls = c;
				}
				catch (SecurityException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无法访问属性", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}
				catch (NoSuchFieldException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无此属性", e);
					be.pushToken(GrammarToken.createToken(attr, token.line));
					throw be;
				}

			}
			else if (node instanceof NativeArrayNode)
			{
				if (!type.cls.isArray())
				{
					BeetlException be = new BeetlException(BeetlException.ARRAY_TYPE_ERROR);
					//最好是把上一个字符显示出来
					be.pushToken(GrammarToken.createToken("[]", token.line));
					throw be;
				}
				type.cls = type.cls.getComponentType();
			}
			else if (node instanceof NativeMethodNode)
			{
				NativeMethodNode methodNode = (NativeMethodNode) node;
				String method = methodNode.method;
				Expression[] expList = methodNode.paras;

				Class[] argTypes = expList.length == 0 ? ObjectUtil.EMPTY_CLASS_ARRAY : new Class[expList.length];

				for (int i = 0; i < expList.length; i++)
				{
					expList[i].infer(inferCtx);
					argTypes[i] = expList[i].type.cls;

				}

				try
				{
					ObjectMethodMatchConf conf = ObjectUtil.findMethod(type.cls, method, argTypes);
					if (conf == null)
					{

						type.cls = Object.class;
					}
					else
					{
						type.cls = conf.method.getReturnType();
					}

				}
				catch (SecurityException e)
				{
					BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用方法");
					be.pushToken(GrammarToken.createToken(method, token.line));
					throw be;
				}

			}

		}
		this.type = type;

	}

	private void checkNull(Object o, NativeNode node)
	{
		if (o == null)
		{

			BeetlException be = new BeetlException(BeetlException.NULL);
			be.pushToken(GrammarToken.createToken(node.getName(), token.line));
			throw be;

		}
	}

	private void checkPermit(Context ctx, Class targetCls, Object targetObj, String method)
	{
		if (targetCls == null)
			return;
		if (!ctx.gt.getNativeSecurity().permit(ctx.template.program.res.getId(), targetCls, targetObj, method))
		{
			BeetlException be = new BeetlException(BeetlException.NATIVE_SECUARITY_EXCEPTION);
			be.pushToken(GrammarToken.createToken(method, token.line));
			throw be;
		}
	}
}


text: <?PHP echo $footer->title ?> © 2016


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RDFSharp.Model;

namespace RDFSharp.Test.Model
{
    [TestClass]
    public class RDFTargetSubjectsOfTest
    {
        #region Test
        [TestMethod]
        public void ShouldCreateTargetSubjectsOf()
        {
            RDFTargetSubjectsOf targetSubjectsOf = new RDFTargetSubjectsOf(new RDFResource("ex:targetSubjectsOf"));

            Assert.IsNotNull(targetSubjectsOf);
            Assert.IsTrue(targetSubjectsOf.TargetValue.Equals(new RDFResource("ex:targetSubjectsOf")));
        }

        [TestMethod]
        public void ShouldThrowExceptionOnCreatingTargetSubjectsOfBecauseNullValue()
            => Assert.ThrowsException<RDFModelException>(() => new RDFTargetSubjectsOf(null));

        [TestMethod]
        public void ShouldExportTargetSubjectsOf()
        {
            RDFTargetSubjectsOf targetSubjectsOf = new RDFTargetSubjectsOf(new RDFResource("ex:targetSubjectsOf"));
            RDFGraph graph = targetSubjectsOf.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:nodeShape")));

            Assert.IsNotNull(graph);
            Assert.IsTrue(graph.TriplesCount == 1);
            Assert.IsTrue(graph.ContainsTriple(new RDFTriple(new RDFResource("ex:nodeShape"), RDFVocabulary.SHACL.TARGET_SUBJECTS_OF, targetSubjectsOf.TargetValue)));
        }
        #endregion
    }
}


text:
package org.jclouds.ec2.xml;

import java.net.URI;
import java.util.Map;

import javax.annotation.Resource;

import org.jclouds.http.functions.ParseSax;
import org.jclouds.logging.Logger;

import com.google.common.collect.Maps;

public class DescribeRegionsResponseHandler extends ParseSax.HandlerWithResult<Map<String, URI>> {
   private StringBuilder currentText = new StringBuilder();

   private Map<String, URI> regionEndpoints = Maps.newHashMap();
   private String region;
   private URI regionEndpoint;
   @Resource
   protected Logger logger = Logger.NULL;

   public Map<String, URI> getResult() {
      return regionEndpoints;
   }

   public void endElement(String uri, String name, String qName) {
      if (qName.equals("regionName")) {
         String pending = currentText.toString().trim();
         if (pending.indexOf("Walrus") == -1)
            region = pending;
         // Nova uses regionUrl
      } else if (qName.equals("regionEndpoint") || qName.equals("regionUrl")) {
         String pending = currentText.toString().trim();
         if (pending.indexOf("Walrus") == -1)
            regionEndpoint = URI.create(pending.startsWith("http") ? pending : String.format("https://%s", pending));
      } else if (qName.equals("item") && region != null && regionEndpoint != null) {
         regionEndpoints.put(region, regionEndpoint);
         this.region = null;
         this.regionEndpoint = null;
      }
      currentText.setLength(0);
   }

   public void characters(char ch[], int start, int length) {
      currentText.append(ch, start, length);
   }
}


text:
[test](../index.md) / [containsAll](./contains-all.md)

# containsAll

`fun <E> containsAll(elements: Collection<@UnsafeVariance `[`E`](contains-all.md#E)`>): @UnsafeVariance `[`E`](contains-all.md#E)


text:
from sympy.core.basic import Basic, S
from sympy.core.function import Function, diff
from sympy.core.numbers import Number
from sympy.core.relational import Relational
from sympy.core.sympify import sympify
from sympy.core.sets import Interval, Set

class ExprCondPair(Function):
    """Represents an expression, condition pair."""

    def __new__(cls, *args, **assumptions):
        if isinstance(args[0], cls):
            expr = args[0].expr
            cond = args[0].cond
        elif len(args) == 2:
            expr = sympify(args[0])
            cond = sympify(args[1])
        else:
            raise TypeError("args must be a (expr, cond) pair")
        return Basic.__new__(cls, expr, cond, **assumptions)

    @property
    def expr(self):
        return self.args[0]

    @property
    def cond(self):
        return self.args[1]

    def __iter__(self):
        yield self.expr
        yield self.cond

class Piecewise(Function):
    """
    Represents a piecewise function.

    Usage
    =====
      Piecewise( (expr,cond), (expr,cond), ... )
        - Each argument is a 2-tuple defining a expression and condition
        - The conds are evaluated in turn returning the first that is True.
          If any of the evaluated conds are not determined explicitly False,
          e.g. x < 1, the function is returned in symbolic form.
        - If the function is evaluated at a place where all conditions are False,
          a ValueError exception will be raised.
        - Pairs where the cond is explicitly False, will be removed.

    Examples
    ========
      >>> from sympy import Piecewise, log
      >>> from sympy.abc import x
      >>> f = x**2
      >>> g = log(x)
      >>> p = Piecewise( (0, x<-1), (f, x<=1), (g, True))
      >>> p.subs(x,1)
      1
      >>> p.subs(x,5)
      log(5)

    """

    nargs = None
    is_Piecewise = True

    def __new__(cls, *args, **options):
        # (Try to) sympify args first
        newargs = []
        for ec in args:
            pair = ExprCondPair(*ec)
            cond_type = type(pair.cond)
            if not (cond_type is bool or issubclass(cond_type, Relational) or \
                    issubclass(cond_type, Number) or issubclass(cond_type, Set)):
                raise TypeError, \
                    "Cond %s is of type %s, but must be a bool," \
                    " Relational, Number or Set" % (pair.cond, cond_type)
            newargs.append(pair)

        r = cls.eval(*newargs)

        if r is None:
            return Basic.__new__(cls, *newargs, **options)
        else:
            return r

    def __getnewargs__(self):
        # Convert ExprCondPair objects to tuples.
        args = []
        for expr, condition in self.args:
            args.append((expr, condition))
        return tuple(args)

    @classmethod
    def eval(cls, *args):
        # Check for situations where we can evaluate the Piecewise object.
        # 1) Hit an unevaluatable cond (e.g. x<1) -> keep object
        # 2) Hit a true condition -> return that expr
        # 3) Remove false conditions, if no conditions left -> raise ValueError
        all_conds_evaled = True    # Do all conds eval to a bool?
        piecewise_again = False    # Should we pass args to Piecewise again?
        non_false_ecpairs = []
        for expr, cond in args:
            # Check here if expr is a Piecewise and collapse if one of
            # the conds in expr matches cond. This allows the collapsing
            # of Piecewise((Piecewise(x,x<0),x<0)) to Piecewise((x,x<0)).
            # This is important when using piecewise_fold to simplify
            # multiple Piecewise instances having the same conds.
            # Eventually, this code should be able to collapse Piecewise's
            # having different intervals, but this will probably require
            # using the new assumptions.
            if isinstance(expr, Piecewise):
                for e, c in expr.args:
                    # Don't collapse if cond is "True" as this leads to
                    # incorrect simplifications with nested Piecewises.
                    if c == cond and cond is not True:
                        expr = e
                        piecewise_again = True
            cond_eval = cls.__eval_cond(cond)
            if cond_eval is None:
                all_conds_evaled = False
                non_false_ecpairs.append( (expr, cond) )
            elif cond_eval:
                if all_conds_evaled:
                    return expr
                non_false_ecpairs.append( (expr, cond) )
        if len(non_false_ecpairs) != len(args) or piecewise_again:
            return Piecewise(*non_false_ecpairs)

        # Count number of arguments.
        nargs = 0
        for expr, cond in args:
            if hasattr(expr, 'nargs'):
                nargs = max(nargs, expr.nargs)
            elif hasattr(expr, 'args'):
                nargs = max(nargs, len(expr.args))
        if nargs:
            cls.narg = nargs
        return None

    def doit(self, **hints):
        newargs = []
        for e, c in self.args:
            if hints.get('deep', True):
                if isinstance(e, Basic):
                    e = e.doit(**hints)
                if isinstance(c, Basic):
                    c = c.doit(**hints)
            newargs.append((e, c))
        return Piecewise(*newargs)

    def _eval_integral(self,x):
        from sympy.integrals import integrate
        return  Piecewise(*[(integrate(e, x), c) for e, c in self.args])

    def _eval_interval(self, sym, a, b):
        """Evaluates the function along the sym in a given interval ab"""
        # FIXME: Currently only supports conds of type sym < Num, or Num < sym
        int_expr = []
        mul = 1
        if a > b:
            a, b, mul = b, a, -1
        default = None

        # Determine what intervals the expr,cond pairs affect.
        # 1) If cond is True, then log it as default
        # 1.1) Currently if cond can't be evaluated, throw NotImplentedError.
        # 2) For each inequality, if previous cond defines part of the interval
        #    update the new conds interval.
        #    -  eg x < 1, x < 3 -> [oo,1],[1,3] instead of [oo,1],[oo,3]
        # 3) Sort the intervals to make it easier to find correct exprs
        for expr, cond in self.args:
            if isinstance(cond, bool) or cond.is_Number:
                if cond:
                    default = expr
                    break
                else:
                    continue
            curr = list(cond.args)
            if cond.args[0] == sym:
                curr[0] = S.NegativeInfinity
            elif cond.args[1] == sym:
                curr[1] = S.Infinity
            else:
                raise NotImplementedError, \
                    "Currently only supporting evaluation with only " \
                    "sym on one side of the relation."
            curr = [max(a, curr[0]), min(b, curr[1])]
            for n in xrange(len(int_expr)):
                if self.__eval_cond(curr[0] < int_expr[n][1]) and \
                        self.__eval_cond(curr[0] >= int_expr[n][0]):
                    curr[0] = int_expr[n][1]
                if self.__eval_cond(curr[1] > int_expr[n][0]) and \
                        self.__eval_cond(curr[1] <= int_expr[n][1]):
                    curr[1] = int_expr[n][0]
            if self.__eval_cond(curr[0] < curr[1]):
                int_expr.append(curr + [expr])
        int_expr.sort(key=lambda x:x[0])

        # Add holes to list of intervals if there is a default value,
        # otherwise raise a ValueError.
        holes = []
        curr_low = a
        for int_a, int_b, expr in int_expr:
            if curr_low < int_a:
                holes.append([curr_low, min(b, int_a), default])
            curr_low = int_b
            if curr_low > b:
                break
        if curr_low < b:
            holes.append([curr_low, b, default])

        if holes and default != None:
            int_expr.extend(holes)
        elif holes and default == None:
            raise ValueError, "Called interval evaluation over piecewise " \
                              "function on undefined intervals %s" % \
                              ", ".join([str((h[0], h[1])) for h in holes])

        # Finally run through the intervals and sum the evaluation.
        ret_fun = 0
        for int_a, int_b, expr in int_expr:
            ret_fun += expr._eval_interval(sym,  max(a, int_a), min(b, int_b))
        return mul * ret_fun

    def _eval_derivative(self, s):
        return Piecewise(*[(diff(e, s), c) for e, c in self.args])

    def _eval_subs(self, old, new):
        if self == old:
            return new
        new_args = []
        for e, c in self.args:
            if isinstance(c, bool):
                new_args.append((e._eval_subs(old, new), c))
            elif isinstance(c, Set):
                # What do we do if there are more than one symbolic
                # variable. Which do we put pass to Set.contains?
                new_args.append((e._eval_subs(old, new),  c.contains(new)))
            else:
                new_args.append((e._eval_subs(old, new), c._eval_subs(old, new)))
        return Piecewise( *new_args )

    @classmethod
    def __eval_cond(cls, cond):
        """Returns S.One if True, S.Zero if False, or None if undecidable."""
        if type(cond) == bool or cond.is_number:
            if cond:
                return S.One
            else:
                return S.Zero
        elif type(cond) == Set:
            return None
        return None

def piecewise_fold(expr):
    """
    Takes an expression containing a piecewise function and returns the
    expression in piecewise form.

    >>> from sympy import Piecewise, piecewise_fold
    >>> from sympy.abc import x
    >>> p = Piecewise((x, x < 1), (1, 1 <= x))
    >>> piecewise_fold(x*p)
    Piecewise((x**2, x < 1), (x, 1 <= x))

    """
    if not isinstance(expr, Basic) or not expr.has_piecewise:
        return expr
    new_args = map(piecewise_fold, expr.args)
    if expr.func is ExprCondPair:
        return ExprCondPair(*new_args)
    piecewise_args = []
    for n, arg in enumerate(new_args):
        if arg.func is Piecewise:
            piecewise_args.append(n)
    if len(piecewise_args) > 0:
        n = piecewise_args[0]
        new_args = [(expr.func(*(new_args[:n] + [e] + new_args[n+1:])), c) \
                        for e, c in new_args[n].args]
        if len(piecewise_args) > 1:
            return piecewise_fold(Piecewise(*new_args))
    return Piecewise(*new_args)


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/food/crafted/shared_drink_accarragm.iff"
	result.attribute_template_id = 5
	result.stfName("food_name","accarragm")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
class SweetPotato:
    def __init__(self):
        self.cookedString = "1"
        self.cookedLevel = 0
        self.condiments = []

    # def __str__(self):
    #     return "state:%s (%d)" % (self.cookedString, self.cookedLevel)

    def cook(self, cooked_time):
        self.cookedLevel += cooked_time

        if cooked_time >=0 and cooked_time < 3:
            self.cookedString = "1"
        elif cooked_time >= 3 and cooked_time < 5:
            self.cookedString = "2"
        elif cooked_time > 5 and cooked_time < 8:
            self.cookedString = "0"
        else:
            self.cookedString = "3"

    def addCondiments(self, item):
        self.condiments.append(item)

di_gua = SweetPotato()
print(di_gua)

di_gua.cook(1)
print(di_gua)


text:
<?php

namespace Omnipay\Weixin\Message;

use Illuminate\Support\Facades\Log;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
use Omnipay\Common\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\RedirectResponse as HttpRedirectResponse;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

/**
 * Buckaroo Purchase Response
 */
class QrPurchaseResponse extends PurchaseResponse
{
    public $response;

    public function isSuccessful()
    {
        return false;
    }

    public function isRedirect()
    {
        return true;
    }

    public function getRedirectUrl()
    {
        if ($this->getRedirectMethod() == 'GET') {
            return $this->getRequest()->getEndpoint() . '?' . http_build_query($this->getRedirectData());
        } else {
            return $this->getRequest()->getEndpoint();
        }
    }

    public function getRedirectMethod()
    {
        return 'POST';
    }

    public function getRedirectData()
    {
        return $this->data;
    }

    public function getQrcodeUri()
    {
        $this->response = parent::fromXml($this->getRedirectResponse()->getContent());

        /*
        $qrParams = [
            'appid' =>$this->data['appid'],
            'mch_id' =>$this->data['mch_id'],
            'nonce_str' =>$this->data['nonce_str'],
            'product_id' =>$this->data['product_id'],
            'time_stamp' =>time()
        ];
        $qrParams['sign'] = Helper::getParamsSignature($qrParams, $this->request->getApiKey());
        $qrParamsStr = Helper::toUrlParams($qrParams,true);
        return $this->response['code_url'].'&'.$qrParamsStr;
        */
        Log::info($this->response);
        return $this->response['code_url'];
    }

    public function getRedirectResponse()
    {
        if (!$this instanceof RedirectResponseInterface || !$this->isRedirect()) {
            throw new RuntimeException('This response does not support redirection.');
        }

        if ('GET' === $this->getRedirectMethod()) {
            return HttpRedirectResponse::create($this->getRedirectUrl());
        } elseif ('POST' === $this->getRedirectMethod()) {
            $xml = $this->toXml($this->getRedirectData());
            return HttpResponse::create(parent::postXmlCurl($xml,$this->getRedirectUrl(),false));
        }

        throw new RuntimeException('Invalid redirect method "'.$this->getRedirectMethod().'".');
    }
}


text:
package org.springframework.beans.factory.parsing;

/**
 * SPI interface allowing tools and other external processes to handle errors
 * and warnings reported during bean definition parsing.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 2.0
 * @see Problem
 */
public interface ProblemReporter {

	/**
	 * Called when a fatal error is encountered during the parsing process.
	 *

	 * Implementations must treat the given problem as fatal, i.e. they have to
	 * eventually raise an exception.
	 *
	 * @param problem the source of the error (never {@code null})
	 */
	void fatal(Problem problem);

	/**
	 * Called when an error is encountered during the parsing process.
	 *

	 * Implementations may choose to treat errors as fatal.
	 *
	 * @param problem the source of the error (never {@code null})
	 */
	void error(Problem problem);

	/**
	 * Called when a warning is raised during the parsing process.
	 *

	 * Warnings are never considered to be fatal.
	 *
	 * @param problem the source of the warning (never {@code null})
	 */
	void warning(Problem problem);

}


text:
namespace System.Web.Services.Protocols {
    using System;

    /// <include file='doc\HttpMethodAttribute.uex' path='docs/doc[@for="HttpMethodAttribute"]/*' />
    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class HttpMethodAttribute : System.Attribute {
        Type returnFormatter;
        Type parameterFormatter;

        /// <include file='doc\HttpMethodAttribute.uex' path='docs/doc[@for="HttpMethodAttribute.HttpMethodAttribute"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public HttpMethodAttribute() {
            returnFormatter = null;
            parameterFormatter = null;
        }

        /// <include file='doc\HttpMethodAttribute.uex' path='docs/doc[@for="HttpMethodAttribute.HttpMethodAttribute1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public HttpMethodAttribute(Type returnFormatter, Type parameterFormatter) {
            this.returnFormatter = returnFormatter;
            this.parameterFormatter = parameterFormatter;
        }

        /// <include file='doc\HttpMethodAttribute.uex' path='docs/doc[@for="HttpMethodAttribute.ReturnFormatter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public Type ReturnFormatter {
            get { return returnFormatter; }
            set { returnFormatter = value; }
        }

        /// <include file='doc\HttpMethodAttribute.uex' path='docs/doc[@for="HttpMethodAttribute.ParameterFormatter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public Type ParameterFormatter {
            get { return parameterFormatter; }
            set { parameterFormatter = value; }
        }
    }
}