text:
package org.apache.geode.redis.internal.data;

import static org.apache.geode.test.dunit.rules.RedisClusterStartupRule.BIND_ADDRESS;
import static org.apache.geode.test.dunit.rules.RedisClusterStartupRule.REDIS_CLIENT_TIMEOUT;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.dunit.rules.RedisClusterStartupRule;

public class PartitionedRegionStatsUpdateTest {

  @ClassRule
  public static RedisClusterStartupRule clusterStartUpRule = new RedisClusterStartupRule(3);

  private static MemberVM server1;
  private static MemberVM server2;

  private static JedisCluster jedis;

  private static final String STRING_KEY = "{tag1}string key";
  private static final String SET_KEY = "{tag1}set key";
  private static final String HASH_KEY = "{tag1}hash key";
  private static final String LONG_APPEND_VALUE = String.valueOf(Integer.MAX_VALUE);
  private static final String FIELD = "field";

  @BeforeClass
  public static void classSetup() {
    MemberVM locator = clusterStartUpRule.startLocatorVM(0);
    int locatorPort = locator.getPort();

    server1 = clusterStartUpRule.startRedisVM(1, locatorPort);
    server2 = clusterStartUpRule.startRedisVM(2, locatorPort);

    int redisServerPort1 = clusterStartUpRule.getRedisPort(1);
    jedis = new JedisCluster(new HostAndPort(BIND_ADDRESS, redisServerPort1), REDIS_CLIENT_TIMEOUT);
  }

  @AfterClass
  public static void cleanup() {
    jedis.close();
  }

  @Before
  public void setup() {
    clusterStartUpRule.flushAll();
  }

  @Test
  public void should_showIncreaseInDatastoreBytesInUse_givenStringValueSizeIncreases() {
    String LONG_APPEND_VALUE = String.valueOf(Integer.MAX_VALUE);
    jedis.set(STRING_KEY, "value");

    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    for (int i = 0; i < 1000; i++) {
      jedis.append(STRING_KEY, LONG_APPEND_VALUE);
    }

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse1).isGreaterThan(initialDataStoreBytesInUse1);
    long server2finalDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);
    assertThat(server2finalDataStoreBytesInUse).isEqualTo(finalDataStoreBytesInUse1);
  }

  @Test
  public void should_showDecreaseInDatastoreBytesInUse_givenStringValueDeleted() {
    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    jedis.set(STRING_KEY, "value");

    long intermediateDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long intermediateDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);
    assertThat(intermediateDataStoreBytesInUse1).isGreaterThan(initialDataStoreBytesInUse1);
    assertThat(intermediateDataStoreBytesInUse2).isGreaterThan(initialDataStoreBytesInUse2);

    jedis.del(STRING_KEY);

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isEqualTo(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isEqualTo(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_showDecreaseInDatastoreBytesInUse_givenStringValueShortened() {
    jedis.set(STRING_KEY, "longer value");
    // The first set of a key stores a serialized blob on the secondary.
    // Any set after that stores a deserialized RedisString on the secondary.
    // So we do an extra set here so that the size will be consistent between thw two calls.
    // Note: we don't know which server will be the primary and which the secondary.
    jedis.set(STRING_KEY, "longer value");

    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    jedis.set(STRING_KEY, "value");

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isLessThan(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isLessThan(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_resetMemoryUsage_givenFlushAllCommand() {
    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(initialDataStoreBytesInUse1).isEqualTo(0L);
    assertThat(initialDataStoreBytesInUse2).isEqualTo(0L);

    jedis.set(STRING_KEY, "value");

    clusterStartUpRule.flushAll();

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isEqualTo(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isEqualTo(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_showNoIncreaseInDatastoreBytesInUse_givenStringValueSizeDoesNotIncrease() {
    jedis.set(STRING_KEY, "value");
    // The first set of a key stores a serialized blob on the secondary.
    // Any set after that stores a deserialized RedisString on the secondary.
    // So we do an extra set here so that the size will be consistent between thw two calls.
    // Note: we don't know which server will be the primary and which the secondary.
    jedis.set(STRING_KEY, "value");

    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 1000; i++) {
      jedis.set(STRING_KEY, "value");
    }

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isEqualTo(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isEqualTo(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_showIncreaseInDatastoreBytesInUse_givenSetValueSizeIncreases() {
    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 1000; i++) {
      jedis.sadd(SET_KEY, "value" + i);
    }

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isGreaterThan(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isGreaterThan(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_showNoIncreaseInDatastoreBytesInUse_givenSetValueSizeDoesNotIncrease() {
    jedis.sadd(SET_KEY, "value");

    long initialDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long initialDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 1000; i++) {
      jedis.sadd(SET_KEY, "value");
    }

    assertThat(jedis.scard(SET_KEY)).isEqualTo(1);

    long finalDataStoreBytesInUse1 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long finalDataStoreBytesInUse2 =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse1).isEqualTo(initialDataStoreBytesInUse1);
    assertThat(finalDataStoreBytesInUse2).isEqualTo(initialDataStoreBytesInUse2);
  }

  @Test
  public void should_showDecreaseInDatastoreBytesInUse_givenSetValueDeleted() {
    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    jedis.sadd(SET_KEY, "value");

    long intermediateDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    assertThat(intermediateDataStoreBytesInUse).isGreaterThan(initialDataStoreBytesInUse);

    jedis.del(SET_KEY);

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isEqualTo(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showDecreaseInDatastoreBytesInUse_givenSetValueSizeDecreases() {
    for (int i = 0; i < 10; i++) {
      jedis.sadd(SET_KEY, "value" + i);
    }

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    for (int i = 0; i < 10; i++) {
      jedis.srem(SET_KEY, "value" + i);
    }

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isLessThan(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showIncreaseInDatastoreBytesInUse_givenHashValueSizeIncreases() {
    jedis.hset(HASH_KEY, FIELD, "value");

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    for (int i = 0; i < 1000; i++) {
      jedis.hset(HASH_KEY, FIELD + i, LONG_APPEND_VALUE);
    }

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isGreaterThan(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showDecreaseInDatastoreBytesInUse_givenHashValueDeleted() {
    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    jedis.hset(HASH_KEY, FIELD, "value");

    long intermediateDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    assertThat(intermediateDataStoreBytesInUse).isGreaterThan(initialDataStoreBytesInUse);

    jedis.del(HASH_KEY);

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isEqualTo(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showNoIncreaseInDatastoreBytesInUse_givenHSetDoesNotIncreaseHashSize() {
    jedis.hset(HASH_KEY, FIELD, "initialvalue"); // two hsets are required to force
    jedis.hset(HASH_KEY, FIELD, "value"); // deserialization on both servers
    // otherwise primary/secondary can disagree on size, and which server is primary varies

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 10; i++) {
      jedis.hset(HASH_KEY, FIELD, "value");
    }

    assertThat(jedis.hgetAll(HASH_KEY).size()).isEqualTo(1);

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(finalDataStoreBytesInUse).isEqualTo(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showIncreaseInDatastoreBytesInUse_givenHSetNXIncreasesHashSize() {
    jedis.hset(HASH_KEY, FIELD, "value");

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    for (int i = 0; i < 1000; i++) {
      jedis.hsetnx(HASH_KEY, FIELD + i, "value");
    }

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isGreaterThan(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showNoIncreaseInDatastoreBytesInUse_givenHSetNXDoesNotIncreaseHashSize() {
    jedis.hset(HASH_KEY, FIELD, "value");

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    for (int i = 0; i < 1000; i++) {
      jedis.hsetnx(HASH_KEY, FIELD, "value");
    }

    long finalDataStoreBytesInUse = clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(finalDataStoreBytesInUse).isEqualTo(initialDataStoreBytesInUse);
  }

  /******* confirm that the other member agrees upon size *******/

  @Test
  public void should_showMembersAgreeUponUsedHashMemory_afterDeltaPropagation() {
    jedis.hset(HASH_KEY, FIELD, "initialvalue"); // two hsets are required to force
    jedis.hset(HASH_KEY, FIELD, "finalvalue"); // deserialization on both servers
    // otherwise primary/secondary can disagree on size, and which server is primary varies

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 10; i++) {
      jedis.hset(HASH_KEY, FIELD, "finalvalue");
    }

    assertThat(jedis.hgetAll(HASH_KEY).size()).isEqualTo(1);

    long server2FinalDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);
    long server1FinalDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);

    assertThat(server1FinalDataStoreBytesInUse)
        .isEqualTo(server2FinalDataStoreBytesInUse)
        .isEqualTo(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showMembersAgreeUponUsedSetMemory_afterDeltaPropagationWhenAddingMembers() {
    jedis.sadd(SET_KEY, "other"); // two sadds are required to force
    jedis.sadd(SET_KEY, "value"); // deserialization on both servers
    // otherwise primary/secondary can disagree on size, and which server is primary varies

    long initialDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    for (int i = 0; i < 10; i++) {
      jedis.sadd(SET_KEY, "value");
    }

    assertThat(jedis.scard(SET_KEY)).isEqualTo(2);

    long server1FinalDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long server2FinalDataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(server1FinalDataStoreBytesInUse)
        .isEqualTo(server2FinalDataStoreBytesInUse)
        .isEqualTo(initialDataStoreBytesInUse);
  }

  @Test
  public void should_showMembersAgreeUponUsedSetMemory_afterDeltaPropagationWhenRemovingMembers() {
    String value1 = "value1";
    String value2 = "value2";
    jedis.sadd(SET_KEY, value1); // two sadds are required to force
    jedis.sadd(SET_KEY, value2); // deserialization on both servers
    // otherwise primary/secondary can disagree on size, and which server is primary varies

    jedis.sadd(SET_KEY, "value3");

    jedis.srem(SET_KEY, value1, value2);

    assertThat(jedis.scard(SET_KEY)).isEqualTo(1);

    long server1DataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long server2DataStoreBytesInUse =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(server1DataStoreBytesInUse).isEqualTo(server2DataStoreBytesInUse);
  }

  @Test
  public void bothPrimaryAndSecondaryChangeWhenRedisStringAddedAndRemoved() {
    long server1SizeBeforeSet =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long server2SizeBeforeSet =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    jedis.set(STRING_KEY, "value");

    long server1SizeAfterSet =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long server2SizeAfterSet =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    jedis.del(STRING_KEY);

    long server1SizeAfterDel =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server1);
    long server2SizeAfterDel =
        clusterStartUpRule.getDataStoreBytesInUseForDataRegion(server2);

    assertThat(server1SizeAfterSet)
        .isGreaterThan(server1SizeBeforeSet);
    assertThat(server2SizeAfterSet)
        .isGreaterThan(server2SizeBeforeSet);

    assertThat(server1SizeAfterDel)
        .isEqualTo(server1SizeBeforeSet);
    assertThat(server2SizeAfterDel)
        .isEqualTo(server2SizeBeforeSet);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zeroseven.atomscript">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ConsoleActivity"
            android:icon="@mipmap/ic_launcher">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="file" />
                <data android:host="*" />
                <data android:mimeType="*/*" />
                <data android:pathPattern=".*\\.atom" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="http" />
                <data android:host="*" />
                <data android:mimeType="*/*" />
                <data android:pathPattern=".*\\.atom" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="atomscript" />
                <data android:host="*" />
                <data android:mimeType="*/*" />
                <data android:pathPattern=".*\\.atom" />
            </intent-filter>

        </activity>
        <activity
            android:name=".UiActivity"
            android:icon="@mipmap/ic_launcher">
        </activity>
    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using BEPUutilities;
using BEPUutilities.DataStructures;

namespace BEPUik
{
    /// <summary>
    /// Piece of a character which is moved by constraints.
    /// </summary>
    public class Bone
    {
        internal List<IKJoint> joints = new List<IKJoint>();

        /// <summary>
        /// Gets or sets the position of the bone.
        /// </summary>
        public Vector3 Position;

        /// <summary>
        /// Gets or sets the orientation of the bone.
        /// </summary>
        public Quaternion Orientation = Quaternion.Identity;

        /// <summary>
        /// The mid-iteration angular velocity associated with the bone.
        /// This is computed during the velocity subiterations and then applied to the orientation at the end of each position iteration.
        /// </summary>
        internal Vector3 angularVelocity;

        /// <summary>
        /// The mid-iteration linear velocity associated with the bone.
        /// This is computed during the velocity subiterations and then applied to the position at the end of each position iteration.
        /// </summary>
        internal Vector3 linearVelocity;

        internal float inverseMass;

        /// <summary>
        /// Gets or sets the mass of the bone.
        /// High mass bones resist motion more than those of small mass.
        /// Setting the mass updates the inertia tensor of the bone.
        /// </summary>
        public float Mass
        {
            get { return 1 / inverseMass; }
            set
            {
                if (value > 0)
                    inverseMass = 1 / value;
                else
                    throw new ArgumentException("Mass must be positive.");
                ComputeLocalInertiaTensor();
            }
        }

        internal Matrix3x3 inertiaTensorInverse;
        internal Matrix3x3 localInertiaTensorInverse;

        /// <summary>
        /// An arbitrary scaling factor is applied to the inertia tensor. This tends to improve stability.
        /// </summary>
        public static float InertiaTensorScaling = 2.5f;

        /// <summary>
        /// Gets the list of joints affecting this bone.
        /// </summary>
        public ReadOnlyList<IKJoint> Joints
        {
            get { return new ReadOnlyList<IKJoint>(joints); }
        }

        /// <summary>
        /// Gets or sets whether or not this bone is pinned. Pinned bones cannot be moved by constraints.
        /// </summary>
        public bool Pinned { get; set; }

        /// <summary>
        /// Gets whether or not the bone is a member of the active set as determined by the last IK solver execution.
        /// </summary>
        public bool IsActive { get; internal set; }

        private float radius;
        /// <summary>
        /// Gets or sets the radius of the bone.
        /// Setting the radius changes the inertia tensor of the bone.
        /// </summary>
        public float Radius
        {
            get
            { return radius; }
            set
            {
                radius = value;
                ComputeLocalInertiaTensor();
            }
        }

        private float halfHeight;
        /// <summary>
        /// Gets or sets the height, divided by two, of the bone.
        /// The half height extends both ways from the center position of the bone.
        /// Setting the half height changes the inertia tensor of the bone.
        /// </summary>
        public float HalfHeight
        {
            get { return halfHeight; }
            set
            {
                halfHeight = value;
                ComputeLocalInertiaTensor();
            }
        }

        /// <summary>
        /// Gets or sets the height of the bone.
        /// Setting the height changes the inertia tensor of the bone.
        /// </summary>
        public float Height
        {
            get { return halfHeight * 2; }
            set
            {
                halfHeight = value / 2;
                ComputeLocalInertiaTensor();
            }
        }

        /// <summary>
        /// Constructs a new bone.
        /// </summary>
        /// <param name="position">Initial position of the bone.</param>
        /// <param name="orientation">Initial orientation of the bone.</param>
        /// <param name="radius">Radius of the bone.</param>
        /// <param name="height">Height of the bone.</param>
        /// <param name="mass">Mass of the bone.</param>
        public Bone(Vector3 position, Quaternion orientation, float radius, float height, float mass)
            :this(position, orientation, radius, height)
        {
            Mass = mass;
        }

        /// <summary>
        /// Constructs a new bone. Assumes the mass will be set later.
        /// </summary>
        /// <param name="position">Initial position of the bone.</param>
        /// <param name="orientation">Initial orientation of the bone.</param>
        /// <param name="radius">Radius of the bone.</param>
        /// <param name="height">Height of the bone.</param>
        public Bone(Vector3 position, Quaternion orientation, float radius, float height)
        {
            Mass = 1;
            Position = position;
            Orientation = orientation;
            Radius = radius;
            Height = height;
        }

        void ComputeLocalInertiaTensor()
        {
            var localInertiaTensor = new Matrix3x3();
            var multiplier = Mass * InertiaTensorScaling;
            float diagValue = (.0833333333f * Height * Height + .25f * Radius * Radius) * multiplier;
            localInertiaTensor.M11 = diagValue;
            localInertiaTensor.M22 = .5f * Radius * Radius * multiplier;
            localInertiaTensor.M33 = diagValue;
            Matrix3x3.Invert(ref localInertiaTensor, out localInertiaTensorInverse);
        }

        /// <summary>
        /// Updates the world inertia tensor based upon the local inertia tensor and current orientation.
        /// </summary>
        internal void UpdateInertiaTensor()
        {
            //This is separate from the position update because the orientation can change outside of our iteration loop, so this has to run first.
            //Iworld^-1 = RT * Ilocal^1 * R
            Matrix3x3 orientationMatrix;
            Matrix3x3.CreateFromQuaternion(ref Orientation, out orientationMatrix);
            Matrix3x3.MultiplyTransposed(ref orientationMatrix, ref localInertiaTensorInverse, out inertiaTensorInverse);
            Matrix3x3.Multiply(ref inertiaTensorInverse, ref orientationMatrix, out inertiaTensorInverse);
        }

        /// <summary>
        /// Integrates the position and orientation of the bone forward based upon the current linear and angular velocity.
        /// </summary>
        internal void UpdatePosition()
        {
            //Update the position based on the linear velocity.
            Vector3.Add(ref Position, ref linearVelocity, out Position);

            //Update the orientation based on the angular velocity.
            Vector3 increment;
            Vector3.Multiply(ref angularVelocity, .5f, out increment);
            var multiplier = new Quaternion(increment.X, increment.Y, increment.Z, 0);
            Quaternion.Multiply(ref multiplier, ref Orientation, out multiplier);
            Quaternion.Add(ref Orientation, ref multiplier, out Orientation);
            Orientation.Normalize();

            //Eliminate any latent velocity in the bone to prevent unwanted simulation feedback.
            //This is the only thing conceptually separating this "IK" solver from the regular dynamics loop in BEPUphysics.
            //(Well, that and the whole lack of collision detection...)
            linearVelocity = new Vector3();
            angularVelocity = new Vector3();

            //Note: Unlike a regular dynamics simulation, we do not include any 'dt' parameter in the above integration.
            //Setting the velocity to 0 every update means that no more than a single iteration's worth of velocity accumulates.
            //Since the softness of constraints already varies with the time step and bones never accelerate for more than one frame,
            //scaling the velocity for position integration actually turns out generally worse.
            //This is not a rigorously justifiable approach, but this isn't a regular dynamic simulation anyway.
        }

        internal void ApplyLinearImpulse(ref Vector3 impulse)
        {
            Vector3 velocityChange;
            Vector3.Multiply(ref impulse, inverseMass, out velocityChange);
            Vector3.Add(ref linearVelocity, ref velocityChange, out linearVelocity);
        }

        internal void ApplyAngularImpulse(ref Vector3 impulse)
        {
            Vector3 velocityChange;
            Matrix3x3.Transform(ref impulse, ref inertiaTensorInverse, out velocityChange);
            Vector3.Add(ref velocityChange, ref angularVelocity, out angularVelocity);
        }

        /// <summary>
        /// Used by the per-control traversals to find stressed paths.
        /// It has to be separate from the IsActive flag because the IsActive flag is used in the same traversal
        /// to denote all visited bones (including unstressed ones).
        /// Also used in the unstressed traversals; FindCycles uses the IsActive flag and the following DistributeMass phase uses the traversed flag.
        /// </summary>
        internal bool traversed;

        /// <summary>
        /// The number of stressed paths which use this bone. A stressed path is a possible path between a pin and a control.
        /// </summary>
        internal int stressCount;

        /// <summary>
        /// The set of parents of a given bone in a traversal. This is like a list of parents; there can be multiple incoming paths and they all need to be kept handy in order to perform some traversal details.
        /// </summary>
        internal List<Bone> predecessors = new List<Bone>();

        /// <summary>
        /// True of the bone is a member of a cycle in an unstressed part of the graph or an unstressed predecessor of an unstressed cycle.
        /// Marking all the predecessors is conceptually simpler than attempting to mark the cycles in isolation.
        /// </summary>
        internal bool unstressedCycle;

        /// <summary>
        /// True if the bone is targeted by a control in the current stress cycle traversal that isn't the current source control.
        /// </summary>
        internal  bool targetedByOtherControl;
    }
}


text:
package com.google.devtools.depan.nodes.filters.eclipse.ui.widgets;

import com.google.devtools.depan.nodes.filters.sequence.ComposeMode;
import com.google.devtools.depan.platform.AlphabeticSorter;
import com.google.devtools.depan.platform.ViewerObjectToString;
import com.google.devtools.depan.platform.eclipse.ui.widgets.Selections;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

/**
 * Allow the user to choice among several values for {@link ComposeMode}.
 *
 * @author Lee Carver
 */
public class ComposeModeControl extends Composite {

  private final ComboViewer viewer;

  private ControlSelectionChangedListener listener;

  public ComposeModeControl(Composite parent) {
    super(parent, SWT.NONE);
    setLayout(new FillLayout());

    viewer = new ComboViewer(this, SWT.READ_ONLY | SWT.FLAT);
    viewer.setContentProvider(new ArrayContentProvider());
    viewer.setLabelProvider(CONTROL_LABEL_PROVIDER);
    viewer.setComparator(new AlphabeticSorter(new ViewerObjectToString() {

        @Override
        public String getString(Object object) {
          return CONTROL_LABEL_PROVIDER.getText(object);
        }
      }));

    viewer.setInput(ComposeMode.values());

    listener = new ControlSelectionChangedListener();
    viewer.addSelectionChangedListener(listener);
  }

  private static ControlLabelProvider CONTROL_LABEL_PROVIDER =
      new ControlLabelProvider();

  private static class ControlLabelProvider extends LabelProvider {

    @Override
    public String getText(Object element) {
      if (element instanceof ComposeMode) {
        ComposeMode item = (ComposeMode) element;
        return item.getTitle();
      }

      // Not what was expected.
      return null;
    }
  }

  public void setComposeMode(ComposeMode mode) {
    viewer.setSelection(new StructuredSelection(mode));
  }

  public ComposeMode getComposeMode() {
    return listener.getChoice();
  }

  private class ControlSelectionChangedListener
      implements ISelectionChangedListener {

    private ComposeMode choice;

    @Override
    public void selectionChanged(SelectionChangedEvent event) {
      ISelection selection = event.getSelection();
      choice = Selections.getFirstElement(selection, ComposeMode.class);
    }

    public ComposeMode getChoice() {
      return choice;
    }
  }
}


text:
const data = fc.randomFinancial()(50);

const container = document.querySelector('d3fc-canvas');

const xScale = d3
    .scaleTime()
    .domain(fc.extentDate().accessors([d => d.date])(data));

const yScale = d3
    .scaleLinear()
    .domain(fc.extentLinear().accessors([d => d.high])(data));

const series = fc
    .seriesCanvasCandlestick()
    .xScale(xScale)
    .yScale(yScale);

d3.select(container)
    .on('draw', () => {
        series(data);
    })
    .on('measure', event => {
        const { width, height } = event.detail;
        xScale.range([0, width]);
        yScale.range([height, 0]);

        const ctx = container.querySelector('canvas').getContext('2d');
        series.context(ctx);
    });

container.requestRedraw();


text:
def add_native_methods(clazz):
    def getGlyphPointNative__sun_font_Font2D__long__long__int__int__(a0, a1, a2, a3, a4, a5):
        raise NotImplementedError()

    def createScalerContextNative__long__double____int__int__float__float__(a0, a1, a2, a3, a4, a5, a6):
        raise NotImplementedError()

    clazz.getGlyphPointNative__sun_font_Font2D__long__long__int__int__ = getGlyphPointNative__sun_font_Font2D__long__long__int__int__
    clazz.createScalerContextNative__long__double____int__int__float__float__ = createScalerContextNative__long__double____int__int__float__float__


text:
DatFileLogger::DatFileLogger(LoggerParameters loggerParams, std::string coordinateName) :
		_file{ loggerParams.filepath + loggerParams.name + "_results_" + coordinateName + ".dat" }
	{
		if (!_file) {
			throw std::runtime_error{ "the file was not created" };
		}

	}
DatFileLogger::~DatFileLogger()
{
	_file.close();
}
void DatFileLogger::save(const std::string& dataToLog) {
	_file << dataToLog;
	}


text:
require 'grape'
require_relative '../config/mongo'
require_relative 'entities/standard_set'
require_relative '../importer/transformers/query_to_standard_set'
require_relative '../lib/standard_hierarchy'

module API
  class StandardSets < Grape::API

    namespace "/standard_sets", desc: "Standards grouped by grade level & subject" do

      desc "Fetch a standards set", entity: Entities::StandardSet
      params do
        requires :id, type: String, desc: "ID", default: "49FCDFBD2CF04033A9C347BFA0584DF0_D2604890_grade-01"
        optional :standardsAsArray, type: Boolean, desc: "Send back standards as an array instead of a dictionary", default: false
      end
      get "/:id" do
        standard_set = $db[:standard_sets].find({
          :_id => params.id
        }).to_a.first

        return {data:{}} if standard_set.nil?

        # Add the ancestor ids to the response. This a read only field
        standard_set["standards"] = StandardHierarchy.add_ancestor_ids(standard_set["standards"])
        if params[:standardsAsArray]
          standard_set["standards"] = standard_set["standards"].values
        end
        standard_set["educationLevels"] ||= []
        standard_set["id"] = standard_set["_id"]

        present :data, standard_set, with: Entities::StandardSet
      end

      desc "To preview the results of a standard set query, we call this api."
      post "/from_query", hidden: true do
        validate_token
        standards_doc = $db[:standard_documents].find({
          :_id => params.standardsDocumentId
        }).to_a.first

        QueryToStandardSet.generate(standards_doc, params.query.to_hash)
      end

    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Trommsdorffia pulverulenta Mart.

### Remarks
null


text:
package mcjty.rftools.shapes;

import io.netty.buffer.ByteBuf;
import mcjty.lib.network.NetworkTools;
import mcjty.lib.thirteen.Context;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;

import java.util.List;
import java.util.function.Supplier;

public class PacketReturnExtraData implements IMessage {

    private int scanId;
    private ScanExtraData data;

    @Override
    public void fromBytes(ByteBuf buf) {
        scanId = buf.readInt();
        int size = buf.readInt();
        if (size == -1) {
            data = null;
        } else {
            data = new ScanExtraData();
            for (int i = 0; i < size; i++) {
                BlockPos pos = NetworkTools.readPos(buf);
                BeaconType type = BeaconType.VALUES[buf.readByte()];
                boolean doBeacon = buf.readBoolean();
                data.addBeacon(pos, type, doBeacon);
            }
        }
    }

    @Override
    public void toBytes(ByteBuf buf) {
        buf.writeInt(scanId);
        if (data == null) {
            buf.writeInt(-1);
        } else {
            List<ScanExtraData.Beacon> beacons = data.getBeacons();
            buf.writeInt(beacons.size());
            for (ScanExtraData.Beacon beacon : beacons) {
                NetworkTools.writePos(buf, beacon.getPos());
                buf.writeByte(beacon.getType().ordinal());
                buf.writeBoolean(beacon.isDoBeacon());
            }
        }
    }

    public PacketReturnExtraData() {
    }

    public PacketReturnExtraData(ByteBuf buf) {
        fromBytes(buf);
    }

    public PacketReturnExtraData(int scanId, ScanExtraData extraData) {
        this.scanId = scanId;
        this.data = extraData;
    }

    public void handle(Supplier<Context> supplier) {
        Context ctx = supplier.get();
        ctx.enqueueWork(() -> {
            ScanDataManagerClient.getScansClient().registerExtraDataFromServer(scanId, data);
        });
        ctx.setPacketHandled(true);
    }
}


text:
package eu.hansolo.enzo.ledbargraph;

import eu.hansolo.enzo.led.Led;
import eu.hansolo.enzo.ledbargraph.skin.LedBargraphSkin;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.geometry.Orientation;
import javafx.scene.control.Control;
import javafx.scene.control.Skin;
import javafx.scene.paint.Color;

import java.util.List;

/**
 * Created by
 * User: hansolo
 * Date: 16.02.12
 * Time: 11:29
 */
public class LedBargraph extends Control {
    private Led.LedType _ledType = Led.LedType.ROUND;
    private ObjectProperty<Led.LedType>    ledType;
    private boolean                     _frameVisible = false;
    private BooleanProperty             frameVisible;
    private double                      _ledSize = 16;
    private DoubleProperty              ledSize;
    private Orientation                 _orientation = Orientation.HORIZONTAL;
    private ObjectProperty<Orientation> orientation;
    private int                         _noOfLeds = 16;
    private IntegerProperty             noOfLeds;
    private ListProperty<Color>         ledColors;
    private boolean                     _peakValueVisible = false;
    private BooleanProperty             peakValueVisible;
    private DoubleProperty              value;

    // ******************** Constructors **************************************
    public LedBargraph() {
        getStyleClass().add("bargraph");
        ledColors = new SimpleListProperty(this, "ledColors", FXCollections.<Color>observableArrayList());
        value     = new SimpleDoubleProperty(this, "value", 0);

        for (int i = 0 ; i < getNoOfLeds() ; i++) {
            if (i < 11) {
                ledColors.get().add(Color.LIME);
            } else if (i > 10 && i < 13) {
                ledColors.get().add(Color.YELLOW);
            } else {
                ledColors.get().add(Color.RED);
            }
        }
    }

    // ******************** Methods *******************************************
    public final Led.LedType getLedType() {
        return null == ledType ? _ledType : ledType.get();
    }
    public final void setLedType(final Led.LedType LED_TYPE) {
        if (null == ledType) {
            _ledType = LED_TYPE;
        } else {
            ledType.set(LED_TYPE);
        }
    }
    public final ObjectProperty<Led.LedType> ledTypeProperty() {
        if (null == ledType) {
            ledType = new SimpleObjectProperty<>(this, "ledType", _ledType);
        }
        return ledType;
    }

    public final boolean isFrameVisible() {
        return null == frameVisible ? _frameVisible : frameVisible.get();
    }
    public final void setFrameVisible(final boolean FRAME_VISIBLE) {
        if (null == frameVisible) {
            _frameVisible = FRAME_VISIBLE;
        } else {
            frameVisible.set(FRAME_VISIBLE);
        }
    }
    public final BooleanProperty frameVisibleProperty() {
        if (null == frameVisible) {
            frameVisible = new SimpleBooleanProperty(this, "frameVisible", _frameVisible);
        }
        return frameVisible;
    }

    public final double getLedSize() {
        return null == ledSize ? _ledSize : ledSize.get();
    }
    public final void setLedSize(final double LED_SIZE) {
        double size = LED_SIZE < 10 ? 10 : (LED_SIZE > 50 ? 50 : LED_SIZE);
        if (null == ledSize) {
            _ledSize = size;
        } else {
            ledSize.set(size);
        }
    }
    public final DoubleProperty ledSizeProperty() {
        if (null == ledSize) {
            ledSize = new SimpleDoubleProperty(this, "ledSize", _ledSize);
        }
        return ledSize;
    }

    public final Orientation getOrientation() {
        return null == orientation ? _orientation : orientation.get();
    }
    public final void setOrientation(final Orientation ORIENTATION) {
        if (null == orientation) {
            _orientation = ORIENTATION;
        } else {
            orientation.set(ORIENTATION);
        }
    }
    public final ObjectProperty<Orientation> orientationProperty() {
        if (null == orientation) {
            orientation = new SimpleObjectProperty<>(this, "orientation", _orientation);
        }
        return orientation;
    }

    public final int getNoOfLeds() {
        return null == noOfLeds ? _noOfLeds : noOfLeds.get();
    }
    public final void setNoOfLeds(final int NO_OF_LEDS) {
        int amount = NO_OF_LEDS < 5 ? 5 : NO_OF_LEDS;
        if (amount > noOfLeds.get()) {
            for (int i = 0 ; i < (amount - noOfLeds.get()) ; i++) {
                ledColors.get().add(Color.RED);
            }
        }
        if (null == noOfLeds) {
            _noOfLeds = amount;
        } else {
            noOfLeds.set(amount);
        }
    }
    public final IntegerProperty noOfLedsProperty() {
        if (null == noOfLeds) {
            noOfLeds = new SimpleIntegerProperty(this, "noOfLeds", _noOfLeds);
        }
        return noOfLeds;
    }

    public final List<Color> getLedColors() {
        return ledColors.get();
    }
    public final void setLedColors(final List<Color> LED_COLORS) {
        ledColors.get().setAll(LED_COLORS);
    }
    public final ListProperty<Color> ledColorsProperty() {
        return ledColors;
    }

    public final Color getLedColor(final int INDEX) {
        Color ledColor;
        if (INDEX < 0) {
            ledColor = ledColors.get().get(0);
        } else if (INDEX > getNoOfLeds() - 1) {
            ledColor = ledColors.get().get(getNoOfLeds() - 1);
        } else {
            ledColor = ledColors.get().get(INDEX);
        }
        return ledColor;
    }
    public final void setLedColor(final int INDEX, final Color COLOR) {
        int realIndex = INDEX - 1;
        if (realIndex < 0) {
            ledColors.get().set(0, COLOR);
        } else if (realIndex > noOfLeds.get() - 1) {
            ledColors.get().set(noOfLeds.get() - 1, COLOR);
        } else {
            ledColors.get().set(realIndex, COLOR);
        }
    }

    public final boolean isPeakValueVisible() {
        return null == peakValueVisible ? _peakValueVisible : peakValueVisible.get();
    }
    public final void setPeakValueVisible(final boolean PEAK_VALUE_VISIBLE) {
        if (null == peakValueVisible) {
            _peakValueVisible = PEAK_VALUE_VISIBLE;
        } else {
            peakValueVisible.set(PEAK_VALUE_VISIBLE);
        }
    }
    public final BooleanProperty peakValueVisibleProperty() {
        if (null == peakValueVisible) {
            peakValueVisible = new SimpleBooleanProperty(this, "peakValueVisible", _peakValueVisible);
        }
        return peakValueVisible;
    }

    public final double getValue() {
        return value.get();
    }
    public final void setValue(final double VALUE) {
        double val = VALUE < 0 ? 0 : (VALUE > 1 ? 1 : VALUE);
        value.set(val);
    }
    public final DoubleProperty valueProperty() {
        return value;
    }

    // ******************** Stylesheet handling *******************************
    @Override protected Skin createDefaultSkin() {
        return new LedBargraphSkin(this);
    }

    @Override public String getUserAgentStylesheet() {
        return getClass().getResource("ledbargraph.css").toExternalForm();
    }
}


text:
package http

import (
	"go-common/app/job/main/block/conf"
	"go-common/app/job/main/block/service"
	"go-common/library/log"
	bm "go-common/library/net/http/blademaster"
)

var (
	svc *service.Service
)

// Init init
func Init() {
	initService()
	engine := bm.DefaultServer(conf.Conf.BM)
	router(engine)
	if err := engine.Start(); err != nil {
		log.Error("%+v", err)
		panic(err)
	}
}

// initService init services.
func initService() {
	svc = service.New()
}

// router init inner router api path.
func router(e *bm.Engine) {
	//init api
	e.GET("/monitor/ping", ping)
}

// ping check server ok.
func ping(c *bm.Context) {
}


text:
namespace omaha {

namespace internal {

// The class structure is as following:
//    - NetworkRequest and the underlying NetworkRequestImpl provide fault
//      tolerant client server http transactions.
//    - HttpRequestInterface defines an interface for different mechanisms that
//      can move bytes between the client and the server. These mechanisms are
//      chained up so that the control passes from one mechanism to the next
//      until one of them is able to fulfill the request or an error is
//      generated. Currently, SimpleRequest and BitsRequest are provided.
//    - HttpClient is the c++ wrapper over winhttp-wininet.
class NetworkRequestImpl {
 public:
  explicit NetworkRequestImpl(const NetworkConfig::Session& network_session);
  ~NetworkRequestImpl();

  HRESULT Close();

  void AddHttpRequest(HttpRequestInterface* http_request);

  HRESULT Post(const CString& url,
               const void* buffer,
               size_t length,
               std::vector<uint8>* response);
  HRESULT Get(const CString& url, std::vector<uint8>* response);
  HRESULT DownloadFile(const CString& url, const CString& filename);

  HRESULT Pause();
  HRESULT Resume();
  HRESULT Cancel();

  void AddHeader(const TCHAR* name, const TCHAR* value);

  HRESULT QueryHeadersString(uint32 info_level,
                             const TCHAR* name,
                             CString* value);

  int http_status_code() const { return http_status_code_; }

  CString response_headers() const { return response_headers_; }

  void set_proxy_auth_config(const ProxyAuthConfig& proxy_auth_config) {
    proxy_auth_config_ = proxy_auth_config;
  }

  void set_num_retries(int num_retries) { num_retries_ = num_retries; }

  void set_time_between_retries(int time_between_retries_ms) {
    initial_retry_delay_ms_ = time_between_retries_ms;
  }

  void set_retry_delay_jitter(int jitter_ms) {
    retry_delay_jitter_ms_ = jitter_ms;
  }

  void set_callback(NetworkRequestCallback* callback) {
    callback_ = callback;
  }

  void set_low_priority(bool low_priority) { low_priority_ = low_priority; }

  void set_proxy_configuration(const ProxyConfig* proxy_configuration) {
    if (proxy_configuration) {
      proxy_configuration_.reset(new ProxyConfig);
      *proxy_configuration_ = *proxy_configuration;
    } else {
      proxy_configuration_.reset();
    }
  }

  CString trace() const { return trace_; }

  std::vector<DownloadMetrics> download_metrics() const {
    return download_metrics_;
  }

  // Detects the available proxy configurations and returns the chain of
  // configurations to be used.
  void DetectProxyConfiguration(
      std::vector<ProxyConfig>* proxy_configurations) const;

 private:
  // Resets the state of the output data members.
  void Reset();

  // Sends the request with a retry policy. This is the only function that
  // modifies the state of the output data members: the status code, the
  // response headers, and the response. When errors are encountered, the
  // output data members contain the values corresponding to first network
  // configuration and first HttpRequest instance in the fallback chain.
  HRESULT DoSendWithRetries();

  // Sends a single request and receives the response.
  HRESULT DoSend(int* http_status_code,
                 CString* response_headers,
                 std::vector<uint8>* response);

  // Sends the request using the current configuration. The request is tried for
  // each HttpRequestInterface in the fallback chain until one of them succeeds
  // or the end of the chain is reached.
  HRESULT DoSendWithConfig(int* http_status_code,
                           CString* response_headers,
                           std::vector<uint8>* response);

  // Sends an http request using the current HttpRequest interface over the
  // current network configuration.
  HRESULT DoSendHttpRequest(int* http_status_code,
                            CString* response_headers,
                            std::vector<uint8>* response);

  // Returns true if we should continue to retry a network request, false if
  // we should bail out early.
  bool CanRetryRequest();

  // Delays for a specified interval, notifying any specified callbacks at the
  // beginning and end of the wait.
  HRESULT DoWaitBetweenRetries();

  // Adjusts the delay until the next retry, given the current retry status
  // and the result of the previous network attempt.
  void ComputeNextRetryDelay(HttpClient::StatusCodeClass previous_result);

  // Builds headers for the current HttpRequest and network configuration.
  CString BuildPerRequestHeaders() const;

  // Specifies the chain of HttpRequestInterface to handle the request.
  std::vector<HttpRequestInterface*> http_request_chain_;

  // Specifies the detected proxy configurations.
  std::vector<ProxyConfig> proxy_configurations_;

  // Specifies the proxy configuration override. When set, the proxy
  // configurations are not auto detected.
  std::unique_ptr<ProxyConfig> proxy_configuration_;

  // Input data members.
  // The request and response buffers are owner by the caller.
  CString  url_;
  const void* request_buffer_;     // Contains the request body for POST.
  size_t   request_buffer_length_;  // Length of the request body.
  CString  filename_;              // Contains the response for downloads.
  CString  additional_headers_;    // Headers common to all requests.
                                   // Each header is separated by \r\n.
  ProxyAuthConfig proxy_auth_config_;
  int      num_retries_;
  bool     low_priority_;
  int      initial_retry_delay_ms_;
  int      retry_delay_jitter_ms_;

  // Output data members.
  int      http_status_code_;
  CString  response_headers_;      // Each header is separated by \r\n.
  std::vector<uint8>* response_;   // Contains the response for Post and Get.

  const NetworkConfig::Session  network_session_;
  NetworkRequestCallback*       callback_;

  // The http request and the network configuration currently in use.
  HttpRequestInterface* cur_http_request_;
  const ProxyConfig*    cur_proxy_config_;

  // The HRESULT and HTTP status code updated by the prior
  // DoSendHttpRequest() call.
  HRESULT  last_hr_;
  int      last_http_status_code_;

  // Stores the last valid value of the optional X-Retry-After header or -1 if
  // the header was not present in the request. Only HTTPS X-Retry-After header
  // values are respected.
  // If the server sends a positive value in seconds for this header, the
  // request will stop processing fallbacks and will return from the
  // NetworkRequestImpl::DoSendWithRetries() call immediately.
  int retry_after_seconds_;

  // The current retry count and delay between retries, defined by the outermost
  // DoSendWithRetries() call.
  int cur_retry_count_;
  int cur_retry_delay_ms_;

  // Count of DoSendHttpRequest() calls.
  int http_attempts_;

  volatile LONG is_canceled_;
  scoped_event event_cancel_;

  LLock lock_;

  // Contains the trace of the request as handled by the fallback chain.
  CString trace_;

  std::vector<DownloadMetrics> download_metrics_;

  static const int kDefaultTimeBetweenRetriesMs      = 5000;    // 5 seconds.
  static const int kServerErrMinTimeBetweenRetriesMs = 20000;   // 20 seconds.
  static const int kMaxTimeBetweenRetriesMs          = 100000;  // 100 seconds.
  static const int kTimeBetweenRetriesMultiplier     = 2;
  static const int kDefaultRetryTimeJitterMs         = 3000;    // +- 3 seconds.

  DISALLOW_COPY_AND_ASSIGN(NetworkRequestImpl);
};

}   // namespace internal

}   // namespace omaha

#endif  // OMAHA_NET_NETWORK_REQUEST_IMPL_H_


text:
from __future__ import print_function
import httplib2
import re
import os
import sys
import datetime
from functools import total_ordering

import dateutil.parser
import pytz

from jira.exceptions import JIRAError

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

class WorklogParseError(RuntimeError):
    pass

def import_worklogs(jira, jira_user, worklogconfig, calendar_name, from_day, to_day):
    """
    Imports worklogs using the Google Calendar API and sumbits them to JIRA.
    Calendar entries must start with JIRA issue IDs opitionally followed by
    ':' and comments. Returns total hours logged as timedelta.
    """
    if from_day >= to_day:
        print('Start date must be before end date, start:', from_day, 'end:', to_day)
        return 0

    from_day = _convert_to_datestring(from_day, worklogconfig)
    to_day = _convert_to_datestring(to_day, worklogconfig)
    service = _get_calendar_service(worklogconfig)
    calendarId = _get_calendar_id(service, calendar_name)

    eventsResult = service.events().list(calendarId=calendarId, timeMin=from_day, timeMax=to_day,
                                         maxResults=1000, singleEvents=True, orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print('No events found in calendar', calendar_name, 'during', from_day, '-', to_day)
        return 0

    durations = []
    prefix_filter = worklogconfig.WORKLOG_PREFIX_FILTER if hasattr(worklogconfig,
            'WORKLOG_PREFIX_FILTER') and worklogconfig.WORKLOG_PREFIX_FILTER else None
    if prefix_filter:
        print('** Filtering worklogs by prefix', prefix_filter)
        events = [event for event in events if
                event['summary'].startswith(prefix_filter)]
    for event in events:
        try:
            gcal_worklog = Worklog.from_gcal(event)
            jira_worklogs = [Worklog.from_jira(w)
                    for w in jira.worklogs(gcal_worklog.issue)
                    if w.author.key == jira_user]
            # breakpoint()
            if (jira_worklogs and gcal_worklog in jira_worklogs):
                jira_worklog = next(w for w in jira_worklogs if w == gcal_worklog)
                if gcal_worklog.duration != jira_worklog.duration:
                    raise WorklogParseError('Google worklog for issue %s '
                                            'starting at %s: duration %s differs from JIRA duration %s'
                                            % (gcal_worklog.issue, gcal_worklog.start,
                                               gcal_worklog.duration, jira_worklog.duration))
                print(gcal_worklog.duration, 'hours starting', gcal_worklog.start,
                      'already logged for', gcal_worklog.issue)
            else:
                print('Logging', gcal_worklog.duration, 'hours starting', gcal_worklog.start, 'for', gcal_worklog.issue)
                started = gcal_worklog.start
                # Dates in JIRA use JIRA server timezone, tzinfo is ignored, hence manual offset calculation is required
                # if timezone support is required in Jira.
                if worklogconfig.JIRA_TIMEZONE:
                    jira_tz = pytz.timezone(worklogconfig.JIRA_TIMEZONE)
                    started -= jira_tz.utcoffset(gcal_worklog.start.replace(tzinfo=None))
                jira.add_worklog(issue=gcal_worklog.issue,
                                 timeSpentSeconds=gcal_worklog.duration.seconds,
                                 started=started,
                                 comment=gcal_worklog.comment)
                durations.append(gcal_worklog.duration)
        except WorklogParseError as e:
            print(e)
        except JIRAError as e:
            print("Issue '" + gcal_worklog.issue + "' does not exist (or other JIRA error):", e)

    return sum(durations, datetime.timedelta(0))

JIRA_ISSUE_REGEX = re.compile('[A-Z\d]+-\d+')

@total_ordering
class Worklog(object):

    @staticmethod
    def from_gcal(event):
        start = _parse_iso_date(event['start'].get('dateTime'))
        end = _parse_iso_date(event['end'].get('dateTime'))
        duration = end - start
        summary = event['summary']
        summary = event['summary'].split(':', 1)
        issue = summary[0].strip()
        if not JIRA_ISSUE_REGEX.match(issue):
            raise WorklogParseError("'%s' is not a JIRA issue ID" %
                                    issue.encode('utf-8'))
        comment = summary[1].strip() if len(summary) > 1 else ''
        return Worklog(start, duration, issue, comment)

    @staticmethod
    def from_jira(jira_worklog):
        start = _parse_iso_date(jira_worklog.started)
        duration = datetime.timedelta(seconds=jira_worklog.timeSpentSeconds)
        return Worklog(start, duration)

    def __init__(self, start, duration, issue=None, comment=None):
        self.start = start
        self.duration = duration
        self.issue = issue
        self.comment = comment

    def __eq__(self, other):
        if type(self) is not type(other):
            return NotImplemented
        return self.start == other.start

    def __lt__(self, other):
        return NotImplemented

def _convert_to_datestring(datestr, conf):
    return datetime.datetime.strptime(datestr, '%Y-%m-%d').isoformat() + conf.TIMEZONE

def _get_calendar_service(conf):
    credentials = _get_credentials(conf)
    return build('calendar', 'v3', credentials=credentials)

def _get_calendar_id(service, calendar_name):
    calendars = service.calendarList().list().execute().get('items', [])
    calendarId = next((c['id'] for c in calendars
                       if c['summary'] == calendar_name), None)
    if calendarId is None:
        raise RuntimeError("Calendar '%s' not found" % calendar_name)
    return calendarId

def _parse_iso_date(datestr):
    return dateutil.parser.parse(datestr)

def _get_credentials(conf):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    credentials = None
    if os.path.exists(conf.CREDENTIAL_FILE):
        credentials = Credentials.from_authorized_user_file(conf.CREDENTIAL_FILE, conf.SCOPES)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            # avoid mess with argparse
            # sys.argv = [sys.argv[0]]
            flow = InstalledAppFlow.from_client_secrets_file(conf.CLIENT_SECRET_FILE, conf.SCOPES)
            credentials = flow.run_local_server(port=0)
        # Save the credentials for the next run
        print('Storing Google Calendar credentials to', conf.CREDENTIAL_FILE)
        with open(conf.CREDENTIAL_FILE, 'w') as credentials_token:
            credentials_token.write(credentials.to_json())
    return credentials


text:
Apple
:   Pomaceous fruit of plants of the genus Malus in
    the family Rosaceae.

Orange
:   The fruit of an evergreen tree of the genus Citrus.


text:
using System;
using System.Collections.Generic;

namespace Cython.EnergyShields
{
	public class ShieldSaveFile
	{
		public List<ShieldMessage> ShieldGenerators = new List<ShieldMessage>();

		public ShieldSaveFile()
		{
		}
	}
}


text:
package org.semanticweb.elk.owl.interfaces;

import org.semanticweb.elk.owl.visitors.ElkDataExactCardinalityVisitor;

/**
 * A common interface for qualified and unqualified min cardinality restrictions
 * on data.
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface ElkDataExactCardinality
		extends ElkCardinalityRestriction<ElkDataPropertyExpression> {

	/**
	 * Accept an {@link ElkDataExactCardinalityVisitor}.
	 *
	 * @param visitor
	 *            the visitor that can work with this object type
	 * @return the output of the visitor
	 */
	public <O> O accept(ElkDataExactCardinalityVisitor<O> visitor);

	/**
	 * A factory for creating instances
	 *
	 * @author Yevgeny Kazakov
	 *
	 */
	interface Factory extends ElkDataExactCardinalityQualified.Factory,
			ElkDataExactCardinalityUnqualified.Factory {

		// combined interface

	}

}


text:
layout: post
title: Milky way
tags: [stars, milkyway]

category: blog

---

![milky way](https://www.spacetelescope.org/static/archives/images/screen/ann0912a.jpg)

i think this track suits well, i love stars.

<iframe scrolling="no" frameborder="0" allowTransparency="true" src="https://www.deezer.com/plugins/player?autoplay=false&playlist=false&width=542&height=80&cover=true&type=album&id=7769437&title=&app_id=undefined" width="542" height="80"></iframe>

(image via [NASA & ESA](https://www.spacetelescope.org/images/ann0912a/))


text:
layout: post
title: Wordpress Ninja Gaiden
subtitle: Black Side of the Force
bigimg: /img/ninja.gif
---

# Wordpress Ninja Gaiden
Black Side of the Force

## Basic Template Files

### Theme

| Archive  | Function |
| ------------- | ------------- |
| style.css | Style sheet file |
| index.php | Home Page file |
| single.php | Single post page file |
| archive.php | Archive or Category file |
| searchform.php | Search form file |
| search.php | Search content file |
| 404.php | Error page file |
| comments.php | Comments template file |
| footer.php | Footer content file |
| header.php | Header content file |
| sidebar.php | Sidebar content file |
| page.php | Single page file |

### Theme - header

| PHP Snippets for Header         |                                     |
|---------------------------------|-------------------------------------|
| bloginfo('name');               | Title of the site                   |
| wp_title();                     | Title of the specific post or page  |
| get_stylesheet_directory_uri(); | The style.css file's location       |
| bloginfo('pingback_url');       | Pingback URL for this site          |
| bloginfo('template_url');       | Location for the site's theme files |
| bloginfo('version');            | WordPress version for the site      |
| bloginfo('atom_url');           | Atom URL for the site               |
| bloginfo('rss2_url');           | RSS2 URL for the site               |
| get_site_url();                 | Exact URL for the site              |
| bloginfo('name');               | Name of the site                    |
| bloginfo('html_type');          | HTML version of the site            |
| bloginfo('charset');            | Charset parameter of the site       |

### Theme for templates

| PHP Snippets for Templates       	|                                      	|
|----------------------------------	|--------------------------------------	|
| the_content();                   	| Content of the posts                 	|
| if(have_posts()):                	| Check if there are posts             	|
| while(have_posts()): the_post(); 	| Shows posts if posts are available   	|
| endwhile;                        	| Closes the 'while' PHP function      	|
| endif;                           	| Closes the 'if' PHP function         	|
| get_header();                    	| Header.php file's content            	|
| get_sidebar();                   	| Sidebar.php file's content           	|
| get_footer();                    	| Footer.php file's content            	|
| the_time('m-d-y');               	| The date in '08-18-07′ format        	|
| comments_popup_link();           	| Link for the comments on the post    	|
| the_title()';                    	| Title of a specific post or page     	|
| the_permalink();                 	| URL of a specific post or page       	|
| the_category();                  	| Categor of a specific post or page   	|
| the_author();                    	| Author of a specific post or page    	|
| the_ID();                        	| ID of a specific post or page        	|
| edit_post_link();                	| Link to edit a specific post or page 	|
| get_links_list();                	| Links from the blogroll              	|
| comments_template();             	| Comment PHP file's content           	|
| wp_list_pages();                 	| List of pages of the site            	|
| wp_list_cats();                  	| List of categories for the site      	|
| next_post_link('%link');         	| URL to the next post                 	|
| previoust_post_link('%link');    	| URL to the previoust post            	|
| get_calendar()'                  	| The built-in calendar                	|
| wp_get_archives();               	| List of archives for the site        	|
| posts_nav_link();                	| Next and previous post links         	|
| bloginfo('description');         	| Site's description                   	|

### Theme - Navigation menu

Category Based Navigation

```
<ul id="menu">
<li <?php if(is_home()) { ?> class="current-cat" <?php } ?> >
<a href="<php bloginfo('home'); ?>">Home</a></li>
<?php wp_list_categories('title_li=&orderby=id'); ?>
</ul>
```

Pages based Navigation

```
<ul id="menu">
<li <?php if(is_home()) { ?> class="current_page_item" <?php } >>>
<a href="<php bloginfo('home'); ?>">Home</a></li>
<?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?>
</ul>
```

### Theme extras

| Extra stuff                  |                                                |
|------------------------------|------------------------------------------------|
| /%postname%/                 | Custom permalinks                              |
| include(TEMPATEPATH . '/x'); | Include any file                               |
| the_search_query();          | Value for search form                          |
| _e('Message');               | Prints out message                             |
| wp_register();               | Displays the register link                     |
| wp_loginout();               | Displas the login/logout link                  |
| <!--next page-->             | Divides the content into pages                 |
| <!--more-->                  | Cuts off the content and adds a read more link |
| wp_meta();                   | Meta for administrators                        |
| timer_stop(1);               | Time to load the page                          |
| echo get_num_queries();      | Queries to load the page                       |

### Theme - The Loop

```
<php if(have_posts()): ?>
<php while(have_posts()): the_post(); ?>
// Post content here (Custom HTML & PHP code)
<php else; ?>
<php endif; ?>
```

#### thz

**Font:** [startbloggingonline](https://startbloggingonline.com/wordpress-cheat-sheet/)