text:
@interface PodsDummy_NGAParallaxMotion : NSObject
@end
@implementation PodsDummy_NGAParallaxMotion
@end

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.jetel.util.primitive Class Hierarchy</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.jetel.util.primitive

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractList<E> (implements java.util.List<E>)

java.util.ArrayList<E> (implements java.lang.Cloneable, java.util.List<E>, java.util.RandomAccess, java.io.Serializable)

org.jetel.util.primitive.IdentityArrayList<E>

org.jetel.util.primitive.BitArray (implements java.io.Serializable)

java.util.Dictionary<K,V>

java.util.Hashtable<K,V> (implements java.lang.Cloneable, java.util.Map<K,V>, java.io.Serializable)

java.util.Properties

org.jetel.util.primitive.TypedProperties

org.jetel.util.primitive.DuplicateKeyMap (implements java.util.Map<K,V>)

org.jetel.util.primitive.MultiValueMap<K,V> (implements java.util.Map<K,V>)

org.jetel.util.primitive.Queue

org.jetel.util.primitive.BlockingQueue

org.jetel.util.primitive.SimpleCache<K,V>

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
package database

import (
	"context"
	"fmt"

	"github.com/sacloud/libsacloud/v2/helper/service"
	"github.com/sacloud/libsacloud/v2/helper/wait"
	"github.com/sacloud/libsacloud/v2/sacloud"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
)

func (s *Service) Delete(req *DeleteRequest) error {
	return s.DeleteWithContext(context.Background(), req)
}

func (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {
	if err := req.Validate(); err != nil {
		return err
	}

	client := sacloud.NewDatabaseOp(s.caller)
	target, err := client.Read(ctx, req.Zone, req.ID)
	if err != nil {
		return service.HandleNotFoundError(err, !req.FailIfNotFound)
	}

	if !req.Force && target.InstanceStatus.IsUp() {
		return fmt.Errorf("target %s:%q has not yet shut down", req.Zone, req.ID)
	}

	if target.InstanceStatus.IsUp() {
		if err := client.Shutdown(ctx, req.Zone, req.ID, &sacloud.ShutdownOption{Force: true}); err != nil {
			return err
		}
	}

	// 元の状態がUnknownでなければwait
	if target.InstanceStatus != types.ServerInstanceStatuses.Unknown {
		if _, err := wait.UntilDatabaseIsDown(ctx, client, req.Zone, req.ID); err != nil {
			return err
		}
	}

	if err := client.Delete(ctx, req.Zone, req.ID); err != nil {
		return service.HandleNotFoundError(err, !req.FailIfNotFound)
	}
	return nil
}


text:
#pragma once
#include "Common/GameData/npc_definitions.h"
#include <QHash>

struct NPCStorage
{
    AllNpcs_Data m_all_npcs;
    QHash<QString,Parse_NPC *> m_name_to_npc_def;
    void prepare_dictionaries();
    int npc_idx(const Parse_NPC *npc) const;
    int npc_idx(const QString &name);
    const Parse_NPC *npc_by_name(const QStringRef &name) const;
};


text:
package org.labkey.wnprc_ehr.dataentry.forms.HousingRequest.FormSections;

import org.labkey.api.ehr.dataentry.SimpleFormSection;

public class HousingSection extends SimpleFormSection {
    public HousingSection() {
        super("study", "Housing", "Housing", "ehr-gridpanel");

        this.addConfigSource("Request");
    }
}


text:
<?php

namespace Symfony\Runtime\Symfony\Component\HttpKernel;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
 * @internal
 */
class HttpKernelInterfaceRuntime extends SymfonyRuntime
{
}


text:
package org.aesh.readline.util;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * @author Ståle W. Pedersen
 */
public class ShortHelperTest {

    @Test
    public void testShortConverter() {
        testString("foo");
        testString("as')(#/&!\"=#)dfae09fajfjdf aeufa3jas");
    }

    private void testString(String input) {
        short[] shorts = ShortHelper.toShortPoints(input);
        int[] ints = Parser.toCodePoints(input);

        assertTrue(shorts.length == ints.length);

        for(int i=0; i < shorts.length; i++) {
            assertTrue(shorts[i] == ints[i]);
        }
    }

    @Test
    public void testFromShortToString() {
        fromShortToString("foo");
        fromShortToString("as')(#/&!\"=#)dfae09fajfjdf aeufa3jas");
    }

    private void fromShortToString(String input) {
        short[] shorts = ShortHelper.toShortPoints(input);
        String out = ShortHelper.fromShortPoints(shorts);

        assertEquals(input, out);
    }
}


text:
<!DOCTYPE html>

    <link rel="shortcut icon" href="https://google.github.io/starthinker/static/favicon.ico" type="image/x-icon">
    <link rel="icon" href="https://google.github.io/starthinker/static/favicon.ico" type="image/x-icon">

    <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined" rel="stylesheet">

    <link rel="stylesheet" href="https://google.github.io/starthinker/static/css/materialize-1.0.0.min.css">

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

          StarThinker

        menu

Solutions

Help

Solutions

Help

  All

settings_input_component Google API To BigQuery

Execute any Google API function and store results to BigQuery.

      lock_openGet Access

        listGit Hub

        sourcePython

        menu_bookColab

        airAirflow

        thumb_upTest

Impact Level

                Spend Optimization

                Spend Growth

                Time Savings

                Account Health

                Csat Improvement

Value Proposition

                Call any Google API ednpoint.

                Move results into BigQuery.

Instructions

                Enter an api name and version.

                Specify the function using dot notation.

                Specify the arguments using json.

                Iterate is optional, use if API returns a list of items that are not unpacking correctly.

                The API Key may be required for some calls.

                The Developer Token may be required for some calls.

                Give BigQuery dataset and table where response will be written.

                All API calls are based on discovery document, for example the Campaign Manager API.

Details

              Open Source
              YES

              Age
              June 10, 2018 (3 years, 5 months)

              Authors
              kenjora@google.com

                  Shedule Days
                  Configured by user.

                  Shedule Hours
                  Configured by user.

[
    {
        "google_api": {
            "auth": {
                "field": {
                    "name": "auth_read",
                    "kind": "authentication",
                    "order": 1,
                    "default": "user",
                    "description": "Credentials used for reading data."
                }
            },
            "api": {
                "field": {
                    "name": "api",
                    "kind": "string",
                    "order": 1,
                    "default": "displayvideo",
                    "description": "See developer guide."
                }
            },
            "version": {
                "field": {
                    "name": "version",
                    "kind": "string",
                    "order": 2,
                    "default": "v1",
                    "description": "Must be supported version."
                }
            },
            "function": {
                "field": {
                    "name": "function",
                    "kind": "string",
                    "order": 3,
                    "default": "advertisers.list",
                    "description": "Full function dot notation path."
                }
            },
            "kwargs": {
                "field": {
                    "name": "kwargs",
                    "kind": "json",
                    "order": 4,
                    "default": {
                        "partnerId": 234340
                    },
                    "description": "Dictionray object of name value pairs."
                }
            },
            "kwargs_remote": {
                "field": {
                    "name": "kwargs_remote",
                    "kind": "json",
                    "order": 5,
                    "default": {},
                    "description": "Fetch arguments from remote source."
                }
            },
            "key": {
                "field": {
                    "name": "api_key",
                    "kind": "string",
                    "order": 6,
                    "default": "",
                    "description": "Associated with a Google Cloud Project."
                }
            },
            "headers": {
                "developer-token": {
                    "field": {
                        "name": "developer_token",
                        "kind": "string",
                        "order": 7,
                        "default": "",
                        "description": "Associated with your organization."
                    }
                },
                "login-customer-id": {
                    "field": {
                        "name": "login_customer_id",
                        "kind": "string",
                        "order": 8,
                        "default": "",
                        "description": "Associated with your Adwords account."
                    }
                }
            },
            "results": {
                "bigquery": {
                    "dataset": {
                        "field": {
                            "name": "dataset",
                            "kind": "string",
                            "order": 9,
                            "default": "",
                            "description": "Existing dataset in BigQuery."
                        }
                    },
                    "table": {
                        "field": {
                            "name": "table",
                            "kind": "string",
                            "order": 10,
                            "default": "",
                            "description": "Table to write API call results to."
                        }
                    }
                }
            }
        }
    }
]

Run This Workflow In Minutes On Google Cloud

Everything from a quick Google Cloud UI to reference developer code for your team in one GitHub repository.

      Deployment Stepslaunch

      Developer Guidebuild

      UI How Tolaptop

      © 2019 Google LLC


text:
XSPrototype
===========

Xamarin Studio F# Prototype - WP8, Android and iOS apps running off an F# Core


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

<title>TiledMapRenderer (libgdx API)</title>
<meta name="date" content="2013-05-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.maps.tiled

Interface TiledMapRenderer

All Superinterfaces:

MapRenderer

All Known Implementing Classes:

BatchTiledMapRenderer, HexagonalTiledMapRenderer, IsometricTiledMapRenderer, OrthogonalTiledMapRenderer, OrthogonalTiledMapRenderer2

public interface TiledMapRenderer
extends MapRenderer

Method Summary

Methods

Modifier and Type
Method and Description

void
renderObject(MapObject object)

void
renderTileLayer(TiledMapTileLayer layer)

Methods inherited from interface com.badlogic.gdx.maps.MapRenderer

render, render, setView, setView

Method Detail

renderObject

void renderObject(MapObject object)

renderTileLayer

void renderTileLayer(TiledMapTileLayer layer)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
// Copyright (c) 2011 Chan Wai Shing
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package syntaxhighlighter.theme;

import java.awt.Color;
import java.awt.Font;
import syntaxhighlight.Style;
import syntaxhighlight.Theme;

/**
 * Django theme.
 * @author Chan Wai Shing <cws1989@gmail.com>
 */
public class ThemeDjango extends Theme {

  public ThemeDjango() {
    super();

    setFont(new Font("Consolas", Font.PLAIN, 12));
    setBackground(Color.decode("0x0a2b1d"));

    setHighlightedBackground(Color.decode("0x233729"));

    setGutterText(Color.decode("0x497958"));
    setGutterBorderColor(Color.decode("0x41a83e"));
    setGutterBorderWidth(3);
    setGutterTextFont(new Font("Verdana", Font.PLAIN, 11));
    setGutterTextPaddingLeft(7);
    setGutterTextPaddingRight(7);

    Style style = new Style();
    style.setBold(true);
    addStyle("bold", style);

    style = new Style();
    style.setColor(Color.decode("0xf8f8f8"));
    addStyle("plain", style);
    setPlain(style);

    style = new Style();
    style.setItalic(true);
    style.setColor(Color.decode("0x336442"));
    addStyle("comments", style);

    style = new Style();
    style.setColor(Color.decode("0x9df39f"));
    addStyle("string", style);

    style = new Style();
    style.setBold(true);
    style.setColor(Color.decode("0x96dd3b"));
    addStyle("keyword", style);

    style = new Style();
    style.setColor(Color.decode("0x91bb9e"));
    addStyle("preprocessor", style);

    style = new Style();
    style.setColor(Color.decode("0xffaa3e"));
    addStyle("variable", style);

    style = new Style();
    style.setColor(Color.decode("0xf7e741"));
    addStyle("value", style);

    style = new Style();
    style.setColor(Color.decode("0xffaa3e"));
    addStyle("functions", style);

    style = new Style();
    style.setColor(Color.decode("0xe0e8ff"));
    addStyle("constants", style);

    style = new Style();
    style.setBold(true);
    style.setColor(Color.decode("0x96dd3b"));
    addStyle("script", style);

    style = new Style();
    addStyle("scriptBackground", style);

    style = new Style();
    style.setColor(Color.decode("0xeb939a"));
    addStyle("color3", style);

    style = new Style();
    style.setColor(Color.decode("0x91bb9e"));
    addStyle("color2", style);

    style = new Style();
    style.setColor(Color.decode("0xedef7d"));
    addStyle("color3", style);
  }
}


text:
various tests with wrong param count
--SKIPIF--
<?php
$target_dbs = array('oracledb' => true, 'timesten' => false);  // test runs on these DBs
require(dirname(__FILE__).'/skipif.inc');
?>
--FILE--
<?php

require dirname(__FILE__).'/connect.inc';
require dirname(__FILE__).'/create_table.inc';

$ora_sql = "INSERT INTO
                       ".$schema.$table_name." (blob)
                      VALUES (empty_blob())
                      RETURNING
                               blob
                      INTO :v_blob ";

$statement = oci_parse($c,$ora_sql);
$blob = oci_new_descriptor($c,OCI_D_LOB,1,2,3);
$blob = oci_new_descriptor($c);
$int = 1;
oci_bind_by_name($statement,":v_blob", $blob,-1,OCI_B_BLOB,4);
oci_bind_by_name($statement,":v_blob", $blob,-1,OCI_B_BLOB,4,5);
oci_bind_by_name($statement,":v_blob", $int,-1);
oci_bind_by_name($statement,":v_blob", $int);
oci_bind_by_name($statement,":v_blob");
oci_bind_by_name($statement);
oci_execute($statement, OCI_DEFAULT);

var_dump($blob);

require dirname(__FILE__).'/drop_table.inc';

echo "Done\n";

?>
--EXPECTF--
Warning: oci_new_descriptor() expects at most 2 parameters, 5 given in %s on line %d

Warning: oci_bind_by_name() expects at most 5 parameters, 6 given in %s on line %d

Warning: oci_bind_by_name() expects at most 5 parameters, 7 given in %s on line %d

Warning: oci_bind_by_name() expects at least 3 parameters, 2 given in %s on line %d

Warning: oci_bind_by_name() expects at least 3 parameters, 1 given in %s on line %d

Warning: oci_execute(): ORA-00932: %s on line %d
object(OCI-Lob)#%d (1) {
  ["descriptor"]=>
  resource(%d) of type (oci8 descriptor)
}
Done


text:
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from utool import util_inject
from utool import util_str
print, rrr, profile = util_inject.inject2(__name__)

try:
    # Resource does not exist in win32
    import resource

    def time_in_usermode():
        stime = resource.getrusage(resource.RUSAGE_SELF).ru_stime
        return stime

    def time_in_systemmode():
        utime = resource.getrusage(resource.RUSAGE_SELF).ru_utime
        return utime

    def peak_memory():
        """Returns the resident set size (the portion of
        a process's memory that is held in RAM.)
        """
        # MAXRSS is expressed in kilobytes. Convert to bytes
        # FIXME: MAXRSS is NOT expressed in kilobytes. use resource.getpagesize to Convert to bytes
        # References: http://stackoverflow.com/questions/938733/total-memory-used-by-python-process
        #resource.getpagesize
        maxrss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024
        return maxrss

    def get_resource_limits():
        #rlimit_keys = [key for key in six.iterkeys(resource.__dict__) if key.startswith('RLIMIT_')]
        #print('\n'.join(['(\'%s\', resource.%s),' % (key.replace('RLIMIT_', ''), key) for key in rlimit_keys]))
        rlim_keytups = [
            ('MEMLOCK', resource.RLIMIT_MEMLOCK),
            ('NOFILE', resource.RLIMIT_NOFILE),
            ('CPU', resource.RLIMIT_CPU),
            ('DATA', resource.RLIMIT_DATA),
            ('OFILE', resource.RLIMIT_OFILE),
            ('STACK', resource.RLIMIT_STACK),
            ('FSIZE', resource.RLIMIT_FSIZE),
            ('CORE', resource.RLIMIT_CORE),
            ('NPROC', resource.RLIMIT_NPROC),
            ('AS', resource.RLIMIT_AS),
            ('RSS', resource.RLIMIT_RSS),
        ]
        rlim_valtups = [(lbl, resource.getrlimit(rlim_key)) for (lbl, rlim_key) in rlim_keytups]
        def rlimval_str(rlim_val):
            soft, hard = rlim_val
            softstr = util_str.byte_str2(soft) if soft != -1 else 'None'
            hardstr = util_str.byte_str2(hard) if hard != -1 else 'None'
            return '%12s, %12s' % (softstr, hardstr)
        rlim_strs = ['%8s: %s' % (lbl, rlimval_str(rlim_val)) for (lbl, rlim_val) in rlim_valtups]
        print('Resource Limits: ')
        print('%8s  %12s  %12s' % ('id', 'soft', 'hard'))
        print('\n'.join(rlim_strs))
        return rlim_strs

    #def rusage_flags():
        #0	ru_utime	time in user mode (float)
        #1	ru_stime	time in system mode (float)
        #2	ru_maxrss	maximum resident set size
        #3	ru_ixrss	shared memory size
        #4	ru_idrss	unshared memory size
        #5	ru_isrss	unshared stack size
        #6	ru_minflt	page faults not requiring I/O
        #7	ru_majflt	page faults requiring I/O
        #8	ru_nswap	number of swap outs
        #9	ru_inblock	block input operations
        #10	ru_oublock	block output operations
        #11	ru_msgsnd	messages sent
        #12	ru_msgrcv	messages received
        #13	ru_nsignals	signals received
        #14	ru_nvcsw	voluntary context switches
        #15	ru_nivcsw	involuntary context switches
except ImportError:
    def time_in_usermode():
        raise NotImplementedError('unavailable in win32')

    def time_in_systemmode():
        raise NotImplementedError('unavailable in win32')

    def peak_memory():
        """Returns the resident set size (the portion of
        a process's memory that is held in RAM.)
        """
        raise NotImplementedError('unavailable in win32')

    def get_resource_limits():
        raise NotImplementedError('unavailable in win32')

def time_str2(seconds):
    return '%.2f sec' % (seconds,)

def print_resource_usage():
    print(get_resource_usage_str())

def get_resource_usage_str():
    usage_str_list = [
        ('+______________________'),
        ('|    RESOURCE_USAGE    process.get_memory_info()[0] / float(2 ** 20) '),
        ('|  * current_memory = %s' % util_str.byte_str2(current_memory_usage())),
    ]
    try:
        usage_str_list.extend([
            ('|  * peak_memory    = %s' % util_str.byte_str2(peak_memory())),
            ('|  * user_time      = %s' % time_str2(time_in_usermode())),
            ('|  * system_time    = %s' % time_str2(time_in_systemmode())),
        ])
    except Exception:
        pass
    usage_str_list.append('L______________________')
    usage_str = '\n'.join(usage_str_list)
    return usage_str

def current_memory_usage():
    """
    Returns this programs current memory usage in bytes
    """
    import psutil
    proc = psutil.Process(os.getpid())
    #meminfo = proc.get_memory_info()
    meminfo = proc.memory_info()
    rss = meminfo[0]  # Resident Set Size / Mem Usage
    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA
    return rss

def get_matching_process_ids(cmd_pattern, user_pattern):
    """
    CommandLine:
        export PID=30196
        export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'python2.7'))")
        export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'matlab'))")
        sudo -H echo $PID
        ps -o pid,comm,nice -p $PID
        renice 10 -p $PID
        sudo renice -4 -p $PID

    user_pattern = 'jonc'
    cmd_pattern = 'main.py'
    user_pattern = None
    cmd_pattern = 'matlab'
    get_matching_process_ids(cmd_pattern, user_pattern)
    """
    import psutil
    import re
    process_list = list(psutil.process_iter())
    def matches_pattern(proc, user_pattern, cmd_pattern):
        matches_user = True if user_pattern is None else re.match(user_pattern, proc.username())
        cmdline_str = ' '.join(proc.cmdline())
        matches_name = True if cmd_pattern is None else re.search(cmd_pattern, cmdline_str)
        return matches_user and matches_name
    filtered_proc_list = [proc for proc in process_list if matches_pattern(proc, user_pattern, cmd_pattern)]

    for proc in filtered_proc_list:
        print(' | '.join([str(proc.username()), str(proc.nice()), str(proc), ' '.join(proc.cmdline())]))
        #print(proc.cmdline())
        #print(proc.pid)
        #print('---')

    important_process_list = [proc for proc in process_list if proc.nice() < -4]
    for proc in important_process_list:
        print(' -- '.join([str(proc.username()), str(proc.nice()), str(proc), ' '.join(proc.cmdline())]))

    #for proc in filtered_proc_list:
    #    print('---')
    #    print(proc)
    #    print(proc.cmdline())
    #    print(proc.nice())
    #    print(proc.pid)
    filtered_pid_list = [proc.pid for proc in filtered_proc_list]
    return filtered_pid_list

def num_cpus():
    import psutil
    return psutil.cpu_count(logical=True)

def num_unused_cpus(thresh=10):
    """
    Returns the number of cpus with utilization less than `thresh` percent
    """
    import psutil
    cpu_usage = psutil.cpu_percent(percpu=True)
    return sum([p < thresh for p in cpu_usage])

def available_memory():
    """
    Returns total system wide available memory in bytes
    """
    import psutil
    return psutil.virtual_memory().available

def total_memory():
    """
    Returns total system wide memory in bytes
    """
    import psutil
    return psutil.virtual_memory().total

def used_memory():
    """
    Returns total system wide used memory in bytes
    """
    return total_memory() - available_memory()

def memstats():
    print(get_memstats_str())

def get_memstats_str():
    return '\n'.join([
        ('[psutil] total     = %s' % util_str.byte_str2(total_memory())),
        ('[psutil] available = %s' % util_str.byte_str2(available_memory())),
        ('[psutil] used      = %s' % util_str.byte_str2(used_memory())),
        ('[psutil] current   = %s' % util_str.byte_str2(current_memory_usage())),
    ])

def get_python_datastructure_sizes():
    """
    References:
        http://stackoverflow.com/questions/1331471/in-memory-size-of-python-stucture

    CommandLine:
        python -m utool.util_resources --test-get_python_datastructure_sizes

    Example:
        >>> # ENABLE_DOCTEST
        >>> from utool.util_resources import *  # NOQA
        >>> import utool as ut  # NOQA
        >>> type_sizes = get_python_datastructure_sizes()
        >>> result = ut.repr4(type_sizes, sorted_=True)
        >>> print(result)
    """
    import sys
    import decimal
    import six

    empty_types = {
        'int'     : 0,
        'float'   : 0.0,
        'dict'    : dict(),
        'set'     : set(),
        'tuple'   : tuple(),
        'list'    : list(),
        'str'     : '',
        'unicode' : u'',
        'decimal' : decimal.Decimal(0),
        'object'  : object(),
    }
    type_sizes = {key: sys.getsizeof(val)
                  for key, val in six.iteritems(empty_types)}
    return type_sizes

#psutil.virtual_memory()
#psutil.swap_memory()
#psutil.disk_partitions()
#psutil.disk_usage("/")
#psutil.disk_io_counters()
#psutil.net_io_counters(pernic=True)
#psutil.get_users()
#psutil.get_boot_time()
#psutil.get_pid_list()

if __name__ == '__main__':
    """
    CommandLine:
        python -m utool.util_resources
        python -m utool.util_resources --allexamples
        python -m utool.util_resources --allexamples --noface --nosrc
    """
    import multiprocessing
    multiprocessing.freeze_support()  # for win32
    import utool as ut  # NOQA
    ut.doctest_funcs()


text:
These are the PowerShell files we demo'd at Cinegy TechCon 2016 - in their full, working form.

Also included is the PowerShell script we used to change the output mutlicast address for our scripted, mass-launched Multiviewers - it's a great little script that lets you see how to read IP address details from a machine, and manipulate an XML file from inside PowerShell.

The 'extended' scripts take the original, and add some little extra bonus bits we felt were fun over time - since we actually use these scripts.

For help understanding how they work, best look at the Cinegy Open post about Scaling with Powershell at http://open.cinegy.com.

Have fun with them!


text:
<?php
    /**
     * Image class
     * @author      Gerald Plusquellec
     */
    namespace Thin;

    class Image
    {
        protected static $_adapterOptions = array(
            'preserveAlpha'     => true,
            'alphaMaskColor'    => array(
                255,
                255,
                255
            ),
            'preserveTransparency'  => true,
            'transparencyMaskColor' => array(
                0,
                0,
                0
            ),
            'resizeUp' => true
        );

        /**
        * @param string $adapterClass
        * @param array $adapterOptions
        * @return FTV_Image_Adapter_Abstract
        */
        public static function factory($adapterClass = null, $adapterOptions = null)
        {
            if (null === $adapterClass) {
                if (extension_loaded('gd')) {
                    $adapterClass = 'Image\\Adapter\\Gd';
                } else {
                    /* TODO */
                    $adapterClass = 'Image\\Adapter\\ImageMagick';
                }
            }

            if (null === $adapterOptions) {
                $adapterOptions = static::$_adapterOptions;
            }

            return new $adapterClass($adapterOptions);
        }
    }


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/clothing/general-topics/childrens-fashion" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/clothing/general-topics/childrens-fashion</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Children's Fashion</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/clothing/general-topics/childrens-fashion</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/clothing/general-topics/childrens-fashion</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
package org.apache.flink.streaming.runtime.io;

import org.apache.flink.annotation.Internal;
import org.apache.flink.runtime.io.network.partition.consumer.BufferOrEvent;

import java.io.IOException;
import java.util.Optional;

/**
 * Always empty implementation of {@link BufferStorage}. It doesn't allow for adding any data.
 */
@Internal
public class EmptyBufferStorage implements BufferStorage {
	@Override
	public void add(BufferOrEvent boe) throws IOException {
		throw new UnsupportedOperationException("Adding to EmptyBufferStorage is unsupported");
	}

	@Override
	public boolean isFull() {
		return false;
	}

	@Override
	public void rollOver() throws IOException {
	}

	@Override
	public long getPendingBytes() {
		return 0;
	}

	@Override
	public long getRolledBytes() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return true;
	}

	@Override
	public Optional<BufferOrEvent> pollNext() throws IOException {
		return Optional.empty();
	}

	@Override
	public long getMaxBufferedBytes() {
		return -1;
	}

	@Override
	public void close() throws IOException {
	}
}


text:
import {Component} from '@angular/core';
import {Router} from '@angular/router-deprecated';
import {ContactService} from '../contact.service';
import {Contact} from '../model/contact';
import {ContactForm} from '../form/contact.form';

@Component({
    template: `
        CONTACT CREATE COMPONENT
        <contactForm [model]="model"></contactForm>
        <button (click)="onCreate()">Create</button>
    `,
    directives: [ContactForm]
})
export class ContactCreateComponent {
    model:Contact;

    constructor(protected service:ContactService, protected router:Router) {
        this.model = new Contact();
    }

    onCreate() {
        this.service.create(this.model).subscribe(
           val => this.router.navigate(['Detail', { id: val }]),
           err => console.log("err")
        )
    }

}


text:
layout: post
title: The Future of Open Source Catholic
author: geerlingguy
nid: 486
comments: true
redirect_from: /blog/jeff-geerling/future-open-source/
created: 1422978324
---
When I started Open Source Catholic in 2009, I was hoping to create a centralized resource for Catholics who were involved in OSS, sharing of ideas, tips and techniques for technology and web use for Catholic organizations, and a forum for Catholic software and app developers.

I was also employed by the Church at the time, and spent a good deal of time working on the problem of the Catholic Church being far behind tech trends in the wider tech world.

Times have changed, this site has basically been on mothballs for a couple years, and besides keeping the site patched for security updates, I haven't really had any incentive/plans to keep the site or the community going.

If someone else in the OSC community would like to take the reins, host the site, etc., I'd be happy to turn this over to them. Otherwise, my plan at this point is to turn the site into a static site, put it on mothballs permanently, and close out the social media accounts.

Are there any objections? Any feedback on this plan? I've been putting off this decision for some time, but it seems the time has come to do something about it, as crawlers (which aren't respecting robots.txt, and which I don't want to spend time fighting) have begun to practically DoS the server this site is on from time to time, and activity throughout the OSC realm has dropped to basically nil.


text:
/*
Theme Name: Start Bootstrap Blog - Wordpress Edition
Author: Sebastian Suen
Description: Bootstrap Blog template converted to WordPress, original Bootstrap template courtesy of startbootstrap.com
Version: 0.0.1
Tags: bootstrap
*/


text:
	    <button type="button" class="btn btn-primary">Main</button>
		<button type="button" class="btn btn-primary" ng-click="getStocks()">Stock List</button>
	    <button type="button" class="btn btn-primary">Add Stock</button>

Stock List
(Clicking Stock List button will reseed with one stock if list is empty)

{{stock.name}}


text:
namespace app_list_features {

const base::Feature kEnableAnswerCard{"EnableAnswerCard",
                                      base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnablePlayStoreAppSearch{
    "EnablePlayStoreAppSearch", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableAppDataSearch{"EnableAppDataSearch",
                                         base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableSettingsShortcutSearch{
    "EnableSettingsShortcutSearch", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableZeroStateSuggestions{
    "EnableZeroStateSuggestions", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableAppListSearchAutocomplete{
    "EnableAppListSearchAutocomplete", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableAppRanker{"EnableAppRanker",
                                     base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableZeroStateAppsRanker{
    "EnableZeroStateAppsRanker", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableQueryBasedMixedTypesRanker{
    "EnableQueryBasedMixedTypesRanker", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableZeroStateMixedTypesRanker{
    "EnableZeroStateMixedTypesRanker", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableAppReinstallZeroState{
    "EnableAppReinstallZeroState", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableSuggestedFiles{"EnableSuggestedFiles",
                                          base::FEATURE_DISABLED_BY_DEFAULT};

// "EnableEmbeddedAssistantUI" is used in finch experiment therefore we cannot
// change it until fully launched. It is used to redirect Launcher search to
// Assistant search.
const base::Feature kEnableAssistantSearch{"EnableEmbeddedAssistantUI",
                                           base::FEATURE_DISABLED_BY_DEFAULT};

const base::Feature kEnableAppGridGhost{"EnableAppGridGhost",
                                        base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableAppListLaunchRecording{
    "EnableAppListLaunchRecording", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableAggregatedMlAppRanking{
    "EnableAggregatedMlAppRanking", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kLauncherSettingsSearch{"LauncherSettingsSearch",
                                            base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kEnableFuzzyAppSearch{"EnableFuzzyAppSearch",
                                          base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableExactMatchForNonLatinLocale{
    "EnableExactMatchForNonLatinLocale", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kEnableAggregatedMlSearchRanking{
    "EnableAggregatedMlSearchRanking", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kNewDragSpecInLauncher{"NewDragSpecInLauncher",
                                           base::FEATURE_DISABLED_BY_DEFAULT};

bool IsAnswerCardEnabled() {
  // Not using local static variable to allow tests to change this value.
  // Do not show answer card if Assistant search is enabled.
  return base::FeatureList::IsEnabled(kEnableAnswerCard) &&
         !IsAssistantSearchEnabled();
}

bool IsPlayStoreAppSearchEnabled() {
  // Not using local static variable to allow tests to change this value.
  return base::FeatureList::IsEnabled(kEnablePlayStoreAppSearch);
}

bool IsAppDataSearchEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppDataSearch);
}

bool IsSettingsShortcutSearchEnabled() {
  return base::FeatureList::IsEnabled(kEnableSettingsShortcutSearch);
}

bool IsZeroStateSuggestionsEnabled() {
  return base::FeatureList::IsEnabled(kEnableZeroStateSuggestions);
}

bool IsAppListSearchAutocompleteEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppListSearchAutocomplete);
}

bool IsAppRankerEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppRanker);
}

bool IsZeroStateAppsRankerEnabled() {
  return base::FeatureList::IsEnabled(kEnableZeroStateAppsRanker);
}

bool IsQueryBasedMixedTypesRankerEnabled() {
  return base::FeatureList::IsEnabled(kEnableQueryBasedMixedTypesRanker);
}

bool IsZeroStateMixedTypesRankerEnabled() {
  return base::FeatureList::IsEnabled(kEnableZeroStateMixedTypesRanker);
}

bool IsAppReinstallZeroStateEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppReinstallZeroState);
}

bool IsSuggestedFilesEnabled() {
  return base::FeatureList::IsEnabled(kEnableSuggestedFiles);
}

bool IsAssistantSearchEnabled() {
  return base::FeatureList::IsEnabled(kEnableAssistantSearch);
}

bool IsAppGridGhostEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppGridGhost);
}

bool IsAggregatedMlAppRankingEnabled() {
  return base::FeatureList::IsEnabled(kEnableAggregatedMlAppRanking);
}

bool IsLauncherSettingsSearchEnabled() {
  return base::FeatureList::IsEnabled(kLauncherSettingsSearch);
}

bool IsFuzzyAppSearchEnabled() {
  return base::FeatureList::IsEnabled(kEnableFuzzyAppSearch);
}

bool IsExactMatchForNonLatinLocaleEnabled() {
  return base::FeatureList::IsEnabled(kEnableExactMatchForNonLatinLocale);
}

bool IsAggregatedMlSearchRankingEnabled() {
  return base::FeatureList::IsEnabled(kEnableAggregatedMlSearchRanking);
}

bool IsNewDragSpecInLauncherEnabled() {
  return base::FeatureList::IsEnabled(kNewDragSpecInLauncher);
}

std::string AnswerServerUrl() {
  const std::string experiment_url =
      base::GetFieldTrialParamValueByFeature(kEnableAnswerCard, "ServerUrl");
  if (!experiment_url.empty())
    return experiment_url;
  return "https://www.google.com/coac";
}

std::string AnswerServerQuerySuffix() {
  return base::GetFieldTrialParamValueByFeature(kEnableAnswerCard,
                                                "QuerySuffix");
}

std::string AppSearchResultRankerPredictorName() {
  const std::string predictor_name = base::GetFieldTrialParamValueByFeature(
      kEnableZeroStateAppsRanker, "app_search_result_ranker_predictor_name");
  if (!predictor_name.empty())
    return predictor_name;
  return std::string("MrfuAppLaunchPredictor");
}

bool IsAppListLaunchRecordingEnabled() {
  return base::FeatureList::IsEnabled(kEnableAppListLaunchRecording);
}

}  // namespace app_list_features


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

package org.flowable.cmmn.engine.impl.persistence.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.flowable.cmmn.api.runtime.PlanItemDefinitionType;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceQuery;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.converter.util.PlanItemDependencyUtil;
import org.flowable.cmmn.engine.CmmnEngineConfiguration;
import org.flowable.cmmn.engine.impl.persistence.entity.data.PlanItemInstanceDataManager;
import org.flowable.cmmn.engine.impl.runtime.PlanItemInstanceQueryImpl;
import org.flowable.cmmn.engine.impl.util.CaseInstanceUtil;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.cmmn.engine.impl.util.ExpressionUtil;
import org.flowable.cmmn.model.EventListener;
import org.flowable.cmmn.model.PlanFragment;
import org.flowable.cmmn.model.PlanItem;
import org.flowable.cmmn.model.PlanItemDefinition;
import org.flowable.cmmn.model.Stage;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.api.scope.ScopeTypes;
import org.flowable.common.engine.impl.context.Context;
import org.flowable.common.engine.impl.el.ExpressionManager;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.persistence.entity.AbstractEngineEntityManager;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityManager;
import org.flowable.job.service.impl.persistence.entity.ExternalWorkerJobEntity;
import org.flowable.job.service.impl.persistence.entity.ExternalWorkerJobEntityManager;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntity;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntityManager;
import org.flowable.variable.service.VariableService;
import org.flowable.variable.service.impl.persistence.entity.VariableInstanceEntity;

/**
 * @author Joram Barrez
 */
public class PlanItemInstanceEntityManagerImpl
        extends AbstractEngineEntityManager<CmmnEngineConfiguration, PlanItemInstanceEntity, PlanItemInstanceDataManager>
        implements PlanItemInstanceEntityManager {

    public PlanItemInstanceEntityManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration, PlanItemInstanceDataManager planItemInstanceDataManager) {
        super(cmmnEngineConfiguration, planItemInstanceDataManager);
    }

    @Override
    public PlanItemInstanceEntityBuilder createPlanItemInstanceEntityBuilder() {
        return new PlanItemInstanceEntityBuilderImpl(this);
    }

    public PlanItemInstanceEntity createChildPlanItemInstance(PlanItemInstanceEntityBuilderImpl builder) {
        ExpressionManager expressionManager = engineConfiguration.getExpressionManager();

        PlanItemInstanceEntity planItemInstanceEntity = create();
        planItemInstanceEntity.setCaseDefinitionId(builder.getCaseDefinitionId());
        planItemInstanceEntity.setDerivedCaseDefinitionId(builder.getDerivedCaseDefinitionId());
        planItemInstanceEntity.setCaseInstanceId(builder.getCaseInstanceId());

        planItemInstanceEntity.setCreateTime(engineConfiguration.getClock().getCurrentTime());
        planItemInstanceEntity.setElementId(builder.getPlanItem().getId());
        PlanItemDefinition planItemDefinition = builder.getPlanItem().getPlanItemDefinition();
        if (planItemDefinition != null) {
            planItemInstanceEntity.setPlanItemDefinitionId(planItemDefinition.getId());

            String planItemDefinitionType = planItemDefinition.getClass().getSimpleName().toLowerCase();
            planItemInstanceEntity.setPlanItemDefinitionType(planItemDefinitionType);
            planItemInstanceEntity.setStage(PlanItemDefinitionType.STAGE.equals(planItemDefinitionType));
        } else {
            planItemInstanceEntity.setStage(false);
        }

        PlanItemInstance stagePlanItemInstance = builder.getStagePlanItemInstance();
        if (stagePlanItemInstance != null) {
            planItemInstanceEntity.setStageInstanceId(stagePlanItemInstance.getId());

            // if the stage has a derived case definition id (e.g. was dynamically injected, we need to pass it on to child plan items, otherwise they cannot
            // load the plan item model
            if (stagePlanItemInstance.getDerivedCaseDefinitionId() != null && builder.getDerivedCaseDefinitionId() == null) {
                planItemInstanceEntity.setDerivedCaseDefinitionId(stagePlanItemInstance.getDerivedCaseDefinitionId());
            }
        }
        planItemInstanceEntity.setTenantId(builder.getTenantId());

        insert(planItemInstanceEntity);

        // adding variables must be done after the entity was inserted, before it does not yet have an id for the variables to be referenced
        if (builder.hasLocalVariables()) {
            planItemInstanceEntity.setVariablesLocal(builder.getLocalVariables());
        }

        // check for an explicitly set name for the plan item instance
        if (builder.getName() != null) {
            planItemInstanceEntity.setName(builder.getName());
        } else {
            // the name might have an expression being based on local variables, so we can only set the name after insertion
            if (builder.getPlanItem().getName() != null) {
                Expression nameExpression = expressionManager.createExpression(builder.getPlanItem().getName());
                String name;
                if (builder.isSilentNameExpressionEvaluation()) {
                    try {
                        name = nameExpression.getValue(planItemInstanceEntity).toString();
                    } catch (Exception e) {
                        // we silently catch this exception as it is expected to a possible failure due to the state of the name evaluation
                        // we use the expression itself as a fallback in this case
                        name = builder.getPlanItem().getName();
                    }
                } else {
                    name = nameExpression.getValue(planItemInstanceEntity).toString();
                }
                planItemInstanceEntity.setName(name);
            }
        }

        if (builder.addToParent) {
            addPlanItemInstanceToParent(planItemInstanceEntity);
        }

        return planItemInstanceEntity;
    }

    protected void addPlanItemInstanceToParent(PlanItemInstanceEntity planItemInstanceEntity) {
        if (planItemInstanceEntity.getStageInstanceId() != null) {
            PlanItemInstanceEntity stagePlanItemInstanceEntity = engineConfiguration.getPlanItemInstanceEntityManager()
                    .findById(planItemInstanceEntity.getStageInstanceId());
            stagePlanItemInstanceEntity.getChildPlanItemInstances().add(planItemInstanceEntity);
        } else {
            CaseInstanceEntity caseInstanceEntity = engineConfiguration.getCaseInstanceEntityManager().findById(planItemInstanceEntity.getCaseInstanceId());
            caseInstanceEntity.getChildPlanItemInstances().add(planItemInstanceEntity);
        }
    }

    @Override
    public void deleteSentryRelatedData(String planItemId) {
        PlanItemInstanceEntity planItemInstanceEntity = dataManager.findById(planItemId);

        deleteSentryPartInstances(planItemInstanceEntity);
        deleteOrphanEventListeners(planItemInstanceEntity);
    }

    /**
     * Deletes any part instance of a sentry that was satisfied before to clean it up for further evaluation cycles.
     */
    protected void deleteSentryPartInstances(PlanItemInstanceEntity planItemInstanceEntity) {
        SentryPartInstanceEntityManager sentryPartInstanceEntityManager = engineConfiguration.getSentryPartInstanceEntityManager();
        if (planItemInstanceEntity.getPlanItem() != null
            && (!planItemInstanceEntity.getPlanItem().getEntryCriteria().isEmpty()
            || !planItemInstanceEntity.getPlanItem().getExitCriteria().isEmpty())) {
            if (planItemInstanceEntity.getSatisfiedSentryPartInstances() != null) {
                for (SentryPartInstanceEntity sentryPartInstanceEntity : planItemInstanceEntity.getSatisfiedSentryPartInstances()) {
                    sentryPartInstanceEntityManager.delete(sentryPartInstanceEntity);
                }
                // reset the internal satisfied sentry list, so it is not re-used again
                planItemInstanceEntity.setSatisfiedSentryPartInstances(null);
            }
        }
    }

    /**
     * Event listeners can become 'orphaned': when they reference sentries on plan item instances
     * that have moved to a terminal state, they would occur without anything listening to them
     * (and block completion of the parent stage). In that situation, they need to be removed.
     */
    protected void deleteOrphanEventListeners(PlanItemInstanceEntity planItemInstanceEntity) {

        /*
         * 'Orphan' event listeners are event listeners that are no longer referenced by any plan item instance that is not in a terminal state.
         * Said simpler: when they occur, nothing is listening to them anymore. As such, they have no value to keep around.
         * For example, imagine a user event listener is used to exit a stage. When the stage goes into a terminal state (via another way),
         * there is no purpose for the user event listener anymore. At that point, it is removed.
         *
         * Note that this needs to be done both on activating and terminating a plan item instance, as orphans can happen in both cases.
         *
         * The way these orphan event listeners are determined is as follows:
         * 1. Get all dependencies of the plan item that's currently being moved into a terminal state.
         *    (dependencies are all other plan items that are references through its sentries)
         * 2. Filter out the event listeners from that list.
         * 3. For those event listeners, get the dependent plan items.
         *    These dependents are the plan items that depend in their sentries on this event listener.
         * 4. Fetch the plan item instances for these dependent plan items.
         *    - If the event listener is used for an entry criterion: if they are all in a state different from available, it is an orphan.
         *    - If the event listener is used for an exit criterion: if they are all in a terminal state, the user event listener is an orphan and can be deleted.
         *    Note: if the plan item instance has a parent that is non-terminal, the plan item instance can still become active later and the event listener still is needed
         */

        PlanItem planItem = planItemInstanceEntity.getPlanItem();
        if (planItem != null) {

            // Step 1 and 2 (gather and filter)
            List<PlanItem> eventListenerDependencies = gatherEventListenerDependencies(planItem, planItemInstanceEntity);

            // Step 3 and 4 (determine dependent plan items for the event listener and check if it's orphaned)
            if (!eventListenerDependencies.isEmpty()) {
                terminateOrphanedEventListeners(planItemInstanceEntity, eventListenerDependencies);
            }
        }
    }

    protected List<PlanItem> gatherEventListenerDependencies(PlanItem planItem, PlanItemInstanceEntity planItemInstanceEntity) {
        // first collect the event listeners
        List<PlanItem> eventListenerDependencies;

        // if the plan item has repetition, we don't remove any event listeners for entry dependencies, as they might trigger in the future and re-create
        // the plan item as it has repetition and therefore, we also don't remove any exit sentry dependant event listeners, as if in the future, the plan
        // item becomes active again, those event listeners might trigger again to terminate it, so we need them to stay in place
        // furthermore, don't investigate into not-yet-created child plan items having event listeners as they might become active at a later state
        if (ExpressionUtil.hasRepetitionRule(planItem)) {
            return Collections.emptyList();
        } else {
            eventListenerDependencies = Stream.concat(
                planItem.getEntryDependencies().stream().filter(p -> p.getPlanItemDefinition() instanceof EventListener),
                planItem.getExitDependencies().stream().filter(p -> p.getPlanItemDefinition() instanceof EventListener))
                .collect(Collectors.toList());
        }

        // Special case: if the current plan item is a stage, we need to also verify all event listeners
        // that reference a child plan item of this stage. Normally this will happen automatically, unless
        // the child plan item instances haven't been created yet (e.g with nested stages).
        // As such, we need to check all plan items for which there hasn't been a plan item instance yet.

        if (planItem.getPlanItemDefinition() instanceof PlanFragment
            && PlanItemInstanceState.isInTerminalState(planItemInstanceEntity)) { //  This is only true when stopping, not when a plan item gets activated (in that case, the child plan items can still be created and no special care is needed)

            List<PlanItem> childPlanItemsWithDependencies = getChildPlanItemsWithDependencies((PlanFragment) planItem.getPlanItemDefinition());

            CaseInstanceEntity caseInstanceEntity = engineConfiguration.getCaseInstanceEntityManager()
                    .findById(planItemInstanceEntity.getCaseInstanceId());
            Map<String, List<PlanItemInstanceEntity>> childPlanItemInstancesMap = CaseInstanceUtil
                .findChildPlanItemInstancesMap(caseInstanceEntity, childPlanItemsWithDependencies);

            for (PlanItem childPlanItemWithDependencies : childPlanItemsWithDependencies) {
                if (!childPlanItemInstancesMap.containsKey(childPlanItemWithDependencies.getId())) {
                    eventListenerDependencies.addAll(childPlanItemWithDependencies.getEntryDependencies().stream()
                        .filter(p -> p.getPlanItemDefinition() instanceof EventListener).collect(Collectors.toList()));
                    eventListenerDependencies.addAll(childPlanItemWithDependencies.getExitDependencies().stream()
                        .filter(p -> p.getPlanItemDefinition() instanceof EventListener).collect(Collectors.toList()));
                }
            }
        }

        return eventListenerDependencies;
    }

    protected void terminateOrphanedEventListeners(PlanItemInstanceEntity planItemInstanceEntity,  List<PlanItem> eventListenerDependencies) {

        CaseInstanceEntity caseInstanceEntity = engineConfiguration.getCaseInstanceEntityManager()
                .findById(planItemInstanceEntity.getCaseInstanceId());

        for (PlanItem eventListenerPlanItem : eventListenerDependencies) {

            List<PlanItemInstanceEntity> eventListenerPlanItemInstance = CaseInstanceUtil
                .findNonTerminalChildPlanItemInstances(caseInstanceEntity, eventListenerPlanItem);

            // Step 3
            if (!eventListenerPlanItemInstance.isEmpty()) {

                List<PlanItem> dependentPlanItems = eventListenerPlanItem.getAllDependentPlanItems();
                Map<String, List<PlanItemInstanceEntity>> dependentPlanItemInstancesMap = CaseInstanceUtil
                    .findChildPlanItemInstancesMap(caseInstanceEntity, dependentPlanItems);

                // Step 4
                boolean isOrphan = true;
                Iterator<PlanItem> planItemIterator = dependentPlanItems.iterator();
                while (isOrphan && planItemIterator.hasNext()) {

                    PlanItem dependentPlanItem = planItemIterator.next();

                    List<PlanItemInstanceEntity> dependentPlanItemInstances = dependentPlanItemInstancesMap.get(dependentPlanItem.getId());
                    if (dependentPlanItemInstances != null && !dependentPlanItemInstances.isEmpty()) {

                        // In case there are instances, check the state

                        for (PlanItemInstanceEntity dependentPlanItemInstance : dependentPlanItemInstances) {
                            if (PlanItemDependencyUtil.isEntryDependency(dependentPlanItemInstance.getPlanItem(), eventListenerPlanItem)) {
                                if (PlanItemInstanceState.AVAILABLE.equals(dependentPlanItemInstance.getState())
                                    || PlanItemInstanceState.WAITING_FOR_REPETITION.equals(dependentPlanItemInstance.getState())) {
                                    isOrphan = false;
                                }
                            }

                            if (PlanItemDependencyUtil.isExitDependency(dependentPlanItemInstance.getPlanItem(), eventListenerPlanItem)) {
                                if (!PlanItemInstanceState.TERMINAL_STATES.contains(dependentPlanItemInstance.getState())) {
                                    isOrphan = false;
                                }
                            }
                        }

                    } else {

                        // In case there are no instances, we need to check potential parents.
                        // If there is a nonterminal parent, the event listener still might be needed and cannot be terminated

                        Stage parentStage = dependentPlanItem.getParentStage();
                        while (isOrphan && parentStage != null && !parentStage.isPlanModel()) {
                            List<PlanItemInstanceEntity> nonTerminalStagePlanItemInstances = CaseInstanceUtil
                                .findNonTerminalChildPlanItemInstances(caseInstanceEntity, parentStage.getPlanItem());
                            if (!nonTerminalStagePlanItemInstances.isEmpty()) {
                                isOrphan = false;
                            } else {
                                parentStage = parentStage.getParentStage();
                            }
                        }

                    }

                }

                if (isOrphan) {
                    for (PlanItemInstanceEntity eventListenerPlanItemInstanceEntity : eventListenerPlanItemInstance) {
                        // don't propagate the exit event type and exit type, if used on orphaned child plan items
                        CommandContextUtil.getAgenda().planTerminatePlanItemInstanceOperation(eventListenerPlanItemInstanceEntity,
                            null, null);
                    }
                }

            }
        }
    }

    protected List<PlanItem> getChildPlanItemsWithDependencies(PlanFragment planFragment) {
        List<PlanItem> childPlanItemsWithDependencies = new ArrayList<>();
        internalGetChildPlanItemsWithDependencies(planFragment, childPlanItemsWithDependencies);
        return childPlanItemsWithDependencies;
    }

    protected void internalGetChildPlanItemsWithDependencies(PlanFragment planFragment, List<PlanItem> childPlanItemsWithDependencies) {
        for (PlanItem planItem : planFragment.getPlanItems()) {
            if (!planItem.getEntryDependencies().isEmpty() || !planItem.getExitDependencies().isEmpty()) {
                childPlanItemsWithDependencies.add(planItem);

                if (planItem.getPlanItemDefinition() instanceof PlanFragment) {
                    internalGetChildPlanItemsWithDependencies((PlanFragment) planItem.getPlanItemDefinition(), childPlanItemsWithDependencies);
                }
            }
        }
    }

    @Override
    public void deleteByCaseDefinitionId(String caseDefinitionId) {
        dataManager.deleteByCaseDefinitionId(caseDefinitionId);
    }

    @Override
    public void deleteByStageInstanceId(String stageInstanceId) {
        dataManager.deleteByStageInstanceId(stageInstanceId);
    }

    @Override
    public void deleteByCaseInstanceId(String caseInstanceId) {
        dataManager.deleteByCaseInstanceId(caseInstanceId);
    }

    @Override
    public PlanItemInstanceQuery createPlanItemInstanceQuery() {
        return new PlanItemInstanceQueryImpl(engineConfiguration.getCommandExecutor(), engineConfiguration);
    }

    @Override
    public long countByCriteria(PlanItemInstanceQuery planItemInstanceQuery) {
        return dataManager.countByCriteria((PlanItemInstanceQueryImpl) planItemInstanceQuery);
    }

    @Override
    public List<PlanItemInstance> findByCriteria(PlanItemInstanceQuery planItemInstanceQuery) {
        return dataManager.findByCriteria((PlanItemInstanceQueryImpl) planItemInstanceQuery);
    }

    @Override
    public List<PlanItemInstanceEntity> findByCaseInstanceId(String caseInstanceId) {
        return dataManager.findByCaseInstanceId(caseInstanceId);
    }

    @Override
    public List<PlanItemInstanceEntity> findByStagePlanItemInstanceId(String stagePlanItemInstanceId) {
        return dataManager.findByStagePlanItemInstanceId(stagePlanItemInstanceId);
    }

    @Override
    public List<PlanItemInstanceEntity> findByCaseInstanceIdAndPlanItemId(String caseInstanceId, String planitemId) {
        return dataManager.findByCaseInstanceIdAndPlanItemId(caseInstanceId, planitemId);
    }

    @Override
    public void delete(PlanItemInstanceEntity planItemInstanceEntity, boolean fireEvent) {
        CountingPlanItemInstanceEntity countingPlanItemInstanceEntity = (CountingPlanItemInstanceEntity) planItemInstanceEntity;

        // Variables
        if (countingPlanItemInstanceEntity.getVariableCount() > 0) {

            VariableService variableService = engineConfiguration.getVariableServiceConfiguration().getVariableService();
            List<VariableInstanceEntity> variableInstanceEntities = variableService
                    .createInternalVariableInstanceQuery()
                    .subScopeId(planItemInstanceEntity.getId())
                    .scopeTypes(ScopeTypes.CMMN_DEPENDENT)
                    .list();
            for (VariableInstanceEntity variableInstanceEntity : variableInstanceEntities) {
                variableService.deleteVariableInstance(variableInstanceEntity);
            }
        }

        if (planItemInstanceEntity.isStage()) {
            if (planItemInstanceEntity.getChildPlanItemInstances() != null && !planItemInstanceEntity.getChildPlanItemInstances().isEmpty()) {
                for (PlanItemInstanceEntity childPlanItem : planItemInstanceEntity.getChildPlanItemInstances()) {
                    delete(childPlanItem, fireEvent);
                }
            }
        }

        if (planItemInstanceEntity.getPlanItemDefinitionType().equals(PlanItemDefinitionType.TIMER_EVENT_LISTENER)) {
            TimerJobEntityManager timerJobEntityManager = engineConfiguration.getJobServiceConfiguration().getTimerJobEntityManager();
            List<TimerJobEntity> timerJobsEntities = timerJobEntityManager
                .findJobsByScopeIdAndSubScopeId(planItemInstanceEntity.getCaseInstanceId(), planItemInstanceEntity.getId());
            for (TimerJobEntity timerJobEntity : timerJobsEntities) {
                timerJobEntityManager.delete(timerJobEntity);
            }
        }

        if (planItemInstanceEntity.getPlanItemDefinitionType().equals(PlanItemDefinitionType.CASE_PAGE_TASK)) {
            IdentityLinkEntityManager identityLinkEntityManager = engineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager();
            List<IdentityLinkEntity> identityLinkEntities = identityLinkEntityManager
                .findIdentityLinksBySubScopeIdAndType(planItemInstanceEntity.getId(), ScopeTypes.PLAN_ITEM);
            for (IdentityLinkEntity identityLinkEntity : identityLinkEntities) {
                identityLinkEntityManager.delete(identityLinkEntity);
            }
        }

        if (planItemInstanceEntity.getPlanItemDefinitionType().equals(PlanItemDefinitionType.EXTERNAL_WORKER_TASK)) {
            ExternalWorkerJobEntityManager externalWorkerJobEntityManager = engineConfiguration
                    .getJobServiceConfiguration().getExternalWorkerJobEntityManager();
            List<ExternalWorkerJobEntity> externalWorkerJobEntities = externalWorkerJobEntityManager
                    .findJobsByScopeIdAndSubScopeId(planItemInstanceEntity.getCaseInstanceId(), planItemInstanceEntity.getId());

            for (ExternalWorkerJobEntity externalWorkerJobEntity : externalWorkerJobEntities) {
                externalWorkerJobEntityManager.delete(externalWorkerJobEntity);
            }
        }

        getDataManager().delete(planItemInstanceEntity);
    }

    @Override
    public void updatePlanItemInstancesCaseDefinitionId(String caseInstanceId, String caseDefinitionId) {
        CommandContext commandContext = Context.getCommandContext();
        PlanItemInstanceQuery planItemQuery = new PlanItemInstanceQueryImpl(commandContext, engineConfiguration)
                .caseInstanceId(caseInstanceId)
                .includeEnded();
        List<PlanItemInstance> planItemInstances = findByCriteria(planItemQuery);
        if (planItemInstances != null) {
            for (PlanItemInstance planItemInstance : planItemInstances) {
                PlanItemInstanceEntity planItemInstanceEntity = (PlanItemInstanceEntity) planItemInstance;
                planItemInstanceEntity.setCaseDefinitionId(caseDefinitionId);
                update(planItemInstanceEntity);
            }
        }
    }

    protected CaseInstanceEntityManager getCaseInstanceEntityManager() {
        return engineConfiguration.getCaseInstanceEntityManager();
    }

}


text:
module Csound.Air.Wave (
	 -- * Bipolar
    osc, oscBy, saw, isaw, pulse, sqr, pw, tri, ramp, blosc,

    -- ** With phase control
    osc', oscBy', saw', isaw', pulse', sqr', pw', tri', ramp', blosc',

    -- ** With random phase
    rndOsc, rndOscBy, rndSaw, rndIsaw, rndPulse, rndSqr, rndPw, rndTri, rndRamp, rndBlosc,

    -- * Unipolar
    unipolar, bipolar, uosc, uoscBy, usaw, uisaw, upulse, usqr, upw, utri, uramp, ublosc,

    -- ** With phase control
    uosc', uoscBy', usaw', uisaw', upulse', usqr', upw', utri', uramp', ublosc',

    -- ** With random phase
    urndOsc, urndOscBy, urndSaw, urndIsaw, urndPulse, urndSqr, urndPw, urndTri, urndRamp, urndBlosc,

    -- * Noise
    rndh, urndh, rndi, urndi, white, pink,

    -- * Frequency modulation
    fosc,

    -- * Low frequency oscillators
    Lfo, lfo,

    -- * Detune
    detune,

    -- * Unision
    multiHz, multiCent, multiRnd, multiGauss, multiRndSE, multiGaussSE,

    -- * Random splines
    urspline, birspline
) where

import Csound.Typed
import Csound.Typed.Opcode hiding (lfo)
import Csound.Tab(sine, sines4)
import Csound.SigSpace

-- | A pure tone (sine wave).
osc :: Sig -> Sig
osc cps = oscil3 1 cps sine

-- | A pure tone (sine wave) with initial phase (the first argiment).
osc' :: D -> Sig -> Sig
osc' phase cps = oscil3 1 cps sine `withD` phase

-- | An oscillator with user provided waveform.
oscBy :: Tab -> Sig -> Sig
oscBy tb cps = oscil3 1 cps tb

-- | An oscillator with user provided waveform with initial phase (the second argiment).
oscBy' :: Tab -> D -> Sig -> Sig
oscBy' tb phase cps = oscil3 1 cps tb `withD` phase

-- unipolar waveforms

-- | Turns a bipolar sound (ranges from -1 to 1) to unipolar (ranges from 0 to 1)
unipolar :: Sig -> Sig
unipolar a = 0.5 + 0.5 * a

-- | Turns an unipolar sound (ranges from 0 to 1) to bipolar (ranges from -1 to 1)
bipolar :: Sig -> Sig
bipolar a = 2 * a - 1

-- | Unipolar pure tone.
uosc :: Sig -> Sig
uosc = unipolar . osc

-- | Unipolar 'Csound.Air.oscBy'.
uoscBy :: Tab -> Sig -> Sig
uoscBy tb = unipolar . oscBy tb

-- | Unipolar sawtooth.
usaw :: Sig -> Sig
usaw = unipolar . saw

-- | Unipolar integrated sawtooth.
uisaw :: Sig -> Sig
uisaw = unipolar . isaw

-- | Unipolar square wave.
usqr :: Sig -> Sig
usqr = unipolar . sqr

-- | Unipolar triangle wave.
utri :: Sig -> Sig
utri = unipolar . tri

-- | Unipolar pulse.
upulse :: Sig -> Sig
upulse = unipolar . pulse

-- | Unipolar band-limited oscillator.
ublosc :: Tab -> Sig -> Sig
ublosc tb = unipolar . blosc tb

-- | Unipolar random splines.
-- It generates the splines with unipolar output (ranges from 0 to 1).
-- Arguments affect the frequency for generation of new values.
--
-- > urspline cpsMin cpsMax
urspline :: Sig -> Sig -> SE Sig
urspline cpsMin cpsMax = rspline 0 1 cpsMin cpsMax

-- | Bipolar random splines.
-- It generates the splines with bipolar output (ranges from -1 to 1).
-- Arguments affect the frequency for generation of new values.
--
-- > birspline cpsMin cpsMax
birspline :: Sig -> Sig -> SE Sig
birspline cpsMin cpsMax = rspline (-1) 1 cpsMin cpsMax

-----------------------

-- | Frequency modulation
--
-- > fosc carrierFreq modulatorFreq modIndex cps
fosc :: Sig -> Sig -> Sig -> Sig -> Sig
fosc car mod ndx cps = foscili 1 cps car mod ndx sine

-- | Pulse width modulation (width range is 0 to 1)
--
-- > pw dutyCycle cps
pw :: Sig -> Sig -> Sig
pw duty cps = vco2 1 cps `withD` 2 `withSig` duty

-- | Pulse width modulation (width range is 0 to 1)
--
-- > pw' dutyCycle phase cps
pw' :: Sig -> D -> Sig -> Sig
pw' duty phase cps = vco2 1 cps `withD` 2 `withSig` duty `withD` phase

-- | Triangle wave with ramp factor (factor's range is 0 to 1)
--
-- > ramp factor cps
ramp :: Sig -> Sig -> Sig
ramp duty cps = vco2 1 cps `withD` 4 `withSig` (uon 0.01 0.99 $ duty)

-- | Triangle wave with ramp factor (factor's range is 0 to 1)
--
-- > ramp' factor phase cps
ramp' :: Sig -> D -> Sig -> Sig
ramp' duty phase cps = vco2 1 cps `withD` 4 `withSig` (uon 0.01 0.99 $ duty) `withD` phase

-- | Unipolar pulse width modulation wave.
upw :: Sig -> Sig -> Sig
upw duty cps = unipolar $ pw duty cps

-- | Unipolar triangle wave with ram factor.
uramp :: Sig -> Sig -> Sig
uramp duty cps = unipolar $ ramp duty cps

--------------------------------------------------------------------------
-- unipolar oscils with phase control

unipolar' :: (D -> Sig -> Sig) -> (D -> Sig -> Sig)
unipolar' f phs cps = unipolar $ f phs cps

uosc' = unipolar' osc'
uoscBy' a = unipolar' (oscBy' a)
usaw' = unipolar' saw'
uisaw' = unipolar' isaw'
upulse' = unipolar' pulse'
usqr' = unipolar' sqr'
upw' a = unipolar' (pw' a)
utri' = unipolar' tri'
uramp' a = unipolar' (ramp' a)
ublosc' a = unipolar' (blosc' a)

--------------------------------------------------------------------------
-- random phase

rndPhs :: (D -> Sig -> Sig) -> (Sig -> SE Sig)
rndPhs f cps = fmap (\x -> f x cps) $ rnd 1

rndOsc = rndPhs osc'
rndOscBy a = rndPhs (oscBy' a)
rndSaw = rndPhs saw'
rndIsaw = rndPhs isaw'
rndPulse = rndPhs pulse'
rndSqr = rndPhs sqr'
rndPw a = rndPhs (pw' a)
rndTri = rndPhs tri'
rndRamp a = rndPhs (ramp' a)
rndBlosc a = rndPhs (blosc' a)

urndOsc = rndPhs uosc'
urndOscBy a = rndPhs (uoscBy' a)
urndSaw = rndPhs usaw'
urndIsaw = rndPhs uisaw'
urndPulse = rndPhs upulse'
urndSqr = rndPhs usqr'
urndPw a = rndPhs (upw' a)
urndTri = rndPhs utri'
urndRamp a = rndPhs (uramp' a)
urndBlosc a = rndPhs (ublosc' a)

--------------------------------------------------------------------------
-- unipolar random phase

--------------------------------------------------------------------------
-- noise

-- | Constant random signal. It updates random numbers with given frequency.
--
-- > constRnd freq
rndh :: Sig -> SE Sig
rndh = randh 1

-- | Linear random signal. It updates random numbers with given frequency.
--
-- > rndi freq
rndi :: Sig -> SE Sig
rndi = randi 1

-- | Unipolar @rndh@
urndh :: Sig -> SE Sig
urndh = fmap unipolar . rndh

-- | Unipolar @rndi@
urndi :: Sig -> SE Sig
urndi = fmap unipolar . rndi

-- | White noise.
white :: SE Sig
white = noise 1 0

-- | Pink noise.
pink :: SE Sig
pink = pinkish 1

--------------------------------------------------------------------------
-- lfo

-- | Low frequency oscillator
type Lfo = Sig

-- | Low frequency oscillator
--
-- > lfo shape depth rate
lfo :: (Sig -> Sig) -> Sig -> Sig -> Sig
lfo shape depth rate = depth * shape rate

--------------------------------------------------------------------------

-- | Scales the oscillator by frequency.
-- That's how we can rise the pitch by 2 semitones and 15 cents:
--
-- > detune (semitone 2 * cent 15) osc
detune :: Sig -> (Sig -> a) -> (Sig -> a)
detune k f cps = f (k * cps)

--------------------------------------------------------------------------

linRange n amount = fmap (\x -> amount * sig (2 * double x - 1)) [0, (1 / fromIntegral n) .. 1]

-- | Unision by Hertz. It creates n oscillators that are playing
-- the same pitch slightly detuned. The oscillatos's pitch is evenly distributed in Hz.
--
-- > multiHz numberOfUnits amountHz wave
multiHz :: Fractional a => Int -> Sig -> (Sig -> a) -> (Sig -> a)
multiHz n amount f cps = mean $ fmap (f . (cps + )) $ linRange n amount

-- | Unision by Cents. It creates n oscillators that are playing
-- the same pitch slightly detuned. The oscillatos's pitch is evenly distributed in cents.
--
-- > multiCent numberOfUnits amountCent wave
multiCent :: Fractional a => Int -> Sig -> (Sig -> a) -> (Sig -> a)
multiCent n amount f cps = mean $ fmap (f . (cps * ) . cent) $ linRange n amount

-- | Oscillators are detuned randomly in the given interval.
--
-- > multiRnd numberOfUnits amountCent wave
multiRnd :: Fractional a => Int -> Sig -> (Sig -> a) -> (Sig -> SE a)
multiRnd = genMultiRnd (rnd 1)

-- | Oscillators are detuned randomly with Gauss distribution in the given interval.
--
-- > multiGauss numberOfUnits amountCent wave
multiGauss :: Fractional a => Int -> Sig -> (Sig -> a) -> (Sig -> SE a)
multiGauss = genMultiRnd (fmap ((+ 0.5) . ir) $ gauss 0.5)

genMultiRnd :: Fractional a => (SE D) -> Int -> Sig -> (Sig -> a) -> (Sig -> SE a)
genMultiRnd gen n amount f cps = fmap mean $ mapM (const go) $ replicate n ()
    where go = fmap (\dx -> f $ cps + amount * (sig $ 2 * dx - 1)) gen

-- | Oscillators are detuned randomly in the given interval.
-- Useful for waves that return a signals with Side Effects.
--
-- > multiRnd numberOfUnits amountCent wave
multiRndSE :: Fractional a => Int -> Sig -> (Sig -> SE a) -> (Sig -> SE a)
multiRndSE = genMultiRndSE (rnd 1)

-- | Oscillators are detuned randomly with Gauss distribution in the given interval.
-- Useful for waves that return a signals with Side Effects.
--
-- > multiGauss numberOfUnits amountCent wave
multiGaussSE :: Fractional a => Int -> Sig -> (Sig -> SE a) -> (Sig -> SE a)
multiGaussSE = genMultiRndSE (fmap ((+ 0.5) . ir) $ gauss 0.5)

genMultiRndSE :: Fractional a => (SE D) -> Int -> Sig -> (Sig -> SE a) -> (Sig -> SE a)
genMultiRndSE gen n amount f cps = fmap mean $ mapM (const go) $ replicate n ()
    where go = (\dx -> f $ cps * cent (amount * (sig $ 2 * dx - 1))) =<< gen

-- | Mean value.
mean :: Fractional a => [a] -> a
mean xs = sum xs / (fromIntegral $ length xs)


text:
include(CMakeForceCompiler)

# User configurable variables
# (show up in cmake-gui)
#
set(TEENSY_VERSION 31 CACHE STRING "Set to the Teensy version corresponding to your board (30 or 31 allowed)" FORCE)
set(CPU_CORE_SPEED 72000000 CACHE STRING "Set to 24000000, 48000000, 72000000 or 96000000 to set CPU core speed" FORCE)
set(ARDUINOPATH "/Applications/Arduino.app/Contents/Resources/Java/" CACHE STRING "Path to Arduino installation" FORCE)

# Derived variables
#
set(CPU cortex-m4)

set(TOOLSPATH "${ARDUINOPATH}hardware/tools/")
set(COMPILERPATH "${TOOLSPATH}arm/bin/")
set(COREPATH "${ARDUINOPATH}hardware/teensy/avr/cores/teensy3/")

# Normal toolchain configuration
#

# this one is important
set(CMAKE_SYSTEM_NAME Generic)

# specify the cross compiler
cmake_force_c_compiler(${COMPILERPATH}arm-none-eabi-gcc GNU)
cmake_force_cxx_compiler(${COMPILERPATH}arm-none-eabi-g++ GNU)

# where is the target environment
set(CMAKE_FIND_ROOT_PATH ${COMPILERPATH})

# search for programs in the build host directories
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)

# for libraries and headers in the target directories
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

# Additional C and CPP files for Arduino support
#

file(GLOB TEENSY_C_FILES ${COREPATH}*.c)
file(GLOB TEENSY_CPP_FILES ${COREPATH}*.cpp)
set(TEENSY_SOURCES ${TEENSY_C_FILES} ${TEENSY_CPP_FILES})
list(REMOVE_ITEM TEENSY_SOURCES ${COREPATH}main.cpp)

# Teensy 3.0 and 3.1 differentiation
#

if (TEENSY_VERSION EQUAL 30)
	set(CPU_DEFINE __MK20DX128__)
	set(LINKER_FILE ${COREPATH}mk20dx128.ld)
else()
	set(CPU_DEFINE __MK20DX256__)
	set(LINKER_FILE ${COREPATH}mk20dx256.ld)
endif()

set(TEENSY_DEFINITIONS USB_SERIAL
                       LAYOUT_US_ENGLISH
                       F_CPU=${CPU_CORE_SPEED}
                       ${CPU_DEFINE})

# Macros to wrap add_[executable|library] for seamless Teensy integration
#
function(teensy_add_executable TARGET)
	set(ELFTARGET ${TARGET}.elf)

    add_executable(${ELFTARGET} ${ARGN} ${TEENSY_SOURCES})

    set_target_properties(${ELFTARGET} PROPERTIES COMPILE_FLAGS "-Wall -g -Os -mcpu=${CPU} -mthumb -nostdlib -MMD -felide-constructors -fno-exceptions -fno-rtti -std=gnu++0x")
	set_target_properties(${ELFTARGET} PROPERTIES COMPILE_DEFINITIONS "${TEENSY_DEFINITIONS}")
	set_target_properties(${ELFTARGET} PROPERTIES INCLUDE_DIRECTORIES "${COREPATH}")
	set_target_properties(${ELFTARGET} PROPERTIES LINK_FLAGS "-Os -Wl,--gc-sections,--defsym=__rtc_localtime=0 --specs=nano.specs -mcpu=${CPU} -mthumb -T${LINKER_FILE}")

	add_custom_command(OUTPUT ${TARGET}.hex
	                   COMMAND ${COMPILERPATH}arm-none-eabi-size ${ELFTARGET}
	                   COMMAND ${COMPILERPATH}arm-none-eabi-objcopy -O ihex -R .eeprom ${ELFTARGET} ${TARGET}.hex
	                   COMMAND ${TOOLSPATH}teensy_post_compile -file=${TARGET} -path=${CMAKE_CURRENT_BINARY_DIR} -tools=${TOOLSPATH}
	                   DEPENDS ${ELFTARGET}
	                   COMMENT "Creating HEX file for ${ELFTARGET}")

	add_custom_target(hex ALL DEPENDS ${TARGET}.hex)
endfunction()


text:
package kujiin.ui.table;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class TableItem_Number_Name_Duration_Ambience {
    public IntegerProperty number;
    public StringProperty name;
    public StringProperty duration;
    public StringProperty ambience;

    public TableItem_Number_Name_Duration_Ambience(int number, String name, String duration, String haspresetambience) {
        this.number = new SimpleIntegerProperty(number);
        this.name = new SimpleStringProperty(name);
        this.duration = new SimpleStringProperty(duration);
        this.ambience = new SimpleStringProperty(haspresetambience);
    }
}


text:
maintainer       "tlowrimore"
maintainer_email "tlowrimore@coroutine.com"
license          "Apache 2.0"
description      "Configures Rails Apps with Apache/Passenger/RVM"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "0.1.6"

recipe           "rails_apps::default", "Installs Apache, RVM, and Passenger"
recipe           "rails_apps::setup", "Creates directory structure for Rails apps"
recipe           "rails_apps::apache_config", "Configures Apache, Passenger"
recipe           "rails_apps::logrotate", "Sets up logrotate for Rails logs"

depends "apache2"
depends "rvm"
depends "rvm_passenger"

recommends "logrotate"

%w{ ubuntu debian }.each do |os|
  supports os
end


text:
from bzt.jmx.base import JMX, try_convert

GETTING_PARAM_ERR_MSG = "{tg}: getting of {name} is impossible ({params})"

class AbstractThreadGroup(object):
    XPATH = None
    RAMP_UP_SEL = None
    CONCURRENCY_SEL = None
    RATE_SEL = None
    ITER_SEL = None

    def __init__(self, element, logger):
        self.element = element
        self.gtype = self.__class__.__name__
        self.log = logger.getChild(self.gtype)

    def get_testname(self):
        return self.element.get('testname')

    def set_concurrency(self, concurrency=None):
        self.log.warning('Setting of concurrency for %s not implemented', self.gtype)

    def set_ramp_up(self, ramp_up=None):
        self.log.warning('Setting of ramp-up for %s not implemented', self.gtype)

    def get_duration(self):
        return self._get_val("duration")

    def get_rate(self, raw=False):
        return self._get_val("rate", self.RATE_SEL, default=1, raw=raw)

    def get_iterations(self, raw=False):
        return self._get_val("iterations", self.ITER_SEL, raw=raw)

    def get_ramp_up(self, raw=False):
        return self._get_val("ramp-up", self.RAMP_UP_SEL, default=0, raw=raw)

    def get_concurrency(self, raw=False):
        raw_concurrency = self._get_val("concurrency", self.CONCURRENCY_SEL, default=1, raw=True)
        if raw:
            return raw_concurrency
        else:
            return try_convert(raw_concurrency, default=1)

    def _get_val(self, name, selector=None, default=None, raw=False):
        if not selector:
            self.log.debug(GETTING_PARAM_ERR_MSG.format(tg=self.gtype, name=name, params="not implemented"))
            return default

        element = self.element.find(selector)
        if element is None:
            raw_val = None
        else:
            raw_val = element.text

        if raw:
            return raw_val

        if raw_val:
            if raw_val.isdigit() or raw_val[1:].isdigit():  # positive or negative number
                return int(raw_val)
            else:
                return raw_val
        return default

    def get_on_error(self):
        selector = ".//stringProp[@name='ThreadGroup.on_sample_error']"
        return self._get_val("on-error", selector, raw=True)

class ThreadGroup(AbstractThreadGroup):
    XPATH = 'jmeterTestPlan>hashTree>hashTree>ThreadGroup'
    CONCURRENCY_SEL = ".//*[@name='ThreadGroup.num_threads']"
    RAMP_UP_SEL = ".//*[@name='ThreadGroup.ramp_time']"

    def get_duration(self):
        sched_sel = ".//*[@name='ThreadGroup.scheduler']"
        scheduler = self._get_val("scheduler", sched_sel, raw=True)

        if scheduler == 'true':
            duration_sel = ".//*[@name='ThreadGroup.duration']"
            return self._get_val("duration", duration_sel)
        elif scheduler == 'false':
            return self._get_val("ramp-up", self.RAMP_UP_SEL)
        else:
            msg = 'Getting of ramp-up for %s is impossible due to scheduler: %s'
            self.log.warning(msg, (self.gtype, scheduler))

    def get_iterations(self):
        loop_control_sel = ".//*[@name='LoopController.continue_forever']"
        loop_controller = self._get_val("loop controller", loop_control_sel, raw=True)
        if loop_controller == "false":
            loop_sel = ".//*[@name='LoopController.loops']"
            return self._get_val("loops", loop_sel)
        else:
            msg = 'Getting of ramp-up for %s is impossible due to loop_controller: %s'
            self.log.warning(msg, (self.gtype, loop_controller))

    def get_thread_delay(self):
        delay_sel = ".//*[@name='ThreadGroup.delayedStart']"
        delay = self._get_val("delay", delay_sel, raw=True)
        return delay == "true"

    def get_scheduler_delay(self):
        delay_sel = ".//*[@name='ThreadGroup.delay']"
        return self._get_val("delay", delay_sel, raw=True)

class SteppingThreadGroup(AbstractThreadGroup):
    XPATH = r'jmeterTestPlan>hashTree>hashTree>kg\.apc\.jmeter\.threads\.SteppingThreadGroup'
    CONCURRENCY_SEL = ".//*[@name='ThreadGroup.num_threads']"

class UltimateThreadGroup(AbstractThreadGroup):
    XPATH = r'jmeterTestPlan>hashTree>hashTree>kg\.apc\.jmeter\.threads\.UltimateThreadGroup'

# parent of ConcurrencyThreadGroup and ArrivalThreadGroup
class AbstractDynamicThreadGroup(AbstractThreadGroup):
    RAMP_UP_SEL = ".//*[@name='RampUp']"
    ITER_SEL = ".//*[@name='Iterations']"

    def _get_time_unit(self):
        unit_sel = ".//*[@name='Unit']"
        return self._get_val("unit", unit_sel, raw=True)

    def set_ramp_up(self, ramp_up=None):
        ramp_up_element = self.element.find(self.RAMP_UP_SEL)
        ramp_up_element.text = str(ramp_up)

    def get_duration(self):
        hold_sel = ".//*[@name='Hold']"

        hold = self._get_val("hold", hold_sel)
        ramp_up = self.get_ramp_up()

        # 'empty' means 0 sec, let's detect that
        p_hold = self._get_val("hold", hold_sel, raw=True)
        p_ramp_up = self.get_ramp_up(raw=True)
        if hold is None and not p_hold:
            hold = 0
        if ramp_up is None and not p_ramp_up:
            ramp_up = 0

        if hold is not None and ramp_up is not None:
            result = hold + ramp_up
            if self._get_time_unit() == 'M':
                result *= 60

            return result

class ConcurrencyThreadGroup(AbstractDynamicThreadGroup):
    XPATH = r'jmeterTestPlan>hashTree>hashTree>com\.blazemeter\.jmeter\.threads\.concurrency\.ConcurrencyThreadGroup'
    CONCURRENCY_SEL = ".//*[@name='TargetLevel']"

    def set_concurrency(self, concurrency=None):
        concurrency_prop = self.element.find(self.CONCURRENCY_SEL)
        concurrency_prop.text = str(concurrency)

class ArrivalsThreadGroup(AbstractDynamicThreadGroup):
    XPATH = r'jmeterTestPlan>hashTree>hashTree>com\.blazemeter\.jmeter\.threads\.arrivals\.ArrivalsThreadGroup'
    RATE_SEL = ".//*[@name='TargetLevel']"

    def set_rate(self, rate=None):
        rate_prop = self.element.find(self.RATE_SEL)
        rate_prop.text = str(rate)

class ThreadGroupHandler(object):
    CLASSES = [ThreadGroup, SteppingThreadGroup, UltimateThreadGroup, ConcurrencyThreadGroup, ArrivalsThreadGroup]

    def __init__(self, logger):
        self.log = logger.getChild(self.__class__.__name__)

    def groups(self, jmx):
        """
        Get wrappers for thread groups that are enabled
        """
        for _class in self.CLASSES:
            for group in jmx.get(_class.XPATH):
                if group.get("enabled") != "false":
                    yield _class(group, self.log)

    def convert(self, source, target_gtype, load, concurrency, iterations):
        """
        Convert a thread group to ThreadGroup/ConcurrencyThreadGroup for applying of load
        """
        msg = "Converting %s (%s) to %s and apply load parameters"
        self.log.debug(msg, source.gtype, source.get_testname(), target_gtype)
        on_error = source.get_on_error()

        if target_gtype == ThreadGroup.__name__:
            thread_delay = None
            scheduler_delay = None
            if source.gtype == target_gtype:
                thread_delay = source.get_thread_delay()
                scheduler_delay = source.get_scheduler_delay()

            new_group_element = JMX.get_thread_group(
                concurrency=concurrency,
                rampup=load.ramp_up,
                hold=load.hold,
                iterations=iterations if iterations is not None else load.iterations,
                testname=source.get_testname(),
                on_error=on_error,
                thread_delay=thread_delay,
                scheduler_delay=scheduler_delay)
        elif target_gtype == ConcurrencyThreadGroup.__name__:
            iterations = None
            if source.gtype == target_gtype:
                iterations = source.get_iterations(raw=True)
            iterations = iterations or ""

            new_group_element = JMX.get_concurrency_thread_group(
                concurrency=concurrency,
                rampup=load.ramp_up,
                hold=load.hold,
                steps=load.steps,
                testname=source.get_testname(),
                on_error=on_error,
                iterations=iterations)
        else:
            self.log.warning('Unsupported preferred thread group: %s', target_gtype)
            return

        source.element.getparent().replace(source.element, new_group_element)


text:
<?php
/**
 * BusinessLogicServiceState
 *
 * PHP version 5
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * businessLogicService/businessLogicService.proto
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: version not set
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.27
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Alfaview\Model;
use \Alfaview\ObjectSerializer;

/**
 * BusinessLogicServiceState Class Doc Comment
 *
 * @category Class
 * @description State denotes the limited number of states a task can be in when in the queue.
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class BusinessLogicServiceState
{
    /**
     * Possible values of this enum
     */
    const UNDEFINED = 'UNDEFINED';
    const QUEUED = 'QUEUED';
    const ASSIGNED = 'ASSIGNED';
    const FAILED = 'FAILED';
    const FAILED_PERMANENTLY = 'FAILED_PERMANENTLY';
    const DONE = 'DONE';

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public static function getAllowableEnumValues()
    {
        return [
            self::UNDEFINED,
            self::QUEUED,
            self::ASSIGNED,
            self::FAILED,
            self::FAILED_PERMANENTLY,
            self::DONE,
        ];
    }
}