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

    <color name="white">#FFFFFF</color>
    <color name="grey">#cccccc</color>
    <color name="grey_700">#646464</color>
    <color name="black">#000000</color>

    <color name="sunshine_light_blue">#ff64c2f4</color>
    <color name="sunshine_blue">#ff1ca8f4</color>
    <color name="sunshine_dark_blue">#0288D1</color>

    <color name="primary_light">#B3E5FC</color>
    <color name="primary">#03A9F4</color>
    <color name="primary_dark">#0288D1</color>
    <color name="accent">#FFD740</color>

    <!-- using the "Light Blue" Material Palette -->
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#727272</color>

    <!-- our detail accent colors -->
    <color name="detail_accent_pane_background">#455A64</color>
    <color name="detail_accent_label">#90A4AE</color>

    <color name="activated">#E0E0E0</color>

    <color name="forecast_low_text">#607D8B</color>

</resources>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CustomFontDialog
{
    public partial class FontList : UserControl
    {

        public event EventHandler SelectedFontFamilyChanged;
        private int lastSelectedIndex = -1;

        public FontList()
        {
            InitializeComponent();

            foreach (FontFamily f in FontFamily.Families)
            {
                try
                {
                    if (!string.IsNullOrEmpty(f.Name))
                    {
                        FontStyle? firstAvailableStyle = null;
                        foreach (FontStyle style in Enum.GetValues(typeof(FontStyle)))
                        {
                            if (f.IsStyleAvailable(style))
                            {
                                firstAvailableStyle = style;
                                break;
                            }
                        }
                        if (firstAvailableStyle.HasValue)
                        {
                            lstFont.Items.Add(new Font(f, 12, firstAvailableStyle.Value));
                        }
                    }
                }
                catch (Exception ex)
                {
                }

            }
        }

        public FontFamily SelectedFontFamily
        {
            get
            {
                if (lstFont.SelectedItem != null)
                    return ((Font)lstFont.SelectedItem).FontFamily;
                else
                    return null;
            }
            set
            {
                if (value == null) lstFont.ClearSelected();
                else
                {
                    lstFont.SelectedIndex = IndexOf(value);
                }

            }
        }

        public int IndexOf(FontFamily ff)
        {
            for (int i = 1; i < lstFont.Items.Count; i++)
            {
                if (lstFont.Items[i] == "Section") continue;
                Font f = (Font)lstFont.Items[i];
                if (f.FontFamily.Name == ff.Name)
                {
                    return i;
                }
            }

            return -1;
        }

        private void lstFont_DrawItem(object sender, DrawItemEventArgs e)
        {
            // Draw the background of the ListBox control for each item.
            e.DrawBackground();

            Font font = (Font)lstFont.Items[e.Index];
            e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);

            // If the ListBox has focus, draw a focus rectangle around the selected item.
            e.DrawFocusRectangle();
        }

        private void lstFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstFont.SelectedItem != null)
            {
                if (!txtFont.Focused)
                {
                    Font f = (Font)lstFont.SelectedItem;
                    txtFont.Text = f.Name;
                }

                SelectedFontFamilyChanged(lstFont, new EventArgs());
                lastSelectedIndex = lstFont.SelectedIndex;
            }
        }

        private void txtFont_TextChanged(object sender, EventArgs e)
        {
            if (!txtFont.Focused) return;

            for (int i = 0; i < lstFont.Items.Count; i++)
            {
                string str = ((Font)lstFont.Items[i]).Name;
                if (str.StartsWith(txtFont.Text, true, null))
                {
                    lstFont.SelectedIndex = i;

                    const uint WM_VSCROLL = 0x0115;
                    const uint SB_THUMBPOSITION = 4;

                    uint b = ((uint)(lstFont.SelectedIndex) << 16) | (SB_THUMBPOSITION & 0xffff);
                    SendMessage(lstFont.Handle, WM_VSCROLL, b, 0);

                    return;
                }
            }
        }

        private void txtFont_MouseClick(object sender, MouseEventArgs e)
        {
            txtFont.SelectAll();
        }

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstFont_KeyDown(object sender, KeyEventArgs e)
        {
            // if you type alphanumeric characters while focus is on ListBox, it shifts the focus to TextBox.
            if (Char.IsLetterOrDigit((char)e.KeyValue))
            {
                txtFont.Focus();
                txtFont.Text = ((char)e.KeyValue).ToString();
                txtFont.SelectionStart = 1;
            }
        }

        // ensures that focus is lstFont control whenever the form is loaded
        private void FontList_Load(object sender, EventArgs e)
        {
            this.ActiveControl = lstFont;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout ="@id/drawer_layout" ="fill_parent" ="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout ="@id/background" ="@color/purple" ="fill_parent" ="fill_parent">
        <com.quizup.lib.widgets.topBar.TopBar ="@id/top_bar" style="@style/top_bar" />
        <ListView ="vertical" ="@*android:id/list" ="none" ="false" ="fill_parent" ="fill_parent" ="@*android:color/transparent" ="@null" ="@id/top_bar" ="true" ="false" ="never" style="@style/item_list_topic_buttons" />
        <com.quizup.lib.widgets.LoaderAnimationWidget ="@id/loading_layer" ="gone" ="fill_parent" ="fill_parent" ="@id/top_bar" />
        <ImageView ="@id/shadow" ="@drawable/top_bar_shadow" ="fill_parent" ="wrap_content" ="@id/top_bar" ="@string/shadow_desc" />
    </RelativeLayout>
    <com.quizup.core.widgets.sidebar.Sidebar ="end" ="@id/left_drawer" ="true" style="@style/sidebar" />
</android.support.v4.widget.DrawerLayout>


text:
typedef struct {
  // Stores the most recently added position with the given hash value.
  int32_t hash_to_first_index_[HASH_SIZE];
  // chain_[pos] stores the previous position with the same hash value
  // for every pixel in the image.
  int32_t* chain_;
} HashChain;

// -----------------------------------------------------------------------------

static const uint8_t plane_to_code_lut[128] = {
 96,   73,  55,  39,  23,  13,   5,  1,  255, 255, 255, 255, 255, 255, 255, 255,
 101,  78,  58,  42,  26,  16,   8,  2,    0,   3,  9,   17,  27,  43,  59,  79,
 102,  86,  62,  46,  32,  20,  10,  6,    4,   7,  11,  21,  33,  47,  63,  87,
 105,  90,  70,  52,  37,  28,  18,  14,  12,  15,  19,  29,  38,  53,  71,  91,
 110,  99,  82,  66,  48,  35,  30,  24,  22,  25,  31,  36,  49,  67,  83, 100,
 115, 108,  94,  76,  64,  50,  44,  40,  34,  41,  45,  51,  65,  77,  95, 109,
 118, 113, 103,  92,  80,  68,  60,  56,  54,  57,  61,  69,  81,  93, 104, 114,
 119, 116, 111, 106,  97,  88,  84,  74,  72,  75,  85,  89,  98, 107, 112, 117
};

static int DistanceToPlaneCode(int xsize, int dist) {
  const int yoffset = dist / xsize;
  const int xoffset = dist - yoffset * xsize;
  if (xoffset <= 8 && yoffset < 8) {
    return plane_to_code_lut[yoffset * 16 + 8 - xoffset] + 1;
  } else if (xoffset > xsize - 8 && yoffset < 7) {
    return plane_to_code_lut[(yoffset + 1) * 16 + 8 + (xsize - xoffset)] + 1;
  }
  return dist + 120;
}

static WEBP_INLINE int FindMatchLength(const uint32_t* const array1,
                                       const uint32_t* const array2,
                                       const int max_limit) {
  int match_len = 0;
  while (match_len < max_limit && array1[match_len] == array2[match_len]) {
    ++match_len;
  }
  return match_len;
}

// -----------------------------------------------------------------------------
//  VP8LBackwardRefs

void VP8LInitBackwardRefs(VP8LBackwardRefs* const refs) {
  if (refs != NULL) {
    refs->refs = NULL;
    refs->size = 0;
    refs->max_size = 0;
  }
}

void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs) {
  if (refs != NULL) {
    free(refs->refs);
    VP8LInitBackwardRefs(refs);
  }
}

int VP8LBackwardRefsAlloc(VP8LBackwardRefs* const refs, int max_size) {
  assert(refs != NULL);
  refs->size = 0;
  refs->max_size = 0;
  refs->refs = (PixOrCopy*)WebPSafeMalloc((uint64_t)max_size,
                                          sizeof(*refs->refs));
  if (refs->refs == NULL) return 0;
  refs->max_size = max_size;
  return 1;
}

// -----------------------------------------------------------------------------
// Hash chains

static WEBP_INLINE uint64_t GetPixPairHash64(const uint32_t* const argb) {
  uint64_t key = ((uint64_t)(argb[1]) << 32) | argb[0];
  key = (key * HASH_MULTIPLIER) >> (64 - HASH_BITS);
  return key;
}

static HashChain* HashChainNew(int size) {
  int i;
  HashChain* const p = (HashChain*)malloc(sizeof(*p));
  if (p == NULL) {
    return NULL;
  }
  p->chain_ = (int*)WebPSafeMalloc((uint64_t)size, sizeof(*p->chain_));
  if (p->chain_ == NULL) {
    free(p);
    return NULL;
  }
  for (i = 0; i < size; ++i) {
    p->chain_[i] = -1;
  }
  for (i = 0; i < HASH_SIZE; ++i) {
    p->hash_to_first_index_[i] = -1;
  }
  return p;
}

static void HashChainDelete(HashChain* const p) {
  if (p != NULL) {
    free(p->chain_);
    free(p);
  }
}

// Insertion of two pixels at a time.
static void HashChainInsert(HashChain* const p,
                            const uint32_t* const argb, int pos) {
  const uint64_t hash_code = GetPixPairHash64(argb);
  p->chain_[pos] = p->hash_to_first_index_[hash_code];
  p->hash_to_first_index_[hash_code] = pos;
}

static void GetParamsForHashChainFindCopy(int quality, int xsize,
                                          int cache_bits, int* window_size,
                                          int* iter_pos, int* iter_limit) {
  const int iter_mult = (quality < 27) ? 1 : 1 + ((quality - 27) >> 4);
  const int iter_neg = -iter_mult * (quality >> 1);
  // Limit the backward-ref window size for lower qualities.
  const int max_window_size = (quality > 50) ? WINDOW_SIZE
                            : (quality > 25) ? (xsize << 8)
                            : (xsize << 4);
  assert(xsize > 0);
  *window_size = (max_window_size > WINDOW_SIZE) ? WINDOW_SIZE
               : max_window_size;
  *iter_pos = 8 + (quality >> 3);
  // For lower entropy images, the rigorous search loop in HashChainFindCopy
  // can be relaxed.
  *iter_limit = (cache_bits > 0) ? iter_neg : iter_neg / 2;
}

static int HashChainFindCopy(const HashChain* const p,
                             int base_position, int xsize_signed,
                             const uint32_t* const argb, int max_len,
                             int window_size, int iter_pos, int iter_limit,
                             int* const distance_ptr,
                             int* const length_ptr) {
  const uint32_t* const argb_start = argb + base_position;
  uint64_t best_val = 0;
  uint32_t best_length = 1;
  uint32_t best_distance = 0;
  const uint32_t xsize = (uint32_t)xsize_signed;
  const int min_pos =
      (base_position > window_size) ? base_position - window_size : 0;
  int pos;
  assert(xsize > 0);
  if (max_len > MAX_LENGTH) {
    max_len = MAX_LENGTH;
  }
  for (pos = p->hash_to_first_index_[GetPixPairHash64(argb_start)];
       pos >= min_pos;
       pos = p->chain_[pos]) {
    uint64_t val;
    uint32_t curr_length;
    uint32_t distance;
    const uint64_t* const ptr1 =
        (const uint64_t*)(argb + pos + best_length - 1);
    const uint64_t* const ptr2 =
        (const uint64_t*)(argb_start + best_length - 1);

    if (iter_pos < 0) {
      if (iter_pos < iter_limit || best_val >= 0xff0000) {
        break;
      }
    }
    --iter_pos;

    // Before 'expensive' linear match, check if the two arrays match at the
    // current best length index and also for the succeeding elements.
    if (*ptr1 != *ptr2) continue;

    curr_length = FindMatchLength(argb + pos, argb_start, max_len);
    if (curr_length < best_length) continue;

    distance = (uint32_t)(base_position - pos);
    val = curr_length << 16;
    // Favoring 2d locality here gives savings for certain images.
    if (distance < 9 * xsize) {
      const uint32_t y = distance / xsize;
      uint32_t x = distance % xsize;
      if (x > (xsize >> 1)) {
        x = xsize - x;
      }
      if (x <= 7) {
        val += 9 * 9 + 9 * 9;
        val -= y * y + x * x;
      }
    }
    if (best_val < val) {
      best_val = val;
      best_length = curr_length;
      best_distance = distance;
      if (curr_length >= (uint32_t)max_len) {
        break;
      }
      if ((best_distance == 1 || distance == xsize) &&
          best_length >= 128) {
        break;
      }
    }
  }
  *distance_ptr = (int)best_distance;
  *length_ptr = best_length;
  return (best_length >= MIN_LENGTH);
}

static WEBP_INLINE void PushBackCopy(VP8LBackwardRefs* const refs, int length) {
  int size = refs->size;
  while (length >= MAX_LENGTH) {
    refs->refs[size++] = PixOrCopyCreateCopy(1, MAX_LENGTH);
    length -= MAX_LENGTH;
  }
  if (length > 0) {
    refs->refs[size++] = PixOrCopyCreateCopy(1, length);
  }
  refs->size = size;
}

static void BackwardReferencesRle(int xsize, int ysize,
                                  const uint32_t* const argb,
                                  VP8LBackwardRefs* const refs) {
  const int pix_count = xsize * ysize;
  int match_len = 0;
  int i;
  refs->size = 0;
  PushBackCopy(refs, match_len);    // i=0 case
  refs->refs[refs->size++] = PixOrCopyCreateLiteral(argb[0]);
  for (i = 1; i < pix_count; ++i) {
    if (argb[i] == argb[i - 1]) {
      ++match_len;
    } else {
      PushBackCopy(refs, match_len);
      match_len = 0;
      refs->refs[refs->size++] = PixOrCopyCreateLiteral(argb[i]);
    }
  }
  PushBackCopy(refs, match_len);
}

static int BackwardReferencesHashChain(int xsize, int ysize,
                                       const uint32_t* const argb,
                                       int cache_bits, int quality,
                                       VP8LBackwardRefs* const refs) {
  int i;
  int ok = 0;
  int cc_init = 0;
  const int use_color_cache = (cache_bits > 0);
  const int pix_count = xsize * ysize;
  HashChain* const hash_chain = HashChainNew(pix_count);
  VP8LColorCache hashers;
  int window_size = WINDOW_SIZE;
  int iter_pos = 1;
  int iter_limit = -1;

  if (hash_chain == NULL) return 0;
  if (use_color_cache) {
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
    if (!cc_init) goto Error;
  }

  refs->size = 0;
  GetParamsForHashChainFindCopy(quality, xsize, cache_bits,
                                &window_size, &iter_pos, &iter_limit);
  for (i = 0; i < pix_count; ) {
    // Alternative#1: Code the pixels starting at 'i' using backward reference.
    int offset = 0;
    int len = 0;
    if (i < pix_count - 1) {  // FindCopy(i,..) reads pixels at [i] and [i + 1].
      int max_len = pix_count - i;
      HashChainFindCopy(hash_chain, i, xsize, argb, max_len,
                        window_size, iter_pos, iter_limit,
                        &offset, &len);
    }
    if (len >= MIN_LENGTH) {
      // Alternative#2: Insert the pixel at 'i' as literal, and code the
      // pixels starting at 'i + 1' using backward reference.
      int offset2 = 0;
      int len2 = 0;
      int k;
      HashChainInsert(hash_chain, &argb[i], i);
      if (i < pix_count - 2) {  // FindCopy(i+1,..) reads [i + 1] and [i + 2].
        int max_len = pix_count - (i + 1);
        HashChainFindCopy(hash_chain, i + 1, xsize, argb, max_len,
                          window_size, iter_pos, iter_limit,
                          &offset2, &len2);
        if (len2 > len + 1) {
          const uint32_t pixel = argb[i];
          // Alternative#2 is a better match. So push pixel at 'i' as literal.
          if (use_color_cache && VP8LColorCacheContains(&hashers, pixel)) {
            const int ix = VP8LColorCacheGetIndex(&hashers, pixel);
            refs->refs[refs->size] = PixOrCopyCreateCacheIdx(ix);
          } else {
            if (use_color_cache) VP8LColorCacheInsert(&hashers, pixel);
            refs->refs[refs->size] = PixOrCopyCreateLiteral(pixel);
          }
          ++refs->size;
          i++;  // Backward reference to be done for next pixel.
          len = len2;
          offset = offset2;
        }
      }
      if (len >= MAX_LENGTH) {
        len = MAX_LENGTH - 1;
      }
      refs->refs[refs->size++] = PixOrCopyCreateCopy(offset, len);
      if (use_color_cache) {
        for (k = 0; k < len; ++k) {
          VP8LColorCacheInsert(&hashers, argb[i + k]);
        }
      }
      // Add to the hash_chain (but cannot add the last pixel).
      {
        const int last = (len < pix_count - 1 - i) ? len : pix_count - 1 - i;
        for (k = 1; k < last; ++k) {
          HashChainInsert(hash_chain, &argb[i + k], i + k);
        }
      }
      i += len;
    } else {
      const uint32_t pixel = argb[i];
      if (use_color_cache && VP8LColorCacheContains(&hashers, pixel)) {
        // push pixel as a PixOrCopyCreateCacheIdx pixel
        const int ix = VP8LColorCacheGetIndex(&hashers, pixel);
        refs->refs[refs->size] = PixOrCopyCreateCacheIdx(ix);
      } else {
        if (use_color_cache) VP8LColorCacheInsert(&hashers, pixel);
        refs->refs[refs->size] = PixOrCopyCreateLiteral(pixel);
      }
      ++refs->size;
      if (i + 1 < pix_count) {
        HashChainInsert(hash_chain, &argb[i], i);
      }
      ++i;
    }
  }
  ok = 1;
Error:
  if (cc_init) VP8LColorCacheClear(&hashers);
  HashChainDelete(hash_chain);
  return ok;
}

// -----------------------------------------------------------------------------

typedef struct {
  double alpha_[VALUES_IN_BYTE];
  double red_[VALUES_IN_BYTE];
  double literal_[PIX_OR_COPY_CODES_MAX];
  double blue_[VALUES_IN_BYTE];
  double distance_[NUM_DISTANCE_CODES];
} CostModel;

static int BackwardReferencesTraceBackwards(
    int xsize, int ysize, int recursive_cost_model,
    const uint32_t* const argb, int quality, int cache_bits,
    VP8LBackwardRefs* const refs);

static void ConvertPopulationCountTableToBitEstimates(
    int num_symbols, const int population_counts[], double output[]) {
  int sum = 0;
  int nonzeros = 0;
  int i;
  for (i = 0; i < num_symbols; ++i) {
    sum += population_counts[i];
    if (population_counts[i] > 0) {
      ++nonzeros;
    }
  }
  if (nonzeros <= 1) {
    memset(output, 0, num_symbols * sizeof(*output));
  } else {
    const double logsum = VP8LFastLog2(sum);
    for (i = 0; i < num_symbols; ++i) {
      output[i] = logsum - VP8LFastLog2(population_counts[i]);
    }
  }
}

static int CostModelBuild(CostModel* const m, int xsize, int ysize,
                          int recursion_level, const uint32_t* const argb,
                          int quality, int cache_bits) {
  int ok = 0;
  VP8LHistogram histo;
  VP8LBackwardRefs refs;

  if (!VP8LBackwardRefsAlloc(&refs, xsize * ysize)) goto Error;

  if (recursion_level > 0) {
    if (!BackwardReferencesTraceBackwards(xsize, ysize, recursion_level - 1,
                                          argb, quality, cache_bits, &refs)) {
      goto Error;
    }
  } else {
    if (!BackwardReferencesHashChain(xsize, ysize, argb, cache_bits, quality,
                                     &refs)) {
      goto Error;
    }
  }
  VP8LHistogramCreate(&histo, &refs, cache_bits);
  ConvertPopulationCountTableToBitEstimates(
      VP8LHistogramNumCodes(histo.palette_code_bits_),
      histo.literal_, m->literal_);
  ConvertPopulationCountTableToBitEstimates(
      VALUES_IN_BYTE, histo.red_, m->red_);
  ConvertPopulationCountTableToBitEstimates(
      VALUES_IN_BYTE, histo.blue_, m->blue_);
  ConvertPopulationCountTableToBitEstimates(
      VALUES_IN_BYTE, histo.alpha_, m->alpha_);
  ConvertPopulationCountTableToBitEstimates(
      NUM_DISTANCE_CODES, histo.distance_, m->distance_);
  ok = 1;

 Error:
  VP8LClearBackwardRefs(&refs);
  return ok;
}

static WEBP_INLINE double GetLiteralCost(const CostModel* const m, uint32_t v) {
  return m->alpha_[v >> 24] +
         m->red_[(v >> 16) & 0xff] +
         m->literal_[(v >> 8) & 0xff] +
         m->blue_[v & 0xff];
}

static WEBP_INLINE double GetCacheCost(const CostModel* const m, uint32_t idx) {
  const int literal_idx = VALUES_IN_BYTE + NUM_LENGTH_CODES + idx;
  return m->literal_[literal_idx];
}

static WEBP_INLINE double GetLengthCost(const CostModel* const m,
                                        uint32_t length) {
  int code, extra_bits;
  VP8LPrefixEncodeBits(length, &code, &extra_bits);
  return m->literal_[VALUES_IN_BYTE + code] + extra_bits;
}

static WEBP_INLINE double GetDistanceCost(const CostModel* const m,
                                          uint32_t distance) {
  int code, extra_bits;
  VP8LPrefixEncodeBits(distance, &code, &extra_bits);
  return m->distance_[code] + extra_bits;
}

static int BackwardReferencesHashChainDistanceOnly(
    int xsize, int ysize, int recursive_cost_model, const uint32_t* const argb,
    int quality, int cache_bits, uint32_t* const dist_array) {
  int i;
  int ok = 0;
  int cc_init = 0;
  const int pix_count = xsize * ysize;
  const int use_color_cache = (cache_bits > 0);
  float* const cost =
      (float*)WebPSafeMalloc((uint64_t)pix_count, sizeof(*cost));
  CostModel* cost_model = (CostModel*)malloc(sizeof(*cost_model));
  HashChain* hash_chain = HashChainNew(pix_count);
  VP8LColorCache hashers;
  const double mul0 = (recursive_cost_model != 0) ? 1.0 : 0.68;
  const double mul1 = (recursive_cost_model != 0) ? 1.0 : 0.82;
  const int min_distance_code = 2;  // TODO(vikasa): tune as function of quality
  int window_size = WINDOW_SIZE;
  int iter_pos = 1;
  int iter_limit = -1;

  if (cost == NULL || cost_model == NULL || hash_chain == NULL) goto Error;

  if (use_color_cache) {
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
    if (!cc_init) goto Error;
  }

  if (!CostModelBuild(cost_model, xsize, ysize, recursive_cost_model, argb,
                      quality, cache_bits)) {
    goto Error;
  }

  for (i = 0; i < pix_count; ++i) cost[i] = 1e38f;

  // We loop one pixel at a time, but store all currently best points to
  // non-processed locations from this point.
  dist_array[0] = 0;
  GetParamsForHashChainFindCopy(quality, xsize, cache_bits,
                                &window_size, &iter_pos, &iter_limit);
  for (i = 0; i < pix_count; ++i) {
    double prev_cost = 0.0;
    int shortmax;
    if (i > 0) {
      prev_cost = cost[i - 1];
    }
    for (shortmax = 0; shortmax < 2; ++shortmax) {
      int offset = 0;
      int len = 0;
      if (i < pix_count - 1) {  // FindCopy reads pixels at [i] and [i + 1].
        int max_len = shortmax ? 2 : pix_count - i;
        HashChainFindCopy(hash_chain, i, xsize, argb, max_len,
                          window_size, iter_pos, iter_limit,
                          &offset, &len);
      }
      if (len >= MIN_LENGTH) {
        const int code = DistanceToPlaneCode(xsize, offset);
        const double distance_cost =
            prev_cost + GetDistanceCost(cost_model, code);
        int k;
        for (k = 1; k < len; ++k) {
          const double cost_val = distance_cost + GetLengthCost(cost_model, k);
          if (cost[i + k] > cost_val) {
            cost[i + k] = (float)cost_val;
            dist_array[i + k] = k + 1;
          }
        }
        // This if is for speedup only. It roughly doubles the speed, and
        // makes compression worse by .1 %.
        if (len >= 128 && code <= min_distance_code) {
          // Long copy for short distances, let's skip the middle
          // lookups for better copies.
          // 1) insert the hashes.
          if (use_color_cache) {
            for (k = 0; k < len; ++k) {
              VP8LColorCacheInsert(&hashers, argb[i + k]);
            }
          }
          // 2) Add to the hash_chain (but cannot add the last pixel)
          {
            const int last = (len + i < pix_count - 1) ? len + i
                                                       : pix_count - 1;
            for (k = i; k < last; ++k) {
              HashChainInsert(hash_chain, &argb[k], k);
            }
          }
          // 3) jump.
          i += len - 1;  // for loop does ++i, thus -1 here.
          goto next_symbol;
        }
      }
    }
    if (i < pix_count - 1) {
      HashChainInsert(hash_chain, &argb[i], i);
    }
    {
      // inserting a literal pixel
      double cost_val = prev_cost;
      if (use_color_cache && VP8LColorCacheContains(&hashers, argb[i])) {
        const int ix = VP8LColorCacheGetIndex(&hashers, argb[i]);
        cost_val += GetCacheCost(cost_model, ix) * mul0;
      } else {
        if (use_color_cache) VP8LColorCacheInsert(&hashers, argb[i]);
        cost_val += GetLiteralCost(cost_model, argb[i]) * mul1;
      }
      if (cost[i] > cost_val) {
        cost[i] = (float)cost_val;
        dist_array[i] = 1;  // only one is inserted.
      }
    }
 next_symbol: ;
  }
  // Last pixel still to do, it can only be a single step if not reached
  // through cheaper means already.
  ok = 1;
Error:
  if (cc_init) VP8LColorCacheClear(&hashers);
  HashChainDelete(hash_chain);
  free(cost_model);
  free(cost);
  return ok;
}

// We pack the path at the end of *dist_array and return
// a pointer to this part of the array. Example:
// dist_array = [1x2xx3x2] => packed [1x2x1232], chosen_path = [1232]
static void TraceBackwards(uint32_t* const dist_array,
                           int dist_array_size,
                           uint32_t** const chosen_path,
                           int* const chosen_path_size) {
  uint32_t* path = dist_array + dist_array_size;
  uint32_t* cur = dist_array + dist_array_size - 1;
  while (cur >= dist_array) {
    const int k = *cur;
    --path;
    *path = k;
    cur -= k;
  }
  *chosen_path = path;
  *chosen_path_size = (int)(dist_array + dist_array_size - path);
}

static int BackwardReferencesHashChainFollowChosenPath(
    int xsize, int ysize, const uint32_t* const argb,
    int quality, int cache_bits,
    const uint32_t* const chosen_path, int chosen_path_size,
    VP8LBackwardRefs* const refs) {
  const int pix_count = xsize * ysize;
  const int use_color_cache = (cache_bits > 0);
  int size = 0;
  int i = 0;
  int k;
  int ix;
  int ok = 0;
  int cc_init = 0;
  int window_size = WINDOW_SIZE;
  int iter_pos = 1;
  int iter_limit = -1;
  HashChain* hash_chain = HashChainNew(pix_count);
  VP8LColorCache hashers;

  if (hash_chain == NULL) goto Error;

  if (use_color_cache) {
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
    if (!cc_init) goto Error;
  }

  refs->size = 0;
  GetParamsForHashChainFindCopy(quality, xsize, cache_bits,
                                &window_size, &iter_pos, &iter_limit);
  for (ix = 0; ix < chosen_path_size; ++ix, ++size) {
    int offset = 0;
    int len = 0;
    int max_len = chosen_path[ix];
    if (max_len != 1) {
      HashChainFindCopy(hash_chain, i, xsize, argb, max_len,
                        window_size, iter_pos, iter_limit,
                        &offset, &len);
      assert(len == max_len);
      refs->refs[size] = PixOrCopyCreateCopy(offset, len);
      if (use_color_cache) {
        for (k = 0; k < len; ++k) {
          VP8LColorCacheInsert(&hashers, argb[i + k]);
        }
      }
      {
        const int last = (len < pix_count - 1 - i) ? len : pix_count - 1 - i;
        for (k = 0; k < last; ++k) {
          HashChainInsert(hash_chain, &argb[i + k], i + k);
        }
      }
      i += len;
    } else {
      if (use_color_cache && VP8LColorCacheContains(&hashers, argb[i])) {
        // push pixel as a color cache index
        const int idx = VP8LColorCacheGetIndex(&hashers, argb[i]);
        refs->refs[size] = PixOrCopyCreateCacheIdx(idx);
      } else {
        if (use_color_cache) VP8LColorCacheInsert(&hashers, argb[i]);
        refs->refs[size] = PixOrCopyCreateLiteral(argb[i]);
      }
      if (i + 1 < pix_count) {
        HashChainInsert(hash_chain, &argb[i], i);
      }
      ++i;
    }
  }
  assert(size <= refs->max_size);
  refs->size = size;
  ok = 1;
Error:
  if (cc_init) VP8LColorCacheClear(&hashers);
  HashChainDelete(hash_chain);
  return ok;
}

// Returns 1 on success.
static int BackwardReferencesTraceBackwards(int xsize, int ysize,
                                            int recursive_cost_model,
                                            const uint32_t* const argb,
                                            int quality, int cache_bits,
                                            VP8LBackwardRefs* const refs) {
  int ok = 0;
  const int dist_array_size = xsize * ysize;
  uint32_t* chosen_path = NULL;
  int chosen_path_size = 0;
  uint32_t* dist_array =
      (uint32_t*)WebPSafeMalloc((uint64_t)dist_array_size, sizeof(*dist_array));

  if (dist_array == NULL) goto Error;

  if (!BackwardReferencesHashChainDistanceOnly(
      xsize, ysize, recursive_cost_model, argb, quality, cache_bits,
      dist_array)) {
    goto Error;
  }
  TraceBackwards(dist_array, dist_array_size, &chosen_path, &chosen_path_size);
  if (!BackwardReferencesHashChainFollowChosenPath(
      xsize, ysize, argb, quality, cache_bits, chosen_path, chosen_path_size,
      refs)) {
    goto Error;
  }
  ok = 1;
 Error:
  free(dist_array);
  return ok;
}

static void BackwardReferences2DLocality(int xsize,
                                         VP8LBackwardRefs* const refs) {
  int i;
  for (i = 0; i < refs->size; ++i) {
    if (PixOrCopyIsCopy(&refs->refs[i])) {
      const int dist = refs->refs[i].argb_or_distance;
      const int transformed_dist = DistanceToPlaneCode(xsize, dist);
      refs->refs[i].argb_or_distance = transformed_dist;
    }
  }
}

int VP8LGetBackwardReferences(int width, int height,
                              const uint32_t* const argb,
                              int quality, int cache_bits, int use_2d_locality,
                              VP8LBackwardRefs* const best) {
  int ok = 0;
  int lz77_is_useful;
  VP8LBackwardRefs refs_rle, refs_lz77;
  const int num_pix = width * height;

  VP8LBackwardRefsAlloc(&refs_rle, num_pix);
  VP8LBackwardRefsAlloc(&refs_lz77, num_pix);
  VP8LInitBackwardRefs(best);
  if (refs_rle.refs == NULL || refs_lz77.refs == NULL) {
 Error1:
    VP8LClearBackwardRefs(&refs_rle);
    VP8LClearBackwardRefs(&refs_lz77);
    goto End;
  }

  if (!BackwardReferencesHashChain(width, height, argb, cache_bits, quality,
                                   &refs_lz77)) {
    goto End;
  }
  // Backward Reference using RLE only.
  BackwardReferencesRle(width, height, argb, &refs_rle);

  {
    double bit_cost_lz77, bit_cost_rle;
    VP8LHistogram* const histo = (VP8LHistogram*)malloc(sizeof(*histo));
    if (histo == NULL) goto Error1;
    // Evaluate lz77 coding
    VP8LHistogramCreate(histo, &refs_lz77, cache_bits);
    bit_cost_lz77 = VP8LHistogramEstimateBits(histo);
    // Evaluate RLE coding
    VP8LHistogramCreate(histo, &refs_rle, cache_bits);
    bit_cost_rle = VP8LHistogramEstimateBits(histo);
    // Decide if LZ77 is useful.
    lz77_is_useful = (bit_cost_lz77 < bit_cost_rle);
    free(histo);
  }

  // Choose appropriate backward reference.
  if (lz77_is_useful) {
    // TraceBackwards is costly. Don't execute it at lower quality.
    const int try_lz77_trace_backwards = (quality >= 25);
    *best = refs_lz77;   // default guess: lz77 is better
    VP8LClearBackwardRefs(&refs_rle);
    if (try_lz77_trace_backwards) {
      // Set recursion level for large images using a color cache.
      const int recursion_level =
          (num_pix < 320 * 200) && (cache_bits > 0) ? 1 : 0;
      VP8LBackwardRefs refs_trace;
      if (!VP8LBackwardRefsAlloc(&refs_trace, num_pix)) {
        goto End;
      }
      if (BackwardReferencesTraceBackwards(width, height, recursion_level, argb,
                                           quality, cache_bits, &refs_trace)) {
        VP8LClearBackwardRefs(&refs_lz77);
        *best = refs_trace;
      }
    }
  } else {
    VP8LClearBackwardRefs(&refs_lz77);
    *best = refs_rle;
  }

  if (use_2d_locality) BackwardReferences2DLocality(width, best);

  ok = 1;

 End:
  if (!ok) {
    VP8LClearBackwardRefs(best);
  }
  return ok;
}

// Returns entropy for the given cache bits.
static double ComputeCacheEntropy(const uint32_t* const argb,
                                  int xsize, int ysize,
                                  const VP8LBackwardRefs* const refs,
                                  int cache_bits) {
  int pixel_index = 0;
  int i;
  uint32_t k;
  const int use_color_cache = (cache_bits > 0);
  int cc_init = 0;
  double entropy;
  const double kSmallPenaltyForLargeCache = 4.0;
  VP8LColorCache hashers;
  VP8LHistogram histo;

  if (use_color_cache) {
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
    if (!cc_init) return MAX_ENTROPY;
  }

  VP8LHistogramInit(&histo, cache_bits);
  for (i = 0; i < refs->size; ++i) {
    const PixOrCopy* const v = &refs->refs[i];
    if (PixOrCopyIsLiteral(v)) {
      if (use_color_cache &&
          VP8LColorCacheContains(&hashers, argb[pixel_index])) {
        // push pixel as a cache index
        const int ix = VP8LColorCacheGetIndex(&hashers, argb[pixel_index]);
        const PixOrCopy token = PixOrCopyCreateCacheIdx(ix);
        VP8LHistogramAddSinglePixOrCopy(&histo, &token);
      } else {
        VP8LHistogramAddSinglePixOrCopy(&histo, v);
      }
    } else {
      VP8LHistogramAddSinglePixOrCopy(&histo, v);
    }
    if (use_color_cache) {
      for (k = 0; k < PixOrCopyLength(v); ++k) {
        VP8LColorCacheInsert(&hashers, argb[pixel_index + k]);
      }
    }
    pixel_index += PixOrCopyLength(v);
  }
  assert(pixel_index == xsize * ysize);
  (void)xsize;  // xsize is not used in non-debug compilations otherwise.
  (void)ysize;  // ysize is not used in non-debug compilations otherwise.
  entropy = VP8LHistogramEstimateBits(&histo) +
      kSmallPenaltyForLargeCache * cache_bits;
  if (cc_init) VP8LColorCacheClear(&hashers);
  return entropy;
}

// Returns how many bits are to be used for a color cache.
int VP8LCalculateEstimateForCacheSize(const uint32_t* const argb,
                                      int xsize, int ysize, int quality,
                                      int* const best_cache_bits) {
  int ok = 0;
  int eval_low = 1;
  int eval_high = 1;
  double entropy_low = MAX_ENTROPY;
  double entropy_high = MAX_ENTROPY;
  int cache_bits_low = 0;
  int cache_bits_high = MAX_COLOR_CACHE_BITS;
  VP8LBackwardRefs refs;

  if (!VP8LBackwardRefsAlloc(&refs, xsize * ysize) ||
      !BackwardReferencesHashChain(xsize, ysize, argb, 0, quality, &refs)) {
    goto Error;
  }
  // Do a binary search to find the optimal entropy for cache_bits.
  while (cache_bits_high - cache_bits_low > 1) {
    if (eval_low) {
      entropy_low =
          ComputeCacheEntropy(argb, xsize, ysize, &refs, cache_bits_low);
      eval_low = 0;
    }
    if (eval_high) {
      entropy_high =
          ComputeCacheEntropy(argb, xsize, ysize, &refs, cache_bits_high);
      eval_high = 0;
    }
    if (entropy_high < entropy_low) {
      *best_cache_bits = cache_bits_high;
      cache_bits_low = (cache_bits_low + cache_bits_high) / 2;
      eval_low = 1;
    } else {
      *best_cache_bits = cache_bits_low;
      cache_bits_high = (cache_bits_low + cache_bits_high) / 2;
      eval_high = 1;
    }
  }
  ok = 1;
 Error:
  VP8LClearBackwardRefs(&refs);
  return ok;
}


text:
//
//  HSTableView1.h
//  点击cell,然后在他下边插入一个不变的cell
//
//  Created by shenghuihan on 15/10/21.
//  Copyright © 2015年 shenghuihan. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol HSTableViewDelegate <NSObject>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (NSInteger)getNumberofsubArr:(NSIndexPath *)indexpath;
- (void)changeSelectedIndexPath:(NSIndexPath *)indexpath withInsertArr:(NSMutableArray *)insertArr;
- (void)changeArrIndexPath:(NSIndexPath *)indexPath;
@end

@protocol HSTableViewDatasource <NSObject>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
@end

@interface HSTableView : UITableView

/**delegate*/
@property (nonatomic, strong) id<HSTableViewDelegate> hsDelegate;

/**datasource*/
@property (nonatomic, strong) id<HSTableViewDatasource> hsDatasource;

@end


text:
import logging
import psutil
import socket

from shortcut.channel import const as C
from core import shortcut_channels_model as M

PID_TYPE = 'integer(min=1, max=999999)'

CMDS = {
    'list': {
    },
    'start': {
        'command': 'string()',
    },
    'kill': {
        'pid': PID_TYPE,
    },
    'detail': {
        'pid': PID_TYPE,
    },
    'global': {
    },
}

TYPES = {
    'processes': {
        C.TYPE: C.LIST,
        C.ITEM_TYPE: 'process',
    },
    'process': {
        C.TYPE: C.DICT,
        'pid': PID_TYPE,
        'name': C.STRING,
        'uid': C.INTEGER,
        'gid': C.INTEGER,
        'username': C.STRING,
        'command_line': {
            C.TYPE: C.LIST,
            C.ITEM_TYPE: C.STRING,
        },
        'path': C.STRING,
        'cpu': 'process_cpu',
        'mem': 'process_mem',
        'create_time': C.DATETIME,
    },
    'process_cpu': {
        C.TYPE: C.DICT,
        'percent': C.FLOAT,
        'user': C.FLOAT,
        'system': C.FLOAT,
    },
    'process_mem': {
        C.TYPE: C.DICT,
        'rss': C.LONG,
        'vms': C.LONG,
        'percent': C.FLOAT,
    },
    'global': {
        C.TYPE: C.DICT,
        'hostname': C.STRING,
        'cpu': 'global_cpu',
        'mem': 'global_mem',
    },
    'global_cpu': {
        'idle': C.FLOAT,
        'nice': C.FLOAT,
        'system': C.FLOAT,
        'user': C.FLOAT,
        'percent': C.FLOAT,
    },
    'global_mem': {
        'used_physical': C.LONG,
        'used_virtual': C.LONG,
        'available_physical': C.LONG,
        'available_virtual': C.LONG,
    },
}

PROPERTIES = {
    'all_processes': 'processes',
    'user_processes': 'processes',
    'global': 'global',
}

TITLE = 'Process Moniter/Controller'
DESCRIPTION = \
'You can watch the processes that running in the system, and you can also ' \
'control them in certain ways.'

PROTOCOL = {
    C.TYPE: 'process',
    C.TITLE: TITLE,
    C.DESCRIPTION: DESCRIPTION,
    C.CMDS: CMDS,
    C.TYPES: TYPES,
    C.PROPERTIES: PROPERTIES,
}

class ProcessChannel(M.AbstractChannel):
    protocol = PROTOCOL

    def on_global(self, msg=None):
        global_cpu = psutil.get_system_cpu_times()
        global_cpu['percent'] = psutil.cpu_percent()
        global_mem = {
            'used_physical': psutil.used_phymem(),
            'used_virtual': psutil.used_virtmem(),
            'available_physical': psutil.avail_phymem(),
            'available_virtual': psutil.avail_virtmem(),
        }
        result = {
            'hostnome': socket.gethostname(),
            'cpu': global_cpu,
            'mem': global_mem,
        }
        return {'global': result}

    def get_process(self, pid):
        p = psutil.Process(pid)
        process_cpu = {}
        process_mem = {}
        try:
            user, system = p.get_cpu_times()
            process_cpu['user'] = user
            process_cpu['system'] = system
            process_cpu['percent'] = p.get_cpu_percent()
            rss, vms = p.get_memory_info()
            process_mem['rss'] = rss
            process_mem['vms'] = vms
            process_mem['percent'] = p.get_memory_percent()
        except Exception, e:
            logging.critical('Get cpu/mem error: %s' % e, exc_info=True)
            pass # most likely lacking permission for other users' processes
        process = {
            'pid': pid,
            'name': p.name,
            'uid': p.uid,
            'gid': p.gid,
            'username': self.get_username(p),
            'command_line': p.cmdline,
            'path': p.path,
            'cpu': process_cpu,
            'mem': process_mem,
            'create_time': p.create_time,
        }
        return process

    def get_username(self, p):
        username = getattr(p, "username", None)
        if username is None:
            try:
                import pwd
                username = pwd.getpwuid(p.uid).pw_name
            except Exception, e:
                logging.debug('Failed to get username: %s' % e, exc_info=True)
                username = 'n/a'
        return username

    def on_detail(self, pid, msg=None):
        return {'process': self.get_process(pid)}

    def on_list(self, msg=None):
        processes = []
        for pid in psutil.get_pid_list():
            processes.append(self.get_process(pid))
        return {
            'processes': processes,
        }


text: package armlabservices


text:
class CreateDatalogs < ActiveRecord::Migration
  def self.up
    create_table :datalogs do |t|
      t.references :server
      t.string :key
      t.string :value
      t.timestamps
    end
    execute "CREATE UNIQUE INDEX datalog_id ON servers(id);"
  end

  def self.down
    drop_table :datalogs
  end
end


text:
/*
 * @OSF_FREE_COPYRIGHT@
 */
/*
 * Mach Operating System
 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie Mellon
 * the rights to redistribute these changes.
 */
/*
 */
/*
 *	File:	thread.h
 *	Author:	Avadis Tevanian, Jr.
 *
 *	This file contains the structure definitions for threads.
 *
 */
/*
 * Copyright (c) 1993 The University of Utah and
 * the Computer Systems Laboratory (CSL).  All rights reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS
 * IS" CONDITION.  THE UNIVERSITY OF UTAH AND CSL DISCLAIM ANY LIABILITY OF
 * ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * CSL requests users of this software to return to csl-dist@cs.utah.edu any
 * improvements that they make and grant CSL redistribution rights.
 *
 */

#ifndef	_KERN_THREAD_H_
#define _KERN_THREAD_H_

#include <mach/kern_return.h>
#include <mach/mach_types.h>
#include <mach/message.h>
#include <mach/boolean.h>
#include <mach/vm_param.h>
#include <mach/thread_info.h>
#include <mach/thread_status.h>
#include <mach/exception_types.h>

#include <kern/kern_types.h>

#include <sys/cdefs.h>

__BEGIN_DECLS

extern thread_t		current_thread(void);

extern void			thread_reference(
						thread_t	thread);

extern void			thread_deallocate(
						thread_t	thread);

__END_DECLS

__BEGIN_DECLS

extern uint64_t	 		thread_dispatchqaddr(
						thread_t thread);

__END_DECLS

__BEGIN_DECLS

extern uint64_t	 		thread_tid(thread_t thread);

__END_DECLS

__BEGIN_DECLS

/*! @function kernel_thread_start
    @abstract Create a kernel thread.
    @discussion This function takes three input parameters, namely reference to the function that the thread should execute, caller specified data and a reference which is used to return the newly created kernel thread. The function returns KERN_SUCCESS on success or an appropriate kernel code type indicating the error. It may be noted that the caller is responsible for explicitly releasing the reference to the created thread when no longer needed. This should be done by calling thread_deallocate(new_thread).
    @param continuation A C-function pointer where the thread will begin execution.
    @param parameter Caller specified data to be passed to the new thread.
    @param new_thread Reference to the new thread is returned in this parameter.
    @result Returns KERN_SUCCESS on success or an appropriate kernel code type.
*/

extern kern_return_t	kernel_thread_start(
							thread_continue_t	continuation,
							void				*parameter,
							thread_t			*new_thread);
void thread_set_eager_preempt(thread_t thread);
void thread_clear_eager_preempt(thread_t thread);
extern ipc_port_t convert_thread_to_port(thread_t);
extern ipc_port_t convert_thread_inspect_to_port(thread_inspect_t);
extern boolean_t is_vm_privileged(void);
extern boolean_t set_vm_privilege(boolean_t);

__END_DECLS

#endif	/* _KERN_THREAD_H_ */


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

#include "LanguageFeature.h"

#include <stdlib.h>

#include "Basics/ArangoGlobalContext.h"
#include "Basics/FileUtils.h"
#include "Basics/application-exit.h"
#include "Basics/directories.h"
#include "Basics/error.h"
#include "Basics/exitcodes.h"
#include "Basics/files.h"
#include "Basics/memory.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "ProgramOptions/Option.h"
#include "ProgramOptions/Parameters.h"
#include "ProgramOptions/ProgramOptions.h"

namespace {
void setCollator(std::string_view language, void* icuDataPtr,
                 arangodb::basics::LanguageType type) {
  using arangodb::basics::Utf8Helper;

  if (!Utf8Helper::DefaultUtf8Helper.setCollatorLanguage(language, type,
                                                         icuDataPtr)) {
    LOG_TOPIC("01490", FATAL, arangodb::Logger::FIXME)
        << "error setting collator language to '" << language << "'. "
        << "The icudtl.dat file might be of the wrong version. "
        << "Check for an incorrectly set ICU_DATA environment variable";
    FATAL_ERROR_EXIT_CODE(TRI_EXIT_ICU_INITIALIZATION_FAILED);
  }
}

void setLocale(icu::Locale& locale) {
  using arangodb::basics::Utf8Helper;
  std::string languageName;

  if (Utf8Helper::DefaultUtf8Helper.getCollatorCountry() != "") {
    languageName =
        std::string(Utf8Helper::DefaultUtf8Helper.getCollatorLanguage() + "_" +
                    Utf8Helper::DefaultUtf8Helper.getCollatorCountry());
    locale =
        icu::Locale(Utf8Helper::DefaultUtf8Helper.getCollatorLanguage().c_str(),
                    Utf8Helper::DefaultUtf8Helper.getCollatorCountry().c_str()
                    /*
                       const   char * variant  = 0,
                       const   char * keywordsAndValues = 0
                    */
        );
  } else {
    locale = icu::Locale(
        Utf8Helper::DefaultUtf8Helper.getCollatorLanguage().c_str());
    languageName = Utf8Helper::DefaultUtf8Helper.getCollatorLanguage();
  }

  LOG_TOPIC("f6e04", DEBUG, arangodb::Logger::CONFIG)
      << "using default language '" << languageName << "'";
}

arangodb::basics::LanguageType getLanguageType(std::string_view default_lang,
                                               std::string_view icu_lang) {
  if (icu_lang.empty()) {
    return arangodb::basics::LanguageType::DEFAULT;
  } else if (default_lang.empty()) {
    return arangodb::basics::LanguageType::ICU;
  } else {
    return arangodb::basics::LanguageType::INVALID;
  }
}

}  // namespace

using namespace arangodb::basics;
using namespace arangodb::options;

namespace arangodb {

LanguageFeature::~LanguageFeature() = default;

void LanguageFeature::collectOptions(
    std::shared_ptr<options::ProgramOptions> options) {
  options
      ->addOption("--default-language",
                  "An ISO-639 language code. You can only set this option "
                  "once, when initializing the database.",
                  new StringParameter(&_defaultLanguage),
                  arangodb::options::makeDefaultFlags(
                      arangodb::options::Flags::Uncommon))
      .setDeprecatedIn(31000)
      .setLongDescription(R"(The default language is used for sorting and
comparing strings. The language value is a two-letter language code (ISO-639) or
it is composed by a two-letter language code followed by a two letter country
code (ISO-3166). For example: `de`, `en`, `en_US`, `en_UK`.

The default is the system locale of the platform.)");

  options
      ->addOption(
          "--icu-language",
          "An ICU locale ID to set a language and optionally additional "
          "properties that affect string comparisons and sorting. You can only "
          "set this option once, when initializing the database.",
          new StringParameter(&_icuLanguage),
          arangodb::options::makeDefaultFlags(
              arangodb::options::Flags::Uncommon))
      .setIntroducedIn(30901)
      .setLongDescription(R"(With this option, you can get the sorting and
comparing order exactly as it is defined in the ICU standard. The language value
can be a two-letter language code (ISO-639), a two-letter language code followed
by a two letter country code (ISO-3166), or any other valid ICU locale
definition. For example: `de`, `en`, `en_US`, `en_UK`,
`de_AT@collation=phonebook`.

For the Swedish language (`sv`), for instance, the correct ICU-based sorting
order for letters is `'a','A','b','B','z','Z','å','Ä','ö','Ö'`. To get this
order, use `--icu-language sv`. If you use `--default-language sv` instead, the
sorting order will be `"A", "a", "B", "b", "Z", "z", "å", "Ä", "Ö", "ö"`.

**Note**: You can use only one of the language options, either `--icu-language`
or `--default-language`. Setting both of them results in an error.)");

  options
      ->addOption(
          "--default-language-check",
          "Check if `--icu-language` / `--default-language` matches the "
          "stored language.",
          new BooleanParameter(&_forceLanguageCheck),
          arangodb::options::makeDefaultFlags(
              arangodb::options::Flags::Uncommon))
      .setIntroducedIn(30800);
}

std::string LanguageFeature::prepareIcu(std::string const& binaryPath,
                                        std::string const& binaryExecutionPath,
                                        std::string& path,
                                        std::string const& binaryName) {
  std::string fn("icudtl.dat");
  if (TRI_GETENV("ICU_DATA", path)) {
    path = FileUtils::buildFilename(path, fn);
  }
  if (path.empty() || !TRI_IsRegularFile(path.c_str())) {
    if (!path.empty()) {
      LOG_TOPIC("581d1", WARN, arangodb::Logger::FIXME)
          << "failed to locate '" << fn << "' at '" << path << "'";
    }

    std::string bpfn = FileUtils::buildFilename(binaryExecutionPath, fn);

    if (TRI_IsRegularFile(fn.c_str())) {
      path = fn;
    } else if (TRI_IsRegularFile(bpfn.c_str())) {
      path = bpfn;
    } else {
      std::string argv0 =
          FileUtils::buildFilename(binaryExecutionPath, binaryName);
      path = TRI_LocateInstallDirectory(argv0.c_str(), binaryPath.c_str());
      path = FileUtils::buildFilename(path, ICU_DESTINATION_DIRECTORY, fn);

      if (!TRI_IsRegularFile(path.c_str())) {
        // Try whether we have an absolute install prefix:
        path = FileUtils::buildFilename(ICU_DESTINATION_DIRECTORY, fn);
      }
    }

    if (!TRI_IsRegularFile(path.c_str())) {
      std::string msg =
          std::string("failed to initialize ICU library. Could not locate '") +
          path +
          "'. Please make sure it is available. "
          "The environment variable ICU_DATA";
      std::string icupath;
      if (TRI_GETENV("ICU_DATA", icupath)) {
        msg += "='" + icupath + "'";
      }
      msg += " should point to the directory containing '" + fn + "'";

      LOG_TOPIC("0de77", FATAL, arangodb::Logger::FIXME) << msg;
      FATAL_ERROR_EXIT_CODE(TRI_EXIT_ICU_INITIALIZATION_FAILED);
    } else {
      std::string icu_path = path.substr(0, path.length() - fn.length());
      FileUtils::makePathAbsolute(icu_path);
      FileUtils::normalizePath(icu_path);
#ifndef _WIN32
      setenv("ICU_DATA", icu_path.c_str(), 1);
#else
      icu::UnicodeString uicuEnv(icu_path.c_str(), (uint16_t)icu_path.length());
      SetEnvironmentVariableW(L"ICU_DATA",
                              (wchar_t*)uicuEnv.getTerminatedBuffer());
#endif
    }
  }

  std::string icuData = basics::FileUtils::slurp(path);

  if (icuData.empty()) {
    LOG_TOPIC("d8a98", FATAL, arangodb::Logger::FIXME)
        << "failed to load '" << fn << "' at '" << path << "' - "
        << TRI_last_error();
    FATAL_ERROR_EXIT_CODE(TRI_EXIT_ICU_INITIALIZATION_FAILED);
  }

  return icuData;
}

void LanguageFeature::prepare() {
  std::string p;
  auto context = ArangoGlobalContext::CONTEXT;
  std::string binaryExecutionPath = context->getBinaryPath();
  std::string binaryName = context->binaryName();
  if (_icuData.empty()) {
    _icuData = LanguageFeature::prepareIcu(_binaryPath, binaryExecutionPath, p,
                                           binaryName);
  }

  _langType = ::getLanguageType(_defaultLanguage, _icuLanguage);

  if (LanguageType::INVALID == _langType) {
    LOG_TOPIC("d8a99", FATAL, arangodb::Logger::CONFIG)
        << "Only one parameter from --default-language and --icu-language "
           "should be specified";
    FATAL_ERROR_EXIT();
  }

  ::setCollator(
      _langType == LanguageType::ICU ? _icuLanguage : _defaultLanguage,
      _icuData.data(), _langType);
}

void LanguageFeature::start() { ::setLocale(_locale); }

icu::Locale& LanguageFeature::getLocale() { return _locale; }

std::tuple<std::string_view, LanguageType> LanguageFeature::getLanguage()
    const {
  if (LanguageType::ICU == _langType) {
    return {_icuLanguage, _langType};
  } else {
    TRI_ASSERT(LanguageType::DEFAULT == _langType);
    // If it is invalid type just returning _defaultLanguage
    return {_defaultLanguage, _langType};
  }
}

bool LanguageFeature::forceLanguageCheck() const { return _forceLanguageCheck; }

std::string LanguageFeature::getCollatorLanguage() const {
  using arangodb::basics::Utf8Helper;
  return Utf8Helper::DefaultUtf8Helper.getCollatorLanguage();
}

void LanguageFeature::resetLanguage(std::string_view language,
                                    arangodb::basics::LanguageType type) {
  _langType = type;
  _defaultLanguage.clear();
  _icuLanguage.clear();
  switch (_langType) {
    case LanguageType::DEFAULT:
      _defaultLanguage = language;
      break;

    case LanguageType::ICU:
      _icuLanguage = language;
      break;

    case LanguageType::INVALID:
    default:
      TRI_ASSERT(false);
      return;
  }

  ::setCollator(language.data(), _icuData.data(), _langType);
  ::setLocale(_locale);
}

}  // namespace arangodb


text:
#include <ctime>
#include <iostream>
#include <fstream>

#include "constants.h"
#include "config.h"
#include "user.h"
#include "logger.h"
#include "mineserver.h"
#include "permissions.h"
#include "tools.h"
#include "plugin.h"
#include "utf8.h"

#include "chat.h"

#include "protocol.h"

Chat::Chat()
{
}

Chat::~Chat()
{
}

bool Chat::sendUserlist(User* user)
{
  sendMsg(user, MC_COLOR_BLUE + "[ " + dtos(User::all().size()) + " / " + dtos(ServerInstance->config()->iData("system.user_limit")) + " players online ]", USER);
  std::string playerDesc;

  for (std::set<User*>::const_iterator it = ServerInstance->users().begin(); it != ServerInstance->users().end(); ++it)
  {
    if (!(*it)->logged)
    {
      continue;
    }
    playerDesc += (*it)->nick;
    if ((*it)->muted)
    {
      playerDesc += MC_COLOR_YELLOW + " (muted)";
    }
    if ((*it)->dnd)
    {
      playerDesc += MC_COLOR_YELLOW + " (dnd)";
    }
    playerDesc += ", ";
  }
  sendMsg(user, playerDesc, USER);

  return true;
}

std::deque<std::string> Chat::parseCmd(std::string cmd)
{
  int del;
  std::deque<std::string> temp;

  while (cmd.length() > 0)
  {
    while (cmd[0] == ' ')
    {
      cmd = cmd.substr(1);
    }

    del = cmd.find(' ');

    if (del > -1)
    {
      temp.push_back(cmd.substr(0, del));
      cmd = cmd.substr(del + 1);
    }
    else
    {
      temp.push_back(cmd);
      break;
    }
  }

  if (temp.empty())
  {
    temp.push_back("empty");
  }

  return temp;
}

bool Chat::handleMsg(User* user, std::string msg)
{
  if (msg.empty()) // If the message is empty handle it as if there is no message.
  {
    return true;
  }

  // Timestamp
  time_t rawTime = time(NULL);
  struct tm* Tm  = localtime(&rawTime);
  std::string timeStamp(asctime(Tm));
  timeStamp = timeStamp.substr(11, 5);

  runCallbackUntilFalse("PlayerChatPre",user->nick.c_str(), rawTime, msg.c_str());
  if (callbackReturnValue)
  {
    return false;
  }
  runAllCallback("PlayerChatPost",user->nick.c_str(), rawTime, msg.c_str());
  char prefix = msg[0];

  switch (prefix)
  {
    // Servermsg (Admin-only)
  case SERVERMSGPREFIX:
    if (IS_ADMIN(user->permissions))
    {
      handleServerMsg(user, msg, timeStamp);
    }
    break;

    // Admin message
  case ADMINCHATPREFIX:
    if (IS_ADMIN(user->permissions))
    {
      handleAdminChatMsg(user, msg, timeStamp);
    }
    break;

  case CHATCMDPREFIX:
    handleCommand(user, msg, timeStamp);
    break;
    // Normal chat message
  default:
    handleChatMsg(user, msg, timeStamp);
    break;
  }

  return true;
}

void Chat::handleCommand(User* user, std::string msg, const std::string& timeStamp)
{
  std::deque<std::string> cmd = parseCmd(msg.substr(1));

  if (!cmd.size() || !cmd[0].size())
  {
    return;
  }

  std::string command = cmd[0];
  cmd.pop_front();

  //Converting to char* array for plugins
  char** param = new char *[cmd.size()];
  for (uint32_t i = 0; i < cmd.size(); i++)
  {
    param[i] = (char*)cmd[i].c_str();
  }

  // If hardcoded auth command, ignore default password "CHANGEME"
  if (command == "auth" && cmd[0] != "CHANGEME" && cmd[0] == ServerInstance->config()->sData("system.admin.password"))
  {
    user->serverAdmin = true;
    SET_ADMIN(user->permissions);
    msg = MC_COLOR_RED + "[!] " + MC_COLOR_GREEN + "You have been authed as admin!";
    sendMsg(user, msg, USER);
  }
  else
  {
    runAllCallback("PlayerChatCommand",user->nick.c_str(), command.c_str(), cmd.size(), (const char**)param);
  }

  delete [] param;

}

void Chat::handleServerMsg(User* user, std::string msg, const std::string& timeStamp)
{
  // Decorate server message
  LOG2(INFO, "[!] " + msg.substr(1));
  msg = MC_COLOR_RED + "[!] " + MC_COLOR_GREEN + msg.substr(1);
  this->sendMsg(user, msg, ALL);
}

void Chat::handleAdminChatMsg(User* user, std::string msg, const std::string& timeStamp)
{
  LOG2(INFO, "[@] <" + user->nick + "> " + msg.substr(1));
  msg = timeStamp +  MC_COLOR_RED + " [@]" + MC_COLOR_WHITE + " <" + MC_COLOR_DARK_MAGENTA + user->nick + MC_COLOR_WHITE + "> " + msg.substr(1);
  this->sendMsg(user, msg, ADMINS);
}

void Chat::handleChatMsg(User* user, std::string msg, const std::string& timeStamp)
{
  if (user->isAbleToCommunicate("chat") == false)
  {
    return;
  }

  // Check for Admins or Server Console
  if (user->UID == SERVER_CONSOLE_UID)
  {
    LOG2(INFO, user->nick + " " + msg);
    msg = timeStamp + " " + MC_COLOR_RED + user->nick + MC_COLOR_WHITE + " " + msg;
  }
  else if (IS_ADMIN(user->permissions))
  {
    LOG2(INFO, "<" + user->nick + "> " + msg);
    msg = timeStamp + " <" + MC_COLOR_DARK_MAGENTA + user->nick + MC_COLOR_WHITE + "> " + msg;
  }
  else
  {
    LOG2(INFO, "<" + user->nick + "> " + msg);
    msg = timeStamp + " <" + user->nick + "> " + msg;
  }

  this->sendMsg(user, msg, ALL);
}

bool Chat::sendMsg(User* user, std::string msg, MessageTarget action)
{
  Packet pkt = Protocol::chatMsg("{\"text\": \""+json_esc(msg)+"\"}");

  switch (action)
  {
  case ALL:
    user->sendAll(pkt);
    break;

  case USER:
    user->writePacket(pkt);
    break;

  case ADMINS:
    user->sendAdmins(pkt);
    break;

  case OPS:
    user->sendOps(pkt);
    break;

  case GUESTS:
    user->sendGuests(pkt);
    break;

  case OTHERS:
    user->sendOthers(pkt);
    break;
  }

  return true;
}


text:
SeriesData::SeriesData(QObject *parent, QVariantMap params) :
    QObject(parent)
{

    m_id = params["id"].toInt();
    m_actors = params["actors"].toString();
    m_airsDayOfWeek = params["airsDayOfWeek"].toString();
    m_airsTime = params["airsTime"].toString();
    m_contentRating = params["contentRating"].toString();
    m_firstAired = params["firstAired"].toString();
    m_genre = params["genre"].toString();
    m_imdbId = params.contains("imdbId") ? params["imdbId"].toString() : params["imdbID"].toString();
    m_language = params["language"].toString();
    m_network = params["network"].toString();
    m_overview = params["overview"].toString();
    m_rating = params["rating"].toString();
    m_ratingCount = params["ratingCount"].toInt();
    m_runtime = params["runtime"].toInt();
    m_seriesName = params["seriesName"].toString();
    m_aliasNames = params["aliasNames"].toString();
    m_status = params["status"].toString();
    m_added = params["added"].toString();
    m_addedBy = params["addedBy"].toInt();
    m_banner = params["banner"].toString();
    m_fanart = params["fanart"].toString();
    m_lastUpdated = params["lastUpdated"].toString();
    m_poster = params["poster"].toString();
    m_zap2itId = params["zap2itid"].toString();
    m_watched = params["watched"].toInt();
    m_isAdded = params["isAdded"].toBool();
    m_nextEpisodeId = params["nextEpisodeId"].toString();
    m_nextEpisodeName = params["nextEpisodeName"].toString();
    m_nextEpisodeNumber = params["nextEpisodeNumber"].toString();
    m_nextEpisodeSeasonNumber = params["nextEpisodeSeasonNumber"].toString();
    m_daysToNextEpisode = params["daysToNext"].toString();
    m_nextEpisodeFirstAired = params["nextEpisodeFirstAired"].toString();
    m_nextEpisodeBanner = params["nextEpisodeBanner"].toString();
    m_nextEpisodeOverview = params["nextEpisodeOverview"].toString();
    m_nextEpisodeGuestStars = params["nextEpisodeGuestStars"].toString();
    m_nextEpisodeWriter = params["nextEpisodeWriter"].toString();
    m_nextEpisodeWatched = params["nextEpisodeWatched"].toInt();
    m_nextEpisodeFilename = params["nextEpisodeFilename"].toString();
}

int SeriesData::getID() { return m_id; }

QString SeriesData::getActors() { return m_actors; }

QString SeriesData::getAirsDayOfWeek() { return m_airsDayOfWeek; }

QString SeriesData::getAirsTime() { return m_airsTime; }

QString SeriesData::getContentRating() { return m_contentRating; }

QString SeriesData::getGenre() { return m_genre; }

QString SeriesData::getRating() { return m_rating; }

int SeriesData::getRatingCount() { return m_ratingCount; }

int SeriesData::getRuntime() { return m_runtime; }

QString SeriesData::getStatus() { return m_status; }

QString SeriesData::getAdded() { return m_added; }

int SeriesData::getAddedBy() { return m_addedBy; }

QString SeriesData::getFanart() { return m_fanart; }

QString SeriesData::getLastUpdated() { return m_lastUpdated; }

QString SeriesData::getPoster() { return m_poster; }

int SeriesData::getWatched() { return m_watched; }

QString SeriesData::getLanguage() { return m_language; }

QString SeriesData::getSeriesName() { return m_seriesName; }

QString SeriesData::getAliasNames() { return m_aliasNames; }

QString SeriesData::getBanner() { return m_banner; }

QString SeriesData::getOverview() { return m_overview; }

QString SeriesData::getFirstAired() { return m_firstAired; }

QString SeriesData::getIMDB_ID() { return m_imdbId; }

QString SeriesData::getZap2it_ID() { return m_zap2itId; }

QString SeriesData::getNetwork() { return m_network; }

void SeriesData::setWatched(int watched)
{
    if (m_watched != watched) {
        m_watched = watched;
        emit watchedChanged();
    }
}

bool SeriesData::getIsAdded() { return m_isAdded; }

QString SeriesData::getNextEpisodeId() { return m_nextEpisodeId; }

QString SeriesData::getNextEpisodeName() { return m_nextEpisodeName; }

QString SeriesData::getNextEpisodeNumber() { return m_nextEpisodeNumber; }

QString SeriesData::getNextEpisodeSeasonNumber() { return m_nextEpisodeSeasonNumber; }

QString SeriesData::getDaysToNextEpisode() { return m_daysToNextEpisode; }

QString SeriesData::getWatchedCount() { return m_watchedCount; }

QString SeriesData::getTotalCount() { return m_totalCount; }

QString SeriesData::getNextEpisodeFirstAired() { return m_nextEpisodeFirstAired; }

QString SeriesData::getNextEpisodeBanner() { return m_nextEpisodeBanner; }

QString SeriesData::getNextEpisodeOverview() { return m_nextEpisodeOverview; }

QString SeriesData::getNextEpisodeGuestStars() { return m_nextEpisodeGuestStars; }

QString SeriesData::getNextEpisodeWriter() { return m_nextEpisodeWriter; }

int SeriesData::getNextEpisodeWatched() { return m_nextEpisodeWatched; }

void SeriesData::setNextEpisodeWatched(int watched)
{
    if (m_nextEpisodeWatched != watched) {
        m_nextEpisodeWatched = watched;
        emit nextEpisodeWatchedChanged();
    }
}

QString SeriesData::getNextEpisodeFilename()
{
    return m_nextEpisodeFilename;
}


text:
package net.sf.antcontrib.cpptasks.sun;
import java.io.File;
import java.util.Vector;

import net.sf.antcontrib.cpptasks.CCTask;
import net.sf.antcontrib.cpptasks.CUtil;
import net.sf.antcontrib.cpptasks.compiler.CommandLineLinker;
import net.sf.antcontrib.cpptasks.compiler.LinkType;
import net.sf.antcontrib.cpptasks.compiler.Linker;
import net.sf.antcontrib.cpptasks.types.LibrarySet;
import net.sf.antcontrib.cpptasks.types.LibraryTypeEnum;
import net.sf.antcontrib.cpptasks.VersionInfo;

/**
 * Adapter for the Sun C89 Linker
 *
 * @author Hiram Chirino (cojonudo14@hotmail.com)
 */
public final class C89Linker extends CommandLineLinker {
    private static final C89Linker dllLinker = new C89Linker("lib", ".so");
    private static final C89Linker instance = new C89Linker("", "");
    public static C89Linker getInstance() {
        return instance;
    }
    private String outputPrefix;
    private C89Linker(String outputPrefix, String outputSuffix) {
        super("ld", "/bogus", new String[]{".o", ".a", ".lib", ".x"},
                new String[]{}, outputSuffix, false, null);
        this.outputPrefix = outputPrefix;
    }
    protected void addBase(long base, Vector args) {
    }
    protected void addFixed(Boolean fixed, Vector args) {
    }
    protected void addImpliedArgs(boolean debug, LinkType linkType, Vector args) {
        if (linkType.isSharedLibrary()) {
            args.addElement("-G");
        }
    }
    protected void addIncremental(boolean incremental, Vector args) {
    }
    public String[] addLibrarySets(CCTask task, LibrarySet[] libsets,
            Vector preargs, Vector midargs, Vector endargs) {
        super.addLibrarySets(task, libsets, preargs, midargs, endargs);
        StringBuffer buf = new StringBuffer("-l");
        for (int i = 0; i < libsets.length; i++) {
            LibrarySet set = libsets[i];
            File libdir = set.getDir(null);
            String[] libs = set.getLibs();
            if (libdir != null) {
                endargs.addElement("-L");
                endargs.addElement(libdir.getAbsolutePath());
            }
            for (int j = 0; j < libs.length; j++) {
                //
                //  reset the buffer to just "-l"
                //
                buf.setLength(2);
                //
                //  add the library name
                buf.append(libs[j]);
                //
                //  add the argument to the list
                endargs.addElement(buf.toString());
            }
        }
        return null;
    }
    protected void addMap(boolean map, Vector args) {
    }
    protected void addStack(int stack, Vector args) {
    }
    /* (non-Javadoc)
     * @see net.sf.antcontrib.cpptasks.compiler.CommandLineLinker#addEntry(int, java.util.Vector)
     */
    protected void addEntry(String entry, Vector args) {
    }

    public String getCommandFileSwitch(String commandFile) {
        return "@" + commandFile;
    }
    public File[] getLibraryPath() {
        return CUtil.getPathFromEnvironment("LIB", ";");
    }
    public String[] getLibraryPatterns(String[] libnames, LibraryTypeEnum libType) {
        return C89Processor.getLibraryPatterns(libnames, libType);
    }
    public Linker getLinker(LinkType linkType) {
        if (linkType.isSharedLibrary()) {
            return dllLinker;
        }
        /*
         * if(linkType.isStaticLibrary()) { return
         * OS390Librarian.getInstance(); }
         */
        return instance;
    }
    public int getMaximumCommandLength() {
        return Integer.MAX_VALUE;
    }
    public String[] getOutputFileNames(String baseName, VersionInfo versionInfo) {
        String[] baseNames = super.getOutputFileNames(baseName, versionInfo);
        if (outputPrefix.length() > 0) {
            for(int i = 0; i < baseNames.length; i++) {
                baseNames[i] = outputPrefix + baseNames[i];
            }
        }
        return baseNames;
    }
    public String[] getOutputFileSwitch(String outputFile) {
        return new String[]{"-o", outputFile};
    }
    public boolean isCaseSensitive() {
        return C89Processor.isCaseSensitive();
    }
}


text:
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "toplev.h"

int main (int argc, char **argv);

/* We define main() to call toplev_main(), which is defined in toplev.c.
   We do this in a separate file in order to allow the language front-end
   to define a different main(), if it so desires.  */

int
main (int argc, char **argv)
{
  return toplev_main (argc, (const char **) argv);
}


text:
using Skahal.Infrastructure.Framework.Logging;

namespace SpecFlowHelper.Logging
{
    /// <summary>
    /// The log helper.
    /// </summary>
    public static class LogHelper
    {
        #region Fields
        private static ILogStrategy s_logStrategy;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes the <see cref="LogHelper"/> class.
        /// </summary>
        static LogHelper()
        {
            s_logStrategy = new Log4netLogStrategy("Specs");
        }
        #endregion

        #region Methods
        /// <summary>
        /// Logs the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="args">The arguments.</param>
        public static void Log(string message, params object[] args)
        {
            s_logStrategy.WriteDebug(message, args);
        }
        #endregion
    }
}


text:
export PORT=80
export SLACK_VERIFY_TOKEN=[YOUR_SLACK_VERIFY_TOKEN] # https://api.slack.com/slash-commands
export BEEPBOOP_ID=[BEEP BOOP ID]
export BEEPBOOP_RESOURCER=[BEEP BOOP RESOURCER URL]
export BEEPBOOP_TOKEN=[BEEP BOOP TOKEN]

npm run start:dev


text:
package fi.iki.elonen;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.junit.Test;

public class BadRequestTest extends HttpServerTest {

    @Test
    public void testEmptyRequest() throws IOException {
        ByteArrayOutputStream outputStream = invokeServer("\n\n");
        String[] expected = new String[]{
            "HTTP/1.1 400 Bad Request"
        };
        assertResponse(outputStream, expected);
    }

    @Test
    public void testInvalidMethod() throws IOException {
        ByteArrayOutputStream outputStream = invokeServer("GETT http://example.com");
        String[] expected = new String[]{
            "HTTP/1.1 400 Bad Request"
        };
        assertResponse(outputStream, expected);
    }

    @Test
    public void testMissingURI() throws IOException {
        ByteArrayOutputStream outputStream = invokeServer("GET");
        String[] expected = new String[]{
            "HTTP/1.1 400 Bad Request"
        };
        assertResponse(outputStream, expected);
    }

}


text:
package io.vertigo.orchestra;

import io.vertigo.app.config.AppConfig;
import io.vertigo.app.config.AppConfigBuilder;
import io.vertigo.app.config.ModuleConfigBuilder;
import io.vertigo.commons.impl.CommonsFeatures;
import io.vertigo.commons.plugins.cache.memory.MemoryCachePlugin;
import io.vertigo.core.param.Param;
import io.vertigo.core.plugins.resource.classpath.ClassPathResourceResolverPlugin;
import io.vertigo.core.plugins.resource.url.URLResourceResolverPlugin;
import io.vertigo.dynamo.impl.DynamoFeatures;
import io.vertigo.dynamo.impl.database.vendor.h2.H2DataBase;
import io.vertigo.dynamo.plugins.database.connection.c3p0.C3p0ConnectionProviderPlugin;
import io.vertigo.dynamo.plugins.kvstore.delayedmemory.DelayedMemoryKVStorePlugin;
import io.vertigo.dynamo.plugins.store.datastore.sql.SqlDataStorePlugin;
import io.vertigo.orchestra.boot.DataBaseInitializer;
import io.vertigo.orchestra.util.monitoring.MonitoringServices;
import io.vertigo.orchestra.util.monitoring.MonitoringServicesImpl;
import io.vertigo.orchestra.webservices.WsDefinition;
import io.vertigo.orchestra.webservices.WsExecution;
import io.vertigo.orchestra.webservices.WsExecutionControl;
import io.vertigo.orchestra.webservices.data.user.TestUserSession;
import io.vertigo.orchestra.webservices.data.user.WsTestLogin;
import io.vertigo.persona.impl.security.PersonaFeatures;
import io.vertigo.vega.VegaFeatures;

public final class MyAppConfig {
	public static final int WS_PORT = 8088;

	public static AppConfigBuilder createAppConfigBuilder() {
		return new AppConfigBuilder().beginBoot()
				.withLocales("fr_FR")
				.addPlugin(ClassPathResourceResolverPlugin.class)
				.addPlugin(URLResourceResolverPlugin.class)
				.silently()
				.endBoot()
				.addModule(new CommonsFeatures()
						.withCache(MemoryCachePlugin.class)
						.withScript()
						.build())
				.addModule(new DynamoFeatures()
						.withKVStore()
						.addKVStorePlugin(DelayedMemoryKVStorePlugin.class,
								Param.create("collections", "tokens"),
								Param.create("timeToLiveSeconds", "120"))
						.withStore()
						.addDataStorePlugin(SqlDataStorePlugin.class,
								Param.create("dataSpace", "orchestra"),
								Param.create("connectionName", "orchestra"),
								Param.create("sequencePrefix", "SEQ_"))
						.withSqlDataBase()
						.addSqlConnectionProviderPlugin(C3p0ConnectionProviderPlugin.class,
								Param.create("name", "orchestra"),
								Param.create("dataBaseClass", H2DataBase.class.getName()),
								Param.create("jdbcDriver", org.h2.Driver.class.getName()),
								Param.create("jdbcUrl", "jdbc:h2:mem:database"))
						.build())
				// we build h2 mem
				.addModule(new ModuleConfigBuilder("databaseInitializer").withNoAPI().addComponent(DataBaseInitializer.class).build())
				//
				.addModule(new OrchestraFeatures()
						.withDataBase("NODE_TEST_1", 1, 3, 60)
						.withMemory(1)
						.build())
				.addModule(new ModuleConfigBuilder("orchestra-test")
						//---Services
						.addComponent(MonitoringServices.class, MonitoringServicesImpl.class)
						.build());
	}

	public static void addVegaEmbeded(final AppConfigBuilder appConfigBuilder) {
		appConfigBuilder
				.addModule(new PersonaFeatures()
						.withUserSession(TestUserSession.class)
						.build())
				.addModule(new VegaFeatures()
						.withTokens("tokens")
						.withSecurity()
						.withMisc()
						.withEmbeddedServer(WS_PORT)
						.build());
	}

	public static void addWebServices(final AppConfigBuilder appConfigBuilder) {
		appConfigBuilder
				.addModule(new ModuleConfigBuilder("orchestra-ws")
						.withNoAPI()
						.addComponent(WsDefinition.class)
						.addComponent(WsExecution.class)
						.addComponent(WsExecutionControl.class)
						.addComponent(WsTestLogin.class)
						.build());
	}

	public static AppConfig config() {
		// @formatter:off
		return createAppConfigBuilder().build();
	}

	public static AppConfig configWithVega() {
		// @formatter:off
		final AppConfigBuilder builder = createAppConfigBuilder();
		addVegaEmbeded(builder);
		addWebServices(builder);
		return builder.build();
	}

}


text:
#ifndef BOOST_NUMERIC_ODEINT_EXTERNAL_BLAZE_BLAZE_ALGEBRA_DISPATCHER_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_EXTERNAL_BLAZE_BLAZE_ALGEBRA_DISPATCHER_HPP_INCLUDED

#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>
#include <blaze/math/dense/StaticVector.h>
#include <blaze/math/dense/DynamicVector.h>

namespace boost {
namespace numeric {
namespace odeint {

template< typename T , size_t N , bool TF >
struct algebra_dispatcher< blaze::StaticVector< T , N , TF >  >
{
    typedef vector_space_algebra algebra_type;
};

template< typename T , bool TF >
struct algebra_dispatcher< blaze::DynamicVector< T , TF > >
{
    typedef vector_space_algebra algebra_type;
};

}
}
}

#endif // BOOST_NUMERIC_ODEINT_EXTERNAL_BLAZE_BLAZE_ALGEBRA_DISPATCHER_HPP_INCLUDED


text:
namespace core {

namespace {

// Decompose a block of code using distorm wrapper.
_DecodeResult DecomposeCode(const uint8_t* code_data,
                            size_t length,
                            _DInst result[],
                            const unsigned int max_results,
                            unsigned int* result_count) {
  _CodeInfo code = {};
  code.dt = Decode32Bits;
  code.features = DF_NONE;
  code.codeOffset = 0;
  code.codeLen = length;
  code.code = code_data;
  return DistormDecompose(&code, result, max_results, result_count);
}

// Decompose a block of code using distorm directly.
_DecodeResult RawDecomposeCode(const uint8_t* code_data,
                               size_t length,
                               _DInst result[],
                               const unsigned int max_results,
                               unsigned int* result_count) {
  _CodeInfo code = {};
  code.dt = Decode32Bits;
  code.features = DF_NONE;
  code.codeOffset = 0;
  code.codeLen = length;
  code.code = code_data;
  return distorm_decompose(&code, result, max_results, result_count);
}

_DInst DecodeBuffer(const uint8_t* buffer, size_t length) {
  _DInst inst = {};
  EXPECT_TRUE(DecodeOneInstruction(buffer, length, &inst));
  EXPECT_EQ(length, inst.size);
  return inst;
}

// One of the AVX instructions that is currently not supported by distorm.
// vxorps ymm0, ymm0, ymm0
const uint8_t kVxorps[] = {0xC5, 0xFC, 0x57, 0xC0};

// Instructions for which distorm indicates a size of 0 for the destination
// operand size.
const uint8_t kFxsave[] = {0x0F, 0xAE, 0x00};
const uint8_t kFxrstor[] = {0x0F, 0xAE, 0x08};

// FPU instructions for which distorm had some decoding issues in the past.
// fnstcw m16
const uint8_t kFnstcw[] = {0xD9, 0x7D, 0xEA};
// fldcw m16
const uint8_t kFldcw[] = {0xD9, 0x6D, 0xE4};

// Instructions for which distorm do not activated the write flag.
// fst qword ptr [0A374E8h]
const uint8_t kFst[] = {0xDD, 0x15, 0xE8, 0x74, 0xA3, 0x00};
// fstp qword ptr [0A374E8h]
const uint8_t kFstp[] = {0xDD, 0x1D, 0xE8, 0x74, 0xA3, 0x00};
// fist qword ptr [0A374E8h]
const uint8_t kFist[] = {0xDB, 0x15, 0xE0, 0x74, 0xA3, 0x00};
// fistp qword ptr [0A374E8h]
const uint8_t kFistp[] = {0xDB, 0x1D, 0xE0, 0x74, 0xA3, 0x00};
// crc32 cx,word ptr [esi]
const uint8_t kCrc32CX[] = {0x66, 0xF2, 0x0F, 0x38, 0xF1, 0x0E};

// Nop Instruction byte sequences.
const uint8_t kNop2Mov[] = {0x8B, 0xFF};
const uint8_t kNop3Lea[] = {0x8D, 0x49, 0x00};
// The recommended NOP sequences.
using testing::kNop1;
using testing::kNop2;
using testing::kNop3;
using testing::kNop4;
using testing::kNop5;
using testing::kNop6;
using testing::kNop7;
using testing::kNop8;
using testing::kNop9;
using testing::kNop10;
using testing::kNop11;

// Call instruction.
const uint8_t kCall[] = {0xE8, 0xCA, 0xFE, 0xBA, 0xBE};

// Control Flow byte sequences (note that the JMP is indirect).
const uint8_t kJmp[] = {0xFF, 0x24, 0x8D, 0xCA, 0xFE, 0xBA, 0xBE};
const uint8_t kRet[] = {0xC3};
const uint8_t kRetN[] = {0xC2, 0x08, 0x00};
const uint8_t kJe[] = {0x74, 0xCA};
const uint8_t kSysEnter[] = {0x0F, 0x34};
const uint8_t kSysExit[] = {0x0F, 0x35};

// Interrupts.
const uint8_t kInt2[] = {0xCD, 0x02};
const uint8_t kInt3[] = {0xCC};

// VEX encoded instructions that Distorm doesn't handle properly.
const std::vector<std::vector<uint8_t>> kVexInstructions = {
    // AVX instructions.
    {0xC4, 0xE3, 0xFD, 0x00, 0xED, 0x44},        // vpermq
    {0xC4, 0xE2, 0x4D, 0x36, 0xC0},              // vpermd
    {0xC4, 0xE2, 0x7D, 0x5A, 0x45, 0xD0},        // vbroadcasti128
    {0xC4, 0xE3, 0x7D, 0x38, 0x2C, 0x0F, 0x01},  // vinserti128
    {0xC4, 0xE2, 0x79, 0x78, 0xC0},              // vpbroadcastb
    {0xC4, 0xE2, 0x7D, 0x58, 0x40, 0x04},        // vpbroadcastd
    {0xC4, 0xE2, 0x7D, 0x18, 0xC0},              // vbroadcastss
    {0xC4, 0xE3, 0x7D, 0x39, 0xC8, 0x01},        // vextracti128
    {0xC4, 0xE2, 0x7D, 0x90, 0x1C, 0x88},        // vpgatherdd
    {0xC4, 0xE2, 0x7D, 0x8C, 0x00},              // vpmaskmovd
    {0xC4, 0xE2, 0x7D, 0x8E, 0x90},              // vpmaskmovd

    // F16C instructions.
    {0xC4, 0xE3, 0x79, 0x1D, 0xC8, 0x00},  // vcvtps2ph
    {0xC4, 0xE2, 0x79, 0x13, 0xE0},        // vcvtps2ps
};

void TestBadlyDecodedInstruction(const uint8_t* code, size_t code_length) {
  _DInst inst[1] = {};
  unsigned int inst_count = 0;
  _DecodeResult result = RawDecomposeCode(
      code, code_length, inst, arraysize(inst), &inst_count);
  EXPECT_EQ(DECRES_MEMORYERR, result);
  EXPECT_EQ(0u, inst_count);

  result = DecomposeCode(
      code, code_length, inst, arraysize(inst), &inst_count);
  EXPECT_EQ(DECRES_SUCCESS, result);
  EXPECT_EQ(1u, inst_count);
  EXPECT_EQ(code_length, inst[0].size);
}

}  // namespace

TEST(DisassemblerUtilTest, DistormWrapperVxorpsPasses) {
  _DInst inst = {};
  EXPECT_TRUE(DecodeOneInstruction(kVxorps, sizeof(kVxorps), &inst));
}

TEST(DisassemblerUtilTest, InstructionToString) {
  _DInst inst = {};
  inst = DecodeBuffer(kNop1, sizeof(kNop1));

  std::string Nop1Str;
  EXPECT_TRUE(InstructionToString(inst, kNop1, sizeof(kNop1), &Nop1Str));
  ASSERT_THAT(Nop1Str, testing::HasSubstr("90"));
  ASSERT_THAT(Nop1Str, testing::HasSubstr("NOP"));
}

TEST(DisassemblerUtilTest, IsNop) {
  EXPECT_FALSE(IsNop(DecodeBuffer(kJmp, sizeof(kJmp))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop1, sizeof(kNop1))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop2, sizeof(kNop2))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop3, sizeof(kNop3))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop4, sizeof(kNop4))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop5, sizeof(kNop5))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop6, sizeof(kNop6))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop7, sizeof(kNop7))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop8, sizeof(kNop8))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop9, sizeof(kNop9))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop10, sizeof(kNop10))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop11, sizeof(kNop11))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop2Mov, sizeof(kNop2Mov))));
  EXPECT_TRUE(IsNop(DecodeBuffer(kNop3Lea, sizeof(kNop3Lea))));
}

TEST(DisassemblerUtilTest, IsCall) {
  EXPECT_FALSE(IsCall(DecodeBuffer(kJmp, sizeof(kJmp))));
  EXPECT_FALSE(IsCall(DecodeBuffer(kNop1, sizeof(kNop1))));
  EXPECT_TRUE(IsCall(DecodeBuffer(kCall, sizeof(kCall))));
}

TEST(DisassemblerUtilTest, IsSystemCall) {
  EXPECT_FALSE(IsSystemCall(DecodeBuffer(kJmp, sizeof(kJmp))));
  EXPECT_FALSE(IsSystemCall(DecodeBuffer(kNop1, sizeof(kNop1))));
  EXPECT_TRUE(IsSystemCall(DecodeBuffer(kSysEnter, sizeof(kSysEnter))));
  EXPECT_TRUE(IsSystemCall(DecodeBuffer(kSysExit, sizeof(kSysExit))));
}

TEST(DisassemblerUtilTest, IsConditionalBranch) {
  EXPECT_FALSE(IsConditionalBranch(DecodeBuffer(kNop4, sizeof(kNop4))));
  EXPECT_FALSE(IsConditionalBranch(DecodeBuffer(kJmp, sizeof(kJmp))));
  EXPECT_FALSE(IsConditionalBranch(DecodeBuffer(kRet, sizeof(kRet))));
  EXPECT_TRUE(IsConditionalBranch(DecodeBuffer(kJe, sizeof(kJe))));
}

TEST(DisassemblerUtilTest, IsUnconditionalBranch) {
  EXPECT_FALSE(IsUnconditionalBranch(DecodeBuffer(kNop4, sizeof(kNop4))));
  EXPECT_FALSE(IsUnconditionalBranch(DecodeBuffer(kRet, sizeof(kRet))));
  EXPECT_FALSE(IsUnconditionalBranch(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_TRUE(IsUnconditionalBranch(DecodeBuffer(kJmp, sizeof(kJmp))));
}

TEST(DisassemblerUtilTest, IsBranch) {
  EXPECT_FALSE(IsBranch(DecodeBuffer(kNop4, sizeof(kNop4))));
  EXPECT_FALSE(IsBranch(DecodeBuffer(kRet, sizeof(kRet))));
  EXPECT_TRUE(IsBranch(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_TRUE(IsBranch(DecodeBuffer(kJmp, sizeof(kJmp))));
}

TEST(DisassemblerUtilTest, HasPcRelativeOperand) {
  EXPECT_FALSE(HasPcRelativeOperand(DecodeBuffer(kRetN, sizeof(kRet)), 0));
  EXPECT_FALSE(HasPcRelativeOperand(DecodeBuffer(kJmp, sizeof(kJmp)), 0));
  EXPECT_TRUE(HasPcRelativeOperand(DecodeBuffer(kJe, sizeof(kJe)), 0));
}

TEST(DisassemblerUtilTest, IsControlFlow) {
  EXPECT_FALSE(IsControlFlow(DecodeBuffer(kNop4, sizeof(kNop4))));
  EXPECT_TRUE(IsControlFlow(DecodeBuffer(kJmp, sizeof(kJmp))));
  EXPECT_TRUE(IsControlFlow(DecodeBuffer(kRet, sizeof(kRet))));
  EXPECT_TRUE(IsControlFlow(DecodeBuffer(kRetN, sizeof(kRetN))));
  EXPECT_TRUE(IsControlFlow(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_TRUE(IsControlFlow(DecodeBuffer(kSysEnter, sizeof(kSysEnter))));
}

TEST(DisassemblerUtilTest, IsImplicitControlFlow) {
  EXPECT_FALSE(IsImplicitControlFlow(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_TRUE(IsImplicitControlFlow(DecodeBuffer(kRet, sizeof(kRet))));
  EXPECT_TRUE(IsImplicitControlFlow(DecodeBuffer(kRetN, sizeof(kRetN))));
  EXPECT_TRUE(IsImplicitControlFlow(DecodeBuffer(kJmp, sizeof(kJmp))));
}

TEST(DisassemblerUtilTest, IsInterrupt) {
  EXPECT_FALSE(IsInterrupt(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_TRUE(IsInterrupt(DecodeBuffer(kInt2, sizeof(kInt2))));
  EXPECT_TRUE(IsInterrupt(DecodeBuffer(kInt3, sizeof(kInt3))));
}

TEST(DisassemblerUtilTest, IsDebugInterrupt) {
  EXPECT_FALSE(IsDebugInterrupt(DecodeBuffer(kJe, sizeof(kJe))));
  EXPECT_FALSE(IsDebugInterrupt(DecodeBuffer(kInt2, sizeof(kInt2))));
  EXPECT_TRUE(IsDebugInterrupt(DecodeBuffer(kInt3, sizeof(kInt3))));
}

TEST(DisassemblerUtilTest, GetRegisterType) {
  EXPECT_EQ(R_DL, GetRegisterType(assm::kRegisterDl));
  EXPECT_EQ(R_AX, GetRegisterType(assm::kRegisterAx));
  EXPECT_EQ(R_EDI, GetRegisterType(assm::kRegisterEdi));

  EXPECT_EQ(R_BH, GetRegisterType(assm::bh));
  EXPECT_EQ(R_CX, GetRegisterType(assm::cx));
  EXPECT_EQ(R_ESP, GetRegisterType(assm::esp));
}

TEST(DisassemblerUtilTest, GetRegisterId) {
  EXPECT_EQ(assm::kRegisterAl, GetRegisterId(R_AL));
  EXPECT_EQ(assm::kRegisterSp, GetRegisterId(R_SP));
  EXPECT_EQ(assm::kRegisterEdi, GetRegisterId(R_EDI));
}

TEST(DisassemblerUtilTest, GetRegister) {
  EXPECT_EQ(assm::bh, GetRegister(R_BH));
  EXPECT_EQ(assm::cx, GetRegister(R_CX));
  EXPECT_EQ(assm::ebp, GetRegister(R_EBP));
}

TEST(DisassemblerUtilTest, DistormDecompose) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            DecomposeCode(kNop3Lea,
                          sizeof(kNop3Lea),
                          results,
                          kMaxResults,
                          &result_count));
  EXPECT_EQ(1U, result_count);
  EXPECT_EQ(32U, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, DistormDecomposeFnstcw) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            DecomposeCode(kFnstcw,
                          sizeof(kFnstcw),
                          results,
                          kMaxResults,
                          &result_count));
  EXPECT_EQ(1U, result_count);
  EXPECT_EQ(16U, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, DistormDecomposeFldcw) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            DecomposeCode(kFldcw,
                          sizeof(kFldcw),
                          results,
                          kMaxResults,
                          &result_count));
  EXPECT_EQ(1U, result_count);
  EXPECT_EQ(16U, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, WrongAccessSizeOnRawDistormDecomposeFxsave) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS, RawDecomposeCode(kFxsave, sizeof(kFxsave), results,
                                             kMaxResults, &result_count));
  EXPECT_EQ(1U, result_count);
  EXPECT_EQ(0U, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, DistormDecomposeFxsave) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            DecomposeCode(kFxsave,
                          sizeof(kFxsave),
                          results,
                          kMaxResults,
                          &result_count));
  EXPECT_EQ(1, result_count);
  EXPECT_EQ(64, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, WrongAccessSizeOnRawDistormDecomposeFxrstor) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            RawDecomposeCode(kFxrstor, sizeof(kFxrstor), results, kMaxResults,
                             &result_count));
  EXPECT_EQ(1U, result_count);
  EXPECT_EQ(0U, results[0].ops[0].size);
}

TEST(DisassemblerUtilTest, DistormDecomposeFxrstor) {
  const unsigned int kMaxResults = 16;
  unsigned int result_count = 0;
  _DInst results[kMaxResults];
  EXPECT_EQ(DECRES_SUCCESS,
            DecomposeCode(kFxrstor,
                          sizeof(kFxrstor),
                          results,
                          kMaxResults,
                          &result_count));
  EXPECT_EQ(1, result_count);
  EXPECT_EQ(64, results[0].ops[0].size);
}

// If this test starts failing then Distorm now properly handles the AVX2
// instructions. Please remove the workaround in disassembler_util.cc.
TEST(DisassemblerUtilTest, TestBadlyDecodedVexInstructions) {
  for (const auto iter : kVexInstructions) {
    EXPECT_NO_FATAL_FAILURE(
        TestBadlyDecodedInstruction(iter.data(), iter.size()));
  }
}

TEST(DisassemblerUtilTest, TestBadlyDecodedCRC32) {
  // CRC32 with a 16 bit operand size prefix is not handled correctly by
  // distorm.
  EXPECT_NO_FATAL_FAILURE(
      TestBadlyDecodedInstruction(kCrc32CX, sizeof(kCrc32CX)));
}

}  // namespace core


text:
package sonata.kernel.WimAdaptor.commons;

import java.util.ArrayList;

import com.fasterxml.jackson.annotation.JsonProperty;

public class WimRecord {

  private String uuid;
  private String name;
  @JsonProperty("attached_vims")
  private ArrayList<String> attachedVims = new ArrayList<String>();

  public String getUuid() {
    return uuid;
  }
  public String getName() {
    return name;
  }
  public ArrayList<String> getAttachedVims() {
    return attachedVims;
  }
  public void setUuid(String uuid) {
    this.uuid = uuid;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void setAttachedVims(ArrayList<String> attachedVims) {
    this.attachedVims = attachedVims;
  }

  @Override
  public String toString(){
    String out = "uuid: "+this.uuid+"\n"+
        "name: "+this.name+"\n"+
        "attachedVim: "+this.attachedVims.toString();

    return out;
  }

}