text:
/*!
 */
#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <cstdlib>
#include "utils.h"
#include "mxnet-cpp/MxNetCpp.h"

using namespace mxnet::cpp;

Symbol AlexnetSymbol(int num_classes) {
  auto input_data = Symbol::Variable("data");
  auto target_label = Symbol::Variable("label");
  /*stage 1*/
  auto conv1 = Operator("Convolution")
                   .SetParam("kernel", Shape(11, 11))
                   .SetParam("num_filter", 96)
                   .SetParam("stride", Shape(4, 4))
                   .SetParam("dilate", Shape(1, 1))
                   .SetParam("pad", Shape(0, 0))
                   .SetParam("num_group", 1)
                   .SetParam("workspace", 512)
                   .SetParam("no_bias", false)
                   .SetInput("data", input_data)
                   .CreateSymbol("conv1");
  auto relu1 = Operator("Activation")
                   .SetParam("act_type", "relu") /*relu,sigmoid,softrelu,tanh */
                   .SetInput("data", conv1)
                   .CreateSymbol("relu1");
  auto pool1 = Operator("Pooling")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("pool_type", "max") /*avg,max,sum */
                   .SetParam("global_pool", false)
                   .SetParam("stride", Shape(2, 2))
                   .SetParam("pad", Shape(0, 0))
                   .SetInput("data", relu1)
                   .CreateSymbol("pool1");
  auto lrn1 = Operator("LRN")
                  .SetParam("nsize", 5)
                  .SetParam("alpha", 0.0001)
                  .SetParam("beta", 0.75)
                  .SetParam("knorm", 1)
                  .SetInput("data", pool1)
                  .CreateSymbol("lrn1");
  /*stage 2*/
  auto conv2 = Operator("Convolution")
                   .SetParam("kernel", Shape(5, 5))
                   .SetParam("num_filter", 256)
                   .SetParam("stride", Shape(1, 1))
                   .SetParam("dilate", Shape(1, 1))
                   .SetParam("pad", Shape(2, 2))
                   .SetParam("num_group", 1)
                   .SetParam("workspace", 512)
                   .SetParam("no_bias", false)
                   .SetInput("data", lrn1)
                   .CreateSymbol("conv2");
  auto relu2 = Operator("Activation")
                   .SetParam("act_type", "relu") /*relu,sigmoid,softrelu,tanh */
                   .SetInput("data", conv2)
                   .CreateSymbol("relu2");
  auto pool2 = Operator("Pooling")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("pool_type", "max") /*avg,max,sum */
                   .SetParam("global_pool", false)
                   .SetParam("stride", Shape(2, 2))
                   .SetParam("pad", Shape(0, 0))
                   .SetInput("data", relu2)
                   .CreateSymbol("pool2");
  auto lrn2 = Operator("LRN")
                  .SetParam("nsize", 5)
                  .SetParam("alpha", 0.0001)
                  .SetParam("beta", 0.75)
                  .SetParam("knorm", 1)
                  .SetInput("data", pool2)
                  .CreateSymbol("lrn2");
  /*stage 3*/
  auto conv3 = Operator("Convolution")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("num_filter", 384)
                   .SetParam("stride", Shape(1, 1))
                   .SetParam("dilate", Shape(1, 1))
                   .SetParam("pad", Shape(1, 1))
                   .SetParam("num_group", 1)
                   .SetParam("workspace", 512)
                   .SetParam("no_bias", false)
                   .SetInput("data", lrn2)
                   .CreateSymbol("conv3");
  auto relu3 = Operator("Activation")
                   .SetParam("act_type", "relu") /*relu,sigmoid,softrelu,tanh */
                   .SetInput("data", conv3)
                   .CreateSymbol("relu3");
  auto conv4 = Operator("Convolution")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("num_filter", 384)
                   .SetParam("stride", Shape(1, 1))
                   .SetParam("dilate", Shape(1, 1))
                   .SetParam("pad", Shape(1, 1))
                   .SetParam("num_group", 1)
                   .SetParam("workspace", 512)
                   .SetParam("no_bias", false)
                   .SetInput("data", relu3)
                   .CreateSymbol("conv4");
  auto relu4 = Operator("Activation")
                   .SetParam("act_type", "relu") /*relu,sigmoid,softrelu,tanh */
                   .SetInput("data", conv4)
                   .CreateSymbol("relu4");
  auto conv5 = Operator("Convolution")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("num_filter", 256)
                   .SetParam("stride", Shape(1, 1))
                   .SetParam("dilate", Shape(1, 1))
                   .SetParam("pad", Shape(1, 1))
                   .SetParam("num_group", 1)
                   .SetParam("workspace", 512)
                   .SetParam("no_bias", false)
                   .SetInput("data", relu4)
                   .CreateSymbol("conv5");
  auto relu5 = Operator("Activation")
                   .SetParam("act_type", "relu")
                   .SetInput("data", conv5)
                   .CreateSymbol("relu5");
  auto pool3 = Operator("Pooling")
                   .SetParam("kernel", Shape(3, 3))
                   .SetParam("pool_type", "max")
                   .SetParam("global_pool", false)
                   .SetParam("stride", Shape(2, 2))
                   .SetParam("pad", Shape(0, 0))
                   .SetInput("data", relu5)
                   .CreateSymbol("pool3");
  /*stage4*/
  auto flatten =
      Operator("Flatten").SetInput("data", pool3).CreateSymbol("flatten");
  auto fc1 = Operator("FullyConnected")
                 .SetParam("num_hidden", 4096)
                 .SetParam("no_bias", false)
                 .SetInput("data", flatten)
                 .CreateSymbol("fc1");
  auto relu6 = Operator("Activation")
                   .SetParam("act_type", "relu")
                   .SetInput("data", fc1)
                   .CreateSymbol("relu6");
  auto dropout1 = Operator("Dropout")
                      .SetParam("p", 0.5)
                      .SetInput("data", relu6)
                      .CreateSymbol("dropout1");
  /*stage5*/
  auto fc2 = Operator("FullyConnected")
                 .SetParam("num_hidden", 4096)
                 .SetParam("no_bias", false)
                 .SetInput("data", dropout1)
                 .CreateSymbol("fc2");
  auto relu7 = Operator("Activation")
                   .SetParam("act_type", "relu")
                   .SetInput("data", fc2)
                   .CreateSymbol("relu7");
  auto dropout2 = Operator("Dropout")
                      .SetParam("p", 0.5)
                      .SetInput("data", relu7)
                      .CreateSymbol("dropout2");
  /*stage6*/
  auto fc3 = Operator("FullyConnected")
                 .SetParam("num_hidden", num_classes)
                 .SetParam("no_bias", false)
                 .SetInput("data", dropout2)
                 .CreateSymbol("fc3");
  auto softmax = Operator("SoftmaxOutput")
                     .SetParam("grad_scale", 1)
                     .SetParam("ignore_label", -1)
                     .SetParam("multi_output", false)
                     .SetParam("use_ignore", false)
                     .SetParam("normalization", "null") /*batch,null,valid */
                     .SetInput("data", fc3)
                     .SetInput("label", target_label)
                     .CreateSymbol("softmax");
  return softmax;
}

int main(int argc, char const *argv[]) {
  /*basic config*/
  int batch_size = 256;
  int max_epo = argc > 1 ? strtol(argv[1], NULL, 10) : 100;
  float learning_rate = 1e-4;
  float weight_decay = 1e-4;

  /*context and net symbol*/
  auto ctx = Context::gpu();
#if MXNET_USE_CPU
  ctx = Context::cpu();
#endif

  auto Net = AlexnetSymbol(10);

  /*args_map and aux_map is used for parameters' saving*/
  std::map<std::string, NDArray> args_map;
  std::map<std::string, NDArray> aux_map;

  /*we should tell mxnet the shape of data and label*/
  args_map["data"] = NDArray(Shape(batch_size, 3, 256, 256), ctx);
  args_map["label"] = NDArray(Shape(batch_size), ctx);

  /*with data and label, executor can be generated automatically*/
  auto *exec = Net.SimpleBind(ctx, args_map);
  auto arg_names = Net.ListArguments();
  aux_map = exec->aux_dict();
  args_map = exec->arg_dict();

  /*if fine tune from some pre-trained model, we should load the parameters*/
  // NDArray::Load("./model/alex_params_3", nullptr, &args_map);
  /*else, we should use initializer Xavier to init the params*/
  Xavier xavier = Xavier(Xavier::gaussian, Xavier::in, 2.34);
  for (auto &arg : args_map) {
    /*be careful here, the arg's name must has some specific ends or starts for
     * initializer to call*/
    xavier(arg.first, &arg.second);
  }

  /*these binary files should be generated using im2rc tools, which can be found
   * in mxnet/bin*/
  std::vector<std::string> data_files = { "./data/mnist_data/train-images-idx3-ubyte",
                                "./data/mnist_data/train-labels-idx1-ubyte",
                                "./data/mnist_data/t10k-images-idx3-ubyte",
                                "./data/mnist_data/t10k-labels-idx1-ubyte"
                              };

  auto train_iter =  MXDataIter("MNISTIter");
  if (!setDataIter(&train_iter, "Train", data_files, batch_size)) {
    return 1;
  }

  auto val_iter = MXDataIter("MNISTIter");
  if (!setDataIter(&val_iter, "Label", data_files, batch_size)) {
    return 1;
  }

  Optimizer* opt = OptimizerRegistry::Find("sgd");
  opt->SetParam("momentum", 0.9)
     ->SetParam("rescale_grad", 1.0 / batch_size)
     ->SetParam("clip_gradient", 10)
     ->SetParam("lr", learning_rate)
     ->SetParam("wd", weight_decay);

  Accuracy acu_train, acu_val;
  LogLoss logloss_val;
  for (int iter = 0; iter < max_epo; ++iter) {
    LG << "Train Epoch: " << iter;
    /*reset the metric every epoch*/
    acu_train.Reset();
    /*reset the data iter every epoch*/
    train_iter.Reset();
    while (train_iter.Next()) {
      auto batch = train_iter.GetDataBatch();
      /*use copyto to feed new data and label to the executor*/
      batch.data.CopyTo(&args_map["data"]);
      batch.label.CopyTo(&args_map["label"]);
      exec->Forward(true);
      exec->Backward();
      for (size_t i = 0; i < arg_names.size(); ++i) {
        if (arg_names[i] == "data" || arg_names[i] == "label") continue;
        opt->Update(i, exec->arg_arrays[i], exec->grad_arrays[i]);
      }

      NDArray::WaitAll();
      acu_train.Update(batch.label, exec->outputs[0]);
    }
    LG << "ITER: " << iter << " Train Accuracy: " << acu_train.Get();

    LG << "Val Epoch: " << iter;
    acu_val.Reset();
    val_iter.Reset();
    logloss_val.Reset();
    while (val_iter.Next()) {
      auto batch = val_iter.GetDataBatch();
      LG << val_iter.GetDataBatch().index.size();
      batch.data.CopyTo(&args_map["data"]);
      batch.label.CopyTo(&args_map["label"]);
      exec->Forward(false);
      NDArray::WaitAll();
      acu_val.Update(batch.label, exec->outputs[0]);
      logloss_val.Update(batch.label, exec->outputs[0]);
    }
    LG << "ITER: " << iter << " Val Accuracy: " << acu_val.Get();
    LG << "ITER: " << iter << " Val LogLoss: " << logloss_val.Get();

    /*save the parameters*/
    std::stringstream ss;
    ss << iter;
    std::string iter_str;
    ss >> iter_str;
    std::string save_path_param = "alex_param_" + iter_str;
    auto save_args = args_map;
    /*we do not want to save the data and label*/
    save_args.erase(save_args.find("data"));
    save_args.erase(save_args.find("label"));
    /*the alexnet does not get any aux array, so we do not need to save
     * aux_map*/
    LG << "ITER: " << iter << " Saving to..." << save_path_param;
    NDArray::Save(save_path_param, save_args);
  }
  /*don't foget to release the executor*/
  delete exec;
  MXNotifyShutdown();
  return 0;
}


text:
This repository contains a simulation source codes for Vectio, a new network
transport design that can be implemented in NIC H/W.

**This is not an officially supported Google product.**

## Source Code Headers

Every file containing source code must include copyright and license
information. This includes any JS/CSS files that you might be serving out to
browsers. (This is to help well-intentioned people avoid accidental copying that
doesn't comply with the license.)

Apache header:

    Copyright 2020 Google LLC

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

redpajama_set_name: RedPajamaGithub


text:
This library is now **deprecated** and moved to the official [firebase](https://pub.dartlang.org/packages/firebase).

Please update your `pubspec.yaml` file to `firebase` dependency, do the `pub get`, update imports to `firebase` library and you are ready to go:

```
dependencies:
  firebase: '^3.0.0'
```


text:
* POST /api/emotions
* GET /api/highscore


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace PHBGTU.Areas.Auction.Models
{
    public class AuctionMedia
    {
        [Key]
        public int AuctionMediaId { get; set; }
        [Required]
        public DateTime LastUsed { get; set; }
        public String Url { get; set; }
        [Required]
        public bool SafeToDelete { get; set; }

    }
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SidenavComponent } from './sidenav/sidenav.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [SidenavComponent],
  exports: [SidenavComponent]
})
export class SharedModule { }


text:
package org.apache.nifi.hl7.hapi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.nifi.hl7.model.HL7Message;
import org.apache.nifi.hl7.model.HL7Segment;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Group;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Segment;
import ca.uhn.hl7v2.model.Structure;

public class HapiMessage implements HL7Message {

    private final Message message;
    private final List<HL7Segment> allSegments;
    private final Map<String, List<HL7Segment>> segmentMap;

    public HapiMessage(final Message message) throws HL7Exception {
        this.message = message;

        allSegments = new ArrayList<>();
        populateSegments(message, allSegments);

        segmentMap = new HashMap<>();
        for (final HL7Segment segment : allSegments) {
            final String segmentName = segment.getName();
            List<HL7Segment> segmentList = segmentMap.get(segmentName);
            if (segmentList == null) {
                segmentList = new ArrayList<>();
                segmentMap.put(segmentName, segmentList);
            }

            segmentList.add(segment);
        }
    }

    private void populateSegments(final Group group, final List<HL7Segment> segments) throws HL7Exception {
        for (final String structureName : group.getNames()) {
            final Structure[] structures = group.getAll(structureName);
            if (group.isGroup(structureName)) {
                for (final Structure structure : structures) {
                    populateSegments((Group) structure, segments);
                }
            } else {
                for (final Structure structure : structures) {
                    final Segment segment = (Segment) structure;
                    final HapiSegment hapiSegment = new HapiSegment(segment);
                    segments.add(hapiSegment);
                }
            }
        }
    }

    @Override
    public List<HL7Segment> getSegments() {
        return Collections.unmodifiableList(allSegments);
    }

    @Override
    public List<HL7Segment> getSegments(final String segmentType) {
        final List<HL7Segment> segments = segmentMap.get(segmentType);
        if (segments == null) {
            return Collections.emptyList();
        }

        return Collections.unmodifiableList(segments);
    }

    @Override
    public String toString() {
        return message.toString();
    }
}


text:
var express = require('express')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(5885);

app.configure(function(){
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.bodyParser());
});

app.get('/', function (req, res) {
	res.writeHeader(200, {"Content-Type": "text/html"});
	res.write("nothing...");
	res.end();
});

io.sockets.on('connection', function (socket) {

  socket.emit('handshake', { message: 'pong' });

  socket.on('request', function (data) {
    console.log(data);
    socket.emit('response', { result: 'harr' });
  });

});


text:
class CCatPage : public CSitePage
{
	public:
		CCatPage(const std::string name, const CFCGIRequest* currRequest);
		virtual ~CCatPage();
	protected:
		virtual std::string buildContent() const;
	private:
};

#endif // CCATPAGE_H


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

<title>ClassificationDataSpecification (ARX API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.aggregates.classification

Class ClassificationDataSpecification

java.lang.Object

org.deidentifier.arx.aggregates.classification.ClassificationDataSpecification

public class ClassificationDataSpecification
extends java.lang.Object

A complete specification of all input and output data

Field Summary

Fields

Modifier and Type
Field and Description

int
classIndex

Index

java.util.Map<java.lang.String,java.lang.Integer>
classMap

Map

int[]
featureIndices

Indexes

ClassificationFeatureMetadata[]
inputFeatureMetadata

Feature meta data

ClassificationFeatureMetadata[]
outputFeatureMetadata

Feature meta data

Constructor Summary

Constructors

Constructor and Description

ClassificationDataSpecification(DataHandleInternal inputFeatureHandle,
                               DataHandleInternal outputFeatureHandle,
                               java.lang.String[] features,
                               java.lang.String clazz,
                               WrappedBoolean interrupt)

Creates a new instance

Method Summary

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

classIndex

public final int classIndex

Index

classMap

public final java.util.Map<java.lang.String,java.lang.Integer> classMap

Map

featureIndices

public final int[] featureIndices

Indexes

inputFeatureMetadata

public final ClassificationFeatureMetadata[] inputFeatureMetadata

Feature meta data

outputFeatureMetadata

public final ClassificationFeatureMetadata[] outputFeatureMetadata

Feature meta data

Constructor Detail

ClassificationDataSpecification

public ClassificationDataSpecification(DataHandleInternal inputFeatureHandle,
                               DataHandleInternal outputFeatureHandle,
                               java.lang.String[] features,
                               java.lang.String clazz,
                               WrappedBoolean interrupt)

Creates a new instance

Parameters:

inputFeatureHandle -

outputFeatureHandle -

classHandle -

features -

clazz -

interrupt -

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
define([
    'jquery',
    "underscore",
    'handlebars',
    'filter_base',
    'jqueryui'
], function ($, _, handlebars, filter_base) {
  "use strict";

  var TextFilter = function(field){
    this.base = filter_base.FilterBase;
    this.base(field);
    this.items_hash = {};
  }
  TextFilter.prototype = new filter_base.FilterBase;

  TextFilter.prototype.get_filter_template = function(){
    return handlebars.compile(
      "
" +
        "
" +
          "
Filter by {{name}}
" +
          "" +
        "
" +
        "
" +
          "
" +
            "<input class='search-input' type='text'/>" +
          "
" +
          "
" +
        "
" +
        "
" +
          "Select All"+
          "Reset"+
        "
" +
      "
"
    );
  }

  TextFilter.prototype.initialize_min_max = function(item){
    $.proxy(this.base.prototype.initialize_min_max.call(this, item), this);
    var item_value = item[this.field];
    this.items_hash[item_value] = {id: item_value, value: item_value}
  }

  TextFilter.prototype.initialize_controls = function(){
    $.proxy(this.base.prototype.initialize_controls.call(this), this);
    this.filter_grid_elem = this.filter_elem.find(".text-filter-grid");
    this.search_string = "";

    this.grid_items = _.values(this.items_hash);

    this.data_view = new Slick.Data.DataView({
      inlineFilters: false,
      enableTextSelectionOnCells: true
    });

    this.sort_comparer = function(x, y){
      var x_value = x.value;
      var y_value = y.value;

      // selected row should be sorted to the top
      if (x.selected != y.selected){
        return x.selected ? -1 : 1;
      }

      return x_value > y_value ? 1 : -1;
    }

    var text_filter = function(item, args){
      if (this.search_string){
        if (item.value.toLowerCase().indexOf(this.search_string.toLowerCase()) == -1){
          return false;
        }
      }
      return true;
    }

    this.data_view.beginUpdate();
    this.data_view.setItems(this.grid_items);
    this.data_view.setFilter($.proxy(text_filter, this));
    this.data_view.sort($.proxy(this.sort_comparer, this), true);
    this.data_view.endUpdate();

    var row_formatter = function(row, cell, value, columnDef, dataContext){
      return "" + dataContext.value + "";
    }

    var checkboxSelector = new Slick.CheckboxSelectColumn({
      cssClass: "check-box-cell"
    })

    var columns = [
      checkboxSelector.getColumnDefinition(),
      {
        id: "name",
        name: "Name",
        field: "name",
        formatter: row_formatter,
        sortable: true
      }];

    var options = {
      enableCellNavigation: true,
      fullWidthRows: true,
      syncColumnCellResize: true,
      rowHeight: 32,
      forceFitColumns: true,
      enableColumnReorder: false,
      autoHeight: true
    };

    var max_height = options.rowHeight * 10;
    var grid_height = max_height;
    // totalRowHeight is how tall the grid would have to be to fit all of the rows in the dataframe.
    var total_row_height = (this.grid_items.length) * options.rowHeight;
    if (total_row_height <= max_height){
      grid_height = total_row_height;
      this.filter_grid_elem.addClass('hide-scrollbar');
    }
    this.filter_grid_elem.height(grid_height);

    this.filter_grid = new Slick.Grid(this.filter_grid_elem, this.data_view,  columns, options);
    this.filter_grid.registerPlugin(checkboxSelector);

    this.row_selection_model = new Slick.RowSelectionModel({selectActiveRow: false});
    this.row_selection_model.onSelectedRangesChanged.subscribe($.proxy(this.handle_selection_changed, this));

    this.filter_grid.setSelectionModel(this.row_selection_model);
    this.data_view.syncGridSelection(this.filter_grid, true, true);
    this.filter_grid.render();

    this.data_view.onRowCountChanged.subscribe($.proxy(function(e, args){
      this.filter_grid.updateRowCount();
      this.filter_grid.render();
    }, this));

    this.data_view.onRowsChanged.subscribe($.proxy(function(e, args){
      this.filter_grid.invalidateRows(args.rows);
      this.filter_grid.render();
    }, this));

    this.security_search = this.filter_elem.find(".search-input");
    this.security_search.keyup($.proxy(this.handle_text_input_key_up, this));
    this.security_search.click($.proxy(this.handle_text_input_click, this));

    this.filter_grid.onClick.subscribe($.proxy(this.handle_grid_clicked, this));
    this.filter_grid.onKeyDown.subscribe($.proxy(this.handle_grid_key_down, this));

    this.filter_elem.find("a.select-all-link").click($.proxy(function(e){
      this.reset_filter();
      var all_row_indices = [];
      var all_rows = this.data_view.getItems();
      for (var i=0; i< all_rows.length; i++){
        all_row_indices.push(i)
      }
      this.row_selection_model.setSelectedRows(all_row_indices);
      $(this).trigger("filter_changed");
      return false;
    }, this));
  }

  TextFilter.prototype.toggle_row_selected = function(row_index){
    var old_selected_rows = this.row_selection_model.getSelectedRows();
    // if the row is already selected, remove it from the selected rows array.
    var selected_rows = old_selected_rows.filter(function(word){
      return word !== row_index;
    });
    // otherwise add it to the selected rows array so it gets selected
    if (selected_rows.length == old_selected_rows.length){
      selected_rows.push(row_index);
    }
    this.row_selection_model.setSelectedRows(selected_rows);
  }

  TextFilter.prototype.handle_grid_clicked = function(e, args){
    this.toggle_row_selected(args.row);
    var active_cell = this.filter_grid.getActiveCell();
    if (!active_cell){
      e.stopImmediatePropagation();
    }
  }

  TextFilter.prototype.handle_grid_key_down = function(e, args){
    var active_cell = this.filter_grid.getActiveCell();
    if (active_cell){
      if (e.keyCode == 13){ // enter key
        this.toggle_row_selected(active_cell.row);
        return;
      }

      // focus on the search box for any key other than the up/down arrows
      if (e.keyCode != 40 && e.keyCode != 38){
        this.focus_on_search_box();
        return;
      }

      // also focus on the search box if we're at the top of the grid and this is the up arrow
      else if (active_cell.row == 0 && e.keyCode == 38){
        this.focus_on_search_box();
        e.preventDefault();
        return;
      }
    }
  }

  TextFilter.prototype.sort_if_needed = function(force){
    if (force || this.sort_needed){
      this.data_view.sort(this.sort_comparer, true);
      this.sort_needed = false;
    }
  }

  TextFilter.prototype.focus_on_search_box = function(){
    this.security_search.focus().val(this.search_string);
    this.filter_grid.resetActiveCell();
  }

  TextFilter.prototype.handle_text_input_key_up = function(e){
    var old_search_string = this.search_string;
    if (e.keyCode == 40){ // down arrow
      this.filter_grid.focus();
      this.filter_grid.setActiveCell(0, 0);
      return;
    }
    if (e.keyCode == 13){ // enter key
      if (this.security_grid.getDataLength() > 0){
        this.toggle_row_selected(0);
        this.security_search.val("");
      }
    }

    this.search_string = this.security_search.val();
    if (old_search_string != this.search_string){
      this.data_view.refresh();
      this.sort_if_needed();
    }
  }

  TextFilter.prototype.handle_text_input_click = function(e){
    this.filter_grid.resetActiveCell();
  }

  TextFilter.prototype.handle_selection_changed = function(e, args){
    var all_rows = this.data_view.getItems();

    // Set selected to false for all visible rows (non visible rows
    // aren't included in the getSelectedRows, so we should leave the
    // state of those untouched)
    for (var row_index=0; row_index < all_rows.length; row_index++){
      var cur_row = all_rows[row_index];
      if (this.data_view.getRowById(cur_row.id) !== undefined){
        cur_row.selected = false;
      }
    }
    // Set selected to true for all selected rows
    var rows = this.row_selection_model.getSelectedRows();
    if (rows.length > 0){
      for (var row_index=0; row_index < rows.length; row_index++){
        var data_row_index = rows[row_index];
        var row = this.data_view.getItem(data_row_index);
        row.selected = true;
      }
    }
    // Regenerate the filter_sid_list by looping through all rows
    // (visible and filtered out) and adding them to the list if selected is true.
    this.filter_list = {};
    var something_selected = false
    for (var row_index=0; row_index < all_rows.length; row_index++){
      var row = all_rows[row_index];
      if (row.selected){
        something_selected = true;
        this.filter_list[row.value] = row.value;
      }
    }
    // If nothing is selected, then indicate that the grid should be unfiltered by setting
    // the filter_sid_list to null.
    if (!something_selected){
      this.filter_list = null;
    }

    // We want to resort the grid, but not immediately when a row is checked, because
    // it's jarring to have the row that the user just checked jump to the top of the grid.
    // Instead, we just set this flag so that we know to resort the grid the next time the filter
    // changes or the filter dropdown gets re-opened.
    this.sort_needed = true;

    $(this).trigger("filter_changed");
  }

  TextFilter.prototype.handle_filter_button_clicked = function(e){
    $.proxy(this.base.prototype.handle_filter_button_clicked.call(this, e), this);
    this.filter_grid.setColumns(this.filter_grid.getColumns());
    this.filter_grid.resizeCanvas();
    this.sort_if_needed();
    this.focus_on_search_box();
    return false;
  }

  TextFilter.prototype.is_active = function(){
    return this.filter_list != null;
  }

  TextFilter.prototype.reset_filter = function(){
    this.search_string = "";
    this.security_search.val("");
    this.data_view.refresh();
    this.row_selection_model.setSelectedRows([]);
    this.filter_list = null;
  }

  TextFilter.prototype.include_item = function(item){
    if (this.filter_list && !this.filter_list[item[this.field]]){
      return false;
    }
    return true;
  }

  return {'TextFilter': TextFilter}
});


text:
namespace aura {
class Window;
}

namespace gfx {
class Display;
class Rect;
class Point;
}

namespace ash {

class ASH_EXPORT ScreenUtil {
 public:
  // Finds the display that contains |point| in screeen coordinates.
  // Returns invalid display if there is no display that can satisfy
  // the condition.
  static gfx::Display FindDisplayContainingPoint(const gfx::Point& point);

  // Returns the bounds for maximized windows in parent coordinates.
  // Maximized windows trigger auto-hiding the shelf.
  static gfx::Rect GetMaximizedWindowBoundsInParent(aura::Window* window);

  // Returns the display bounds in parent coordinates.
  static gfx::Rect GetDisplayBoundsInParent(aura::Window* window);

  // Returns the display's work area bounds in parent coordinates.
  static gfx::Rect GetDisplayWorkAreaBoundsInParent(aura::Window* window);

  // Returns the physical display bounds containing the shelf that
  // shares the same root window as |root|. Physical displays can
  // differ from logical displays in unified desktop mode.
  // TODO(oshima): If we need to expand the unified desktop support to
  // general use, we should consider always using physical display in
  // window layout instead of root window, and keep the logical
  // display only in display management code.
  static gfx::Rect GetShelfDisplayBoundsInRoot(aura::Window* window);

  // TODO(oshima): Move following two to wm/coordinate_conversion.h
  // Converts |rect| from |window|'s coordinates to the virtual screen
  // coordinates.
  static gfx::Rect ConvertRectToScreen(aura::Window* window,
                                       const gfx::Rect& rect);

  // Converts |rect| from virtual screen coordinates to the |window|'s
  // coordinates.
  static gfx::Rect ConvertRectFromScreen(aura::Window* window,
                                         const gfx::Rect& rect);

  // Returns a gfx::Display object for secondary display. Returns
  // invalid display if there is no secondary display connected.
  static const gfx::Display& GetSecondaryDisplay();

 private:
  ScreenUtil() {}
  ~ScreenUtil() {}

  DISALLOW_COPY_AND_ASSIGN(ScreenUtil);
};

}  // namespace ash

#endif  // ASH_SCREEN_UTIL_H_


text:
{% assign author = site.authors | where: "name", page.author | first %}
{{ author.display_name }}


text:
import { expect } from 'chai';

import createGrid from '../createGrid';
import gridInsertPattern, { patterns } from '../gridInsertPattern';

describe('gridInsertPattern', () => {
  it('should insert block pattern to position [0, 0]', () => {
    const grid = createGrid(2, 2);
    const resultGrid = gridInsertPattern('block', grid, 0, 0);

    expect(resultGrid).to.deep.equal(patterns.block);
  });

  it('should insert beacon pattern to position [0, 0]', () => {
    const grid = createGrid(4, 4);
    const resultGrid = gridInsertPattern('beacon', grid, 0, 0);

    expect(resultGrid).to.deep.equal(patterns.beacon);
  });

  it('should insert blinker1 pattern to position [0, 0]', () => {
    const grid = createGrid(3, 3);
    const resultGrid = gridInsertPattern('blinker1', grid, 0, 0);

    expect(resultGrid).to.deep.equal(patterns.blinker1);
  });

  it('should insert lwss pattern to position [0, 0]', () => {
    const grid = createGrid(5, 4);
    const resultGrid = gridInsertPattern('lwss', grid, 0, 0);

    expect(resultGrid).to.deep.equal(patterns.lwss);
  });

  it('should insert block pattern to position [1, 2]', () => {
    const grid = createGrid(4, 4);
    const expectedGrid = [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 1, 1, 0],
      [0, 1, 1, 0],
    ];
    const resultGrid = gridInsertPattern('block', grid, 1, 2);

    expect(resultGrid).to.deep.equal(expectedGrid);
  });

  it('should return identical grid when specified unknown-pattern', () => {
    const expectedGrid = [
      [0, 1, 0, 1],
      [0, 0, 0, 0],
      [0, 1, 1, 0],
      [0, 1, 1, 0],
    ];
    const resultGrid = gridInsertPattern('unknown-pattern', expectedGrid, 1, 2);

    expect(resultGrid).to.deep.equal(expectedGrid);
  });

});


text:
import json
from datetime import datetime

from timecard.models import admin_required, is_admin, db, config, set_config, User, TimeSegment, Template, TemplateSegment

from flask import Blueprint, session, request, abort, jsonify
from flask_cas import login_required

api_views = Blueprint('api', __name__, url_prefix='/api')

@api_views.route('/users', methods=['POST', 'GET'])
@login_required
@admin_required
def all_users():
    """
    POST:   Create new user, with endpoint /users/<id>.
            Return 201 with location if successful, 409 if user already exists.
    GET:    Fetch all-user data summary for specified period.
    Only admins are allowed to create users or view summary.
    """

    if request.method == 'POST':
        request_dict = request.get_json(silent=True)

        # Check that the request parameters are valid
        if not request_dict:
            abort(400)

        user_id = request_dict['id']
        user_name_first = request_dict['name_first']
        user_name_last = request_dict['name_last']

        if not user_id or not user_name_first or not user_name_last:
            abort(400)

        new_user = User(id=user_id.upper(), name_first=user_name_first, name_last=user_name_last)

        db.session.add(new_user)
        db.session.commit()

        # TODO: test Respond with location header for new user
        return jsonify(), 201, {'location': '/users/{0}'.format(new_user.id)}

    elif request.method == 'GET':
        # Return all-user data summary for specified period
        # Request args is a series of start and end timestamp pairs
        # Returns total hours between each pair

        start_timestamps = request.args.getlist('start')
        end_timestamps = request.args.getlist('end')

        range_start = start_timestamps[0]
        range_end = end_timestamps[-1]

        summary_dict = {
            'users': []
        }

        users = User.query.order_by(User.name_last, User.name_first)

        for u in users:
            user_dict = u.to_dict()
            user_dict['hours'] = []  # Array of totals, one per specified period

            # Select all TimeSegments of this user that intersect the full selection period
            time_segments = u.time_segments.filter(TimeSegment.start_timestamp <= range_end,
                                                   TimeSegment.end_timestamp >= range_start)

            # This will iterate each pair of (start, end) timestamps
            for i in range(len(start_timestamps)):
                selection_start = int(start_timestamps[i])
                selection_end = int(end_timestamps[i])

                if not selection_start < selection_end:
                    abort(400)

                # select from time_segments those that intersect this selection
                selection_segments = time_segments.filter(TimeSegment.start_timestamp <= selection_end,
                                                          TimeSegment.end_timestamp >= selection_start)

                selection_total = 0.0
                for s in selection_segments:
                    # Trim start and end to the part that intersects this selection
                    segment_start = max(s.start_timestamp, selection_start)
                    segment_end = min(s.end_timestamp, selection_end)

                    selection_total += (segment_end - segment_start) / 3600  # Duration seconds converted to hours

                user_dict['hours'].append(selection_total)
                user_dict['total_hours'] = sum(user_dict['hours'])

            summary_dict['users'].append(user_dict)

        return jsonify(summary_dict)

@api_views.route('/users/<user_id>', methods=['GET', 'DELETE'])
@login_required
@admin_required
def specified_user(user_id):
    """
    GET:    Fetch full user data set, including all time-segments.
    PATCH:  Modify user data?
    DELETE: Delete this user.
    Only admins are allowed to modify user accounts.
    """

    user = User.query.get_or_404(user_id.upper())

    if request.method == 'GET':
        # Return full user information along with every associated TimeSegment

        user_dict = user.to_dict()
        user_dict['segments'] = [t.to_dict for t in user.time_segments]

        return jsonify(user_dict)

    elif request.method == 'DELETE':
        # delete this user and associated data
        db.session.delete(user)
        db.session.commit()

        return 'success', 200, {'Content-Type': 'text/plain'}

@api_views.route('/users/<user_id>/hours', methods=['POST', 'GET'])
@login_required
def specified_user_hours(user_id):
    """
    POST:   Fill or delete a time segment for this user.
    GET:    Fetch all time-segments in range specified by URL query.
    Only this user can modify their hours.
    """

    user = User.query.get_or_404(user_id.upper())

    if request.method == 'POST':
        # Users can only modify their own hours.
        if not user.id.upper() == session['CAS_USERNAME'].upper():
            abort(403)

        # Create new segment, return url with id

        request_dict = request.get_json(silent=True)

        # Check that the request parameters are valid
        if not request_dict or 'start' not in request_dict or 'end' not in request_dict:
            abort(400)

        delete = request_dict['delete']
        # Order shouldn't matter as long as one is before the other
        segment_start = min(int(request_dict['start']), int(request_dict['end']))
        segment_end = max(int(request_dict['start']), int(request_dict['end']))

        if not segment_start < segment_end:
            abort(400)

        # TODO: Find any segments that intersect this one, use to create one segment
        # Segments are added sequentially. They may be adjacent, but may not overlap.
        # If 'Add' a new segment intersects with an existing segment, the new takes precedence and the old is trimmed.
        # 'Delete' is a segment (not id) of time during which there should be no segment (trim).

        if delete:
            segments = user.time_segments.filter(TimeSegment.start_timestamp <= segment_end,
                                                 TimeSegment.end_timestamp >= segment_start)

            # Trim each segment so it no longer intersects the specified period
            for s in segments:
                if s.start_timestamp >= segment_start and s.end_timestamp <= segment_end:
                    # Segment is fully inside, delete it
                    user.time_segments.remove(s)

                elif segment_start > s.start_timestamp and segment_end < s.end_timestamp:
                    new_segment_1 = TimeSegment(start_timestamp=s.start_timestamp, end_timestamp=segment_start - 1)
                    new_segment_2 = TimeSegment(start_timestamp=segment_end + 1, end_timestamp=s.end_timestamp)
                    user.time_segments.remove(s)
                    user.time_segments.append(new_segment_1)
                    user.time_segments.append(new_segment_2)

                elif s.start_timestamp < segment_start:
                    # end of segment intersects, trim it
                    s.end_timestamp = segment_start - 1

                elif s.end_timestamp > segment_end:
                    # start of segment intersects, trim it
                    s.start_timestamp = segment_end + 1

            user.modified = datetime.utcnow()
            db.session.commit()

            return 'success', 200, {'Content-Type': 'text/plain'}

        else:
            # Offset by 1 to get adjacent segments as well
            segments = user.time_segments.filter(TimeSegment.start_timestamp - 1 <= segment_end,
                                                 TimeSegment.end_timestamp + 1 >= segment_start)

            # Merge with segments contained by or adjacent to this one
            # Delete any segment contained, shift upper and lower bound to those of adjacent

            for s in segments:
                if s.start_timestamp >= segment_start and s.end_timestamp <= segment_end:
                    # Segment is fully inside, delete it
                    user.time_segments.remove(s)

                elif s.start_timestamp < segment_start:
                    # end of segment intersects, shift this lower bound
                    segment_start = s.start_timestamp
                    user.time_segments.remove(s)

                elif s.end_timestamp > segment_end:
                    # start of segment intersects, shift this upper bound
                    segment_end = s.end_timestamp
                    user.time_segments.remove(s)

            new_segment = TimeSegment(start_timestamp=segment_start, end_timestamp=segment_end)
            user.time_segments.append(new_segment)

            user.modified = datetime.utcnow()
            db.session.commit()
            # Respond with location header for new segment
            return jsonify(), 201, {'location': '/users/{0}/hours/{1}'.format(user.id, new_segment.id)}

    elif request.method == 'GET':
        # This user or any admin can get hours
        if not user.id.upper() == session['CAS_USERNAME'].upper() and not is_admin():
            abort(403)

        # Return this user's time segments in range specified by args

        selection_start_timestamp = request.args.get('start')
        selection_end_timestamp = request.args.get('end')

        # Select all TimeSegments that intersect this selection. TODO: <= or <?
        time_segments = user.time_segments.filter(TimeSegment.start_timestamp <= selection_end_timestamp,
                                                  TimeSegment.end_timestamp >= selection_start_timestamp)

        segments_dict = {
            'modified': user.modified.isoformat(),
            'time_segments': [t.to_dict() for t in time_segments]
        }

        return jsonify(segments_dict)

@api_views.route('/users/<user_id>/hours/<segment_id>', methods=['GET', 'DELETE'])
def specified_user_hours_segment(user_id, segment_id):
    """
    GET:    Fetch time segment specified by segment_id.
    DELETE: Delete time segment specified by segment_id.
    Only this user can modify their hours.
    """

    user = User.query.get_or_404(user_id.upper())

    # Make sure this time segment exists.
    # TODO: Make sure time segments are stored per user?
    segment = TimeSegment.query.get_or_404(segment_id)

    if not user.id.upper() == session['CAS_USERNAME'].upper():
        abort(403)

    if request.method == 'GET':
        # Get segment <segment_id>

        return jsonify(segment.to_dict())

    elif request.method == 'DELETE':
        # Delete segment <segment_id>
        user.time_segments.remove(segment)
        # db.session.delete(segment)
        db.session.commit()

        return 'success', 200, {'Content-Type': 'text/plain'}

@api_views.route('/users/<user_id>/templates', methods=['POST', 'GET', 'DELETE'])
@login_required
def specified_user_templates(user_id):
    """
    POST:   Create a new template with specified segments.
    GET:    Fetch all templates for this user.
    DELETE: Delete template with specified id.
    """

    user = User.query.get_or_404(user_id.upper())

    if not user.id.upper() == session['CAS_USERNAME'].upper():
        abort(403)

    if request.method == 'POST':
        request_dict = request.get_json(silent=True)

        if not request_dict or 'name' not in request_dict or 'segments' not in request_dict or not len(
                request_dict['segments']) > 0:
            abort(400)

        new_template = Template(name=request_dict['name'])

        for seg in request_dict['segments']:
            new_template.template_segments.append(TemplateSegment(start_time=int(seg[0]), end_time=int(seg[1])))

        user.templates.append(new_template)
        db.session.commit()

        return jsonify(), 201, {'location': '/users/{0}/templates/{1}'.format(user.id, new_template.id)}

    elif request.method == 'GET':
        return jsonify({'templates': {t.id: t.to_dict() for t in user.templates}})

@api_views.route('/users/<user_id>/templates/<template_id>', methods=['GET', 'DELETE'])
@login_required
def specified_user_specified_template(user_id, template_id):
    """
    GET:    Fetch the template with this id.
    DELETE: Delete the template with this id.
    """

    user = User.query.get_or_404(user_id.upper())

    if not user.id.upper() == session['CAS_USERNAME'].upper():
        abort(403)

    template = Template.query.get_or_404(template_id)

    if request.method == 'GET':
        return jsonify(template.to_dict())

    elif request.method == 'DELETE':
        user.templates.remove(template)
        # db.session.delete(template)
        db.session.commit()

        return 'success', 200, {'Content-Type': 'text/plain'}

@api_views.route('/settings', methods=['GET', 'POST'])
@login_required
@admin_required
def admin_settings_load():
    if request.method == 'GET':
        response_dict = {}
        response_dict['admins'] = [a.lower() for a in config['admins']]  # (', '.join(config['admins'])).lower()
        response_dict['period_duration'] = config['period_duration']
        response_dict['valid_period_start'] = config['valid_period_start']
        response_dict['view_days'] = config['view_days']
        response_dict['slot_increment'] = config['slot_increment']
        response_dict['slot_first_start'] = config['slot_first_start']
        response_dict['slot_last_start'] = config['slot_last_start']

        return jsonify(response_dict)

    elif request.method == 'POST':
        request_dict = request.get_json(silent=True)

        if not request_dict:
            abort(400)

        new_config = config

        # TODO: Validate values
        if 'admins' in request_dict:
            new_config['admins'] = [a.upper() for a in request_dict['admins']]

        if 'period_duration' in request_dict:
            new_config['period_duration'] = int(request_dict['period_duration'])

        if 'valid_period_start' in request_dict:
            new_config['valid_period_start'] = request_dict['valid_period_start']

        if 'view_days' in request_dict:
            new_config['view_days'] = int(request_dict['view_days'])

        if 'slot_increment' in request_dict:
            new_config['slot_increment'] = int(request_dict['slot_increment'])

        if 'slot_first_start' in request_dict:
            new_config['slot_first_start'] = request_dict['slot_first_start']

        if 'slot_last_start' in request_dict:
            new_config['slot_last_start'] = request_dict['slot_last_start']

        set_config(new_config)

        return 'success', 200, {'Content-Type': 'text/plain'}


text:
package com.salesmanager.core.business.content.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.UniqueConstraint;
import javax.validation.Valid;

import org.hibernate.validator.constraints.NotEmpty;

import com.salesmanager.core.business.common.model.audit.AuditListener;
import com.salesmanager.core.business.common.model.audit.AuditSection;
import com.salesmanager.core.business.generic.model.SalesManagerEntity;
import com.salesmanager.core.business.merchant.model.MerchantStore;
import com.salesmanager.core.constants.SchemaConstant;

@Entity
@EntityListeners(value = AuditListener.class)
@Table(name = "CONTENT", schema= SchemaConstant.SALESMANAGER_SCHEMA,uniqueConstraints=
    @UniqueConstraint(columnNames = {"MERCHANT_ID", "CODE"}) )
public class Content extends SalesManagerEntity<Long, Content> implements Serializable {

	private static final long serialVersionUID = 1772757159185494620L;

	@Id
	@Column(name = "CONTENT_ID", unique=true, nullable=false)
	@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CONTENT_SEQ_NEXT_VAL")
	@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
	private Long id;

	@Embedded
	private AuditSection auditSection = new AuditSection();

	@Valid
	@OneToMany(mappedBy="content", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	private List<ContentDescription> descriptions = new ArrayList<ContentDescription>();

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="MERCHANT_ID", nullable=false)
	private MerchantStore merchantStore;

	@NotEmpty
	@Column(name="CODE", length=100, nullable=false)
	private String code;

	@Column(name = "VISIBLE")
	private boolean visible;

	@Column(name = "CONTENT_POSITION", length=10, nullable=true)
	@Enumerated(value = EnumType.STRING)
	private ContentPosition contentPosition;

	//Used for grouping
	//BOX, SECTION, PAGE
	@Column(name = "CONTENT_TYPE", length=10, nullable=true)
	@Enumerated(value = EnumType.STRING)
	private ContentType contentType;

	@Column(name = "SORT_ORDER")
	private Integer sortOrder = 0;

	@Override
	public Long getId() {
		return this.id;
	}

	@Override
	public void setId(Long id) {
		this.id = id;

	}

	public void setAuditSection(AuditSection auditSection) {
		this.auditSection = auditSection;
	}

	public AuditSection getAuditSection() {
		return auditSection;
	}

	public MerchantStore getMerchantStore() {
		return merchantStore;
	}

	public void setMerchantStore(MerchantStore merchantStore) {
		this.merchantStore = merchantStore;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public boolean isVisible() {
		return visible;
	}

	public void setVisible(boolean visible) {
		this.visible = visible;
	}

	public List<ContentDescription> getDescriptions() {
		return descriptions;
	}

	public void setDescriptions(List<ContentDescription> descriptions) {
		this.descriptions = descriptions;
	}

	public void setContentType(ContentType contentType) {
		this.contentType = contentType;
	}

	public ContentType getContentType() {
		return contentType;
	}

	public ContentDescription getDescription() {

		if(this.getDescriptions()!=null && this.getDescriptions().size()>0) {
			return this.getDescriptions().get(0);
		}

		return null;

	}

	public void setSortOrder(Integer sortOrder) {
		this.sortOrder = sortOrder;
	}

	public Integer getSortOrder() {
		return sortOrder;
	}

	public void setContentPosition(ContentPosition contentPosition) {
		this.contentPosition = contentPosition;
	}

	public ContentPosition getContentPosition() {
		return contentPosition;
	}

}


text:
from __future__ import annotations

import pytest

from pants.backend.helm.utils.yaml import YamlPath

@pytest.mark.parametrize(
    "path, is_absolute, is_root, is_index",
    [
        ("/", True, True, False),
        ("/0", True, False, True),
        ("/path", True, False, False),
        ("0", False, False, True),
        ("path", False, False, False),
    ],
)
def test_yaml_path_parser(path: str, is_absolute: bool, is_root: bool, is_index: bool) -> None:
    parsed = YamlPath.parse(path)

    assert parsed.is_absolute == is_absolute
    assert parsed.is_root == is_root
    assert parsed.is_index == is_index

    if parsed.is_root:
        assert not parsed.parent

        nested = parsed / "nested"

        assert not nested.is_root
        assert nested.parent == parsed

    if not parsed.is_absolute:
        absolute = YamlPath.root() / parsed

        assert absolute.is_absolute

    if parsed.is_index:
        index = YamlPath.index(int(parsed.current))

        assert not index.is_absolute
        assert index.is_index
        assert index.current == parsed.current


text:
<?php
//require 'core/common.php';
require 'vendor/autoload.php';

// Start session
session_start();

function send_forgot_email($email,$id,$config, $db) {
   $time = time();
   $rand = getrandnum(10);
   $forgot = md5($time.'_:_'.$rand.'_:_'.$email);

   $db->where("user_id", addslashes($id));
   $db->update("users", Array("forgot" => addslashes($forgot)));
   echo $db->getLastQuery();

   $mail = new \PHPMailer();

   if($config['email.type'] == 'smtp') {
      $mail->IsSMTP();
      $mail->SMTPAuth = true;
      $mail->Username = $config['email.smtp.user'];
      $mail->Password = $config['email.smtp.pass'];
      $mail->Host = $config['email.smtp.host'];
   } else if ($config['email.type'] == 'sendmail') {
      $mail->IsSendmail();
   } else {
      $mail->IsMail();
   }

   $mail->FromName = $config['site.title'];
   $mail->From = $config['site.admin_email'];
   $mail->AddAddress($email);

   $mail->Subject = $config['site.title'] . ": Forgot Password";
   $mail->Body = "To reset your password please click the link below:\n\n".$config['site.base_url'].$config['site.base_path']."/login.php?forgot=".$forgot."&r=".$rand."&e=".$email."&t=".$time;
   $mail->IsHTML(false);
   $mail->Send();
}

$config = new HackerNews\Config('config.ini');
$base_url = $config['site.base_url'] . $config['site.base_path'] . '/';
$db = HackerNews\Common::database($config);

// Set number of errors to 0
$errors = 0;

// Set default error message
$login_error = '';

if(isset($_POST['forgot'])) $_GET['forgot'] = $_POST['forgot'];
if(isset($_POST['r'])) $_GET['r'] = $_POST['r'];
if(isset($_POST['e'])) $_GET['e'] = $_POST['e'];
if(isset($_POST['t'])) $_GET['t'] = $_POST['t'];

// Check if they are using a forgot password link
if(isset($_GET['forgot'])) {
   $db->where("email", HackerNews\Common::validate_input($_GET['e']));
   $forgot = $db->getOne("users", Array("user_id", "forgot", "username"));

   if($_GET['forgot'] == $forgot['forgot']) {
      if($_GET['forgot'] == md5($_GET['t'].'_:_'.$_GET['r'].'_:_'.$_GET['e'])) {
         // Check that the link hasn't timed out (30 minutes old)
         if($_GET['t'] > (time()-108000)) {
            $forgot_error = '';

            if(isset($_POST['password'])) {
               if( (strlen($_POST['password']) < 4) OR (strlen($_POST['password']) > 16) ) {
                  $forgot_error = "Password should be between 4 to 16 characters";
               } else {
                  if($_POST['password'] == $_POST['password2']) {
                     $db->where("user_id", HackerNews\Common::validate_input($forgot["user_id"]));
                     $db->update("users", Array("forgot" => ''));

                     $db->where("user_id", HackerNews\Common::validate_input($forgot["user_id"]));
                     $db->update("users", Array("password" => md5($_POST['password'])));

                     $twig = new HackerNews\TwigEngine($config);
                     echo $twig->setVars(array('username' => $forgot['username'], 'mode' => 'password_reset_success'))->render('login');

                     exit;
                  } else {
                     $twig = new HackerNews\TwigEngine($config);
                     echo $twig->setVars(array('error_message' => 'Passwords do not match. Try again', 'mode' => 'error'))->render('login');
                  }
               }
            }

            $twig = new HackerNews\TwigEngine($config);
            echo $twig->setVars(array(
               'username' => $forgot['username'],
               'forgot' => $_GET['forgot'],
               'r' => $_GET['r'],
               'e' => $_GET['e'],
               't' => $_GET['t'],
               'mode' => 'password_reset'
            ))->render('login');

            exit;
         } else {
            $twig = new HackerNews\TwigEngine($config);
            echo $twig->setVars(array('error_message' => 'Passwords code expired. Please try again', 'mode' => 'error'))->render('login');
         }
      } else {
         $twig = new HackerNews\TwigEngine($config);
         echo $twig->setVars(array('error_message' => 'Invalid passwords code. Please try again', 'mode' => 'error'))->render('login');
      }
   } else {
      $twig = new HackerNews\TwigEngine($config);
      echo $twig->setVars(array('error_message' => 'Invalid passwords code. Please try again', 'mode' => 'error'))->render('login');
   }

   exit;
}

// Check if they are trying to retrieve their email
if(isset($_POST['email']) && ($_POST['email'] != ''))
{

   $db->where("email", HackerNews\Common::validate_input($_POST['email']));
   $user_id = $db->getValue("users", "user_id");
   print_r($user_id);

   // Check if the email address exists
   if($user_id) {
      // Send the email
      send_forgot_email($_POST['email'],$user_id,$config, $db);

      $twig = new HackerNews\TwigEngine($config);
      echo $twig->setVars(array('mode' => 'email_sent'))->render('login');

   } else {
      $twig = new HackerNews\TwigEngine($config);
      echo $twig->setVars(array('error_message' => "That email does not exist in our system. Please retry.", 'mode' => 'error'))->render('login');

      exit;
   }
}

$login_error = '';
// Check if a user has submitted the form
if(isset($_POST['username'])) {
   if(!isset($_POST['redirect'])) {
      $_POST['redirect'] = '';
   }

   // Lookup the users table for that user
   $db->where("username", HackerNews\Common::validate_input($_POST['username']));
   $db->where("password", HackerNews\Common::validate_input(md5($_POST['password'])));
   $userinfo = $db->getOne("users", Array("user_id", "remember", "commentst", "status"));
   //echo $db->getLastQuery();

   // The submitted details are valid
   if(isset($userinfo["user_id"])) {
      if($userinfo["status"] == '0') {
         $login_error = "This account is not configured";
      } else {
         if(isset($_POST['remember'])) {
            $rem = array();
            $rem['uid'] = $userinfo["user_id"];
            $rem['username'] = $_POST['username'];
            $rem['rem'] = $userinfo["remember"];
            $rem['tries'] = 0;

            setcookie($config['cookies.name'],serialize($rem),time()+$config['cookies.time']);
         }

         $_SESSION['hn_login']['id'] = $userinfo["user_id"];
         $_SESSION['hn_login']['name'] = $_POST['username'];
         $_SESSION['hn_login']['comm'] = $userinfo["commentst"];
         $_SESSION['voted'] = array();

         if($_POST['redirect']) {
            header('Location: '.$config['site_url'].urldecode($_POST['redirect']));
         } else {
            header('Location: '.$config['site_url'].'index.php');
         }
         exit;
      }
   } else {
      $login_error = "Password incorrect";
   }
}

if(isset($_POST['redirect'])) $_GET['redirect'] = $_POST['redirect'];

$twig = new HackerNews\TwigEngine($config);
echo $twig->setVars(array('redirect' => $_GET['redirect'], 'mode' => 'login', 'login_error' => $login_error))
   ->render('login');
?>


text: HTML & CSS homework for Telerik Academy


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

import java.io.File;

/**
 *
 * @author dark
 */
public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Zip z = new Zip();
        //Object[] r = z.validarArchivoGrup(new File("/home/dark/Documentos/Elion_unificados.zip"));
        //Object[] r = z.validarArchivoGrup(new File("/home/dark/proyectos/Modulos_test/Modulo1.zip"));

        File file = new File("/home/dark/Documents/Tesis-Plinio/InterfazIntegradora/Core/src/ima/delete.png");
        System.out.println(file.exists()+"    ");

    }

}


text: Vim configuration file


text:
package com.taobao.tddl.common.properties;

import com.taobao.tddl.common.exception.TddlRuntimeException;
import com.taobao.tddl.common.exception.code.ErrorCode;

/**
 * A ConfigParam embodies the metadata about a JE configuration parameter: the
 * parameter name, default value, and a validation method. Validation can be
 * done in the scope of this parameter, or as a function of other parameters.
 */
public class ConfigParam {

    protected String      name;
    private final String  defaultValue;
    private final boolean mutable;
    private boolean       isMultiValueParam;

    /**
     * Create a String parameter.
     */
    public ConfigParam(String configName, String configDefault, boolean mutable) throws IllegalArgumentException{
        if (configName == null) {
            name = null;
        } else {
            /**
             * For Multi-Value params (i.e. those whose names end with ".#"),
             * strip the .# off the end of the name before storing and flag it
             * with isMultiValueParam=true.
             */
            int mvFlagIdx = configName.indexOf(".#");
            if (mvFlagIdx < 0) {
                name = configName;
                isMultiValueParam = false;
            } else {
                name = configName.substring(0, mvFlagIdx);
                isMultiValueParam = true;
            }
        }

        defaultValue = configDefault;
        this.mutable = mutable;

        /* Check that the name and default value are valid */
        validateName(name);
        validateValue(configDefault);

        /* Add it the list of supported environment parameters. */
        ConnectionParams.addSupportedParam(this);
    }

    /*
     * Return the parameter name of a multi-value parameter. e.g.
     * "je.rep.remote.address.foo" => "je.rep.remote.address"
     */
    public static String multiValueParamName(String paramName) {
        int mvParamIdx = paramName.lastIndexOf('.');
        if (mvParamIdx < 0) {
            return null;
        }
        return paramName.substring(0, mvParamIdx);
    }

    /*
     * Return the label of a multi-value parameter. e.g.
     * "je.rep.remote.address.foo" => foo.
     */
    public static String mvParamIndex(String paramName) {
        int mvParamIdx = paramName.lastIndexOf('.');
        return paramName.substring(mvParamIdx + 1);
    }

    public String getName() {
        return name;
    }

    public String getDefault() {
        return defaultValue;
    }

    public boolean isMutable() {
        return mutable;
    }

    public boolean isMultiValueParam() {
        return isMultiValueParam;
    }

    /**
     * A param name can't be null or 0 length
     */
    private void validateName(String name) throws IllegalArgumentException {
        if ((name == null) || (name.length() < 1)) {
            throw new TddlRuntimeException(ErrorCode.ERR_CONFIG,
                "A configuration parameter name can't be null or 0 length");
        }
    }

    /**
     * Validate your value. (No default validation for strings.) May be
     * overridden for (e.g.) Multi-value params.
     *
     * @throws IllegalArgumentException via XxxConfig.setXxx methods and
     * XxxConfig(Properties) ctor.
     */
    public void validateValue(String value) throws IllegalArgumentException {

    }

    @Override
    public String toString() {
        return name;
    }
}


text:
Replace me with a description of changes. Include screenshots where appropriate.

## Checklist

- [ ] \*Added unit tests
- [ ] \*Added a code reviewer
- [ ] Added changes to `/projects/swimlane/ngx-ui/CHANGELOG.md` under HEAD (Unreleased)
- [ ] Updated the demo page
- [ ] Included screenshots of visual changes

_\*required_


text:
package com.echomap.kqf.profile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.echomap.kqf.data.FormatDao;
import com.echomap.kqf.profile.persist.ProfileBiz;
import com.echomap.kqf.profile.persist.ProfileData;
import com.echomap.kqf.profile.persist.ProfilePersist;
import com.echomap.kqf.profile.persist.ProfilePersistV1;
import com.echomap.kqf.profile.persist.ProfilePersistV2;
import com.echomap.kqf.two.gui.EmptyTwoClass;

public class ProfileManager {
	private final static Logger LOGGER = LogManager.getLogger(ProfileManager.class);

	private final Preferences userPrefsV1;
	private final Preferences userPrefsV2;
	String appVersion = null;
	private final List<String> messages = new ArrayList<>();
	private Exception error = null;
	private boolean wasError = false;
	private List<Profile> profiles = new ArrayList<>();
	String currentVersion = null;
	Profile profileSavedForCopy = null;

	public ProfileManager() {
		// try {
		// final Class oldPackage =
		// Class.forName("com.echomap.kqf.two.gui.KQFCtrl");
		// userPrefsV1 = Preferences.userNodeForPackage(oldPackage);
		// } catch (ClassNotFoundException e) {
		// userPrefsV1 = Preferences.userNodeForPackage(KQFCtrl.class);
		// e.printStackTrace();
		// }
		// userPrefsV1 = Preferences.userNodeForPackage(KQFCtrl.class);
		userPrefsV1 = Preferences.userNodeForPackage(EmptyTwoClass.class);
		userPrefsV2 = Preferences.userNodeForPackage(ProfileBiz.class);
		// this.appVersion = appVersion;
		resetData();
	}

	// public ProfileManager(final Preferences userPrefsV1) {
	// this.userPrefsV1 = userPrefsV1;
	// userPrefsV2 = Preferences.userNodeForPackage(ProfileBiz.class);
	// // this.appVersion = appVersion;
	// resetData();
	// }

	public ProfileManager(final Preferences userPrefsV1, final String appVersion) {
		this.userPrefsV1 = userPrefsV1;
		userPrefsV2 = Preferences.userNodeForPackage(ProfilePersist.class);
		this.appVersion = appVersion;
		resetData();
	}

	public void setAppVersion(final String appVersion) {
		this.appVersion = appVersion;
	}

	public List<String> getMessages() {
		return messages;
	}

	public boolean isWasError() {
		return wasError;
	}

	public Exception getError() {
		return error;
	}

	public List<Profile> getProfiles() {
		return profiles;
	}

	/**
	 *
	 * @return
	 */
	public boolean loadProfileData() { // throws BackingStoreException {
		LOGGER.debug("loadProfileData: Called");
		resetData();

		LOGGER.debug("Check status of Profile V1");
		int v1Status = checkProfileStatus(userPrefsV1);
		LOGGER.debug("Check status of Profile V2");
		int v2Status = checkProfileStatus(userPrefsV2);
		LOGGER.info("Profile Data V1 Status = " + v1Status);
		LOGGER.info("Profile Data V2 Status = " + v2Status);

		// try to load ProfilePrefsV2, if nothing, load 1
		if (v2Status == 0) {
			// Load V1 data for testing
			// FUTURE: offer to import?
			final ProfilePersistV1 persist = new ProfilePersistV1(userPrefsV1);
			persist.loadProfiles();
			LOGGER.debug("Persist error? " + persist.isWasError());
			final List<String> mgs = persist.getMessages();
			if (mgs != null) {
				for (String msg : mgs) {
					LOGGER.debug("Persist msg?" + msg);
				}
			}
			final List<ProfileData> profileDataList = persist.getProfiles();
			for (ProfileData profileData : profileDataList) {
				LOGGER.debug("Persist profileData=" + profileData);
			}

			// Import from V1 to V2\
			final ProfilePersistV2 persist2 = new ProfilePersistV2();
			for (ProfileData profileData : profileDataList) {
				final Profile profile = persist2.convertFromV1toV2(profileData);
				profiles.add(profile);
			}
			return true;
		} else if (v2Status == 1) {
			LOGGER.info("Load V2 data");
			// Load V2
			final ProfilePersistV2 persist2 = new ProfilePersistV2();
			final List<Profile> profileDataList = persist2.getProfiles();
			for (Profile profile : profileDataList) {
				LOGGER.debug("Persist profile=" + profile);
				profiles.add(profile);
			}
			return true;
		}
		return false;
	}

	private int checkProfileStatus(final Preferences userPrefs) {
		boolean outOfDate = false;
		int status = 0;

		// Check Profile Version #1
		try {
			if (userPrefsV1 != null && userPrefs.keys() != null) {
				LOGGER.debug("loadProfileData: has userPrefs, checking");
				final String currentVerS = userPrefsV1.get("version", null);
				LOGGER.debug("loadProfileData: userPrefs: currentVerS = " + currentVerS);
				if (!StringUtils.isBlank(currentVerS)) {
					LOGGER.debug("loadProfileData: currentVerS: '" + currentVerS + "'");
					final Integer currentVer = Integer.valueOf(currentVerS);
					final Integer appVer = Integer.valueOf(appVersion);
					if (currentVer < appVer) {
						outOfDate = true;
						status = 0;
					}
				} else {
					outOfDate = true;
					status = 0;
				}

				final String[] prefkeys = userPrefs.childrenNames();
				if (prefkeys != null && prefkeys.length > 0)
					status = 1;

				if (prefkeys != null && prefkeys.length > 0) {
					for (final String str1 : prefkeys) {
						LOGGER.debug("loadProfiles: str1 = '" + str1 + "'");
					}
				}
			}
		} catch (NumberFormatException e) {
			LOGGER.warn("Error in V1's version info='" + userPrefs.get("version", null) + "'");
			e.printStackTrace();
		} catch (BackingStoreException e) {
			LOGGER.warn("Error with loading userPrefs data");
			e.printStackTrace();
		}
		LOGGER.debug("loadProfileData: outOfDate = " + outOfDate);
		LOGGER.debug("loadProfileData: status = " + status);
		return status;
	}

	private void resetStatus() {
		this.wasError = false;
		this.messages.clear();
	}

	private void resetData() {
		this.wasError = false;
		this.profiles.clear();
		this.messages.clear();
	}

	public void setupDao(final FormatDao formatDao, final String selectedProfileKey) throws IOException {
		LOGGER.debug("setupDao: Called");
		final Profile selectedProfile = selectProfileByMainTitle(selectedProfileKey);
		setupDao(formatDao, selectedProfile);
	}

	public void setupDao(final FormatDao formatDao, final Profile selectedProfile) throws IOException {
		LOGGER.debug("setupDao: Called");

		if (selectedProfile == null) {
			LOGGER.debug("Please select a profile before running!!");
			//
			throw new IOException("Please select a profile before running!!");
			// return;
		}
		final ProfilePersistV2 persist = new ProfilePersistV2();
		persist.setupDao(formatDao, selectedProfile, appVersion);
	}

	public Profile selectProfileByMainTitle(final String profileKey) {
		Profile selectedProfile = null;
		final List<Profile> profiles = getProfiles();
		for (Profile profile : profiles) {
			if (profile.getMainTitle().trim().compareTo(profileKey.trim()) == 0) {
				selectedProfile = profile;
				break;
			}
		}
		return selectedProfile;
	}

	public Profile selectProfileByKey(final String profileKey) {
		Profile selectedProfile = null;
		final List<Profile> profiles = getProfiles();
		for (Profile profile : profiles) {
			if (profile.getKey().compareTo(profileKey) == 0) {
				selectedProfile = profile;
				break;
			}
		}
		return selectedProfile;
	}

	public void saveProfileData(final Profile profile) {
		LOGGER.debug("loadProfileData: Called");
		resetStatus();

		LOGGER.debug("Check status of Profile V1");
		int v1Status = checkProfileStatus(userPrefsV1);
		LOGGER.debug("Check status of Profile V2");
		int v2Status = checkProfileStatus(userPrefsV2);
		LOGGER.info("Profile Data V1 Status = " + v1Status);
		LOGGER.info("Profile Data V2 Status = " + v2Status);

		// try to load ProfilePrefsV2, if nothing, load 1
		if (v2Status == 0) {
			// Import from V1 to V2\
			final ProfilePersistV2 persist2 = new ProfilePersistV2();
			final ProfileData profile1 = persist2.convertFromV2toV1(profile);

			// Load V1 data for testing
			// FUTURE: offer to import?
			final ProfilePersistV1 persist = new ProfilePersistV1(userPrefsV1);
			try {
				persist.saveProfiles(profile1);
				LOGGER.debug("Persist error? " + persist.isWasError());
				final List<String> mgs = persist.getMessages();
				if (mgs != null) {
					for (String msg : mgs) {
						LOGGER.debug("Persist msg?" + msg);
					}
				}
			} catch (BackingStoreException e) {
				e.printStackTrace();
				this.wasError = true;
				this.messages.add(e.getMessage());
				this.error = e;
			}
		} else {
			// Load V2
			// Check Version
		}
		loadProfileData();// TODO ix so refresh not necessary
		LOGGER.debug("loadProfileData: Done");
	}

	public void deleteProfile(final Profile profile) {
		LOGGER.debug("deleteProfileByKey: Called");
		resetStatus();

		LOGGER.debug("Check status of Profile V1");
		int v1Status = checkProfileStatus(userPrefsV1);
		LOGGER.debug("Check status of Profile V2");
		int v2Status = checkProfileStatus(userPrefsV2);
		LOGGER.info("Profile Data V1 Status = " + v1Status);
		LOGGER.info("Profile Data V2 Status = " + v2Status);

		// try to load ProfilePrefsV2, if nothing, load 1
		if (v2Status == 0) {

			final ProfilePersistV1 persist = new ProfilePersistV1(userPrefsV1);
			try {
				persist.deleteProfile(profile.getKey());
				LOGGER.debug("Persist error? " + persist.isWasError());
				final List<String> mgs = persist.getMessages();
				if (mgs != null) {
					for (String msg : mgs) {
						LOGGER.debug("Persist msg?" + msg);
					}
				}
			} catch (BackingStoreException e) {
				e.printStackTrace();
				this.wasError = true;
				this.messages.add(e.getMessage());
				this.error = e;
			}
		} else {
			// Load V2
			// Check Version
		}
		loadProfileData();// TODO ix so refresh not necessary
		LOGGER.debug("deleteProfileByKey: Done");
	}

	public void renameProfile(final Profile profile, final String newKey) {
		LOGGER.debug("renameProfile: Called");
		resetStatus();

		LOGGER.debug("Check status of Profile V1");
		int v1Status = checkProfileStatus(userPrefsV1);
		LOGGER.debug("Check status of Profile V2");
		int v2Status = checkProfileStatus(userPrefsV2);
		LOGGER.info("Profile Data V1 Status = " + v1Status);
		LOGGER.info("Profile Data V2 Status = " + v2Status);

		// try to load ProfilePrefsV2, if nothing, load 1
		if (v2Status == 0) {

			final ProfilePersistV2 persist2 = new ProfilePersistV2();
			final ProfilePersistV1 persist = new ProfilePersistV1(userPrefsV1);
			try {
				final ProfileData profileData = persist2.convertFromV2toV1(profile);
				persist.renameProfile(profileData, profile.getKey(), newKey);
				LOGGER.debug("Persist error? " + persist.isWasError());
				final List<String> mgs = persist.getMessages();
				if (mgs != null) {
					for (final String msg : mgs) {
						LOGGER.debug("Persist msg?" + msg);
					}
				}
			} catch (BackingStoreException e) {
				e.printStackTrace();
				this.wasError = true;
				this.messages.add(e.getMessage());
				this.error = e;
			}
		} else {
			// Load V2
			// Check Version
		}
		loadProfileData();// TODO ix so refresh not necessary
		LOGGER.debug("renameProfile: Done");
	}

	//
	public Profile createDefaultProfile(final String inputKey, final Properties appProps) {
		LOGGER.debug("createDefaultProfile: Called ");
		final Profile profile = new Profile();
		profile.setKey(inputKey);
		//
		profile.setFmtMode(loadPropFromAppOrDefault("defaultOutputFormatting", "", appProps));
		profile.setOutputEncoding(loadPropFromAppOrDefault("defaultEncoding", "", appProps));

		final String sceneM = loadPropFromAppOrDefault("sceneMain", "scene, subscene", appProps);
		final String sceneC = loadPropFromAppOrDefault("sceneCoalate", "description, scene", appProps);
		final String outC = loadPropFromAppOrDefault("outlineCompress", "subscene, outlinedata, outlinesub, suboutline",
				appProps);
		final String outE = loadPropFromAppOrDefault("outineExpand", "outline, scene", appProps);
		profile.setDocTagsOutlineTags(outE);
		profile.setDocTagsOutlineCompressTags(outC);
		profile.setDocTagsSceneTags(sceneM);
		profile.setDocTagsSceneCompressTags(sceneC);

		final String regExpChp = loadPropFromAppOrDefault("regexpChapterText", "", appProps);
		final String regExpSec = loadPropFromAppOrDefault("regexpSectionText", "", appProps);
		profile.setRegexpChapter(regExpChp);
		profile.setRegexpSection(regExpSec);
		//
		LOGGER.debug("createDefaultProfile: Done ");
		return profile;
	}

	private String loadPropFromAppOrDefault(final String key, final String defaultValue, final Properties appProps) {
		if (appProps != null) {
			final String value = appProps.getProperty(key);
			return value;
		}
		return defaultValue;
	}

	public void selectProfileForCopy(final Profile selectedProfile) {
		this.profileSavedForCopy = selectedProfile;
	}

	public void copyProfileFromCopy(final Profile selectedProfile) throws IOException {
		//
		if (this.profileSavedForCopy == null) {
			throw new IOException("No profile selected for copy");
		}
		//
		// selectedProfile.setAppendUnderscoreToPrefix(appendUnderscoreToPrefix);
		//
		Profile profile = selectedProfile;
		Profile profileData = profileSavedForCopy;

		// <Main Section>
		// profile.setKey(profileData.getKey());
		profile.setMainTitle(profileData.getMainTitle());
		profile.setSubTitle(profileData.getSubTitle());
		profile.setSeriesTitle(profileData.getSeriesTitle());
		profile.setVolume(profileData.getVolume());
		profile.setKeywords(profileData.getKeywords());

		// profile.setInputFile(setupValue(profileData, "inputFile", ""));
		// profile.setInputFilePrefix(setupValue(profileData, "inputFilePrefix", ""));
		profile.setAppendUnderscoreToPrefix(profileData.isAppendUnderscoreToPrefix());

		// <RegEx Section>
		profile.setRegexpChapter(profileData.getRegexpChapter());
		profile.setRegexpSection(profileData.getRegexpSection());

		// <Word Counter Section>
		// profile.setOutputCountFile(profileData.getOutputCountFile());

		// <Formatting Section>
		// profile.setOutputFormatSingleFile(profileData.getOutputFormatSingleFile());
		// profile.setOutputFormatChpHtmlDir(profileData.getOutputFormatChpHtmlDir());
		// profile.setOutputFormatChpTextDir(profileData.getOutputFormatChpTextDir());

		profile.setCbRemoveDiv(profileData.isCbRemoveDiv());
		profile.setCbCenterStars(profileData.isCbCenterStars());
		profile.setCbDropCapChapters(profileData.isCbDropCapChapters());
		profile.setWantTextChptOutput(profileData.isWantTextChptOutput());
		profile.setTimeLineAddTimePerScene(profileData.isTimeLineAddTimePerScene());

		//
		profile.setCounterDigitChoice(profileData.getCounterDigitChoice());

		// <DocTag Outliner Section>
		// profile.setOutputDocTagsOutlineFile(profileData.getOutputDocTagsOutlineFile());
		// profile.setOutputDocTagsSceneFile(profileData.getOutputDocTagsSceneFile());
		profile.setOutputDocTagsMaxLineLength(profileData.getOutputDocTagsMaxLineLength());
		profile.setOutputDocTagsScenePrefix(profileData.getOutputDocTagsSubScenePrefix());
		profile.setOutputDocTagsSubScenePrefix(profileData.getOutputDocTagsSubScenePrefix());
		profile.setSceneCoalateDiv(profileData.getSceneCoalateDiv());
		profile.setDocTagsOutlineTags(profileData.getDocTagsOutlineTags());
		profile.setDocTagsOutlineCompressTags(profileData.getDocTagsOutlineCompressTags());
		profile.setDocTagsSceneTags(profileData.getDocTagsSceneTags());
		profile.setDocTagsSceneCompressTags(profileData.getDocTagsSceneCompressTags());

		// Misnamed in V1
		// profile.setOutputCSVOutlineFile(profileData.getOutputCSVOutlineFile());
		// Misnamed in V1
		// profile.setOutputCSVAllFile(profileData.getOutputCSVAllFile());

		// <Input/Output Section>
		profile.setOutputEncoding(profileData.getOutputEncoding());
		profile.setChapterHeaderTag(profileData.getChapterHeaderTag());
		profile.setSectionHeaderTag(profileData.getSectionHeaderTag());
		profile.setFmtMode(profileData.getFmtMode());
		profile.setDocTagStart(profileData.getDocTagStart());
		profile.setDocTagEnd(profileData.getDocTagEnd());

		// Other Files Section
		profile.setOutputs(profileData.getOutputs());
		profile.setExternalIDs(profileData.getExternalIDs());

		//
		profile.setCbRemoveSectDiv(profileData.isCbRemoveSectDiv());
		profile.setCbRemoveSectDiv(profileData.isCbRemoveSectDiv());
		profile.setChpDiv(profileData.getChpDiv());
		profile.setSecDiv(profileData.getSecDiv());
		//

		// profile.setOutputCharCardFile(profileData.getOutputCharCardFile());
		profile.setTimelineTimePadding(profileData.getTimelineTimePadding());
		//
		saveProfileData(profile);
	}

}


text:
var escapeHTML = require('./escapeHTML');

describe('String/escapeHTML', function () {
  it('should escape a HTML string', function () {
    expect(escapeHTML('


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Portfolio OMC | PROJECT</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" href="favicon.ico">

        <link href="https://fonts.googleapis.com/css?family=Indie+Flower|Neucha" rel="stylesheet">

        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/bootstrap.css">
        <link rel="stylesheet" href="css/main.css">

MY PROJECTS

Copy of existing site

                        keyboard_arrow_right

                        ArchiDuchesse

                        Air BNB

                        LeBonCoin

                        Palais des Beaux Arts de Lille

My creations

                        keyboard_arrow_right

                        Vente en ligne

                        Plombier

                        Tatoueur

                        To be continued

            HOME
            CONTACT ME


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('logger', '0012_add_asset_uid_to_xform'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='ziggyinstance',
            name='reporter',
        ),
        migrations.RemoveField(
            model_name='ziggyinstance',
            name='xform',
        ),
        migrations.RemoveField(
            model_name='xform',
            name='bamboo_dataset',
        ),
        migrations.DeleteModel(
            name='ZiggyInstance',
        ),
    ]


text:
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var view_1 = require("../core/view");
__export(require("../core/view"));
var ActivityIndicatorBase = (function (_super) {
    __extends(ActivityIndicatorBase, _super);
    function ActivityIndicatorBase() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ActivityIndicatorBase;
}(view_1.View));
exports.ActivityIndicatorBase = ActivityIndicatorBase;
exports.busyProperty = new view_1.Property({ name: "busy", defaultValue: false, valueConverter: view_1.booleanConverter });
exports.busyProperty.register(ActivityIndicatorBase);
//# sourceMappingURL=activity-indicator-common.js.map


text:
package boofcv.alg.transform.pyramid;

import boofcv.alg.interpolate.InterpolatePixelS;
import boofcv.core.image.border.BorderType;
import boofcv.factory.interpolate.FactoryInterpolation;
import boofcv.gui.SelectInputPanel;
import boofcv.gui.image.ImagePyramidPanel;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageUInt8;
import boofcv.struct.pyramid.PyramidFloat;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * Displays an image pyramid.
 *
 * @author Peter Abeles
 */
public class VisualizePyramidFloatApp <T extends ImageSingleBand>
	extends SelectInputPanel
{
	double scales[] = new double[]{1,1.2,2.4,3.6,4.8,6.0,12,20};

	Class<T> imageType;
	InterpolatePixelS<T> interp;
	ImagePyramidPanel<T> gui = new ImagePyramidPanel<T>();
	boolean processedImage = false;

	public VisualizePyramidFloatApp( Class<T> imageType ) {
		this.imageType = imageType;
		interp = FactoryInterpolation.bilinearPixelS(imageType, BorderType.EXTENDED);

		setMainGUI(gui);
	}

	public void process( final BufferedImage input ) {
		setInputImage(input);
		final T gray = ConvertBufferedImage.convertFromSingle(input, null, imageType);

		PyramidFloat<T> pyramid = new PyramidFloatScale<T>(interp,scales,imageType);

		pyramid.process(gray);

		gui.set(pyramid,true);

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				gui.render();
				gui.repaint();
				setPreferredSize(new Dimension(gray.width+50,gray.height+20));
				processedImage = true;
			}});
	}

	@Override
	public void loadConfigurationFile(String fileName) {}

	@Override
	public synchronized void changeInput(String name, int index) {
		BufferedImage image = media.openImage(inputRefs.get(index).getPath());

		if( image != null ) {
			process(image);
		}
	}

	@Override
	public boolean getHasProcessedImage() {
		return processedImage;
	}

	public static void main( String args[] ) {

//		VisualizePyramidFloatApp<ImageFloat32> app = new VisualizePyramidFloatApp<ImageFloat32>(ImageFloat32.class);
		VisualizePyramidFloatApp<ImageUInt8> app = new VisualizePyramidFloatApp<ImageUInt8>(ImageUInt8.class);

		java.util.List<PathLabel> inputs = new ArrayList<PathLabel>();
		inputs.add(new PathLabel("boat","../data/evaluation/standard/boat.png"));
		inputs.add(new PathLabel("shapes","../data/evaluation/shapes01.png"));
		inputs.add(new PathLabel("sunflowers","../data/evaluation/sunflowers.png"));

		app.setInputList(inputs);

		// wait for it to process one image so that the size isn't all screwed up
		while( !app.getHasProcessedImage() ) {
			Thread.yield();
		}

		ShowImages.showWindow(app,"Image Float Pyramid");
	}
}


text:
package com.google.errorprone.predicates;

import com.google.errorprone.VisitorState;
import com.sun.tools.javac.code.Type;
import java.io.Serializable;

/** A predicate for testing {@link Type}s. */
public interface TypePredicate extends Serializable {
  boolean apply(Type type, VisitorState state);
}