text:
import re
import cPickle
import os
from cStringIO import StringIO

class UnpickleError(Exception):
    pass

GPU_LOCK_NO_SCRIPT = -2
GPU_LOCK_NO_LOCK = -1

def pickle(filename, data):
    fo = filename
    if type(filename) == str:
        fo = open(filename, "w")

    cPickle.dump(data, fo, protocol=cPickle.HIGHEST_PROTOCOL)
    fo.close()

def unpickle(filename):
    if not os.path.exists(filename):
        raise UnpickleError("Path '%s' does not exist." % filename)

    fo = open(filename, 'r')
    z = StringIO()
    file_size = os.fstat(fo.fileno()).st_size
    # Read 1GB at a time to avoid overflow
    while fo.tell() < file_size:
        z.write(fo.read(1 << 30))
    fo.close()
    dict = cPickle.loads(z.getvalue())
    z.close()

    return dict

def is_intel_machine():
    VENDOR_ID_REGEX = re.compile('^vendor_id\s+: (\S+)')
    f = open('/proc/cpuinfo')
    for line in f:
        m = VENDOR_ID_REGEX.match(line)
        if m:
            f.close()
            return m.group(1) == 'GenuineIntel'
    f.close()
    return False

# Returns the CPUs associated with a given GPU
def get_cpus_for_gpu(gpu):
    #proc = subprocess.Popen(['nvidia-smi', '-q', '-i', str(gpu)], stdout=subprocess.PIPE)
    #lines = proc.communicate()[0]
    #lines = subprocess.check_output(['nvidia-smi', '-q', '-i', str(gpu)]).split(os.linesep)

    with open('/proc/driver/nvidia/gpus/%d/information' % gpu) as f:
        for line in f:
            if line.startswith('Bus Location'):
                bus_id = line.split(':', 1)[1].strip()
                bus_id = bus_id[:7] + ':' + bus_id[8:]
                ff = open('/sys/module/nvidia/drivers/pci:nvidia/%s/local_cpulist' % bus_id)
                cpus_str = ff.readline()
                ff.close()
                cpus = [cpu for s in cpus_str.split(',') for cpu in range(int(s.split('-')[0]),int(s.split('-')[1])+1)]
                return cpus
    return [-1]

def get_cpu():
    if is_intel_machine():
        return 'intel'
    return 'amd'

def is_windows_machine():
    return os.name == 'nt'

def tryint(s):
    try:
        return int(s)
    except:
        return s

def alphanum_key(s):
    return [tryint(c) for c in re.split('([0-9]+)', s)]


text:
(function () {
	'use strict';

	var logger = require('bunyan').createLogger({name: 'nodecore'});

	var i8 = require('i8');
	var server = new i8.Server(logger);
	var config = server.getConfig();

	/*var mongoose = require("mongoose");
	mongoose.connect.apply(mongoose, [config.dbUrl]);
	mongoose.connection.on("connected", function () {
    logger.info([config.dbUrl, "mongoose connected");
	});
	mongoose.connection.on("error", function () {
    logger.error("Mongoose not connected. Exiting.");
    process.exit(1);
	});*/

	var router = i8.createRouter();
	router.get('/', function (req, res, next) {
		res.status(200).jsonp({message: 'Hello API World at ' + Date.now() });
	});

	server.use('/api', router);
	server.static('/', './main/web');
	server.startup();

})();

redpajama_set_name: RedPajamaGithub


text:
product: material-ui
title: React Timeline component
components: Timeline, TimelineItem, TimelineSeparator, TimelineDot, TimelineConnector, TimelineContent, TimelineOppositeContent
githubLabel: 'component: timeline'
packageName: '@mui/lab'
---

# Timeline

The timeline displays a list of events in chronological order.

**Note:** This component is not documented in the [Material Design guidelines](https://material.io/), but MUI supports it.

{{"component": "modules/components/ComponentLinkHeader.js"}}

## Basic timeline

A basic timeline showing list of events.

{{"demo": "BasicTimeline.js"}}

## Left-positioned timeline

The main content of the timeline can be positioned on the left side relative to the time axis.

{{"demo": "LeftPositionedTimeline.js"}}

## Alternating timeline

The timeline can display the events on alternating sides.

{{"demo": "AlternateTimeline.js"}}

## Color

The `TimelineDot` can appear in different colors from theme palette.

{{"demo": "ColorsTimeline.js"}}

## Outlined

{{"demo": "OutlinedTimeline.js"}}

## Opposite content

The timeline can display content on opposite sides.

{{"demo": "OppositeContentTimeline.js"}}

## Customization

Here is an example of customizing the component.
You can learn more about this in the [overrides documentation page](/material-ui/customization/how-to-customize/).

{{"demo": "CustomizedTimeline.js"}}


text:
package ca.ualberta.lard.test;

import ca.ualberta.lard.MainActivity;
import ca.ualberta.lard.model.Picture;
import android.test.ActivityInstrumentationTestCase2;

/**
 * Tests the LARD Picture Model. Test String and byte array getters and setters
 */
public class PictureModelTests extends ActivityInstrumentationTestCase2<MainActivity> {

	public PictureModelTests() {
		super (MainActivity.class);
	}

	/**
	 * Tests the byte getters and setters to make sure they are not returning null
	 */
	public void testByteArray(){
		Picture picture = new Picture();
		byte[] byteArray = new byte[] {(byte) 0x00, (byte)0xf3};
		picture.setImageByte(byteArray);
		assertNotNull("The setted byteArray should not be null", picture.getImageByte() );
	}

}


text:
    Work with us :)

      Sign In

Welcome,


text:
package org.theospi.portfolio.shared.mgt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.metaobj.shared.mgt.HomeFactory;
import org.sakaiproject.metaobj.shared.mgt.IdManager;
import org.sakaiproject.metaobj.shared.mgt.ReadableObjectHome;
import org.sakaiproject.metaobj.shared.model.Artifact;
import org.sakaiproject.metaobj.shared.model.Id;
import org.sakaiproject.metaobj.shared.model.PersistenceException;

public class ArtifactUserType {
   protected final transient Log logger = LogFactory.getLog(getClass());

   private Id id = null;
   private ReadableObjectHome home = null;

   public ArtifactUserType() {
   }

   public ArtifactUserType(String id, String type) {
      this.id = getIdManager().getId(id);
      setHome(type);
   }

   protected IdManager getIdManager() {
      return (IdManager) ComponentManager.getInstance().get("idManager");
   }

   protected HomeFactory getHomeFactory() {
      return (HomeFactory) ComponentManager.getInstance().get("homeFactory");
   }

   public Artifact load() throws PersistenceException {
      if (home != null && id != null) {
         return home.load(id);
      }
      else {
         return null;
      }
   }

   public Id getId() {
      return id;
   }

   public void setId(Id id) {
      this.id = id;
   }

   public ReadableObjectHome getHome() {
      return home;
   }

   public void setHome(String homeName) {
      this.home = getHomeFactory().getHome(homeName);
   }

   public void setHome(ReadableObjectHome home) {
      this.home = home;
   }

   public String toString() {
      return "ArtifactUserType{" +
         "id=" + id +
         ", home=" + home +
         "}";
   }

}


text:
package com.etsy.statsd.profiler.worker;

import com.etsy.statsd.profiler.Profiler;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;

/**
 * Worker thread for executing a profiler
 *
 * @author Andrew Johnson
 */
public class ProfilerWorkerThread implements Runnable {
    private final Profiler profiler;
    private final List<String> errors;

    public ProfilerWorkerThread(Profiler profiler, List<String> errors) {
        this.profiler = profiler;
        this.errors = errors;
    }

    @Override
    public void run() {
        try {
            profiler.profile();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            errors.add(String.format("Received an error running profiler: %s, error: %s", profiler.getClass().getName(), sw.toString()));
            if (errors.size() > 10) {
                ((LinkedList) errors).pollFirst();
            }
        }
    }
}


text:
function [A, F, M] = Assembler_3D(MESH, DATA, FE_SPACE, OPERATOR, TC_d, TC_t, subdomain, t)
%ASSEMBLER_3D assembler for 3D ADR equations with numerical
%quadratures.
%
%   [A, F] = ASSEMBLER_3D(MESH, DATA, FE_SPACE) given MESH and
%   FE_SPACE structs, assemble the stiffness matrix A and rhs vector F
%   of the advection-diffusion-reaction differential operator using the
%   parameters specified in the DATA struct. The resulting matrix and
%   vector doesn't take into account for Boundary Conditions.
%
%   [A, F, M] = ASSEMBLER_3D(MESH, DATA, FE_SPACE, T) as before, but also
%   returns the mass matrix M. Moreover, the problem's parameters are
%   evaluated with respect to a given time T.
%
%   [A] = Assembler_3D(MESH, DATA, FE_SPACE, 'diffusion', [i j], [], k);
%   returns the matrix corresponding to the (i,j)-th second derivative
%   (diffusion operator) assembled over the subdomain \Omega_k
%   A spatial dependent coefficient has to be defined in DATA.diffusion
%
%   [A] = Assembler_3D(MESH, DATA, FE_SPACE, 'transport', [], [i], k);
%   returns the matrix corresponding to the (i)-th first derivative
%   (advection operator) assembled over the subdomain \Omega_k
%   A spatial dependent coefficient has to be defined in DATA.transport{i}

%   This file is part of redbKIT.
%   Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne (EPFL)
%   Author: Federico Negri <federico.negri@epfl.ch>

warning('Assembler_3D is deprecated. Use ADR_Assembler instead.')

if nargin < 4 || isempty(OPERATOR)
    OPERATOR = 'all';
end

if nargin < 5 || isempty(TC_d)
    TC_d = [10 10];% diagonal components of the diffusion operator by default
end

if nargin < 6 || isempty(TC_t)
    TC_t = 10; % all components of the transport operator by default
end

if nargin < 7
    subdomain = [];
end

if nargin < 8
    t = [];
end

if ~isempty(subdomain)
    index_subd = [];
    for q = 1 : length(subdomain)
        index_subd = [index_subd find(MESH.elements(FE_SPACE.numElemDof+1,:) == subdomain(q))];
    end
    MESH.elements = MESH.elements(:,index_subd);
    MESH.numElem  = size(MESH.elements,2);
else
    index_subd = [1:MESH.numElem];
end

%% Computations of all quadrature nodes in the elements
x = zeros(MESH.numElem,FE_SPACE.numQuadNodes); y = x; z = x;
coord_ref = MESH.chi;

for j = 1:4
    i = MESH.elements(j,:);
    vtemp = MESH.vertices(1,i);
    x = x + vtemp'*coord_ref(j,:);
    vtemp = MESH.vertices(2,i);
    y = y + vtemp'*coord_ref(j,:);
    vtemp = MESH.vertices(3,i);
    z = z + vtemp'*coord_ref(j,:);
end

%% Evaluation of coefficients in the quadrature nodes
mu  = DATA.diffusion(x,y,z,t,DATA.param);
si  = DATA.reaction(x,y,z,t,DATA.param);

switch class(DATA.force)
      case {'function_handle','inline'}
            f  = DATA.force(x,y,z,t,DATA.param);

      case 'double'
            if size(DATA.force,1)>1 && size(DATA.force,2)>1
                  f = DATA.force(index_subd,:);

            elseif length(DATA.force)==MESH.numNodes

                  f = zeros(MESH.numElem,FE_SPACE.numQuadNodes);
                  for j = 1 : FE_SPACE.numElemDof
                        i = MESH.elements(j,:);
                        f = f + DATA.force(i)*FE_SPACE.phi(j,:);
                  end
            end
end

bx  = DATA.transport{1}(x,y,z,t,DATA.param);
by  = DATA.transport{2}(x,y,z,t,DATA.param);
bz  = DATA.transport{3}(x,y,z,t,DATA.param);

%% Vectorized assemly, returns matrices in sparse vector format
[Arows, Acols, Acoef, Mcoef, Rrows, Rcoef] = ADR_assembler_C_omp(MESH.dim, OPERATOR, TC_d, TC_t, MESH.elements, FE_SPACE.numElemDof, mu, [bx by bz], si, f,...
    FE_SPACE.quad_weights, MESH.invjac(index_subd,:,:), MESH.jac(index_subd), FE_SPACE.phi, FE_SPACE.dphi_ref);

%% Build sparse matrices and rhs
A    = sparse(Arows,Acols,Acoef,MESH.numNodes,MESH.numNodes);
M    = sparse(Arows,Acols,Mcoef,MESH.numNodes,MESH.numNodes);
F    = sparse(Rrows,1,Rcoef,MESH.numNodes,1);

return


text:
from __future__ import unicode_literals

import os
import logging
from django.conf import settings
from django.apps import AppConfig

class AtsConfig(AppConfig):
    name = 'ats'
    verbose_name = 'Active Task Summary'

    # app info
    APP_VERSION = '3.1.0'
    APP_AUTHER = 'dictoss'

    # valid range is between 1 and 24.
    ATS_REGIST_HOUR_MAX = 16

    # valid range is between 1 and 30.
    ATS_REGIST_MIN_SPAN = [0, 15, 30, 45]

    ATS_IS_LASTNAME_FRONT = False

    HIDDEN_DEFAULT_SUPERUSER = ''


text:
/**
 * CSS for the documents list.
 */

#documents {
  font-size: 13px;
  top: 29px;
}

#documents-status {
  margin-top: 3px;
  margin-left: 17px;
  font-size: 13px;
}

div.document {
  border-left: 2px dotted #a0a0a0;
}

a.in-clusters,
a.in-new-window,
a.show-preview {
  padding-left: 16px;
  background-position: right 2px;
}

a.in-clusters {
  background-image: url('../../common/img/icon-in-clusters.gif'); /** sprite-ref: vert; sprite-alignment: right; sprite-margin-bottom: 20px; sprite-margin-top: 2px */
}

a.in-new-window {
  background-image: url('../../common/img/icon-in-new-window.gif'); /** sprite-ref: vert; sprite-alignment: right; sprite-margin-bottom: 20px; sprite-margin-top: 2px */
}

a.show-preview {
  background-image: url('../../common/img/icon-show-preview.gif'); /** sprite-ref: vert; sprite-alignment: right; sprite-margin-bottom: 20px; sprite-margin-top: 2px */
}


text:
import express = require('express');
import path = require('path');
import favicon = require('serve-favicon');
import logger = require('morgan');
import cookieParser = require('cookie-parser');
import bodyParser = require('body-parser');
import http = require('http');

import routes = require('./routes');

var app = express();
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var server = http.createServer(app);
server.listen(port, ip);


text:
/**
 * @flow
 */

var z: number = 123;

declare class Foo {
  get goodGetterWithAnnotation(): number;
  set goodSetterWithAnnotation(x: number): void;

  get propWithMatchingGetterAndSetter(): number;
  set propWithMatchingGetterAndSetter(x: number): void;

  // The getter and setter need not have the same type - no error
  get propWithSubtypingGetterAndSetter(): ?number;
  set propWithSubtypingGetterAndSetter(x: number): void;

  // The getter and setter need not have the same type - no error
  set propWithSubtypingGetterAndSetterReordered(x: number): void;
  get propWithSubtypingGetterAndSetterReordered(): ?number;

  get propWithMismatchingGetterAndSetter(): number;
  set propWithMismatchingGetterAndSetter(x: string): void; // doesn't match getter (OK)

  propOverriddenWithGetter: number; // error: can't shadow proto with incompatible own
  get propOverriddenWithGetter(): string;

  propOverriddenWithSetter: number; // error: can't shadow proto with incompatible own
  set propOverriddenWithSetter(x: string): void;
};

var foo = new Foo();

// Test getting properties with getters
var testGetterNoError2: number = foo.goodGetterWithAnnotation;

var testGetterWithError2: string = foo.goodGetterWithAnnotation; // Error number ~> string

// Test setting properties with getters
foo.goodSetterWithAnnotation = 123;

foo.goodSetterWithAnnotation = "hello"; // Error string ~> number

var testSubtypingGetterAndSetter: number = foo.propWithSubtypingGetterAndSetter; // Error ?number ~> number

var testPropOverridenWithGetter: number = foo.propOverriddenWithGetter; // Error string ~> number
foo.propOverriddenWithSetter = 123; // Error number ~> string


text:
"""
Name   : modular_theory.py
Author : David Freestone (david.freestone@bucknell.edu)
Date   : 01.01.2016

This time_event module is covered under the modified BSD license
Copyright (c) 2015, David M. Freestone
All rights reserved.

Description:
"""

# What we need:
# [1] Main loop
#     [a]: update procedure state
#     [b]: update model state
#     [c]: update subject state

from pandas import DataFrame
from numba import jit
from numpy import array, zeros, arange, linspace
import numpy as np
import re

NUMBA_DISABLE_JIT = 1  # Disables JIT for debugging

class Simulation():

    def __init__(self, notation=None, resolution=0.01, parameters=None):

        self.parameters = {"beta_r": 0.5,
                           "beta_e": 1e-5,
                           "c": 1.0,
                           "alpha": 0.05,
                           "phi": 50.0,
                           "gamma": 0.2,
                           "r0": 0.05,
                           "A": 5.0,
                           "mu_poisson": 3.0,
                           "mu_wald": 0.68,
                           "lambda_wald": 0.93}
        if parameters is not None:
            self.parameters.update(parameters)

        # TODO(David): Completely change this, probably, because it sucks
        self.resolution = resolution
        self.original_notation = notation
        self.notation = notation  # in case we need to convert point events
        self.array_notation = notation  # numpy array for jit
        self.parse_notation()
        self.convert_notation()

        # TODO(David): Fix for multiple cycle types
        df_cycle_types = DataFrame(self.array_notation[:, :, 0], columns=["event", "id"])
        df_cycle_types = df_cycle_types[(df_cycle_types.event==STIMULUS_ON) | (df_cycle_types.event==STIMULUS_OFF)].drop_duplicates()
        df_cycle_types["row"] = arange(0, df_cycle_types.shape[0])

        self.time_marker_info = df_cycle_types.as_matrix()
        self.n_time_markers = self.time_marker_info.shape[0]
        self.time_marker_row = 2

    def parse_notation(self):
        """Return cycle information"""
        if self.notation is None:
            return None

        if not isinstance(self.notation, dict):
            self.notation = {'C1': self.notation}

        for cycle in self.notation:
            notation = self.convert_point_events(self.notation[cycle],
                                                 self.resolution)
            states = tuple([self.parse_state(state)
                            for state in notation.split()])
            self.notation[cycle] = {'notation': notation,
                                    'states': states}
        return None

    @staticmethod
    def convert_point_events(notation, resolution):
        """Return full notation, i.e., O.1 to O1 0.02T o1"""
        notation = notation.split()
        for i, state in enumerate(notation):
            if '.' in state:
                event, criteria = state.split('.')
                notation[i] = '{}{} {}T {}{}'.format(event, criteria,
                                                     resolution,
                                                     event.lower(), criteria)
        return ' '.join(notation)

    @staticmethod
    def parse_state(state_notation):
        """Split state inot event and criteria"""
        tokens = re.split(r'([0-9\.]+)', state_notation)
        state = [None, None]
        for token in tokens:
            if len(token) == 0:
                continue
            try:
                state[0] = float(token)
            except ValueError:
                state[1] = token
            #       TODO(David): Allow non-integer event IDs?
        if 'T' not in state and None not in state:
            state[0] = int(state[0])
        return tuple(state)

    def convert_notation(self):
        ncycles = len(self.notation)
        max_states = max([len(self.notation[cycle]['states'])
                          for cycle in self.notation])
        self.array_notation = zeros((max_states, 2, ncycles), dtype=float)
        for icy, cycle in enumerate(self.notation):
            for ist, state in enumerate(self.notation[cycle]['states']):
                criteria, event = state
                event = -ord(event[1]) if event == '~T' else ord(event)
                self.array_notation[ist, :, icy] = array([event, criteria])

    def run(self):
        (self.data, self.strength_memory,
         self.reference_memory, self.packet_initiation_rate, self.max_timestep) = __run__(self.array_notation, self.time_marker_info, self.n_time_markers, self.time_marker_row,
                                                                       self.parameters["beta_r"], self.parameters["beta_e"],
                                                                       self.parameters["c"], self.parameters["alpha"],
                                                                       self.parameters["phi"], self.parameters["gamma"],
                                                                       self.parameters["r0"], self.parameters["A"],
                                                                       self.parameters["mu_poisson"], self.parameters["mu_wald"],
                                                                       self.parameters["lambda_wald"])
        self.data = DataFrame(self.data, columns=["time", "event", "id"])
        self.data.event = self.data.event.astype(int).map(chr)

STIMULUS_ON = ord('S')
STIMULUS_OFF = ord('s')
RESPONSE_ON = ord('R')
RESPONSE_OFF = ord('r')
OUTCOME_ON = ord('O')
OUTCOME_OFF = ord('o')
TIME = ord('T')
RANDOM_TIME = -ord('T')
RANDOM_EXPONENTIAL = ord('E')

# indices for state matrix
event_idx = 0
criteria_idx = 1

@jit(nopython=True)
def __run__(CYCLE_TYPES, time_marker_info, n_time_markers, time_marker_row,
            beta_r, beta_e, c, alpha, phi, gamma,
            r0, A, mu_poisson, mu_wald, lambda_wald):
    # Experiment info
    time = 0
    resolution = 0.01
    session_duration = 120 * 60
    max_timesteps = 2 * int(session_duration / resolution)  # 2x for buffer

    data = zeros((int(max_timesteps), 3))
    data_count = 0

    response = True
    cycle = 0
    state = 0
    nstates = get_nstates(CYCLE_TYPES[:, :, 0])
    state_time = 0
    # TODO(David): This doesn't copy fully, so any change to current_cycle_info propogates... :-(
    cycle, nstates = get_next_cycle(CYCLE_TYPES)
    cycle_types = copy_matrix(CYCLE_TYPES)
    current_cycle_info = cycle_types[:, :, cycle]

    # model setup
    time_marker_started = zeros(int(n_time_markers))
    timestep = zeros(int(n_time_markers))
    max_timestep = zeros(int(n_time_markers))
    model_state = zeros(int(n_time_markers))

    # TODO(David): Optimize for C or R major ordering
    strength_memory = zeros((int(max_timesteps), int(n_time_markers)))
    scalar_strength_memory = zeros(int(n_time_markers))

    perceptual_store = linspace(0, 2*session_duration, int(max_timesteps))

    # TODO(David): Optimize for C or R major ordering
    reference_memory = zeros((int(max_timesteps), int(n_time_markers)))
    threshold = zeros(int(n_time_markers))

    reliability = zeros(int(n_time_markers))
    packet_initiation_rate = zeros(int(n_time_markers))
    total_packet_initiation_rate = zeros((int(max_timesteps), int(n_time_markers)))

    response_queue = zeros(int(max_timesteps))
    response_idx = 0
    response_count = 0
    max_response_count = int(max_timesteps)

    running = True
    while running:

        # update experiment
        time += resolution
        if time >= session_duration:
            running = False
            break

        # update procedure
        state_time += resolution
        outcome = False

        next_event = True
        while next_event:
            if state > nstates:
                state = 0
                state_time = 0
                cycle, nstates = get_next_cycle(CYCLE_TYPES)
                cycle_types = copy_matrix(CYCLE_TYPES)
                # TODO(David): This doesn't copy fully, so any change to current_cycle_info propogates... :-(
                current_cycle_info = cycle_types[:, :, cycle]

            event = int(current_cycle_info[state, event_idx])
            criteria = current_cycle_info[state, criteria_idx]

            if event == TIME:
                if state_time >= criteria:
                    state += 1
                    state_time = 0
                    data[data_count, 0] = time
                    data[data_count, 1] = TIME
                    data[data_count, 2] = criteria
                    data_count += 1
                else:
                    next_event = False

            elif event == RANDOM_TIME:
                # TODO(David): Implement me!
                current_cycle_info[state, event_idx] = RANDOM_EXPONENTIAL

            elif event == RESPONSE_ON:
                if response:
                    # TODO(David): Shoudl this record the end of this state?
                    #              So that we separate the response code from the state codes?
                    state += 1
                    state_time = 0
                else:
                    next_event = False

            elif event == RESPONSE_OFF:
                # TODO(David): Shoudl this record the end of this state?
                #              So that we separate the response code from the state codes?
                # TODO(David): Implement me!
                pass

            elif event == STIMULUS_ON:
                # NOTE(David): The [0] at the end is needed so that numba can represent the row as an int rather than a numpy array. Or something
                row = time_marker_info[(time_marker_info[:,0]==STIMULUS_ON) & (time_marker_info[:,1]==criteria), 2][0]
                time_marker_started[int(row)] = 1
                state += 1
                state_time = 0
                data[data_count, 0] = time
                data[data_count, 1] = STIMULUS_ON
                data[data_count, 2] = criteria
                data_count += 1

            elif event == STIMULUS_OFF:
                #NOTE(David): In reality, Modular Theory has no notion of stimulus state (on or off),
                #             It just has time markers. So there is no real "STIMULUS_OFF", there's just
                #             a time to reset a time marker (when it comes on)
                #             We'll keep this because its easier to work with both "S" and "s" this way
                row = time_marker_info[(time_marker_info[:,0]==STIMULUS_OFF) & (time_marker_info[:,1]==criteria), 2][0]
                time_marker_started[int(row)] = 1
                state += 1
                state_time = 0
                data[data_count, 0] = time
                data[data_count, 1] = STIMULUS_OFF
                data[data_count, 2] = criteria
                data_count += 1

            elif event == OUTCOME_ON:
                # TODO(David): Add this as a stimulus
                state += 1
                state_time = 0
                outcome = True
                data[data_count, 0] = time
                data[data_count, 1] = OUTCOME_ON
                data[data_count, 2] = criteria
                data_count += 1

            elif event == OUTCOME_OFF:
                # TODO(David): Add this as a stimulus
                state += 1
                state_time = 0
                outcome = False  # TODO(David): Make sure this actually works
                data[data_count, 0] = time
                data[data_count, 1] = OUTCOME_OFF
                data[data_count, 2] = criteria
                data_count += 1

            elif event == RANDOM_EXPONENTIAL:
                current_cycle_info[state, criteria_idx] = np.random.exponential(criteria)
                current_cycle_info[state, event_idx] = TIME
                data[data_count, 0] = time
                data[data_count, 1] = RANDOM_EXPONENTIAL
                data[data_count, 2] = criteria
                data_count += 1

        # update model state
        for time_marker in time_marker_info[:, 2]:

            """ update or reset time """
            if time_marker_started[int(time_marker)]:
                timestep[int(time_marker)] = 0
                time_marker_started[int(time_marker)] = 0
            else:
                timestep[int(time_marker)] += 1

            if outcome:
                """ Equation 1: clock """
                # TODO(David): we need to convert the timesteps to time, scale by c, then convert back to timestep
                #              but since model_state updates in real continous time, we don't want to update the
                #              timestep for real so it gets out of sync. So we'll create a temporary timestep
                perceived_time = c * (timestep[int(time_marker)] * resolution)
                temporary_timestep = int(perceived_time / resolution)

                """ Equation 2: perceptual store """
                # Using an already filled list that we just index into whenever we need to, e.g.

                """ Equation 3: reference memory """
                # TODO(David): Probably easiest thing to do is to make this a ufunc
                if temporary_timestep > max_timestep[int(time_marker)]:
                    reference_memory[max_timestep[int(time_marker)]:int(temporary_timestep), int(time_marker)] = perceptual_store[int(temporary_timestep):max_timestep[int(time_marker)]:-1]
                    max_timestep[int(time_marker)] = temporary_timestep
                for i in range(temporary_timestep+1):
                    reference_memory[i, int(time_marker)] = alpha*perceptual_store[int(temporary_timestep-i)] + (1-alpha)*reference_memory[i, int(time_marker)]

                """ Equation 4: threshold """
                # As long as there's reference_memory
                if max_timestep[int(time_marker)] > 0:
                    max_perceived_time = max_timestep[int(time_marker)] * resolution
                    random_threshold = phi + (phi*gamma)*np.random.randn()
                    # NOTE(David): numba now supports np.histogram
                    histogram_reference_memory = histogram(reference_memory[:max_timestep[int(time_marker)], int(time_marker)], int(max_timestep[int(time_marker)]), max_perceived_time, resolution)
                    threshold[int(time_marker)] = percentile(histogram_reference_memory, resolution, random_threshold)

            """ Equation 5: state """
            model_state[int(time_marker)] = int(reference_memory[int(timestep[int(time_marker)]), int(time_marker)] < threshold[int(time_marker)])

            """ Equation 6: update strength memory """
            # NOTE(David): keeping a scalar_reference_memory means we don't need to store p_timestep anymore,
            #              and keeping a strength_memory means we can still store the entire time vector of strenghts
            beta = beta_r if outcome else beta_e
            scalar_strength_memory[int(time_marker)] += beta*(outcome - scalar_strength_memory[int(time_marker)]) * resolution
            strength_memory[int(timestep[int(time_marker)]), int(time_marker)] = scalar_strength_memory[int(time_marker)]

            """ Model update done  """

            """ Equation 7: operant rate """
            # Nothing to do here, its just a constant

            """ Equation 8: packet initation rate """
            packet_initiation_rate[int(time_marker)] = resolution*(r0 + (A * model_state[int(time_marker)] * strength_memory[int(timestep[int(time_marker)]), int(time_marker)]))
            total_packet_initiation_rate[int(timestep[int(time_marker)]), int(time_marker)] = packet_initiation_rate[int(time_marker)]

            # Update subject
            """New equation: summing packet initiation rates"""
            reliability[int(time_marker)] = reference_memory[0, int(time_marker)] if reference_memory[0, int(time_marker)] > 0 else 1

        # TODO(David): Note reliability is commented out below
        total_reliability = reliability.sum()
        combined_packet_initiation_rate = 0
        for i in range(n_time_markers):
            combined_packet_initiation_rate += packet_initiation_rate[i] * (reliability[i]/total_reliability)

        if np.random.rand() <= combined_packet_initiation_rate:
            """ Equation 9a: Poisson rv """
            P_u = np.random.poisson(mu_poisson)

            """ Equation 9b: Inverse Gaussian rv """
            # TODO(David): Make this a ufunc, prob.
            #              Numba does not have the function definition for adding
            #              the size argument
            if P_u > 0:
                rt = time  # TODO(David): Maybe clean this up too?
                for _ in range(P_u):
                    rt += np.random.wald(mu_wald, lambda_wald)
                    response_queue[response_count] = rt
                    response_count += 1
                    if response_count >= max_response_count:
                        # TODO(David): Repark the counters and junk
                        # For now, just erase all responses (bad!)
                        response_idx = 0
                        response_count = 0

        # TODO(David): Handle response_off in a reasonable way
        response = (response_count > 0) and time >= response_queue[response_idx]
        if response:
            # TODO(David): Add this as a stimulus
            response_idx += 1  # This procedure handles recording the response
            data[data_count, 0] = time
            data[data_count, 1] = RESPONSE_ON
            data[data_count, 2] = 1  # TODO(David): This does not account for more than 1 response
                                     #              Its 1 because if it were "criteria" like everything else,
                                     #              it would be wrong (it would be the criteria for whatever state we're in)
            data_count += 1
            if response_idx > response_count:
                response_idx = 0
                response_count = 0

    data = data[:data_count, :]
    return data, strength_memory, reference_memory, total_packet_initiation_rate, max_timestep

@jit(nopython=True)
def copy_matrix(src):
    dst = zeros(src.shape)
    for i in range(src.shape[0]):
        for j in range(src.shape[1]):
            for k in range(src.shape[2]):
                dst[i, j, k] = src[i, j, k]
    return dst

@jit(nopython=True)
def percentile(arr, resolution, p):
    n = arr.size
    np = (p/100)*n
    s = 0
    for i in range(n):
        s += arr[i]
        if s >= np:
            return (1+i) * resolution  # TODO(David): Make sure it actually is 1+i rather than i
    return n * resolution

# NOTE(David): Numba now supports np.histogram
@jit(nopython=True)
def histogram(arr_in, n, hmax, resolution):
    """ Modifies arr_out in place """
    nbins = int(hmax / resolution)
    # TODO(David): Should we allocate with zeros, or zero the array?
    arr_out = zeros(nbins)
    for i in range(n):
        bin_index = int(arr_in[i] / resolution)
        # TODO(David): Test if this if-else statement is event necessary
        if 0 <= bin_index < nbins:
            arr_out[int(bin_index)] += 1
        elif arr_in[i] >= hmax:
            arr_out[int(nbins)] += 1  # All other elements go into the last bin
    return arr_out

@jit(nopython=True)
def is_sorted(arr):
    for i in range(1, arr.size):
        if arr[i] < arr[i-1]:
            return False
    return True

@jit(nopython=True)
def quickSort(arr):
    """"  quickSort
      This function was modified translated from Darel Rex Finley's C implementation
    """
    MAX_LEVELS = 300

    beg = zeros(MAX_LEVELS)
    end = zeros(MAX_LEVELS)

    end[0] = arr.size

    i = 0
    while (i >= 0):
        L = int(beg[i])
        R = int(end[i]-1)

        if (L < R):
            piv = arr[L]

            while (L < R):
                while ((arr[R] >= piv) and (L < R)):
                    R -= 1
                if (L < R):
                    arr[L] = arr[R]
                    L += 1

                while ((arr[L] <= piv) and (L < R)):
                    L += 1
                if (L < R):
                    arr[R] = arr[L]
                    R -= 1

            arr[L] = piv
            beg[i+1] = L+1
            end[i+1] = end[i]
            end[i] = L
            i += 1
            if (end[i]-beg[i] > end[i-1]-beg[i-1]):
                swap = beg[i]
                beg[i] = beg[i-1]
                beg[i-1] = swap

                swap = end[i]
                end[i] = end[i-1]
                end[i-1] = swap
        else:
            i -= 1

@jit(nopython=True)
def __round__(x, dx):
    return round(x/dx) * dx

@jit(nopython=True)
def get_next_cycle(cycle_types):
    # TODO(David): Implement for real
    #               Need a way to put in the cycle as a cycle order
    cycle = 0
    nstates = get_nstates(cycle_types[:, :, cycle])
    return cycle, nstates

@jit(nopython=True)
def get_nstates(cycle_type):
    for state in range(cycle_type.shape[0]):
        if cycle_type[state, 1] == 0:
            return state
    return state

if __name__ == "__main__":
    procedure = "10T S1 60T O.1 s1"
    simulation = Simulation(procedure)
    simulation.run()


text:
class Projects::RefsController < Projects::ApplicationController
  include ExtractsPath
  include TreeHelper

  before_action :require_non_empty_project
  before_action :validate_ref_id
  before_action :assign_ref_vars
  before_action :authorize_download_code!

  def switch
    respond_to do |format|
      format.html do
        new_path =
          case params[:destination]
          when "tree"
            namespace_project_tree_path(@project.namespace, @project, @id)
          when "blob"
            namespace_project_blob_path(@project.namespace, @project, @id)
          when "graph"
            namespace_project_network_path(@project.namespace, @project, @id, @options)
          when "graphs"
            namespace_project_graph_path(@project.namespace, @project, @id)
          when "find_file"
            namespace_project_find_file_path(@project.namespace, @project, @id)
          when "graphs_commits"
            commits_namespace_project_graph_path(@project.namespace, @project, @id)
          when "badges"
            namespace_project_pipelines_settings_path(@project.namespace, @project, ref: @id)
          else
            namespace_project_commits_path(@project.namespace, @project, @id)
          end

        redirect_to new_path
      end
    end
  end

  def logs_tree
    @offset = if params[:offset].present?
                params[:offset].to_i
              else
                0
              end

    @limit = 25

    @path = params[:path]

    contents = []
    contents.push(*tree.trees)
    contents.push(*tree.blobs)
    contents.push(*tree.submodules)

    @logs = contents[@offset, @limit].to_a.map do |content|
      file = @path ? File.join(@path, content.name) : content.name
      last_commit = @repo.last_commit_for_path(@commit.id, file)
      {
        file_name: content.name,
        commit: last_commit
      }
    end

    offset = (@offset + @limit)
    if contents.size > offset
      @more_log_url = logs_file_namespace_project_ref_path(@project.namespace, @project, @ref, @path || '', offset: offset)
    end

    respond_to do |format|
      format.html { render_404 }
      format.js
    end
  end

  private

  def validate_ref_id
    return not_found! if params[:id].present? && params[:id] !~ Gitlab::Regex.git_reference_regex
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Interface IPropertyStore
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Interface IPropertyStore
   ">
    <meta name="generator" content="docfx 2.16.2.2">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Interface IPropertyStore

The interface a property store (for dead properties) must implement

Namespace:FubarDev.WebDavServer.Props.Store

Assembly:FubarDev.WebDavServer.dll

Syntax

public interface IPropertyStore

Properties

                |
                Improve this Doc

                View Source

Cost

Gets the cost to query the properties of a property store

Declaration

int Cost { get; }

Property Value

                    Type
                    Description

                    Int32

Methods

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_Create_FubarDev_WebDavServer_FileSystem_IEntry_System_Xml_Linq_XName_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.Create(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Xml.Linq.XName)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

Create(IEntry, XName)

Creates a dead property by its name for a given entry

Declaration

[NotNull]
IDeadProperty Create([NotNull] IEntry entry, [NotNull] XName name)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to create the dead property with the given name for

                    XName
                    name

The name of the dead property to create for the given entry for

Returns

                    Type
                    Description

                    IDeadProperty

The created dead property with the given name for the given entry

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_GetAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.GetAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

GetAsync(IEntry, CancellationToken)

Gets all dead properties for a given entry

Declaration

[NotNull]
[ItemNotNull]
Task<IReadOnlyCollection<XElement>> GetAsync([NotNull] IEntry entry, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to get all the dead properties for

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<IReadOnlyCollection<XElement>>

The collection of all dead properties

Remarks

A GetETagProperty will not be returned by this function.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_GetAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Xml_Linq_XName_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.GetAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Xml.Linq.XName%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

GetAsync(IEntry, XName, CancellationToken)

Gets a dead property with the given name for the given entry

Declaration

[NotNull]
[ItemCanBeNull]
Task<XElement> GetAsync([NotNull] IEntry entry, [NotNull] XName name, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to get the property with the given name for

                    XName
                    name

The name of the parameter to get for a given entry

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<XElement>

The XElement for the given dead property

Remarks

A GetETagProperty will not be returned by this function.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_GetETagAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.GetETagAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

GetETagAsync(IEntry, CancellationToken)

Gets the entity tag for a given entry

Declaration

[NotNull]
Task<EntityTag> GetETagAsync([NotNull] IEntry entry, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to get the entity tag for

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<EntityTag>

The loaded entity tag

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_LoadAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.LoadAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

LoadAsync(IEntry, CancellationToken)

Loads all dead properties for a given entry into IDeadProperty implementations

Declaration

[NotNull]
[ItemNotNull]
Task<IReadOnlyCollection<IDeadProperty>> LoadAsync([NotNull] IEntry entry, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to load the dead properties for

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<IReadOnlyCollection<IDeadProperty>>

The collection of the loaded dead properties

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_LoadAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Xml_Linq_XName_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.LoadAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Xml.Linq.XName%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

LoadAsync(IEntry, XName, CancellationToken)

Loads the dead property with the given name into a IDeadProperty implementation

Declaration

[NotNull]
[ItemNotNull]
Task<IDeadProperty> LoadAsync([NotNull] IEntry entry, [NotNull] XName name, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to load the dead property for

                    XName
                    name

The name of the dead property

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<IDeadProperty>

The implementation of the dead property

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_RemoveAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Collections_Generic_IEnumerable_System_Xml_Linq_XName__System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.RemoveAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Collections.Generic.IEnumerable%7BSystem.Xml.Linq.XName%7D%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

RemoveAsync(IEntry, IEnumerable<XName>, CancellationToken)

Remove multiple dead properties by its name at once from the given entry

Declaration

[NotNull]
[ItemNotNull]
Task<IReadOnlyCollection<bool>> RemoveAsync([NotNull] IEntry entry, [NotNull] IEnumerable<XName> names, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to remove the given property names from

                    IEnumerable<XName>
                    names

The names of the dead properties to remove from the given entry

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<IReadOnlyCollection<Boolean>>

A collection of booleans where a true value indicates that there was a dead property for a given
name that could be removed from the entry. A GetETagProperty cannot be removed
by this function.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_RemoveAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.RemoveAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

RemoveAsync(IEntry, CancellationToken)

Remove all dead propertied (including a probably exting GetETagProperty) from a given entry

Declaration

[NotNull]
Task RemoveAsync([NotNull] IEntry entry, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to remove all the dead properties from

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task

The async task

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_RemoveAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Xml_Linq_XName_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.RemoveAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Xml.Linq.XName%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

RemoveAsync(IEntry, XName, CancellationToken)

Removes a dead property with a given name from the given entry

Declaration

[NotNull]
Task<bool> RemoveAsync([NotNull] IEntry entry, [NotNull] XName name, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to remove the dead property with the given name from

                    XName
                    name

The name of the parameter to remove from the entry

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<Boolean>

true when there was a dead property with the given name that could be removed

Remarks

A GetETagProperty cannot be removed by this function.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_SetAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Collections_Generic_IEnumerable_System_Xml_Linq_XElement__System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.SetAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Collections.Generic.IEnumerable%7BSystem.Xml.Linq.XElement%7D%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

SetAsync(IEntry, IEnumerable<XElement>, CancellationToken)

Sets all given dead properties for the given entry

Declaration

[NotNull]
Task SetAsync([NotNull] IEntry entry, [NotNull, ItemNotNull] IEnumerable<XElement> properties, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to set all the dead properties for

                    IEnumerable<XElement>
                    properties

The properties to set for the given entry

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task

The async task

Remarks

A GetETagProperty cannot be updated using this method

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_SetAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Xml_Linq_XElement_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.SetAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Xml.Linq.XElement%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

SetAsync(IEntry, XElement, CancellationToken)

Sets a dead property for the given entry to the given element

Declaration

[NotNull]
Task SetAsync([NotNull] IEntry entry, [NotNull] XElement element, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to set the property element for

                    XElement
                    element

The element to set the entry for

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task

The async task

Remarks

A GetETagProperty cannot be updated by this function.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Props_Store_IPropertyStore_UpdateETagAsync_FubarDev_WebDavServer_FileSystem_IEntry_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Props.Store.IPropertyStore.UpdateETagAsync(FubarDev.WebDavServer.FileSystem.IEntry%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

UpdateETagAsync(IEntry, CancellationToken)

Updates an entity tag for a given entry

Declaration

[NotNull]
Task<EntityTag> UpdateETagAsync([NotNull] IEntry entry, CancellationToken cancellationToken)

Parameters

                    Type
                    Name
                    Description

                    IEntry
                    entry

The entry to get the entity tag for

                    CancellationToken
                    cancellationToken

The cancellation token

Returns

                    Type
                    Description

                    Task<EntityTag>

The updated entity tag

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2016-2017 Fubar Development Junker
Generated by DocFX


text:
/**
 * Jakarta Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.constraints.builtinconstraints;

import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.assertNoViolations;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.assertThat;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.violationOf;

import java.util.Set;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;

import org.hibernate.beanvalidation.tck.beanvalidation.Sections;
import org.hibernate.beanvalidation.tck.tests.AbstractTCKTest;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.test.audit.annotations.SpecAssertion;
import org.jboss.test.audit.annotations.SpecVersion;
import org.testng.annotations.Test;

/**
 * Tests for {@link NotBlank} built-in constraint.
 *
 * @author Guillaume Smet
 */
@SpecVersion(spec = "beanvalidation", version = "3.0.0")
public class NotBlankConstraintTest extends AbstractTCKTest {

	@Deployment
	public static WebArchive createTestArchive() {
		return webArchiveBuilder()
				.withTestClass( NotBlankConstraintTest.class )
				.build();
	}

	@Test
	@SpecAssertion(section = Sections.BUILTINCONSTRAINTS, id = "a")
	@SpecAssertion(section = Sections.BUILTINCONSTRAINTS_NOTBLANK, id = "a")
	public void testNotBlankConstraint() {
		Validator validator = getValidator();
		NotBlankDummyEntity foo = new NotBlankDummyEntity();

		Set<ConstraintViolation<NotBlankDummyEntity>> constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = "";
		constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = " ";
		constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = "\t";
		constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = "\n";
		constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = "john doe";
		constraintViolations = validator.validate( foo );
		assertNoViolations( constraintViolations );
	}

	@Test
	@SpecAssertion(section = Sections.BUILTINCONSTRAINTS, id = "a")
	@SpecAssertion(section = Sections.BUILTINCONSTRAINTS_NOTBLANK, id = "a")
	public void testNotBlankConstraintOnStringBuilder() {
		// @NotBlank has to support CharSequence so let's also try a StringBuilder
		Validator validator = getValidator();
		NotBlankStringBuilderDummyEntity foo = new NotBlankStringBuilderDummyEntity();

		Set<ConstraintViolation<NotBlankStringBuilderDummyEntity>> constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = new StringBuilder( " " );
		constraintViolations = validator.validate( foo );
		assertThat( constraintViolations ).containsOnlyViolations(
				violationOf( NotBlank.class ).withProperty( "name" )
		);

		foo.name = new StringBuilder( "john doe" );
		constraintViolations = validator.validate( foo );
		assertNoViolations( constraintViolations );
	}

	private class NotBlankDummyEntity {

		@NotBlank
		private String name;
	}

	private class NotBlankStringBuilderDummyEntity {

		@NotBlank
		private StringBuilder name;
	}
}


text:
package com.mattunderscore.trees.examples;

import com.mattunderscore.trees.balanced.BalancingTree;
import com.mattunderscore.trees.construction.TypeKey;
import com.mattunderscore.trees.organised.OrganisedTreeBuilder;
import com.mattunderscore.trees.tree.Node;
import com.mattunderscore.trees.tree.Tree;

/**
 * @author Matt Champion on 30/08/14.
 */
public final class BalancedTreeExamples {
    public void balancedTreeExample(OrganisedTreeBuilder<String, Node<String>, Tree<String, Node<String>>> builder) {
        final BalancingTree<String, Node<String>> tree = builder
            .addElement("a")
            .addElement("b")
            .addElement("c")
            .build(new TypeKey<BalancingTree<String, Node<String>>>(){});
        tree
            .addElement("c")
            .addElement("d");
    }
}


text:
using SE.DSP.Foundation.Infrastructure.Expr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SE.DSP.Foundation.Infrastructure.BE.Structure
{

    /// <summary>
    /// FormulaVariable
    /// </summary>
    public class FormulaVariable
    {
        /// <summary>
        /// VariableType
        /// </summary>
        public VariableType VariableType { get; set; }
        /// <summary>
        /// HierarchyCode
        /// </summary>
        public String HierarchyCode { get; set; }
        /// <summary>
        /// VariableCode
        /// </summary>
        public String VariableCode { get; set; }
        /// <summary>
        /// CustomerId
        /// </summary>
        public long CustomerId { get; set; }
    }
}


text:
package android.support.v4.media;

public class TransportStateListener {
    public void onPlayingChanged(TransportController controller) {
    }

    public void onTransportControlsChanged(TransportController controller) {
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lycoperdon muscorum var. muscorum

### Remarks
null


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

namespace NSynth.Containers.ISOBaseMediaFormat
{
    public class HandlerBox : FullBox
    {

        public HandlerBox()
            : base(BoxTypes.Handler, 0, 0)
        {

        }

        public uint PreDefined { get; set; }

        public uint HandlerType { get; set; }

        // Reserve 12 bytes here.

        public string Name { get; set; }
    }
}


text:
namespace g{
namespace Fuse{
namespace Scripting{
namespace Duktape{

// internal static extern class duktape :571
// {
uClassType* duktape_typeof();
void duktape__create_heap_default_fn(void** __retval);
void duktape__del_prop_string_fn(void** ctx, int* obj_index, uString* key, bool* __retval);
void duktape__destroy_heap_fn(void** ctx);
void duktape__enum__fn(void** ctx, int* index, int* flags);
void duktape__error_fn(void** ctx, uString* message);
void duktape__get_boolean_fn(void** ctx, int* index, bool* __retval);
void duktape__get_heapptr_fn(void** ctx, int* index, void** __retval);
void duktape__get_int_fn(void** ctx, int* index, int* __retval);
void duktape__get_length_fn(void** ctx, int* index, int64_t* __retval);
void duktape__get_number_fn(void** ctx, int* index, double* __retval);
void duktape__get_prop_index_fn(void** ctx, int* index, int* arr_index, bool* __retval);
void duktape__get_prop_string_fn(void** ctx, int* obj_index, uString* key, bool* __retval);
void duktape__get_string_fn(void** ctx, int* index, uString** __retval);
void duktape__get_top_fn(void** ctx, int* __retval);
void duktape__has_prop_string_fn(void** ctx, int* index, uString* key, bool* __retval);
void duktape__is_array_fn(void** ctx, int* index, bool* __retval);
void duktape__is_boolean_fn(void** ctx, int* index, bool* __retval);
void duktape__is_function_fn(void** ctx, int* index, bool* __retval);
void duktape__is_null_or_undefined_fn(void** ctx, int* index, bool* __retval);
void duktape__is_number_fn(void** ctx, int* index, bool* __retval);
void duktape__is_object_fn(void** ctx, int* index, bool* __retval);
void duktape__is_string_fn(void** ctx, int* index, bool* __retval);
void duktape__new__fn(void** ctx, int* nargs);
void duktape__next_fn(void** ctx, int* index, bool* getValue, bool* __retval);
void duktape__pcall_fn(void** ctx, int* nargs, int* __retval);
void duktape__pcall_method_fn(void** ctx, int* nargs, int* __retval);
void duktape__pcompile_fn(void** ctx, uint32_t* flags, int* __retval);
void duktape__pcompile_string_fn(void** ctx, uint32_t* flags, uString* src, int* __retval);
void duktape__peval_string_fn(void** ctx, uString* code, int* __retval);
void duktape__pop_fn(void** ctx);
void duktape__pop_2_fn(void** ctx);
void duktape__push_array_fn(void** ctx, int* __retval);
void duktape__push_boolean_fn(void** ctx, bool* value);
void duktape__push_callback_proxy_fn(void** ctx, int* argc);
void duktape__push_delegate_fn(void** ctx, uDelegate* del);
void duktape__push_global_object_fn(void** ctx);
void duktape__push_global_stash_fn(void** ctx);
void duktape__push_heapptr_fn(void** ctx, void** ptr, int* __retval);
void duktape__push_int_fn(void** ctx, int* val);
void duktape__push_null_fn(void** ctx);
void duktape__push_number_fn(void** ctx, double* val);
void duktape__push_object_fn(void** ctx, int* __retval);
void duktape__push_string_fn(void** ctx, uString* str);
void duktape__put_prop_index_fn(void** ctx, int* index, int* arr_index, bool* __retval);
void duktape__put_prop_string_fn(void** ctx, int* obj_index, uString* key, bool* __retval);
void duktape__safe_to_string_fn(void** ctx, int* index, uString** __retval);

struct duktape : uObject
{
    static void* create_heap_default();
    static bool del_prop_string(void* ctx, int obj_index, uString* key);
    static void destroy_heap(void* ctx);
    static void enum_(void* ctx, int index, int flags);
    static void error(void* ctx, uString* message);
    static bool get_boolean(void* ctx, int index);
    static void* get_heapptr(void* ctx, int index);
    static int get_int(void* ctx, int index);
    static int64_t get_length(void* ctx, int index);
    static double get_number(void* ctx, int index);
    static bool get_prop_index(void* ctx, int index, int arr_index);
    static bool get_prop_string(void* ctx, int obj_index, uString* key);
    static uString* get_string(void* ctx, int index);
    static int get_top(void* ctx);
    static bool has_prop_string(void* ctx, int index, uString* key);
    static bool is_array(void* ctx, int index);
    static bool is_boolean(void* ctx, int index);
    static bool is_function(void* ctx, int index);
    static bool is_null_or_undefined(void* ctx, int index);
    static bool is_number(void* ctx, int index);
    static bool is_object(void* ctx, int index);
    static bool is_string(void* ctx, int index);
    static void new_(void* ctx, int nargs);
    static bool next(void* ctx, int index, bool getValue);
    static int pcall(void* ctx, int nargs);
    static int pcall_method(void* ctx, int nargs);
    static int pcompile(void* ctx, uint32_t flags);
    static int pcompile_string(void* ctx, uint32_t flags, uString* src);
    static int peval_string(void* ctx, uString* code);
    static void pop(void* ctx);
    static void pop_2(void* ctx);
    static int push_array(void* ctx);
    static void push_boolean(void* ctx, bool value);
    static void push_callback_proxy(void* ctx, int argc);
    static void push_delegate(void* ctx, uDelegate* del);
    static void push_global_object(void* ctx);
    static void push_global_stash(void* ctx);
    static int push_heapptr(void* ctx, void* ptr);
    static void push_int(void* ctx, int val);
    static void push_null(void* ctx);
    static void push_number(void* ctx, double val);
    static int push_object(void* ctx);
    static void push_string(void* ctx, uString* str);
    static bool put_prop_index(void* ctx, int index, int arr_index);
    static bool put_prop_string(void* ctx, int obj_index, uString* key);
    static uString* safe_to_string(void* ctx, int index);
};
// }

}}}} // ::g::Fuse::Scripting::Duktape


text:
namespace IM {

class Contact
{
	public:
		Contact();
		Contact( const entry_ref & );
		Contact( const BEntry & );
//		Contact( const node_ref & );
		Contact( const Contact & );
		~Contact();

		//
		void SetTo( const entry_ref &);
		void SetTo( const BEntry &);
//		void SetTo( const node_ref &);
		void SetTo( const Contact &);

		// returns B_OK if the Contact is connected to a valid People-file
		status_t InitCheck();

		bool Exists();

		// call this function to reload information from attributes
		void Update();

		// Connection management
		status_t AddConnection( const char * proto_id );
		status_t RemoveConnection( const char * proto_id );
		int CountConnections();
		status_t ConnectionAt( int index, char * );
		status_t FindConnection( const char * protocol, char * );

		// Various data
		status_t	GetStatus(char *bug, int size);
		status_t	SetStatus(const char *);
		status_t	GetName(char *buf, int size);
		status_t	SetName(const char *);
		status_t	GetNickname(char *buf, int size);
		status_t	SetNickname(const char *);
		status_t	GetEmail(char *buf, int size);
		status_t	SetEmail(const char *);
		status_t	GetURL(char* buf, int size);
		status_t	SetURL(const char*);
		status_t	GetBirthday(char* buf, int size);
		status_t	SetBirthday(const char*);

		int32		CountGroups(void);
		const char	*GroupAt(int32 index);

		status_t	SetBuddyIcon(const char *protocol, BBitmap *icon);
		BBitmap		*GetBuddyIcon(const char *protocol, int16 size = 48);

		// comparison, both with Contacts and entry_refs and node_refs
		// representing Contacts
		bool operator == ( const entry_ref & ) const;
		bool operator == ( const BEntry & ) const;
		bool operator == ( const Contact & ) const;
		bool operator < ( const Contact & ) const;

		entry_ref	EntryRef(void) const;

		// for easy addition to BMessages
		operator const entry_ref * () const;
//		const node_ref operator Contact();

	private:
		status_t	LoadConnections();
		status_t	SaveConnections();
		status_t	ReadAttribute(const char * attr, char * buffer, int bufsize);
		status_t	ReadAttribute(const char *attr, char **buffer, int32 *size);
		status_t	WriteAttribute(const char *name, const char *buffer, int32 size);
		status_t	LoadGroups(void);

		void		Clear();

		entry_ref	fEntry;
		BList		fConnections;
		BList		fGroups;

};

};

#endif


text:
@interface PodsDummy_Pods_JWPopView : NSObject
@end
@implementation PodsDummy_Pods_JWPopView
@end


text:
package com.base.spring.controller.ajax;

import com.base.spring.domain.TreeEntity;
import com.base.spring.domain.TreeType;
import com.base.spring.repository.RoleRepository;
import com.base.spring.repository.TreeRepository;
import com.base.spring.service.TreeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 树操作 : add, copy ,delete and ajax request
 */
@Slf4j
@Controller
@RequestMapping("/ajax/tree/ztree")
public class ZTreeAjaxController {

    //private static final log log = LoggerFactory.getLogger(ZTreeAjaxController.class);

    @Autowired
    TreeRepository treeNodeRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    TreeService treeNodeService;

    /**
     * 异步加载,获取数据。
     *

     * 点击关闭的父节点,传过来该父节点的 id,会激发本函数
     *

     * 维护界面,不涉及 getCheckedNodes 操作,展开指定层级即可
     *
     * @param id       首次加载页面,没有点击某个关闭的父节点,此时 id=null
     * @param menuType 第一次加载树,决定了是哪种类型
     * @return
     */
    @RequestMapping(value = "/asyncByTreeType.html", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String asyncByTreeType(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "treeType", required = true) TreeType menuType) {

        log.info("id={} , menuType={}", id, menuType);

        List<TreeType> list = new ArrayList(2);
        if (menuType.equals(TreeType.Menu))      //菜单时,同时显示 PageResource
            list.addAll(Arrays.asList(TreeType.Menu, TreeType.PageResource));
        else list.add(menuType);

        return treeNodeService.asyncTree(id, list);

    }

    /**
     * @param id
     * @param menuType
     * @return
     */
    @RequestMapping(value = "/asyncByTreeTypeAndRole.html", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String asyncByTreeTypeAndRole(@RequestParam(value = "id", required = false) Long id,
                                         @RequestParam(value = "treeType", required = true) TreeType menuType,
                                         @RequestParam(value = "role_id", required = true) String roleId) {

        log.info("id={} , menuType={}, roleId={}", id, menuType, roleId);

        List<TreeType> list = new ArrayList(2);
        if (menuType.equals(TreeType.Menu))      //菜单时,同时显示 PageResource
            list.addAll(Arrays.asList(TreeType.Menu, TreeType.PageResource));
        else list.add(menuType);

        if (roleId.isEmpty())    // 还没有选择 role,返回初始的树
            return treeNodeService.asyncTree(id, list);
        else
            return treeNodeService.asyncRoleTree(id, list, roleRepository.getOne(Long.valueOf(roleId))); //和 role 关联的树节点会自动选中
    }

    /**
     * 创建菜单
     *
     * @param name
     * @param level
     * @param index
     * @param isParent
     * @param pId      被选择的子节点,在该节点下创建子节点。
     * @param treeType 菜单类型
     */
    @RequestMapping(value = "/add.html", method = RequestMethod.POST)
    @ResponseBody
    public String add(@RequestParam(value = "name", required = true) String name,
                      @RequestParam(value = "level", required = true) Integer level,
                      @RequestParam(value = "index", required = true) Integer index,
                      @RequestParam(value = "pId", required = true) Long pId,
                      @RequestParam(value = "isParent", required = true) boolean isParent,
                      @RequestParam(value = "treeType", required = false) TreeType treeType) {

        log.info("add new treeNode : name={},level={},index={},pId={},isParent={} , menuType={}", name, level, index, pId, isParent, treeType);
        treeNodeService.add(name, level, index, isParent, pId, treeType);
        return "add succeed.";
    }

    /**
     * edit
     *
     * @return
     */
    @RequestMapping(value = "/edit.html", method = RequestMethod.POST)
    @ResponseBody
    public String edit(@RequestParam(value = "id", required = true) Long id, @RequestParam(value = "name", required = true) String name) {
        log.info("edit treeNode : id={} , name={}", id, name);
        //treeNodeService.clearChildren(id);
        TreeEntity treeNode = treeNodeRepository.getOne(id);
        treeNode.setName(name);
        treeNodeRepository.save(treeNode);
        return "edit succeed.";
    }

    /**
     * del
     *
     * @return
     */
    @RequestMapping(value = "/del.html", method = RequestMethod.POST)
    @ResponseBody
    public String remove(@RequestParam(value = "id", required = true) Long id) {
        log.info("del treeNode : id={} ", id);
        TreeEntity tree = treeNodeRepository.getOne(id);
        if (tree.isRoot())
            return "root node can not be delete";

        treeNodeRepository.deleteById(id);

        return "del succeed.";
    }

    /**
     * clear
     *
     * @return
     */
    @RequestMapping(value = "/clear.html", method = RequestMethod.POST)
    @ResponseBody
    public String clearChildren(@RequestParam(value = "id", required = true) Long id) {
        log.info("clear treeNode : id={} ", id);
        treeNodeService.clearChildren(id);
        return "clear succeed.";
    }

    /**
     * paste
     * 无论是那种类型的粘帖,ztree 默认添加到子节点的尾部,后台也默认添加到尾部。
     *
     * @return
     */
    @RequestMapping(value = {"/paste.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String paste(@RequestParam(value = "id", required = true) Long id,
                        // @RequestParam(value = "index", required = true) Integer index,
                        @RequestParam(value = "pId", required = true) Long pId,
                        @RequestParam(value = "curType", required = true) String curType) {

        log.info("paste treeNode : id={},pId={},curType={}", id, pId, curType);

        treeNodeService.paste(id, pId, curType);

        return "paste succeed.";
    }

    /**
     * move
     * 移动节点到指定位置
     *
     * @param id    被移动 节点
     * @param index 移动到位置
     * @param pId   被移动节点的父节点
     * @return
     */
    @RequestMapping(value = {"/move.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String move(@RequestParam(value = "id", required = true) Long id,
                       @RequestParam(value = "index", required = true) Integer index,
                       @RequestParam(value = "pId", required = true) Long pId) {

        log.info("move treeNode : id={},pId={},index={}", id, pId, index);
        treeNodeService.move(id, pId, index);
        return "move succeed.";
    }

    /**
     * 节点 CSS 修改
     *
     * @return
     */
    @RequestMapping(value = {"/node/edit/css.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String editCss(@RequestParam(value = "id", required = true) Long id,
                          @RequestParam(value = "css", required = true) String css) {

        log.info("move treeNode : id={},css={}", id, css.trim());
        treeNodeService.editCss(id, css.trim());
        return "css edit succeed.";
    }

    /**
     * 节点 URL 修改
     *
     * @return
     */
    @RequestMapping(value = {"/node/edit/url.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String editUrl(@RequestParam(value = "id", required = true) Long id,
                          @RequestParam(value = "url", required = true) String url) {

        log.info("move treeNode : id={},url={}", id, url.trim());
        treeNodeService.editUrl(id, url.trim());
        return "css edit succeed.";
    }

    /**
     * 节点关联标准,可以一次关联多个
     *
     * @return
     */
    @RequestMapping(value = {"/node/link/standard.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String linkStandard(@RequestParam(value = "id", required = true) Long id,
                               @RequestParam(value = "standard", required = true) String standard) {

        log.info("move treeNode : id={},standard={}", id, standard.trim());
        return "css edit succeed.";
    }

}


text:
nimbusec API client in Go

Full documentation on https://kb.nimbusec.com/API/API


text:
package alien4cloud.paas.cloudify2.events;

import java.io.IOException;

import org.openspaces.admin.Admin;

public class TestGigaSpacesPUDeployer {

    public static void main(String[] args) throws InterruptedException, IOException {
        Admin admin = null;
        try {
            admin = GigaSpacesPUDeployer.createAdmin("129.185.67.65");
            GigaSpacesPUDeployer.undeploy(admin, "event");
        } finally {
            if (admin != null)
                admin.close();
        }
    }
}


text:
var DB = {
    NAME: "dbName",
    OBJECT_STORE_1: "objectStore1",
    OBJECT_STORE_2: "objectStore2",
    OBJECT_STORE_3: "objectStore3",
    OBJECT_STORE_4: "objectStore4",
    OBJECT_STORE_5: "objectStore5",
    INDEX1_ON_OBJECT_STORE_1: "Index1_ObjectStore1",
    INDEX1_ON_OBJECT_STORE_2: "Index1_ObjectStore2"
};

var sample = (function(){
    var generatedNumbers = {};
    return {
        obj: function(){
            return {
                "String": "Sample " + new Date(),
                "Int": this.integer(),
                "Float": Math.random(),
                "Boolean": true
            };
        },
        integer: function(arg){
            // Ensuring a unique integer everytime, for the sake of indexe get
            var r;
            do {
                r = parseInt(Math.random() * (arg || 100), 10);
            }
            while (generatedNumbers[r]);
            generatedNumbers[r] = true;
            return r;
        }
    };
}());


text:
import { EventType } from 'engine/enums/event-type';
import _events from 'engine/events';

import { chatnpc, chatplayer } from 'shared/dialog';

_events.bindEventListener(EventType.OPNPC1, 8072, async (ctx) => {
	await chatplayer(ctx.player, "Hello there. Could I ask you about th-");
	await chatnpc(ctx.player, ctx.npc, "Hmph! Don't you know anything? It not safe to talk right<br> now.");
});