text:
Distributed Git repo synchronization tool.

##Intro
Hesokuri synchronizes one or more Git source code repositories between multiple
machines on a network. It is useful in the following situations:

1. You want the peace of mind of controlling the machines where your source code
   is stored.
2. You control/own multiple machines and work on the same project on them.
3. You want changes on one machine to appear on all other machines as soon as
   they are connected.
4. There is enough disk capacity on the machines such that each repository can
   fit on two or more peers.
5. The data to store is confidential or sensitive so it cannot be stored on a
   third-party's machine or on a traditional cloud storage system.
6. You want to use existing hardware rather than buy a dedicated backup device.

###What Hesokuri does
Simply stated, as soon as you commit a change in a repository, Hesokuri attempts
to push the changes to every peer that holds an instance of the repository in
the configuration file.

Hesokuri pushes commits on local branches to a remote branch called
`X_hesokr_Y`, where `X` is the local name of the branch and `Y` is the identity
of the host pushing the change.

####Live-edit branches
Sometimes, you will manually merge changes from `X_hesokr_Y` into the local
branch `X` when you need to access them. However, if `X` is a _live-edit_
branch, and it is a fast-forward of the local `X` branch, and the local `X`
branch is either not checked out or it is checked out and the working area and
index are clean, `X` will automatically be reset to the commit pointed to by
`X_hesokr_Y`. _This means if `X` is checked out and there are no uncommitted
changes to it, your working tree will update automatically when another peer
commits changes to it._ This process is referred to as _advancing_ in the source
code.

You can specify which branches are live-edit in the configuration file (see the
**Configure** section below).

####Sharing changes from other peers
For every branch named `X_hesokr_Y`, Hesokuri will try to push it to other peers
(besides `Y`) using the same branch name. This is useful for sharing changes
between two peers that are not running at the same time, but are running at the
same time as some third peer. In this case, the third peer acts as a carrier for
changes that did not originate from it.

##Getting started

###Requirements
All machines should have the following. Use earlier versions of each component
at your own risk.

1. The latest [Hesokuri release jar](http://github.com/google/hesokuri/releases)
2. Java Development Kit 1.7 or higher
3. Git version 1.8.5.6 or higher
4. A Unix-like OS is recommended. Hesokuri is tested on Mac OS X and Linux, but
   Windows is worth a try if you are feeling adventurous.
5. A static hostname or IP address. i.e. you should be able to do `ping FOO`
   from any machine and get a response, where `FOO` always refers to the same
   machine. This is string is called the _identity_.
6. Public-key ssh login enabled for each machine. You should not be asked for
   credentials when logging in between peers. Super-condensed directions
   which will work for most cases (`CENTRAL` is the identity of some arbitrary
   "central peer"):
   - Enable ssh login on each machine if it is not already
   - For each peer, run `ssh-keygen -t rsa` (enter an empty string when asked
     for a passphrase)
   - For each peer `FOO` (including `CENTRAL`), run:
     `scp ~/.ssh/id_rsa.pub CENTRAL:/tmp/id_rsa.pub.FOO`
   - After the previous command has been run on all peers, run the following on
     `CENTRAL` for each peer `FOO`:
     `cat /tmp/id_rsa.pub.* > /tmp/heso_keys`
   - For each peer FOO (including CENTRAL), run
     `scp CENTRAL:/tmp/heso_keys /tmp/heso_keys`
     `cat /tmp/heso_keys >> ~/.ssh/authorized_keys`
7. (alternative to 6) Be willing to use the experimental feature of authorized
   keys synchronization, documented in
   [the wiki](https://github.com/google/hesokuri/wiki/Authorized-keys-synchronization).

###Configure
Decide on a directory in your home folder to put the configuration file. If you
already have a Git repository for syncing configuration files and other assorted
files between machines, use that. These instructions assume this directory is
`~/etc` and the configuration file is `~/etc/hesocfg`.

On each peer, create a file at `~/[ETC]/.hesocfg` which specifies all Git repos
and peers to sync with. `[ETC]` can be anything you like, and also contains
other configuration files that you want to sync between machines. You are now
ready to create your configuration file.

1. Create a repo at `~/etc` (`git init ~/etc`)
2. Assuming the peers to sync have addresses `host-1` and `host-2`, create the
   configuration file at `~/etc/hesocfg` with this text:
   ```Clojure
{:comment
 ["You can put any data here as notes to maintainers of this file."]

 :sources
 [{:host-to-path {"host-1" "/home/jdoe/etc"
                  "host-2" "/home/jdoe/etc"}
   :live-edit-branches {:only #{"master"}}}]}
```
3. Commit the file: `cd ~/etc; git add hesocfg; git commit -m 'add hesocfg'`

For detailed guidance on the configuration file, see
[the wiki](https://github.com/google/hesokuri/wiki/Configuration-file).

If a repo or any containing directory does not exist on a peer and you start
Hesokuri on it, the containing directory and repo will be created automatically.

###Run
To run, execute `java -jar hesokuri.jar` at the command line. This starts
Hesokuri in background mode, which means it is monitoring the repos for changes
and pushing them or merging them automatically. Hesokuri also has sub-commands
which may be handy. Run `java -jar hesokuri.jar help` for more information.

When you first run Hesokuri, check the output occassionally to see if it shows
prompts for passwords or to confirm host keys. (It is doing this through your
`ssh` client, of course). If you see it, then the `known_hosts` and/or
`authorized_keys` files are not up-to-date. `known_hosts` can be updated by
manually ssh-ing to the host machine, (this can be impractical for large numbers
of hosts). Updating `authorized_keys` requires more effort, although Hesokuri
can help with this - see the **Requirements** section above.

###Web interface
When Hesokuri is running in background mode, you can go to
<http://localhost:8080> in a web browser to see the status of all sources and
last-pushed hashes for each branch and peer. The port can be changed from the
default of 8080 by setting the environment variable `HESOPORT` to the desired
port number.

##More information

- The [wiki on Github](https://github.com/google/hesokuri/wiki) documents
  things that don't quite fit in the README, like the contribution process.
- Join the [Google group](https://groups.google.com/forum/#!forum/hesokuri)
  to get tips, discuss possible improvements to the tool, etc.

##FAQ

###Where does the name of the project come from?
From the Japanese word meaning "secret cash hoard." It was chosen because this
tool enables a kind of "hoarding" of data on a personal machine. The name also
contrasts this practice with the alternative of storing your data on a third
party server, while the alternative to a hesokuri is storing your money in the
family bank account.

###Does Hesokuri support synchronizing bare repositories?
Hesokuri is mostly tested with non-bare repositories with their own working
trees. Bare repositories should also work, assuming they are initialized
manually with `git init --bare` in the directory specified by the configuration
file.

###What happens when some peer is unreachable?
Before pushing a branch to a remote peer, Hesokuri makes sure it is responsive
with [`InetAddress.isReachable`](http://goo.gl/VnJL7o) (essentially a ping). If
it is not responsive, Hesokuri will not push anything to that peer. Every three
minutes, Hesokuri attempts a ping and push for every peer that does not have the
most recent version of a branch. You can also use the web interface to force an
immediate push for peers that failed their last ping.


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.getValuePropValue = getValuePropValue;
exports.getPropValue = getPropValue;
exports.isCombobox = isCombobox;
exports.isMultipleOrTags = isMultipleOrTags;
exports.isMultipleOrTagsOrCombobox = isMultipleOrTagsOrCombobox;
exports.isSingleMode = isSingleMode;
exports.toArray = toArray;
exports.preventDefaultEvent = preventDefaultEvent;
exports.getSelectKeys = getSelectKeys;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _rcMenu = require('rc-menu');

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function getValuePropValue(child) {
  var props = child.props;
  if ('value' in props) {
    return props.value;
  }
  if (child.key) {
    return child.key;
  }
  throw new Error('no key or value for ' + child);
}

function getPropValue(child, prop) {
  if (prop === 'value') {
    return getValuePropValue(child);
  }
  return child.props[prop];
}

function isCombobox(props) {
  return props.combobox;
}

function isMultipleOrTags(props) {
  return props.multiple || props.tags;
}

function isMultipleOrTagsOrCombobox(props) {
  return isMultipleOrTags(props) || isCombobox(props);
}

function isSingleMode(props) {
  return !isMultipleOrTagsOrCombobox(props);
}

function toArray(value) {
  var ret = value;
  if (value === undefined) {
    ret = [];
  } else if (!Array.isArray(value)) {
    ret = [value];
  }
  return ret;
}

function preventDefaultEvent(e) {
  e.preventDefault();
}

function getSelectKeys(menuItems, value) {
  if (value === null || value === undefined) {
    return [];
  }
  var selectedKeys = [];
  _react2['default'].Children.forEach(menuItems, function (item) {
    if (item.type === _rcMenu.ItemGroup) {
      selectedKeys = selectedKeys.concat(getSelectKeys(item.props.children, value));
    } else {
      var itemValue = getValuePropValue(item);
      var itemKey = item.key;
      if (value.indexOf(itemValue) !== -1 && itemKey) {
        selectedKeys.push(itemKey);
      }
    }
  });
  return selectedKeys;
}

var UNSELECTABLE_STYLE = {
  userSelect: 'none',
  WebkitUserSelect: 'none'
};

exports.UNSELECTABLE_STYLE = UNSELECTABLE_STYLE;
var UNSELECTABLE_ATTRIBUTE = {
  unselectable: 'unselectable'
};
exports.UNSELECTABLE_ATTRIBUTE = UNSELECTABLE_ATTRIBUTE;

redpajama_set_name: RedPajamaGithub


text:
Meeting Calendar for Redmine
=============================

This Redmine plugin allows you to book and thence display meetings on a calendar interface

# Requirements
------------

* Redmine 2.x or 3.x (does not work with Redmine 1.x)

# Install
-------

Clone the plugin source code into your Redmines plugin directory:

    git clone https://github.com/dro123/redmine_meeting_room_calendar.git
    (original code: git clone https://github.com/QBurst/qbmeetingroomplugin.git)

**NOTE:** Make sure the plugin directory is named `redmine_meeting_room_calendar`.

Run the following command from a command line:

    rake redmine:plugins:migrate

# Setup
-----

Login with your administrator account and go to the admin menu.

## 1. Create Project
Create new project that holds the bookings for the rooms and add all the groups and users that should be allowed to book meetings.

## 2. Create Tracker
Create a new tracker, name it something like 'Meeting' and make sure that the standard fields 'Assignee', 'Start date' and 'Due date' are selected and copy the workflow from a already existing tracker (e.g. 'Bug')
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/1_new_tracker.png)

## 3. Create CustomFields
Create 3 new custom fields: Room, Start time, End time.

### Room
Name: Something like 'Room' (the name does not matter).
**Format:** List
**Multiple values:** No
**Possible values:** A list of rooms you want to be able to book meetings for
**Default value:** none
**Trackers:** 'Meeting' or whatever you called the tracker you created.
**Required:** Yes
**For all projects:** No
**Used as a filter:** Yes
**Searchable:** Yes
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/2_new_customfield1.png)

### Start time
**Name:** Something like 'Start time' (the name does not matter).
**Format:** List
**Multiple values:** No
**Possible values:**
06:00
06:15
06:30
06:45
07:00
07:15
07:30
07:45
08:00
08:15
08:30
08:45
09:00
09:15
09:30
09:45
10:00
10:15
10:30
10:45
11:00
11:15
11:30
11:45
12:00
12:15
12:30
12:45
13:00
13:15
13:30
13:45
14:00
14:15
14:30
14:45
15:00
15:15
15:30
15:45
16:00
16:15
16:30
16:45
17:00
17:15
17:30
17:45
18:00
18:15
18:30
18:45
19:00
19:15
19:30
19:45
20:00
20:15
20:30
20:45
21:00
**Default value:** none
**Trackers:** 'Meeting' or whatever you called the tracker you created.
**Required:** Yes
**For all projects:** No
**Used as a filter:** No
**Searchable:** Yes
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/3_new_customfield2.png)

### End time
**Name:** Something like 'End time' (the name does not matter).
**Format:** List
**Multiple values:** No
**Possible values:** same as 'Start time'
**Default value:** none
**Trackers:** 'Meeting' or whatever you called the tracker you created.
**Required:** Yes
**For all projects:** No
**Used as a filter:** No
**Searchable:** Yes
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/4_new_customfield3.png)

## 4. Setup project
Go to the project settings of the project you created.
In the 'Information' panel set:
**Trackers:** 'Meeting' (or whatever you called the tracker you created)
**Custom fields:** 'Room', 'Start time', 'End time' (or whatever you called the custom fields you created)
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/5_project_settings.png)

## 5. Configure Plugin
Go to the plugin settings in Admin -> Plugins and click on 'Configure' for the plugin 'Redmine Meeting Room Calendar plugin'.
* Select the project you created
* Select the tracker you created
* Select the custom fields you created
* Decide wheter the project menu should be visible in the calendar view
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/6_plugin_settings.png)

## 6. Configure Redmine
Go to the plugin settings in Admin -> Settings -> Authentication
If 'Authentication required' is activated or the project you created is not public you have to enable the REST web service authentication with 'Enable REST web service'.
![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/7_redmine_settings.png)

# How it Works

* The plug-in uses a Fullcalendar jQuery plug-in which uses ajax calls to fetch the events,which are the booked meeting rooms in Redmine by various employees.
* The calendar has a toggleable Moth view, Week view and Day view on the top right corner; of which the Week view is the default.
* The Week view has the span of the week written as the title along with the year.
* There is also a Go to date picker to take the user to a future date he/she wants to take a quick view.
* This also helps in reducing the clicks required to book a meeting room in some far future.
* There is also a drop down, populated with all the meeting rooms available at the time, to select whichever room a user wants to book a room.
* There is a quick jump Today button to take the user to the present day so that the status of a particular room for such a day could be viewed.
* Both the Week view and Day view exhibit a time line from 06:00 to 21:00 with the aid of which a meeting room can be booked at various time slots between 06:00 to 20:45, avoiding an overlap.
* Events could be booked also on a recurring basis. The available options are daily, weekly and bi-weekly, in which case the meeting room goes occupied for the specified time range.
* On the event of an overlap about to occur the calendar itself alerts the scheduler about the issue and in no case will it be possible to book an event ignoring the alert.
* The meeting rooms are booked with the currently logged in users authorship but can be assigned to another user.
* The main feature of the suggested plug-in is that knowing the Project Id and Issue tracker Id of the Book Meeting Project, the plug-in is stand alone in that no other files need to be edited in the actual project.
* For easy realization of the situation, the title bars of rooms booked by the presently logged in user is made different in color while displaying along with the others and marked with a wrench.
* Besides booking, a meeting room can also be edited; only by the author or the assigned person of the booking.
* The plug-in requires some details like project_id and tracker_id to be defined in the plugin configuration.

# Screenshots

![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/screenshot_index1.png)

![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/screenshot_add1.png)

![ScreenShot](https://raw.github.com/dro123/redmine_meeting_room_calendar/master/screenshots/screenshot_update_delete1.png)


text:
from __future__ import unicode_literals

import django
from django.test import TestCase

from data.filter.filter import DataFilter
from data.interface.interface import Interface
from data.interface.parameter import FileParameter, JsonParameter
from job.models import Job
from job.test import utils as job_test_utils
from recipe.definition.definition import RecipeDefinition
from recipe.instance.exceptions import InvalidRecipe
from recipe.instance.json.recipe_v6 import convert_recipe_to_v6_json, RecipeInstanceV6
from recipe.instance.recipe import RecipeInstance
from recipe.test import utils as recipe_test_utils

class TestRecipeInstanceV6(TestCase):

    def setUp(self):
        django.setup()

    def test_convert_recipe_to_v6_json_empty(self):
        """Tests calling convert_recipe_to_v6_json() with an empty recipe instance"""

        recipe = recipe_test_utils.create_recipe()
        definition = RecipeDefinition(Interface())
        recipe_instance = RecipeInstance(definition, recipe, [])
        json = convert_recipe_to_v6_json(recipe_instance)
        RecipeInstanceV6(json=json.get_dict(), do_validate=True)  # Revalidate
        self.assertDictEqual(json.get_dict()['nodes'], {})

    def test_convert_recipe_to_v6_json(self):
        """Tests calling convert_recipe_to_v6_json() successfully"""

        job_type_1 = job_test_utils.create_seed_job_type()
        job_type_2 = job_test_utils.create_seed_job_type()
        job_type_3 = job_test_utils.create_seed_job_type()
        job_type_4 = job_test_utils.create_seed_job_type()
        recipe_type_1 = recipe_test_utils.create_recipe_type_v6()

        interface = Interface()
        interface.add_parameter(FileParameter('file_param_1', ['image/gif']))
        interface.add_parameter(JsonParameter('json_param_1', 'object'))
        df1 = DataFilter(filter_list=[{'name': 'file_param_1', 'type': 'media-type', 'condition': '==', 'values': ['image/gif']},
                                      {'name': 'json_param_1', 'type': 'object', 'condition': 'superset of', 'values': [{}]}],
                        all=False)

        definition = RecipeDefinition(interface)
        definition.add_job_node('A', job_type_1.name, job_type_1.version, job_type_1.revision_num)
        definition.add_job_node('B', job_type_2.name, job_type_2.version, job_type_2.revision_num)
        definition.add_job_node('C', job_type_3.name, job_type_3.version, job_type_3.revision_num)
        definition.add_recipe_node('D', recipe_type_1.name, recipe_type_1.revision_num)
        definition.add_job_node('E', job_type_4.name, job_type_4.version, job_type_4.revision_num)
        definition.add_condition_node('F', interface, df1) #False
        definition.add_job_node('G', job_type_4.name, job_type_4.version, job_type_4.revision_num)
        definition.add_dependency('A', 'B')
        definition.add_dependency('A', 'C')
        definition.add_dependency('B', 'E')
        definition.add_dependency('C', 'D')
        definition.add_dependency('A', 'F')
        definition.add_dependency('F', 'G')
        definition.add_recipe_input_connection('A', 'input_1', 'file_param_1')
        definition.add_dependency_input_connection('B', 'b_input_1', 'A', 'a_output_1')
        definition.add_dependency_input_connection('C', 'c_input_1', 'A', 'a_output_2')
        definition.add_dependency_input_connection('D', 'd_input_1', 'C', 'c_output_1')
        definition.add_recipe_input_connection('D', 'd_input_2', 'json_param_1')

        recipe = recipe_test_utils.create_recipe()
        job_a = job_test_utils.create_job(job_type=job_type_1, status='COMPLETED', save=False)
        job_b = job_test_utils.create_job(job_type=job_type_2, status='RUNNING', save=False)
        job_c = job_test_utils.create_job(job_type=job_type_3, status='COMPLETED', save=False)
        job_e = job_test_utils.create_job(job_type=job_type_4, status='PENDING', num_exes=0, save=False)
        Job.objects.bulk_create([job_a, job_b, job_c, job_e])
        condition_f = recipe_test_utils.create_recipe_condition(is_processed=True, is_accepted=False, save=True)
        recipe_d = recipe_test_utils.create_recipe(recipe_type=recipe_type_1)
        recipe_node_a = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='A', job=job_a, save=False)
        recipe_node_b = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='B', job=job_b, save=False)
        recipe_node_c = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='C', job=job_c, save=False)
        recipe_node_d = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='D', sub_recipe=recipe_d,
                                                             save=False)
        recipe_node_e = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='E', job=job_e, save=False)
        recipe_node_f = recipe_test_utils.create_recipe_node(recipe=recipe, node_name='F', condition=condition_f,
                                                             save=False)
        recipe_nodes = [recipe_node_a, recipe_node_b, recipe_node_c, recipe_node_d, recipe_node_e, recipe_node_f]

        recipe_instance = RecipeInstance(definition, recipe, recipe_nodes)
        json = convert_recipe_to_v6_json(recipe_instance)
        RecipeInstanceV6(json=json.get_dict(), do_validate=True)  # Revalidate
        self.assertSetEqual(set(json.get_dict()['nodes'].keys()), {'A', 'B', 'C', 'D', 'E', 'F'})

    def test_init_validation(self):
        """Tests the validation done in __init__"""

        # Try minimal acceptable configuration
        RecipeInstanceV6(do_validate=True)

        # Invalid version
        json = {'version': 'BAD'}
        self.assertRaises(InvalidRecipe, RecipeInstanceV6, json, True)


text:
module Shoehorn
  class Image
     attr_accessor :imgurl, :index

     def initialize(imgurl, index)
       @imgurl = imgurl
       @index = index
     end

  end
end


text:
// [START earthengine__apidocs__ee_imagecollection_filterdate]
// A Landsat 8 TOA image collection intersecting a specific point.
var col = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(ee.Geometry.Point(-90.70, 34.71));

// Filter the collection by date using date strings.
print('2020 images', col.filterDate('2020', '2021'));
print('July images, 2020', col.filterDate('2020-07', '2020-08'));
print('Early July images, 2020', col.filterDate('2020-07-01', '2020-07-10'));
print('Include time (13 hours, July 7, 2020)',
      col.filterDate('2020-07-05T06:34:46', '2020-07-05T19:34:46'));

// Use milliseconds since Unix epoch.
print('Milliseconds inputs', col.filterDate(1593967014062, 1595349419611));

// Use ee.Date objects.
print('ee.Date inputs', col.filterDate(ee.Date('2020'), ee.Date('2021')));

// Use an ee.DateRange object.
var dateRange = ee.DateRange('2020-07-01', '2020-07-10');
print('ee.DateRange input', col.filterDate(dateRange));
// [END earthengine__apidocs__ee_imagecollection_filterdate]


text:
module a
end

module b
end module

module c
end module c

module d
  integer::i=3
  logical::l
  real::r
end module d

program t
  use d
  print *,i
end program t


text:
static std::mutex* aMutex;

void locking_function(int mode, int n, const char* file, int line)
{
    if(mode & CRYPTO_LOCK){
        aMutex[n].lock();
    }
    else{
        aMutex[n].unlock();
    }
}

unsigned long id_function()
{
    return (unsigned long)std::hash<std::thread::id>()   (std::this_thread::get_id());
}

int thread_setup()
{
    aMutex = new std::mutex[CRYPTO_num_locks()];
    curl_global_init(CURL_GLOBAL_ALL);

    if(!aMutex)
        return 0;
    else{
        CRYPTO_set_id_callback(id_function);
        CRYPTO_set_locking_callback(locking_function);
    }
    return 1;
}

int thread_cleanup()
{
    if(!aMutex)
        return 0;

    curl_global_cleanup();
    CRYPTO_set_id_callback(NULL);
    CRYPTO_set_locking_callback(NULL);
    delete[] aMutex;
    aMutex = NULL;
    return 1;
}

#endif // OPENSSLMULTITHREADED_H


text:
package io.rong.models.response;

import io.rong.models.Result;
import io.rong.models.group.GroupModel;
import io.rong.util.GsonUtil;

public class GroupMuteAllMembersListResult extends Result {
    public GroupMuteAllMembersListResult(Integer code, String errorMessage, GroupModel[] groups) {
        super(code, errorMessage);
        this.groups = groups;
    }

    private GroupModel[] groups;

    public GroupModel[] getGroups() {
        return groups;
    }

    public void setGroups(GroupModel[] groups) {
        this.groups = groups;
    }

    @Override
    public String toString() {
        return GsonUtil.toJson(this, GroupMuteAllMembersListResult.class);
    }
}


text:
import logging

import libsolace
from libsolace.Decorators import only_on_shutdown, only_if_not_exists, only_if_exists, primary, deprecation_warning
from libsolace.SolaceCommandQueue import SolaceCommandQueue
from libsolace.SolaceXMLBuilder import SolaceXMLBuilder
from libsolace.plugin import Plugin, PluginResponse
from libsolace.util import get_key_from_kwargs

@libsolace.plugin_registry.register
class SolaceQueue(Plugin):
    """Manage a Solace Queue

    Description
    ===========
        This plugin manages Queues within Solace. Typically you should invoke this plugin via L{SolaceAPI.SolaceAPI}.

        Please see L{plugin.Plugin} for how plugins are instantiated and used.
    """

    plugin_name = "SolaceQueue"

    # defaults should be provided from the settingsloader key
    defaults = {
        "retries": 0,
        "exclusive": "true",
        "queue_size": 1024,
        "consume": "all",
        "max_bind_count": 1000,
        "owner": "default"
    }

    def __init__(self, *args, **kwargs):
        """
        :param api: The instance of SolaceAPI if not called from SolaceAPI.manage
        :param queue_name: the queue name in Query mode
        :param queues: list of queue dictionaries with keys: name, queue_config
        :param vpn_name: name of the VPN to scope the ACL to
        :param defaults: dictionary of queue properties, see `defaults` in SolaceQueue class
        :type api: SolaceAPI
        :type queue_name: str
        :type vpn_name: str
        :type defaults: dict
        :returns: instance with batch requests on SolaceACLProfile.commands.commands
        :rtype: SolaceClientProfile

        Example:

        >>> api = SolaceAPI("dev")
        >>> sq = api.manage("SolaceQueue")
        >>> dict_queue = sq.get(vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> api.rpc(sq.max_bind_count(vpn_name="dev_testvpn", queue_name="testqueue1", max_bind_count=10))

        """
        self.api = get_key_from_kwargs("api", kwargs)
        self.commands = SolaceCommandQueue(version=self.api.version)
        kwargs.pop("api")

        if kwargs == {}:
            logging.info("Query Mode")
            return

        logging.info("Provision mode: %s" % kwargs)
        self.vpn_name = get_key_from_kwargs("vpn_name", kwargs, default="default")
        self.testmode = get_key_from_kwargs("testmode", kwargs, default=False)
        self.queues = get_key_from_kwargs("queues", kwargs, default={})
        self.shutdown_on_apply = get_key_from_kwargs("shutdown_on_apply", kwargs, default=False)
        self.defaults = get_key_from_kwargs('defaults', kwargs, default=self.defaults)
        self.options = None
        logging.info("Queues: %s" % self.queues)

        # backwards compatibility for None options passed to still execute "add" code
        if self.options is None:
            logging.warning(
                    "No options passed, assuming you meant 'add', please update usage of this class to pass a OptionParser instance")

            for queue in self.queues:

                queueName = queue['name']

                queue_config = self.get_queue_config(queue, **kwargs)
                self.create_queue(queue_name=queueName, **kwargs)
                self.shutdown_egress(queue_name=queueName, **kwargs)
                if queue_config['exclusive'].lower() == "true":
                    self.exclusive(queue_name=queueName, exclusive=True, **kwargs)
                else:
                    self.exclusive(queue_name=queueName, exclusive=False, **kwargs)
                self.owner(queue_name=queueName, owner_username=queue_config['owner'], **kwargs)
                self.max_bind_count(queue_name=queueName, max_bind_count=queue_config['max_bind_count'], **kwargs)
                self.consume(queue_name=queueName, consume=queue_config['consume'], **kwargs)
                self.spool_size(queue_name=queueName, queue_size=queue_config['queue_size'], **kwargs)
                self.retries(queue_name=queueName, retries=queue_config['retries'], **kwargs)
                self.reject_on_discard(queue_name=queueName, **kwargs)
                self.enable(queue_name=queueName, **kwargs)

    def get(self, **kwargs):
        """Fetch a queue from the appliance

        :type queue_name: str
        :type vpn_name: str
        :param queue_name: Queue name or filter
        :param vpn_name: name of the VPN
        :rtype: plugin.PluginResponse
        :returns: the queue(s)

        Examples:

        >>> api = SolaceAPI("dev")
        >>> list_queues = api.manage("SolaceQueue").get(queue_name='*', vpn_name='dev_testvpn')

        """
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        detail = get_key_from_kwargs("detail", kwargs, default=False)

        # if this request is not specifically targeted at the backup, default to primary
        if get_key_from_kwargs("backupOnly", kwargs, default=False) is False:
            kwargs["primaryOnly"] = True

        self.api.x = SolaceXMLBuilder("Querying Queue %s" % queue_name, version=self.api.version)
        self.api.x.show.queue.name = queue_name
        self.api.x.show.queue.vpn_name = vpn_name
        if detail:
            self.api.x.show.queue.detail
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return self.api.rpc(PluginResponse(str(self.api.x), **kwargs))

    def get_queue_config(self, queue, **kwargs):
        """ Returns a queue config for the queue and overrides where neccessary

        :param queue: single queue dictionary e.g.
            {
                "name": "foo",
                "env": [
                    "qa1": {
                        "queue_config": {
                            "retries": 0,
                            "exclusive": "false",
                            "queue_size": 1024,
                            "consume": "all",
                            "max_bind_count": 1000,
                            "owner": "dev_testuser"
                        }
                    }
                ]
            }

        """

        # get the queue name from the queue dictionary as passed to this method
        queue_name = get_key_from_kwargs("name", queue)

        try:
            logging.debug("Checking env overrides for queue %s" % queue['env'])
            for e in queue['env']:
                if e['name'] == self.api.environment:
                    logging.info('setting queue_config to environment %s values' % e['name'])
                    return self.__apply_default_config__(e['queue_config'], self.defaults)
        except:
            logging.warn("No environment overrides for queue %s" % queue_name)
            pass
        try:
            return self.__apply_default_config__(queue['queue_config'], self.defaults)
        except:
            logging.warning("No queue_config for queue: %s found, please check site-config" % queue_name)
            raise

    def __apply_default_config__(self, config, default):
        """ copys keys from default dict to config dict when not present """

        logging.info("Applying default config after config")

        final_config = {}

        for k, v in default.items():
            if k in config:
                logging.info("Using environment config key: %s to %s" % (k, config[k]))
                final_config[k] = config[k]
            else:
                logging.info("Using default config key: %s to %s" % (k, v))
                final_config[k] = v
        return final_config

    # perform the if_exists on the primary only
    @only_if_not_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def create_queue(self, **kwargs):
        """Create a queue / endpoint only if it doesnt exist.

        :param queue_name: the queue name
        :param vpn_name: the vpn name
        :type queue_name: str
        :type vpn_name: str
        :type: plugin.PluginResponse
        :returns: single SEMP request

        Example 1: Create Request, then Execute

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").create_queue(vpn_name="dev_testvpn", queue_name="my_test_queue")
        >>> # response = api.rpc(request)

        """
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        vpn_name = get_key_from_kwargs("vpn_name", kwargs)

        # Create a queue
        self.api.x = SolaceXMLBuilder("Creating Queue %s in vpn: %s" % (queue_name, vpn_name), version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.create.queue.name = queue_name
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        self.exists = True
        return PluginResponse(str(self.api.x), **kwargs)

    # perform the if_exists on the primary only
    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    # @only_on_shutdown('queue')
    @primary()
    def shutdown_egress(self, **kwargs):
        """Shutdown egress for a queue

        :param shutdown_on_apply: is shutdown permitted boolean or char
        :param vpn_name: name of the vpn
        :param queue_name: name of the queue
        :type shutdown_on_apply: char or bool
        :type queue_name: str
        :type vpn_name: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example 1: One Shot

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").shutdown_egress(shutdown_on_apply=True, vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> # response = api.rpc(request)

        Example 2: Create Request, then Execute

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").shutdown_egress(shutdown_on_apply=True, vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> # response = api.rpc(request)

        """

        shutdown_on_apply = get_key_from_kwargs("shutdown_on_apply", kwargs)
        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)

        if (shutdown_on_apply == 'b') or (shutdown_on_apply == 'q') or (shutdown_on_apply is True):
            # Lets only shutdown the egress of the queue
            self.api.x = SolaceXMLBuilder("Shutting down egress for queue:%s" % queue_name, version=self.api.version)
            self.api.x.message_spool.vpn_name = vpn_name
            self.api.x.message_spool.queue.name = queue_name
            self.api.x.message_spool.queue.shutdown.egress
            self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
            return PluginResponse(str(self.api.x), **kwargs)
        else:
            logging.warning("Not disabling Queue, commands could fail since shutdown_on_apply = %s" % shutdown_on_apply)

    # perform the if_exists on the primary only
    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    # @only_on_shutdown('queue')
    @primary()
    def shutdown_ingress(self, **kwargs):
        """Shutdown the ingress of a queue

        :param shutdown_on_apply: is shutdown permitted boolean or char
        :param vpn_name: name of the vpn
        :param queue_name: name of the queue
        :type shutdown_on_apply: char or bool
        :type queue_name: str
        :type vpn_name: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example 1: Instant Execution:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").shutdown_ingress(shutdown_on_apply=True, vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> # response = api.rpc(request)

        Example 2: Create Request, then Execute

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").shutdown_ingress(shutdown_on_apply=True, vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> # api.rpc(request)

        """

        shutdown_on_apply = get_key_from_kwargs("shutdown_on_apply", kwargs)
        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)

        if (shutdown_on_apply == 'b') or (shutdown_on_apply == 'q') or (shutdown_on_apply is True):
            # Lets only shutdown the egress of the queue
            self.api.x = SolaceXMLBuilder("Shutting down egress for queue:%s" % queue_name, version=self.api.version)
            self.api.x.message_spool.vpn_name = vpn_name
            self.api.x.message_spool.queue.name = queue_name
            self.api.x.message_spool.queue.shutdown.ingress
            self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
            return PluginResponse(str(self.api.x), **kwargs)
        else:
            logging.warning("Not disabling Queue, commands could fail since shutdown_on_apply = %s" % shutdown_on_apply)

    # perform the if_exists on the primary only
    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    # @only_on_shutdown('queue')
    @primary()
    def exclusive(self, **kwargs):
        """Set queue exclusivity

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param exclusive: state
        :type vpn_name: str
        :type queue_name: str
        :type exclusive: bool
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example: Shutdown, Set Exclusive, Start

        >>> api = SolaceAPI("dev")
        >>> requests = []
        >>> requests.append(api.manage("SolaceQueue").shutdown_ingress(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True))
        >>> requests.append(api.manage("SolaceQueue").exclusive(queue_name="testqueue1", vpn_name="dev_testvpn", exclusive=False, shutdown_on_apply=True))
        >>> requests.append(api.manage("SolaceQueue").enable(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True))
        >>> # [api.rpc(x) for x in requests]

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        exclusive = get_key_from_kwargs("exclusive", kwargs)

        # Default to NON Exclusive queue
        if not exclusive:
            self.api.x = SolaceXMLBuilder("Set Queue %s to Non Exclusive " % queue_name, version=self.api.version)
            self.api.x.message_spool.vpn_name = vpn_name
            self.api.x.message_spool.queue.name = queue_name
            self.api.x.message_spool.queue.access_type.non_exclusive
        else:
            # Non Exclusive queue
            self.api.x = SolaceXMLBuilder("Set Queue %s to Exclusive " % queue_name, version=self.api.version)
            self.api.x.message_spool.vpn_name = vpn_name
            self.api.x.message_spool.queue.name = queue_name
            self.api.x.message_spool.queue.access_type.exclusive
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    # @only_on_shutdown('queue')
    @primary()
    def owner(self, **kwargs):
        """ Set the owner

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param owner: the owner client-username
        :type vpn_name: str
        :type queue_name: str
        :type owner: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> requests = []
        >>> requests.append(api.manage("SolaceQueue").shutdown_ingress(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True))
        >>> requests.append(api.manage("SolaceQueue").shutdown_egress(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True))
        >>> requests.append(api.manage("SolaceQueue").owner(vpn_name="dev_testvpn", queue_name="testqueue1", owner_username="dev_testproductA"))
        >>> requests.append(api.manage("SolaceQueue").enable(queue_name="testqueue1", vpn_name="dev_testvpn"))
        >>> # [api.rpc(x) for x in requests]

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        owner = get_key_from_kwargs("owner_username", kwargs)

        if owner == "%lsVPN":
            owner = vpn_name
            logging.info("Owner being set  to VPN itself: %s" % owner)

        # Queue Owner
        self.api.x = SolaceXMLBuilder("Set Queue %s owner to %s" % (queue_name, vpn_name), version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.owner.owner = owner
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def max_bind_count(self, **kwargs):
        """Limit the max bind count

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param max_bind_count: max bind count
        :type vpn_name: str
        :type queue_name: str
        :type max_bind_count: int
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> requests = api.manage("SolaceQueue").max_bind_count(vpn_name="dev_testvpn", queue_name="testqueue1", max_bind_count=50)
        >>> # response = api.rpc(requests)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        max_bind_count = get_key_from_kwargs("max_bind_count", kwargs)

        self.api.x = SolaceXMLBuilder("Settings Queue %s max bind count to %s" % (queue_name, str(max_bind_count)),
                                      version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.max_bind_count.value = max_bind_count
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True, backupOnly=False)
    # @only_on_shutdown('queue')
    @primary()
    @deprecation_warning("Please implement the use of the 'permission' method instead of relying on this")
    def consume(self, **kwargs):
        """Sets consume permission. add `consume` kwarg to allow non-owner users to consume.

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param consume: set to "all" to allow ALL appliance client-users to "consume"
        :type vpn_name: str
        :type queue_name: str
        :type consume: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request
        .. deprecated:: 2.0
             Use :func:`permission` instead.

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").consume(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True, consume="all")
        >>> # response = api.rpc(request)
        ""

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        consume = get_key_from_kwargs("consume", kwargs)

        # Open Access
        self.api.x = SolaceXMLBuilder("Settings Queue %s Permission to Consume" % queue_name, version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        if consume == "all":
            self.api.x.message_spool.queue.permission.all
        self.api.x.message_spool.queue.permission.consume
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True, backupOnly=False)
    # @only_on_shutdown('queue')
    @primary()
    def permission(self, **kwargs):
        """Sets permission on a queue

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param permission: which permission to grant non-owner users. e.g. "consume", "delete", "modify-topic", "read-only"
        :type vpn_name: str
        :type queue_name: str
        :type permission: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").permission(queue_name="testqueue1", vpn_name="dev_testvpn", shutdown_on_apply=True, permission="consume")
        >>> # api.rpc(request)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        permission = get_key_from_kwargs("permission", kwargs)

        # Open Access
        self.api.x = SolaceXMLBuilder("Settings Queue %s Permission to %s" % (queue_name, permission),
                                      version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.permission.all
        if permission == "consume":
            self.api.x.message_spool.queue.permission.consume
        elif permission == "delete":
            self.api.x.message_spool.queue.permission.delete
        elif permission == "modify-topic":
            self.api.x.message_spool.queue.permission.modify_topic
        elif permission == "read-only":
            self.api.x.message_spool.queue.permission.read_only
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def spool_size(self, **kwargs):
        """Set the spool size

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param queue_size: size of the spool in mb
        :type vpn_name: str
        :type queue_name: str
        :type queue_size: int
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").spool_size(vpn_name="dev_testvpn", queue_name="testqueue1", queue_size=64)
        >>> # response = api.rpc(request)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        queue_size = get_key_from_kwargs("queue_size", kwargs)

        # Configure Queue Spool Usage
        self.api.x = SolaceXMLBuilder("Set Queue %s spool size: %s" % (queue_name, queue_size),
                                      version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.max_spool_usage.size = queue_size
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def retries(self, **kwargs):
        """Delivery retries before failing the message

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :param retries: number of retries
        :type vpn_name: str
        :type queue_name: str
        :type retries: int
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").retries(vpn_name="dev_testvpn", queue_name="testqueue1", retries=5)
        >>> # response = api.rpc(request)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)
        retries = get_key_from_kwargs("retries", kwargs, default=0)

        self.api.x = SolaceXMLBuilder("Tuning max-redelivery retries for %s to %s" % (queue_name, retries),
                                      version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.max_redelivery.value = retries
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def enable(self, **kwargs):
        """Enable a the queue

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :type vpn_name: str
        :type queue_name: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").enable(queue_name="testqueue1", vpn_name="dev_testvpn")
        >>> # response = api.rpc(request)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)

        # Enable the Queue
        self.api.x = SolaceXMLBuilder("Enabling Queue %s" % queue_name, version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.no.shutdown.full
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)

    @only_if_exists('get', 'rpc-reply.rpc.show.queue.queues.queue.info', primaryOnly=True)
    @primary()
    def reject_on_discard(self, **kwargs):
        """ Reject to sender on discard

        :param vpn_name: the name of the vpn
        :param queue_name: the queue name
        :type vpn_name: str
        :type queue_name: str
        :rtype: plugin.PluginResponse
        :returns: single SEMP request

        Example:

        >>> api = SolaceAPI("dev")
        >>> request = api.manage("SolaceQueue").reject_on_discard(vpn_name="dev_testvpn", queue_name="testqueue1")
        >>> # response = api.rpc(request)

        """

        vpn_name = get_key_from_kwargs("vpn_name", kwargs)
        queue_name = get_key_from_kwargs("queue_name", kwargs)

        self.api.x = SolaceXMLBuilder("Setting Queue to Reject Drops", version=self.api.version)
        self.api.x.message_spool.vpn_name = vpn_name
        self.api.x.message_spool.queue.name = queue_name
        self.api.x.message_spool.queue.reject_msg_to_sender_on_discard
        self.commands.enqueue(PluginResponse(str(self.api.x), **kwargs))
        return PluginResponse(str(self.api.x), **kwargs)


text:
package org.jrebirth.af.showcase.fxml.ui.embedded;

import java.net.URL;
import java.util.ResourceBundle;

import org.jrebirth.af.api.ui.View;
import org.jrebirth.af.core.ui.fxml.AbstractFXMLController;

public class EmbeddedFXMLController extends AbstractFXMLController<EmbeddedModel, View<EmbeddedModel, ?, ?>> {

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(final URL url, final ResourceBundle resource) {

    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no" />
  <title>COIES 2017</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link href="css/styles.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">

  <link rel="icon" href="img/logo.png">

Inicio

Temáticas

Comités

Conferencistas

Programa

Fechas e Inscripción

Resúmenes

Workshop

Bucaramanga

Inicio

Temáticas

Comités

Conferencistas

Programa

Fechas e Inscripción

Resúmenes

Workshop

Bucaramanga

      menu

Conferencistas

Professor Daniel
Tartakovsky

Stanford University

USA

Professor Christine
Ehlig-Economides

Houston University

USA

Professor Juliet
Newson

Reykjavik University

Iceland

Professor Khamid
Mahkamov

Northumbria University

England, UK

Professor Jirí Jaromir
Klemes

Manchester University
Brno University

Czech Republic

Professor Antonio
Zuorro

Sapienza Universitá di Roma

Italy

Professor Erenio
González Suárez

Central University of the Villas

Cuba

Professor Dorothée
Laurenti.

"Catalytic conversion of micro-algae, lignin or lignocellulose for various applications"

University of Lyon

France

Professor Mickael
Capron

"Biomass valorization through the transformation of alcohols into chemicals"

University of Science and Technology of Lille

France

Professor María Teresa
Caldes Ricos

"Using aberration-corrected electron microscopy for energy materials characterisation"

University of Nantes

France

Professor Liliana
Mogni

"Modificacion de superficie de electrodos para celdas SOFC por decorado con nanoparticulas"

National University of Cuyo

Argentina

Professor Pascal
Fongarland

"Evolution of Cobalt active phases during Fischer-Tropsch synthesis: caracterisation"

Claude Bernard University Lyon I

France


text:
export class TokenValidationConfig {
    static timeoutInSeconds = 3600;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Phrase-Zoomer-Inner</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="title_activity_display_message">My Message</string>
    <string name="hello_world">Hello world!</string>

</resources>


text:
WAMP Specification
==================

Bonefish is based on a set of open-source specifications for WAMP application servers. The specification is split into two parts:

- [**Basic**](https://github.com/tavendo/WAMP/blob/master/spec/basic.md)
- [**Advanced**](https://github.com/tavendo/WAMP/blob/master/spec/advanced.md)

## Basic

The basic specification contains all of the architectural overview, fundamental building blocks, and definitions necessary to build a minimally complete WAMP application server. It acts as a software design reference for bonefish. If you want to get an understanding of the basic operation of a WAMP application server this is a good starting point.

## Advanced

The advanced specification is basically a document that details the extentions and features that can be built on top of the basic profile.


text:
from ..simu import *

# Add each new received buffer to a list of buffers
class NumpySink(GenericSink):
    def __init__(self,inputSize,fifoin,matplotlibBuffer):
        GenericSink.__init__(self,inputSize,fifoin)
        self._bufPos=0
        self._buffer=matplotlibBuffer

    def run(self):
        b=self.getReadBuffer()
        buf = np.zeros(self._inputSize)
        buf[:] = b[:]
        self._buffer.append(buf)

        return(0)


text:
#ifndef CRYPT_WRAPPER_H
#define CRYPT_WRAPPER_H

NSPR_BEGIN_EXTERN_C

NSAPI_PUBLIC extern void ACL_CryptCritInit(void);
NSAPI_PUBLIC extern char *ACL_Crypt(const char *key, const char *salt);
NSAPI_PUBLIC extern int ACL_CryptCompare(const char *key, const char *salt, const char *encrypted);

NSPR_END_EXTERN_C

#endif


text:
package io.quarkus.it.panache;

import java.io.Serializable;
import java.util.Objects;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;

import io.quarkus.hibernate.orm.panache.PanacheEntityBase;

@Entity
@IdClass(ObjectWithCompositeId.ObjectKey.class)
public class ObjectWithCompositeId extends PanacheEntityBase {
    @Id
    public String part1;
    @Id
    public String part2;
    public String description;

    static class ObjectKey implements Serializable {
        private String part1;
        private String part2;

        public ObjectKey() {
        }

        public ObjectKey(String part1, String part2) {
            this.part1 = part1;
            this.part2 = part2;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;
            ObjectKey objectKey = (ObjectKey) o;
            return part1.equals(objectKey.part1) &&
                    part2.equals(objectKey.part2);
        }

        @Override
        public int hashCode() {
            return Objects.hash(part1, part2);
        }
    }
}


text:
#import <UIKit/UIKit.h>
#import "APCBaseGraphView.h"

FOUNDATION_EXPORT NSString * const kAPCLineGraphViewTriggerAnimationsNotification;
FOUNDATION_EXPORT NSString * const kAPCLineGraphViewRefreshNotification;

@protocol APCLineGraphViewDataSource;
@protocol APCLineGraphViewDelegate;

@interface APCLineGraphView : APCBaseGraphView

@property (nonatomic, weak) IBOutlet id <APCLineGraphViewDataSource> datasource;

@property (nonatomic, strong) UIView *plotsView;
@property (nonatomic) BOOL smoothLines;
@property (nonatomic) BOOL showsFillPath;

@end

@protocol APCLineGraphViewDataSource <NSObject>

@required

- (NSInteger)lineGraph:(APCLineGraphView *)graphView numberOfPointsInPlot:(NSInteger)plotIndex;

- (CGFloat)lineGraph:(APCLineGraphView *)graphView plot:(NSInteger)plotIndex valueForPointAtIndex:(NSInteger)pointIndex;

@optional

- (NSInteger)numberOfPlotsInLineGraph:(APCLineGraphView *)graphView;

- (NSInteger)numberOfDivisionsInXAxisForGraph:(APCLineGraphView *)graphView;

- (CGFloat)maximumValueForLineGraph:(APCLineGraphView *)graphView;

- (CGFloat)minimumValueForLineGraph:(APCLineGraphView *)graphView;

- (NSString *)lineGraph:(APCLineGraphView *)graphView titleForXAxisAtIndex:(NSInteger)pointIndex;

@end


text:
package textbackend

import (
	"testing"
)

// tests

func Test_TextRow_NewTextRow(t *testing.T) {
	row := NewTextRow(1, "hello world")
	if row.GetLevel() != 1 {
		t.Error("TextRow.GetLevel() not equal")
	}
	if row.GetText() != "hello world" {
		t.Error("TextRow.GetText() not equal")
	}
	if row.GetTextLength() != 11 {
		t.Error("TextRow.GetTextLength() not equal")
	}
}

var testTableNewTextRowFromString = []struct {
	text          string
	ws            string
	expectedLevel uint8
	expectedText  string
}{
	{"hello", "\t", 0, "hello"},
	{"\t\thello", "\t", 2, "hello"},
	{"\t\thello world", "\t", 2, "hello world"},
	{"\t\thello\tworld", "\t", 2, "hello\tworld"},
	{"\t\t hello\tcrazy\tworld\t", "\t", 2, " hello\tcrazy\tworld\t"},
}

func Test_TextRow_NewTextRowFromString(t *testing.T) {
	for k, tt := range testTableNewTextRowFromString {
		row := NewTextRowFromString(tt.text, tt.ws)
		if row.Level != tt.expectedLevel {
			t.Error(k, "NewTextRowFromString Level not equal")
		}
		if row.Text != tt.expectedText {
			t.Error(k, "NewTextRowFromString Text not equal")
		}
	}
}

func Test_TextRow_GetLevelWhitespace(t *testing.T) {
	textRow := TextRow{}
	textRow.Level = 1
	if textRow.GetLevelWhitespace("\t") != "\t" {
		t.Error("GetLevelWhitespace failed")
	}
	textRow.Level = 3
	if textRow.GetLevelWhitespace("\t") != "\t\t\t" {
		t.Error("GetLevelWhitespace failed")
	}
}

func Test_TextRow_GetString(t *testing.T) {
	textRow := NewTextRow(0, "hello world")
	if textRow.GetString("\t") != "hello world" {
		t.Error("GetString failed")
	}
	textRow2 := NewTextRow(1, "hello world")
	if textRow2.GetString("\t") != "\thello world" {
		t.Error("GetString failed")
	}
}

func Test_TextRow_AppendText(t *testing.T) {
	row := NewTextRow(0, "hello")
	row.AppendText(" world")
	if row.GetText() != "hello world" {
		t.Error("AppendText failed")
	}
}

func Test_TextRow_EqualTo(t *testing.T) {
	row := NewTextRow(0, "hello")
	if row.EqualTo("hello") == false {
		t.Error("TextRow.TextEqualTo() not equal, expected true")
	}
	if row.EqualTo("hello broken") == true {
		t.Error("TextRow.TextEqualTo() not equal, expected false")
	}
}

// benchmarks

var resultTextRow string

func benchmarkTextRow(l uint8, c string, b *testing.B) {
	var r string
	for n := 0; n < b.N; n++ {
		row := NewTextRow(l, c)
		r = row.GetString("<br>")
	}
	resultTextRow = r
}

func Benchmark_TextRow_level4(b *testing.B) {
	benchmarkTextRow(4, "hello world", b)
}
func Benchmark_TextRow_level8(b *testing.B) {
	benchmarkTextRow(8, "hello world", b)
}
func Benchmark_TextRow_level16(b *testing.B) {
	benchmarkTextRow(16, "hello world", b)
}
func Benchmark_TextRow_small(b *testing.B) {
	benchmarkTextRow(2, "hello world", b)
}
func Benchmark_TextRow_middle(b *testing.B) {
	benchmarkTextRow(2, "hello world, this is just a test", b)
}
func Benchmark_TextRow_large(b *testing.B) {
	benchmarkTextRow(2, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", b)
}


text:
package com.miguelgaeta.media_picker;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Miguel Gaeta on 2/11/16.
 */
class MediaPickerChooser {

    /**
     * Gets an chooser intent that attempts to discover all activities on
     * the device that can be used to select media.
     *
     * @param packageManager Device {@link PackageManager}.
     * @param chooserTitle Title for the chooser.
     * @param captureFileURI Capture result URI for camera.
     *
     * @return Chooser {@link Intent}
     *
     * @throws IOException
     */
    static Intent getMediaChooserIntent(final @NonNull PackageManager packageManager,
                                        final @NonNull String chooserTitle,
                                        final @NonNull Uri captureFileURI,
                                        final @NonNull String mimeType) throws IOException {

        final Collection<Intent> intents = getMediaActivityIntents(packageManager, captureFileURI, mimeType);

        if (intents.isEmpty()) {

            throw new IOException("No media applications available on this device.");
        }

        final Iterator<Intent> iterator = intents.iterator();

        final Intent firstIntent = iterator.next();

        final List<Intent> remainingIntents = new ArrayList<>();

        while (iterator.hasNext()) {

            remainingIntents.add(iterator.next());
        }

        final Intent chooserIntent = Intent.createChooser(firstIntent, chooserTitle);

        if (!remainingIntents.isEmpty()) {

            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, remainingIntents.toArray(new Parcelable[remainingIntents.size()]));
        }

        return chooserIntent;
    }

    /**
     * Find a collection of all matching media intents on the device.
     *
     * @param packageManager Device {@link PackageManager}.
     * @param captureFileURI Capture result URI for camera.
     *
     * @return Collection of media activity intents.
     */
    private static Collection<Intent> getMediaActivityIntents(final @NonNull PackageManager packageManager,
                                                              final @NonNull Uri captureFileURI,
                                                              final @NonNull String mimeType) {

        final Intent typeCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
            .putExtra(MediaStore.EXTRA_OUTPUT, captureFileURI)
            .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        final Intent typeGallery = MediaPicker.getIntent(Intent.ACTION_PICK, mimeType);
        final Intent typeDocuments = MediaPicker.getIntent(Intent.ACTION_GET_CONTENT, mimeType);

        final Map<String, Intent> intents = new LinkedHashMap<>();

        getIntentActivities(intents, packageManager, typeDocuments, null);
        getIntentActivities(intents, packageManager, typeGallery, null);
        getIntentActivities(intents, packageManager, typeCamera, new IntentModifier() {

            @Override
            public void onFoundIntent(Intent intent) {

                intent.putExtra(MediaStore.EXTRA_OUTPUT, captureFileURI);
            }
        });

        return intents.values();
    }

    /**
     * Given a filter, create a list of all matching activities and
     * return them as a list of intents.
     *
     * @param packageManager Device {@link PackageManager}.
     * @param filterIntent Filter by {@link Intent}.
     * @param modifier Callback to modify each matched {@link Intent}.
     */
    private static void getIntentActivities(final @NonNull Map<String, Intent> intents,
                                            final @NonNull PackageManager packageManager,
                                            final @NonNull Intent filterIntent,
                                            final @Nullable IntentModifier modifier) {

        for (final ResolveInfo resolveInfo : packageManager.queryIntentActivities(filterIntent, 0)) {

            final ComponentName componentName = new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
            final Intent intent = new Intent(filterIntent);

            intent.setComponent(componentName);
            intent.setPackage(resolveInfo.activityInfo.packageName);

            if (modifier != null) {
                modifier.onFoundIntent(intent);
            }

            intents.put(resolveInfo.activityInfo.packageName, intent);
        }
    }

    private interface IntentModifier {

        void onFoundIntent(final Intent intent);
    }
}


text:
package com.communote.plugins.api.rest.v24.resource.validation;

/**
 * abstract class, defining validator for the rest parameters. To be implemented for each resource,
 * that need to verify its parameters.
 *
 * Appropriate method is invoked during the request processing. In order to tell that some errors
 * have been occurred, the method implementation is supposed to throw ParameterValidationException.
 * The exception includes list of all the errors, that could have been discovered
 *
 * @author Communote GmbH - http://www.communote.com/
 *
 * @param <C>
 *            create resource parameter
 * @param <E>
 *            edit resource parameter
 * @param <D>
 *            delete resource parameter
 * @param <G>
 *            get resource parameter
 * @param <L>
 *            list resource parameter
 */
public abstract class Validator<C, E, D, G, L> {

    /**
     * validates create parameter
     *
     * @param createPrameter
     *            parameter to be validated
     * @throws ParameterValidationException
     *             is thrown if validation fails
     */
    public abstract void validateCreate(C createPrameter) throws ParameterValidationException;

    /**
     * validates delete parameter
     *
     * @param deletePrameter
     *            parameter to be validated
     * @throws ParameterValidationException
     *             is thrown if validation fails
     */
    public abstract void validateDelete(D deletePrameter) throws ParameterValidationException;;

    /**
     * validates edit parameter
     *
     * @param editPrameter
     *            parameter to be validated
     * @throws ParameterValidationException
     *             is thrown if validation fails
     */
    public abstract void validateEdit(E editPrameter) throws ParameterValidationException;;

    /**
     * validates get parameter
     *
     * @param getSinglePrameter
     *            parameter to be validated
     * @throws ParameterValidationException
     *             is thrown if validation fails
     */
    public abstract void validateGetSingle(G getSinglePrameter) throws ParameterValidationException;;

    /**
     * validates list parameter
     *
     * @param listPrameter
     *            parameter to be validated
     * @throws ParameterValidationException
     *             is thrown if validation fails
     */
    public abstract void validateList(L listPrameter) throws ParameterValidationException;;
}


text:
import cPickle

from IPython.parallel import Client

from synth_harness import parse_cmd_line_args
from pyglm.models.model_factory import make_model
from population import Population

def load_data(options):
    # Load data
    if not options.dataFile is None:
        if options.dataFile.endswith('.mat'):
            print "Loading data from %s" % options.dataFile
            #data = scipy.io.loadmat(options.dataFile)
            # Scipy's IO is weird -- we can save dicts as structs but its hard to reload them
            raise Exception('Loading from .mat file is not implemented!')
        elif options.dataFile.endswith('.pkl'):
            print "Loading data from %s" % options.dataFile
            with open(options.dataFile,'r') as f:
                data = cPickle.load(f)
        else:
            raise Exception("Unrecognized file type: %s" % options.dataFile)

    else:
        raise Exception("Data is required for parallel MAP")

    return data

def load_imports_on_client(dview):
    """ Import required modules on client
    """
    dview.execute('from population import Population')
    dview.execute('popn = None')

def initialize_client(model, data):
    """ Initialize a population objsect on the client
    """
    # Initialize a model with N neurons
    print "Initializing GLM"
    global popn
    popn = Population(model)

    # Initialize the GLM with the data
    popn.set_data(data)

def run_parallel_map():
    """ Run a test with synthetic data and MCMC inference
    """
    # Parse command line args
    (options, args) = parse_cmd_line_args()

    # Load the data
    data = load_data(options)
    # Get a model for the data
    model_type = 'standard_glm'
    model = make_model(model_type, N=data['N'])

    # Get parallel clients
    rc = Client(profile="sge")
    dview = rc[:]
    # dview = get_engines(n_workers=8)

    # Load imports on the client
    load_imports_on_client(dview)

    # Initialize population objects on the clients
    dview.apply_sync(initialize_client, (model_type,N,data))

    ## Sample random initial state
    #x0 = population.sample()
    #ll0 = population.compute_log_p(x0)
    #print "LL0: %f" % ll0
    #
    ## Perform inference
    #x_inf = coord_descent(population, data, x0=x0, maxiter=1,
    #                      use_hessian=False,
    #                      use_rop=False)
    #ll_inf = population.compute_log_p(x_inf)
    #print "LL_inf: %f" % ll_inf
    #
    ## TODO Save results
    #
    ## Plot results
    #plot_results(population, x_inf, x_true)

if __name__ == "__main__":
    run_parallel_map()


text:
import {
  Cartesian2,
  Cartesian3,
  Math as CesiumMath,
  MetadataClass,
  MetadataEntity,
} from "../../index.js";

describe("Scene/MetadataEntity", function () {
  let classWithNoPropertiesDefinition;
  let classDefinition;
  let properties;
  let classWithNoDataValues;
  beforeAll(function () {
    classWithNoPropertiesDefinition = new MetadataClass({
      id: "building",
      class: {},
    });

    classDefinition = new MetadataClass({
      id: "building",
      class: {
        properties: {
          name: {
            type: "STRING",
            semantic: "NAME",
            required: true,
          },
          height: {
            type: "SCALAR",
            componentType: "FLOAT32",
            required: false,
            default: 10.0,
          },
          position: {
            type: "SCALAR",
            componentType: "FLOAT32",
            array: true,
            count: 3,
            required: true,
          },
          axisColors: {
            array: true,
            count: 3,
            type: "VEC3",
            componentType: "UINT8",
            normalized: true,
            required: true,
          },
          temperature: {
            type: "SCALAR",
            componentType: "UINT8",
            normalized: true,
            offset: 32,
            scale: 180,
          },
          temperatureArray: {
            array: true,
            count: 4,
            type: "SCALAR",
            componentType: "UINT8",
            normalized: true,
            offset: [32, 32, 32, 32],
            scale: [180, 180, 180, 180],
          },
        },
      },
    });

    classWithNoDataValues = new MetadataClass({
      id: "noData",
      class: {
        properties: {
          noDefault: {
            type: "SCALAR",
            componentType: "INT32",
            required: false,
            noData: -1,
          },
          hasDefault: {
            type: "SCALAR",
            componentType: "INT32",
            required: false,
            noData: -1,
            default: 100,
          },
          noDefaultVector: {
            type: "VEC2",
            componentType: "FLOAT32",
            required: false,
            noData: [0.0, 0.0],
          },
          hasDefaultVector: {
            type: "VEC2",
            componentType: "FLOAT32",
            required: false,
            noData: [0.0, 0.0],
            default: [100.0, 100.0],
          },
          noDefaultArray: {
            array: true,
            type: "SCALAR",
            componentType: "UINT8",
            count: 3,
            required: false,
            noData: [0, 0, 0],
          },
          hasDefaultArray: {
            array: true,
            type: "SCALAR",
            componentType: "UINT8",
            required: false,
            noData: [],
            default: [1, 1, 1],
          },
          noDefaultArrayOfVector: {
            array: true,
            type: "VEC2",
            componentType: "FLOAT32",
            count: 3,
            required: false,
            noData: [
              [0.0, 0.0],
              [0.0, 0.0],
              [0.0, 0.0],
            ],
          },
          hasDefaultArrayOfVector: {
            array: true,
            type: "VEC2",
            componentType: "FLOAT32",
            required: false,
            noData: [],
            default: [
              [1.0, 1.0],
              [1.0, 1.0],
            ],
          },
        },
      },
    });
  });

  beforeEach(function () {
    properties = {
      name: "Building A",
      position: [0.0, 0.0, 0.0],
      axisColors: [
        [255, 0, 0],
        [0, 255, 0],
        [0, 0, 255],
      ],
      temperature: 0,
      temperatureArray: [0, 255, 255, 0],
    };
  });

  const noDataProperties = {
    noDefault: -1,
    hasDefault: -1,
    noDefaultVector: [0.0, 0.0],
    hasDefaultVector: [0.0, 0.0],
    noDefaultArray: [0, 0, 0],
    hasDefaultArray: [],
    noDefaultArrayOfVector: [
      [0.0, 0.0],
      [0.0, 0.0],
      [0.0, 0.0],
    ],
    hasDefaultArrayOfVector: [],
  };

  it("throws when using MetadataEntity directly", function () {
    const entity = new MetadataEntity();
    expect(function () {
      return entity.class;
    }).toThrowDeveloperError();
    expect(function () {
      entity.hasProperty();
    }).toThrowDeveloperError();
    expect(function () {
      entity.hasPropertyBySemantic();
    }).toThrowDeveloperError();
    expect(function () {
      entity.getPropertyIds();
    }).toThrowDeveloperError();
    expect(function () {
      entity.getProperty();
    }).toThrowDeveloperError();
    expect(function () {
      entity.setProperty();
    }).toThrowDeveloperError();
    expect(function () {
      entity.getPropertyBySemantic();
    }).toThrowDeveloperError();
    expect(function () {
      entity.setPropertyBySemantic();
    }).toThrowDeveloperError();
  });

  it("hasProperty returns false when there are no properties", function () {
    expect(
      MetadataEntity.hasProperty("name", {}, classWithNoPropertiesDefinition)
    ).toBe(false);
  });

  it("hasProperty returns false when there's no property with the given property ID", function () {
    expect(
      MetadataEntity.hasProperty("volume", properties, classDefinition)
    ).toBe(false);
  });

  it("hasProperty returns true when there's a property with the given property ID", function () {
    expect(
      MetadataEntity.hasProperty("name", properties, classDefinition)
    ).toBe(true);
  });

  it("hasProperty returns true when the class has a default value for a missing property", function () {
    expect(
      MetadataEntity.hasProperty("height", properties, classDefinition)
    ).toBe(true);
  });

  it("hasProperty throws without propertyId", function () {
    expect(function () {
      MetadataEntity.hasProperty(undefined, properties, classDefinition);
    }).toThrowDeveloperError();
  });

  it("hasProperty throws without properties", function () {
    expect(function () {
      MetadataEntity.hasProperty("name", undefined, classDefinition);
    }).toThrowDeveloperError();
  });

  it("hasProperty throws without classDefinition", function () {
    expect(function () {
      MetadataEntity.hasProperty("name", properties, undefined);
    }).toThrowDeveloperError();
  });

  it("hasPropertyBySemantic returns false when there's no properties", function () {
    expect(
      MetadataEntity.hasPropertyBySemantic(
        "NAME",
        {},
        classWithNoPropertiesDefinition
      )
    ).toBe(false);
  });

  it("hasPropertyBySemantic returns false when there's no property with the given property ID", function () {
    expect(
      MetadataEntity.hasPropertyBySemantic(
        "VOLUME",
        properties,
        classDefinition
      )
    ).toBe(false);
  });

  it("hasPropertyBySemantic returns true when there's a property with the given property ID", function () {
    expect(
      MetadataEntity.hasPropertyBySemantic("NAME", properties, classDefinition)
    ).toBe(true);
  });

  it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function () {
    expect(
      MetadataEntity.hasPropertyBySemantic("NAME", properties, classDefinition)
    ).toBe(true);
  });

  it("hasPropertyBySemantic throws without semantic", function () {
    expect(function () {
      MetadataEntity.hasPropertyBySemantic(
        undefined,
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("hasPropertyBySemantic throws without properties", function () {
    expect(function () {
      MetadataEntity.hasPropertyBySemantic("NAME", undefined, classDefinition);
    }).toThrowDeveloperError();
  });

  it("hasPropertyBySemantic throws without class definition", function () {
    expect(function () {
      MetadataEntity.hasPropertyBySemantic("NAME", properties, undefined);
    }).toThrowDeveloperError();
  });

  it("getPropertyIds returns empty array when there are no properties", function () {
    expect(
      MetadataEntity.getPropertyIds({}, classWithNoPropertiesDefinition).length
    ).toBe(0);
  });

  it("getPropertyIds returns array of property IDs", function () {
    // Includes height which has a default value
    expect(
      MetadataEntity.getPropertyIds(properties, classDefinition).sort()
    ).toEqual([
      "axisColors",
      "height",
      "name",
      "position",
      "temperature",
      "temperatureArray",
    ]);
  });

  it("getPropertyIds uses results argument", function () {
    const results = [];
    const returnedResults = MetadataEntity.getPropertyIds(
      properties,
      classDefinition,
      results
    );

    expect(results).toBe(returnedResults);
    expect(results.sort()).toEqual([
      "axisColors",
      "height",
      "name",
      "position",
      "temperature",
      "temperatureArray",
    ]);
  });

  it("getPropertyIds throws without properties", function () {
    expect(function () {
      MetadataEntity.getPropertyIds(undefined, classDefinition);
    }).toThrowDeveloperError();
  });

  it("getPropertyIds throws without classDefinition", function () {
    expect(function () {
      const results = [];
      MetadataEntity.getPropertyIds(properties, undefined, results);
    }).toThrowDeveloperError();
  });

  it("getProperty throws when there's no property with the given property ID", function () {
    expect(function () {
      return MetadataEntity.getProperty("volume", properties, classDefinition);
    }).toThrowDeveloperError();
  });

  it("getProperty returns the property value", function () {
    const value = MetadataEntity.getProperty(
      "position",
      properties,
      classDefinition
    );
    expect(value).toEqual(properties.position);
  });

  it("getProperty returns the default value when the property is missing", function () {
    expect(
      MetadataEntity.getProperty("height", properties, classDefinition)
    ).toBe(10.0);
  });

  it("getProperty handles noData correctly", function () {
    expect(
      MetadataEntity.getProperty(
        "noDefault",
        noDataProperties,
        classWithNoDataValues
      )
    ).not.toBeDefined();
    expect(
      MetadataEntity.getProperty(
        "hasDefault",
        noDataProperties,
        classWithNoDataValues
      )
    ).toBe(100);
    expect(
      MetadataEntity.getProperty(
        "noDefaultVector",
        noDataProperties,
        classWithNoDataValues
      )
    ).not.toBeDefined();
    expect(
      MetadataEntity.getProperty(
        "hasDefaultVector",
        noDataProperties,
        classWithNoDataValues
      )
    ).toEqual(new Cartesian2(100.0, 100.0));
    expect(
      MetadataEntity.getProperty(
        "noDefaultArray",
        noDataProperties,
        classWithNoDataValues
      )
    ).not.toBeDefined();
    expect(
      MetadataEntity.getProperty(
        "hasDefaultArray",
        noDataProperties,
        classWithNoDataValues
      )
    ).toEqual([1, 1, 1]);
    expect(
      MetadataEntity.getProperty(
        "noDefaultArrayOfVector",
        noDataProperties,
        classWithNoDataValues
      )
    ).not.toBeDefined();
    expect(
      MetadataEntity.getProperty(
        "hasDefaultArrayOfVector",
        noDataProperties,
        classWithNoDataValues
      )
    ).toEqual([new Cartesian2(1.0, 1.0), new Cartesian2(1.0, 1.0)]);
  });

  it("handles offset and scale", function () {
    expect(
      MetadataEntity.getProperty("temperature", properties, classDefinition)
    ).toEqual(32);

    expect(
      MetadataEntity.getProperty(
        "temperatureArray",
        properties,
        classDefinition
      )
    ).toEqual([32, 212, 212, 32]);
  });

  it("getProperty throws without propertyId", function () {
    expect(function () {
      MetadataEntity.getProperty(undefined, properties, classDefinition);
    }).toThrowDeveloperError();
  });

  it("getProperty throws without properties", function () {
    expect(function () {
      MetadataEntity.getProperty("name", undefined, classDefinition);
    }).toThrowDeveloperError();
  });

  it("getProperty throws without classDefinition", function () {
    expect(function () {
      MetadataEntity.getProperty("name", properties, undefined);
    }).toThrowDeveloperError();
  });

  it("getProperty handles arrays of vectors correctly", function () {
    expect(
      MetadataEntity.getProperty("axisColors", properties, classDefinition)
    ).toEqual([
      new Cartesian3(1, 0, 0),
      new Cartesian3(0, 1, 0),
      new Cartesian3(0, 0, 1),
    ]);
  });

  it("setProperty returns false if property doesn't exist", function () {
    expect(
      MetadataEntity.setProperty("volume", 100.0, properties, classDefinition)
    ).toBe(false);
  });

  it("setProperty sets property value", function () {
    const position = [1.0, 1.0, 1.0];
    expect(
      MetadataEntity.setProperty(
        "position",
        position,
        properties,
        classDefinition
      )
    ).toBe(true);
    const retrievedPosition = MetadataEntity.getProperty(
      "position",
      properties,
      classDefinition
    );
    expect(retrievedPosition).toEqual(position);
    expect(retrievedPosition).not.toBe(position); // The value is cloned
  });

  it("setProperty handles arrays of vectors correctly", function () {
    const axisColors = [
      new Cartesian3(1, 0, 0),
      new Cartesian3(0, 1, 0),
      new Cartesian3(0, 0, 1),
    ];
    expect(
      MetadataEntity.setProperty(
        "axisColors",
        axisColors,
        properties,
        classDefinition
      )
    ).toBe(true);
    const retrievedPosition = MetadataEntity.getProperty(
      "axisColors",
      properties,
      classDefinition
    );
    expect(retrievedPosition).toEqual(axisColors);
    expect(retrievedPosition).not.toBe(axisColors); // The value is cloned
  });

  it("handles offset and scale", function () {
    expect(
      MetadataEntity.setProperty("temperature", 70, properties, classDefinition)
    ).toBe(true);

    // There is some expected loss of precision due to storing as a UINT8
    // so the result is not 0
    expect(
      MetadataEntity.getProperty("temperature", properties, classDefinition)
    ).toEqualEpsilon(70.11764705882354, CesiumMath.EPSILON15);

    const values = [32, 32, 32, 32];
    expect(
      MetadataEntity.setProperty(
        "temperatureArray",
        values,
        properties,
        classDefinition
      )
    ).toBe(true);

    const result = MetadataEntity.getProperty(
      "temperatureArray",
      properties,
      classDefinition
    );
    expect(result).toEqual(values);
    expect(result).not.toBe(values); // value should be cloned
  });

  it("setProperty throws without propertyId", function () {
    expect(function () {
      MetadataEntity.setProperty(
        undefined,
        "Building B",
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setProperty throws without value", function () {
    expect(function () {
      MetadataEntity.setProperty(
        "name",
        undefined,
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setProperty throws without properties", function () {
    expect(function () {
      MetadataEntity.setProperty(
        "name",
        "Building B",
        undefined,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setProperty throws without classDefinition", function () {
    expect(function () {
      MetadataEntity.setProperty("name", "Building B", properties, undefined);
    }).toThrowDeveloperError();
  });

  it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function () {
    expect(
      MetadataEntity.getPropertyBySemantic(
        "HEIGHT",
        properties,
        classDefinition
      )
    ).toBeUndefined();
  });

  it("getPropertyBySemantic returns the property value", function () {
    expect(
      MetadataEntity.getPropertyBySemantic("NAME", properties, classDefinition)
    ).toBe("Building A");
  });

  it("getPropertyBySemantic throws without semantic", function () {
    expect(function () {
      MetadataEntity.getPropertyBySemantic(
        undefined,
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("getPropertyBySemantic throws without properties", function () {
    expect(function () {
      MetadataEntity.getPropertyBySemantic("NAME", undefined, classDefinition);
    }).toThrowDeveloperError();
  });

  it("getPropertyBySemantic throws without classDefinition", function () {
    expect(function () {
      MetadataEntity.getPropertyBySemantic("NAME", properties, undefined);
    }).toThrowDeveloperError();
  });

  it("setPropertyBySemantic sets property value", function () {
    expect(
      MetadataEntity.setPropertyBySemantic(
        "NAME",
        "Building B",
        properties,
        classDefinition
      )
    ).toBe(true);
    expect(
      MetadataEntity.getProperty("name", properties, classDefinition)
    ).toBe("Building B");
  });

  it("setPropertyBySemantic returns false if the semantic does not exist", function () {
    expect(
      MetadataEntity.setPropertyBySemantic(
        "HEIGHT",
        20.0,
        properties,
        classDefinition
      )
    ).toBe(false);
  });

  it("setPropertyBySemantic throws without semantic", function () {
    expect(function () {
      MetadataEntity.setPropertyBySemantic(
        undefined,
        "Building B",
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setPropertyBySemantic throws without value", function () {
    expect(function () {
      MetadataEntity.setPropertyBySemantic(
        "NAME",
        undefined,
        properties,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setPropertyBySemantic throws without properties", function () {
    expect(function () {
      MetadataEntity.setPropertyBySemantic(
        "NAME",
        "Building B",
        undefined,
        classDefinition
      );
    }).toThrowDeveloperError();
  });

  it("setPropertyBySemantic throws without classDefinition", function () {
    expect(function () {
      MetadataEntity.setPropertyBySemantic(
        "NAME",
        "Building B",
        properties,
        undefined
      );
    }).toThrowDeveloperError();
  });
});


text:
BASEDIR=$(dirname $0)

# export 3rdparty packages, profiles and finally copy settings
$BASEDIR/3rdparty/export-all.sh
$BASEDIR/profiles/export-all.sh


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/glue/GlueRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Glue
{
namespace Model
{

  /**
   */
  class AWS_GLUE_API GetUserDefinedFunctionRequest : public GlueRequest
  {
  public:
    GetUserDefinedFunctionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetUserDefinedFunction"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline const Aws::String& GetCatalogId() const{ return m_catalogId; }

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline bool CatalogIdHasBeenSet() const { return m_catalogIdHasBeenSet; }

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline void SetCatalogId(const Aws::String& value) { m_catalogIdHasBeenSet = true; m_catalogId = value; }

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline void SetCatalogId(Aws::String&& value) { m_catalogIdHasBeenSet = true; m_catalogId = std::move(value); }

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline void SetCatalogId(const char* value) { m_catalogIdHasBeenSet = true; m_catalogId.assign(value); }

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline GetUserDefinedFunctionRequest& WithCatalogId(const Aws::String& value) { SetCatalogId(value); return *this;}

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline GetUserDefinedFunctionRequest& WithCatalogId(Aws::String&& value) { SetCatalogId(std::move(value)); return *this;}

    /**
     *
The ID of the Data Catalog where the function to be retrieved is located. If
     * none is provided, the AWS account ID is used by default.

     */
    inline GetUserDefinedFunctionRequest& WithCatalogId(const char* value) { SetCatalogId(value); return *this;}

    /**
     *
The name of the catalog database where the function is located.

     */
    inline const Aws::String& GetDatabaseName() const{ return m_databaseName; }

    /**
     *
The name of the catalog database where the function is located.

     */
    inline bool DatabaseNameHasBeenSet() const { return m_databaseNameHasBeenSet; }

    /**
     *
The name of the catalog database where the function is located.

     */
    inline void SetDatabaseName(const Aws::String& value) { m_databaseNameHasBeenSet = true; m_databaseName = value; }

    /**
     *
The name of the catalog database where the function is located.

     */
    inline void SetDatabaseName(Aws::String&& value) { m_databaseNameHasBeenSet = true; m_databaseName = std::move(value); }

    /**
     *
The name of the catalog database where the function is located.

     */
    inline void SetDatabaseName(const char* value) { m_databaseNameHasBeenSet = true; m_databaseName.assign(value); }

    /**
     *
The name of the catalog database where the function is located.

     */
    inline GetUserDefinedFunctionRequest& WithDatabaseName(const Aws::String& value) { SetDatabaseName(value); return *this;}

    /**
     *
The name of the catalog database where the function is located.

     */
    inline GetUserDefinedFunctionRequest& WithDatabaseName(Aws::String&& value) { SetDatabaseName(std::move(value)); return *this;}

    /**
     *
The name of the catalog database where the function is located.

     */
    inline GetUserDefinedFunctionRequest& WithDatabaseName(const char* value) { SetDatabaseName(value); return *this;}

    /**
     *
The name of the function.

     */
    inline const Aws::String& GetFunctionName() const{ return m_functionName; }

    /**
     *
The name of the function.

     */
    inline bool FunctionNameHasBeenSet() const { return m_functionNameHasBeenSet; }

    /**
     *
The name of the function.

     */
    inline void SetFunctionName(const Aws::String& value) { m_functionNameHasBeenSet = true; m_functionName = value; }

    /**
     *
The name of the function.

     */
    inline void SetFunctionName(Aws::String&& value) { m_functionNameHasBeenSet = true; m_functionName = std::move(value); }

    /**
     *
The name of the function.

     */
    inline void SetFunctionName(const char* value) { m_functionNameHasBeenSet = true; m_functionName.assign(value); }

    /**
     *
The name of the function.

     */
    inline GetUserDefinedFunctionRequest& WithFunctionName(const Aws::String& value) { SetFunctionName(value); return *this;}

    /**
     *
The name of the function.

     */
    inline GetUserDefinedFunctionRequest& WithFunctionName(Aws::String&& value) { SetFunctionName(std::move(value)); return *this;}

    /**
     *
The name of the function.

     */
    inline GetUserDefinedFunctionRequest& WithFunctionName(const char* value) { SetFunctionName(value); return *this;}

  private:

    Aws::String m_catalogId;
    bool m_catalogIdHasBeenSet;

    Aws::String m_databaseName;
    bool m_databaseNameHasBeenSet;

    Aws::String m_functionName;
    bool m_functionNameHasBeenSet;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Example

Resize this page to see how the text below changes:

This text is shown only on an EXTRA SMALL screen.

This text is shown only on a SMALL screen.

This text is shown only on a MEDIUM screen.

This text is shown only on a LARGE screen.

Note: The visible-* classes are deprecated as of Bootstrap v3.2.0