text:
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi.Enums
{
	 /// <summary>
	 /// SupportByVersion PowerPoint 14, 15, 16
	 /// </summary>
	 ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/PowerPoint.XlLegendPosition"/> </remarks>
	[SupportByVersion("PowerPoint", 14,15,16)]
	[EntityType(EntityType.IsEnum)]
	public enum XlLegendPosition
	{
		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>-4107</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionBottom = -4107,

		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionCorner = 2,

		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>-4131</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionLeft = -4131,

		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>-4152</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionRight = -4152,

		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>-4160</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionTop = -4160,

		 /// <summary>
		 /// SupportByVersion PowerPoint 14, 15, 16
		 /// </summary>
		 /// <remarks>-4161</remarks>
		 [SupportByVersion("PowerPoint", 14,15,16)]
		 xlLegendPositionCustom = -4161
	}
}


text:
using System;
using System.Globalization;
using System.Windows.Data;

namespace MyVocabulary.Converters
{
    class StringToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !string.IsNullOrEmpty((string)value) && System.Convert.ToBoolean(value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToString(value);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Steve has a string, , consisting of  lowercase English alphabetic
letters. In one operation, he can delete any pair of adjacent
letters with same value. For example, string "aabcc" would become
either "aab" or "bcc" after operation.

Steve wants to reduce  as much as possible. To do this, he will
repeat the above operation as many times as it can be performed.
Help Steve out by finding and printing 's non-reducible form!

Note: If the final string is empty, print Empty String.

Sample Input: aaabccddd
Sample Output: abd
"""

def reduce_string(s):
    """
    >>> assert(reduce_string(None) == 'Empty String')
    >>> assert(reduce_string('') == 'Empty String')
    >>> assert(reduce_string('abc') == 'abc')
    >>> assert(reduce_string('aabbc') == 'c')
    >>> assert(reduce_string('abcc') == 'ab')
    >>> assert(reduce_string('aabbcc') == 'Empty String')
    """
    if s is None or len(s) == 0:
        return 'Empty String'

    stack = []

    for char in s:
        if len(stack) == 0:
            stack.append(char)
            continue

        if char == stack[-1]:
            stack.pop()
        else:
            stack.append(char)

    return 'Empty String' if len(stack) == 0 else ''.join(stack)


text:
namespace net {

namespace {

std::string FirstAddress(const AddressList& address_list) {
  if (address_list.empty())
    return std::string();
  return address_list.front().ToString();
}

TEST(MappedHostResolverTest, Inclusion) {
  // Create a mock host resolver, with specific hostname to IP mappings.
  scoped_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddSimulatedFailure("*google.com");
  resolver_impl->rules()->AddRule("baz.com", "192.168.1.5");
  resolver_impl->rules()->AddRule("foo.com", "192.168.1.8");
  resolver_impl->rules()->AddRule("proxy", "192.168.1.11");

  // Create a remapped resolver that uses |resolver_impl|.
  scoped_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));

  int rv;
  AddressList address_list;

  // Try resolving "www.google.com:80". There are no mappings yet, so this
  // hits |resolver_impl| and fails.
  TestCompletionCallback callback;
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.google.com", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(ERR_NAME_NOT_RESOLVED, rv);

  // Remap *.google.com to baz.com.
  EXPECT_TRUE(resolver->AddRuleFromString("map *.google.com baz.com"));

  // Try resolving "www.google.com:80". Should be remapped to "baz.com:80".
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.google.com", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));

  // Try resolving "foo.com:77". This will NOT be remapped, so result
  // is "foo.com:77".
  rv = resolver->Resolve(HostResolver::RequestInfo(HostPortPair("foo.com", 77)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.8:77", FirstAddress(address_list));

  // Remap "*.org" to "proxy:99".
  EXPECT_TRUE(resolver->AddRuleFromString("Map *.org proxy:99"));

  // Try resolving "chromium.org:61". Should be remapped to "proxy:99".
  rv = resolver->Resolve(HostResolver::RequestInfo
                             (HostPortPair("chromium.org", 61)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.11:99", FirstAddress(address_list));
}

// Tests that exclusions are respected.
TEST(MappedHostResolverTest, Exclusion) {
  // Create a mock host resolver, with specific hostname to IP mappings.
  scoped_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.5");
  resolver_impl->rules()->AddRule("www.google.com", "192.168.1.3");

  // Create a remapped resolver that uses |resolver_impl|.
  scoped_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));

  int rv;
  AddressList address_list;
  TestCompletionCallback callback;

  // Remap "*.com" to "baz".
  EXPECT_TRUE(resolver->AddRuleFromString("map *.com baz"));

  // Add an exclusion for "*.google.com".
  EXPECT_TRUE(resolver->AddRuleFromString("EXCLUDE *.google.com"));

  // Try resolving "www.google.com". Should not be remapped due to exclusion).
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.google.com", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.3:80", FirstAddress(address_list));

  // Try resolving "chrome.com:80". Should be remapped to "baz:80".
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("chrome.com", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));
}

TEST(MappedHostResolverTest, SetRulesFromString) {
  // Create a mock host resolver, with specific hostname to IP mappings.
  scoped_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.7");
  resolver_impl->rules()->AddRule("bar", "192.168.1.9");

  // Create a remapped resolver that uses |resolver_impl|.
  scoped_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));

  int rv;
  AddressList address_list;
  TestCompletionCallback callback;

  // Remap "*.com" to "baz", and *.net to "bar:60".
  resolver->SetRulesFromString("map *.com baz , map *.net bar:60");

  // Try resolving "www.google.com". Should be remapped to "baz".
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.google.com", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.7:80", FirstAddress(address_list));

  // Try resolving "chrome.net:80". Should be remapped to "bar:60".
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("chrome.net", 80)),
                         &address_list, callback.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.9:60", FirstAddress(address_list));
}

// Parsing bad rules should silently discard the rule (and never crash).
TEST(MappedHostResolverTest, ParseInvalidRules) {
  scoped_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(scoped_ptr<HostResolver>()));

  EXPECT_FALSE(resolver->AddRuleFromString("xyz"));
  EXPECT_FALSE(resolver->AddRuleFromString(std::string()));
  EXPECT_FALSE(resolver->AddRuleFromString(" "));
  EXPECT_FALSE(resolver->AddRuleFromString("EXCLUDE"));
  EXPECT_FALSE(resolver->AddRuleFromString("EXCLUDE foo bar"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE x"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE x :10"));
}

// Test mapping hostnames to resolving failures.
TEST(MappedHostResolverTest, MapToError) {
  scoped_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("*", "192.168.1.5");

  scoped_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));

  int rv;
  AddressList address_list;

  // Remap *.google.com to resolving failures.
  EXPECT_TRUE(resolver->AddRuleFromString("MAP *.google.com ~NOTFOUND"));

  // Try resolving www.google.com --> Should give an error.
  TestCompletionCallback callback1;
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.google.com", 80)),
                         &address_list, callback1.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_NAME_NOT_RESOLVED, rv);

  // Try resolving www.foo.com --> Should succeed.
  TestCompletionCallback callback2;
  rv = resolver->Resolve(HostResolver::RequestInfo(
                             HostPortPair("www.foo.com", 80)),
                         &address_list, callback2.callback(), NULL,
                         BoundNetLog());
  EXPECT_EQ(ERR_IO_PENDING, rv);
  rv = callback2.WaitForResult();
  EXPECT_EQ(OK, rv);
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));
}

}  // namespace

}  // namespace net


text:
'use strict';

var cookie_domain_stripper = require('../../../lib/middleware/cookie_domain_stripper');

describe('cookie_domain_stripper', function() {
    beforeEach(function() {
        this.object = cookie_domain_stripper();
    });

    it('should call original writeHead method', function () {
        var res = { writeHead: function() {}, getHeader: function() {} };
        var spy = spyOn(res, 'writeHead');

        this.object({}, res, function() {});

        res.writeHead(200);

        expect(spy).toHaveBeenCalledWith(200);
    });

    it('should strip domain from `set-cookie` header', function () {
        var res = { writeHead: function() {}, setHeader: function() {}, removeHeader: function() {} };
        var spy = spyOn(res, 'writeHead');

        var header = 'GDCAuthSST=x8qtuB7HjE1pJ4xx; path=/gdc/account; domain=secure.gooddata.com; secure; HttpOnly';
        var modifiedHeader = 'GDCAuthSST=x8qtuB7HjE1pJ4xx; path=/gdc/account; secure; HttpOnly';
        var headers = { 'set-cookie': [header] };
        var modifiedHeaders = { 'set-cookie': [modifiedHeader] };

        this.object({}, res, function() {});

        res.writeHead(200, headers);

        expect(spy).toHaveBeenCalledWith(200, modifiedHeaders);
    });

    it('should strip domain from `set-cookie` header when headers are passed in response object', function () {
        var res = { writeHead: function() {}, getHeader: function() { return [header]; }, setHeader: function() {}, removeHeader: function() {} };
        var spy = spyOn(res, 'setHeader');
        var spy2 = spyOn(res, 'removeHeader');

        var header = 'GDCAuthSST=x8qtuB7HjE1pJ4xx; path=/gdc/account; domain=secure.gooddata.com; secure; HttpOnly';
        var modifiedHeader = 'GDCAuthSST=x8qtuB7HjE1pJ4xx; path=/gdc/account; secure; HttpOnly';

        this.object({}, res, function() {});

        res.writeHead(200);

        expect(spy2).toHaveBeenCalled();
        expect(spy).toHaveBeenCalledWith('set-cookie', [modifiedHeader]);
    });
});


text:
// icons.lodash.css -- Template for the automatically generated icon stack
//
// Copyright (C) 2016 Michael Seibt
//
// With contributions from: -
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

@font-face {
  font-family: "<%= fontName %>";
  src: url('<%= fontPath %><%= fontName %>.eot');
  src: url('<%= fontPath %><%= fontName %>.eot?#iefix') format('eot'),
    url('<%= fontPath %><%= fontName %>.woff') format('woff'),
    url('<%= fontPath %><%= fontName %>.ttf') format('truetype'),
    url('<%= fontPath %><%= fontName %>.svg#<%= fontName %>') format('svg');
  font-weight: normal;
  font-style: normal;
}

.<%= className %>:before {
  display: inline-block;
  font-family: "<%= fontName %>";
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.<%= className %>-lg {
  font-size: 1.3333333333333333em;
  line-height: 0.75em;
  vertical-align: -15%;
}
.<%= className %>-2x { font-size: 2em; }
.<%= className %>-3x { font-size: 3em; }
.<%= className %>-4x { font-size: 4em; }
.<%= className %>-5x { font-size: 5em; }
.<%= className %>-fw {
  width: 1.2857142857142858em;
  text-align: center;
}

<% _.each(glyphs, function(glyph) { %>
/**
 * @icon .<%= className %>--<%= glyph.name %><%
 if((className == 'ico') && (glyph.name == 'logo')) { %>
 * @deprecated <% } %>
 * @markup
 *  <i class="<%= className %> <%= className %>--<%= glyph.name %>"></i>
 */
  .<%= className %>--<%= glyph.name %>:before {
    content: "\<%= glyph.unicode[0].charCodeAt(0).toString(16).toUpperCase() %>"
  }
<% }); %>


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_TOURNAMENTS_BEGIN

/// <summary>
/// Represents a reference to a multiplayer session.
/// </summary>
public ref class PreviousMatchMetadata sealed
{
public:

    /// <summary>
    /// Previous game's result for the tournament.
    /// </summary>
    property Microsoft::Xbox::Services::Tournaments::TournamentTeamResult^ Result
    {
        Microsoft::Xbox::Services::Tournaments::TournamentTeamResult^ get();
    }

    /// <summary>
    /// The timestamp when the match ended.
    /// </summary>
    DEFINE_PROP_GET_DATETIME_OBJ(EndTime, end_time);

    /// <summary>
    /// Metadata associated with the team's previously played match.
    /// </summary>
    property MatchMetadata^ MatchDetails { MatchMetadata^ get(); }

internal:
    PreviousMatchMetadata(
        _In_ xbox::services::tournaments::previous_match_metadata cppObj
        );

    const xbox::services::tournaments::previous_match_metadata& GetCppObj() const;

private:
    xbox::services::tournaments::previous_match_metadata m_cppObj;
    MatchMetadata^ m_matchDetails;
    Microsoft::Xbox::Services::Tournaments::TournamentTeamResult^ m_result;
};

NAMESPACE_MICROSOFT_XBOX_SERVICES_TOURNAMENTS_END


text:
"use strict"

var path = require('path');
// Get the absolute path to this directory
var dir = path.resolve(__dirname);

module.exports = function() {
  return {
    "motion/Actuate": path.join(dir, "motion/Actuate"),
    "motion/MotionPath": path.join(dir, "motion/MotionPath"),
    "motion/actuators": path.join(dir, "motion/actuators"),
    "motion/easing": path.join(dir, "motion/easing"),
  };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Cucumber</id>
          </State>
          <State>
            <id>JSON</id>
          </State>
          <State>
            <id>JavaScript</id>
          </State>
          <State>
            <id>JavaScript validity issuesJavaScript</id>
          </State>
          <State>
            <id>Ruby</id>
          </State>
          <State>
            <id>SQL</id>
          </State>
        </expanded-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectRootManager" version="2" project-jdk-name="rbenv: 2.2.1" project-jdk-type="RUBY_SDK" />
  <component name="SshConsoleOptionsProvider">
    <option name="myEncoding" value="UTF-8" />
    <option name="myConnectionType" value="NONE" />
    <option name="myConnectionId" value="" />
  </component>
</project>


text:
"""Subgoal Wrapper around Maze Environment."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from . import environment
from absl import flags
from ..models import tdm
from ..models import vae
import numpy as np
from tensor2tensor.bin.t2t_decoder import create_hparams
from tensor2tensor.utils import registry
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import estimator as tf_estimator
from ..utils import save_im

FLAGS = flags.FLAGS

class SubGoalEnv(object):
  """Subgoal Wrapper around Maze Environment."""

  def __init__(self, difficulty, modeltype, cost, numsg=1, savedir='/tmp/',
               envtype='maze', phorizon=5, parallel=0,
               tdmdir='/tmp/mazetdm/', vaedir='/tmp/mazevae'):
    self.parallel = parallel
    self.envtype = envtype
    self.cost = cost
    self.modeltype = modeltype

    # Only use maze env
    if self.envtype == 'maze':
      self.env = environment.Environment(difficulty=difficulty)
      self.num_acts = 2
    else:
      raise NotImplementedError

    self.numsg = numsg
    self.eps = 0
    self.savedir = savedir
    self.planstep = 0
    self.phorizon = phorizon

    self.it_graph = tf.Graph()
    with self.it_graph.as_default():
      self.itsess = tf.Session()
      self.it = vae.ImageTransformSC(8)
      outall = self.it(bs=1)
      self.out, _, _, _ = outall

      itsaver = tf.train.Saver()
      vaedir = vaedir + '256_8/'
      # Restore variables from disk.
      itsaver.restore(self.itsess, vaedir + 'model-0')
      print('LOADED VAE!')

    # LOADING TDM
    self.tdm_graph = tf.Graph()
    with self.tdm_graph.as_default():
      self.tdmsess = tf.Session()
      self.tdm = tdm.TemporalModel()
      self.s1 = tf.placeholder(tf.float32, shape=[None, 64, 64, 3])
      self.s2 = tf.placeholder(tf.float32, shape=[None, 64, 64, 3])
      self.tdout = tf.nn.softmax(self.tdm(self.s1, self.s2))

      tdmsaver = tf.train.Saver()
      tdmdir = tdmdir + '256TDM/'
      # Restore variables from disk.
      tdmsaver.restore(self.tdmsess, tdmdir + 'model-0')
      print('LOADED TDM!')

    # LOADING SV2P (Modify this to your path and problem)
    homedir = '/usr/local/google/home/nairsuraj'
    FLAGS.data_dir = homedir + '/data/maze3/'
    FLAGS.output_dir = homedir + '/models/rs=6.3/maze3/checkpoint'
    FLAGS.problem = 'video_bair_robot_pushing'
    FLAGS.hparams = 'video_num_input_frames=1,video_num_target_frames=10'
    FLAGS.hparams_set = 'next_frame_sv2p'
    FLAGS.model = 'next_frame_sv2p'
    # Create hparams
    hparams = create_hparams()
    hparams.video_num_input_frames = 1
    hparams.video_num_target_frames = self.phorizon

    # Params
    num_replicas = 200
    frame_shape = hparams.problem.frame_shape
    forward_graph = tf.Graph()
    with forward_graph.as_default():
      self.forward_sess = tf.Session()
      input_size = [num_replicas, hparams.video_num_input_frames]
      target_size = [num_replicas, hparams.video_num_target_frames]
      self.forward_placeholders = {
          'inputs':
              tf.placeholder(tf.float32, input_size + frame_shape),
          'input_action':
              tf.placeholder(tf.float32, input_size + [self.num_acts]),
          'targets':
              tf.placeholder(tf.float32, target_size + frame_shape),
          'target_action':
              tf.placeholder(tf.float32, target_size + [self.num_acts]),
      }
      # Creat model
      forward_model_cls = registry.model(FLAGS.model)
      forward_model = forward_model_cls(hparams, tf_estimator.ModeKeys.PREDICT)
      self.forward_prediction_ops, _ = forward_model(self.forward_placeholders)
      forward_saver = tf.train.Saver()
      forward_saver.restore(self.forward_sess,
                            homedir + '/models/rs=6.3/maze6/model.ckpt-0')
    print('LOADED SV2P!')

    _, self.state = self.env.get_observation()

  def reset(self):
    """Reset environment."""
    self.eps += 1  # Episode counter
    self.steps = 0
    self.env.reset()
    self.goalim = self.env.get_goal_im()
    _, self.state = self.env.get_observation()

    # Logdir for episode
    os.makedirs(self.savedir +  str(self.eps) + '/')
    # Save Current and Goal Image
    save_im(self.goalim, self.savedir + str(self.eps) + '/' + str(self.steps) +
            'goalim.jpg')
    save_im(self.state, self.savedir + str(self.eps) + '/' + str(self.steps) +
            'currstate.jpg')
    self._episode_ended = False
    return np.array(self.state, dtype=np.uint8)

  def latent_to_im(self, latent):
    """Takes subgoal latent and feeds it through decoder to generate image."""
    forward_feed = {
        self.it.s1:
            np.repeat(np.expand_dims(self.state/255., 0), self.numsg, 0),
        self.it.s2:
            np.repeat(np.expand_dims(self.state/255., 0), self.numsg, 0),
        self.it.z:
            latent.reshape((self.numsg, 8)),
        }
    delta = 255. * self.itsess.run(self.out, forward_feed)
    return delta

  def temporal_cost(self, ims, goal, tp=1):
    """Takes two images and returns temporal distance prediction."""
    if tp == 1:
      forward_feed = {
          self.s1:
              ims/255.0,
          self.s2:
              np.repeat(np.expand_dims(goal/255., 0), ims.shape[0], 0),
      }
      costs = self.tdmsess.run(self.tdout, forward_feed)[:, 0]
      return costs
    else:
      forward_feed = {
          self.s1: ims/255.0,
      }
      ims_e = self.tdmsess.run(self.tdout, forward_feed)
      forward_feed = {
          self.s1:
              np.repeat(np.expand_dims(goal/255., 0), ims.shape[0], 0),
      }
      g_e = self.tdmsess.run(self.tdout, forward_feed)
      return np.mean((g_e - ims_e)**2, 1)

  def plan(self, im1, im2):
    """Plans between two images."""
    action, cost = self.cem(self.forward_sess, self.forward_placeholders,
                            self.forward_prediction_ops, im1, im2)
    return action, cost

  def step(self, action):
    """Step one 'Subgoal' action in the environment."""
    self.steps += 1
    # Convert subgoals to image
    im = self.latent_to_im(action)
    costs = []
    trajs = []
    for i in range(self.numsg+1):
      if i == 0:
        acts, cost = self.plan(self.state, im[i])
      elif i == self.numsg:
        acts, cost = self.plan(im[i-1], self.goalim)
      else:
        acts, cost = self.plan(im[i-1], im[i])
      costs.append(cost)
      trajs.append(acts)

      if i == self.numsg:
        save_im(self.goalim, self.savedir + str(self.eps) +'/' + str(self.steps)
                +  '_C_' + str(cost) +  'subgoal' + str(i) + '.jpg')
      else:
        save_im(im[i], self.savedir + str(self.eps) + '/' + str(self.steps)
                +  '_C_' + str(cost) + 'subgoal'+ str(i) + '.jpg')

    return -np.max(costs), trajs
    # return -np.mean(costs), trajs

  def cem(self, forward_sess, forward_placeholders, forward_ops, im1, im2):
    """Runs Visual MPC between two images."""

    horizon = forward_placeholders['targets'].shape[1]
    mu1 = np.array([0]*(self.num_acts * horizon))
    sd1 = np.array([0.2]*(self.num_acts * horizon))

    t = 0
    sample_size = 200
    resample_size = 40

    if horizon == 15:
      hz = 5
    else:
      hz = horizon

    while np.max(sd1) > .001:
      if t == 0:
        acts1x = np.random.uniform(0, 3, (sample_size, hz, 1))
        acts1y = np.random.uniform(-3, 3, (sample_size, hz, 1))
        acts1 = np.concatenate([acts1x, acts1y], 2)
      else:
        acts1 = np.random.normal(mu1, sd1, (sample_size, self.num_acts *  hz))
      acts1 = acts1.reshape((sample_size, hz, self.num_acts))
      if horizon == 15:
        acts1 = np.repeat(acts1, 3, axis=1)
      acts0 = acts1[:, 0:1, :]

      forward_feed = {
          forward_placeholders['inputs']:
              np.repeat(np.expand_dims(np.expand_dims(im1, 0), 0),
                        sample_size, axis=0),
          forward_placeholders['input_action']:
              acts0,
          forward_placeholders['targets']:
              np.zeros(forward_placeholders['targets'].shape),
          forward_placeholders['target_action']:
              acts1
      }
      forward_predictions = forward_sess.run(forward_ops, forward_feed)

      losses = []
      if self.cost == 'temporal':
        losses = self.temporal_cost(forward_predictions.reshape(-1, 64, 64, 3),
                                    im2)
        losses = losses.reshape(sample_size, horizon)
      elif self.cost == 'pixel':
        goalim = np.repeat(np.expand_dims(
            np.repeat(np.expand_dims(im2, 0), horizon, 0), 0), sample_size, 0)
        losses = (goalim - forward_predictions[:, :, :, :, :, 0])**2
        losses = losses.mean(axis=(2, 3, 4))
      losses = losses[:, -1]

      for q in range(sample_size):
        head = self.savedir + str(self.eps) + '/' + str(self.planstep) + '/'
        tail = str(t) + '/' + str(losses[q]) + '_' + str(q) + '/'
        drr = head + tail
        os.makedirs(drr)
        with open(drr + 'acts.txt', 'a') as f:
          f.write(str(acts1[q]))
        save_im(im1, drr+'curr.jpg')
        save_im(im2, drr+'goal.jpg')
        for p in range(horizon):
          save_im(forward_predictions[q, p, :, :, :, 0], drr + str(p) + '.jpg')

      best_actions = np.array([x for _, x in sorted(
          zip(losses, acts1.tolist()), reverse=False)][:resample_size])
      best_costs = np.array([x for x, _ in sorted(
          zip(losses, acts1.tolist()), reverse=False)][:resample_size])

      if horizon == 15:
        best_actions = best_actions[:, ::3, :]
      else:
        best_actions = best_actions[:, :, :]
      best_actions1 = best_actions.reshape(resample_size, -1)
      mu1 = np.mean(best_actions1, axis=0)
      sd1 = np.std(best_actions1, axis=0)
      t += 1
      if t >= 5:
        break

    chosen = best_actions1[0]
    bestcost = best_costs[0]
    return chosen, bestcost


text:
#include "third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h"

#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/core/events/progress_event.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"

namespace blink {

XMLHttpRequestUpload::XMLHttpRequestUpload(XMLHttpRequest* xml_http_request)
    : xml_http_request_(xml_http_request),
      last_bytes_sent_(0),
      last_total_bytes_to_be_sent_(0) {}

const AtomicString& XMLHttpRequestUpload::InterfaceName() const {
  return event_target_names::kXMLHttpRequestUpload;
}

ExecutionContext* XMLHttpRequestUpload::GetExecutionContext() const {
  return xml_http_request_->GetExecutionContext();
}

void XMLHttpRequestUpload::DispatchProgressEvent(
    uint64_t bytes_sent,
    uint64_t total_bytes_to_be_sent) {
  last_bytes_sent_ = bytes_sent;
  last_total_bytes_to_be_sent_ = total_bytes_to_be_sent;
  probe::AsyncTask async_task(GetExecutionContext(),
                              xml_http_request_->async_task_context(),
                              "progress", xml_http_request_->IsAsync());
  DispatchEvent(*ProgressEvent::Create(event_type_names::kProgress, true,
                                       bytes_sent, total_bytes_to_be_sent));
}

void XMLHttpRequestUpload::DispatchEventAndLoadEnd(const AtomicString& type,
                                                   bool length_computable,
                                                   uint64_t bytes_sent,
                                                   uint64_t total) {
  DCHECK(type == event_type_names::kLoad || type == event_type_names::kAbort ||
         type == event_type_names::kError ||
         type == event_type_names::kTimeout);
  probe::AsyncTask async_task(GetExecutionContext(),
                              xml_http_request_->async_task_context(), "event",
                              xml_http_request_->IsAsync());
  DispatchEvent(
      *ProgressEvent::Create(type, length_computable, bytes_sent, total));
  DispatchEvent(*ProgressEvent::Create(event_type_names::kLoadend,
                                       length_computable, bytes_sent, total));
}

void XMLHttpRequestUpload::HandleRequestError(const AtomicString& type) {
  bool length_computable = last_total_bytes_to_be_sent_ > 0 &&
                           last_bytes_sent_ <= last_total_bytes_to_be_sent_;
  probe::AsyncTask async_task(GetExecutionContext(),
                              xml_http_request_->async_task_context(), "error",
                              xml_http_request_->IsAsync());
  DispatchEventAndLoadEnd(type, length_computable, last_bytes_sent_,
                          last_total_bytes_to_be_sent_);
}

void XMLHttpRequestUpload::Trace(Visitor* visitor) const {
  visitor->Trace(xml_http_request_);
  XMLHttpRequestEventTarget::Trace(visitor);
}

}  // namespace blink


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.harvard.iq.dataverse;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 *
 * @author skraffmi
 */
public class FileVersionDifference {

    private  FileMetadata newFileMetadata;
    private  FileMetadata originalFileMetadata;
    private boolean details = false;

    private List<FileDifferenceSummaryGroup> differenceSummaryGroups = new ArrayList();
    private List<FileDifferenceDetailItem> differenceDetailItems = new ArrayList();

    public FileVersionDifference(FileMetadata newFileMetadata, FileMetadata originalFileMetadata) {

       this(newFileMetadata, originalFileMetadata, false);

    }

    public FileVersionDifference(FileMetadata newFileMetadata, FileMetadata originalFileMetadata, boolean details) {

        this.newFileMetadata = newFileMetadata;
        this.originalFileMetadata = originalFileMetadata;
        this.details = details;

        compareMetadata(newFileMetadata, originalFileMetadata);
        //Compare versions - File Metadata first

    }

    private void compareMetadata(FileMetadata newFileMetadata, FileMetadata originalFileMetadata ){

        if (newFileMetadata.getDataFile() == null && originalFileMetadata == null){
            //File in neither version
            //Don't add any groups
        }

        if (newFileMetadata.getDataFile() == null && originalFileMetadata != null){
            //File Deleted
            updateDifferenceSummary("", ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileGroupTitle"),  0, 0, 1, 0);
            return;
        }

        if (this.originalFileMetadata == null && this.newFileMetadata.getDataFile() != null ){
            //File Added
            updateDifferenceSummary( "", ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileGroupTitle"), 1, 0, 0, 0);
        }

        //Check to see if File replaced
        if (originalFileMetadata != null &&
                 newFileMetadata.getDataFile() != null && originalFileMetadata.getDataFile() != null &&!this.originalFileMetadata.getDataFile().equals(this.newFileMetadata.getDataFile())){
            updateDifferenceSummary( "", ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileGroupTitle"), 0, 0, 0, 1);
        }

        if ( originalFileMetadata != null) {
            if (!newFileMetadata.getLabel().equals(originalFileMetadata.getLabel())) {
                if (details) {
                    differenceDetailItems.add(new FileDifferenceDetailItem(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileNameDetailTitle"), originalFileMetadata.getLabel(), newFileMetadata.getLabel()));
                }
                updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileMetadataGroupTitle"),
                        ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileNameDetailTitle"), 0, 1, 0, 0);
            }
        }
        if ( originalFileMetadata != null) {
            if (newFileMetadata.getDescription() != null
                    && originalFileMetadata.getDescription() != null
                    && !newFileMetadata.getDescription().equals(originalFileMetadata.getDescription())) {
                if (details) {
                    differenceDetailItems.add(new FileDifferenceDetailItem(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), originalFileMetadata.getDescription(), newFileMetadata.getDescription()));
                }
                updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileMetadataGroupTitle"),
                        ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), 0, 1, 0, 0);
            }
            if (newFileMetadata.getDescription() != null
                    && originalFileMetadata.getDescription() == null
                    ) {
                if (details) {
                    differenceDetailItems.add(new FileDifferenceDetailItem(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), "", newFileMetadata.getDescription()));
                }
                updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileMetadataGroupTitle"),
                        ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), 1, 0, 0, 0);
            }
            if (newFileMetadata.getDescription() == null
                    && originalFileMetadata.getDescription() != null
                    ) {
                if (details) {
                    differenceDetailItems.add(new FileDifferenceDetailItem(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), originalFileMetadata.getDescription(), "" ));
                }
                updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileMetadataGroupTitle"),
                        ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.descriptionDetailTitle"), 0, 0, 1, 0);
            }
        }
        if (originalFileMetadata != null) {
            /*
            get Tags differences
            */
            String value1 = originalFileMetadata.getCategoriesByName().toString();
            String value2 = newFileMetadata.getCategoriesByName().toString();
            if (value1 == null || value1.equals("") || value1.equals(" ")) {
                value1 = "";
            }
            if (value2 == null || value2.equals("") || value2.equals(" ")) {
                value2 = "";
            }

            if (!value1.equals(value2)) {

                int added = 0;
                int deleted = 0;

                added = newFileMetadata.getCategoriesByName().stream().map((tag) -> {
                    boolean found = false;
                    for (String tagOld : originalFileMetadata.getCategoriesByName() ){
                        if (tag.equals(tagOld)){
                            found = true;
                            break;
                        }
                    }
                    return found;
                }).filter((found) -> (!found)).map((_item) -> 1).reduce(added, Integer::sum);

                for (String tag : originalFileMetadata.getCategoriesByName()) {
                    boolean found = false;
                    for (String tagNew : newFileMetadata.getCategoriesByName() ){
                        if (tag.equals(tagNew)){
                            found = true;
                            break;
                        }
                    }
                    if (!found){
                        deleted++;
                    }
                }
                if (added > 0){
                    updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileTagsGroupTitle"), "", added, 0, 0, 0, true);
                }
                if (deleted > 0){
                    updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileTagsGroupTitle"), "", 0, 0, deleted, 0, true);
                }

            }

            /*
            Get Restriction Differences
            */
            value1 = originalFileMetadata.isRestricted() ? ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileRestricted") : ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileUnrestricted");
            value2 = newFileMetadata.isRestricted() ? ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileRestricted") : ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileUnrestricted");
            if (!value1.equals(value2)) {
                if (!value1.equals(value2)) {
                    updateDifferenceSummary(ResourceBundle.getBundle("Bundle").getString("file.versionDifferences.fileAccessTitle"), value2, 0, 0, 0, 0);
                }
            }
        }
    }

     private void updateDifferenceSummary(String groupLabel, String itemLabel, int changed, int added, int deleted, int replaced) {
        updateDifferenceSummary(groupLabel, itemLabel, changed, added, deleted, replaced, false);
    }

    private void updateDifferenceSummary(String groupLabel, String itemLabel, int changed, int added, int deleted, int replaced, boolean multiple) {
        FileDifferenceSummaryGroup summaryGroup = new FileDifferenceSummaryGroup(groupLabel);
        FileDifferenceSummaryItem summaryItem = new FileDifferenceSummaryItem(itemLabel, changed, added, deleted, replaced, multiple);

        if (!this.differenceSummaryGroups.contains(summaryGroup)) {
            summaryGroup.getFileDifferenceSummaryItems().add(summaryItem);
            this.differenceSummaryGroups.add(summaryGroup);
        } else {
            this.differenceSummaryGroups.stream().filter((test) -> (test.equals(summaryGroup))).forEach((test) -> {
                test.getFileDifferenceSummaryItems().add(summaryItem);
            });
        }
    }

    public FileMetadata getNewFileMetadata(){
        return this.newFileMetadata;
    }

    public void setNewFileMetadata(FileMetadata in){
         this.newFileMetadata = in;
    }

        public FileMetadata getOriginalFileMetadata() {
        return originalFileMetadata;
    }

    public void setOriginalFileMetadata(FileMetadata originalFileMetadata) {
        this.originalFileMetadata = originalFileMetadata;
    }

    public List<FileDifferenceSummaryGroup> getDifferenceSummaryGroups() {
        return differenceSummaryGroups;
    }

    public void setDifferenceSummaryGroups(List<FileDifferenceSummaryGroup> differenceSummaryGroups) {
        this.differenceSummaryGroups = differenceSummaryGroups;
    }

    public  class FileDifferenceSummaryGroup {

        private String name;
        private List<FileDifferenceSummaryItem> fileDifferenceSummaryItems;

        public FileDifferenceSummaryGroup(String name) {
            this.name = name;
            this.fileDifferenceSummaryItems = new ArrayList();

        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<FileDifferenceSummaryItem> getFileDifferenceSummaryItems() {
            return fileDifferenceSummaryItems;
        }

        public void setFileDifferenceSummaryItems(List<FileDifferenceSummaryItem> fileDifferenceSummaryItems) {
            this.fileDifferenceSummaryItems = fileDifferenceSummaryItems;
        }

        @Override
        public String toString() {

            String retval = getName();
            if (!retval.isEmpty()){
                retval += ": ";
            }

            for (FileDifferenceSummaryItem item : this.fileDifferenceSummaryItems){
                retval += " " + item.toString();
            }

            return retval;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 97 * hash + Objects.hashCode(this.fileDifferenceSummaryItems);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final FileDifferenceSummaryGroup other = (FileDifferenceSummaryGroup) obj;
            if (!Objects.equals(this.name, other.name)) {
                return false;
            }
            return true;
        }
    }

    public final class FileDifferenceDetailItem{
        private String displayName;
        private String originalValue;
        private String newValue;

        public FileDifferenceDetailItem(String displayName, String originalValue, String newValue) {
            this.displayName = displayName;
            this.originalValue = originalValue;
            this.newValue = newValue;
        }

        public String getDisplayName() {
            return displayName;
        }

        public void setDisplayName(String displayName) {
            this.displayName = displayName;
        }

        public String getOriginalValue() {
            return originalValue;
        }

        public void setOriginalValue(String originalValue) {
            this.originalValue = originalValue;
        }

        public String getNewValue() {
            return newValue;
        }

        public void setNewValue(String newValue) {
            this.newValue = newValue;
        }

    }

    public class FileDifferenceSummaryItem{

        private String name;
        private int added;
        private int changed;
        private int deleted;
        private int replaced;
        private boolean multiple;

        public FileDifferenceSummaryItem(String name, int added, int changed, int deleted, int replaced, boolean multiple) {
            this.name = name;
            this.added = added;
            this.changed = changed;
            this.deleted = deleted;
            this.replaced = replaced;
            this.multiple = multiple;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAdded() {
            return added;
        }

        public void setAdded(int added) {
            this.added = added;
        }

        public int getChanged() {
            return changed;
        }

        public void setChanged(int changed) {
            this.changed = changed;
        }

        public int getDeleted() {
            return deleted;
        }

        public void setDeleted(int deleted) {
            this.deleted = deleted;
        }

        public int getReplaced() {
            return replaced;
        }

        public void setReplaced(int replaced) {
            this.replaced = replaced;
        }

        public boolean isMultiple() {
            return multiple;
        }

        public void setMultiple(boolean multiple) {
            this.multiple = multiple;
        }

    }

}


text:
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Query;
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
	/// <summary>
	/// Shows how to create a ClassBreaksRenderer for a graphics layer.
	/// Data points are pulled from an online source and rendered using the GraphicsLayer ClassBreaksRenderer.
	/// </summary>
	/// <title>Class Breaks Renderer</title>
	/// <category>Symbology</category>
	public partial class ClassBreaksRendererSample : Windows.UI.Xaml.Controls.Page
	{
		private Random _random = new Random();
		private GraphicsOverlay _cities;

		/// <summary>Construct Class Breaks Renderer sample control</summary>
		public ClassBreaksRendererSample()
		{
			InitializeComponent();

			_cities = MyMapView.GraphicsOverlays["cities"];

			MyMapView.SpatialReferenceChanged += MyMapView_SpatialReferenceChanged;
		}

		// Load data
		private async void MyMapView_SpatialReferenceChanged(object sender, EventArgs e)
		{
			try
			{
				MyMapView.SpatialReferenceChanged -= MyMapView_SpatialReferenceChanged;
				await LoadDataAsync();
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog("Error loading data: " + ex.Message, "Sample Error").ShowAsync();
			}
		}

		// Change the graphics layer renderer to a new ClassBreaksRenderer
		private void ChangeRendererButton_Click(object sender, RoutedEventArgs e)
		{
			SimpleMarkerStyle style = (SimpleMarkerStyle)_random.Next(0, 6);

			_cities.Renderer = new ClassBreaksRenderer()
			{
				Field = "pop2000",
				Infos = new ClassBreakInfoCollection()
				{
					new ClassBreakInfo() { Minimum = 0, Maximum = 50000, Symbol = GetRandomSymbol(style) },
					new ClassBreakInfo() { Minimum = 50000, Maximum = 100000, Symbol = GetRandomSymbol(style) },
					new ClassBreakInfo() { Minimum = 100000, Maximum = 250000, Symbol = GetRandomSymbol(style) },
					new ClassBreakInfo() { Minimum = 250000, Maximum = 500000, Symbol = GetRandomSymbol(style) },
					new ClassBreakInfo() { Minimum = 500000, Maximum = 1000000, Symbol = GetRandomSymbol(style) },
					new ClassBreakInfo() { Minimum = 1000000, Maximum = 5000000, Symbol = GetRandomSymbol(style) },
				}
			};
		}

		// Load earthquakes from map service
		private async Task LoadDataAsync()
		{
			var queryTask = new QueryTask(
				new Uri("http://sampleserver6.arcgisonline.com/ArcGIS/rest/services/USA/MapServer/0"));
			var query = new Query(MyMapView.Extent)
			{
				ReturnGeometry = true,
				OutSpatialReference = MyMapView.SpatialReference,
				Where = "pop2000 > 50000",
				OutFields = new OutFields(new string[] { "pop2000" })
			};
			var result = await queryTask.ExecuteAsync(query);

			_cities.Graphics.Clear();
			_cities.Graphics.AddRange(result.FeatureSet.Features.OfType<Graphic>());
		}

		// Utility: Generate a random simple marker symbol
		private SimpleMarkerSymbol GetRandomSymbol(SimpleMarkerStyle style)
		{
			return new SimpleMarkerSymbol()
			{
				Size = 12,
				Color = GetRandomColor(),
				Style = style
			};
		}

		// Utility function: Generate a random System.Windows.Media.Color
		private Color GetRandomColor()
		{
			var colorBytes = new byte[3];
			_random.NextBytes(colorBytes);
			return Color.FromArgb(0xFF, colorBytes[0], colorBytes[1], colorBytes[2]);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version4" level="2" version="4">
  <model metaid="_case00663" id="case00663" name="case00663">
    <listOfCompartments>
      <compartment id="C" name="C" size="1" units="volume"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="S1" name="S1" compartment="C" initialAmount="0.002" substanceUnits="substance"/>
      <species id="S2" name="S2" compartment="C" initialAmount="0.002" substanceUnits="substance"/>
      <species id="S3" name="S3" compartment="C" initialAmount="0" substanceUnits="substance"/>
      <species id="S4" name="S4" compartment="C" initialAmount="0" substanceUnits="substance"/>
    </listOfSpecies>
    <listOfParameters>
      <parameter id="k1" name="k1" value="1000"/>
      <parameter id="k2" name="k2" constant="false"/>
      <parameter id="k3" name="k3" value="0.7"/>
    </listOfParameters>
    <listOfRules>
      <algebraicRule metaid="rule1">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <apply>
            <plus/>
            <ci> k2 </ci>
            <cn> -0.9 </cn>
          </apply>
        </math>
      </algebraicRule>
    </listOfRules>
    <listOfReactions>
      <reaction id="reaction1" name="reaction1" reversible="false" fast="false">
        <listOfReactants>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S3"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <times/>
              <ci> C </ci>
              <ci> k1 </ci>
              <ci> S1 </ci>
              <ci> S2 </ci>
            </apply>
          </math>
        </kineticLaw>
      </reaction>
      <reaction id="reaction2" name="reaction2" reversible="false" fast="false">
        <listOfReactants>
          <speciesReference species="S3"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <times/>
              <ci> C </ci>
              <ci> k2 </ci>
              <ci> S3 </ci>
            </apply>
          </math>
        </kineticLaw>
      </reaction>
      <reaction id="reaction3" name="reaction3" reversible="false" fast="false">
        <listOfReactants>
          <speciesReference species="S3"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S1"/>
          <speciesReference species="S4"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <times/>
              <ci> C </ci>
              <ci> k3 </ci>
              <ci> S3 </ci>
            </apply>
          </math>
        </kineticLaw>
      </reaction>
    </listOfReactions>
    <listOfEvents>
      <event id="event1" name="event1">
        <trigger>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <gt/>
              <ci> S4 </ci>
              <ci> S3 </ci>
            </apply>
          </math>
        </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="S4">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <apply>
                <times/>
                <cn type="integer"> 2 </cn>
                <ci> S4 </ci>
              </apply>
            </math>
          </eventAssignment>
        </listOfEventAssignments>
      </event>
    </listOfEvents>
  </model>
</sbml>


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Display overview for courses
 *
 * @param array $courses courses for which overview needs to be shown
 * @return array html overview
 */
function block_course_overview_get_overviews($courses) {
    $htmlarray = array();
    if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
        // Split courses list into batches with no more than MAX_MODINFO_CACHE_SIZE courses in one batch.
        // Otherwise we exceed the cache limit in get_fast_modinfo() and rebuild it too often.
        if (defined('MAX_MODINFO_CACHE_SIZE') && MAX_MODINFO_CACHE_SIZE > 0 && count($courses) > MAX_MODINFO_CACHE_SIZE) {
            $batches = array_chunk($courses, MAX_MODINFO_CACHE_SIZE, true);
        } else {
            $batches = array($courses);
        }
        foreach ($batches as $courses) {
            foreach ($modules as $fname) {
                $fname($courses, $htmlarray);
            }
        }
    }
    return $htmlarray;
}

/**
 * Sets user preference for maximum courses to be displayed in course_overview block
 *
 * @param int $number maximum courses which should be visible
 */
function block_course_overview_update_mynumber($number) {
    set_user_preference('course_overview_number_of_courses', $number);
}

/**
 * Sets user course sorting preference in course_overview block
 *
 * @param array $sortorder sort order of course
 */
function block_course_overview_update_myorder($sortorder) {
    set_user_preference('course_overview_course_order', serialize($sortorder));
}

/**
 * Returns shortname of activities in course
 *
 * @param int $courseid id of course for which activity shortname is needed
 * @return string|bool list of child shortname
 */
function block_course_overview_get_child_shortnames($courseid) {
    global $DB;
    $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
    $sql = "SELECT c.id, c.shortname, $ctxselect
            FROM {enrol} e
            JOIN {course} c ON (c.id = e.customint1)
            JOIN {context} ctx ON (ctx.instanceid = e.customint1)
            WHERE e.courseid = :courseid AND e.enrol = :method AND ctx.contextlevel = :contextlevel ORDER BY e.sortorder";
    $params = array('method' => 'meta', 'courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);

    if ($results = $DB->get_records_sql($sql, $params)) {
        $shortnames = array();
        // Preload the context we will need it to format the category name shortly.
        foreach ($results as $res) {
            context_helper::preload_from_record($res);
            $context = context_course::instance($res->id);
            $shortnames[] = format_string($res->shortname, true, $context);
        }
        $total = count($shortnames);
        $suffix = '';
        if ($total > 10) {
            $shortnames = array_slice($shortnames, 0, 10);
            $diff = $total - count($shortnames);
            if ($diff > 1) {
                $suffix = get_string('shortnamesufixprural', 'block_course_overview', $diff);
            } else {
                $suffix = get_string('shortnamesufixsingular', 'block_course_overview', $diff);
            }
        }
        $shortnames = get_string('shortnameprefix', 'block_course_overview', implode('; ', $shortnames));
        $shortnames .= $suffix;
    }

    return isset($shortnames) ? $shortnames : false;
}

/**
 * Returns maximum number of courses which will be displayed in course_overview block
 *
 * @return int maximum number of courses
 */
function block_course_overview_get_max_user_courses() {
    // Get block configuration
    $config = get_config('block_course_overview');
    $limit = $config->defaultmaxcourses;

    // If max course is not set then try get user preference
    if (empty($config->forcedefaultmaxcourses)) {
        $limit = get_user_preferences('course_overview_number_of_courses', $limit);
    }
    return $limit;
}

/**
 * Return sorted list of user courses
 *
 * @return array list of sorted courses and count of courses.
 */
function block_course_overview_get_sorted_courses() {
    global $USER;

    $limit = block_course_overview_get_max_user_courses();

    $courses = enrol_get_my_courses('id, shortname, fullname, modinfo, sectioncache');
    $site = get_site();

    if (array_key_exists($site->id,$courses)) {
        unset($courses[$site->id]);
    }

    foreach ($courses as $c) {
        if (isset($USER->lastcourseaccess[$c->id])) {
            $courses[$c->id]->lastaccess = $USER->lastcourseaccess[$c->id];
        } else {
            $courses[$c->id]->lastaccess = 0;
        }
    }

    // Get remote courses.
    $remotecourses = array();
    if (is_enabled_auth('mnet')) {
        $remotecourses = get_my_remotecourses();
    }
    // Remote courses will have -ve remoteid as key, so it can be differentiated from normal courses
    foreach ($remotecourses as $id => $val) {
        $remoteid = $val->remoteid * -1;
        $val->id = $remoteid;
        $courses[$remoteid] = $val;
    }

    $order = array();
    if (!is_null($usersortorder = get_user_preferences('course_overview_course_order'))) {
        $order = unserialize($usersortorder);
    }

    $sortedcourses = array();
    $counter = 0;
    // Get courses in sort order into list.
    foreach ($order as $key => $cid) {
        if (($counter >= $limit) && ($limit != 0)) {
            break;
        }

        // Make sure user is still enroled.
        if (isset($courses[$cid])) {
            $sortedcourses[$cid] = $courses[$cid];
            $counter++;
        }
    }
    // Append unsorted courses if limit allows
    foreach ($courses as $c) {
        if (($limit != 0) && ($counter >= $limit)) {
            break;
        }
        if (!in_array($c->id, $order)) {
            $sortedcourses[$c->id] = $c;
            $counter++;
        }
    }

    // From list extract site courses for overview
    $sitecourses = array();
    foreach ($sortedcourses as $key => $course) {
        if ($course->id > 0) {
            $sitecourses[$key] = $course;
        }
    }
    return array($sortedcourses, $sitecourses, count($courses));
}


text:
"""
Setuptools script for pp-apiaccesstoken (pp.apiaccesstoken)
"""
try:
    from pkglib.setuptools import setup
except ImportError:
    print "PkgLib is not available. Please run \"easy_install pkglib\""
    import sys
    sys.exit(1)

setup()


text:
package org.jboss.pnc.bpm.task;

import lombok.ToString;
import org.jboss.pnc.bpm.BpmTask;
import org.jboss.pnc.model.ProductMilestone;
import org.jboss.pnc.rest.restmodel.bpm.MilestoneReleaseParameters;
import org.jboss.pnc.rest.restmodel.causeway.MilestoneReleaseRest;
import org.jboss.pnc.spi.exception.CoreException;

import java.io.Serializable;

/**
 * @author Michal Szynkiewicz
 */
@ToString(callSuper = true)
public class MilestoneReleaseTask extends BpmTask {

    private final ProductMilestone milestone;

    public MilestoneReleaseTask(ProductMilestone milestone, String accessToken) {
        this.milestone = milestone;
        setAccessToken(accessToken);
    }

    private MilestoneReleaseRest createMilestoneRest(ProductMilestone milestone) {
        return new MilestoneReleaseRest(milestone.getId());
    }

    @Override
    protected Serializable getProcessParameters() throws CoreException {
        return new MilestoneReleaseParameters(
                createMilestoneRest(milestone),
                config.getPncBaseUrl(),
                config.getCausewayBaseUrl()
        );
    }

    @Override
    protected String getProcessId() {
        return config.getMilestoneReleaseProcessId();
    }
}


text:
package azurerm

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAzureRMServiceBusTopic_basic(t *testing.T) {
	ri := acctest.RandInt()
	config := fmt.Sprintf(testAccAzureRMServiceBusTopic_basic, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMServiceBusTopicDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMServiceBusTopicExists("azurerm_servicebus_topic.test"),
				),
			},
		},
	})
}

func TestAccAzureRMServiceBusTopic_update(t *testing.T) {
	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_basic, ri, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_update, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMServiceBusTopicDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMServiceBusTopicExists("azurerm_servicebus_topic.test"),
				),
			},
			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "enable_batched_operations", "true"),
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "enable_express", "true"),
				),
			},
		},
	})
}

func TestAccAzureRMServiceBusTopic_enablePartitioningStandard(t *testing.T) {
	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_basic, ri, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_enablePartitioningStandard, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMServiceBusTopicDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMServiceBusTopicExists("azurerm_servicebus_topic.test"),
				),
			},
			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "enable_partitioning", "true"),
					// Ensure size is read back in it's original value and not the x16 value returned by Azure
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "max_size_in_megabytes", "5120"),
				),
			},
		},
	})
}

func TestAccAzureRMServiceBusTopic_enablePartitioningPremium(t *testing.T) {
	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_basic, ri, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_enablePartitioningPremium, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMServiceBusTopicDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMServiceBusTopicExists("azurerm_servicebus_topic.test"),
				),
			},
			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "enable_partitioning", "true"),
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "max_size_in_megabytes", "81920"),
				),
			},
		},
	})
}

func TestAccAzureRMServiceBusTopic_enableDuplicateDetection(t *testing.T) {
	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_basic, ri, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMServiceBusTopic_enableDuplicateDetection, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMServiceBusTopicDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMServiceBusTopicExists("azurerm_servicebus_topic.test"),
				),
			},
			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"azurerm_servicebus_topic.test", "requires_duplicate_detection", "true"),
				),
			},
		},
	})
}

func testCheckAzureRMServiceBusTopicDestroy(s *terraform.State) error {
	client := testAccProvider.Meta().(*ArmClient).serviceBusTopicsClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "azurerm_servicebus_topic" {
			continue
		}

		name := rs.Primary.Attributes["name"]
		namespaceName := rs.Primary.Attributes["namespace_name"]
		resourceGroup := rs.Primary.Attributes["resource_group_name"]

		resp, err := client.Get(resourceGroup, namespaceName, name)
		if err != nil {
			if resp.StatusCode == http.StatusNotFound {
				return nil
			}
			return err
		}

		if resp.StatusCode != http.StatusNotFound {
			return fmt.Errorf("ServiceBus Topic still exists:\n%+v", resp.TopicProperties)
		}
	}

	return nil
}

func testCheckAzureRMServiceBusTopicExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		// Ensure we have enough information in state to look up in API
		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		topicName := rs.Primary.Attributes["name"]
		namespaceName := rs.Primary.Attributes["namespace_name"]
		resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
		if !hasResourceGroup {
			return fmt.Errorf("Bad: no resource group found in state for topic: %s", topicName)
		}

		client := testAccProvider.Meta().(*ArmClient).serviceBusTopicsClient

		resp, err := client.Get(resourceGroup, namespaceName, topicName)
		if err != nil {
			return fmt.Errorf("Bad: Get on serviceBusTopicsClient: %+v", err)
		}

		if resp.StatusCode == http.StatusNotFound {
			return fmt.Errorf("Bad: Topic %q (resource group: %q) does not exist", namespaceName, resourceGroup)
		}

		return nil
	}
}

var testAccAzureRMServiceBusTopic_basic = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "standard"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
}
`

var testAccAzureRMServiceBusTopic_basicPremium = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "premium"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
}
`

var testAccAzureRMServiceBusTopic_update = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "standard"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
    enable_batched_operations = true
    enable_express = true
}
`

var testAccAzureRMServiceBusTopic_enablePartitioningStandard = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "standard"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
    enable_partitioning = true
	max_size_in_megabytes = 5120
}
`

var testAccAzureRMServiceBusTopic_enablePartitioningPremium = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "premium"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
    enable_partitioning = true
	max_size_in_megabytes = 81920
}
`

var testAccAzureRMServiceBusTopic_enableDuplicateDetection = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_servicebus_namespace" "test" {
    name = "acctestservicebusnamespace-%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    sku = "standard"
}

resource "azurerm_servicebus_topic" "test" {
    name = "acctestservicebustopic-%d"
    location = "West US"
    namespace_name = "${azurerm_servicebus_namespace.test.name}"
    resource_group_name = "${azurerm_resource_group.test.name}"
    requires_duplicate_detection = true
}
`


text:
namespace boost { namespace network { namespace http {

    template <class Tag>
    struct unsupported_tag;

    struct request_header_narrow {
        typedef std::string string_type;
        std::string name, value;
    };

    struct request_header_wide {
        typedef std::wstring string_type;
        std::wstring name, value;
    };

    template <class Tag>
    struct request_header
    : mpl::if_<
        is_default_string<Tag>,
        request_header_narrow,
        typename mpl::if_<
            is_default_wstring<Tag>,
            request_header_wide,
            unsupported_tag<Tag>
        >::type
    >
    {};

    inline void swap(request_header_narrow & l, request_header_narrow & r) {
        swap(l.name, r.name);
        swap(l.value, r.value);
    }

    inline void swap(request_header_wide & l, request_header_wide & r) {
        swap(l.name, r.name);
        swap(l.value, r.value);
    }

    struct response_header_narrow {
        typedef std::string string_type;
        std::string name, value;
    };

    struct response_header_wide {
        typedef std::wstring string_type;
        std::wstring name, value;
    };

    template <class Tag>
    struct response_header
    : mpl::if_<
        is_default_string<Tag>,
        response_header_narrow,
        typename mpl::if_<
            is_default_wstring<Tag>,
            response_header_wide,
            unsupported_tag<Tag>
        >::type
    >
    {};

    inline void swap(response_header_narrow & l, response_header_narrow & r) {
        std::swap(l.name, r.name);
        std::swap(l.value, r.value);
    }

    inline void swap(response_header_wide & l, response_header_wide & r) {
        std::swap(l.name, r.name);
        std::swap(l.value, r.value);
    }

} // namespace http

} // namespace network

} // namespace boost

BOOST_FUSION_ADAPT_STRUCT(
    boost::network::http::request_header_narrow,
    (std::string, name)
    (std::string, value)
    )

BOOST_FUSION_ADAPT_STRUCT(
    boost::network::http::request_header_wide,
    (std::wstring, name)
    (std::wstring, value)
    )

BOOST_FUSION_ADAPT_STRUCT(
    boost::network::http::response_header_narrow,
    (std::string, name)
    (std::string, value)
    )

BOOST_FUSION_ADAPT_STRUCT(
    boost::network::http::response_header_wide,
    (std::wstring, name)
    (std::wstring, value)
    )

#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HEADER_HPP_20101122


text:
layout: post
title:  "My Experience During ISWI(International Student Week in Ilmenau)"
date:   2017-06-12 20:15:09 +0800
comments: true
tags:
- life
---

Last month I spent such an unforgettable week with participants from all over the world in Ilmenau, Germany(2017.iswi.org) to discuss the topic 'Global Justice'. It was my first time in Europe and the first student conference I joined, the conference was a crazy party week and it was so amazing. I came there alone and surprised to find that I'm the only delegate from China!

### To Get to Ilmenau
Ilmenau was quite a small city located in central Germany, the transportation is not that convinient compared with other big cities. From Berlin, I could either take FlixBus or ICE, finally I chose to take ICE from Berlin Central Station which is 20 mins from the airport, it took about 4 hours to get to ilmenau. Pay attention that ICE has a reservation system, if you don't pay for the reservation you can still choose a seat after riding on the train, but it might be reserved, in that case you need to look for some other seat.

### General Experience
The conference was held by TU Ilmenau, an university centering in technology. The campus was built on a moutain with a very nice secenery. I actually met several computer science guys there ^_^.

A typical day during the week is basically lecture/workshop + discussion + live concert/some other festival + club night, starting from 9 am to 2pm. The lectures were actually very interesting, there were topics on international NGOs, human rights, and even Bitcoin!

I was in the music group, and I met extremly talented people there, there was a professional pianist and famous band members! We made an original EuroVision-like song about global justice. Somehow I've managed to play the electronic guitar and the closing ceremony finally ^_^.

During the live concert, I could experiece something "Germany" (mixed beer haha). Somehow I love the idea of mixing beer with everything.

After schedule on the time table finally comes party time! I'm not a night person so I only went to clubs inside campus for three times, I tasted all kinds of beer from different parts of Germany, but unluckily I missed the "Jägermeister night".

### Incidents in Berlin
Unluckily my cash (about 150 euros) was stolen in the bus from the airport to Berlin central station. Before coming I thought Germany was general safe but this incident told me it's not. What disappoints me most is how the police deal with such things. In my case, the policeman said it wasn't much money at all and it happens here every day. I believe they're not making any efforts to stop theft towards travellers, even not putting on a notice telling people to take care of their wallet.

Another incident was after the conference when I spent several days to hangout with my friends in Berlin. One day I walked on the street and suddenly a middle aged man riding a bicycle passed by me calling me "stupid Chinese". I tried to grab him out of his fucking bycle but he had been already far away. Guys if you encounter similar insults in Germany, erect your middle figure and call him "Wichser".

I'm so disappointed in Berlin, the conference I joined was about "Global Justice", and in Berlin it seems not "safe" to be Asian, it's not global justice at all. There're still many ignorant people in the world, that's why global justice is so hard to achieve.

### My Thinkings
Except the disappointment in Berlin, I had nice time in Germany. I met amazing people of my age in the conference, my vision about the world was different now, I saw young people doing great effort to achieve global justice, it's not easy, let's try at least!


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>io.permazen.parse.func (Permazen 4.1.9 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

io.permazen.parse.func

Interfaces

Function

Classes

AbstractFunction

AllFunction

ConcatFunction

CountFunction

CreateFunction

LimitFunction

ListFunction

QueryCompositeIndexFunction

QueryIndexFunction

QueryListElementIndexFunction

QueryMapValueIndexFunction

QueryVersionFunction

SimpleFunction

UpgradeFunction

VersionFunction


text:
package org.apache.hadoop.hdfs.server.blockmanagement;

import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * This exception is thrown when the name node runs out of V1 (legacy)
 * generation stamps.
 *
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class OutOfLegacyGenerationStampsException extends IOException {
  private static final long serialVersionUID = 1L;

  public OutOfLegacyGenerationStampsException() {
    super("Out of V1 (legacy) generation stamps\n");
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST ClearComboBoxItemSelection" />
  <property name="jnlp.Name"     value="ClearComboBoxItemSelection" />
  <property name="jnlp.name"     value="clearcomboboxitemselection" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/clearcomboboxitemselection/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/ClearComboBoxItemSelection.html" />
</project>


text:
package me.pbox.site.dao.impl;

import me.pbox.site.dao.CategoryDao;
import me.pbox.site.model.Category;
import me.pbox.site.model.Package;
import org.jacuzzi.core.DatabaseException;

/**
 * @author Mike Mirzayanov (mirzayanovmr@gmail.com)
 */
public class CategoryDaoImpl extends ApplicationDaoImpl<Category> implements CategoryDao {
    @Override
    public Category find(String name) {
        return findOnlyBy("name=?", name);
    }

    @Override
    public void ensureExistsByPackage(Package p) {
        Category category = find(p.getName());
        if (category == null) {
            category = new Category();
            category.setName(p.getName());
            try {
                insert(category);
            } catch (DatabaseException ignored) {
                // No operations.
            }
        }
    }

    @Override
    public void onDownload(Package p) {
        if (getJacuzzi().execute("UPDATE `Category` SET `downloadCount`=`downloadCount`+1 WHERE `name`=?", p.getName()) != 1) {
            throw new DatabaseException("Can't update category by " + p + '.');
        }
    }
}


text:
var React = require('react');
var Foo = require('Foo');

/**
 * General component description.
 */
var Component = React.createClass({
  displayName: 'Component',

  propTypes: {
    ...Foo.propTypes,
    /**
     * Prop description
     */
    bar: React.PropTypes.number
  },

  getDefaultProps: function() {
    return {
      bar: 21
    };
  },

  render: function() {
    // ...
  }
});

module.exports = Component;


text:
/**
 * \file robust_multi_sensor_gaussian_filter.hpp
 * \date August 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#pragma once

#include <fl/util/meta.hpp>
#include <fl/util/profiling.hpp>
#include <fl/util/traits.hpp>

#include <fl/model/sensor/multi_robust_sensor_function.hpp>

#include <fl/filter/gaussian/update_policy/sigma_point_update_policy.hpp>
#include <fl/filter/gaussian/update_policy/sigma_point_additive_update_policy.hpp>
#include <fl/filter/gaussian/update_policy/sigma_point_additive_uncorrelated_update_policy.hpp>
#include <fl/filter/gaussian/prediction_policy/sigma_point_prediction_policy.hpp>
#include <fl/filter/gaussian/prediction_policy/sigma_point_additive_prediction_policy.hpp>

#include <fl/filter/gaussian/multi_sensor_gaussian_filter.hpp>
#include <fl/filter/gaussian/X_robust_multi_sensor_gaussian_filter.hpp>

namespace fl
{

// Forward delcaration
template<
    typename TransitionFunction,
    typename ActualJointSensor,
    typename Quadrature
> class XRobustMultiSensorGaussianFilter;

/**
 * \internal
 * \ingroup nonlinear_gaussian_filter
 *
 * Traits of the robust multi sensor GaussianFilter based on quadrature
 * with customizable policies, i.e implementations of the time and measurement
 * updates.
 */
template <
    typename TransitionFunction,
    typename ActualJointSensor,
    typename Quadrature
>
struct Traits<
           XRobustMultiSensorGaussianFilter<
               TransitionFunction, ActualJointSensor, Quadrature>>
{
    typedef typename TransitionFunction::State State;
    typedef typename TransitionFunction::Input Input;
    typedef typename ActualJointSensor::Obsrv Obsrv;
    typedef Gaussian<State> Belief;
};

/**
 * \ingroup nonlinear_gaussian_filter
 */
template<
    typename TransitionFunction,
    typename ActualJointSensor,
    typename Quadrature
>
class XRobustMultiSensorGaussianFilter
    : public FilterInterface<
                XRobustMultiSensorGaussianFilter<
                    TransitionFunction, ActualJointSensor, Quadrature>>
{
public:
    typedef typename TransitionFunction::State State;
    typedef typename TransitionFunction::Input Input;
    typedef typename ActualJointSensor::Obsrv Obsrv;
    typedef Gaussian<State> Belief;

private:
    /** \cond internal */

    // Get the original local model types
    enum : signed int { ModelCount = ActualJointSensor::ModelCount };
    typedef typename ActualJointSensor::LocalModel PlainLocalModel;

    // Define local feature observation model
    typedef MultiRobustSensorFunction<
                PlainLocalModel, ModelCount
            > FeatureSensor;

    // Define robust joint feature observation model
    typedef JointSensor<
                MultipleOf<FeatureSensor, ModelCount>
            > RobustJointFeatureSensor;
    /**
     * \brief Internal generic multi-sensor GaussianFilter for nonlinear
     *        problems
     */
    typedef MultiSensorGaussianFilter<
                TransitionFunction,
                RobustJointFeatureSensor,
                Quadrature
            > InternalMultiSensorGaussianFilter;

    /** \endcond */

public:
    /**
     * \brief Creates a RobustGaussianFilter
     */
    XRobustMultiSensorGaussianFilter(
        const TransitionFunction& transition,
        const ActualJointSensor& joint_sensor,
        const Quadrature& quadrature)
        : joint_sensor_(joint_sensor),
          multi_sensor_gaussian_filter_(
              transition,
              RobustJointFeatureSensor(
                  FeatureSensor(joint_sensor_.local_sensor(),
                                    joint_sensor_.count_local_models()),
                  joint_sensor_.count_local_models()),
              quadrature)
    { }

    /**
     * \brief Overridable default destructor
     */
    virtual ~XRobustMultiSensorGaussianFilter() noexcept { }

    /**
     * \copydoc FilterInterface::predict
     */
    virtual void predict(const Belief& prior_belief,
                         const Input& input,
                         Belief& predicted_belief)
    {
        multi_sensor_gaussian_filter_.predict(
            prior_belief,
            input,
            predicted_belief);
    }

    /**
     * \copydoc FilterInterface::update
     */
    virtual void update(const Belief& predicted_belief,
                        const Obsrv& y,
                        Belief& posterior_belief)
    {
        typedef typename PlainLocalModel::Obsrv PlainObsrv;
        typedef typename PlainLocalModel::BodySensor::Noise BodyNoise;
        typedef typename RobustJointFeatureSensor::Obsrv JointFeatureObsrv;

        auto joint_feature_y =
            JointFeatureObsrv(
                joint_feature_model()
                    .obsrv_dimension());
        joint_feature_y.setZero();

        auto local_body_noise_distr =
            Gaussian<BodyNoise>(
                sensor()
                    .local_sensor()
                    .body_model()
                    .noise_dimension());

        auto h = [&](const State& x, const BodyNoise& w)
        {
           return joint_sensor_
                        .local_sensor()
                        .body_model()
                        .observation(x, w);
        };

        enum : signed int
        {
            NumberOfPoints =
                Quadrature::number_of_points(
                    JoinSizes<
                        SizeOf<State>::Value,
                        SizeOf<BodyNoise>::Value
                    >::Value)
        };

        PointSet<State, NumberOfPoints> X;
        PointSet<BodyNoise, NumberOfPoints> R;
        PointSet<PlainObsrv, NumberOfPoints> Z;

        multi_sensor_gaussian_filter_
           .quadrature()
           .transform_to_points(predicted_belief, local_body_noise_distr, X, R);

        auto W = X.covariance_weights_vector().asDiagonal();

        auto y_mean = typename FirstMomentOf<PlainObsrv>::Type();
        auto y_cov = typename SecondMomentOf<PlainObsrv>::Type();

        auto& local_sensor = sensor().local_sensor();
        auto& local_feature_model = joint_feature_model().local_sensor();

        local_feature_model.mean_state(predicted_belief.mean());

        const int local_obsrv_dim = local_sensor.obsrv_dimension();
        const int local_feature_dim = local_feature_model.obsrv_dimension();
        const int sensor_count = joint_sensor_.count_local_models();

        low_level_obsrv_bg.setZero(sensor_count, 1);
        low_level_obsrv_fg.setZero(sensor_count, 1);
        low_level_obsrv_nan.setZero(sensor_count, 1);

        mean_obsrv.setZero(sensor_count);

        // compute body_tail_sensor parameters
        for (int i = 0; i < sensor_count; ++i)
        {
            if (!std::isfinite(y(i)))
            {
                low_level_obsrv_nan(i) = 0.25;

                joint_feature_y(i * local_feature_dim) =
                    std::numeric_limits<Real>::quiet_NaN();
                continue;
            }

//            joint_sensor_.local_sensor().body_model().id(i);
            local_feature_model.id(i);
            multi_sensor_gaussian_filter_
                .quadrature()
                .propagate_points(h, X, R, Z);

            y_mean = Z.mean();
            mean_obsrv(i) = y_mean(0);
            //! \todo BG changes
            if (!std::isfinite(y_mean(0)))
            {
                low_level_obsrv_bg(i) = 0.50;

                joint_feature_y(i * local_feature_dim) =
                    std::numeric_limits<Real>::infinity();

                continue;
            }
            auto Z_c = Z.centered_points();
            y_cov = (Z_c * W * Z_c.transpose());

            // set the current sensor's parameter
            local_feature_model.body_moments(y_mean, y_cov, i);

            local_feature_model.id(i);
            auto feature = local_feature_model.feature_obsrv(
                        y.middleRows(i * local_obsrv_dim, local_obsrv_dim));

            joint_feature_y.middleRows(i * local_feature_dim, local_feature_dim) =
                    feature;

            low_level_obsrv_fg(i) = 0.75;

        }

        multi_sensor_gaussian_filter_
            .update(predicted_belief, joint_feature_y, posterior_belief);
    }

    Eigen::VectorXd mean_obsrv;

public: /* factory functions */
    virtual Belief create_belief() const
    {
        auto belief = multi_sensor_gaussian_filter_.create_belief();
        return belief; // RVO
    }

public: /* accessors & mutators */
    TransitionFunction& transition()
    {
        return multi_sensor_gaussian_filter_.transition();
    }

    ActualJointSensor& sensor()
    {
        return joint_sensor_;
    }

    const TransitionFunction& transition() const
    {
        return multi_sensor_gaussian_filter_.transition();
    }

    const ActualJointSensor& sensor() const
    {
        return joint_sensor_;
    }

    std::string name() const override
    {
        return "RobustMultiSensorGaussianFilter<"
                + this->list_arguments(multi_sensor_gaussian_filter_.name())
                + ">";
    }

    std::string description() const override
    {
        return "Robust multi-sensor GaussianFilter with"
                + this->list_descriptions(
                      multi_sensor_gaussian_filter_.description());
    }

protected:
    RobustJointFeatureSensor& joint_feature_model()
    {
        return multi_sensor_gaussian_filter_.sensor();
    }

protected:
    /** \cond internal */
    ActualJointSensor joint_sensor_;
    InternalMultiSensorGaussianFilter multi_sensor_gaussian_filter_;
    /** \endcond */

public:
    Eigen::VectorXd low_level_obsrv_bg;
    Eigen::VectorXd low_level_obsrv_fg;
    Eigen::VectorXd low_level_obsrv_nan;
};

}


text:
package com.tenclouds.loadingadaptersample.activities;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;

import com.tenclouds.loadingadaptersample.R;
import com.tenclouds.loadingadaptersample.databinding.ActivityCardDetailBinding;

import io.magicthegathering.javasdk.resource.Card;

public class CardDetailActivity extends AppCompatActivity {

    public static final String EXTRA_CARD = "card";

    public static void start(Context context, @NonNull Card card) {
        Intent intent = new Intent(context, CardDetailActivity.class);
        intent.putExtra(EXTRA_CARD, card);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCardDetailBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_card_detail);
        Card card = (Card) getIntent().getSerializableExtra(EXTRA_CARD);
        binding.setCard(card);

        getSupportActionBar().setTitle(card.getName());
    }
}


text:
from datetime import datetime, timedelta
from io import BytesIO
from itertools import product
from json import loads
from multiprocessing import Pool, cpu_count, Value
from os import makedirs
from os.path import dirname
from time import strptime, strftime, mktime
from urllib.request import urlopen

from PIL import Image
from pytz import timezone
from tzlocal import get_localzone

from .config import level, output_file, auto_offset, hour_offset
from .utils import set_background, get_desktop_environment

counter = None
height = 550
width = 550

def get_time_offset(latest_date):
    if auto_offset:
        local_date = datetime.now(timezone(str(get_localzone())))
        himawari_date = datetime.now(timezone('Australia/Sydney'))
        local_offset = local_date.strftime("%z")
        himawari_offset = himawari_date.strftime("%z")

        offset = int(local_offset) - int(himawari_offset)
        offset /= 100

        offset_tmp = datetime.fromtimestamp(mktime(latest_date))
        offset_tmp = offset_tmp + timedelta(hours=offset)
        offset_time = offset_tmp.timetuple()

    elif hour_offset > 0:
        offset_tmp = datetime.fromtimestamp(mktime(latest_date))
        offset_tmp = offset_tmp - timedelta(hours=hour_offset)
        offset_time = offset_tmp.timetuple()

    return offset_time

def download_chunk(args):
    global counter

    x, y, latest = args
    url_format = "http://himawari8.nict.go.jp/img/D531106/{}d/{}/{}_{}_{}.png"

    with urlopen(url_format.format(level, width, strftime("%Y/%m/%d/%H%M%S", latest), x, y)) as tile_w:
        tiledata = tile_w.read()

    with counter.get_lock():
        counter.value += 1
        print("\rDownloading tiles: {}/{} completed".format(counter.value, level * level), end="", flush=True)
    return x, y, tiledata

def main():
    global counter

    if auto_offset and hour_offset:
        exit("You can not set `auto_offset` to True and `hour_offset` to a value that is different than zero.")
    elif hour_offset < 0:
        exit("`hour_offset` must be greater than or equal to zero. I can't get future images of Earth for now.")

    print("Updating...")
    with urlopen("http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json") as latest_json:
        latest = strptime(loads(latest_json.read().decode("utf-8"))["date"], "%Y-%m-%d %H:%M:%S")

    print("Latest version: {} GMT".format(strftime("%Y/%m/%d %H:%M:%S", latest)))
    if auto_offset or hour_offset > 0:
        requested_time = get_time_offset(latest)
        print("Offset version: {} GMT".format(strftime("%Y/%m/%d %H:%M:%S", requested_time)))
    else:
        requested_time = latest

    print()

    png = Image.new('RGB', (width * level, height * level))

    counter = Value("i", 0)
    p = Pool(cpu_count() * level)
    print("Downloading tiles: 0/{} completed".format(level * level), end="", flush=True)
    res = p.map(download_chunk, product(range(level), range(level), (requested_time,)))

    for (x, y, tiledata) in res:
        tile = Image.open(BytesIO(tiledata))
        png.paste(tile, (width * x, height * y, width * (x + 1), height * (y + 1)))

    print("\nSaving to '%s'..." % (output_file))
    makedirs(dirname(output_file), exist_ok=True)
    png.save(output_file, "PNG")

    if not set_background(output_file):
        exit("Your desktop environment '{}' is not supported.".format(get_desktop_environment()))

    print("Done!")

if __name__ == "__main__":
    main()