text:
namespace {

// Input files.
// const char *kScalarFieldFile = "smoothed_scalar.vtk";
// const char *kScalarFieldFile = "smoothed_scalar_5.vtk";
// const char *kScalarFieldFile = "/home/linyufly/Data/P96_bFTLE.vtk";
// const char *kScalarFieldFile = "/home/linyufly/GitHub/GaussianSmoothing3D/gaussian_smoothed.vtk";
// const char *kScalarFieldFile = "P96_bFTLE/FTLE96ixbwd3D_highres_noT.1.vtk";
// const char *kScalarFieldFile = "/home/linyufly/GitLab/RidgeExtraction/data/convective_half_ftle.vtk";
const char *kScalarFieldFile = "/home/linyufly/GitLab/RidgeExtraction/data/convective_half_label_dig_corrected.vtk";
// const char *kScalarFieldFile = "P96_bFTLE/FTLE96ixbwd3D_highres_noT.1.vtk";
// const char *kScalarFieldFile = "P96_bFTLE/FTLE96ixbwd3D_highres_noT.2.vtk";
// const char *kScalarFieldFile = "P96_bFTLE/FTLE96ixbwd3D_highres_noT.24.vtk";
// const char *kBinaryFieldFile = "binary_volume.vtk";
// const char *kBinaryFieldFile = "threshold_volume_raw_5_2.vtk";
// const char *kBinaryFieldFile = "largest_component.vtk";
const char *kBinaryFieldFile = "component.vtk";
// const char *kBinaryFieldToDeflate = "inflated_binary_volume.vtk";
// const char *kBinaryFieldToDeflate = "inflated_binary_volume_raw_5_2.vtk";
const char *kBinaryFieldToDeflate = "inflate.vtk";
// const char *kMaskFieldFile = "mask_volume.vtk";
// const char *kMaskFieldFile = "deflated_binary_volume_raw_5_2.vtk";
const char *kMaskFieldFile = "deflate.vtk";
// const char *kMaskFieldFile = "inflated_binary_volume.vtk";
// const char *kMaskFieldFile = "deflate.vtk";
// const char *kCoarseLabelFile = "coarse_labelling.vtk";
const char *kCoarseLabelFile = "/home/linyufly/GitHub/Watershed/itk_watershed_image_filter_result.vtk";
// const char *kFineLabelFile = "fine_labelling.vtk";
const char *kFineLabelFile = "/home/linyufly/GitHub/Watershed/itk_watershed_image_filter_result.vtk";
const char *kScalarFieldToCrop = "/home/linyufly/Data/convective_half.vtk";
const char *kScalarFieldToSymmetricalize = "cropped_convective_half.vtk";
// const char *kLabelFieldToModify = "convective_labelling.vtk";
const char *kLabelFieldToModify = "modify.vtk";
const char *kFineLabelFieldFile = "convective_half_fine_labelling.vtk";
const char *kCoarseLabelFieldFile = "convective_half_coarse_labelling.vtk";

// Output files.
const char *kThresholdOutputFile = "threshold.vtk";
const char *kWaterproofOutputFile = "waterproof.vtk";
const char *kComponentOutputFile = "component.vtk";
const char *kInflateOutputFile = "inflate.vtk";
const char *kDeflateOutputFile = "deflate.vtk";
const char *kMaskOutputFile = "masked.vtk";
const char *kBoundaryOutputFile = "boundary.vtk";
const char *kCropOutputFile = "crop.vtk";
const char *kSymmetricalizeOutputFile = "symmetricalize.vtk";
const char *kModifyOutputFile = "modify.vtk";
const char *kDigOutputFile = "dig.vtk";
const char *kMirrorOutputFile = "mirror.vtk";

const double kThreshold = 5.8;  // 4.0, 4.5, 5.0, 5.5, 6.0
                                // 5.8 for 0
                                // 5.8 for 1
                                // 5.7 for 2
                                // 5.4 for 3
                                // 5.4 for 4
                                // 5.4 for 5
                                // 5.4 for 6
                                // 5.3 for 7
                                // 5.3 for 8
                                // 5.3 for 9
                                // 5.2 for 10
                                // 5.2 for 11
                                // 5.2 for 12
                                // 5.3 for 13
                                // 5.3 for 14
                                // 5.4 for 15
                                // 5.4 for 16
                                // 5.4 for 17
                                // 5.4 for 18
                                // 5.4 for 19
                                // 5.4 for 20
                                // 5.4 for 21
                                // 5.5 for 22
                                // 5.7 for 23
                                // 5.7 for 24
const double kCropDistance = 1.6;

const int kConnectivity = 6;
const int kNumberOfInflations = 10;
const int kNumberOfDeflations = 5;

const int dire[6][3] = {
    {1, 0, 0}, {-1, 0, 0},
    {0, 1, 0}, {0, -1, 0},
    {0, 0, 1}, {0, 0, -1}};

int code(int *index, int *dimensions) {
  return (index[2] * dimensions[1] + index[1]) * dimensions[0] + index[0];
}

void decode(int code, int *dimensions, int *index) {
  index[0] = code % dimensions[0];
  code /= dimensions[0];
  index[1] = code % dimensions[1];
  index[2] = code / dimensions[1];
}

bool outside(int *index, int *dimensions) {
  for (int c = 0; c < 3; c++) {
    if (index[c] < 0 || index[c] >= dimensions[c]) {
      return true;
    }
  }

  return false;
}

double square(double value) {
  return value * value;
}

int flood_fill(int s_x, int s_y, int s_z, vtkStructuredPoints *field,
                int color, int ***mark) {
  int dimensions[3];
  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  int start_index[] = {s_x, s_y, s_z};
  std::queue<int> queue;
  queue.push(code(start_index, dimensions));

  mark[s_x][s_y][s_z] = color;

  int num_elements = 0;

  while (!queue.empty()) {
    num_elements++;

    int curr_code = queue.front();
    queue.pop();

    int curr_index[3];

    decode(curr_code, dimensions, curr_index);

    for (int d = 0; d < kConnectivity; d++) {
      int x = curr_index[0] + dire[d][0];
      int y = curr_index[1] + dire[d][1];
      int z = curr_index[2] + dire[d][2];

      int next_index[] = {x, y, z};
      int next_code = code(next_index, dimensions);

      if (outside(next_index, dimensions)) {
        continue;
      }

      if (mark[x][y][z]) {
        continue;
      }

      if (field->GetPointData()->GetScalars()->GetTuple1(next_code)
          <= kThreshold) {
        continue;
      }

      mark[x][y][z] = color;
      queue.push(next_code);
    }
  }

  return num_elements;
}

void inflate(int *dimensions, int num_inflations, bool ***inside) {
  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  int ***steps = create_3d_array<int>(nx, ny, nz);

  std::queue<int> queue;

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        if (!inside[x][y][z]) {
          steps[x][y][z] = -1;
        } else {
          steps[x][y][z] = 0;
          int curr_index[] = {x, y, z};
          int curr_code = code(curr_index, dimensions);
          queue.push(curr_code);
        }
      }
    }
  }

  /// DEBUG ///
  printf("queue.size() = %d\n", static_cast<int>(queue.size()));

  while (!queue.empty()) {
    int curr_code = queue.front();
    queue.pop();

    int curr_index[3];
    decode(curr_code, dimensions, curr_index);

    for (int d = 0; d < kConnectivity; d++) {
      int x = curr_index[0] + dire[d][0];
      int y = curr_index[1] + dire[d][1];
      int z = curr_index[2] + dire[d][2];

      int next_index[] = {x, y, z};

      if (outside(next_index, dimensions)) {
        continue;
      }

      if (steps[x][y][z] != -1) {
        continue;
      }

      /// DEBUG ///
      // printf("x, y, z = %d, %d, %d\n", x, y, z);

      steps[x][y][z] = steps[curr_index[0]][curr_index[1]][curr_index[2]] + 1;
      int next_code = code(next_index, dimensions);

      queue.push(next_code);
    }
  }

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        if (steps[x][y][z] <= num_inflations) {
          inside[x][y][z] = true;
        }

        if (steps[x][y][z] == -1) {
          printf("How could this happen? %d, %d, %d\n", x, y, z);
          exit(0);
        }
      }
    }
  }

  delete_3d_array(steps);
}

}

void threshold_test() {
  printf("threshold_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  for (int i = 0;
       i < field->GetPointData()->GetScalars()->GetNumberOfTuples();
       i++) {
    double value = field->GetPointData()->GetScalars()->GetTuple1(i);
    if (value <= kThreshold) {
      value = 0.0;
    } else {
      value = 1.0;
    }

    field->GetPointData()->GetScalars()->SetTuple1(i, value);
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kThresholdOutputFile);
  writer->SetInputData(field);
  writer->Write();

  printf("} threshold_test\n");
}

void waterproof_test() {
  printf("waterproof_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];

  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  bool ***visited = create_3d_array<bool>(nx, ny, nz);
  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        visited[x][y][z] = false;
      }
    }
  }

  visited[0][0][0] = true;
  std::queue<int> queue;
  queue.push(0);

  while (!queue.empty()) {
    int curr = queue.front();
    queue.pop();

    int curr_index[3];
    decode(curr, dimensions, curr_index);

    for (int d = 0; d < kConnectivity; d++) {
      int x = curr_index[0] + dire[d][0];
      int y = curr_index[1] + dire[d][1];
      int z = curr_index[2] + dire[d][2];

      int next_index[] = {x, y, z};
      if (outside(next_index, dimensions)) {
        continue;
      }

      if (visited[x][y][z]) {
        continue;
      }

      int next_code = code(next_index, dimensions);
      double value = field->GetPointData()->GetScalars()->GetTuple1(next_code);

      if (value > kThreshold) {
        continue;
      }

      visited[x][y][z] = true;
      queue.push(next_code);
    }
  }

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);
        if (visited[x][y][z]) {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 0.0);
        } else {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 1.0);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kWaterproofOutputFile);
  writer->SetInputData(field);
  writer->Write();

  delete_3d_array(visited);

  printf("} waterproof_test\n");
}

void component_test() {
  printf("component_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];

  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  int ***mark = create_3d_array<int>(nx, ny, nz);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        mark[x][y][z] = 0;
      }
    }
  }

  int num_colors = 0;
  int best_color = -1, largest = 0;

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        if (!mark[x][y][z]) {
          int curr_index[] = {x, y, z};
          int curr_code = code(curr_index, dimensions);

          if (field->GetPointData()->GetScalars()->GetTuple1(curr_code)
              > kThreshold) {
            num_colors++;
            int num_elements = flood_fill(x, y, z, field, num_colors, mark);

            if (num_elements > largest) {
              largest = num_elements;
              best_color = num_colors;
            }

            printf("color %d: num_elements = %d (best color: %d, largest: %d)\n",
                   num_colors, num_elements, best_color, largest);
          }
        }
      }
    }
  }

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        if (mark[x][y][z] != best_color) {
          mark[x][y][z] = 0;
        } else {
          mark[x][y][z] = 1;
        }

        field->GetPointData()->GetScalars()->SetTuple1(
            curr_code, static_cast<double>(mark[x][y][z]));
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kComponentOutputFile);
  writer->SetInputData(field);
  writer->Write();

  delete_3d_array(mark);

  printf("} component_test\n");
}

void inflate_test() {
  printf("inflate_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kBinaryFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];

  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  bool ***inside = create_3d_array<bool>(nx, ny, nz);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        double value = field->GetPointData()->GetScalars()
                                            ->GetTuple1(curr_code);

        if (value > 0.5) {
          inside[x][y][z] = true;
        } else {
          inside[x][y][z] = false;
        }
      }
    }
  }

  inflate(dimensions, kNumberOfInflations, inside);

  bool ***visited = create_3d_array<bool>(nx, ny, nz);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        visited[x][y][z] = false;
      }
    }
  }

  printf("inside[0][0][0] = %d\n", static_cast<int>(inside[0][0][0]));

  std::queue<int> queue;
  queue.push(0);
  visited[0][0][0] = true;

  while (!queue.empty()) {
    int curr_code = queue.front();
    queue.pop();

    int curr_index[3];
    decode(curr_code, dimensions, curr_index);

    for (int d = 0; d < kConnectivity; d++) {
      int x = curr_index[0] + dire[d][0];
      int y = curr_index[1] + dire[d][1];
      int z = curr_index[2] + dire[d][2];

      int next_index[] = {x, y, z};

      if (outside(next_index, dimensions)) {
        continue;
      }

      if (visited[x][y][z] || inside[x][y][z]) {
        continue;
      }

      int next_code = code(next_index, dimensions);
      visited[x][y][z] = true;
      queue.push(next_code);
    }
  }

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        if (visited[x][y][z]) {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 0.0);
        } else {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 1.0);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kInflateOutputFile);
  writer->SetInputData(field);
  writer->Write();

  delete_3d_array(visited);
  delete_3d_array(inside);

  printf("} inflate_test\n");
}

void deflate_test() {
  printf("deflate_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kBinaryFieldToDeflate);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];

  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  bool ***outside = create_3d_array<bool>(nx, ny, nz);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        double value = field->GetPointData()->GetScalars()
                                            ->GetTuple1(curr_code);

        if (value > 0.5) {
          outside[x][y][z] = false;
        } else {
          outside[x][y][z] = true;
        }
      }
    }
  }

  inflate(dimensions, kNumberOfDeflations, outside);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        if (outside[x][y][z]) {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 0.0);
        } else {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, 1.0);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kDeflateOutputFile);
  writer->SetInputData(field);
  writer->Write();

  delete_3d_array(outside);

  printf("} deflate_test\n");
}

void mask_test() {
  printf("mask_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  reader->SetFileName(kMaskFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> mask =
      vtkSmartPointer<vtkStructuredPoints>::New();
  mask->DeepCopy(reader->GetOutput());

  int dimensions[3];

  field->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);

        double mask_value = mask->GetPointData()->GetScalars()
                                                ->GetTuple1(curr_code);

        if (mask_value < 0.5) {
          field->GetPointData()->GetScalars()->SetTuple1(curr_code, -1.0);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kMaskOutputFile);
  writer->SetInputData(field);
  writer->Write();

  printf("} mask_test\n");
}

void boundary_test() {
  printf("boundary_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kFineLabelFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> fine =
      vtkSmartPointer<vtkStructuredPoints>::New();
  fine->DeepCopy(reader->GetOutput());

  reader->SetFileName(kCoarseLabelFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> coarse =
      vtkSmartPointer<vtkStructuredPoints>::New();
  coarse->DeepCopy(reader->GetOutput());

  int dimensions[3];

  fine->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  std::map<int, int> label_map;
  int num_labels = 0;

  int ***labels = create_3d_array<int>(nx, ny, nz);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);
        double curr_label =
            coarse->GetPointData()->GetScalars()->GetTuple1(curr_code);

        int value = static_cast<int>(curr_label + 0.5);

        if (label_map.find(value) == label_map.end()) {
          label_map[value] = num_labels++;
        }

        labels[x][y][z] = label_map[value];
      }
    }
  }

  bool detected = false;

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        /// DEBUG ///
        // if (labels[x][y][z] != labels[0][0][0]) {
        //   continue;
        // }

        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);
        double label_0 =
            fine->GetPointData()->GetScalars()->GetTuple1(0);
        double curr_label =
            fine->GetPointData()->GetScalars()->GetTuple1(curr_code);

        if (curr_label != label_0) {
          labels[x][y][z] = num_labels;
          detected = true;
        }
      }
    }
  }

  if (detected) {
    num_labels++;
  }

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int curr_index[] = {x, y, z};
        int curr_code = code(curr_index, dimensions);
        coarse->GetPointData()->GetScalars()->SetTuple1(
            curr_code, static_cast<double>(labels[x][y][z]));
      }
    }
  }

  delete_3d_array(labels);

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kBoundaryOutputFile);
  writer->SetInputData(coarse);
  writer->Write();

  printf("} boundary_test\n");
}

void crop_test() {
  printf("crop_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldToCrop);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];
  field->GetDimensions(dimensions);

  double spacing[3], origin[3];
  field->GetSpacing(spacing);
  field->GetOrigin(origin);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int index = (z * ny + y) * nx + x;

        double coord[3];
        coord[0] = origin[0] + spacing[0] * x;
        coord[1] = origin[1] + spacing[1] * y;
        coord[2] = origin[2] + spacing[2] * z;

        if (sqrt(coord[0] * coord[0] + coord[1] * coord[1]) > kCropDistance) {
          field->GetPointData()->GetScalars()->SetTuple1(index, 0.0);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kCropOutputFile);
  writer->SetInputData(field);
  writer->Write();

  printf("} crop_test\n");
}

void symmetricalize_test() {
  printf("symmetricalize_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldToSymmetricalize);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];
  field->GetDimensions(dimensions);

  double spacing[3], origin[3];
  field->GetSpacing(spacing);
  field->GetOrigin(origin);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  for (int z = 0; z < nz; z++) {
    printf("z = %d\n", z);

    std::map<double, double> sum_value;
    std::map<double, int> count;

    for (int x = 0; x < nx; x++) {
      for (int y = 0; y < ny; y++) {
        int index = (z * ny + y) * nx + x;

        double coord[2];
        coord[0] = origin[0] + spacing[0] * x;
        coord[1] = origin[1] + spacing[1] * y;

        double dist = sqrt(coord[0] * coord[0] + coord[1] * coord[1]);
        double value = field->GetPointData()->GetScalars()->GetTuple1(index);

        sum_value[dist] += value;
        count[dist]++;
      }
    }

    std::vector<double> distance_list;
    for (std::map<double, double>::iterator itr = sum_value.begin();
         itr != sum_value.end(); ++itr) {
      distance_list.push_back(itr->first);
    }

    // double tolerance = sqrt(spacing[0] * spacing[0] + spacing[1] * spacing[1]);
    double tolerance = spacing[0];

    for (int x = 0; x < nx; x++) {
      for (int y = 0; y < ny; y++) {
        int index = (z * ny + y) * nx + x;

        double coord[2];
        coord[0] = origin[0] + spacing[0] * x;
        coord[1] = origin[1] + spacing[1] * y;

        double dist = sqrt(coord[0] * coord[0] + coord[1] * coord[1]);

        int lb = lower_bound(distance_list.begin(), distance_list.end(),
                             dist - tolerance) - distance_list.begin();
        int ub = upper_bound(distance_list.begin(), distance_list.end(),
                             dist + tolerance) - distance_list.begin();

        double sum_scalar = 0.0;
        int sum_count = 0;

        for (int p = lb; p < ub; p++) {
          double curr_dist = distance_list[p];
          if (sum_value.find(curr_dist) == sum_value.end()) {
            continue;
          }

          sum_scalar += sum_value[curr_dist];
          sum_count += count[curr_dist];
        }

        /// DEBUG ///
        if (sum_count == 0) {
          printf("dist = %lf\n", dist);
          printf("x, y, z = %d, %d, %d\n", x, y, z);
          printf("lb, ub = %d, %d\n", lb, ub);
          for (int p = lb; p < ub; p++) {
            printf(" %lf", distance_list[p]);
          }
          printf("\n");
          exit(0);
        }

        double average = sum_scalar / sum_count;

        field->GetPointData()->GetScalars()->SetTuple1(index, average);
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kSymmetricalizeOutputFile);
  writer->SetInputData(field);
  writer->Write();

  printf("} symmetricalize_test\n");
}

void modify_test() {
  printf("modify_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kLabelFieldToModify);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  field->DeepCopy(reader->GetOutput());

  int dimensions[3];
  field->GetDimensions(dimensions);

  double spacing[3], origin[3];
  field->GetSpacing(spacing);
  field->GetOrigin(origin);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  double coord_1[] = {0.0, 1.0, 0.9};
  double coord_2[] = {0.0, 1.0, 2.0};

  int y_1 = static_cast<int>((coord_1[1] - origin[1]) / spacing[1]);
  int z_1 = static_cast<int>((coord_1[2] - origin[2]) / spacing[2]);

  int y_2 = static_cast<int>((coord_2[1] - origin[1]) / spacing[1]);
  int z_2 = static_cast<int>((coord_2[2] - origin[2]) / spacing[2]);

  int index_1 = (z_1 * ny + y_1) * nx;
  int index_2 = (z_2 * ny + y_2) * nx;

  double label_1 = field->GetPointData()->GetScalars()->GetTuple1(index_1);
  double label_2 = field->GetPointData()->GetScalars()->GetTuple1(index_2);

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int index = (z * ny + y) * nx + x;
        if (field->GetPointData()->GetScalars()->GetTuple1(index) == label_1) {
          field->GetPointData()->GetScalars()->SetTuple1(index, label_2);
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetFileName(kModifyOutputFile);
  writer->SetInputData(field);
  writer->Write();

  printf("} modify_test\n");
}

void dig_test() {
  printf("dig_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kFineLabelFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> fine_label_field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  fine_label_field->DeepCopy(reader->GetOutput());

  reader->SetFileName(kCoarseLabelFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> coarse_label_field =
      vtkSmartPointer<vtkStructuredPoints>::New();
  coarse_label_field->DeepCopy(reader->GetOutput());

  int dimensions[3];
  coarse_label_field->GetDimensions(dimensions);

  double origin[3], spacing[3];
  coarse_label_field->GetOrigin(origin);
  coarse_label_field->GetSpacing(spacing);

  double points[4][3] = {{0.0, 1.15, 1.66},
                         {0.0, 1.15, 1.56},
                         {0.0, 1.08, 1.48},
                         {0.0, 1.08, 1.42}};

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  int point_indices[4][3];
  for (int p = 0; p < 4; p++) {
    for (int c = 0; c < 3; c++) {
      point_indices[p][c] = static_cast<int>((points[p][c] - origin[c]) / spacing[c]);
    }
  }

  double point_labels[4];

  int first_index;
  for (int p = 0; p < 4; p++) {
    int index = (point_indices[p][2] * ny + point_indices[p][1]) * nx + point_indices[p][0];

    if (!p) {
      first_index = index;
    }

    point_labels[p] = fine_label_field->GetPointData()->GetScalars()->GetTuple1(index);
  }

  int num_labels = 0;
  std::map<double, int> label_map;

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      for (int z = 0; z < nz; z++) {
        int index = (z * ny + y) * nx + x;

        double label = coarse_label_field->GetPointData()->GetScalars()->GetTuple1(index);

        if (label_map.find(label) == label_map.end()) {
          label_map[label] = num_labels++;
        }

        coarse_label_field->GetPointData()->GetScalars()->SetTuple1(index, label_map[label]);
      }
    }
  }

  double original_label = coarse_label_field->GetPointData()->GetScalars()->GetTuple1(first_index);

  for (int z = 0; z < nz; z++) {
    double min_dist = -1.0;
    double max_dist = -1.0;

    double curr_z = origin[2] + spacing[2] * z;
    /// DEBUG ///
    if (curr_z > 1.624) {
      break;
    }

    for (int y = 0; y < ny; y++) {
      int index = (z * ny + y) * nx;
      double curr_label = fine_label_field->GetPointData()->GetScalars()->GetTuple1(index);
      if (curr_label == point_labels[0]
          || curr_label == point_labels[1]
          || curr_label == point_labels[2]
          || curr_label == point_labels[3]) {
        double dist = square(y * spacing[1] + origin[1]);

        if (min_dist < 0.0 || dist < min_dist) {
          min_dist = dist;
        }
        if (max_dist < dist) {
          max_dist = dist;
        }
      }
    }

    if (min_dist < 0.0) {
      continue;
    }

    for (int x = 0; x < nx; x++) {
      for (int y = 0; y < ny; y++) {
        double dist = square(x * spacing[0] + origin[0]) + square(y * spacing[1] + origin[1]);
        if (min_dist <= dist && dist <= max_dist + 0.1) {
          int index = (z * ny + y) * nx + x;

          if (coarse_label_field->GetPointData()->GetScalars()->GetTuple1(index) == original_label) {
            coarse_label_field->GetPointData()->GetScalars()->SetTuple1(index, num_labels);
          }
        }
      }
    }
  }

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetInputData(coarse_label_field);
  writer->SetFileName(kDigOutputFile);
  writer->Write();

  printf("} dig_test\n");
}

// The minimum x is zero, and we want to create a negative x mirror.
void mirror_test() {
  printf("mirror_test {\n");

  vtkSmartPointer<vtkStructuredPointsReader> reader =
      vtkSmartPointer<vtkStructuredPointsReader>::New();
  reader->SetFileName(kScalarFieldFile);
  reader->Update();

  vtkSmartPointer<vtkStructuredPoints> mesh =
      vtkSmartPointer<vtkStructuredPoints>::New();
  mesh->DeepCopy(reader->GetOutput());

  int dimensions[3];
  mesh->GetDimensions(dimensions);

  int nx = dimensions[0];
  int ny = dimensions[1];
  int nz = dimensions[2];

  double spacing[3], origin[3];
  mesh->GetSpacing(spacing);
  mesh->GetOrigin(origin);

  printf("dimensions: %d, %d, %d\n", dimensions[0], dimensions[1], dimensions[2]);
  printf("spacing: %lf, %lf, %lf\n", spacing[0], spacing[1], spacing[2]);
  printf("origin: %lf, %lf, %lf\n", origin[0], origin[1], origin[2]);

  int new_dimensions[3] = {dimensions[0] * 2 - 1,
                           dimensions[1],
                           dimensions[2]};
  double new_origin[3] = {origin[0] - spacing[0] * (nx - 1),
                          origin[1],
                          origin[2]};

  vtkSmartPointer<vtkDoubleArray> scalar_array =
      vtkSmartPointer<vtkDoubleArray>::New();
  scalar_array->SetNumberOfComponents(1);
  scalar_array->SetNumberOfTuples(
      new_dimensions[0] * new_dimensions[1] * new_dimensions[2]);

  for (int x = 0; x < new_dimensions[0]; x++) {
    for (int y = 0; y < new_dimensions[1]; y++) {
      for (int z = 0; z < new_dimensions[2]; z++) {
        int new_index[] = {x, y, z};
        int new_code = code(new_index, new_dimensions);

        int old_index[] = {x, y, z};
        if (x >= nx - 1) {
          old_index[0] = x - nx + 1;
        } else {
          old_index[0] = nx - 1 - x;
        }

        int old_code = code(old_index, dimensions);
        double scalar = mesh->GetPointData()->GetScalars()->GetTuple1(old_code);
        scalar_array->SetTuple1(new_code, scalar);
      }
    }
  }

  vtkSmartPointer<vtkStructuredPoints> new_mesh =
      vtkSmartPointer<vtkStructuredPoints>::New();
  new_mesh->SetDimensions(new_dimensions);
  new_mesh->SetOrigin(new_origin);
  new_mesh->SetSpacing(spacing);
  new_mesh->GetPointData()->SetScalars(scalar_array);

  vtkSmartPointer<vtkStructuredPointsWriter> writer =
      vtkSmartPointer<vtkStructuredPointsWriter>::New();
  writer->SetInputData(new_mesh);
  writer->SetFileName(kMirrorOutputFile);
  writer->Write();

  printf("} mirror_test\n");
}

#define BOUNDARY

int main() {
  // threshold_test();
  // waterproof_test();

#ifndef BOUNDARY
  component_test();
  inflate_test();
  deflate_test();
  mask_test();
#else
  // boundary_test();
#endif

  // Specifically for convective cell.
  // crop_test();
  // symmetricalize_test();
  // modify_test();
  // dig_test();
  mirror_test();

  return 0;
}


text:
class NavbarController {
	constructor($scope, $firebaseArray, userService) {
		'ngInject';

		this.name = 'navbar';
		this.user = userService.getUser();
		this.hint = false;
		userService.onChangeAuth((user) => {
			this.user = user;
			$scope.$apply();
		});
	}
}

export default NavbarController;

redpajama_set_name: RedPajamaGithub


text:
.. _functions:

Functions
---------

Confab provides four basic functions:

 1. It defines a data model where :term:`hosts<host>` belong to one or more
    :term:`environments<environment>` and are assigned to one or more
    :term:`roles<role>`, which can be made up of :term:`components<component>`.

 2. It defines a mechanism for loading configuration data based on a set of
    *defaults* and override values defined per
    :term:`environment`, :term:`host`, :term:`role`, or :term:`component`.

 3. It defines a mechanism for loading Jinja2_ templates for configuration files
    based on a :term:`role` and/or :term:`component`.

 4. It defines Fabric_ tasks to faciliate publishing configuration files
    generated from applying the configuration data to the Jinja2_ templates to
    :term:`hosts<host>`.

Confab's configuration data and :ref:`templates` are expected to be checked in
to version control so that changes to configuration are managed through a
regular versioning and release process.

.. _Fabric: http://docs.fabfile.org/en/1.6/
.. _Jinja2: http://jinja.pocoo.org/docs/


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Zoobots - Code your SMART jungle</title>

 powered by
    Typeform


text:
using Machine.Specifications;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Utils;

namespace PlainElastic.Net.Tests.Builders.Queries
{
    [Subject(typeof(OrFilter<>))]
    class When_complete_OrFilter_built
    {
        Because of = () => result = new OrFilter<FieldsTestClass>()
                                            .And( a => a.Custom("And"))
                                            .Exists(e => e.Custom("Exists"))
                                            .Nested(n => n.Custom("Nested"))
                                            .Range(r => r.Custom("Range"))
                                            .Term(t => t.Custom("Term"))
                                            .Terms(t => t.Custom("Terms"))
                                            .ToString();

        It should_starts_with_or_declaration = () => result.ShouldStartWith("{ 'or': [".AltQuote());

        It should_return_correct_result = () => result.ShouldEqual("{ 'or': [ { 'and': [ And ] },{ 'exists': { Exists } },{ 'nested': { Nested } },{ 'range': { Range } },{ 'term': { Term } },{ 'terms': { Terms } } ] }".AltQuote());

        private static string result;
    }
}


text:
package org.gradle.api.internal.file.copy;

import org.gradle.api.file.DuplicateFileCopyingException;
import org.gradle.api.file.DuplicatesStrategy;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.CopyActionProcessingStreamAction;
import org.gradle.api.tasks.WorkResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

public class DuplicateHandlingCopyActionDecorator implements CopyAction {

    private final static Logger LOGGER = LoggerFactory.getLogger(DuplicateHandlingCopyActionDecorator.class);
    private final CopyAction delegate;

    public DuplicateHandlingCopyActionDecorator(CopyAction delegate) {
        this.delegate = delegate;
    }

    public WorkResult execute(final CopyActionProcessingStream stream) {
        final Set<RelativePath> visitedFiles = new HashSet<RelativePath>();

        return delegate.execute(new CopyActionProcessingStream() {
            public void process(final CopyActionProcessingStreamAction action) {
                stream.process(new CopyActionProcessingStreamAction() {
                    public void processFile(FileCopyDetailsInternal details) {
                        if (!details.isDirectory()) {
                            DuplicatesStrategy strategy = details.getDuplicatesStrategy();

                            if (!visitedFiles.add(details.getRelativePath())) {
                                if (strategy == DuplicatesStrategy.EXCLUDE) {
                                    return;
                                } else if (strategy == DuplicatesStrategy.FAIL) {
                                    throw new DuplicateFileCopyingException(String.format("Encountered duplicate path \"%s\" during copy operation configured with DuplicatesStrategy.FAIL", details.getRelativePath()));
                                } else if (strategy == DuplicatesStrategy.WARN) {
                                    LOGGER.warn("Encountered duplicate path \"{}\" during copy operation configured with DuplicatesStrategy.WARN", details.getRelativePath());
                                }
                            }
                        }

                        action.processFile(details);
                    }
                });
            }
        });
    }
}


text:
title: '`innerRef`'
subtitle: Comment accéder au `ref`
---

Parfois, vous avez besoin d'accéder au
[`ref`](https://facebook.github.io/react/docs/refs-and-the-dom.html)
du composant qui est rendu. Vous pouvez accomplir cela avec
la prop `innerRef`.

C'est une fonction, et si elle est fournie, elle sera appelée avec la référence de l'élément
intérieur.

```interactive {clickToRender: true, summary: 'Un input dans un form'}
const MyInput = glamorous.input({ borderRadius: 4, padding: '4px 8px' });

class MyComponent extends React.Component {
  constructor() {
    this.alertValue = e => {
      e.preventDefault();
      alert(this._inputRef.value);
    };
  }
  render() {
    return (
      <form onSubmit={this.alertValue}>
        <MyInput innerRef={r => (this._inputRef = r)} />
        <glamorous.Button type="submit" marginTop={12} display="block">
          Envoyer
        </glamorous.Button>
      </form>
    );
  }
}

render(<MyComponent />)
```


text:
<!DOCTYPE html>

{% include system_config.Theme+"/public/head.html" %}

{% include system_config.Theme+"/public/menu.html" %}

            {% for page_info in page_list %}

{{ page_info.time }}

                                {{ page_info.title }}

                            {{ page_info.excerpt }}

                        {% if "image" in page_info %}

                        {% endif %}

Read more

            {% endfor %}

                    {% if now_page != 1 %}
                         Previous
                    {% endif %}

                    {% if now_page != page_row and page_row !=1 %}
                        Next

                    {% endif %}

{% include system_config.Theme+"/public/foot.html" %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerilogWeb.Classic
{
    /// <summary>
    /// Describes options for logging form request data
    /// </summary>
    public enum LogPostedFormDataOption
    {
        /// <summary>
        /// Posted form values are never logged
        /// </summary>
        Never,
        /// <summary>
        /// Posted form values are always logged
        /// </summary>
        Always,
        /// <summary>
        /// Posted form values are logged if Response.StatusCode >= 500
        /// </summary>
        OnlyOnError,
        /// <summary>
        /// Uses the custom predicate defined by <see cref="ApplicationLifecycleModule.ShouldLogPostedFormData"/>
        /// to determine if posted form values are logged
        /// </summary>
        OnMatch
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using Google.GData.Client;
using Google.GData.Extensions;

namespace PicasaWebSync
{
	public class GDataAuthenticator
	{
		public GDataRequestFactory requestFactory { get; set; }

		public GDataAuthenticator (string accessToken)
		{
			requestFactory = new GDataRequestFactory ("PicasaWebSync");
			requestFactory.CustomHeaders.Add (string.Format ("Authorization: Bearer {0}", accessToken));
		}
	}
}


text:
<?php
/**
 * Portuguese language file
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Flávio Roberto Santos <flavio.barata@gmail.com>
 */

// custom language strings for the plugin
$lang['readmore']   = '→ leia mais...';

//Setup VIM: ex: et ts=2 :


text:
//
//  $Id: PGPostgresError.m 3837 2012-09-09 12:25:03Z stuart02 $
//
//  PGPostgresError.m
//  PostgresKit
//
//  Created by Stuart Connolly (stuconnolly.com) on September 3, 2012.
//  Copyright (c) 2012 Stuart Connolly. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.

#import "PGPostgresError.h"
#import "PGPostgresException.h"

@interface PGPostgresError ()

- (void)_extractErrorDetailsFromResult:(const PGresult *)result;
- (NSString *)_extractErrorField:(int)field fromResult:(const PGresult *)result;

@end

@implementation PGPostgresError

@synthesize errorSeverity = _errorSeverity;
@synthesize errorStateCode = _errorStateCode;
@synthesize errorPrimaryMessage = _errorPrimaryMessage;
@synthesize errorDetailMessage = _errorDetailMessage;
@synthesize errorMessageHint = _errorMessageHint;
@synthesize errorStatementPosition = _errorStatementPosition;

#pragma mark -

- (id)init
{
	[PGPostgresException raise:NSInternalInconsistencyException
						 reason:@"%@ shouldn't be init'd directly; use initWithResult: instead.", [self className]];

	return nil;
}

- (id)initWithResult:(const void *)result
{
	if ((self = [super init])) {

		_errorSeverity = nil;
		_errorStateCode = nil;
		_errorPrimaryMessage = nil;
		_errorDetailMessage = nil;
		_errorMessageHint = nil;
		_errorStatementPosition = -1;

		if (result) [self _extractErrorDetailsFromResult:(const PGresult *)result];
	}

	return self;
}

- (NSString *)description
{
	return [NSString stringWithFormat:@"<%@: Sev %@ (%@): %@>", [self className], _errorSeverity, _errorStateCode, _errorPrimaryMessage];
}

#pragma mark -
#pragma mark Private API

/**
 * Extracts all the error information from the supplied result.
 *
 * @param result The Postgres result to extract the information from.
 */
- (void)_extractErrorDetailsFromResult:(const PGresult *)result
{
	// Note that we don't expose all the fields that are available.
	// The ones we don't mostly include information internal to Postgres
	// that generally isn't useful to end users.
	_errorSeverity = [self _extractErrorField:PG_DIAG_SEVERITY fromResult:result];
	_errorStateCode = [self _extractErrorField:PG_DIAG_SQLSTATE fromResult:result];
	_errorPrimaryMessage = [self _extractErrorField:PG_DIAG_MESSAGE_PRIMARY fromResult:result];
	_errorDetailMessage = [self _extractErrorField:PG_DIAG_MESSAGE_DETAIL fromResult:result];
	_errorMessageHint = [self _extractErrorField:PG_DIAG_MESSAGE_HINT fromResult:result];
	_errorStatementPosition = [[self _extractErrorField:PG_DIAG_STATEMENT_POSITION fromResult:result] integerValue];
}

/**
 * Extracts the supplied error field from the supplied Postgres result.
 *
 * @param field The error field to extract.
 * @param result The Postgres result to extract the field from.
 *
 * @return A string representing the error value. The caller is responsible for freeing the associated memory.
 */
- (NSString *)_extractErrorField:(int)field fromResult:(const PGresult *)result
{
	const char *error = PQresultErrorField(result, field);

	return error ? [[[NSString alloc] initWithUTF8String:error] autorelease] : nil;
}

#pragma mark -

- (void)dealloc
{
	if (_errorSeverity) [_errorSeverity release], _errorSeverity = nil;
	if (_errorStateCode) [_errorStateCode release], _errorStateCode = nil;
	if (_errorPrimaryMessage) [_errorPrimaryMessage release], _errorPrimaryMessage = nil;
	if (_errorDetailMessage) [_errorDetailMessage release], _errorDetailMessage = nil;
	if (_errorMessageHint) [_errorMessageHint release], _errorMessageHint = nil;

	[super dealloc];
}

@end


text:
<?php

namespace Odysseus\AdminBundle\Service;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Routing\Router;

class Menu {

    private $router;

    public function __construct(Router $router) {
        $this->router = $router;
    }

    private function eqUrl($cUrl, $url) {
        return (strpos($cUrl, $url) === 0);
    }

    private function eqRoute($cUrl, $route) {
        return $this->eqUrl($cUrl, $this->router->generate($route));
    }

    public function getValues(Request $request) {
        $cUrl = $request->getUri();
        $cRoute = $request->get('_route');

        return array(
            (Object) array(
                'label' => 'Tableau de bord',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_dashboard'),
                'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                'items' => array()
            ),
            (Object) array(
                'label' => 'Articles',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_article'),
                'isActive' => $this->eqRoute($cUrl, 'odysseus_admin_article'),
                'items' => array(
                    (Object) array(
                        'label' => 'Voir les articles',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_article'),
                        'isActive' => ($cRoute == 'odysseus_admin_article'),
                        'items' => array()
                    ),
                    (Object) array(
                        'label' => 'Voir les catégories',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_category'),
                        'isActive' => ($cRoute == 'odysseus_admin_category'),
                        'items' => array()
                    ),
                    (Object) array('separator' => true),
                    (Object) array(
                        'label' => 'Statistique',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_dashboard'),
                        'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                        'items' => array()
                    ),
                )
            ),
            (Object) array(
                'label' => 'Commandes',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_order'),
                'isActive' => $this->eqRoute($cUrl, 'odysseus_admin_order'),
                'items' => array(
                    (Object) array(
                        'label' => 'Voir les commandes',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_order'),
                        'isActive' => ($cRoute == 'odysseus_admin_order'),
                        'items' => array()
                    ),
                    (Object) array('separator' => true),
                    (Object) array(
                        'label' => 'Statistique',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_dashboard'),
                        'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                        'items' => array()
                    ),
                )
            ),
            (Object) array(
                'label' => 'Utilisateurs',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_user'),
                'isActive' => $this->eqRoute($cUrl, 'odysseus_admin_user'),
                'items' => array(
                    (Object) array(
                        'label' => 'Voir les utilisateurs',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_user'),
                        'isActive' => ($cRoute == 'odysseus_admin_user'),
                        'items' => array()
                    ),
                    (Object) array(
                        'label' => 'Nouvel utilisateur',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_user_create'),
                        'isActive' => ($cRoute == 'odysseus_admin_user_create'),
                        'items' => array()
                    ),
                    (Object) array('separator' => true),
                    (Object) array(
                        'label' => 'Statistique',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_dashboard'),
                        'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                        'items' => array()
                    ),
                )
            ),
            (Object) array(
                'label' => 'Pages',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_page'),
                'isActive' => $this->eqRoute($cUrl, 'odysseus_admin_page'),
                'items' => array(
                    (Object) array(
                        'label' => 'Voir les pages',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_page'),
                        'isActive' => ($cRoute == 'odysseus_admin_page'),
                        'items' => array()
                    ),
                    (Object) array(
                        'label' => 'Nouvelle page',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_dashboard'),
                        'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                        'items' => array()
                    ),
                    (Object) array('separator' => true),
                    (Object) array(
                        'label' => 'Statistique',
                        'icon' => null,
                        'url' => $this->router->generate('odysseus_admin_dashboard'),
                        'isActive' => ($cRoute == 'odysseus_admin_dashboard'),
                        'items' => array()
                    ),
                )
            ),
            (Object) array(
                'label' => 'Réglages',
                'icon' => '',
                'url' => $this->router->generate('odysseus_admin_dashboard'),
                'isActive' => false,
                'items' => array()
            )
        );
    }

}


text:
<?php

namespace mako\chrono\stopwatch;

use function count;
use function end;
use function microtime;

/**
 * Stopwatch.
 */
class Stopwatch
{
	/**
	 * Laps.
	 *
	 * @var array
	 */
	protected $laps = [];

	/**
	 * Returns the laps.
	 *
	 * @return array
	 */
	public function getLaps(): array
	{
		return $this->laps;
	}

	/**
	 * Returns the number of laps.
	 *
	 * @return int
	 */
	public function getLapCount(): int
	{
		return count($this->laps);
	}

	/**
	 * Returns TRUE if the stopwatch is still running and FALSE if not.
	 *
	 * @return bool
	 */
	public function isRunning(): bool
	{
		return end($this->laps)->isRunning();
	}

	/**
	 * Starts the stopwatch.
	 *
	 * @return \mako\chrono\stopwatch\Stopwatch
	 */
	public function start(): Stopwatch
	{
		$this->laps[] = (new Lap)->start();

		return $this;
	}

	/**
	 * Starts a new lap and returns the time of the previous lap.
	 *
	 * @return float
	 */
	public function lap(): float
	{
		$last = end($this->laps);

		$time = $last->stop();

		$this->start();

		return $time;
	}

	/**
	 * Get elapsed time.
	 *
	 * @return float
	 */
	public function getElapsedTime(): float
	{
		$last = end($this->laps);

		return ($last->isRunning() ? microtime(true) : $last->getStopTime()) - $this->laps[0]->getStartTime();
	}

	/**
	 * Stops the timer and returns the elapsed time.
	 *
	 * @return float
	 */
	public function stop(): float
	{
		$last = end($this->laps);

		$last->stop();

		return $last->getStopTime() - $this->laps[0]->getStartTime();
	}
}


text: git checkout "$1+" && git merge --no-ff develop && git push && git tag -f $1 && git push --tags -f && git checkout develop


text:
"""
Module providing easy API for working with remote files and folders.
"""

from __future__ import with_statement

import hashlib
import tempfile
import re
import os
from StringIO import StringIO

from fabric.api import *

def exists(path, use_sudo=False, verbose=False):
    """
    Return True if given path exists on the current remote host.

    If ``use_sudo`` is True, will use `sudo` instead of `run`.

    `exists` will, by default, hide all output (including the run line, stdout,
    stderr and any warning resulting from the file not existing) in order to
    avoid cluttering output. You may specify ``verbose=True`` to change this
    behavior.
    """
    func = use_sudo and sudo or run
    cmd = 'test -e "$(echo %s)"' % path
    # If verbose, run normally
    if verbose:
        with settings(warn_only=True):
            return not func(cmd).failed
    # Otherwise, be quiet
    with settings(hide('everything'), warn_only=True):
        return not func(cmd).failed

def first(*args, **kwargs):
    """
    Given one or more file paths, returns first one found, or None if none
    exist. May specify ``use_sudo`` and ``verbose`` which are passed to `exists`.
    """
    for directory in args:
        if exists(directory, **kwargs):
            return directory

def upload_template(filename, destination, context=None, use_jinja=False,
    template_dir=None, use_sudo=False, backup=True, mirror_local_mode=False,
    mode=None):
    """
    Render and upload a template text file to a remote host.

    ``filename`` should be the path to a text file, which may contain `Python
    string interpolation formatting
    <http://docs.python.org/release/2.5.4/lib/typesseq-strings.html>`_ and will
    be rendered with the given context dictionary ``context`` (if given.)

    Alternately, if ``use_jinja`` is set to True and you have the Jinja2
    templating library available, Jinja will be used to render the template
    instead. Templates will be loaded from the invoking user's current working
    directory by default, or from ``template_dir`` if given.

    The resulting rendered file will be uploaded to the remote file path
    ``destination``.  If the destination file already exists, it will be
    renamed with a ``.bak`` extension unless ``backup=False`` is specified.

    By default, the file will be copied to ``destination`` as the logged-in
    user; specify ``use_sudo=True`` to use `sudo` instead.

    The ``mirror_local_mode`` and ``mode`` kwargs are passed directly to an
    internal `~fabric.operations.put` call; please see its documentation for
    details on these two options.

    .. versionchanged:: 1.1
        Added the ``backup``, ``mirror_local_mode`` and ``mode`` kwargs.
    """
    func = use_sudo and sudo or run
    # Normalize destination to be an actual filename, due to using StringIO
    with settings(hide('everything'), warn_only=True):
        if func('test -d %s' % destination).succeeded:
            sep = "" if destination.endswith('/') else "/"
            destination += sep + os.path.basename(filename)

    # Use mode kwarg to implement mirror_local_mode, again due to using
    # StringIO
    if mirror_local_mode and mode is None:
        mode = os.stat(filename).st_mode
        # To prevent put() from trying to do this
        # logic itself
        mirror_local_mode = False

    # Process template
    text = None
    if use_jinja:
        try:
            from jinja2 import Environment, FileSystemLoader
            jenv = Environment(loader=FileSystemLoader(template_dir or '.'))
            text = jenv.get_template(filename).render(**context or {})
        except ImportError:
            import traceback
            tb = traceback.format_exc()
            abort(tb + "\nUnable to import Jinja2 -- see above.")
    else:
        with open(filename) as inputfile:
            text = inputfile.read()
        if context:
            text = text % context

    # Back up original file
    if backup and exists(destination):
        func("cp %s{,.bak}" % destination)

    # Upload the file.
    put(
        local_path=StringIO(text),
        remote_path=destination,
        use_sudo=use_sudo,
        mirror_local_mode=mirror_local_mode,
        mode=mode
    )

def sed(filename, before, after, limit='', use_sudo=False, backup='.bak',
    flags=''):
    """
    Run a search-and-replace on ``filename`` with given regex patterns.

    Equivalent to ``sed -i<backup> -r -e "/<limit>/ s/<before>/<after>/<flags>g
    <filename>"``.

    For convenience, ``before`` and ``after`` will automatically escape forward
    slashes, single quotes and parentheses for you, so you don't need to
    specify e.g.  ``http:\/\/foo\.com``, instead just using ``http://foo\.com``
    is fine.

    If ``use_sudo`` is True, will use `sudo` instead of `run`.

    `sed` will pass ``shell=False`` to `run`/`sudo`, in order to avoid problems
    with many nested levels of quotes and backslashes.

    Other options may be specified with sed-compatible regex flags -- for
    example, to make the search and replace case insensitive, specify
    ``flags="i"``. The ``g`` flag is always specified regardless, so you do not
    need to remember to include it when overriding this parameter.

    .. versionadded:: 1.1
        The ``flags`` parameter.
    """
    func = use_sudo and sudo or run
    # Characters to be escaped in both
    for char in "/'":
        before = before.replace(char, r'\%s' % char)
        after = after.replace(char, r'\%s' % char)
    # Characters to be escaped in replacement only (they're useful in regexen
    # in the 'before' part)
    for char in "()":
        after = after.replace(char, r'\%s' % char)
    if limit:
        limit = r'/%s/ ' % limit
    # Test the OS because of differences between sed versions

    with hide('running', 'stdout'):
        platform = run("uname")
    if platform in ('NetBSD', 'OpenBSD', 'QNX'):
        # Attempt to protect against failures/collisions
        hasher = hashlib.sha1()
        hasher.update(env.host_string)
        hasher.update(filename)
        tmp = "/tmp/%s" % hasher.hexdigest()
        # Use temp file to work around lack of -i
        expr = r"""cp -p %(filename)s %(tmp)s \
&& sed -r -e '%(limit)ss/%(before)s/%(after)s/%(flags)sg' %(filename)s > %(tmp)s \
&& cp -p %(filename)s %(filename)s%(backup)s \
&& mv %(tmp)s %(filename)s"""
        command = expr % locals()
    else:
        expr = r"sed -i%s -r -e '%ss/%s/%s/%sg' %s"
        command = expr % (backup, limit, before, after, flags, filename)
    return func(command, shell=False)

def uncomment(filename, regex, use_sudo=False, char='#', backup='.bak'):
    """
    Attempt to uncomment all lines in ``filename`` matching ``regex``.

    The default comment delimiter is `#` and may be overridden by the ``char``
    argument.

    This function uses the `sed` function, and will accept the same
    ``use_sudo`` and ``backup`` keyword arguments that `sed` does.

    `uncomment` will remove a single whitespace character following the comment
    character, if it exists, but will preserve all preceding whitespace.  For
    example, ``# foo`` would become ``foo`` (the single space is stripped) but
    ``    # foo`` would become ``    foo`` (the single space is still stripped,
    but the preceding 4 spaces are not.)
    """
    return sed(
        filename,
        before=r'^([[:space:]]*)%s[[:space:]]?' % char,
        after=r'\1',
        limit=regex,
        use_sudo=use_sudo,
        backup=backup
    )

def comment(filename, regex, use_sudo=False, char='#', backup='.bak'):
    """
    Attempt to comment out all lines in ``filename`` matching ``regex``.

    The default commenting character is `#` and may be overridden by the
    ``char`` argument.

    This function uses the `sed` function, and will accept the same
    ``use_sudo`` and ``backup`` keyword arguments that `sed` does.

    `comment` will prepend the comment character to the beginning of the line,
    so that lines end up looking like so::

        this line is uncommented
        #this line is commented
        #   this line is indented and commented

    In other words, comment characters will not "follow" indentation as they
    sometimes do when inserted by hand. Neither will they have a trailing space
    unless you specify e.g. ``char='# '``.

    .. note::

        In order to preserve the line being commented out, this function will
        wrap your ``regex`` argument in parentheses, so you don't need to. It
        will ensure that any preceding/trailing ``^`` or ``$`` characters are
        correctly moved outside the parentheses. For example, calling
        ``comment(filename, r'^foo$')`` will result in a `sed` call with the
        "before" regex of ``r'^(foo)$'`` (and the "after" regex, naturally, of
        ``r'#\\1'``.)
    """
    carot, dollar = '', ''
    if regex.startswith('^'):
        carot = '^'
        regex = regex[1:]
    if regex.endswith('$'):
        dollar = '$'
        regex = regex[:-1]
    regex = "%s(%s)%s" % (carot, regex, dollar)
    return sed(
        filename,
        before=regex,
        after=r'%s\1' % char,
        use_sudo=use_sudo,
        backup=backup
    )

def contains(filename, text, exact=False, use_sudo=False, escape=True):
    """
    Return True if ``filename`` contains ``text`` (which may be a regex.)

    By default, this function will consider a partial line match (i.e. where
    ``text`` only makes up part of the line it's on). Specify ``exact=True`` to
    change this behavior so that only a line containing exactly ``text``
    results in a True return value.

    This function leverages ``egrep`` on the remote end (so it may not follow
    Python regular expression syntax perfectly), and skips the usual outer
    ``env.shell`` wrapper that most commands execute with.

    If ``use_sudo`` is True, will use `sudo` instead of `run`.

    If ``escape`` is False, no extra regular expression related escaping is
    performed (this includes overriding ``exact`` so that no ``^``/``$`` is
    added.)

    .. versionchanged:: 1.0
        Swapped the order of the ``filename`` and ``text`` arguments to be
        consistent with other functions in this module.
    .. versionchanged:: 1.4
        Updated the regular expression related escaping to try and solve
        various corner cases.
    .. versionchanged:: 1.4
        Added ``escape`` keyword argument.
    """
    func = use_sudo and sudo or run
    if escape:
        text = _escape_for_regex(text)
        if exact:
            text = "^%s$" % text
    with settings(hide('everything'), warn_only=True):
        egrep_cmd = 'egrep "%s" "%s"' % (text, filename)
        return func(egrep_cmd, shell=False).succeeded

def append(filename, text, use_sudo=False, partial=False, escape=True):
    """
    Append string (or list of strings) ``text`` to ``filename``.

    When a list is given, each string inside is handled independently (but in
    the order given.)

    If ``text`` is already found in ``filename``, the append is not run, and
    None is returned immediately. Otherwise, the given text is appended to the
    end of the given ``filename`` via e.g. ``echo '$text' >> $filename``.

    The test for whether ``text`` already exists defaults to a full line match,
    e.g. ``^<text>$``, as this seems to be the most sensible approach for the
    "append lines to a file" use case. You may override this and force partial
    searching (e.g. ``^<text>``) by specifying ``partial=True``.

    Because ``text`` is single-quoted, single quotes will be transparently
    backslash-escaped. This can be disabled with ``escape=False``.

    If ``use_sudo`` is True, will use `sudo` instead of `run`.

    .. versionchanged:: 0.9.1
        Added the ``partial`` keyword argument.
    .. versionchanged:: 1.0
        Swapped the order of the ``filename`` and ``text`` arguments to be
        consistent with other functions in this module.
    .. versionchanged:: 1.0
        Changed default value of ``partial`` kwarg to be ``False``.
    .. versionchanged:: 1.4
        Updated the regular expression related escaping to try and solve
        various corner cases.
    """
    func = use_sudo and sudo or run
    # Normalize non-list input to be a list
    if isinstance(text, basestring):
        text = [text]
    for line in text:
        regex = '^' + _escape_for_regex(line)  + ('' if partial else '$')
        if (exists(filename, use_sudo=use_sudo) and line
            and contains(filename, regex, use_sudo=use_sudo, escape=False)):
            continue
        line = line.replace("'", r"'\\''") if escape else line
        func("echo '%s' >> %s" % (line, filename))

def _escape_for_regex(text):
    """Escape ``text`` to allow literal matching using egrep"""
    regex = re.escape(text)
    # Seems like double escaping is needed for \
    regex = regex.replace('\\\\', '\\\\\\')
    # Triple-escaping seems to be required for $ signs
    regex = regex.replace(r'\$', r'\\\$')
    # Whereas single quotes should not be escaped
    regex = regex.replace(r"\'", "'")
    return regex


text:
<?php

class AdminStartHandler {

	private $modelName = "";

	function __construct() {

		$this->modelName = 'admin/start';

		if( !defined('ADMIN') ) {

			header('HTTP/1.0 404 Not Found');
			echo "Not found";
			exit;

		}
	}

	function get() {

		if( defined('ADMIN') ) {

			$appActions = new Actions();
			$twig = $appActions->Twigloader();
			$appActions->renderViewStatic($twig, $this->modelName);

		}

	}

	function post() {

		if( defined('ADMIN') ) {

			$varsModel =(isset($_POST['model'])) ? $_POST['model'] : false;
			$varsPage =(isset($_POST['pagename'])) ? $_POST['pagename'] : false;

			$app = new App;
			$response = $app->createPage($varsModel,$varsPage);
			if($response == 'error') { $app->setFlash('Page exsiste deja'); }
			else { $app->setFlash('Page '.$varsPage.' crée'); }
			$this->get();

		}

	}

}


text:
@interface MAEventDescVC ()

@end

@implementation MAEventDescVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.titleView = [Utility lblTitleNavBar:@"Event detail"];

    ArrEvtData=[[NSMutableArray alloc] init];

}
-(void)viewWillAppear:(BOOL)animated
{
    [self callEventDetailAPI];
}

-(void)locationData:(NSString *)value
{
    NSLog(@"eventId%@",value);
    _eventId =value;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark Nav Button Method
#pragma mark
-(void)leftBtn
{
    if ([self.tabBarController.navigationController.parentViewController respondsToSelector:@selector(revealGesture:)] && [self.tabBarController.navigationController.parentViewController respondsToSelector:@selector(revealToggle:)])
    {

        [self.tabBarController.navigationController.parentViewController performSelector:@selector(revealToggle:) withObject:nil afterDelay:0.0];

    }
}
-(void)callEventDetailAPI
{

    [ArrEvtData removeAllObjects];
    NSDictionary* userInfo = @{
                               @"eventId":_eventId
                               };

    [ApplicationDelegate show_LoadingIndicator];
    [API EventDetailWithInfo:[userInfo mutableCopy] completionHandler:^(NSDictionary *responseDict) {
        NSLog(@"responseDict--%@",responseDict);

        if([[responseDict valueForKey:@"result"] intValue] == 1)
        {

            [ArrEvtData addObject:[responseDict valueForKey:@"data"]];
            MALog(@"ArrGrpData--%@",ArrEvtData);

        }else
        {
            [ApplicationDelegate showAlert:ErrorStr];
        }
        if ([ApplicationDelegate isHudShown]) {
            [ApplicationDelegate hide_LoadingIndicator];
        }
         [tblEvtDetail reloadData];
    }];
}

#pragma mark
#pragma mark Map View Delegate  Method
#pragma mark
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    MKPinAnnotationView *pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                                             reuseIdentifier:@"current"];
    UIImageView *houseIconView = [[UIImageView alloc] init];
    NSURL *ImageURL = [NSURL URLWithString:[[ArrEvtData objectAtIndex:0] valueForKey:@"image"]];
    [houseIconView setFrame:CGRectMake(0, 0, 30, 30)];
    [houseIconView sd_setImageWithURL:ImageURL placeholderImage:[UIImage imageNamed:@"placeholderImage.png"] options:SDWebImageRetryFailed];
    pinAnnotationView.leftCalloutAccessoryView = houseIconView;
    pinAnnotationView.animatesDrop = YES;
    pinAnnotationView.pinColor = MKPinAnnotationColorRed;
    pinAnnotationView.canShowCallout = YES;
    return pinAnnotationView;
}
#pragma mark
#pragma mark Table View DataSource/Delegates
#pragma mark

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    if(section ==1)
        return 7.0f;
    else
        return 0.0f;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 512.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Celleventdesc";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    UILabel* txtName;
    UILabel* txtType;
    UILabel* txtDate;
    UILabel* txtfollower;
    UIButton* btnFollow;
    UIButton* btnEdit;
    btnFollow = (UIButton *)[cell.contentView viewWithTag:904];
    btnEdit = (UIButton *)[cell.contentView viewWithTag:905];

    UITextView * lblDesc=(UITextView *)[cell.contentView viewWithTag:1031];
    UIImageView *profileImageVw = (UIImageView *)[cell.contentView  viewWithTag:906];
    txtName = (UILabel *)[cell.contentView viewWithTag:901];
    txtDate = (UILabel *)[cell.contentView viewWithTag:1041];
    txtType = (UILabel *)[cell.contentView viewWithTag:902];
    txtfollower = (UILabel *)[cell.contentView viewWithTag:903];

    if([ArrEvtData count]>0){

        [profileImageVw sd_setImageWithURL:[NSURL URLWithString:[[ArrEvtData objectAtIndex:0] valueForKey:@"image"]] placeholderImage:CoverPlaceholder options:SDWebImageRetryFailed];

        if(txtName)
        {
            txtName.text=[[ArrEvtData objectAtIndex:0]  valueForKey:@"name"];
        }
        if(txtType)
        {
            txtType.text=[[ArrEvtData objectAtIndex:0] valueForKey:@"type"];
        }
        if(txtDate)
        {
            txtDate.text=[[ArrEvtData objectAtIndex:0] valueForKey:@"date"];
        }
        if(txtfollower)
        {
            txtfollower.text=[[ArrEvtData objectAtIndex:indexPath.row] valueForKey:@"followers"];
        }
        if(lblDesc){
            lblDesc.text=[[ArrEvtData objectAtIndex:0] valueForKey:@"description"];
            lblDesc.layer.borderColor = [UIColor blackColor].CGColor;
            lblDesc.layer.borderWidth = 1.0f;
        }
        if(btnFollow && btnEdit)
        {
            if ([[NSString stringWithFormat:@"%@",[[ArrEvtData objectAtIndex:indexPath.row] valueForKey:@"evnt_creator_id"]] isEqualToString:[NSString stringWithFormat:@"%@",[UserDefaults valueForKey:@"user_id"]]])

            {
                btnFollow.hidden=YES;
                btnEdit.hidden=NO;
            }
            else
            {
                btnFollow.hidden=NO;
                btnFollow = (UIButton *)[cell.contentView viewWithTag:904];
                 [btnFollow setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

                NSUInteger index = [[[[ArrEvtData objectAtIndex:0] valueForKey:@"followers_arr"] valueForKey:@"id"] indexOfObject:[UserDefaults valueForKey:@"user_id"]];
                if (index != NSNotFound) {

                    [btnFollow setTitle:@"Following" forState:UIControlStateNormal];
                    [btnFollow  setUserInteractionEnabled:NO];
                }
                else{
                    [btnFollow setTitle:@"Follow" forState:UIControlStateNormal];
                    [btnFollow  setUserInteractionEnabled:YES];
                }

//
                if (btnFollow) {
                    [btnFollow addTarget:self action:@selector(btnPressed_followed:) forControlEvents:UIControlEventTouchUpInside];
                }

                btnEdit.hidden=YES;
            }

        }
        MKMapView *mapView=(MKMapView *)[cell.contentView viewWithTag:1021];
        CLLocationCoordinate2D zoomLocation;
        zoomLocation.latitude
        = [[[ArrEvtData objectAtIndex:0] valueForKey:@"lat"] doubleValue];

        zoomLocation.longitude
        = [[[ArrEvtData objectAtIndex:0] valueForKey:@"lng"] doubleValue];

        MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
        [mapView setRegion:viewRegion animated:YES];

        MALog(@"%@",[[ArrEvtData objectAtIndex:0] valueForKey:@"name"]);
        MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
        annotationPoint.coordinate = zoomLocation;
        annotationPoint.title = [[ArrEvtData objectAtIndex:0] valueForKey:@"name"];
        [mapView addAnnotation:annotationPoint];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (IBAction)btnPressed_editEvent:(id)sender {
    MAAddEventVC *objEvent=VCWithIdentifier(@"MAAddEventVC");
    objEvent.arrEditData=ArrEvtData;
    [self.navigationController pushViewController:objEvent animated:YES];
}
// ACCEPTED PARMS: event_id,follower_id,type

- (IBAction)btnPressed_followed:(id)sender {

    NSDictionary* userInfo = @{@"follower_id":[UserDefaults valueForKey:@"user_id"],
                               @"id":_eventId,
                               @"type":@"follow",
                               @"post_type":@"event"
                               };
     [ApplicationDelegate show_LoadingIndicator];
        [API followEventWithInfo:[userInfo mutableCopy] completionHandler:^(NSDictionary *responseDict) {
            NSLog(@"responseDict--%@",responseDict);
            if([[responseDict valueForKey:@"result"] intValue] == 1)
            {
                [self callEventDetailAPI];
                [ApplicationDelegate showAlert:@"You have successfully follow Event"];
            }
            else
            {
                [ApplicationDelegate showAlert:ErrorStr];
            }
            if ([ApplicationDelegate isHudShown]) {
                [ApplicationDelegate hide_LoadingIndicator];
            }
        }];
}
@end


text:
module DPL
  class Provider
    module Heroku
      class Anvil < Git
        HEROKU_BUILDPACKS = ['ruby', 'nodejs', 'clojure', 'python', 'java', 'gradle', 'grails', 'scala', 'play']
        HEROKU_BUILDPACK_PREFIX = "https://github.com/heroku/heroku-buildpack-"
        requires 'anvil-cli', :load => 'anvil/engine'
        requires 'excon' # comes with heroku
        requires 'json'

        def api
          raise Error, 'anvil deploy strategy only works with api_key' unless options[:api_key]
          super
        end

        def needs_key?
          false
        end

        def push_app
          sha = ENV['TRAVIS_COMMIT'] || `git rev-parse HEAD`.strip
          response = Excon.post release_url,
            :body    => { "slug_url" => slug_url, "description" => "Deploy #{sha} via Travis CI" }.to_json,
            :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }

          print "\nDeploying slug "
          while response.status == 202
            location = response.headers['Location']
            response = Excon.get("https://:#{option(:api_key)}@cisaurus.heroku.com#{location}")
            sleep(1)
            print '.'
          end

          if response.status.between? 200, 299
            puts " success!"
          else
            raise Error, "deploy failed, anvil response: #{response.body}"
          end
        end

        def slug_url
          @slug_url ||= begin
            ::Anvil.headers["X-Heroku-User"] = user
            ::Anvil.headers["X-Heroku-App"]  = option(:app)
            if HEROKU_BUILDPACKS.include? options[:buildpack]
              options[:buildpack] = HEROKU_BUILDPACK_PREFIX + options[:buildpack]
            end
            ::Anvil::Engine.build ".", :buildpack => options[:buildpack]
          rescue ::Anvil::Builder::BuildError => e
            raise Error, "deploy failed, anvil build error: #{e.message}"
          end
        end

        def release_url
          "https://:#{option(:api_key)}@cisaurus.heroku.com/v1/apps/#{option(:app)}/release"
        end
      end
    end
  end
end


text:
package com.nn.math.activations

import javax.swing.AbstractAction

import com.nn.Neuron

import scala.collection.mutable.ArrayBuffer

/**
 * Creates a bipolar sigmoid function for classifications tasks between -1 and 1
 * Created by george on 12/7/14.
 */
class BipolarSigmoidFunction extends ActivationFunction{

  /**
   * sigmoid step function activation
   * @param x
   * @param w
   * @return
   */
  def activation(x : Vector[Double] , w : Vector[Double]) : Double={
    // perform dot product between input and weights
    require(x.size == w.size)
    val dot = (for ((a, b) <- x zip w) yield a * b) sum
    val act = (1.0)/(1-Math.pow(Math.E,-dot))
    return act
  }
}


text:
package org.activiti.engine.test.assertions;

import org.activiti.engine.test.assertions.helpers.Failure;
import org.activiti.engine.test.assertions.helpers.ProcessAssertTestCase;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.test.Deployment;
import org.activiti.engine.test.ActivitiRule;
import org.junit.Rule;
import org.junit.Test;

/**
 * @author Martin Schimak <martin.schimak@plexiti.com>
 */
public class ProcessInstanceAssertIsNotEndedTest extends ProcessAssertTestCase {

  @Rule
  public ActivitiRule ActivitiRule = new ActivitiRule();

  @Test
  @Deployment(resources = {
    "ProcessInstanceAssert-isEnded.bpmn"
  })
  public void testIsNotEnded_Success() {
    // When
    ProcessInstance processInstance = ProcessEngineTests.runtimeService().startProcessInstanceByKey(
      "ProcessInstanceAssert-isEnded"
    );
    // Then
    ProcessEngineAssertions.assertThat(processInstance).isNotEnded();
  }

  @Test
  @Deployment(resources = {
    "ProcessInstanceAssert-isEnded.bpmn"
  })
  public void testIsNotEnded_Failure() {
    // Given
    final ProcessInstance processInstance = ProcessEngineTests.runtimeService().startProcessInstanceByKey(
      "ProcessInstanceAssert-isEnded"
    );
    // When
    ProcessEngineTests.complete(ProcessEngineTests.taskQuery().singleResult());
    // Then
    expect(new Failure() {
      @Override
      public void when() {
        ProcessEngineAssertions.assertThat(processInstance).isNotEnded();
      }
    });
  }

}


text:
package com.anttaylor.common.utils;

import android.app.Application;
import android.content.Context;
import android.os.Handler;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.yolanda.nohttp.Logger;
import com.yolanda.nohttp.NoHttp;

/**
 * @ClassName: GooglePlayApplication
 * @Description: 自定义application,进行全局初始化
 * @author Taylor
 * @date 2016年5月10日 下午12:45:03
 */
public class UtilsApplication  extends Application{

    private static Context context;
    private static Handler handler;
    private static int mainThreadId;

    @Override
    public void onCreate() {
        super.onCreate();

        context = getApplicationContext();
        handler = new Handler();

        //当前线程id,此处是主线程id
        mainThreadId = android.os.Process.myTid();

        // 初始化NoHttp
        NoHttp.init(this);
        // 打开NoHttp的调试模式
        Logger.setDebug(true);
        // 设置NoHttp的日志tag
        Logger.setTag("TestNoHttp");

        // 创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
                this).writeDebugLogs().build();
        ImageLoader.getInstance().init(configuration);
    }

    public static Context getContext() {
        return context;
    }

    public static Handler getHandler() {
        return handler;
    }

    public static int getMainThreadId() {
        return mainThreadId;
    }

}


text:
NS_ASSUME_NONNULL_BEGIN

@interface JWTClaimSerializerBase : NSObject <JWTClaimSerializerProtocol>

@end

NS_ASSUME_NONNULL_END


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
    NotInheritable Class GetTypeExpressionDocumentation
        Inherits AbstractIntrinsicOperatorDocumentation

        Public Overrides Function GetParameterDocumentation(index As Integer) As String
            Select Case index
                Case 0
                    Return VBWorkspaceResources.TypeToReturnObjectFor
                Case Else
                    Throw New ArgumentException("index")
            End Select
        End Function

        Public Overrides Function GetParameterName(index As Integer) As String
            Select Case index
                Case 0
                    Return VBWorkspaceResources.Typename
                Case Else
                    Throw New ArgumentException("index")
            End Select
        End Function

        Public Overrides ReadOnly Property ParameterCount As Integer
            Get
                Return 1
            End Get
        End Property

        Public Overrides ReadOnly Property DocumentationText As String
            Get
                Return VBWorkspaceResources.ReturnsSystemTypeObject
            End Get
        End Property

        Public Overrides ReadOnly Property PrefixParts As IEnumerable(Of SymbolDisplayPart)
            Get
                Return {
                    New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetType"),
                    New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")
                }
            End Get
        End Property

        Public Overrides ReadOnly Property IncludeAsType As Boolean
            Get
                Return True
            End Get
        End Property

        Public Overrides Function TryGetTypeNameParameter(syntaxNode As SyntaxNode, index As Integer) As TypeSyntax
            Dim getTypeExpression = TryCast(syntaxNode, GetTypeExpressionSyntax)

            If getTypeExpression IsNot Nothing Then
                Return getTypeExpression.Type
            Else
                Return Nothing
            End If
        End Function

        Public Overrides ReadOnly Property ReturnTypeMetadataName As String
            Get
                Return "System.Type"
            End Get
        End Property
    End Class
End Namespace


text:
function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.UInt32]
        $Index,

        [parameter(Mandatory = $true)]
        [System.String[]]
        $Servers,

        [parameter(Mandatory = $false)]
        [System.String]
        $RootDirectory,

        [parameter(Mandatory = $true)]
        [System.String]
        $ServiceAppName,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Getting Search Index Partition '$Index' settings"

    $result = Invoke-SPDSCCommand -Credential $InstallAccount `
                                  -Arguments $PSBoundParameters `
                                  -ScriptBlock {
        $params = $args[0]
        $ConfirmPreference = 'None'

        $ssa = Get-SPEnterpriseSearchServiceApplication -Identity $params.ServiceAppName
        $currentTopology = $ssa.ActiveTopology

        $IndexComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | `
                                Where-Object -FilterScript {
                                    ($_.GetType().Name -eq "IndexComponent") `
                                    -and ($_.IndexPartitionOrdinal -eq $params.Index)
                                }).ServerName

        return @{
            Index = $params.Index
            Servers = $IndexComponents
            RootDirectory = $params.RootDirectory
            ServiceAPpName = $params.ServiceAppName
            InstallAccount = $params.InstallAccount
        }
    }
    return $result
}

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.UInt32]
        $Index,

        [parameter(Mandatory = $true)]
        [System.String[]]
        $Servers,

        [parameter(Mandatory = $false)]
        [System.String]
        $RootDirectory,

        [parameter(Mandatory = $true)]
        [System.String]
        $ServiceAppName,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Setting Search Index Partition '$Index' settings"

    $CurrentValues = Get-TargetResource @PSBoundParameters

    Invoke-SPDSCCommand -Credential $InstallAccount `
                        -Arguments @($PSBoundParameters, $CurrentValues) `
                        -ScriptBlock {
        $params = $args[0]
        $CurrentValues = $args[1]
        $ConfirmPreference = 'None'

        $AllSearchServers = $params.Servers

        # Ensure the search service instance is running on all servers
        foreach($searchServer in $AllSearchServers)
        {
            $searchService = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
            if($searchService.Status -eq "Offline")
            {
                Write-Verbose -Message "Start Search Service Instance"
                Start-SPEnterpriseSearchServiceInstance -Identity $searchService
            }

            #Wait for Search Service Instance to come online
            $loopCount = 0
            $online = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
            do
            {
                $online = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
                Write-Verbose -Message "Waiting for service: $($online.TypeName)"
                $loopCount++
                Start-Sleep -Seconds 30
            }
            until ($online.Status -eq "Online" -or $loopCount -eq 20)
        }

        if ($params.ContainsKey("RootDirectory") -eq $true)
        {
            # Create the index partition directory on each remote server
            foreach($IndexPartitionServer in $params.Servers)
            {
                $networkPath = "\\$IndexPartitionServer\" + $params.RootDirectory.Replace(":\", "$\")
                New-Item -Path $networkPath -ItemType Directory -Force
            }

            # Create the directory on the local server as it will not apply the topology without it
            if ((Test-Path -Path $params.RootDirectory) -eq $false)
            {
                New-Item $params.RootDirectory -ItemType Directory -Force
            }
        }

        # Get all service service instances to assign topology components to
        $AllSearchServiceInstances = @{}
        foreach ($server in $AllSearchServers)
        {
            $si = Get-SPEnterpriseSearchServiceInstance -Identity $server
            $AllSearchServiceInstances.Add($server, $si)
        }

        # Get current topology and prepare a new one
        $ssa = Get-SPEnterpriseSearchServiceApplication -Identity $params.ServiceAppName
        $currentTopology = $ssa.ActiveTopology
        $newTopology = New-SPEnterpriseSearchTopology -SearchApplication $ssa `
                                                      -Clone `
                                                      -SearchTopology $currentTopology

        $componentTypes = @{
            Servers = "IndexComponent"
        }

        # Build up the topology changes for each object type
        @("Servers") | ForEach-Object -Process {
            $CurrentSearchProperty = $_
            Write-Verbose -Message "Setting components for '$CurrentSearchProperty' property"

            if ($null -eq $CurrentValues.$CurrentSearchProperty)
            {
                $ComponentsToAdd = $params.$CurrentSearchProperty
            }
            else
            {
                $ComponentsToAdd = @()
                $ComponentsToRemove = @()

                $components = $params.$CurrentSearchProperty | Where-Object -FilterScript {
                    $CurrentValues.$CurrentSearchProperty.Contains($_) -eq $false
                }
                foreach($component in $components)
                {
                    $ComponentsToAdd += $component
                }
                $components = $CurrentValues.$CurrentSearchProperty | Where-Object -FilterScript {
                    $params.$CurrentSearchProperty.Contains($_) -eq $false
                }
                foreach($component in $components)
                {
                    $ComponentsToRemove += $component
                }
            }
            foreach($componentToAdd in $ComponentsToAdd)
            {
                $NewComponentParams = @{
                    SearchTopology = $newTopology
                    SearchServiceInstance = $AllSearchServiceInstances.$componentToAdd
                }
                switch($componentTypes.$CurrentSearchProperty)
                {
                    "IndexComponent" {
                        $NewComponentParams.Add("IndexPartition", $params.Index)
                        if ($params.ContainsKey("RootDirectory") -eq $true)
                        {
                            if ([string]::IsNullOrEmpty($params.RootDirectory) -eq $false)
                            {
                                $NewComponentParams.Add("RootDirectory", $params.RootDirectory)
                            }
                        }
                        New-SPEnterpriseSearchIndexComponent @NewComponentParams
                    }
                }
            }
            foreach($componentToRemove in $ComponentsToRemove)
            {
                $component = Get-SPEnterpriseSearchComponent -SearchTopology $newTopology | `
                    Where-Object -FilterScript {
                        ($_.GetType().Name -eq $componentTypes.$CurrentSearchProperty) `
                            -and ($_.ServerName -eq $componentToRemove) `
                            -and ($_.IndexPartitionOrdinal -eq $params.Index)
                }
                if ($null -ne $component)
                {
                    $component | Remove-SPEnterpriseSearchComponent -SearchTopology $newTopology `
                                                                    -Confirm:$false
                }

            }
        }

        # Apply the new topology
        Set-SPEnterpriseSearchTopology -Identity $newTopology
    }
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.UInt32]
        $Index,

        [parameter(Mandatory = $true)]
        [System.String[]]
        $Servers,

        [parameter(Mandatory = $false)]
        [System.String]
        $RootDirectory,

        [parameter(Mandatory = $true)]
        [System.String]
        $ServiceAppName,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Testing Search Index Partition '$Index' settings"

    $CurrentValues = Get-TargetResource @PSBoundParameters

    return Test-SPDscParameterState -CurrentValues $CurrentValues `
                                              -DesiredValues $PSBoundParameters `
                                              -ValuesToCheck @("Servers")
}

Export-ModuleMember -Function *-TargetResource


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

<title>com.simple.database.crud Class Hierarchy (database API)</title>
<meta name="date" content="2016-08-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.simple.database.crud

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.simple.database.crud.base.BaseSQLBuilder<T> (implements com.simple.database.crud.base.Executable)

com.simple.database.crud.InsertBuilder<T>

com.simple.database.crud.base.WhereBuilder<T>

com.simple.database.crud.CountBuilder

com.simple.database.crud.DeleteBuilder<T>

com.simple.database.crud.QueryBuilder<T>

com.simple.database.crud.UpdateBuilder<T>

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
category: news
---

Look at me! I'm a collection doc in a category!