code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<ul class="error_list">
<ul class="error_list">
<?php foreach ($errors as $error): ?>
<li><?php echo $this->escape($error); ?></li>
<?php endforeach; ?>
</ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $this->escape($error); ?></li>
<?php endforeach; ?>
</ul>
| yasuto777/mini-blog | views/errors.php | PHP | mit | 294 |
<?php
class PagedData implements IteratorAggregate
{
private $page = 1;
private $perPage = 10;
private $pageCount = 0;
private $items = array();
public function __construct($page, $perPage = 10)
{
$this->page = $page < 1 ? 1 : (int)$page;
$this->perPage = (int)$perPage;
}
public function isEmpty()
{
return empty($this->items);
}
public function getIterator()
{
return new ArrayIterator($this->items);
}
public function getPage()
{
return $this->page;
}
public function getOffset()
{
return ($this->page - 1) * $this->perPage;
}
public function getPerPage()
{
return $this->perPage;
}
public function getPageCount()
{
return $this->pageCount;
}
public function fill($totalItems, $items)
{
$this->pageCount = ceil($totalItems / $this->perPage);
$this->items = $items;
}
public function isLinkToFirstPageAvailable()
{
return $this->page > 2;
}
public function isLinkToPreviousPageAvailable()
{
return $this->page > 1;
}
public function isLinkToNextPageAvailable()
{
return $this->page < $this->pageCount;
}
public function isLinkToLastPageAvailable()
{
return $this->page < ($this->pageCount - 1);
}
public function render($href, $param = 'page')
{
if ($this->getPageCount() < 2)
{
return '';
}
$result = 'Strony (<a class="page-total" title="Skocz do strony" href="' . $href . '&' . $param . '=${page}">' . $this->getPageCount() . '</a>): ';
$result .= $this->isLinkToFirstPageAvailable()
? '<a class="page-first" href="' . $href . '&' . $param . '=1">« Pierwsza</a> '
#: '<span class="page-first">« First</span> ';
: '';
$result .= $this->isLinkToPreviousPageAvailable()
? '<a class="page-prev" href="' . $href . '&' . $param . '=' . ($this->getPage() - 1) . '">‹ Poprzednia</a> '
#: '<span class="page-prev">‹ Previous</span> ';
: '';
$pageNumbers = 3;
$page = $this->getPage();
$last = $page + $pageNumbers;
$cut = true;
if (($page - $pageNumbers) < 1)
{
$page = 1;
}
else
{
$page -= $pageNumbers;
if ($page !== 1) $result .= '... ';
}
if ($last > $this->getPageCount())
{
$last = $this->getPageCount();
$cut = false;
}
for (; $page <= $last; ++$page)
{
$result .= $page === $this->getPage()
? '<span class="page-current">' . $page . '</span>'
: '<a class="page" href="' . $href . '&' . $param . '=' . $page . '">' . $page . '</a>';
$result .= $page < $last ? ' | ' : ' ';
}
if ($cut && $last != $this->getPageCount())
{
$result .= '... ';
}
$result .= $this->isLinkToNextPageAvailable()
? '<a class="page-next" href="' . $href . '&' . $param . '=' . ($this->getPage() + 1) . '">Następna ›</a> '
#: '<span class="page-next">Next ›</span> ';
: '';
$result .= $this->isLinkToLastPageAvailable()
? '<a class="page-last" href="' . $href . '&' . $param . '=' . $this->getPageCount() . '">Ostatnia »</a>'
#: '<span class="page-last">Last »</span>';
: '';
return $result;
}
}
| morkai/envis.walkner.pl | _lib_/PagedData.php | PHP | mit | 3,083 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//
//= require_tree .
| devis/email-me | app/assets/javascripts/email_me/application.js | JavaScript | mit | 602 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* ZENBU THIRD-PARTY FIELDTYPE SUPPORT
* ============================================
* Grid field
* @author EllisLab
* ============================================
* File grid.php
*
*/
class Zenbu_grid_ft extends Grid_ft
{
var $dropdown_type = "contains_doesnotcontain";
/**
* Constructor
*
* @access public
*/
function __construct()
{
$this->EE =& get_instance();
$this->EE->load->model('zenbu_get');
$this->EE->load->helper('loader');
}
/**
* ======================
* function zenbu_display
* ======================
* Set up display in entry result cell
*
* @param $entry_id int The entry ID of this single result entry
* @param $channel_id int The channel ID associated to this single result entry
* @param $data array Raw data as found in database cell in exp_channel_data
* @param $table_data array Data array usually retrieved from other table than exp_channel_data
* @param $field_id int The ID of this field
* @param $settings array The settings array, containing saved field order, display, extra options etc settings
* @param $rules array An array of entry filtering rules
* @param $upload_prefs array An array of upload preferences (optional)
* @param $installed_addons array An array of installed addons and their version numbers (optional)
* @param $fieldtypes array Fieldtype of available fieldtypes: id, name, etc (optional)
* @return $output The HTML used to display data
*/
function zenbu_display($entry_id, $channel_id, $data, $grid_data = array(), $field_id, $settings, $rules = array(), $upload_prefs = array(), $installed_addons)
{
$output = NBS;
// If grid_data is empty (no results), stop here and return a space for the field data
if( ! isset($grid_data['table_data']['entry_id_'.$entry_id]['field_id_'.$field_id]))
{
return $output;
}
$output = "";
$row_array = array();
$grid_data['field_id'] = $field_id;
$grid_data['entry_id'] = $entry_id;
// ----------------------------------------
// Rewrite Grid data array with Zenbu-formatted data
// instead of raw Grid DB data
// ----------------------------------------
foreach($grid_data['table_data']['entry_id_'.$entry_id]['field_id_'.$field_id] as $row => $col)
{
foreach($col as $col_id => $data)
{
$fieldtype = $grid_data['headers']['field_id_'.$field_id][$col_id]['fieldtype'];
// ----------------------------------------
// Load Zenbu Fieldtype Class
// ----------------------------------------
$ft_class = $fieldtype.'_ft';
load_ft_class($ft_class);
// ----------------------------------------
// Run the zenbu_display method, if it exists
// This should convert the raw data into Zenbu data
// ----------------------------------------
if(class_exists($ft_class))
{
$ft_object = create_object($ft_class);
// Some stuff we need for zenbu_display
$settings = $this->EE->zenbu_get->_get_settings();
$rules = array();
$output_upload_prefs = $this->EE->zenbu_get->_get_file_upload_prefs();
$installed_addons = $this->EE->zenbu_get->_get_installed_addons();
$fieldtypes = $this->EE->zenbu_get->_get_field_ids();
// ----------------------------------------
// Get relationship data, if present
// ----------------------------------------
// Send grid_id_X array key to signal the
// relationship field that this in a grid
$rel_array = array( $entry_id => array( 'grid_id_'.$field_id => $data ) );
$table_data = (method_exists($ft_object, 'zenbu_get_table_data')) ? $ft_object->zenbu_get_table_data(array($entry_id), array($field_id), $channel_id, $output_upload_prefs, $settings, $rel_array) : array();
$table_data['grid_row'] = substr($row, 4);
$table_data['grid_col'] = substr($col_id, 7);
// ----------------------------------------
// Convert the data
// ----------------------------------------
$data = (method_exists($ft_object, 'zenbu_display')) ? $ft_object->zenbu_display($entry_id, $channel_id, $data, $table_data, $field_id, $settings, $rules, $output_upload_prefs, $installed_addons, $fieldtypes) : $data;
}
$grid_data['table_data']['entry_id_'.$entry_id]['field_id_'.$field_id][$row][$col_id] = $data;
}
}
$this->EE->load->helper('display');
$output = $this->EE->load->view('_grid', $grid_data, TRUE);
//return $output;
/**
* Displaying the matrix inline or as a fancybox link
* Based on user group setting
*/
$extra_options = $settings['setting'][$channel_id]['extra_options'];
if( ! isset($extra_options["field_".$field_id]['grid_option_1']))
{
// Display table in a hidden div, then have a fancybox link show it on click
$output = '<div style="display: none"><div id="e_'.$entry_id.'_f_'.$field_id.'">' . $output . '</div></div>';
$link_to_matrix = '#e_'.$entry_id.'_f_'.$field_id;
return anchor($link_to_matrix, $this->EE->lang->line('show_').$this->EE->lang->line('grid'), 'class="fancybox-inline" rel="#field_id_'.$field_id.'"') . $output;
} else {
// ..else return the table as-is, and see it displayed directly in the row
return $output;
}
}
/**
* =============================
* function zenbu_get_table_data
* =============================
* Retrieve data stored in other database tables
* based on results from Zenbu's entry list
* @uses Instead of many small queries, this function can be used to carry out
* a single query of data to be later processed by the zenbu_display() method
*
* @param $entry_ids array An array of entry IDs from Zenbu's entry listing results
* @param $field_ids array An array of field IDs tied to/associated with result entries
* @param $channel_id int The ID of the channel in which Zenbu searched entries (0 = "All channels")
* @param $output_upload_prefs array An array of upload preferences
* @param $settings array The settings array, containing saved field order, display, extra options etc settings (optional)
* @param $rel_array array A simple array useful when using related entry-type fields (optional)
* @return $output array An array of data (typically broken down by entry_id then field_id) that can be used and processed by the zenbu_display() method
*/
function zenbu_get_table_data($entry_ids, $field_ids, $channel_id)
{
$output = array();
if( empty($entry_ids) || empty($field_ids))
{
return $output;
}
// ----------------------------------------
// Get grid field data as an array
// ----------------------------------------
// ----------------------------------------
// First, get field_ids that are grid fields
// ----------------------------------------
if($this->EE->session->cache('zenbu', 'grid_field_ids'))
{
$field_ids = $this->EE->session->cache('zenbu', 'grid_field_ids');
} else {
$sql = "SHOW TABLES LIKE '%grid_field_%'";
$query = $this->EE->db->query($sql);
$grid_field_ids = array();
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
foreach($row as $val => $table_name)
{
preg_match('/(\d+)$/', $table_name, $matches);
$grid_field_ids[] = $matches[1];
}
}
}
// Make a new field_ids array, which will only be grid_field_ids
$field_ids = array_intersect($grid_field_ids, $field_ids);
$this->EE->session->set_cache('zenbu', 'grid_field_ids', $field_ids);
}
// If the new field_ids array winds up empty, get out.
if( empty($field_ids))
{
return $output;
}
// ----------------------------------------
// Since each Grid field has its own table, to avoid a mess
// of clashing column names, query each table individually.
// ----------------------------------------
$sql = '';
foreach($field_ids as $field_id)
{
if($this->EE->session->cache('zenbu', 'grid_table_data_field_'.$field_id))
{
$table_data = $this->EE->session->cache('zenbu', 'grid_table_data_field_'.$field_id);
} else {
$sql = "/* Zenbu grid.php " . __FUNCTION__ ." field_id_" . $field_id. " */
SELECT * FROM exp_channel_grid_field_" . $field_id . " gf, exp_grid_columns gc
WHERE gc.field_id = " . $field_id . "
AND gf.entry_id IN (" . implode(', ', $entry_ids) . ")
ORDER BY gf.entry_id ASC, gf.row_order ASC, gc.col_order ASC";
$query = $this->EE->db->query($sql);
$headers_array = array();
$col_params = array();
$table_data = array();
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$headers_array['id'][$row['col_id']] = $row['col_id'];
$headers_array['col_order'][$row['col_id']] = $row['col_order'];
$headers_array['label'][$row['col_id']] = $row['col_label'];
$headers_array['fieldtype'][$row['col_id']] = $row['col_type'];
$table_data['headers']['field_id_'.$row['field_id']]['col_id_'.$row['col_id']] = array(
"id" => $row['col_id'],
"col_order" => $row['col_order'],
"label" => $row['col_label'],
"fieldtype" => $row['col_type'],
);
}
foreach($query->result_array() as $row)
{
foreach($headers_array['id'] as $col_id)
{
$table_data['table_data']['entry_id_'.$row['entry_id']]['field_id_'.$field_id]['row_'.$row['row_id']]['col_id_'.$col_id] = $row['col_id_'.$col_id];
}
}
} else {
$headers_array['id'][] = '';
$headers_array['label'][] = '';
$headers_array['fieldtype'][] = '';
}
//$headers = $col_params;
//$this->EE->session->set_cache('zenbu', 'grid_headers_field_'.$field_id, $headers);
$this->EE->session->set_cache('zenbu', 'grid_table_data_field_'.$field_id, $table_data);
}
}
return $table_data;
}
/**
* ===================================
* function zenbu_field_extra_settings
* ===================================
* Set up display for this fieldtype in "display settings"
*
* @param $table_col string A Zenbu table column name to be used for settings and input field labels
* @param $channel_id int The channel ID for this field
* @param $extra_options array The Zenbu field settings, used to retieve pre-saved data
* @return $output The HTML used to display setting fields
*/
function zenbu_field_extra_settings($table_col, $channel_id, $extra_options)
{
$extra_option_1 = (isset($extra_options['grid_option_1'])) ? TRUE : FALSE;
$output['grid_option_1'] = form_label(form_checkbox('settings['.$channel_id.']['.$table_col.'][grid_option_1]', 'y', $extra_option_1).' '.$this->EE->lang->line('show_').$this->EE->lang->line('grid').$this->EE->lang->line('_in_row'));
return $output;
}
/**
* ===================================
* function zenbu_result_query
* ===================================
* Extra queries to be intergrated into main entry result query
*
* @param $rules int An array of entry filtering rules
* @param $field_id array The ID of this field
* @param $fieldtypes array $fieldtype data
* @param $already_queried bool Used to avoid using a FROM statement for the same field twice
* @return A query to be integrated with entry results. Should be in CI Active Record format ($this->EE->db->…)
*/
function zenbu_result_query($rules = array(), $field_id = "", $fieldtypes, $already_queried = FALSE)
{
if(empty($rules))
{
return;
}
if($already_queried === FALSE)
{
$this->EE->db->from("exp_grid_data");
}
$this->EE->db->where("exp_grid_data.field_id", $field_id);
$col_query = $this->EE->db->query("/* Zenbu: Show columns for matrix */\nSHOW COLUMNS FROM exp_grid_data");
$concat = "";
$where_in = array();
if($col_query->num_rows() > 0)
{
foreach($col_query->result_array() as $row)
{
if(strchr($row['Field'], 'col_id_') !== FALSE)
{
$concat .= 'exp_grid_data.'.$row['Field'].', ';
}
}
$concat = substr($concat, 0, -2);
}
$col_query->free_result();
if( ! empty($concat))
{
// Find entry_ids that have the keyword
foreach($rules as $rule)
{
$rule_field_id = (strncmp($rule['field'], 'field_', 6) == 0) ? substr($rule['field'], 6) : 0;
if(isset($fieldtypes['fieldtype'][$rule_field_id]) && $fieldtypes['fieldtype'][$rule_field_id] == "matrix")
{
$keyword = $rule['val'];
$keyword_query = $this->EE->db->query("/* Zenbu: Search matrix */\nSELECT entry_id FROM exp_grid_data WHERE \nCONCAT_WS(',', ".$concat.") \nLIKE '%".$this->EE->db->escape_like_str($keyword)."%'");
$where_in = array();
if($keyword_query->num_rows() > 0)
{
foreach($keyword_query->result_array() as $row)
{
$where_in[] = $row['entry_id'];
}
}
} // if
// If $keyword_query has hits, $where_in should not be empty.
// In that case finish the query
if( ! empty($where_in))
{
if($rule['cond'] == "doesnotcontain")
{
// …then query entries NOT in the group of entries
$this->EE->db->where_not_in("exp_channel_titles.entry_id", $where_in);
} else {
$this->EE->db->where_in("exp_channel_titles.entry_id", $where_in);
}
} else {
// However, $keyword_query has no hits (like on an unexistent word), $where_in will be empty
// Send no results for: "search field containing this unexistent word".
// Else, just show everything, as obviously all entries will not contain the odd word
if($rule['cond'] == "contains")
{
$where_in[] = 0;
$this->EE->db->where_in("exp_channel_titles.entry_id", $where_in);
}
}
} // foreach
} // if
}
} // END CLASS
/* End of file grid.php */
/* Location: ./system/expressionengine/third_party/zenbu/fieldtypes/grid.php */
?> | noslouch/pa | core/expressionengine/third_party/zenbu/fieldtypes/grid.php | PHP | mit | 13,911 |
#include "GeneralProcessor.h"
namespace engine {
////==--------------------------------------------------------------------====//
// ECKERT PROCESSOR / ADD
// [ description ]
// ADD function for 2 complex numbers
// (a + ib) + (c + id) = (a + c) + i(b + d)
// [ Update ]
// Jan 25, 2016
//====--------------------------------------------------------------------==////
SpElement GeneralProcessor::addComplex(const SpElement &p_ey, const SpElement &p_ex) {
SpElement p_etemp;
bool y_cplx = p_ey->isType(Element::COMPLEX);
bool x_cplx = p_ex->isType(Element::COMPLEX);
if (y_cplx && x_cplx) {
//== COMPLEX + COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = a + c
p_real = addScalar(a, c);
// imag = b + d
p_imag = addScalar(b, d);
// optimize complex
setComplex(p_etemp, p_real, p_imag);
}
else if (y_cplx) {
//== COMPLEX + ANY ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = p_ex;
// real = a + c
p_real = addScalar(a, c);
// imag = b
p_imag = b->clone();
// optimize complex
setComplex(p_etemp, p_real, p_imag);
}
else if (x_cplx) {
//== ANY + COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = p_ey;
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = a + c
p_real = addScalar(a, c);
// imag = d
p_imag = d->clone();
setComplex(p_etemp, p_real, p_imag);
}
else {
//== Unexpected ==//
throw BadArgument("BAD_TYPE", __FUNCTION__);
}
return p_etemp;
}
////==--------------------------------------------------------------------====//
// ECKERT PROCESSOR / SUBTRACT
// [ description ]
// Subtract function for 2 complex numbers
// (a + ib) - (c + id) = (a - c) + i(b - d)
// [ Update ]
// Jan 25, 2016
//====--------------------------------------------------------------------==////
SpElement GeneralProcessor::subComplex(const SpElement &p_ey, const SpElement &p_ex) {
SpElement p_etemp;
bool y_cplx = p_ey->isType(Element::COMPLEX);
bool x_cplx = p_ex->isType(Element::COMPLEX);
if (y_cplx && x_cplx) {
//== Complex - Complex ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = a - c
p_real = subScalar(a, c);
// imag = b - d
p_imag = subScalar(b, d);
// optimize complex
setComplex(p_etemp, p_real, p_imag);
}
else if (y_cplx) {
//== Complex - ANY ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = p_ex;
// real = a - c
p_real = subScalar(a, c);
// imag = b
p_imag = b->clone();
// optimize complex
setComplex(p_etemp, p_real, p_imag);
}
else if (x_cplx) {
//== ANY - Complex ==//
SpElement p_real;
SpElement p_imag;
auto a = p_ey;
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = a - c
p_real = subScalar(a, c);
// imag = -d
p_imag = neg(d);
setComplex(p_etemp, p_real, p_imag);
}
else {
//== Unexpected ==//
throw BadArgument("BAD_TYPE", __FUNCTION__);
}
return p_etemp;
}
////==--------------------------------------------------------------------====//
// ECKERT PROCESSOR / MULTIPLY
// [ description ]
// MULTIPLY function for 2 complex numbers
// (a + ib) * (c + id) = (ac - bd) + i(ad + bc)
// [ Update ]
// Jan 28, 2016
//====--------------------------------------------------------------------==////
SpElement GeneralProcessor::mulComplex(const SpElement &p_ey, const SpElement &p_ex) {
SpElement p_etemp;
bool y_cplx = p_ey->isType(Element::COMPLEX);
bool x_cplx = p_ex->isType(Element::COMPLEX);
if (y_cplx && x_cplx) {
//== COMPLEX * COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = (ac - bd)
p_real = subScalar(
mulScalar(a, c), mulScalar(b, d)
);
// imag = (ad + bc)
p_imag = addScalar(
mulScalar(a, d), mulScalar(b, c)
);
setComplex(p_etemp, p_real, p_imag);
}
else if (y_cplx) {
//== COMPLEX * ANY ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = p_ex;
// real = ac
p_real = mulScalar(a, c);
// imag = bc
p_imag = mulScalar(b, c);
setComplex(p_etemp, p_real, p_imag);
}
else if (x_cplx) {
//== ANY * COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = p_ey;
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// real = ac
p_real = mulScalar(a, c);
// imag = ad
p_imag = mulScalar(a, d);
setComplex(p_etemp, p_real, p_imag);
}
else {
//== Unexpected ==//
throw BadArgument("BAD_TYPE", __FUNCTION__);
}
return p_etemp;
}
////==--------------------------------------------------------------------====//
// ECKERT PROCESSOR / DIVIDE
// [ description ]
// DIVIDE function for 2 complex numbers
// (a + ib) / (c + id) = ((ac + bd) / sq) + i((bc - ad) / sq)
// sq = c^2 + d^2
// [ Update ]
// Jan 28, 2016
//====--------------------------------------------------------------------==////
SpElement GeneralProcessor::divComplex(const SpElement &p_ey, const SpElement &p_ex) {
// check division by zero
if (isZero(p_ex)) {
throw InvalidValue("DIV_ZERO", __FUNCTION__);
}
else if (isZero(p_ey)) {
return p_ey;
}
SpElement p_etemp;
bool y_cplx = p_ey->isType(Element::COMPLEX);
bool x_cplx = p_ex->isType(Element::COMPLEX);
if (y_cplx && x_cplx) {
//== COMPLEX / COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// sq = c^2 + d^2
p_etemp = addScalar(
mulScalar(c, c), mulScalar(d, d)
);
// real = (ac + bd) / sq
p_real = addScalar(
mulScalar(a, c), mulScalar(b, d)
);
p_real = divScalar(p_real, p_etemp);
// imag = (bc - ad) / sq
p_imag = subScalar(
mulScalar(b, c), mulScalar(a, d)
);
p_imag = divScalar(p_imag, p_etemp);
setComplex(p_etemp, p_real, p_imag);
}
else if (y_cplx) {
//== COMPLEX / ANY ==//
SpElement p_real;
SpElement p_imag;
auto a = GET_COMPLEX_RE(p_ey);
auto b = GET_COMPLEX_IM(p_ey);
auto c = p_ex;
// real = a/c
p_real = divScalar(a, c);
// imag = b/c
p_imag = divScalar(b, c);
setComplex(p_etemp, p_real, p_imag);
}
else if (x_cplx) {
//== ANY / COMPLEX ==//
SpElement p_real;
SpElement p_imag;
auto a = p_ey;
auto c = GET_COMPLEX_RE(p_ex);
auto d = GET_COMPLEX_IM(p_ex);
// sq = c^2 + d^2
p_etemp = addScalar(
mulScalar(c, c), mulScalar(d, d)
);
// real = ac / sq
p_real = divScalar(
mulScalar(a, c), p_etemp
);
// imag = -ad / sq
p_imag = neg(
divScalar(mulScalar(a, d), p_etemp)
);
// optimize complex
setComplex(p_etemp, p_real, p_imag);
}
else {
//== Unexpected ==//
throw BadArgument("BAD_TYPE", __FUNCTION__);
}
return p_etemp;
}
} // namespace engine
| yuishin-kikuchi/eckert | src/calc/engine/proc/GeneralProcessorComplexArithmetic.cpp | C++ | mit | 7,196 |
export interface IEvent {
EventId: number;
Name: string;
Description: string;
StartTime: Date;
EndTime: Date;
}
| ryankwilson/challengeapp | src/client/app/models/event.ts | TypeScript | mit | 132 |
import fbapi = require("facebook-chat-api");
import { Utils } from "../utils";
import { IContext, MessageModule } from "./chat-module";
export class AdminModule extends MessageModule {
public static AdminUrl: string =
"https://docs.google.com/document/d/1rSDm7SfywNW3NmdurgPvjUhEDc5gANAGqFYSfAnBq3k/edit?usp=sharing";
public static AdminChatId: string = "1448287721947838";
public getHelpLine(): string {
return "/admin info: Get info on group admins\n" +
"/admin request [opt. message]: Send a message to the admin's group";
}
public processMessage(ctx: IContext<fbapi.MessageEvent>): void {
if (ctx.message.body === "/admin info") {
Utils.sendMessage(ctx, AdminModule.AdminUrl);
} else if (ctx.message.body.indexOf("/admin request") === 0) {
const message = (ctx.message.body === "/admin request")
? "Somebody asked for y'all"
: "Message from chat: " + ctx.message.body.substring("/admin request ".length);
Utils.sendMessage(ctx, message, AdminModule.AdminChatId);
Utils.sendMessage(ctx, `Okay, I told the admins "${message}".`);
}
}
}
| Mini-Geek/tmbc-chat-bot | src/chat-modules/admin.ts | TypeScript | mit | 1,224 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* VEX Robotics Victor 888 Speed Controller
*
* The Vex Robotics Victor 884 Speed Controller can also be used with this
* class but may need to be calibrated per the Victor 884 user manual.
*/
public class Victor extends SafePWM implements SpeedController {
/**
* Common initialization code called by all constructors.
*
* Note that the Victor uses the following bounds for PWM values. These values were determined
* empirically and optimized for the Victor 888. These values should work reasonably well for
* Victor 884 controllers also but if users experience issues such as asymmetric behaviour around
* the deadband or inability to saturate the controller in either direction, calibration is recommended.
* The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics:
* http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf
*
* - 2.027ms = full "forward"
* - 1.525ms = the "high end" of the deadband range
* - 1.507ms = center of the deadband range (off)
* - 1.49ms = the "low end" of the deadband range
* - 1.026ms = full "reverse"
*/
private void initVictor() {
setBounds(2.027, 1.525, 1.507, 1.49, 1.026);
setPeriodMultiplier(PeriodMultiplier.k2X);
setRaw(m_centerPwm);
setZeroLatch();
LiveWindow.addActuator("Victor", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_Victor, getChannel());
}
/**
* Constructor.
*
* @param channel The PWM channel that the Victor is attached to. 0-9 are on-board, 10-19 are on the MXP port
*/
public Victor(final int channel) {
super(channel);
initVictor();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately
* scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately.
*/
public void set(double speed, byte syncGroup) {
setSpeed(speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately
* scaling the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
public void set(double speed) {
setSpeed(speed);
Feed();
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
public void pidWrite(double output) {
set(output);
}
}
| trc492/Frc2015RecycleRush | code/WPILibJ/Victor.java | Java | mit | 3,781 |
package main
import (
"flag"
"image/color"
"image/png"
"log"
"os"
"github.com/lethal-guitar/go_tracer/tracing"
"github.com/lethal-guitar/go_tracer/scene"
"github.com/lethal-guitar/go_tracer/vecmath"
)
func main() {
tileSize := flag.Int("tileSize", 64, "Size of a render tile")
flag.Parse()
rayTracer := createTracer()
rendering := rayTracer.Render(*tileSize)
file, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
if err = png.Encode(file, rendering); err != nil {
log.Fatal(err)
}
}
func addAbletonLogo(
model *tracing.Scene,
material *scene.Material,
start,
startY,
startZ float32,
) {
const RADIUS = 2
const STEP = 5.3
for y := 0; y < 5; y++ {
for x := 0; x < 4; x++ {
xPos := start + STEP*float32(x)
yPos := startY + float32(4*y)
model.AddObject(scene.MakeSphere(vecmath.Vec3d{xPos, yPos, startZ}, RADIUS, *material))
}
}
start += 4*STEP
for y := 0; y < 4; y++ {
for x := 0; x < 5; x++ {
xPos := start + float32(4*x)
yPos := startY + float32(y)*STEP
model.AddObject(scene.MakeSphere(vecmath.Vec3d{xPos, yPos, startZ}, RADIUS, *material))
}
}
}
func setupScene() tracing.Scene {
redMaterial := scene.MakeSimpleMaterial(color.RGBA{255, 0, 0, 255})
greenMaterial := scene.MakeSimpleMaterial(color.RGBA{0, 255, 0, 255})
greenMaterial.Specularity = 50
greenMaterial.Reflectivity = 0.22
transparent := scene.MakeSimpleMaterial(color.RGBA{255, 255, 255, 255})
transparent.Transparency = 1.0
transparent.RefractionIndex = 1.49
grayMaterial := scene.MakeSimpleMaterial(color.RGBA{100, 100, 100, 255})
grayMaterial.Specular = scene.FloatColor{}
grayMaterial2 := scene.MakeSimpleMaterial(color.RGBA{100, 100, 100, 255})
grayMaterial.Specular = scene.FloatColor{}
grayMaterial2.Reflectivity = 0.05
mirrorMaterial := scene.MakeSimpleMaterial(color.RGBA{255, 255, 255, 255})
mirrorMaterial.Reflectivity = 0.75
model := tracing.Scene{BackgroundColor: color.RGBA{100, 100, 100, 255}}
for i := 0; i < 5; i++ {
addAbletonLogo(&model, &mirrorMaterial, -18, -2.0, 230 + float32(i)*20)
}
model.AddObject(scene.MakeSphere(vecmath.Vec3d{-16.0, -11.0, 205.0}, 5.0, redMaterial))
model.AddObject(scene.MakeSphere(vecmath.Vec3d{10.0, 13.0, 190.0}, 3.0, greenMaterial))
model.AddObject(scene.MakeSphere(vecmath.Vec3d{20.0, 0.0, 205.0}, 5.0, greenMaterial))
floor := scene.MakePlane(16, vecmath.Vec3d{0,-1,0})
floor.ObjectMaterial = grayMaterial2
floor.AssignedBounds = scene.MakeAABB(-28, 16, -50, 28, 16.1, 320)
leftWall := scene.MakePlane(24, vecmath.Vec3d{1,0,0})
leftWall.ObjectMaterial = grayMaterial
leftWall.AssignedBounds = scene.MakeAABB(-24, -80, -50, -23.9, 80, 320)
backWall := scene.MakePlane(320, vecmath.Vec3d{0,0,-1})
backWall.ObjectMaterial = grayMaterial
backWall.AssignedBounds = scene.MakeAABB(-28, -80, 320, 28, 80, 320.1)
rightWall := scene.MakePlane(28, vecmath.Vec3d{-1,0,0})
rightWall.ObjectMaterial = grayMaterial
rightWall.AssignedBounds = scene.MakeAABB(28, -80, -50, 28.1, 80, 320)
model.AddObject(floor)
white := color.RGBA{255, 255, 255, 255}
dimWhite := color.RGBA{100, 100, 100, 255}
model.AddLight(
scene.MakeColoredLight(vecmath.Vec3d{0.0, -30.0, 210.0}, white))
model.AddLight(
scene.MakeColoredLight(vecmath.Vec3d{26.0, -80.0, 80.0}, white))
model.AddLight(
scene.MakeColoredLight(vecmath.Vec3d{0.0, 0.0, -10.0}, dimWhite))
return model
}
func createTracer() tracing.RayTracer {
// A4 600 DPI: 4961 x 7016
// A4 300 DPI
//width := 3508
//height := 2480
// Full HD
//width := 1920
//height := 1080
width := 1280
height := 1280
// NOTE: For now, the target resolution's aspect ratio must be square,
// otherwise the view frustum wouldn't be right.
scene := setupScene()
tracer := tracing.RayTracer{
Width: width,
Height: height,
Camera: tracing.CameraConfig{
-1.0, 1.0,
-1.0, 1.0,
vecmath.Vec3d{0.0, 0.0, -10.0},
},
Scene: &scene,
}
return tracer
}
| lethal-guitar/go_tracer | main.go | GO | mit | 4,360 |
class LightweightUserAgentParser
VERSION = '1.6.0'.freeze
end
| emartech/lightweight_user_agent_parser | lib/lightweight_user_agent_parser/version.rb | Ruby | mit | 64 |
package com.github.mizool.technology.aws.dynamodb;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter;
public class ZonedDateTimeConverter implements DynamoDBTypeConverter<String, ZonedDateTime>
{
@Override
public String convert(ZonedDateTime object)
{
return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(object);
}
@Override
public ZonedDateTime unconvert(String object)
{
return ZonedDateTime.parse(object, DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
}
| mizool/mizool | technology/aws/src/main/java/com/github/mizool/technology/aws/dynamodb/ZonedDateTimeConverter.java | Java | mit | 605 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace BattleHQ.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
} | otac0n/BattleHQ | BattleHQ/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs | C# | mit | 17,214 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using static JetBrains.Annotations.AssertionConditionType;
namespace Ccr.Core.Extensions
{
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(
this string @this)
{
return string.IsNullOrWhiteSpace(@this);
}
/// <summary>
/// Assertion method that ensures that <paramref name="this"/> is not null
/// </summary>
/// <param name="this">
/// The object in which to ensure non-nullability upon
/// </param>
[ContractAnnotation("this:null => true"), AssertionMethod]
public static bool IsNullOrEmptyEx(
[AssertionCondition(IS_NULL)] this string @this)
{
return string.IsNullOrEmpty(@this);
}
/// <summary>
/// Assertion method that ensures that <paramref name="this"/> is not null
/// </summary>
/// <param name="this">
/// The object in which to ensure non-nullability upon
/// </param>
[ContractAnnotation("this:null => false"), AssertionMethod]
public static bool IsNotNullOrEmptyEx(
[AssertionCondition(IS_NOT_NULL)] this string @this)
{
return !string.IsNullOrEmpty(@this);
}
//IsNotNullOrEmptyEx
public static string Surround(
this string @this,
char c)
{
return $"{c}{@this}{c}";
}
public static string SQuote(
this char @this)
{
return @this.ToString().Surround('\'');
}
public static string Quote(
this char @this)
{
return @this.ToString().Surround('\"');
}
public static string SQuote(
this string @this)
{
return @this.Surround('\'');
}
public static string Quote(
this string @this)
{
return @this.Surround('\"');
}
public static string Limit(
this string @this,
int length)
{
return @this.Length > length
? @this.Substring(0, length)
: @this;
}
private static TextInfo _textInfo;
internal static TextInfo TextInfo
{
get => _textInfo
?? (_textInfo = new CultureInfo("en-US", false).TextInfo);
}
public static string ToTitleCase(
this string @this)
{
return TextInfo.ToTitleCase(@this);
}
public static bool ContainsCaseInsensitive(
this string @this,
string toCheck)
{
return @this
.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0;
}
public static bool IsExclusivelyHex(
this string source)
{
return Regex.IsMatch(
source,
@"\A\b[0-9a-fA-F]+\b\Z");
}
public static bool IsCStyleCompilerHexLiteral(
this string source)
{
return Regex.IsMatch(
source,
@"\A\b(0[xX])?[0-9a-fA-F]+\b\Z");
}//
// definition of a valid C# identifier: http://msdn.microsoft.com/en-us/library/aa664670(v=vs.71).aspx
/// <summary>
/// Information on the standards of how the language specificiation
/// consitutes a valid C# member identifier.
/// </summary>
// ReSharper disable once RedundantArrayCreationExpression
private static readonly List<string> _csharpLanguageKeywords
= new List<string>
{
"abstract", "event", "new", "struct",
"as", "explicit", "null", "switch",
"base", "extern", "object", "this",
"bool", "false", "operator", "throw",
"breal", "finally", "out", "true",
"byte", "fixed", "override", "try",
"case", "float", "params", "typeof",
"catch", "for", "private", "uint",
"char", "foreach", "protected", "ulong",
"checked", "goto", "public", "unchekeced",
"class", "if", "readonly", "unsafe",
"const", "implicit", "ref", "ushort",
"continue", "in", "return", "using",
"decimal", "int", "sbyte", "virtual",
"default", "interface", "sealed", "volatile",
"delegate", "internal", "short", "void",
"do", "is", "sizeof", "while",
"double", "lock", "stackalloc",
"else", "long", "static",
"enum", "namespace", "string"
};
private const string formattingCharacter = @"\p{Cf}";
private const string connectingCharacter = @"\p{Pc}";
private const string decimalDigitCharacter = @"\p{Nd}";
private const string combiningCharacter = @"\p{Mn}|\p{Mc}";
private const string letterCharacter = @"\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}|\p{Nl}";
private const string identifierPartCharacter =
letterCharacter + "|" +
decimalDigitCharacter + "|" +
connectingCharacter + "|" +
combiningCharacter + "|" +
formattingCharacter;
private const string identifierPartCharacters =
"(" + identifierPartCharacter + ")";
private const string identifierStartCharacter =
"(" + letterCharacter + "|_)";
private const string identifierOrKeyword =
identifierStartCharacter + "(" + identifierPartCharacters + ")*";
public static bool IsValidCSharpIdentifier(
this string @this)
{
if (@this.IsNullOrEmptyEx())
return false;
var validIdentifierRegex = new Regex(
$"^{identifierOrKeyword}$",
RegexOptions.Compiled);
var normalizedIdentifier = @this.Normalize();
if (validIdentifierRegex.IsMatch(normalizedIdentifier) &&
!_csharpLanguageKeywords.Contains(normalizedIdentifier))
return true;
return normalizedIdentifier.StartsWith("@") &&
validIdentifierRegex.IsMatch(
normalizedIdentifier.Substring(1));
}
//public static string ToCommaSeparatedList(
// this object[] series,
// CoordinatingConjunction coordinatingConjunction = CoordinatingConjunction.None)
//{
// var stringBuilder = new StringBuilder();
// var seriesLength = series.Length;
// for (var i = 0; i < seriesLength - 2; i++)
// {
// stringBuilder.Append(series[i]);
// stringBuilder.Append(", ");
// }
// stringBuilder.Append(series[seriesLength - 1]);
// return stringBuilder.ToString();
//}
/// <summary>
/// Converts the specified input string to Pascal Case.
/// </summary>
/// <param name="this">
/// The subject <see cref="string"/> in which to convert.
/// </param> c
/// <returns>
/// The value of the provided <paramref name="this"/> converted to Pascal Case.
/// </returns>
public static string ToPascalCase(
[NotNull] this string @this)
{
@this.IsNotNull(nameof(@this));
return Regex.Replace(
@this,
"(?:^|_)(.)",
match => match
.Groups[1]
.Value
.ToUpper());
}
/// <summary>
/// Converts the specified input string to Camel Case.
/// </summary>
/// <param name="this">
/// The subject <see cref="string"/> in which to convert.
/// </param>
/// <returns>
/// The value of the provided <paramref name="this"/> converted to Camel Case.
/// </returns>
public static string ToCamelCase(
[NotNull] this string @this)
{
@this.IsNotNull(nameof(@this));
var pascalCase = @this.ToPascalCase();
return pascalCase.Substring(0, 1).ToLower() +
pascalCase.Substring(1);
}
/// <summary>
/// Separates the input words with underscore.
/// </summary>
/// <param name="this">
/// The subject <see cref="string"/> in which to convert.
/// </param>
/// <returns>
/// The provided <paramref name="this"/> with the words separated by underscores.
/// </returns>
public static string Underscore(
[NotNull] this string @this)
{
@this.IsNotNull(nameof(@this));
return
Regex.Replace(
Regex.Replace(
Regex.Replace(
@this, "([A-Z]+)([A-Z][a-z])", "$1_$2"),
"([a-z\\d])([A-Z])", "$1_$2"),
"[-\\s]", "_")
.ToLower();
}
}
}
| vreniose95/Ccr | Ccr.Core/Core/Extensions/StringExtensions.cs | C# | mit | 7,785 |
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, PreloadAllModules } from '@angular/router';
import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from "@ngrx/store-devtools";
import { StoreLogMonitorModule, useLogMonitor } from "@ngrx/store-log-monitor";
/*
* Platform and Environment providers/directives/pipes
*/
import { ENV_PROVIDERS } from './environment';
import appRoutes from './app.routes';
// App is our top level component
import { AppComponent } from './app.component';
import { HeaderComponent } from './header';
import { FooterComponent } from './footer';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';
import { HomeComponent } from './home';
import { NoContentComponent } from './no-content';
import { productionReducer } from './demos/redux-demo/store';
// Application wide providers
const APP_PROVIDERS = [
...APP_RESOLVER_PROVIDERS
];
type StoreType = {
restoreInputValues: () => void,
disposeOldHosts: () => void
};
/**
* `AppModule` is the main entry point into Angular2's bootstraping process
*/
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
HomeComponent, HeaderComponent, FooterComponent,
NoContentComponent
],
imports: [ // import Angular's modules
BrowserModule,
FormsModule,
HttpModule,
appRoutes,
NgbModule.forRoot(),
/**
* StoreModule.provideStore is imported once in the root module, accepting a reducer
* function or object map of reducer functions. If passed an object of
* reducers, combineReducers will be run creating your application
* meta-reducer. This returns all providers for an @ngrx/store
* based application.
*/
StoreModule.provideStore(productionReducer),
// To use devtools as part of the page
StoreDevtoolsModule.instrumentStore({
monitor: useLogMonitor({
visible: true,
position: 'right'
})
}),
StoreLogMonitorModule
],
providers: [ // expose our Services and Providers into Angular's dependency injection
ENV_PROVIDERS,
APP_PROVIDERS
]
})
export class AppModule {
constructor(public appRef: ApplicationRef) {}
hmrOnInit(store: StoreType) {
// set input values
if ('restoreInputValues' in store) {
let restoreInputValues = store.restoreInputValues;
setTimeout(restoreInputValues);
}
this.appRef.tick();
delete store.restoreInputValues;
}
hmrOnDestroy(store: StoreType) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
// recreate root elements
store.disposeOldHosts = createNewHosts(cmpLocation);
// save input values
store.restoreInputValues = createInputTransfer();
// remove styles
removeNgStyles();
}
hmrAfterDestroy(store: StoreType) {
// display new elements
store.disposeOldHosts();
delete store.disposeOldHosts;
}
}
| errogien/cockpit-seed | src/browser/app/app.module.ts | TypeScript | mit | 3,239 |
package postgresql
import (
"bytes"
"fmt"
"github.com/spf13/viper"
"io"
"strconv"
)
func readInt32(c *PGConn) uint32 {
var ret uint32 = uint32(c.buf[c.idx+0])
ret <<= 8
ret += uint32(c.buf[c.idx+1])
ret <<= 8
ret += uint32(c.buf[c.idx+2])
ret <<= 8
ret += uint32(c.buf[c.idx+3])
c.idx += 4
return ret
}
func readInt16(c *PGConn) uint16 {
var ret uint16 = uint16(c.buf[c.idx+0])
ret <<= 8
ret += uint16(c.buf[c.idx+1])
c.idx += 2
return ret
}
func readInt8(c *PGConn) byte {
c.idx += 1
return c.buf[c.idx-1]
}
func readByteN(c *PGConn, len int) []byte {
c.idx += len
return c.buf[c.idx-len : c.idx]
}
func readString(c *PGConn) string {
idx := bytes.IndexByte(c.buf[c.idx:], 0)
c.idx += idx + 1
return string(c.buf[c.idx-idx-1 : c.idx-1])
}
func getInt32FromByteSlice(bs []byte) uint32 {
var ret uint32 = uint32(bs[0])
ret <<= 8
ret += uint32(bs[1])
ret <<= 8
ret += uint32(bs[2])
ret <<= 8
ret += uint32(bs[3])
return ret
}
func getIntFromByteSlice(bs []byte, len int) int {
ret, _ := strconv.Atoi(string(bs))
return ret
}
func ReadMessage(c *PGConn) (message interface{}, err error) {
header := make([]byte, 5)
n, e := c.conn.Read(header)
if e != nil {
return nil, e
}
if n != 5 {
return nil, fmt.Errorf("cannot read message header (%d)", n)
}
length := getInt32FromByteSlice(header[1:])
if viper.GetBool("info") {
fmt.Printf("type (%c)\n", header[0])
}
body := make([]byte, length-4)
n, e = io.ReadFull(c.conn, body)
if e != nil {
return nil, e
}
if n != int(length)-4 {
return nil, fmt.Errorf("cannot read message body (%d)", n)
}
c.buf = body
c.idx = 0
switch header[0] {
case 'R':
return readAuthenticationMessage(c, length)
case 'S':
name := readString(c)
value := readString(c)
return ParameterStatus{name, value}, nil
case 'K':
processId := readInt32(c)
secretKey := readInt32(c)
return BackendKeyData{processId, secretKey}, nil
case 'Z':
transactionStatus := readInt8(c)
return ReadyForQuery{transactionStatus}, nil
case 'C':
commandTag := readString(c)
return CommandComplete{commandTag}, nil
case 'G': // CopyInResponse
fallthrough
case 'H': // CopyOutResponse, -Flush-
case 'T':
count := int(readInt16(c))
fieldInfos := make([]FieldInfo, 0, count)
for i := 0; i < count; i++ {
name := readString(c)
tableObjectId := readInt32(c)
columnAttributeNum := readInt16(c)
datatypeObjectId := readInt32(c)
datatypeSize := readInt16(c)
typeModifier := readInt32(c)
formatCode := readInt16(c)
fieldInfos = append(fieldInfos, FieldInfo{name, tableObjectId,
columnAttributeNum, datatypeObjectId, datatypeSize,
typeModifier, formatCode})
}
return RowDescription{fieldInfos}, nil
case 'D':
count := int(readInt16(c))
valueInfos := make([]ValueInfo, 0, count)
for i := 0; i < count; i++ {
valueLen := readInt32(c)
value := readByteN(c, int(valueLen))
valueInfos = append(valueInfos, ValueInfo{valueLen, value})
}
return DataRow{valueInfos}, nil
case 'I':
return EmptyQueryResponse{}, nil
case 'E':
fallthrough
case 'N':
errorInfos := make([]ErrorInfo, 0)
for {
code := readInt8(c)
if code == 0 {
break
}
value := readString(c)
errorInfos = append(errorInfos, ErrorInfo{code, value})
}
if header[0] == 'E' {
return ErrorResponse{errorInfos}, nil
} else {
return NoticeResponse{errorInfos}, nil
}
}
return nil, nil
}
func readAuthenticationMessage(c *PGConn, length uint32) (interface{}, error) {
subtype := readInt32(c)
switch subtype {
case 0:
return AuthenticationOk{}, nil
case 2:
return AuthenticationKerberosV5{}, nil
case 3:
return AuthenticationCleartextPassword{}, nil
case 5:
var salt [4]byte
for i := 0; i < 4; i++ {
salt[i] = readInt8(c)
}
return AuthenticationMD5Password{salt}, nil
case 6:
return AuthenticationSCMCredential{}, nil
case 7:
return AuthenticationGSS{}, nil
case 9:
return AuthenticationSSPI{}, nil
case 8:
data := readByteN(c, int(length)-8)
return AuthenticationGSSContinue{data}, nil
}
return nil, nil
}
func StringField(fi FieldInfo) string {
switch fi.DatatypeObjectId {
case 0x17:
return "int"
case 0x412:
return fmt.Sprintf("char(%d)", fi.TypeModifier-4)
case 0x413:
return fmt.Sprintf("varchar(%d)", fi.TypeModifier-4)
case 0x43a:
return "date"
case 0x43f9:
return "enum"
}
return fmt.Sprintf("unknown DatatypeObjectId (%x)", fi.DatatypeObjectId)
}
func StringRows(drs []DataRow, rd RowDescription) string {
var buffer bytes.Buffer
for i := 0; i < len(drs); i++ {
buffer.WriteString(StringRow(drs[i], rd))
buffer.WriteString("\n")
}
if buffer.Len() > 0 {
buffer.Truncate(buffer.Len() - 1)
}
return buffer.String()
}
func StringRow(dr DataRow, rd RowDescription) string {
var buffer bytes.Buffer
buffer.WriteString("{ ")
for i := 0; i < len(dr.ValueInfos); i++ {
vi := dr.ValueInfos[i]
fi := rd.FieldInfos[i]
switch fi.DatatypeObjectId {
case 0x17:
buffer.WriteString(fmt.Sprintf("%d, ",
getIntFromByteSlice(vi.Value, int(vi.ValueLen))))
case 0x412:
buffer.WriteString(fmt.Sprintf("\"%s\", ", string(vi.Value)))
case 0x413:
buffer.WriteString(fmt.Sprintf("\"%s\", ", string(vi.Value)))
case 0x43a:
buffer.WriteString(fmt.Sprintf("\"%s\", ", string(vi.Value)))
case 0x43f9:
buffer.WriteString(fmt.Sprintf("'%c', ", vi.Value[0]))
}
}
if buffer.Len() > 2 {
buffer.Truncate(buffer.Len() - 2)
} else {
buffer.Truncate(buffer.Len() - 1)
}
buffer.WriteString(" }")
return buffer.String()
}
| maczniak/backstage | postgresql/parse.go | GO | mit | 5,552 |
/**
* Vector
*/
(function()
{
var global = this,
nspace = global.Util,
Exception = global.Exception,
math = global.mathjs();
/**
*
* @type Vector
* @param {Array} basis The basis vectors, ordered correctly, orthonormal and complete
*/
var Vector = nspace.Vector = function(basis)
{
if (!basis || ('length' in basis && basis.length === 0))
{
throw new Exception.InvalidPreparation('Basis vector cannot be empty');
}
// Set basis and init components with same length and value of 1
this.basis = basis;
this.components = basis.map(function()
{
return 1;
});
};
/**
* Computes the inner product of two vectors, <v1|v2>
*
* @returns {mathjs} Scalar
*/
Vector.innerProduct = function(v1, v2)
{
var basis1 = v1.getBasis(),
basis2 = v2.getBasis();
// Must have same basis lengths
if (basis1.length !== basis2.length)
{
throw new Exception.InvalidPreparation('Basis must be same length');
}
var comp1 = v1.getComponents(),
comp2 = v2.getComponents();
var product = 0;
// Essentially a foil operation, but this will support greater than two terms
for (var i = 0; i < basis1.length; i++)
{
for (var j = 0; j < basis2.length; j++)
{
var comp = math.multiply(math.conj(comp1[i]), comp2[j]);
var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]);
product = math.add(product, math.multiply(comp, basis));
}
}
return product.get([0,0]);
};
/**
* Computes the outer product of two vectors,
* (|v1x><v1x| + |v1y><v1y|)(|v2x> + |v2y>)
*
* @returns {undefined}
*/
Vector.outerProduct = function(v1, v2)
{
var basis1 = v1.getBasis(),
basis2 = v2.getBasis();
// Must have same basis lengths
if (basis1.length !== basis2.length)
{
throw new Exception.InvalidPreparation('Basis must be same length');
}
var comp1 = v1.getComponents(),
comp2 = v2.getComponents();
var product = new Vector(basis1);
// Essentially a foil operation, but this will support greater than two terms
for (var i = 0; i < basis1.length; i++)
{
var productComp = 0;
for (var j = 0; j < basis2.length; j++)
{
var comp = math.multiply(math.conj(comp1[i]), comp2[j]);
var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]);
productComp = math.add(productComp, math.multiply(comp, basis));
}
product.setComponent(i, productComp.get([0,0]));
}
return product;
};
/**
*
*/
Vector.prototype =
{
basis: null,
components: null,
/**
*
* @param {Number} index The basis vector index
* @param {Mixed} value
* @returns {Vector}
*/
setComponent: function(index, value)
{
if (index >= this.components.length)
{
throw new Exception.InvalidProperty('Invalid basis index');
}
this.components[index] = value;
return this;
},
/**
*
* @param {Number} index The basis vector index
* @returns {Number}
*/
getComponent: function(index)
{
if (index >= this.components.length)
{
throw new Exception.InvalidProperty('Invalid basis index');
}
return this.components[index];
},
/**
*
* @param {Array} values
* @returns {Vector}
*/
setComponents: function(values)
{
if (values.length !== this.components.length)
{
throw new Exception.InvalidProperty('Invalid');
}
this.components = values;
return this;
},
/**
*
* @returns {Number[]}
*/
getComponents: function()
{
return this.components;
},
/**
*
* @returns {mathjs}
*/
getBasis: function()
{
return this.basis;
},
/**
* Applies a scalar to the vector components, simulates applying a scalar to
* vector mathematically
*
* @param {Number} scalar
* @returns {Vector}
*/
scale: function(scalar)
{
this.components = this.components.map(function(component)
{
return math.multiply(scalar, component);
});
return this;
},
/**
* Determines the magnitude of the vector, sqrt(x*x + y*y)
*
* @returns {mathjs}
*/
getMagnitude: function()
{
var magnitude = 0;
for (var i = 0; i < this.components.length; i++)
{
var c = this.components[i];
magnitude = math.add(magnitude, math.multiply(math.conj(c),c));
}
return math.sqrt(magnitude);
},
/**
* Multiplies the components by a scalar to that makes the magnitude 1
*
* @returns {Vector}
*/
normalize: function()
{
var magSq = Vector.innerProduct(this, this);
// Already normalized
if (magSq === 1)
{
return this;
}
return this.scale(math.divide(1,math.sqrt(magSq)));
},
/**
*
* @returns {Vector}
*/
clone: function()
{
var v = new Vector(this.getBasis());
v.setComponents(this.getComponents());
return v;
},
/**
* Returns a new vector that is just one basis dir, by index of the basis
* set
*
* @param {Number} index
* @returns {Vector}
*/
getBasisVector: function(index)
{
var v = this.clone();
// Set all other component values to zero other than the index
v.setComponents(this.components.map(function(val, i)
{
return (i === index)
? val
: 0;
}));
return v.normalize();
}
};
})();
| bjester/quantum-probability | lib/util/Vector.js | JavaScript | mit | 5,940 |
'use strict';
export default function routes($routeProvider) {
'ngInject';
$routeProvider.when('/new_component', {
template: '<about></about>'
});
$routeProvider.when('/new_component/:somethingToPrint', {
template: '<about></about>'
});
}
| whoppa/COMP-3705 | client/app/Component/new_component.routes.js | JavaScript | mit | 259 |
module BWAPI
class Client
# Ping module for ping endpoints
module Ping
# Get ping checking access and available HTTP verbs
#
# @return [Hashie::Mash] User id and name
def get_ping
get "ping"
end
# Post ping checking access and available HTTP verbs
#
# @return [Hashie::Mash] User id and name
def create_ping
post "ping"
end
# Put ping checking access and available HTTP verbs
#
# @return [Hashie::Mash] User id and name
def update_ping
put "ping"
end
# Patch ping checking access and available HTTP verbs
#
# @return [Hashie::Mash] User id and name
def patch_ping
patch "ping"
end
# Delete ping checking access and available HTTP verbs
#
# @return [Hashie::Mash] User id and name
def delete_ping
delete "ping"
end
end
end
end | benSlaughter/bwapi | lib/bwapi/client/ping.rb | Ruby | mit | 937 |
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
# Recursion
# Sort the array at first, then use the recursion to find
# the result, Time O(n^2)
# 96ms
def combinationSum(self, candidates, target):
candidates.sort()
self.result = []
self.dfs(candidates,target,0,[])
return self.result
def dfs(self,candidates,target,start,reslist):
length = len(candidates)
if target == 0:
return self.result.append(reslist)
for i in xrange(start,length):
if target < candidates[i]:return
self.dfs(candidates,target-candidates[i],i,reslist+[candidates[i]])
# DFS, not sort array (220ms)
def combinationSum(self, candidates, target):
self.result = []
self.dfs(candidates,0,target,[])
return self.result
def dfs(self,can,cursum,target,res):
if cursum > target: return
if cursum == target:
self.result.append(res)
return
for i in xrange(len(can)):
if not res or res[len(res)-1] <= can[i]:
self.dfs(can,cursum+can[i],target,res+[can[i]])
For the combination_sum2, just change the start index from i to the i+1
Time Complexity: T(n) = T(n-1) + 1 = O(n) ?
| UmassJin/Leetcode | Array/combination_sum1.py | Python | mit | 1,940 |
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using MongoDB.Driver;
using System;
namespace Microsoft.DataTransfer.MongoDb.Shared
{
sealed class MongoTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
return
// If it we use incompatible driver...
HasException<MongoIncompatibleDriverException>(ex) ||
// ..or it is MongoConnectionException...
(HasException<MongoConnectionException>(ex) &&
// ..but not authentication issue
!HasException<MongoAuthenticationException>(ex));
}
private bool HasException<T>(Exception root)
where T : Exception
{
if (root == null)
return false;
return root is T || HasException<T>(root.InnerException);
}
}
}
| Azure/azure-documentdb-datamigrationtool | MongoDb/Microsoft.DataTransfer.MongoDb/Shared/MongoTransientErrorDetectionStrategy.cs | C# | mit | 961 |
<?php
include_once ROOT. '/cabinet/site/models/Login.php';
class LoginController{
//Загрузка страницы авторизации
public function actionLogin(){
if(isset($_SESSION['id_user'])){
SRC::redirect('/panel');
}
SRC::template('site', 'login', 'login');
return true;
}
//Авторизация пользователя
public function actionSingnIn(){
$email = SRC::validator($_POST['email']);
$password = SRC::validator(md5($_POST['password']));
$result = Login::signIn($email, $password);
if($result){
$_SESSION['cabinet'] = explode(',',','.$result[0]['type_user']);
$id_user= $_SESSION['id_user'] = $result[0]['id_user'];
$result_profile = Login::profileFarmer($id_user);
if(!empty($result_profile[0]['region'])){
$_SESSION['farmer_profile'] = true;
}
if(empty($result_profile[0]['region'])){
$_SESSION['farmer_profile'] = false;
}
setcookie("name_user", $result[0]['name'], time()+3600*24*7);
setcookie("last_name_user", $result[0]['last_name'], time()+3600*24*7);
// setcookie("position", $result[0]['id_user'], time()+3600);
// setcookie("last_login", $result[0]['id_user'], time()+3600);
SRC::redirect('/panel');
}
SRC::redirect('/login');
return true;
}
//Выход, удаление сессий и куки
public function actionExit(){
unset($_SESSION['cabinet']);
unset($_SESSION['id_user']);
unset($_SESSION['farmer_profile']);
SRC::redirect('/login');
}
//Страница кабинетов
public function actionCabinet(){
if(!isset($_SESSION['id_user'])){
SRC::redirect('/login');
}
if(count($_SESSION['cabinet'])==2){
SRC::redirect('/'.$_SESSION['cabinet'][1]);
};
SRC::template('site', 'cabinet', 'cabinet');
return true;
}
}
| stas383/newagro | cabinet/site/controllers/LoginController.php | PHP | mit | 2,091 |
package com.syynth.libcfg;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
/**
* @author syynth
* @since 2/18/14
*/
public class Config {
private final Document config;
private final File file;
/**
* Create a Config document with the file located at <code>name</code>.
* @param name
*/
public Config(String name) {
Document cfg;
file = new File(name);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
cfg = builder.parse(file);
} catch (ParserConfigurationException | SAXException | IOException ex) {
cfg = null;
}
config = cfg;
}
public boolean getBoolean(String name) {
return Boolean.parseBoolean(getProperty(name));
}
public boolean getBoolean(String group, String name) {
return Boolean.parseBoolean(getProperty(group, name));
}
public int getInt(String name) {
return Integer.parseInt(getProperty(name));
}
public int getInt(String group, String name) {
return Integer.parseInt(getProperty(group, name));
}
public float getFloat(String name) {
return Float.parseFloat(getProperty(name));
}
public float getFloat(String group, String name) {
return Float.parseFloat(getProperty(group, name));
}
public double getDouble(String name) {
return Double.parseDouble(getProperty(name));
}
public double getDouble(String group, String name) {
return Double.parseDouble(getProperty(group, name));
}
public String getProperty(String property) {
return getProperty("global", property);
}
public String getProperty(String group, String property) {
if (config != null) {
return "";
}
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
try {
return (String) path.evaluate("//propertyGroup[@name='" + group
+ "']/property[@name='" + property + "']/text()", config, XPathConstants.STRING);
} catch (XPathExpressionException ex) { return ""; }
}
public HashMap<String, String> getPropertyGroup(String groupName) {
HashMap<String, String> group = new HashMap<>();
if (config == null) {
return group;
}
try {
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
NodeList nl = (NodeList) path.evaluate("//propertyGroup[@name='" + groupName + "']/property", config, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); ++i) {
Element n = (Element) nl.item(i);
group.put(n.getAttribute("name"), n.getTextContent());
}
} catch (XPathExpressionException ignored) {}
return group;
}
public boolean setProperty(String group, String name, String value) {
XPathFactory factory = XPathFactory.newInstance();
XPathExpression xpr;
XPath xpath = factory.newXPath();
try {
xpr = xpath.compile("//propertyGroup[@name='" + group
+ "']/property[@name='" + name + "']/text()");
Node n = (Node) xpr.evaluate(config, XPathConstants.NODE);
n.setNodeValue(value);
return new XmlDocumentWriter().write(config, file);
} catch (XPathExpressionException ex) {
return false;
}
}
private static class XmlDocumentWriter {
public boolean write(Document doc, File file) {
TransformerFactory factory = TransformerFactory.newInstance();
try {
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
return false;
}
return true;
}
}
}
| Syynth/libcfg | src/com/syynth/libcfg/Config.java | Java | mit | 4,160 |
<?php
/**
* NOTICE OF LICENSE
*
* The MIT License
*
* Copyright (c) 2016 e-Boekhouden.nl
*
* 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.
*
* @package Eboekhouden_Export
* @copyright Copyright (c) 2016 e-Boekhouden.nl
* @license http://opensource.org/licenses/mit-license.php The MIT License
* @author e-Boekhouden.nl
*/
namespace Eboekhouden\Export\Block\Adminhtml\Rate;
use Magento\Tax\Block\Adminhtml\Rate\Form as Original;
use Eboekhouden\Export\Model\Tax\Attribute\Ebtaxcode;
class Form extends Original
{
// revert template to original module
protected $_template = 'Magento_Tax::rate/form.phtml';
protected function _prepareForm()
{
$response = parent::_prepareForm();
$fieldset = $this->getForm()->getElement('base_fieldset');
// dont want to override __construct so just init here for options
$ebtaxcodes = new Ebtaxcode;
$fieldset->addField(
'tax_ebvatcode',
'select',
[
'name' => 'tax_ebvatcode',
'label' => __('e-Boekhouden.nl BTW Code'),
'title' => __('e-Boekhouden.nl BTW Code'),
'class' => 'required-entry',
'required' => true,
'values' => $ebtaxcodes->toOptionArray()
]
);
return $response;
}
}
| eboekhouden/magento2-export | src/Block/Adminhtml/Rate/Form.php | PHP | mit | 2,374 |
package cn.org.rapid_framework.page.impl;
import java.util.List;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
/**
* 处理List的分页
* @author badqiu
* @see BasePage
*/
@Deprecated
public class ListPage extends Page {
/**
* 构建ListPage对象,完成List数据的分页处理
*
* @param elements List数据源
* @param pageNumber 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。
* 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。
* 这两种情况将重新更改当前页的页码,为最后一页编码。
* @param pageSize 每一页显示的条目数
*/
public ListPage(List elements, int pageNumber, int pageSize){
super(pageNumber,pageSize,elements.size());
List subList = ((List)elements).subList(getThisPageFirstElementNumber() - 1, getThisPageLastElementNumber());
setResult(subList);
}
public ListPage(List elements, PageRequest p){
this(elements,p.getPageNumber(),p.getPageSize());
}
}
| neolfdev/dlscxx | java_core_src/src/cn/org/rapid_framework/page/impl/ListPage.java | Java | mit | 1,198 |
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'firehon',
environment: environment,
contentSecurityPolicy: { 'connect-src': "'self' wss://*.firebaseio.com" },
firebase: 'https://firehon.firebaseio.com/',
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| nihey/firehon | config/environment.js | JavaScript | mit | 1,201 |
package callete.api.services.music.streams;
/**
* Implementing classes retrieve the meta data information
* about a stream, such as artist, station name, track name...
*/
public interface StreamMetaDataProvider {
/**
* Returns the name of the artist that is currently played.
*/
String getArtist();
/**
* Returns the name of the stream.
*/
String getName();
/**
* Returns the name of the stream.
*/
String getTitle();
/**
* Returns the URL the stream is streamed from.
*/
String getStreamUrl();
/**
* Returns false in the case that the stream is not playable.
*/
boolean isAvailable();
}
| syd711/callete | callete-api/src/main/java/callete/api/services/music/streams/StreamMetaDataProvider.java | Java | mit | 648 |
class TwainscanningController < ApplicationController
# skip_before_action :verify_authenticity_token
# protect_from_forgery except: :index
def home
end
def upload
uploaded_io = params[:RemoteFile]
upload_dir = Rails.root.join('public', 'upload')
unless Dir.exist?(upload_dir)
Dir.mkdir(upload_dir)
end
File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
end
| dynamsoftsamples/dwt-ruby-on-rails | app/controllers/twainscanning_controller.rb | Ruby | mit | 490 |
class User < ActiveRecord::Base
rolify
#default_scope :order => 'users.created_at DESC'
# added these 2 lines to add the Gravatar in the app
include Gravtastic
gravtastic :secure => true,
:filetype => :gif,
:size => 30
enum locale: [:en, :es, :it, :tl]
# NO EMAIL IN DEV
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :authentication_keys => [:login]
# Setup accessible (or protected) attributes for your model. Add also :username after add a column for the Devise Model
validates :email, :presence => true
has_many :bookmarks, :dependent => :destroy
has_many :feeds
has_many :feedlists
# SEO User url profile
extend FriendlyId
friendly_id :username
# [A.] snippet to login using username or email according the Devise best practice
def login=(login)
@login = login
end
def login
@login || self.username || self.email
end
# [A.] end snippet
# [B.] snippet to login using username or email
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions.to_h).first
end
end
# [B.] end snippet
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.username = auth.info.name
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
#user.name = auth.info.name # assuming the user model has a name
#user.image = auth.info.image # assuming the user model has an image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
#for me the follow line save without confirmation
user.skip_confirmation!
end
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
def mailboxer_email(object)
email
end
private
def add_user_to_mailchimp
#return if email.include?(ENV['ADMIN_EMAIL'])
mailchimp = Gibbon::API.new
result = mailchimp.lists.subscribe({
:id => ENV['MAILCHIMP_LIST_ID'],
:merge_vars => {:FNAME => self.username},
:email => {:email => self.email},
:double_optin => false,
:update_existing => true,
:send_welcome => true
})
Rails.logger.info("Subscribed #{self.email} to MailChimp") if result
end
def remove_user_from_mailchimp
mailchimp = Gibbon::API.new
result = mailchimp.lists.unsubscribe({
:id => ENV['MAILCHIMP_LIST_ID'],
:email => {:email => self.email},
:delete_member => true,
:send_goodbye => false,
:send_notify => true
})
Rails.logger.info("Unsubscribed #{self.email} from MailChimp") if result
end
end | kepasa-project/kepasa-feeds-aggregator | app/models/user.rb | Ruby | mit | 3,229 |
define([
'base/Module',
'./show/Controller'
],function(Module, ShowController){
var mod = Module('HeaderModule', {autoStart: false});
var API = {
showHeader: function() {
var controller = new ShowController({
region: mod.kernel.headerRegion
});
controller.showHeader();
}
};
mod.on('start', function(){
API.showHeader();
});
}); | alexbrouwer/Symfony2 | src/Gearbox/ClientBundle/Resources/public/js/modules/header/main.js | JavaScript | mit | 435 |
export function pluralize(count, word) {
return count === 1 ? word : word + 's';
}
export function classNames(...args) {
// based on https://github.com/JedWatson/classnames
let classes = '';
args.forEach(arg => {
if (arg) {
const argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes += ' ' + arg;
} else if (Array.isArray(arg)) {
classes += ' ' + classNames(...arg);
} else if (argType === 'object') {
Object.keys(arg).forEach(key => {
if (arg[key]) {
classes += ' ' + key;
}
});
}
}
});
return classes.substr(1);
}
export function uuid() {
let i, random;
let uuid = '';
for (i = 0; i < 32; i++) {
random = Math.random() * 16 | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += '-';
}
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random))
.toString(16);
}
return uuid;
}
| bicyclejs/bicycle | example/client/utils.js | JavaScript | mit | 981 |
module GeoCalculator
VERSION = '0.0.1'
end
| goddamnyouryan/geo-calculator | lib/geo-calculator/version.rb | Ruby | mit | 45 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('artist', '0002_auto_20150322_1630'),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('location', models.CharField(max_length=500, verbose_name='Location')),
('date_time', models.DateTimeField(verbose_name='Date & Time')),
('artist', models.ForeignKey(to='artist.Artist')),
],
options={
},
bases=(models.Model,),
),
]
| fotcorn/liveinconcert | event/migrations/0001_initial.py | Python | mit | 777 |
module SmtRails
class Engine < ::Rails::Engine
initializer "sprockets.smt_rails", :after => "sprockets.environment", :group => :all do |app|
next unless app.assets
app.assets.register_engine(".#{SmtRails.template_extension}", Tilt)
app.config.assets.paths << Rails.root.join("app", "views")
end
end
end | constellationsoftware/smt_rails | lib/smt_rails/engine.rb | Ruby | mit | 332 |
/**
* @file routing.hpp
* @brief this file implements the application routing.
* @author nocotan
* @date 2016/11/4
*/
#ifndef ROUTING_HPP
#define ROUTING_HPP
#include <functional>
#include <string>
namespace ots {
/**
* @struct header
* @brief header
*/
struct header {
const std::string name;
const std::string value;
};
/**
* @struct request
* @brief request
*/
struct request {
const std::string method;
const std::string path;
const std::string source;
const std::string destination;
const std::string body;
const std::vector<header> headers;
};
/**
* @struct otusRouting
* @brief routing
*/
struct otusRouting {
const std::string route;
const std::string method;
const std::function<std::string(request)> action;
};
}
#endif
| nocotan/otus | include/otus/routing.hpp | C++ | mit | 912 |
class Users::RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
end
def account_update_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password)
end
end | kkomaz/co-code | app/controllers/users/registrations_controller.rb | Ruby | mit | 371 |
'use babel';
//showSearch
import FoldNavigatorView from './fold-navigator-view';
import fuzzaldrinPlus from 'fuzzaldrin-plus';
import _ from 'lodash';
import {
CompositeDisposable
} from 'atom';
export default {
config: {
autofold: {
title: 'Autofold on open',
description: 'Autofold all folds when you open a document. config.cson key : autofold',
type: 'boolean',
default: false
},
keepFolding: {
title: 'Keep code folded.',
description: 'Everytime you click on one of the fold navigator element all code folds will be folded before the selected fold opens. Usefull if you want to keep your code folded all the time. Note that if you are using ctrl-alt-cmd-up/down keys to navigate it will not close the folds. Also you can temporarily enable/disable this behaviour by holding down the option key while you click. config.cson key : keepFolding',
type: 'boolean',
default: false
},
showLineNumbers: {
title: 'Show line number.',
description: 'Show line numbers in fold navigator. config.cson key : showLineNumbers',
type: 'boolean',
default: true
},
indentationCharacter: {
title: 'Indentation character.',
description: 'The character used for indentation in the fold navigator panel. config.cson key : indentationCharacter',
type: 'string',
default: 'x'
},
maxLineContentLength: {
title: 'Maximum line length.',
description: 'Fold Navigator will take the line on which the fold is on but if the line is longer than this many characters then it will truncate it. config.cson key : maxLineContentLength',
type: 'integer',
default: 60
},
minLineLength: {
title: 'Minimum line length.',
description: 'Sometimes the fold falls on line which contains very little information. Typically comments like /** are meaningless. If the line content is less then this many characters use the next line for the fold description. config.cson key : minLineLength',
type: 'integer',
default: 6
},
keepFoldingAllTime: {
title: 'Keep code folded even on shortcuts.',
description: 'It will fold all folds before opening a new one. config.cson key : keepFoldingAllTime',
type: 'boolean',
default: false
},
autoScrollFoldNavigatorPanel: {
title: 'Auto scroll fold navigator panel.',
description: 'Scrolls the fold navigator panel to the active fold. config.cson key : autoScrollFoldNavigatorPanel',
type: 'boolean',
default: true
},
unfoldAllSubfolds: {
title: 'Unfold all subfolds.',
description: 'When a fold is selected/active all subfolds will be unfolded as well. When you have lots of subfolds to open this can be sluggish. config.cson key : unfoldAllSubfolds',
type: 'boolean',
default: true
},
maxFoldLevel: {
title: 'Maximum fold level fold navigator will list.',
description: 'It is possibly not much use listing every single fold. With this option you can limit the fold level depth we list on the panel hopefully giving you a better overview of the code. config.cson key : maxFoldLevel',
type: 'integer',
default: 10,
},
whenMatchedUsePreviousLine: {
title: 'Previous line should be used for description.',
description: 'Comma separated values. If the content of the line matches any of these values the previous line is going to be used for the fold description. This is so that we avoid listing just a single bracket for example which would be pretty meaningless.',
type: 'string',
default: '{,{ ',
},
log: {
title: 'Turn on logging',
description: 'It might help to sort out mysterious bugs.',
type: 'boolean',
default: false,
},
},
activate(state) {
//console.log(arguments.callee.name);
/*
this.settings = null;
*/
this.settings = null;
this.iniSettings();
/*
this.lines2fold = [];
Key is the line number and the value is the line number of the last fold looped through in the document.
currently the fold ending are not observed maybe I should change this in the future note that we will work with the line numbers displayed and not the actuall line number which can be 0
*/
this.lines2fold = [];
/*
this.folds = [];
array of row numbers where the folds are
*/
this.folds = [];
/*
this.visibleFolds = [];
same as this.folds but limited by this.settings.maxFoldLevel
*/
this.visibleFolds = [];
/*
this.foldObjects = {};
we need this to be able to navigate levels an example bellow see this.parse it should really be a new Map();
{
line: i,
children: [],
parent: parent,
indentation: indentLevel,
content: '',
}
*/
this.foldObjects = {};
/*
exactly the same as
this.foldObjects but came later because of fuzzaldrin-plus which only seems to work with arrays as far as I can tell
*/
this.foldObjectsArray = [];
/*
this.foldLevels = {};
row numbers of the folds orgenised by level usefull for the commands which fold unfold levels
*/
this.foldLevels = {};
/*
this.history = [];
only used as a short term log so that we can navigate fold level down
*/
this.history = [];
/*
this.activeFold
line number of the fold which we are on this is what gets highlighted on the fold navigator panel item
*/
this.activeFold = null;
// subscriptions
this.subscriptions = new CompositeDisposable();
this.onDidChangeCursorPositionSubscription = null;
this.foldNavigatorView = new FoldNavigatorView(state.foldNavigatorViewState);
// when active pane item changed parse code and change content of navigator panel
atom.workspace.observeActivePaneItem((pane) => {
this.observeActivePaneItem(pane)
});
// parse content of editor each time it stopped changing
atom.workspace.observeTextEditors((editor) => {
this.observeTextEditors(editor)
});
// attach onclick event to the fold navigator lines
this.navigatorElementOnClick();
this.registerCommands();
/*
this.panel = null;
foldnavigator panel
*/
this.panel = null;
this.addNavigatorPanel();
/*
this.searchModal
*/
this.searchModal = null;
this.searchModalElement = null;
this.searchModalInput = null;
this.searchModalItems = null;
this.addSearchModal();
},
// observer text editors coming and going
observeTextEditors(editor) {
//console.log(arguments.callee.name);
if (this.settings && this.settings.autofold && editor){
editor.foldAll();
}
},
// every time the active pane changes this will get called
observeActivePaneItem(pane) {
//console.log(arguments.callee.name);
var editor = atom.workspace.getActiveTextEditor();
var listener;
var editorView;
if (!editor)
return;
//dispose of previous subscription
if (this.onDidChangeCursorPositionSubscription) {
this.onDidChangeCursorPositionSubscription.dispose();
}
// follow cursor in fold navigator register subscription so that we can remove it
this.onDidChangeCursorPositionSubscription = editor.onDidChangeCursorPosition(
_.debounce((event) => this.onDidChangeCursorPosition(event), 500)
);
//dispose of previous subscription
if (this.onDidStopChangingSubscription) {
this.onDidStopChangingSubscription.dispose();
}
// if document changed subscription
this.onDidStopChangingSubscription = editor.onDidStopChanging(
_.debounce((event) => this.parse(editor), 500)
);
this.parse(editor);
},
clearSearchModal() {
if (!this.searchModal)
return;
this.searchModalItems.innerHTML = '';
this.searchModalInput.value = '';
},
alignEditorToSearch() {
var selectedArr = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item-selected');
var selected = selectedArr[0];
var editor = atom.workspace.getActiveTextEditor();
if (selected && selected.dataset.row >= 0) {
this.moveCursor(selected.dataset.row, false);
}
},
searchModalOnClick(event) {
var row;
var editor = atom.workspace.getActiveTextEditor();
var clicked = null;
this.hideSearch();
if (event.target.matches('.fold-navigator-search-modal-item')) {
clicked = event.target;
} else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-search-modal-item')) {
clicked = event.target.parentNode;
}
if (!clicked)
return;
row = clicked.dataset.row;
//problem
if (!row)
return;
this.moveCursor(row, false);
},
addSearchModal() {
this.searchModalElement = document.createElement('div');
this.searchModalElement.classList.add('fold-navigator-search-modal');
this.searchModalElement.classList.add('native-key-bindings');
this.searchModalInput = document.createElement('input');
this.searchModalItems = document.createElement('div');
this.searchModalElement.appendChild(this.searchModalInput);
this.searchModalElement.appendChild(this.searchModalItems);
this.searchModal = atom.workspace.addModalPanel({
item: this.searchModalElement,
visible: false
});
// on blur
this.searchModalInput.addEventListener('blur', (event) => {
// delay hiding because of the on click event won't fire otherwise WHAT an ugly way to solve it :)
setTimeout(() => {
this.hideSearch();
}, 200);
});
// on click
this.searchModalElement.addEventListener('click', (event) => {
this.searchModalOnClick(event);
}, true);
// on input
this.searchModalInput.addEventListener('input', () => {
this.searchModalItems.innerHTML = '';
var query = this.searchModalInput.value;
if (!query || query.length < 1)
return;
var filteredItems = fuzzaldrinPlus.filter(this.foldObjectsArray, query, {
key: 'content'
});
var html = '';
filteredItems.forEach((item, index) => {
let selected = ' fold-navigator-search-modal-item-selected';
if (index > 0) {
selected = '';
}
//let html2add = '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>';
let indentHtml = '';
for (let j = 0; j < item.indentation; j++) {
indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>';
}
html += '<div class="fold-navigator-search-modal-item fold-navigator-item-indent-' + item.indentation + selected + '" data-row="' + item.line + '">' + indentHtml + item.content + '</div>';
});
this.searchModalItems.innerHTML = html;
//var matches = fuzzaldrinPlus.match(displayName, this.searchModalInput.value);
//filterQuery box from text input
//items ??
// { key: @getFilterKey() }
});
this.searchModalElement.addEventListener('keydown', (e) => {
var sc = 'fold-navigator-search-modal-item-selected';
if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode == 13 || e.keyCode == 27) {
var items = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item');
if (!items)
return;
// remove selected
var selectedArr = this.searchModalItems.getElementsByClassName(sc);
var selected = selectedArr[0];
if (selected) {
selected.classList.remove(sc);
}
var first = items[0] ? items[0] : false;
var last = items[items.length - 1] ? items[items.length - 1] : false;
var next = null;
if (e.keyCode === 38) {
// up
if (selected) {
next = selected.previousElementSibling;
}
} else if (e.keyCode === 40) {
// down
if (selected) {
next = selected.nextElementSibling;
}
} else if (e.keyCode === 27) {
// esc
this.hideSearch();
} else if (e.keyCode == 13) {
// enter
if (selected) {
if (selected.dataset.row >= 0) {
let editor = atom.workspace.getActiveTextEditor();
this.moveCursor(selected.dataset.row, false);
this.hideSearch();
}
}
}
// end of line or not selected
if (!next) {
if (e.keyCode === 38)
next = last;
else {
next = first;
}
}
if (next) {
next.classList.add(sc);
}
}
});
//var matches = fuzzaldrinPlus.match(displayName, filterQuery)
},
hideSearch() {
this.searchModal.hide();
let editor = atom.workspace.getActiveTextEditor();
if (editor)
atom.views.getView(editor).focus();
},
showSearch() {
if (!editor)
return;
this.searchModal.show();
this.searchModalInput.focus();
this.searchModalInput.select();
},
toggleSearch() {
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if (this.searchModal.isVisible()) {
this.searchModal.hide();
atom.views.getView(editor).focus();
} else {
this.searchModal.show();
this.searchModalInput.focus();
this.searchModalInput.select();
}
},
onDidChangeCursorPosition(event) {
//console.log(arguments.callee.name);
this.selectRow(event.newBufferPosition.row);
},
addNavigatorPanel() {
//console.log(arguments.callee.name);
var element = this.foldNavigatorView.getElement();
if (atom.config.get('tree-view.showOnRightSide')) {
this.panel = atom.workspace.addLeftPanel({
item: element,
visible: false
});
} else {
this.panel = atom.workspace.addRightPanel({
item: element,
visible: false
});
}
},
iniSettings() {
//console.log(arguments.callee.name);
var editor = atom.workspace.getActiveTextEditor();
var languageSettings = null;
if (editor) {
let scope = editor.getGrammar().scopeName;
languageSettings = atom.config.get('fold-navigator', {
'scope': [scope]
});
}
this.settings = atom.config.get('fold-navigator');
if (languageSettings){
Object.assign(this.settings, languageSettings);
}
// parse the comma separated string whenMatchedUsePreviousLine
if(this.settings.whenMatchedUsePreviousLine && this.settings.whenMatchedUsePreviousLine.trim() != ''){
this.settings.whenMatchedUsePreviousLineArray = this.settings.whenMatchedUsePreviousLine.split(',');
if(this.settings.whenMatchedUsePreviousLineArray.constructor !== Array){
this.settings.whenMatchedUsePreviousLineArray = null;
}
}
},
registerCommands() {
//"ctrl-alt-cmd-up": "fold-navigator:previousFoldAtCurrentLevel",
//"ctrl-alt-cmd-down": "fold-navigator:nextFoldAtCurrentLevel",
//"ctrl-alt-cmd-up": "fold-navigator:previousFold",
//"ctrl-alt-cmd-down": "fold-navigator:nextFold",
//
//console.log(arguments.callee.name);
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggle': () => this.toggle()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:open': () => this.open()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:close': () => this.close()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:previousFold': () => this.previousFold()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:nextFold': () => this.nextFold()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:moveLevelUp': () => this.moveLevelUp()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:moveLevelDown': () => this.moveLevelDown()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:nextFoldAtCurrentLevel': () => this.nextFoldAtCurrentLevel()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:previousFoldAtCurrentLevel': () => this.previousFoldAtCurrentLevel()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldSubfolds': () => this.unfoldSubfoldsPublic()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldActive': () => this.foldActivePublic()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldAtLevel1': () => this.unfoldAtLevel1()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldAtLevel2': () => this.unfoldAtLevel2()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldAtLevel3': () => this.unfoldAtLevel3()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldAtLevel4': () => this.unfoldAtLevel4()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:unfoldAtLevel5': () => this.unfoldAtLevel5()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldAtLevel1': () => this.foldAtLevel1()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldAtLevel2': () => this.foldAtLevel2()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldAtLevel3': () => this.foldAtLevel3()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldAtLevel4': () => this.foldAtLevel4()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:foldAtLevel5': () => this.foldAtLevel5()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleFoldsLevel1': () => this.toggleFoldsLevel1()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleFoldsLevel2': () => this.toggleFoldsLevel2()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleFoldsLevel3': () => this.toggleFoldsLevel3()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleFoldsLevel4': () => this.toggleFoldsLevel4()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleFoldsLevel5': () => this.toggleFoldsLevel5()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleSearch': () => this.toggleSearch()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'fold-navigator:toggleActiveFold': () => this.toggleActiveFold()
}));
},
previousFold() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
var folds = this.visibleFolds;
if (!folds || folds.length === 0)
return;
//console.log(arguments.callee.name);
this.clearHistory();
var fold = this.foldNavigatorView.getActiveFold();
var index = folds.indexOf(fold);
var previous;
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if (index !== 0) {
previous = folds[index - 1];
} else {
previous = folds[folds.length - 1];
}
if (previous || previous === 0) {
this.moveCursor(previous);
}
},
nextFold() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
//console.log(arguments.callee.name);
this.clearHistory();
var folds = this.visibleFolds;
if (!folds || folds.length === 0)
return;
var fold = this.foldNavigatorView.getActiveFold();
var index = folds.indexOf(fold);
var next;
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if (folds.length !== (index + 1)) {
next = folds[index + 1];
} else {
next = folds[0];
}
if (next || next === 0) {
this.moveCursor(next);
}
},
previousFoldAtCurrentLevel() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
//console.log(arguments.callee.name);
this.clearHistory();
var fold = this.foldNavigatorView.getActiveFold();
var previous;
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
var indentation = 0;
if (fold || fold === 0) {
indentation = editor.indentationForBufferRow(fold);
}
var level = this.getLevel(indentation);
if (!level)
return;
var index = level.indexOf(fold);
if (index !== 0) {
previous = level[index - 1];
} else {
previous = level[level.length - 1];
}
if (previous || previous === 0) {
this.moveCursor(previous);
}
},
nextFoldAtCurrentLevel() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
this.clearHistory();
//console.log(arguments.callee.name);
var fold = this.foldNavigatorView.getActiveFold();
var next;
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
var indentation = 0;
if (fold || fold === 0) {
indentation = editor.indentationForBufferRow(fold);
}
var level = this.getLevel(indentation);
if (!level)
return;
var index = level.indexOf(fold);
if (level.length !== (index + 1)) {
next = level[index + 1];
} else {
next = level[0];
}
if (next || next === 0) {
this.moveCursor(next);
}
},
moveLevelUp() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
var fold = this.foldNavigatorView.getActiveFold();
var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false;
var editor = atom.workspace.getActiveTextEditor();
var parent;
if (!editor || !foldObj) {
return;
}
parent = this.getParentFold(foldObj);
if ((parent || parent === 0) && parent !== 'root') {
this.moveCursor(parent);
this.addToHistory(fold);
}
},
moveLevelDown() {
if (this.searchModal.isVisible()) {
this.alignEditorToSearch();
return;
}
var fold = this.foldNavigatorView.getActiveFold();
var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false;
var editor = atom.workspace.getActiveTextEditor();
var child;
if (!editor || !foldObj || foldObj.children.length === 0) {
return;
}
child = this.getLastFromHistory();
// check if the last item in history actually belongs to this parent
if (!child && foldObj.children.indexOf(child) === -1)
child = foldObj.children[0];
if (child) {
this.moveCursor(child);
}
},
getParentFold(foldObj) {
if (!foldObj) {
return false;
}
// badly indented/formated code - there must be a parent so return the previous fold the next best chance of being the parent
if (foldObj.parent === 'root' && foldObj.indentation > 0) {
let index = this.folds.indexOf(foldObj.line);
let prev = this.folds[index - 1];
if (prev || prev === 0)
return prev;
return false;
}
return foldObj.parent;
},
addToHistory(fold) {
var maxSize = 10;
if (!this.history) {
this.history = [];
} else if (this.history.length > maxSize) {
this.history.shift();
}
this.history.push(fold);
},
getLastFromHistory() {
if (!this.history) {
return undefined;
}
return this.history.pop();
},
clearHistory() {
if (!this.history)
return;
this.history.length = 0;
},
// gets all folds at indentation level
getLevel(level) {
//console.log(arguments.callee.name);
return this.foldLevels[level];
},
parse(editor) {
//console.log(arguments.callee.name);
if (!editor)
return;
// initialize
this.iniSettings();
this.clearSearchModal();
this.foldNavigatorView.clearContent();
this.clearHistory();
this.lines2fold = [];
this.folds = [];
this.visibleFolds = [];
this.foldObjects = {};
this.foldObjectsArray = []; // we need this because fuzzaldrin-plus not able to find things in objects only in arrays or I do not know how
this.foldLevels = {};
var numberOfRows = editor.getLastBufferRow();
var html = "";
var currentFold = null;
var temporarilyLastParent = [];
//loop through the lines of the active editor
for (var i = 0; numberOfRows > i; i++) {
if (editor.isFoldableAtBufferRow(i)) {
let indentLevel = editor.indentationForBufferRow(i);
let indentHtml = "";
let lineNumberSpan = "";
let lineContent = "";
let lineContentTrimmed = "";
let classList = "fold-navigator-item";
let id = "";
let gutter = '<span class="fold-navigator-gutter"></span>';
let content = '';
let parent;
// add this line to folds
this.folds.push(i);
// add this line to foldLevels
if (!this.foldLevels.hasOwnProperty(indentLevel)) {
this.foldLevels[indentLevel] = [];
}
this.foldLevels[indentLevel].push(i);
// chop array down - it can not be larger than the current indentLevel
temporarilyLastParent.length = parseInt(indentLevel);
parent = 'root';
if (temporarilyLastParent[indentLevel - 1] || temporarilyLastParent[indentLevel - 1] === 0)
parent = temporarilyLastParent[indentLevel - 1];
if (this.foldObjects[parent]) {
this.foldObjects[parent]['children'].push(i);
}
this.foldObjects[i] = {
line: i,
children: [],
parent: parent,
indentation: indentLevel,
content: '',
};
//temporarilyLastParent
temporarilyLastParent[indentLevel] = i;
for (let j = 0; j < indentLevel; j++) {
indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>';
}
lineContent = editor.lineTextForBufferRow(i);
lineContentTrimmed = lineContent.trim();
// check if the content of the string matches one of those values when the previous line's content should be used instead
// see issue here https://github.com/turigeza/fold-navigator/issues/12
if(this.settings.whenMatchedUsePreviousLineArray && this.settings.whenMatchedUsePreviousLineArray.indexOf(lineContentTrimmed) !== -1){ //&& i !== 0
lineContent = editor.lineTextForBufferRow(i - 1);
}else if (lineContentTrimmed.length < this.settings.minLineLength) {
// check if the line is longer than the minimum in the settings if not grab the next line instead
lineContent = editor.lineTextForBufferRow(i + 1);
}
// default it to string seems to return undefined sometimes most likely only when the first row is {
if(!lineContent){
lineContent = '';
}
// check if line is too long
if (lineContent.length > this.settings.maxLineContentLength) {
lineContent = lineContent.substring(0, this.settings.maxLineContentLength) + '...';
}
/* maybe in the future we should check for lines which are too short and grab the next row */
if (this.settings.showLineNumbers) {
lineNumberSpan = '<span class="fold-navigator-line-number ">' + (i + 1) + '</span>';
}
id = 'fold-navigator-item-' + i;
classList += ' fold-navigator-item-' + i;
classList += ' fold-navigator-item-indent-' + indentLevel;
// escape html
// add content to navigator
if (indentLevel <= this.settings.maxFoldLevel) {
currentFold = i;
content = document.createElement('div');
content.appendChild(document.createTextNode(lineContent));
html += '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>';
this.foldObjects[i]['content'] = lineContent.trim();
this.foldObjectsArray.push(this.foldObjects[i]);
this.visibleFolds.push(i);
}
}
// add this fold to the line2fold lookup array
this.lines2fold[i] = currentFold;
}
this.foldNavigatorView.setContent(html);
this.selectRow(editor.getCursorBufferPosition().row);
},
/* called every time onCursorChange */
selectRow(row) {
//console.log(arguments.callee.name);
var fold = this.lines2fold[row];
var line = this.foldNavigatorView.selectFold(fold);
// autoscroll navigator panel
if ((line) && !this.wasItOnClick && this.settings.autoScrollFoldNavigatorPanel) {
line.scrollIntoViewIfNeeded(false);
if(this.settings.log){
console.log(line);
}
}
if (line) {
this.wasItOnClick = false;
}
},
// not yet used idea stolen from tree view
resizeStarted() {
document.onmousemove = () => {
this.resizePanel()
};
document.onmouseup = () => {
this.resizeStopped()
};
},
// not yet used idea stolen from tree view
resizeStopped() {
document.offmousemove = () => {
this.resizePanel()
};
document.offmouseup = () => {
this.resizeStopped()
};
},
// not yet used idea stolen from tree view
resizePanel(d) {
var pageX = d.pageX;
var which = d.which;
if (which !== 1) {
return this.resizeStopped();
}
},
toggle() {
return (this.panel.isVisible() ? this.panel.hide() : this.panel.show());
},
open() {
var editor = atom.workspace.getActiveTextEditor();
return this.panel.show();
},
close() {
return this.panel.hide();
},
moveCursor(row, wasItOnClick = false) {
//console.log(arguments.callee.name);
this.wasItOnClick = wasItOnClick;
// setCursorBufferPosition dies if row is string
row = parseInt(row);
var editor = atom.workspace.getActiveTextEditor();
if (!editor || row < 0)
return;
//editor.unfoldBufferRow(row);
if (this.settings.keepFoldingAllTime && !wasItOnClick) {
editor.foldAll();
}
this.unfoldSubfolds(row);
editor.setCursorBufferPosition([row, 0]);
editor.scrollToCursorPosition({
center: true
});
},
navigatorElementOnClick() {
//console.log(arguments.callee.name);
var element = this.foldNavigatorView.getElement();
element.onclick = (event) => {
var clicked = null;
var row;
var editor = atom.workspace.getActiveTextEditor();
if (event.target.matches('.fold-navigator-item')) {
clicked = event.target;
} else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-item')) {
clicked = event.target.parentNode;
}
if (!clicked)
return;
row = clicked.dataset.row;
//problem
if (!row)
return;
if (editor && ((this.settings.keepFolding && !event.metaKey) || (!this.settings.keepFolding && event.metaKey))) {
// fold all code before anything else sadly this triggers a lot of onDidChangeCursorPosition events
editor.foldAll();
}
this.moveCursor(row, true);
};
},
foldActivePublic() {
//console.log(arguments.callee.name);
var fold = this.foldNavigatorView.getActiveFold();
var editor = atom.workspace.getActiveTextEditor();
if ((!fold && fold !== 0) || !editor)
return;
editor.foldBufferRow(fold);
},
unfoldSubfoldsPublic() {
//console.log(arguments.callee.name);
this.unfoldSubfolds(false, false, true);
},
unfoldSubfolds(row = false, editor = false, force = false) {
//console.log(arguments.callee.name);
var fold = (row || row === 0) ? row : this.foldNavigatorView.getActiveFold();
if (!fold && fold !== 0)
return;
var foldObj = this.foldObjects[fold];
var editor = editor ? editor : atom.workspace.getActiveTextEditor();
if (!foldObj || !editor)
return;
editor.unfoldBufferRow(fold);
if (!this.settings.unfoldAllSubfolds && !force)
return;
if (foldObj.children.length > 0) {
foldObj.children.forEach(
(value) => {
this.unfoldSubfolds(value, editor)
}
);
}
},
toggleActiveFold() {
//console.log(arguments.callee.name);
var fold = this.foldNavigatorView.getActiveFold();
var editor = atom.workspace.getActiveTextEditor();
if ((!fold && fold !== 0) || !editor)
return;
if (editor.isFoldedAtBufferRow(fold)) {
this.unfoldSubfolds(fold, editor, true);
} else {
editor.foldBufferRow(fold);
}
},
unfoldAtLevel(level) {
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if ([1, 2, 3, 4, 5].indexOf(level) < 0)
return;
var lev = this.getLevel(level - 1);
if (lev) {
lev.forEach((fold) => {
editor.unfoldBufferRow(fold);
});
editor.scrollToCursorPosition({
center: true
});
}
},
foldAtLevel(level) {
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if ([1, 2, 3, 4, 5].indexOf(level) < 0)
return;
var lev = this.getLevel(level - 1);
if (lev) {
lev.forEach((fold) => {
editor.foldBufferRow(fold);
});
editor.scrollToCursorPosition({
center: true
});
}
},
toggleFoldsLevel(level) {
var editor = atom.workspace.getActiveTextEditor();
if (!editor)
return;
if ([1, 2, 3, 4, 5].indexOf(level) < 0)
return;
var lev = this.getLevel(level - 1);
if (!lev)
return;
var first = lev[0];
if (!first && first !== 0)
return;
if (editor.isFoldedAtBufferRow(first)) {
this.unfoldAtLevel(level);
} else {
this.foldAtLevel(level);
}
},
unfoldAtLevel1() {
this.unfoldAtLevel(1);
},
unfoldAtLevel2() {
this.unfoldAtLevel(2);
},
unfoldAtLevel3() {
this.unfoldAtLevel(3);
},
unfoldAtLevel4() {
this.unfoldAtLevel(4);
},
unfoldAtLevel5() {
this.unfoldAtLevel(5);
},
foldAtLevel1() {
this.foldAtLevel(1);
},
foldAtLevel2() {
this.foldAtLevel(2);
},
foldAtLevel3() {
this.foldAtLevel(3);
},
foldAtLevel4() {
this.foldAtLevel(4);
},
foldAtLevel5() {
this.foldAtLevel(5);
},
toggleFoldsLevel1() {
this.toggleFoldsLevel(1);
},
toggleFoldsLevel2() {
this.toggleFoldsLevel(2);
},
toggleFoldsLevel3() {
this.toggleFoldsLevel(3);
},
toggleFoldsLevel4() {
this.toggleFoldsLevel(4);
},
toggleFoldsLevel5() {
this.toggleFoldsLevel(5);
},
startTime() {
this.time = new Date();
},
showTime(text) {
console.log(text);
console.log(new Date() - this.time);
},
deactivate() {
//console.log(arguments.callee.name);
this.panel.destroy();
this.subscriptions.dispose();
this.foldNavigatorView.destroy();
if (this.onDidChangeCursorPositionSubscription) {
this.onDidChangeCursorPositionSubscription.dispose();
}
if (this.onDidStopChangingSubscription) {
this.onDidStopChangingSubscription.dispose();
}
//delete(this.searchModalElement);
//delete(this.searchModalItems);
//delete(this.searchModalInput);
if (this.searchModal) {
this.searchModal.destroy();
}
},
/* we don't need this */
serialize() {}
};
| turigeza/fold-navigator | lib/fold-navigator.js | JavaScript | mit | 41,379 |
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const c2p = require("./codeConverter");
const p2c = require("./protocolConverter");
const Is = require("./utils/is");
const async_1 = require("./utils/async");
const UUID = require("./utils/uuid");
const progressPart_1 = require("./progressPart");
__export(require("vscode-languageserver-protocol"));
class ConsoleLogger {
error(message) {
console.error(message);
}
warn(message) {
console.warn(message);
}
info(message) {
console.info(message);
}
log(message) {
console.log(message);
}
}
function createConnection(input, output, errorHandler, closeHandler) {
let logger = new ConsoleLogger();
let connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger);
connection.onError((data) => { errorHandler(data[0], data[1], data[2]); });
connection.onClose(closeHandler);
let result = {
listen: () => connection.listen(),
sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
onRequest: (type, handler) => connection.onRequest(Is.string(type) ? type : type.method, handler),
sendNotification: (type, params) => connection.sendNotification(Is.string(type) ? type : type.method, params),
onNotification: (type, handler) => connection.onNotification(Is.string(type) ? type : type.method, handler),
onProgress: connection.onProgress,
sendProgress: connection.sendProgress,
trace: (value, tracer, sendNotificationOrTraceOptions) => {
const defaultTraceOptions = {
sendNotification: false,
traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text
};
if (sendNotificationOrTraceOptions === void 0) {
connection.trace(value, tracer, defaultTraceOptions);
}
else if (Is.boolean(sendNotificationOrTraceOptions)) {
connection.trace(value, tracer, sendNotificationOrTraceOptions);
}
else {
connection.trace(value, tracer, sendNotificationOrTraceOptions);
}
},
initialize: (params) => connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params),
shutdown: () => connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined),
exit: () => connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type),
onLogMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, handler),
onShowMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, handler),
onTelemetry: (handler) => connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, handler),
didChangeConfiguration: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, params),
didChangeWatchedFiles: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, params),
didOpenTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, params),
didChangeTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params),
didCloseTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, params),
didSaveTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, params),
onDiagnostics: (handler) => connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, handler),
dispose: () => connection.dispose()
};
return result;
}
/**
* An action to be performed when the connection is producing errors.
*/
var ErrorAction;
(function (ErrorAction) {
/**
* Continue running the server.
*/
ErrorAction[ErrorAction["Continue"] = 1] = "Continue";
/**
* Shutdown the server.
*/
ErrorAction[ErrorAction["Shutdown"] = 2] = "Shutdown";
})(ErrorAction = exports.ErrorAction || (exports.ErrorAction = {}));
/**
* An action to be performed when the connection to a server got closed.
*/
var CloseAction;
(function (CloseAction) {
/**
* Don't restart the server. The connection stays closed.
*/
CloseAction[CloseAction["DoNotRestart"] = 1] = "DoNotRestart";
/**
* Restart the server.
*/
CloseAction[CloseAction["Restart"] = 2] = "Restart";
})(CloseAction = exports.CloseAction || (exports.CloseAction = {}));
class DefaultErrorHandler {
constructor(name) {
this.name = name;
this.restarts = [];
}
error(_error, _message, count) {
if (count && count <= 3) {
return ErrorAction.Continue;
}
return ErrorAction.Shutdown;
}
closed() {
this.restarts.push(Date.now());
if (this.restarts.length < 5) {
return CloseAction.Restart;
}
else {
let diff = this.restarts[this.restarts.length - 1] - this.restarts[0];
if (diff <= 3 * 60 * 1000) {
vscode_1.window.showErrorMessage(`The ${this.name} server crashed 5 times in the last 3 minutes. The server will not be restarted.`);
return CloseAction.DoNotRestart;
}
else {
this.restarts.shift();
return CloseAction.Restart;
}
}
}
}
var RevealOutputChannelOn;
(function (RevealOutputChannelOn) {
RevealOutputChannelOn[RevealOutputChannelOn["Info"] = 1] = "Info";
RevealOutputChannelOn[RevealOutputChannelOn["Warn"] = 2] = "Warn";
RevealOutputChannelOn[RevealOutputChannelOn["Error"] = 3] = "Error";
RevealOutputChannelOn[RevealOutputChannelOn["Never"] = 4] = "Never";
})(RevealOutputChannelOn = exports.RevealOutputChannelOn || (exports.RevealOutputChannelOn = {}));
var State;
(function (State) {
State[State["Stopped"] = 1] = "Stopped";
State[State["Starting"] = 3] = "Starting";
State[State["Running"] = 2] = "Running";
})(State = exports.State || (exports.State = {}));
var ClientState;
(function (ClientState) {
ClientState[ClientState["Initial"] = 0] = "Initial";
ClientState[ClientState["Starting"] = 1] = "Starting";
ClientState[ClientState["StartFailed"] = 2] = "StartFailed";
ClientState[ClientState["Running"] = 3] = "Running";
ClientState[ClientState["Stopping"] = 4] = "Stopping";
ClientState[ClientState["Stopped"] = 5] = "Stopped";
})(ClientState || (ClientState = {}));
const SupportedSymbolKinds = [
vscode_languageserver_protocol_1.SymbolKind.File,
vscode_languageserver_protocol_1.SymbolKind.Module,
vscode_languageserver_protocol_1.SymbolKind.Namespace,
vscode_languageserver_protocol_1.SymbolKind.Package,
vscode_languageserver_protocol_1.SymbolKind.Class,
vscode_languageserver_protocol_1.SymbolKind.Method,
vscode_languageserver_protocol_1.SymbolKind.Property,
vscode_languageserver_protocol_1.SymbolKind.Field,
vscode_languageserver_protocol_1.SymbolKind.Constructor,
vscode_languageserver_protocol_1.SymbolKind.Enum,
vscode_languageserver_protocol_1.SymbolKind.Interface,
vscode_languageserver_protocol_1.SymbolKind.Function,
vscode_languageserver_protocol_1.SymbolKind.Variable,
vscode_languageserver_protocol_1.SymbolKind.Constant,
vscode_languageserver_protocol_1.SymbolKind.String,
vscode_languageserver_protocol_1.SymbolKind.Number,
vscode_languageserver_protocol_1.SymbolKind.Boolean,
vscode_languageserver_protocol_1.SymbolKind.Array,
vscode_languageserver_protocol_1.SymbolKind.Object,
vscode_languageserver_protocol_1.SymbolKind.Key,
vscode_languageserver_protocol_1.SymbolKind.Null,
vscode_languageserver_protocol_1.SymbolKind.EnumMember,
vscode_languageserver_protocol_1.SymbolKind.Struct,
vscode_languageserver_protocol_1.SymbolKind.Event,
vscode_languageserver_protocol_1.SymbolKind.Operator,
vscode_languageserver_protocol_1.SymbolKind.TypeParameter
];
const SupportedCompletionItemKinds = [
vscode_languageserver_protocol_1.CompletionItemKind.Text,
vscode_languageserver_protocol_1.CompletionItemKind.Method,
vscode_languageserver_protocol_1.CompletionItemKind.Function,
vscode_languageserver_protocol_1.CompletionItemKind.Constructor,
vscode_languageserver_protocol_1.CompletionItemKind.Field,
vscode_languageserver_protocol_1.CompletionItemKind.Variable,
vscode_languageserver_protocol_1.CompletionItemKind.Class,
vscode_languageserver_protocol_1.CompletionItemKind.Interface,
vscode_languageserver_protocol_1.CompletionItemKind.Module,
vscode_languageserver_protocol_1.CompletionItemKind.Property,
vscode_languageserver_protocol_1.CompletionItemKind.Unit,
vscode_languageserver_protocol_1.CompletionItemKind.Value,
vscode_languageserver_protocol_1.CompletionItemKind.Enum,
vscode_languageserver_protocol_1.CompletionItemKind.Keyword,
vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
vscode_languageserver_protocol_1.CompletionItemKind.Color,
vscode_languageserver_protocol_1.CompletionItemKind.File,
vscode_languageserver_protocol_1.CompletionItemKind.Reference,
vscode_languageserver_protocol_1.CompletionItemKind.Folder,
vscode_languageserver_protocol_1.CompletionItemKind.EnumMember,
vscode_languageserver_protocol_1.CompletionItemKind.Constant,
vscode_languageserver_protocol_1.CompletionItemKind.Struct,
vscode_languageserver_protocol_1.CompletionItemKind.Event,
vscode_languageserver_protocol_1.CompletionItemKind.Operator,
vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter
];
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
var DynamicFeature;
(function (DynamicFeature) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.register) && Is.func(candidate.unregister) && Is.func(candidate.dispose) && candidate.messages !== void 0;
}
DynamicFeature.is = is;
})(DynamicFeature || (DynamicFeature = {}));
class DocumentNotifiactions {
constructor(_client, _event, _type, _middleware, _createParams, _selectorFilter) {
this._client = _client;
this._event = _event;
this._type = _type;
this._middleware = _middleware;
this._createParams = _createParams;
this._selectorFilter = _selectorFilter;
this._selectors = new Map();
}
static textDocumentFilter(selectors, textDocument) {
for (const selector of selectors) {
if (vscode_1.languages.match(selector, textDocument)) {
return true;
}
}
return false;
}
register(_message, data) {
if (!data.registerOptions.documentSelector) {
return;
}
if (!this._listener) {
this._listener = this._event(this.callback, this);
}
this._selectors.set(data.id, data.registerOptions.documentSelector);
}
callback(data) {
if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) {
if (this._middleware) {
this._middleware(data, (data) => this._client.sendNotification(this._type, this._createParams(data)));
}
else {
this._client.sendNotification(this._type, this._createParams(data));
}
this.notificationSent(data);
}
}
notificationSent(_data) {
}
unregister(id) {
this._selectors.delete(id);
if (this._selectors.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
dispose() {
this._selectors.clear();
if (this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
getProvider(document) {
for (const selector of this._selectors.values()) {
if (vscode_1.languages.match(selector, document)) {
return {
send: (data) => {
this.callback(data);
}
};
}
}
throw new Error(`No provider available for the given text document`);
}
}
class DidOpenTextDocumentFeature extends DocumentNotifiactions {
constructor(client, _syncedDocuments) {
super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter);
this._syncedDocuments = _syncedDocuments;
}
get messages() {
return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });
}
}
register(message, data) {
super.register(message, data);
if (!data.registerOptions.documentSelector) {
return;
}
let documentSelector = data.registerOptions.documentSelector;
vscode_1.workspace.textDocuments.forEach((textDocument) => {
let uri = textDocument.uri.toString();
if (this._syncedDocuments.has(uri)) {
return;
}
if (vscode_1.languages.match(documentSelector, textDocument)) {
let middleware = this._client.clientOptions.middleware;
let didOpen = (textDocument) => {
this._client.sendNotification(this._type, this._createParams(textDocument));
};
if (middleware.didOpen) {
middleware.didOpen(textDocument, didOpen);
}
else {
didOpen(textDocument);
}
this._syncedDocuments.set(uri, textDocument);
}
});
}
notificationSent(textDocument) {
super.notificationSent(textDocument);
this._syncedDocuments.set(textDocument.uri.toString(), textDocument);
}
}
class DidCloseTextDocumentFeature extends DocumentNotifiactions {
constructor(client, _syncedDocuments) {
super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter);
this._syncedDocuments = _syncedDocuments;
}
get messages() {
return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });
}
}
notificationSent(textDocument) {
super.notificationSent(textDocument);
this._syncedDocuments.delete(textDocument.uri.toString());
}
unregister(id) {
let selector = this._selectors.get(id);
// The super call removed the selector from the map
// of selectors.
super.unregister(id);
let selectors = this._selectors.values();
this._syncedDocuments.forEach((textDocument) => {
if (vscode_1.languages.match(selector, textDocument) && !this._selectorFilter(selectors, textDocument)) {
let middleware = this._client.clientOptions.middleware;
let didClose = (textDocument) => {
this._client.sendNotification(this._type, this._createParams(textDocument));
};
this._syncedDocuments.delete(textDocument.uri.toString());
if (middleware.didClose) {
middleware.didClose(textDocument, didClose);
}
else {
didClose(textDocument);
}
}
});
}
}
class DidChangeTextDocumentFeature {
constructor(_client) {
this._client = _client;
this._changeData = new Map();
this._forcingDelivery = false;
}
get messages() {
return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change })
});
}
}
register(_message, data) {
if (!data.registerOptions.documentSelector) {
return;
}
if (!this._listener) {
this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this);
}
this._changeData.set(data.id, {
documentSelector: data.registerOptions.documentSelector,
syncKind: data.registerOptions.syncKind
});
}
callback(event) {
// Text document changes are send for dirty changes as well. We don't
// have dirty / undirty events in the LSP so we ignore content changes
// with length zero.
if (event.contentChanges.length === 0) {
return;
}
for (const changeData of this._changeData.values()) {
if (vscode_1.languages.match(changeData.documentSelector, event.document)) {
let middleware = this._client.clientOptions.middleware;
if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) {
let params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event);
if (middleware.didChange) {
middleware.didChange(event, () => this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params));
}
else {
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
}
}
else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
let didChange = (event) => {
if (this._changeDelayer) {
if (this._changeDelayer.uri !== event.document.uri.toString()) {
// Use this force delivery to track boolean state. Otherwise we might call two times.
this.forceDelivery();
this._changeDelayer.uri = event.document.uri.toString();
}
this._changeDelayer.delayer.trigger(() => {
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document));
});
}
else {
this._changeDelayer = {
uri: event.document.uri.toString(),
delayer: new async_1.Delayer(200)
};
this._changeDelayer.delayer.trigger(() => {
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document));
}, -1);
}
};
if (middleware.didChange) {
middleware.didChange(event, didChange);
}
else {
didChange(event);
}
}
}
}
}
unregister(id) {
this._changeData.delete(id);
if (this._changeData.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
dispose() {
this._changeDelayer = undefined;
this._forcingDelivery = false;
this._changeData.clear();
if (this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
forceDelivery() {
if (this._forcingDelivery || !this._changeDelayer) {
return;
}
try {
this._forcingDelivery = true;
this._changeDelayer.delayer.forceDelivery();
}
finally {
this._forcingDelivery = false;
}
}
getProvider(document) {
for (const changeData of this._changeData.values()) {
if (vscode_1.languages.match(changeData.documentSelector, document)) {
return {
send: (event) => {
this.callback(event);
}
};
}
}
throw new Error(`No provider available for the given text document`);
}
}
class WillSaveFeature extends DocumentNotifiactions {
constructor(client) {
super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, client.clientOptions.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (selectors, willSaveEvent) => DocumentNotifiactions.textDocumentFilter(selectors, willSaveEvent.document));
}
get messages() {
return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type;
}
fillClientCapabilities(capabilities) {
let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization');
value.willSave = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: { documentSelector: documentSelector }
});
}
}
}
class WillSaveWaitUntilFeature {
constructor(_client) {
this._client = _client;
this._selectors = new Map();
}
get messages() {
return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type;
}
fillClientCapabilities(capabilities) {
let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization');
value.willSaveWaitUntil = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: { documentSelector: documentSelector }
});
}
}
register(_message, data) {
if (!data.registerOptions.documentSelector) {
return;
}
if (!this._listener) {
this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this);
}
this._selectors.set(data.id, data.registerOptions.documentSelector);
}
callback(event) {
if (DocumentNotifiactions.textDocumentFilter(this._selectors.values(), event.document)) {
let middleware = this._client.clientOptions.middleware;
let willSaveWaitUntil = (event) => {
return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then((edits) => {
let vEdits = this._client.protocol2CodeConverter.asTextEdits(edits);
return vEdits === void 0 ? [] : vEdits;
});
};
event.waitUntil(middleware.willSaveWaitUntil
? middleware.willSaveWaitUntil(event, willSaveWaitUntil)
: willSaveWaitUntil(event));
}
}
unregister(id) {
this._selectors.delete(id);
if (this._selectors.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
dispose() {
this._selectors.clear();
if (this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
}
class DidSaveTextDocumentFeature extends DocumentNotifiactions {
constructor(client) {
super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, client.clientOptions.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), DocumentNotifiactions.textDocumentFilter);
}
get messages() {
return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'synchronization').didSave = true;
}
initialize(capabilities, documentSelector) {
let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: Object.assign({}, { documentSelector: documentSelector }, { includeText: !!textDocumentSyncOptions.save.includeText })
});
}
}
register(method, data) {
this._includeText = !!data.registerOptions.includeText;
super.register(method, data);
}
}
class FileSystemWatcherFeature {
constructor(_client, _notifyFileEvent) {
this._client = _client;
this._notifyFileEvent = _notifyFileEvent;
this._watchers = new Map();
}
get messages() {
return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true;
}
initialize(_capabilities, _documentSelector) {
}
register(_method, data) {
if (!Array.isArray(data.registerOptions.watchers)) {
return;
}
let disposeables = [];
for (let watcher of data.registerOptions.watchers) {
if (!Is.string(watcher.globPattern)) {
continue;
}
let watchCreate = true, watchChange = true, watchDelete = true;
if (watcher.kind !== void 0 && watcher.kind !== null) {
watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0;
watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0;
watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0;
}
let fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(watcher.globPattern, !watchCreate, !watchChange, !watchDelete);
this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete);
disposeables.push(fileSystemWatcher);
}
this._watchers.set(data.id, disposeables);
}
registerRaw(id, fileSystemWatchers) {
let disposeables = [];
for (let fileSystemWatcher of fileSystemWatchers) {
this.hookListeners(fileSystemWatcher, true, true, true, disposeables);
}
this._watchers.set(id, disposeables);
}
hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) {
if (watchCreate) {
fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({
uri: this._client.code2ProtocolConverter.asUri(resource),
type: vscode_languageserver_protocol_1.FileChangeType.Created
}), null, listeners);
}
if (watchChange) {
fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({
uri: this._client.code2ProtocolConverter.asUri(resource),
type: vscode_languageserver_protocol_1.FileChangeType.Changed
}), null, listeners);
}
if (watchDelete) {
fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({
uri: this._client.code2ProtocolConverter.asUri(resource),
type: vscode_languageserver_protocol_1.FileChangeType.Deleted
}), null, listeners);
}
}
unregister(id) {
let disposeables = this._watchers.get(id);
if (disposeables) {
for (let disposable of disposeables) {
disposable.dispose();
}
}
}
dispose() {
this._watchers.forEach((disposeables) => {
for (let disposable of disposeables) {
disposable.dispose();
}
});
this._watchers.clear();
}
}
class TextDocumentFeature {
constructor(_client, _message) {
this._client = _client;
this._message = _message;
this._registrations = new Map();
}
get messages() {
return this._message;
}
register(message, data) {
if (message.method !== this.messages.method) {
throw new Error(`Register called on wrong feature. Requested ${message.method} but reached feature ${this.messages.method}`);
}
if (!data.registerOptions.documentSelector) {
return;
}
let registration = this.registerLanguageProvider(data.registerOptions);
this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] });
}
unregister(id) {
let registration = this._registrations.get(id);
if (registration !== undefined) {
registration.disposable.dispose();
}
}
dispose() {
this._registrations.forEach((value) => {
value.disposable.dispose();
});
this._registrations.clear();
}
getRegistration(documentSelector, capability) {
if (!capability) {
return [undefined, undefined];
}
else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) {
const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid();
const selector = capability.documentSelector || documentSelector;
if (selector) {
return [id, Object.assign({}, capability, { documentSelector: selector })];
}
}
else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) {
if (!documentSelector) {
return [undefined, undefined];
}
let options = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }));
return [UUID.generateUuid(), options];
}
return [undefined, undefined];
}
getRegistrationOptions(documentSelector, capability) {
if (!documentSelector || !capability) {
return undefined;
}
return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }));
}
getProvider(textDocument) {
for (const registration of this._registrations.values()) {
let selector = registration.data.registerOptions.documentSelector;
if (selector !== null && vscode_1.languages.match(selector, textDocument)) {
return registration.provider;
}
}
throw new Error(`The feature has no registration for the provided text document ${textDocument.uri.toString()}`);
}
}
exports.TextDocumentFeature = TextDocumentFeature;
class WorkspaceFeature {
constructor(_client, _message) {
this._client = _client;
this._message = _message;
this._registrations = new Map();
}
get messages() {
return this._message;
}
register(message, data) {
if (message.method !== this.messages.method) {
throw new Error(`Register called on wron feature. Requested ${message.method} but reached feature ${this.messages.method}`);
}
const registration = this.registerLanguageProvider(data.registerOptions);
this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] });
}
unregister(id) {
let registration = this._registrations.get(id);
if (registration !== undefined) {
registration.disposable.dispose();
}
}
dispose() {
this._registrations.forEach((registration) => {
registration.disposable.dispose();
});
this._registrations.clear();
}
getProviders() {
const result = [];
for (const registration of this._registrations.values()) {
result.push(registration.provider);
}
return result;
}
}
class CompletionItemFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.CompletionRequest.type);
}
fillClientCapabilities(capabilites) {
let completion = ensure(ensure(capabilites, 'textDocument'), 'completion');
completion.dynamicRegistration = true;
completion.contextSupport = true;
completion.completionItem = {
snippetSupport: true,
commitCharactersSupport: true,
documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText],
deprecatedSupport: true,
preselectSupport: true,
tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] }
};
completion.completionItemKind = { valueSet: SupportedCompletionItemKinds };
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider);
if (!options) {
return;
}
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: options
});
}
registerLanguageProvider(options) {
const triggerCharacters = options.triggerCharacters || [];
const provider = {
provideCompletionItems: (document, position, token, context) => {
const client = this._client;
const middleware = this._client.clientOptions.middleware;
const provideCompletionItems = (document, position, context, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document, position, context), token).then(client.protocol2CodeConverter.asCompletionResult, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, error);
return Promise.resolve([]);
});
};
return middleware.provideCompletionItem
? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems)
: provideCompletionItems(document, position, context, token);
},
resolveCompletionItem: options.resolveProvider
? (item, token) => {
const client = this._client;
const middleware = this._client.clientOptions.middleware;
const resolveCompletionItem = (item, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item), token).then(client.protocol2CodeConverter.asCompletionItem, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, error);
return Promise.resolve(item);
});
};
return middleware.resolveCompletionItem
? middleware.resolveCompletionItem(item, token, resolveCompletionItem)
: resolveCompletionItem(item, token);
}
: undefined
};
return [vscode_1.languages.registerCompletionItemProvider(options.documentSelector, provider, ...triggerCharacters), provider];
}
}
class HoverFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.HoverRequest.type);
}
fillClientCapabilities(capabilites) {
const hoverCapability = (ensure(ensure(capabilites, 'textDocument'), 'hover'));
hoverCapability.dynamicRegistration = true;
hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText];
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider);
if (!options) {
return;
}
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: options
});
}
registerLanguageProvider(options) {
const provider = {
provideHover: (document, position, token) => {
const client = this._client;
const provideHover = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asHover, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, error);
return Promise.resolve(null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideHover
? middleware.provideHover(document, position, token, provideHover)
: provideHover(document, position, token);
}
};
return [vscode_1.languages.registerHoverProvider(options.documentSelector, provider), provider];
}
}
class SignatureHelpFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type);
}
fillClientCapabilities(capabilites) {
let config = ensure(ensure(capabilites, 'textDocument'), 'signatureHelp');
config.dynamicRegistration = true;
config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] };
config.signatureInformation.parameterInformation = { labelOffsetSupport: true };
config.contextSupport = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider);
if (!options) {
return;
}
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: options
});
}
registerLanguageProvider(options) {
const provider = {
provideSignatureHelp: (document, position, token, context) => {
const client = this._client;
const providerSignatureHelp = (document, position, context, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document, position, context), token).then(client.protocol2CodeConverter.asSignatureHelp, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, error);
return Promise.resolve(null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideSignatureHelp
? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp)
: providerSignatureHelp(document, position, context, token);
}
};
let disposable;
if (options.retriggerCharacters === undefined) {
const triggerCharacters = options.triggerCharacters || [];
disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, ...triggerCharacters);
}
else {
const metaData = {
triggerCharacters: options.triggerCharacters || [],
retriggerCharacters: options.retriggerCharacters || []
};
disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, metaData);
}
return [disposable, provider];
}
}
class DefinitionFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DefinitionRequest.type);
}
fillClientCapabilities(capabilites) {
let definitionSupport = ensure(ensure(capabilites, 'textDocument'), 'definition');
definitionSupport.dynamicRegistration = true;
definitionSupport.linkSupport = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDefinition: (document, position, token) => {
const client = this._client;
const provideDefinition = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, error);
return Promise.resolve(null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDefinition
? middleware.provideDefinition(document, position, token, provideDefinition)
: provideDefinition(document, position, token);
}
};
return [vscode_1.languages.registerDefinitionProvider(options.documentSelector, provider), provider];
}
}
class ReferencesFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.ReferencesRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'references').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideReferences: (document, position, options, token) => {
const client = this._client;
const _providerReferences = (document, position, options, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document, position, options), token).then(client.protocol2CodeConverter.asReferences, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideReferences
? middleware.provideReferences(document, position, options, token, _providerReferences)
: _providerReferences(document, position, options, token);
}
};
return [vscode_1.languages.registerReferenceProvider(options.documentSelector, provider), provider];
}
}
class DocumentHighlightFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'documentHighlight').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDocumentHighlights: (document, position, token) => {
const client = this._client;
const _provideDocumentHighlights = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDocumentHighlights, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDocumentHighlights
? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights)
: _provideDocumentHighlights(document, position, token);
}
};
return [vscode_1.languages.registerDocumentHighlightProvider(options.documentSelector, provider), provider];
}
}
class DocumentSymbolFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type);
}
fillClientCapabilities(capabilites) {
let symbolCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentSymbol');
symbolCapabilities.dynamicRegistration = true;
symbolCapabilities.symbolKind = {
valueSet: SupportedSymbolKinds
};
symbolCapabilities.hierarchicalDocumentSymbolSupport = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDocumentSymbols: (document, token) => {
const client = this._client;
const _provideDocumentSymbols = (document, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document), token).then((data) => {
if (data === null) {
return undefined;
}
if (data.length === 0) {
return [];
}
else {
let element = data[0];
if (vscode_languageserver_protocol_1.DocumentSymbol.is(element)) {
return client.protocol2CodeConverter.asDocumentSymbols(data);
}
else {
return client.protocol2CodeConverter.asSymbolInformations(data);
}
}
}, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDocumentSymbols
? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols)
: _provideDocumentSymbols(document, token);
}
};
return [vscode_1.languages.registerDocumentSymbolProvider(options.documentSelector, provider), provider];
}
}
class WorkspaceSymbolFeature extends WorkspaceFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type);
}
fillClientCapabilities(capabilites) {
let symbolCapabilities = ensure(ensure(capabilites, 'workspace'), 'symbol');
symbolCapabilities.dynamicRegistration = true;
symbolCapabilities.symbolKind = {
valueSet: SupportedSymbolKinds
};
}
initialize(capabilities) {
if (!capabilities.workspaceSymbolProvider) {
return;
}
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider
});
}
registerLanguageProvider(_options) {
const provider = {
provideWorkspaceSymbols: (query, token) => {
const client = this._client;
const provideWorkspaceSymbols = (query, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then(client.protocol2CodeConverter.asSymbolInformations, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideWorkspaceSymbols
? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols)
: provideWorkspaceSymbols(query, token);
}
};
return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider];
}
}
class CodeActionFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.CodeActionRequest.type);
}
fillClientCapabilities(capabilites) {
const cap = ensure(ensure(capabilites, 'textDocument'), 'codeAction');
cap.dynamicRegistration = true;
cap.isPreferredSupport = true;
cap.codeActionLiteralSupport = {
codeActionKind: {
valueSet: [
vscode_languageserver_protocol_1.CodeActionKind.Empty,
vscode_languageserver_protocol_1.CodeActionKind.QuickFix,
vscode_languageserver_protocol_1.CodeActionKind.Refactor,
vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract,
vscode_languageserver_protocol_1.CodeActionKind.RefactorInline,
vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite,
vscode_languageserver_protocol_1.CodeActionKind.Source,
vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports
]
}
};
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideCodeActions: (document, range, context, token) => {
const client = this._client;
const _provideCodeActions = (document, range, context, token) => {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
context: client.code2ProtocolConverter.asCodeActionContext(context)
};
return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token).then((values) => {
if (values === null) {
return undefined;
}
const result = [];
for (let item of values) {
if (vscode_languageserver_protocol_1.Command.is(item)) {
result.push(client.protocol2CodeConverter.asCommand(item));
}
else {
result.push(client.protocol2CodeConverter.asCodeAction(item));
}
}
return result;
}, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideCodeActions
? middleware.provideCodeActions(document, range, context, token, _provideCodeActions)
: _provideCodeActions(document, range, context, token);
}
};
return [vscode_1.languages.registerCodeActionsProvider(options.documentSelector, provider, (options.codeActionKinds
? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) }
: undefined)), provider];
}
}
class CodeLensFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.CodeLensRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'codeLens').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideCodeLenses: (document, token) => {
const client = this._client;
const provideCodeLenses = (document, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then(client.protocol2CodeConverter.asCodeLenses, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideCodeLenses
? middleware.provideCodeLenses(document, token, provideCodeLenses)
: provideCodeLenses(document, token);
},
resolveCodeLens: (options.resolveProvider)
? (codeLens, token) => {
const client = this._client;
const resolveCodeLens = (codeLens, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then(client.protocol2CodeConverter.asCodeLens, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, error);
return codeLens;
});
};
const middleware = client.clientOptions.middleware;
return middleware.resolveCodeLens
? middleware.resolveCodeLens(codeLens, token, resolveCodeLens)
: resolveCodeLens(codeLens, token);
}
: undefined
};
return [vscode_1.languages.registerCodeLensProvider(options.documentSelector, provider), provider];
}
}
class DocumentFormattingFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'formatting').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDocumentFormattingEdits: (document, options, token) => {
const client = this._client;
const provideDocumentFormattingEdits = (document, options, token) => {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
options: client.code2ProtocolConverter.asFormattingOptions(options)
};
return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDocumentFormattingEdits
? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits)
: provideDocumentFormattingEdits(document, options, token);
}
};
return [vscode_1.languages.registerDocumentFormattingEditProvider(options.documentSelector, provider), provider];
}
}
class DocumentRangeFormattingFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'rangeFormatting').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDocumentRangeFormattingEdits: (document, range, options, token) => {
const client = this._client;
const provideDocumentRangeFormattingEdits = (document, range, options, token) => {
let params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
options: client.code2ProtocolConverter.asFormattingOptions(options)
};
return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, error);
return Promise.resolve([]);
});
};
let middleware = client.clientOptions.middleware;
return middleware.provideDocumentRangeFormattingEdits
? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits)
: provideDocumentRangeFormattingEdits(document, range, options, token);
}
};
return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(options.documentSelector, provider), provider];
}
}
class DocumentOnTypeFormattingFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type);
}
fillClientCapabilities(capabilites) {
ensure(ensure(capabilites, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideOnTypeFormattingEdits: (document, position, ch, options, token) => {
const client = this._client;
const provideOnTypeFormattingEdits = (document, position, ch, options, token) => {
let params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: client.code2ProtocolConverter.asPosition(position),
ch: ch,
options: client.code2ProtocolConverter.asFormattingOptions(options)
};
return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideOnTypeFormattingEdits
? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits)
: provideOnTypeFormattingEdits(document, position, ch, options, token);
}
};
const moreTriggerCharacter = options.moreTriggerCharacter || [];
return [vscode_1.languages.registerOnTypeFormattingEditProvider(options.documentSelector, provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider];
}
}
class RenameFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.RenameRequest.type);
}
fillClientCapabilities(capabilites) {
let rename = ensure(ensure(capabilites, 'textDocument'), 'rename');
rename.dynamicRegistration = true;
rename.prepareSupport = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider);
if (!options) {
return;
}
if (Is.boolean(capabilities.renameProvider)) {
options.prepareProvider = false;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideRenameEdits: (document, position, newName, token) => {
const client = this._client;
const provideRenameEdits = (document, position, newName, token) => {
let params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: client.code2ProtocolConverter.asPosition(position),
newName: newName
};
return client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token).then(client.protocol2CodeConverter.asWorkspaceEdit, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, error);
return Promise.reject(new Error(error.message));
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideRenameEdits
? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits)
: provideRenameEdits(document, position, newName, token);
},
prepareRename: options.prepareProvider
? (document, position, token) => {
const client = this._client;
const prepareRename = (document, position, token) => {
let params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: client.code2ProtocolConverter.asPosition(position),
};
return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token).then((result) => {
if (vscode_languageserver_protocol_1.Range.is(result)) {
return client.protocol2CodeConverter.asRange(result);
}
else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) {
return {
range: client.protocol2CodeConverter.asRange(result.range),
placeholder: result.placeholder
};
}
// To cancel the rename vscode API expects a rejected promise.
return Promise.reject(new Error(`The element can't be renamed.`));
}, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, error);
return Promise.reject(new Error(error.message));
});
};
const middleware = client.clientOptions.middleware;
return middleware.prepareRename
? middleware.prepareRename(document, position, token, prepareRename)
: prepareRename(document, position, token);
}
: undefined
};
return [vscode_1.languages.registerRenameProvider(options.documentSelector, provider), provider];
}
}
class DocumentLinkFeature extends TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type);
}
fillClientCapabilities(capabilites) {
const documentLinkCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentLink');
documentLinkCapabilities.dynamicRegistration = true;
documentLinkCapabilities.tooltipSupport = true;
}
initialize(capabilities, documentSelector) {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider);
if (!options) {
return;
}
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDocumentLinks: (document, token) => {
const client = this._client;
const provideDocumentLinks = (document, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then(client.protocol2CodeConverter.asDocumentLinks, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, error);
return Promise.resolve([]);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDocumentLinks
? middleware.provideDocumentLinks(document, token, provideDocumentLinks)
: provideDocumentLinks(document, token);
},
resolveDocumentLink: options.resolveProvider
? (link, token) => {
const client = this._client;
let resolveDocumentLink = (link, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then(client.protocol2CodeConverter.asDocumentLink, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, error);
return Promise.resolve(link);
});
};
const middleware = client.clientOptions.middleware;
return middleware.resolveDocumentLink
? middleware.resolveDocumentLink(link, token, resolveDocumentLink)
: resolveDocumentLink(link, token);
}
: undefined
};
return [vscode_1.languages.registerDocumentLinkProvider(options.documentSelector, provider), provider];
}
}
class ConfigurationFeature {
constructor(_client) {
this._client = _client;
this._listeners = new Map();
}
get messages() {
return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'workspace'), 'didChangeConfiguration').dynamicRegistration = true;
}
initialize() {
let section = this._client.clientOptions.synchronize.configurationSection;
if (section !== void 0) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: {
section: section
}
});
}
}
register(_message, data) {
let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => {
this.onDidChangeConfiguration(data.registerOptions.section, event);
});
this._listeners.set(data.id, disposable);
if (data.registerOptions.section !== void 0) {
this.onDidChangeConfiguration(data.registerOptions.section, undefined);
}
}
unregister(id) {
let disposable = this._listeners.get(id);
if (disposable) {
this._listeners.delete(id);
disposable.dispose();
}
}
dispose() {
for (let disposable of this._listeners.values()) {
disposable.dispose();
}
this._listeners.clear();
}
onDidChangeConfiguration(configurationSection, event) {
let sections;
if (Is.string(configurationSection)) {
sections = [configurationSection];
}
else {
sections = configurationSection;
}
if (sections !== void 0 && event !== void 0) {
let affected = sections.some((section) => event.affectsConfiguration(section));
if (!affected) {
return;
}
}
let didChangeConfiguration = (sections) => {
if (sections === void 0) {
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null });
return;
}
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections) });
};
let middleware = this.getMiddleware();
middleware
? middleware(sections, didChangeConfiguration)
: didChangeConfiguration(sections);
}
extractSettingsInformation(keys) {
function ensurePath(config, path) {
let current = config;
for (let i = 0; i < path.length - 1; i++) {
let obj = current[path[i]];
if (!obj) {
obj = Object.create(null);
current[path[i]] = obj;
}
current = obj;
}
return current;
}
let resource = this._client.clientOptions.workspaceFolder
? this._client.clientOptions.workspaceFolder.uri
: undefined;
let result = Object.create(null);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let index = key.indexOf('.');
let config = null;
if (index >= 0) {
config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1));
}
else {
config = vscode_1.workspace.getConfiguration(key, resource);
}
if (config) {
let path = keys[i].split('.');
ensurePath(result, path)[path[path.length - 1]] = config;
}
}
return result;
}
getMiddleware() {
let middleware = this._client.clientOptions.middleware;
if (middleware.workspace && middleware.workspace.didChangeConfiguration) {
return middleware.workspace.didChangeConfiguration;
}
else {
return undefined;
}
}
}
class ExecuteCommandFeature {
constructor(_client) {
this._client = _client;
this._commands = new Map();
}
get messages() {
return vscode_languageserver_protocol_1.ExecuteCommandRequest.type;
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true;
}
initialize(capabilities) {
if (!capabilities.executeCommandProvider) {
return;
}
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: Object.assign({}, capabilities.executeCommandProvider)
});
}
register(_message, data) {
const client = this._client;
const middleware = client.clientOptions.middleware;
const executeCommand = (command, args) => {
let params = {
command,
arguments: args
};
return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => {
client.logFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, error);
});
};
if (data.registerOptions.commands) {
const disposeables = [];
for (const command of data.registerOptions.commands) {
disposeables.push(vscode_1.commands.registerCommand(command, (...args) => {
return middleware.executeCommand
? middleware.executeCommand(command, args, executeCommand)
: executeCommand(command, args);
}));
}
this._commands.set(data.id, disposeables);
}
}
unregister(id) {
let disposeables = this._commands.get(id);
if (disposeables) {
disposeables.forEach(disposable => disposable.dispose());
}
}
dispose() {
this._commands.forEach((value) => {
value.forEach(disposable => disposable.dispose());
});
this._commands.clear();
}
}
var MessageTransports;
(function (MessageTransports) {
function is(value) {
let candidate = value;
return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer);
}
MessageTransports.is = is;
})(MessageTransports = exports.MessageTransports || (exports.MessageTransports = {}));
class OnReady {
constructor(_resolve, _reject) {
this._resolve = _resolve;
this._reject = _reject;
this._used = false;
}
get isUsed() {
return this._used;
}
resolve() {
this._used = true;
this._resolve();
}
reject(error) {
this._used = true;
this._reject(error);
}
}
class BaseLanguageClient {
constructor(id, name, clientOptions) {
this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;
this._features = [];
this._method2Message = new Map();
this._dynamicFeatures = new Map();
this._id = id;
this._name = name;
clientOptions = clientOptions || {};
this._clientOptions = {
documentSelector: clientOptions.documentSelector || [],
synchronize: clientOptions.synchronize || {},
diagnosticCollectionName: clientOptions.diagnosticCollectionName,
outputChannelName: clientOptions.outputChannelName || this._name,
revealOutputChannelOn: clientOptions.revealOutputChannelOn || RevealOutputChannelOn.Error,
stdioEncoding: clientOptions.stdioEncoding || 'utf8',
initializationOptions: clientOptions.initializationOptions,
initializationFailedHandler: clientOptions.initializationFailedHandler,
progressOnInitialization: !!clientOptions.progressOnInitialization,
errorHandler: clientOptions.errorHandler || new DefaultErrorHandler(this._name),
middleware: clientOptions.middleware || {},
uriConverters: clientOptions.uriConverters,
workspaceFolder: clientOptions.workspaceFolder
};
this._clientOptions.synchronize = this._clientOptions.synchronize || {};
this.state = ClientState.Initial;
this._connectionPromise = undefined;
this._resolvedConnection = undefined;
this._initializeResult = undefined;
if (clientOptions.outputChannel) {
this._outputChannel = clientOptions.outputChannel;
this._disposeOutputChannel = false;
}
else {
this._outputChannel = undefined;
this._disposeOutputChannel = true;
}
this._traceOutputChannel = clientOptions.traceOutputChannel;
this._listeners = undefined;
this._providers = undefined;
this._diagnostics = undefined;
this._fileEvents = [];
this._fileEventDelayer = new async_1.Delayer(250);
this._onReady = new Promise((resolve, reject) => {
this._onReadyCallbacks = new OnReady(resolve, reject);
});
this._onStop = undefined;
this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter();
this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter();
this._tracer = {
log: (messageOrDataObject, data) => {
if (Is.string(messageOrDataObject)) {
this.logTrace(messageOrDataObject, data);
}
else {
this.logObjectTrace(messageOrDataObject);
}
},
};
this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined);
this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined);
this._syncedDocuments = new Map();
this.registerBuiltinFeatures();
}
get state() {
return this._state;
}
set state(value) {
let oldState = this.getPublicState();
this._state = value;
let newState = this.getPublicState();
if (newState !== oldState) {
this._stateChangeEmitter.fire({ oldState, newState });
}
}
getPublicState() {
if (this.state === ClientState.Running) {
return State.Running;
}
else if (this.state === ClientState.Starting) {
return State.Starting;
}
else {
return State.Stopped;
}
}
get initializeResult() {
return this._initializeResult;
}
sendRequest(type, ...params) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
this.forceDocumentSync();
try {
return this._resolvedConnection.sendRequest(type, ...params);
}
catch (error) {
this.error(`Sending request ${Is.string(type) ? type : type.method} failed.`, error);
throw error;
}
}
onRequest(type, handler) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
try {
this._resolvedConnection.onRequest(type, handler);
}
catch (error) {
this.error(`Registering request handler ${Is.string(type) ? type : type.method} failed.`, error);
throw error;
}
}
sendNotification(type, params) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
this.forceDocumentSync();
try {
this._resolvedConnection.sendNotification(type, params);
}
catch (error) {
this.error(`Sending notification ${Is.string(type) ? type : type.method} failed.`, error);
throw error;
}
}
onNotification(type, handler) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
try {
this._resolvedConnection.onNotification(type, handler);
}
catch (error) {
this.error(`Registering notification handler ${Is.string(type) ? type : type.method} failed.`, error);
throw error;
}
}
onProgress(type, token, handler) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
try {
return this._resolvedConnection.onProgress(type, token, handler);
}
catch (error) {
this.error(`Registering progress handler for token ${token} failed.`, error);
throw error;
}
}
sendProgress(type, token, value) {
if (!this.isConnectionActive()) {
throw new Error('Language client is not ready yet');
}
this.forceDocumentSync();
try {
this._resolvedConnection.sendProgress(type, token, value);
}
catch (error) {
this.error(`Sending progress for token ${token} failed.`, error);
throw error;
}
}
get clientOptions() {
return this._clientOptions;
}
get protocol2CodeConverter() {
return this._p2c;
}
get code2ProtocolConverter() {
return this._c2p;
}
get onTelemetry() {
return this._telemetryEmitter.event;
}
get onDidChangeState() {
return this._stateChangeEmitter.event;
}
get outputChannel() {
if (!this._outputChannel) {
this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name);
}
return this._outputChannel;
}
get traceOutputChannel() {
if (this._traceOutputChannel) {
return this._traceOutputChannel;
}
return this.outputChannel;
}
get diagnostics() {
return this._diagnostics;
}
createDefaultErrorHandler() {
return new DefaultErrorHandler(this._name);
}
set trace(value) {
this._trace = value;
this.onReady().then(() => {
this.resolveConnection().then((connection) => {
connection.trace(this._trace, this._tracer, {
sendNotification: false,
traceFormat: this._traceFormat
});
});
}, () => {
});
}
data2String(data) {
if (data instanceof vscode_languageserver_protocol_1.ResponseError) {
const responseError = data;
return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`;
}
if (data instanceof Error) {
if (Is.string(data.stack)) {
return data.stack;
}
return data.message;
}
if (Is.string(data)) {
return data;
}
return data.toString();
}
info(message, data) {
this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`);
if (data) {
this.outputChannel.appendLine(this.data2String(data));
}
if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) {
this.showNotificationMessage();
}
}
warn(message, data) {
this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`);
if (data) {
this.outputChannel.appendLine(this.data2String(data));
}
if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) {
this.showNotificationMessage();
}
}
error(message, data) {
this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`);
if (data) {
this.outputChannel.appendLine(this.data2String(data));
}
if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) {
this.showNotificationMessage();
}
}
showNotificationMessage() {
vscode_1.window.showInformationMessage('A request has failed. See the output for more information.', 'Go to output').then(() => {
this.outputChannel.show(true);
});
}
logTrace(message, data) {
this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`);
if (data) {
this.traceOutputChannel.appendLine(this.data2String(data));
}
}
logObjectTrace(data) {
if (data.isLSPMessage && data.type) {
this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `);
}
else {
this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `);
}
if (data) {
this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`);
}
}
needsStart() {
return this.state === ClientState.Initial || this.state === ClientState.Stopping || this.state === ClientState.Stopped;
}
needsStop() {
return this.state === ClientState.Starting || this.state === ClientState.Running;
}
onReady() {
return this._onReady;
}
isConnectionActive() {
return this.state === ClientState.Running && !!this._resolvedConnection;
}
start() {
if (this._onReadyCallbacks.isUsed) {
this._onReady = new Promise((resolve, reject) => {
this._onReadyCallbacks = new OnReady(resolve, reject);
});
}
this._listeners = [];
this._providers = [];
// If we restart then the diagnostics collection is reused.
if (!this._diagnostics) {
this._diagnostics = this._clientOptions.diagnosticCollectionName
? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName)
: vscode_1.languages.createDiagnosticCollection();
}
this.state = ClientState.Starting;
this.resolveConnection().then((connection) => {
connection.onLogMessage((message) => {
switch (message.type) {
case vscode_languageserver_protocol_1.MessageType.Error:
this.error(message.message);
break;
case vscode_languageserver_protocol_1.MessageType.Warning:
this.warn(message.message);
break;
case vscode_languageserver_protocol_1.MessageType.Info:
this.info(message.message);
break;
default:
this.outputChannel.appendLine(message.message);
}
});
connection.onShowMessage((message) => {
switch (message.type) {
case vscode_languageserver_protocol_1.MessageType.Error:
vscode_1.window.showErrorMessage(message.message);
break;
case vscode_languageserver_protocol_1.MessageType.Warning:
vscode_1.window.showWarningMessage(message.message);
break;
case vscode_languageserver_protocol_1.MessageType.Info:
vscode_1.window.showInformationMessage(message.message);
break;
default:
vscode_1.window.showInformationMessage(message.message);
}
});
connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => {
let messageFunc;
switch (params.type) {
case vscode_languageserver_protocol_1.MessageType.Error:
messageFunc = vscode_1.window.showErrorMessage;
break;
case vscode_languageserver_protocol_1.MessageType.Warning:
messageFunc = vscode_1.window.showWarningMessage;
break;
case vscode_languageserver_protocol_1.MessageType.Info:
messageFunc = vscode_1.window.showInformationMessage;
break;
default:
messageFunc = vscode_1.window.showInformationMessage;
}
let actions = params.actions || [];
return messageFunc(params.message, ...actions);
});
connection.onTelemetry((data) => {
this._telemetryEmitter.fire(data);
});
connection.listen();
// Error is handled in the initialize call.
return this.initialize(connection);
}).then(undefined, (error) => {
this.state = ClientState.StartFailed;
this._onReadyCallbacks.reject(error);
this.error('Starting client failed', error);
vscode_1.window.showErrorMessage(`Couldn't start client ${this._name}`);
});
return new vscode_1.Disposable(() => {
if (this.needsStop()) {
this.stop();
}
});
}
resolveConnection() {
if (!this._connectionPromise) {
this._connectionPromise = this.createConnection();
}
return this._connectionPromise;
}
initialize(connection) {
this.refreshTrace(connection, false);
let initOption = this._clientOptions.initializationOptions;
let rootPath = this._clientOptions.workspaceFolder
? this._clientOptions.workspaceFolder.uri.fsPath
: this._clientGetRootPath();
let initParams = {
processId: process.pid,
clientInfo: {
name: 'vscode',
version: vscode_1.version
},
rootPath: rootPath ? rootPath : null,
rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null,
capabilities: this.computeClientCapabilities(),
initializationOptions: Is.func(initOption) ? initOption() : initOption,
trace: vscode_languageserver_protocol_1.Trace.toString(this._trace),
workspaceFolders: null
};
this.fillInitializeParams(initParams);
if (this._clientOptions.progressOnInitialization) {
const token = UUID.generateUuid();
const part = new progressPart_1.ProgressPart(connection, token);
initParams.workDoneToken = token;
return this.doInitialize(connection, initParams).then((result) => {
part.done();
return result;
}, (error) => {
part.cancel();
throw error;
});
}
else {
return this.doInitialize(connection, initParams);
}
}
doInitialize(connection, initParams) {
return connection.initialize(initParams).then((result) => {
this._resolvedConnection = connection;
this._initializeResult = result;
this.state = ClientState.Running;
let textDocumentSyncOptions = undefined;
if (Is.number(result.capabilities.textDocumentSync)) {
if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {
textDocumentSyncOptions = {
openClose: false,
change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None,
save: undefined
};
}
else {
textDocumentSyncOptions = {
openClose: true,
change: result.capabilities.textDocumentSync,
save: {
includeText: false
}
};
}
}
else if (result.capabilities.textDocumentSync !== void 0 && result.capabilities.textDocumentSync !== null) {
textDocumentSyncOptions = result.capabilities.textDocumentSync;
}
this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions });
connection.onDiagnostics(params => this.handleDiagnostics(params));
connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params => this.handleRegistrationRequest(params));
// See https://github.com/Microsoft/vscode-languageserver-node/issues/199
connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params));
connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params => this.handleUnregistrationRequest(params));
// See https://github.com/Microsoft/vscode-languageserver-node/issues/199
connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params));
connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params));
connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {});
this.hookFileEvents(connection);
this.hookConfigurationChanged(connection);
this.initializeFeatures(connection);
this._onReadyCallbacks.resolve();
return result;
}).then(undefined, (error) => {
if (this._clientOptions.initializationFailedHandler) {
if (this._clientOptions.initializationFailedHandler(error)) {
this.initialize(connection);
}
else {
this.stop();
this._onReadyCallbacks.reject(error);
}
}
else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) {
vscode_1.window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => {
if (item && item.id === 'retry') {
this.initialize(connection);
}
else {
this.stop();
this._onReadyCallbacks.reject(error);
}
});
}
else {
if (error && error.message) {
vscode_1.window.showErrorMessage(error.message);
}
this.error('Server initialization failed.', error);
this.stop();
this._onReadyCallbacks.reject(error);
}
throw error;
});
}
_clientGetRootPath() {
let folders = vscode_1.workspace.workspaceFolders;
if (!folders || folders.length === 0) {
return undefined;
}
let folder = folders[0];
if (folder.uri.scheme === 'file') {
return folder.uri.fsPath;
}
return undefined;
}
stop() {
this._initializeResult = undefined;
if (!this._connectionPromise) {
this.state = ClientState.Stopped;
return Promise.resolve();
}
if (this.state === ClientState.Stopping && this._onStop) {
return this._onStop;
}
this.state = ClientState.Stopping;
this.cleanUp(false);
// unhook listeners
return this._onStop = this.resolveConnection().then(connection => {
return connection.shutdown().then(() => {
connection.exit();
connection.dispose();
this.state = ClientState.Stopped;
this.cleanUpChannel();
this._onStop = undefined;
this._connectionPromise = undefined;
this._resolvedConnection = undefined;
});
});
}
cleanUp(channel = true, diagnostics = true) {
if (this._listeners) {
this._listeners.forEach(listener => listener.dispose());
this._listeners = undefined;
}
if (this._providers) {
this._providers.forEach(provider => provider.dispose());
this._providers = undefined;
}
if (this._syncedDocuments) {
this._syncedDocuments.clear();
}
for (let handler of this._dynamicFeatures.values()) {
handler.dispose();
}
if (channel) {
this.cleanUpChannel();
}
if (diagnostics && this._diagnostics) {
this._diagnostics.dispose();
this._diagnostics = undefined;
}
}
cleanUpChannel() {
if (this._outputChannel && this._disposeOutputChannel) {
this._outputChannel.dispose();
this._outputChannel = undefined;
}
}
notifyFileEvent(event) {
var _a;
const client = this;
function didChangeWatchedFile(event) {
client._fileEvents.push(event);
client._fileEventDelayer.trigger(() => {
client.onReady().then(() => {
client.resolveConnection().then(connection => {
if (client.isConnectionActive()) {
client.forceDocumentSync();
connection.didChangeWatchedFiles({ changes: client._fileEvents });
}
client._fileEvents = [];
});
}, (error) => {
client.error(`Notify file events failed.`, error);
});
});
}
const workSpaceMiddleware = (_a = this.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
(workSpaceMiddleware === null || workSpaceMiddleware === void 0 ? void 0 : workSpaceMiddleware.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event);
}
forceDocumentSync() {
this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method).forceDelivery();
}
handleDiagnostics(params) {
if (!this._diagnostics) {
return;
}
let uri = this._p2c.asUri(params.uri);
let diagnostics = this._p2c.asDiagnostics(params.diagnostics);
let middleware = this.clientOptions.middleware;
if (middleware.handleDiagnostics) {
middleware.handleDiagnostics(uri, diagnostics, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics));
}
else {
this.setDiagnostics(uri, diagnostics);
}
}
setDiagnostics(uri, diagnostics) {
if (!this._diagnostics) {
return;
}
this._diagnostics.set(uri, diagnostics);
}
createConnection() {
let errorHandler = (error, message, count) => {
this.handleConnectionError(error, message, count);
};
let closeHandler = () => {
this.handleConnectionClosed();
};
return this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8').then((transports) => {
return createConnection(transports.reader, transports.writer, errorHandler, closeHandler);
});
}
handleConnectionClosed() {
// Check whether this is a normal shutdown in progress or the client stopped normally.
if (this.state === ClientState.Stopping || this.state === ClientState.Stopped) {
return;
}
try {
if (this._resolvedConnection) {
this._resolvedConnection.dispose();
}
}
catch (error) {
// Disposing a connection could fail if error cases.
}
let action = CloseAction.DoNotRestart;
try {
action = this._clientOptions.errorHandler.closed();
}
catch (error) {
// Ignore errors coming from the error handler.
}
this._connectionPromise = undefined;
this._resolvedConnection = undefined;
if (action === CloseAction.DoNotRestart) {
this.error('Connection to server got closed. Server will not be restarted.');
this.state = ClientState.Stopped;
this.cleanUp(false, true);
}
else if (action === CloseAction.Restart) {
this.info('Connection to server got closed. Server will restart.');
this.cleanUp(false, false);
this.state = ClientState.Initial;
this.start();
}
}
handleConnectionError(error, message, count) {
let action = this._clientOptions.errorHandler.error(error, message, count);
if (action === ErrorAction.Shutdown) {
this.error('Connection to server is erroring. Shutting down server.');
this.stop();
}
}
hookConfigurationChanged(connection) {
vscode_1.workspace.onDidChangeConfiguration(() => {
this.refreshTrace(connection, true);
});
}
refreshTrace(connection, sendNotification = false) {
let config = vscode_1.workspace.getConfiguration(this._id);
let trace = vscode_languageserver_protocol_1.Trace.Off;
let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;
if (config) {
const traceConfig = config.get('trace.server', 'off');
if (typeof traceConfig === 'string') {
trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig);
}
else {
trace = vscode_languageserver_protocol_1.Trace.fromString(config.get('trace.server.verbosity', 'off'));
traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get('trace.server.format', 'text'));
}
}
this._trace = trace;
this._traceFormat = traceFormat;
connection.trace(this._trace, this._tracer, {
sendNotification,
traceFormat: this._traceFormat
});
}
hookFileEvents(_connection) {
let fileEvents = this._clientOptions.synchronize.fileEvents;
if (!fileEvents) {
return;
}
let watchers;
if (Is.array(fileEvents)) {
watchers = fileEvents;
}
else {
watchers = [fileEvents];
}
if (!watchers) {
return;
}
this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers);
}
registerFeatures(features) {
for (let feature of features) {
this.registerFeature(feature);
}
}
registerFeature(feature) {
this._features.push(feature);
if (DynamicFeature.is(feature)) {
let messages = feature.messages;
if (Array.isArray(messages)) {
for (let message of messages) {
this._method2Message.set(message.method, message);
this._dynamicFeatures.set(message.method, feature);
}
}
else {
this._method2Message.set(messages.method, messages);
this._dynamicFeatures.set(messages.method, feature);
}
}
}
getFeature(request) {
return this._dynamicFeatures.get(request);
}
registerBuiltinFeatures() {
this.registerFeature(new ConfigurationFeature(this));
this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments));
this.registerFeature(new DidChangeTextDocumentFeature(this));
this.registerFeature(new WillSaveFeature(this));
this.registerFeature(new WillSaveWaitUntilFeature(this));
this.registerFeature(new DidSaveTextDocumentFeature(this));
this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments));
this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event)));
this.registerFeature(new CompletionItemFeature(this));
this.registerFeature(new HoverFeature(this));
this.registerFeature(new SignatureHelpFeature(this));
this.registerFeature(new DefinitionFeature(this));
this.registerFeature(new ReferencesFeature(this));
this.registerFeature(new DocumentHighlightFeature(this));
this.registerFeature(new DocumentSymbolFeature(this));
this.registerFeature(new WorkspaceSymbolFeature(this));
this.registerFeature(new CodeActionFeature(this));
this.registerFeature(new CodeLensFeature(this));
this.registerFeature(new DocumentFormattingFeature(this));
this.registerFeature(new DocumentRangeFormattingFeature(this));
this.registerFeature(new DocumentOnTypeFormattingFeature(this));
this.registerFeature(new RenameFeature(this));
this.registerFeature(new DocumentLinkFeature(this));
this.registerFeature(new ExecuteCommandFeature(this));
}
fillInitializeParams(params) {
for (let feature of this._features) {
if (Is.func(feature.fillInitializeParams)) {
feature.fillInitializeParams(params);
}
}
}
computeClientCapabilities() {
let result = {};
ensure(result, 'workspace').applyEdit = true;
let workspaceEdit = ensure(ensure(result, 'workspace'), 'workspaceEdit');
workspaceEdit.documentChanges = true;
workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete];
workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional;
let diagnostics = ensure(ensure(result, 'textDocument'), 'publishDiagnostics');
diagnostics.relatedInformation = true;
diagnostics.versionSupport = false;
diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] };
for (let feature of this._features) {
feature.fillClientCapabilities(result);
}
return result;
}
initializeFeatures(_connection) {
let documentSelector = this._clientOptions.documentSelector;
for (let feature of this._features) {
feature.initialize(this._capabilities, documentSelector);
}
}
handleRegistrationRequest(params) {
return new Promise((resolve, reject) => {
for (let registration of params.registrations) {
const feature = this._dynamicFeatures.get(registration.method);
if (!feature) {
reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`));
return;
}
const options = registration.registerOptions || {};
options.documentSelector = options.documentSelector || this._clientOptions.documentSelector;
const data = {
id: registration.id,
registerOptions: options
};
feature.register(this._method2Message.get(registration.method), data);
}
resolve();
});
}
handleUnregistrationRequest(params) {
return new Promise((resolve, reject) => {
for (let unregistration of params.unregisterations) {
const feature = this._dynamicFeatures.get(unregistration.method);
if (!feature) {
reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`));
return;
}
feature.unregister(unregistration.id);
}
resolve();
});
}
handleApplyWorkspaceEdit(params) {
// This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit.
// However doing it here adds some safety since the server can lag more behind then an extension.
let workspaceEdit = params.edit;
let openTextDocuments = new Map();
vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document));
let versionMismatch = false;
if (workspaceEdit.documentChanges) {
for (const change of workspaceEdit.documentChanges) {
if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) {
let textDocument = openTextDocuments.get(change.textDocument.uri);
if (textDocument && textDocument.version !== change.textDocument.version) {
versionMismatch = true;
break;
}
}
}
}
if (versionMismatch) {
return Promise.resolve({ applied: false });
}
return Is.asPromise(vscode_1.workspace.applyEdit(this._p2c.asWorkspaceEdit(params.edit)).then((value) => { return { applied: value }; }));
}
logFailedRequest(type, error) {
// If we get a request cancel or a content modified don't log anything.
if (error instanceof vscode_languageserver_protocol_1.ResponseError && (error.code === vscode_languageserver_protocol_1.ErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.ErrorCodes.ContentModified)) {
return;
}
this.error(`Request ${type.method} failed.`, error);
}
}
exports.BaseLanguageClient = BaseLanguageClient;
| karan/dotfiles | .vscode/extensions/ms-vscode.go-0.14.1/node_modules/vscode-languageclient/lib/client.js | JavaScript | mit | 119,699 |
Marker = function({ settings, rad }) {
const long = settings.longMarker ? 'protractor-extension-marker-long' : "";
this.theta = rad - Math.PI / 2;
this.phi = settings.phi;
this.settings = settings;
this.node = document.createElement('div');
this.node.className = `protractor-extension-marker ${long}`;
this.node.style.borderBottom = `20px solid ${settings.markerFill}`;
PubSub.subscribe(Channels.MOVE_CONTAINER, this);
PubSub.subscribe(Channels.MOVE_HANDLE_ROTATE, this);
return this.node;
};
Marker.prototype = {
onRotate: function(msg) {
this.rotation += msg.phi;
},
onUpdate: function(chan, msg) {
switch(chan) {
case Channels.MOVE_CONTAINER: this.onMoveContainer(msg); break;
case Channels.MOVE_HANDLE_ROTATE: this.onMoveHandleRotate(msg); break;
}
},
onMoveContainer: function(msg) {
this.node.style.height = `${msg.radius + 10}px`;
if (this.settings.longMarker)
{
const rgba = this.settings.markerFill.replace('1)', '0.4)');
this.node.style.borderTop = `${msg.radius - 10}px solid ${rgba}`;
}
this.transform();
},
onMoveHandleRotate: function(msg) {
this.phi = msg.phi;
this.transform();
},
transform: function() {
this.node.style.transform = `rotate(${this.theta + this.phi}rad)`;
},
setMode: function() {
this.node.className = (msg.mode === "lock" ? 'protractor-extension-marker protractor-extension-marker-locked' : 'protractor-extension-marker');
},
};
| ben-burlingham/protractor | public/scripts/marker.js | JavaScript | mit | 1,607 |
using App.Common.Db;
using Microsoft.EntityFrameworkCore;
using System;
namespace App.Cmd.Commands {
public static class MigrateCommand{
public static void Run(){
Console.WriteLine("Running migrations...");
using (var dbScope = new AppDbScope()){
dbScope.AppDb.Database.Migrate();
}
Console.WriteLine("Done");
}
}
} | caleblloyd/dotnet-core-boilerplate | dotnet/src/App/Cmd/Commands/MigrateCommand.cs | C# | mit | 408 |
package com.tek271.funj;
import com.google.common.annotations.Beta;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
@Beta
public class Transformer {
private List<StepFunction> steps = newArrayList();
public static Transformer create() {
return new Transformer();
}
public Transformer addSteps(StepFunction... steps) {
this.steps.addAll(newArrayList(steps));
return this;
}
@SuppressWarnings("unchecked")
public <IN, OUT> List<OUT> apply(Iterable<IN> iterable) {
List<?> in = newArrayList(iterable);
for (StepFunction step: steps) {
in = step.apply(in);
}
return (List<OUT>) in;
}
}
| ahabra/funj | src/main/java/com/tek271/funj/Transformer.java | Java | mit | 653 |
<?php
/**
* Created by PhpStorm.
* User: daniel
* Date: 13.10.14
* Time: 17:11
*/
namespace Cundd\PersistentObjectStore\Server\BodyParser;
use React\Http\Request;
/**
* Body Parser implementation that can parse form data
*
* @package Cundd\PersistentObjectStore\Server\BodyParser
*/
class FormDataBodyParser implements BodyParserInterface
{
/**
* @param string $data
* @param Request $request
* @return mixed
*/
public function parse($data, $request)
{
$parsedData = array();
parse_str($data, $parsedData);
return $parsedData;
}
}
| cundd/pos | Classes/Server/BodyParser/FormDataBodyParser.php | PHP | mit | 604 |
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
cwd = os.getcwd()
parent = os.path.dirname(cwd)
sys.path.append(parent)
import cbh_core_model
# -- General configuration -----------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'cbh_core_model'
copyright = u'2015, Andrew Stretton'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = cbh_core_model.__version__
# The full version, including alpha/beta/rc tags.
release = cbh_core_model.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ---------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'cbh_core_modeldoc'
# -- Options for LaTeX output --------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'cbh_core_model.tex', u'cbh_core_model Documentation',
u'Andrew Stretton', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'cbh_core_model', u'cbh_core_model Documentation',
[u'Andrew Stretton'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'cbh_core_model', u'cbh_core_model Documentation',
u'Andrew Stretton', 'cbh_core_model', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| thesgc/cbh_core_model | docs/conf.py | Python | mit | 8,194 |
"use strict";
import React from 'react'
import Course from '../partials/Course.js'
import Modal from '../partials/Modal.js'
import MetricModal from '../partials/MetricModal.js'
export default class Courses extends React.Component {
constructor(props) {
super(props);
this.state = {
course: props.course,
sections: props.course.sections,
showModal: false,
showMetricModal: false,
modalInfo: {
modalType: "ADD_QUIZ",
title: "Add Quiz"
}
};
}
componentDidMount() {
this.getCoursesAndSections(this.state.course.id);
}
componentWillReceiveProps(newProps) {
if(newProps.course != undefined) {
this.getCoursesAndSections(newProps.course.id);
}
}
getCoursesAndSections(courseId) {
if(courseId == -1) return;
var me = this;
$.when(
$.post("/course/find", {id: courseId}),
$.post("/section/find", {course: courseId})
).then(function(course, sections) {
console.log("course", course[0]);
console.log("sections", sections[0]);
if(course == undefined) return; // if there are no courses, then there are no sections
me.setState({
course: course[0],
sections: sections[0]
});
});
}
closeModal() {
this.setState({
showModal: false,
showMetricModal: false
});
}
showMetricModal(quiz) {
console.log("showMetricModal!", quiz);
var modalInfo = this.state.modalInfo;
modalInfo.title = quiz.title;
this.setState({
showModal: false,
showMetricModal: true,
modalInfo: modalInfo
});
}
showCourseModal() {
var modalInfo = this.state.modalInfo;
modalInfo.modalType = "ADD_COURSE";
modalInfo.title = "Add Course or Section";
this.setState({
showModal: true,
showMetricModal: false,
modalInfo: modalInfo
});
}
showQuizModal(quizIndex) {
var modalInfo = this.state.modalInfo;
modalInfo.title = "Add Quiz";
modalInfo.modalType = "ADD_QUIZ";
modalInfo.quizIndex = quizIndex;
this.setState({
showModal: true,
showMetricModal: false,
modalInfo: modalInfo
});
}
showQuizInModal(quizIndex) {
console.log("showQuizInModal::quizIndex", quizIndex);
this.showQuizModal(quizIndex);
}
showStudentsModal(section) {
var modalInfo = this.state.modalInfo;
modalInfo.modalType = "ADD_STUDENTS";
modalInfo.title = "Add Students";
modalInfo.section = section;
this.setState({
showModal: true,
showMetricModal: false,
modalInfo: modalInfo
});
}
addQuizToCourse(quiz, quizIndex) {
console.log("Adding quiz '" + quiz.title + "' in course " + this.props.course.title);
var me = this;
if(quizIndex > -1) {
$.post('/quiz/update/' + quiz.id, { title: quiz.title })
.then(function(quiz) {
console.log(quiz);
var course = me.state.course;
course.quizzes[quizIndex] = quiz;
me.setState({course: course});
me.closeModal();
});
} else {
$.post('/quiz/create/',
{
title: quiz.title,
course: me.props.course.id
}
)
.then(function(quiz) {
console.log(quiz);
var course = me.state.course;
course.quizzes.push(quiz);
me.setState({course: course});
me.closeModal();
});
}
}
addSectionToCourse(section) {
var me = this;
if(section.title == '') {
return;
}
$.post('/section/create/', { title: section.title, course: me.state.course.id })
.then(function(section) {
console.log("created section", section);
var sections = me.state.sections;
sections.push(section);
me.setState({sections: sections});
me.closeModal();
});
}
addCourseToProfessor(course, term) {
var me = this;
this.props.addCourseToProfessor(course, term)
.then(function(newCourse) {
me.setState({course: newCourse});
me.closeModal();
});
}
addStudentsToSection(sectionId, studentIds) {
var me = this;
this.props.addStudentsToSection(sectionId, studentIds)
.then(function() {
me.closeModal();
});
}
deleteSectionFromCourse(sectionIndex) {
var me = this;
var sections = me.state.sections;
if(sections[sectionIndex] == undefined) return $.when(null);
$.post('/section/destroy/' + sections[sectionIndex].id)
.then(function(section) {
console.log("section", section);
sections.splice(sectionIndex, 1);
me.setState({sections: sections});
me.closeModal();
});
}
deleteQuizFromCourse(quizIndex) {
var me = this;
var quizzes = this.state.course.quizzes;
$.post('/quiz/find/' + quizzes[quizIndex].id)
.then(function(quiz) {
return $.post('/quiz/destroy/' + quizzes[quizIndex].id);
})
// .then(function(quiz) {
// if(quiz.questions.length == 0) return $.when(null);
// var questionIds = quiz.questions.map(function(question){return question.id;});
// return $.post('/question/multidestroy', {ids: questionIds});
// })
.then(function() {
quizzes.splice(quizIndex, 1);
var course = me.state.course;
course.quizzes = quizzes;
me.setState({course: course});
me.closeModal();
});
}
deleteCourseFromProfessor(course) {
var me = this;
this.props.deleteCourseFromProfessor(course)
.then(function() {
var course = {
id: -1,
title: "FAKE 101",
quizzes: [],
sections: []
};
me.setState({course: course});
});
}
render() {
return (
<div>
<div id="courses" className="quizzlyContent">
{(() => {
if(this.state.course.id > -1) {
return (
<Course
course={this.state.course}
isCourse={true}
ref={'course'}
showQuizModal={this.showQuizModal.bind(this)}
showQuizInModal={this.showQuizInModal.bind(this)}
showMetricModal={this.showMetricModal.bind(this)}
deleteQuizFromCourse={this.deleteQuizFromCourse.bind(this)}
sectionIndex={-1}
deleteCourseFromProfessor={this.deleteCourseFromProfessor.bind(this)}
deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)}
/>
);
}
})()}
{this.state.sections.map(function(section, sectionIndex) {
// this is section, not course!
return (
<Course
section={section}
sectionIndex={sectionIndex}
course={this.state.course}
isCourse={false}
key={sectionIndex}
showQuizInModal={this.showQuizInModal.bind(this)}
showMetricModal={this.showMetricModal.bind(this)}
showStudentsModal={this.showStudentsModal.bind(this)}
deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)}
/>
);
}, this)}
<div className="addEntityButton" onClick={this.showCourseModal.bind(this)}>+</div>
</div>
{(() => {
if(this.state.showModal)
return (
<Modal
modalInfo={this.state.modalInfo}
showModal={this.state.showModal}
course={this.state.course}
quizzes={this.state.course.quizzes}
key={this.state.showModal}
closeModal={this.closeModal.bind(this)}
addQuizToCourse={this.addQuizToCourse.bind(this)}
addCourseToProfessor={this.addCourseToProfessor.bind(this)}
addSectionToCourse={this.addSectionToCourse.bind(this)}
addStudentsToSection={this.addStudentsToSection.bind(this)}
/>
);
})()}
{(() => {
if(this.state.showMetricModal)
return (
<MetricModal
modalInfo={this.state.modalInfo}
showMetricModal={this.state.showMetricModal}
key={this.state.showMetricModal}
closeModal={this.closeModal.bind(this)}
/>
);
})()}
</div>
);
}
}
| freyconner24/Quizzly | components/pages/Courses.js | JavaScript | mit | 8,389 |
import numpy as np
import keras as ks
import matplotlib.pyplot as plt
from keras.datasets import boston_housing
from keras import models
from keras import layers
from keras.utils.np_utils import to_categorical
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
mean = train_data.mean(axis = 0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
test_data -= mean
test_data /= std
def build_model():
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model
k = 4
num_val_samples = len(train_data) // k
num_epochs = 500
all_scores = []
all_mae_histories = []
for i in range(k):
print('processing fold #', i)
val_data = train_data[i * num_val_samples : (i+1) * num_val_samples]
val_targets = train_targets[i * num_val_samples : (i+1) * num_val_samples]
partial_train_data = np.concatenate([train_data[: i * num_val_samples], train_data[(i+1) * num_val_samples:]], axis=0)
partial_train_targets = np.concatenate([train_targets[: i * num_val_samples], train_targets[(i+1) * num_val_samples:]], axis=0)
model = build_model()
history = model.fit(partial_train_data, partial_train_targets, epochs=num_epochs, batch_size=1, verbose=0)
val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
all_mae_histories.append(history.history['mean_absolute_error'])
all_scores.append(val_mae)
print(all_scores)
average_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
# plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
plt.plot(average_mae_history[10:])
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show() | FiveEye/ml-notebook | dlp/ch3_3_boston_housing.py | Python | mit | 1,900 |
package net.techcable.srglib.mappings;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.UnaryOperator;
import javax.annotation.Nullable;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableBiMap;
import net.techcable.srglib.FieldData;
import net.techcable.srglib.JavaType;
import net.techcable.srglib.MethodData;
import net.techcable.srglib.SrgLib;
import net.techcable.srglib.utils.ImmutableMaps;
import static com.google.common.base.Preconditions.*;
import static java.util.Objects.*;
public final class ImmutableMappings implements Mappings {
private final ImmutableBiMap<JavaType, JavaType> classes;
private final ImmutableBiMap<MethodData, MethodData> methods;
private final ImmutableBiMap<FieldData, FieldData> fields;
/* package */ static final ImmutableMappings EMPTY = new ImmutableMappings(ImmutableBiMap.of(), ImmutableBiMap.of(), ImmutableBiMap.of());
private ImmutableMappings(
ImmutableBiMap<JavaType, JavaType> classes,
ImmutableBiMap<MethodData, MethodData> methods,
ImmutableBiMap<FieldData, FieldData> fields
) {
this.classes = requireNonNull(classes, "Null types");
this.methods = requireNonNull(methods, "Null methods");
this.fields = requireNonNull(fields, "Null fields");
}
@Override
public JavaType getNewClass(JavaType original) {
checkArgument(original.isReferenceType(), "Type isn't a reference type: %s", original);
return classes.getOrDefault(requireNonNull(original), original);
}
@Override
public MethodData getNewMethod(MethodData original) {
MethodData result = methods.get(requireNonNull(original));
if (result != null) {
return result;
} else {
return original.mapTypes(this::getNewType);
}
}
@Override
public FieldData getNewField(FieldData original) {
FieldData result = fields.get(requireNonNull(original));
if (result != null) {
return result;
} else {
return original.mapTypes(this::getNewType);
}
}
@Override
public Set<JavaType> classes() {
return classes.keySet();
}
@Override
public Set<MethodData> methods() {
return methods.keySet();
}
@Override
public Set<FieldData> fields() {
return fields.keySet();
}
@Override
public ImmutableMappings snapshot() {
return this;
}
@Nullable
private ImmutableMappings inverted;
@Override
public ImmutableMappings inverted() {
ImmutableMappings inverted = this.inverted;
return inverted != null ? inverted : (this.inverted = invert0());
}
private ImmutableMappings invert0() {
ImmutableMappings inverted = new ImmutableMappings(this.classes.inverse(), this.methods.inverse(), this.fields.inverse());
inverted.inverted = this;
return inverted;
}
public static ImmutableMappings copyOf(
Map<JavaType, JavaType> originalClasses,
Map<MethodData, String> methodNames,
Map<FieldData, String> fieldNames
) {
ImmutableBiMap<JavaType, JavaType> classes = ImmutableBiMap.copyOf(originalClasses); // Defensive copy to an ImmutableBiMap
// No consistency check needed since we're building type-information from scratch
ImmutableBiMap.Builder<MethodData, MethodData> methods = ImmutableBiMap.builder();
ImmutableBiMap.Builder<FieldData, FieldData> fields = ImmutableBiMap.builder();
methodNames.forEach((originalData, newName) -> {
MethodData newData = originalData
.mapTypes((oldType) -> oldType.mapClass(oldClass -> classes.getOrDefault(oldClass, oldClass)))
.withName(newName);
methods.put(originalData, newData);
});
fieldNames.forEach((originalData, newName) -> {
FieldData newData = FieldData.create(
originalData.getDeclaringType().mapClass(oldClass -> classes.getOrDefault(oldClass, oldClass)),
newName
);
fields.put(originalData, newData);
});
return new ImmutableMappings(
ImmutableBiMap.copyOf(classes),
methods.build(),
fields.build()
);
}
/**
* Create new ImmutableMappings with the specified data.
* <p>
* NOTE: {@link #copyOf(Map, Map, Map)} may be preferable,
* as it automatically remaps method signatures for you.
* </p>
*
* @param classes the class data mappings
* @param methods the method data mappings
* @param fields the field data mappings
* @throws IllegalArgumentException if any of the types in the fields or methods don't match the type data
* @return immutable mappings with the specified data
*/
public static ImmutableMappings create(
ImmutableBiMap<JavaType, JavaType> classes,
ImmutableBiMap<MethodData, MethodData> methods,
ImmutableBiMap<FieldData, FieldData> fields
) {
ImmutableMappings result = new ImmutableMappings(classes, methods, fields);
SrgLib.checkConsistency(result);
return result;
}
public static ImmutableMappings copyOf(Mappings other) {
if (other instanceof ImmutableMappings) {
return (ImmutableMappings) other;
} else if (other instanceof SimpleMappings) {
return other.snapshot();
} else {
return create(
ImmutableMaps.createBiMap(other.classes(), other::getNewType),
ImmutableMaps.createBiMap(other.methods(), other::getNewMethod),
ImmutableMaps.createBiMap(other.fields(), other::getNewField)
);
}
}
@Override
public void forEachClass(BiConsumer<JavaType, JavaType> action) {
classes.forEach(action);
}
@Override
public void forEachMethod(BiConsumer<MethodData, MethodData> action) {
methods.forEach(action);
}
@Override
public void forEachField(BiConsumer<FieldData, FieldData> action) {
fields.forEach(action);
}
@Override
public int hashCode() {
return classes.hashCode() ^ methods.hashCode() ^ fields.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null) {
return false;
} else if (obj.getClass() == ImmutableMappings.class) {
return this.classes.equals(((ImmutableMappings) obj).classes)
&& this.methods.equals(((ImmutableMappings) obj).methods)
&& this.fields.equals(((ImmutableMappings) obj).fields);
} else if (obj instanceof Mappings) {
return this.equals(((Mappings) obj).snapshot());
} else {
return false;
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(Mappings.class)
.add("classes", ImmutableMaps.joinToString(
classes,
(original, renamed) -> String.format(" %s = %s", original.getName(), renamed.getName()),
"\n", "{", "}"
))
.add("methods", ImmutableMaps.joinToString(
methods,
(original, renamed) -> String.format(" %s = %s", original, renamed),
"\n", "{\n", "\n}"
))
.add("fields", ImmutableMaps.joinToString(
fields,
(original, renamed) -> String.format(" %s = %s", original, renamed),
"\n", "{\n", "\n}"
))
.toString();
}
}
| ProjectTestificate/SrgLib | src/main/java/net/techcable/srglib/mappings/ImmutableMappings.java | Java | mit | 7,965 |
/*
*
* RayTrace Software Package, release 1.0.3, July 2003.
*
* Author: Samuel R. Buss
*
* Software accompanying the book
* 3D Computer Graphics: A Mathematical Introduction with OpenGL,
* by S. Buss, Cambridge University Press, 2003.
*
* Software is "as-is" and carries no warranty. It may be used without
* restriction, but if you modify it, please change the filenames to
* prevent confusion between different versions. Please acknowledge
* all use of the software in any publications or products based on it.
*
* Bug reports: Sam Buss, sbuss@ucsd.edu.
* Web page: http://math.ucsd.edu/~sbuss/MathCG
*
*/
#include "RgbImage.h"
#ifndef RGBIMAGE_DONT_USE_OPENGL
#include <windows.h>
#include "GL/gl.h"
#endif
RgbImage::RgbImage( int numRows, int numCols )
{
NumRows = numRows;
NumCols = numCols;
ImagePtr = new unsigned char[NumRows*GetNumBytesPerRow()];
if ( !ImagePtr ) {
fprintf(stderr, "Unable to allocate memory for %ld x %ld bitmap.\n",
NumRows, NumCols);
Reset();
ErrorCode = MemoryError;
}
// Zero out the image
unsigned char* c = ImagePtr;
int rowLen = GetNumBytesPerRow();
for ( int i=0; i<NumRows; i++ ) {
for ( int j=0; j<rowLen; j++ ) {
*(c++) = 0;
}
}
}
/* ********************************************************************
* LoadBmpFile
* Read into memory an RGB image from an uncompressed BMP file.
* Return true for success, false for failure. Error code is available
* with a separate call.
* Author: Sam Buss December 2001.
**********************************************************************/
bool RgbImage::LoadBmpFile( const char* filename )
{
Reset();
FILE* infile = fopen( filename, "rb" ); // Open for reading binary data
if ( !infile ) {
fprintf(stderr, "Unable to open file: %s\n", filename);
ErrorCode = OpenError;
return false;
}
bool fileFormatOK = false;
int bChar = fgetc( infile );
int mChar = fgetc( infile );
if ( bChar=='B' && mChar=='M' ) { // If starts with "BM" for "BitMap"
skipChars( infile, 4+2+2+4+4 ); // Skip 4 fields we don't care about
NumCols = readLong( infile );
NumRows = readLong( infile );
skipChars( infile, 2 ); // Skip one field
int bitsPerPixel = readShort( infile );
skipChars( infile, 4+4+4+4+4+4 ); // Skip 6 more fields
if ( NumCols>0 && NumCols<=100000 && NumRows>0 && NumRows<=100000
&& bitsPerPixel==24 && !feof(infile) ) {
fileFormatOK = true;
}
}
if ( !fileFormatOK ) {
Reset();
ErrorCode = FileFormatError;
fprintf(stderr, "Not a valid 24-bit bitmap file: %s.\n", filename);
fclose ( infile );
return false;
}
// Allocate memory
ImagePtr = new unsigned char[NumRows*GetNumBytesPerRow()];
if ( !ImagePtr ) {
fprintf(stderr, "Unable to allocate memory for %ld x %ld bitmap: %s.\n",
NumRows, NumCols, filename);
Reset();
ErrorCode = MemoryError;
fclose ( infile );
return false;
}
unsigned char* cPtr = ImagePtr;
for ( int i=0; i<NumRows; i++ ) {
int j;
for ( j=0; j<NumCols; j++ ) {
*(cPtr+2) = fgetc( infile ); // Blue color value
*(cPtr+1) = fgetc( infile ); // Green color value
*cPtr = fgetc( infile ); // Red color value
cPtr += 3;
}
int k=3*j; // Num bytes already read
for ( ; k<GetNumBytesPerRow(); k++ ) {
fgetc( infile ); // Read and ignore padding;
*(cPtr++) = 0;
}
}
if ( feof( infile ) ) {
fprintf( stderr, "Premature end of file: %s.\n", filename );
Reset();
ErrorCode = ReadError;
fclose ( infile );
return false;
}
fclose( infile ); // Close the file
return true;
}
short RgbImage::readShort( FILE* infile )
{
// read a 16 bit integer
unsigned char lowByte, hiByte;
lowByte = fgetc(infile); // Read the low order byte (little endian form)
hiByte = fgetc(infile); // Read the high order byte
// Pack together
short ret = hiByte;
ret <<= 8;
ret |= lowByte;
return ret;
}
long RgbImage::readLong( FILE* infile )
{
// Read in 32 bit integer
unsigned char byte0, byte1, byte2, byte3;
byte0 = fgetc(infile); // Read bytes, low order to high order
byte1 = fgetc(infile);
byte2 = fgetc(infile);
byte3 = fgetc(infile);
// Pack together
long ret = byte3;
ret <<= 8;
ret |= byte2;
ret <<= 8;
ret |= byte1;
ret <<= 8;
ret |= byte0;
return ret;
}
void RgbImage::skipChars( FILE* infile, int numChars )
{
for ( int i=0; i<numChars; i++ ) {
fgetc( infile );
}
}
/* ********************************************************************
* WriteBmpFile
* Write an RGB image to an uncompressed BMP file.
* Return true for success, false for failure. Error code is available
* with a separate call.
* Author: Sam Buss, January 2003.
**********************************************************************/
bool RgbImage::WriteBmpFile( const char* filename )
{
FILE* outfile = fopen( filename, "wb" ); // Open for reading binary data
if ( !outfile ) {
fprintf(stderr, "Unable to open file: %s\n", filename);
ErrorCode = OpenError;
return false;
}
fputc('B',outfile);
fputc('M',outfile);
int rowLen = GetNumBytesPerRow();
writeLong( 40+14+NumRows*rowLen, outfile ); // Length of file
writeShort( 0, outfile ); // Reserved for future use
writeShort( 0, outfile );
writeLong( 40+14, outfile ); // Offset to pixel data
writeLong( 40, outfile ); // header length
writeLong( NumCols, outfile ); // width in pixels
writeLong( NumRows, outfile ); // height in pixels (pos for bottom up)
writeShort( 1, outfile ); // number of planes
writeShort( 24, outfile ); // bits per pixel
writeLong( 0, outfile ); // no compression
writeLong( 0, outfile ); // not used if no compression
writeLong( 0, outfile ); // Pixels per meter
writeLong( 0, outfile ); // Pixels per meter
writeLong( 0, outfile ); // unused for 24 bits/pixel
writeLong( 0, outfile ); // unused for 24 bits/pixel
// Now write out the pixel data:
unsigned char* cPtr = ImagePtr;
for ( int i=0; i<NumRows; i++ ) {
// Write out i-th row's data
int j;
for ( j=0; j<NumCols; j++ ) {
fputc( *(cPtr+2), outfile); // Blue color value
fputc( *(cPtr+1), outfile); // Blue color value
fputc( *(cPtr+0), outfile); // Blue color value
cPtr+=3;
}
// Pad row to word boundary
int k=3*j; // Num bytes already read
for ( ; k<GetNumBytesPerRow(); k++ ) {
fputc( 0, outfile ); // Read and ignore padding;
cPtr++;
}
}
fclose( outfile ); // Close the file
return true;
}
void RgbImage::writeLong( long data, FILE* outfile )
{
// Read in 32 bit integer
unsigned char byte0, byte1, byte2, byte3;
byte0 = (unsigned char)(data&0x000000ff); // Write bytes, low order to high order
byte1 = (unsigned char)((data>>8)&0x000000ff);
byte2 = (unsigned char)((data>>16)&0x000000ff);
byte3 = (unsigned char)((data>>24)&0x000000ff);
fputc( byte0, outfile );
fputc( byte1, outfile );
fputc( byte2, outfile );
fputc( byte3, outfile );
}
void RgbImage::writeShort( short data, FILE* outfile )
{
// Read in 32 bit integer
unsigned char byte0, byte1;
byte0 = data&0x000000ff; // Write bytes, low order to high order
byte1 = (data>>8)&0x000000ff;
fputc( byte0, outfile );
fputc( byte1, outfile );
}
/*********************************************************************
* SetRgbPixel routines allow changing the contents of the RgbImage. *
*********************************************************************/
void RgbImage::SetRgbPixelf( long row, long col, double red, double green, double blue )
{
SetRgbPixelc( row, col, doubleToUnsignedChar(red),
doubleToUnsignedChar(green),
doubleToUnsignedChar(blue) );
}
void RgbImage::SetRgbPixelc( long row, long col,
unsigned char red, unsigned char green, unsigned char blue )
{
assert ( row<NumRows && col<NumCols );
unsigned char* thePixel = GetRgbPixel( row, col );
*(thePixel++) = red;
*(thePixel++) = green;
*(thePixel) = blue;
}
unsigned char RgbImage::doubleToUnsignedChar( double x )
{
if ( x>=1.0 ) {
return (unsigned char)255;
}
else if ( x<=0.0 ) {
return (unsigned char)0;
}
else {
return (unsigned char)(x*255.0); // Rounds down
}
}
// Bitmap file format (24 bit/pixel form) BITMAPFILEHEADER
// Header (14 bytes)
// 2 bytes: "BM"
// 4 bytes: long int, file size
// 4 bytes: reserved (actually 2 bytes twice)
// 4 bytes: long int, offset to raster data
// Info header (40 bytes) BITMAPINFOHEADER
// 4 bytes: long int, size of info header (=40)
// 4 bytes: long int, bitmap width in pixels
// 4 bytes: long int, bitmap height in pixels
// 2 bytes: short int, number of planes (=1)
// 2 bytes: short int, bits per pixel
// 4 bytes: long int, type of compression (not applicable to 24 bits/pixel)
// 4 bytes: long int, image size (not used unless compression is used)
// 4 bytes: long int, x pixels per meter
// 4 bytes: long int, y pixels per meter
// 4 bytes: colors used (not applicable to 24 bit color)
// 4 bytes: colors important (not applicable to 24 bit color)
// "long int" really means "unsigned long int"
// Pixel data: 3 bytes per pixel: RGB values (in reverse order).
// Rows padded to multiples of four.
#ifndef RGBIMAGE_DONT_USE_OPENGL
bool RgbImage::LoadFromOpenglBuffer() // Load the bitmap from the current OpenGL buffer
{
int viewportData[4];
glGetIntegerv( GL_VIEWPORT, viewportData );
int& vWidth = viewportData[2];
int& vHeight = viewportData[3];
if ( ImagePtr==0 ) { // If no memory allocated
NumRows = vHeight;
NumCols = vWidth;
ImagePtr = new unsigned char[NumRows*GetNumBytesPerRow()];
if ( !ImagePtr ) {
fprintf(stderr, "Unable to allocate memory for %ld x %ld buffer.\n",
NumRows, NumCols);
Reset();
ErrorCode = MemoryError;
return false;
}
}
assert ( vWidth>=NumCols && vHeight>=NumRows );
int oldGlRowLen;
if ( vWidth>=NumCols ) {
glGetIntegerv( GL_UNPACK_ROW_LENGTH, &oldGlRowLen );
glPixelStorei( GL_UNPACK_ROW_LENGTH, NumCols );
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
// Get the frame buffer data.
glReadPixels( 0, 0, NumCols, NumRows, GL_RGB, GL_UNSIGNED_BYTE, ImagePtr);
// Restore the row length in glPixelStorei (really ought to restore alignment too).
if ( vWidth>=NumCols ) {
glPixelStorei( GL_UNPACK_ROW_LENGTH, oldGlRowLen );
}
return true;
}
#endif // RGB_IMAGE_DONT_USE_OPENGL | erich666/jgt-code | Volume_10/Number_3/Buss2005/RgbImage.cpp | C++ | mit | 10,314 |
package eu.sii.pl;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
*/
public class SiiFrame extends JFrame {
private JLabel loginLabel;
private JTextField login;
private JLabel passwordLabel;
private JPasswordField password;
private JButton okButton;
public SiiFrame(String title) throws HeadlessException {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setDimensionAndPosition();
buildContent();
}
private void setDimensionAndPosition() {
setMinimumSize(new Dimension(400, 200));
setLocationRelativeTo(null);
}
private void buildContent() {
// Create components
createComponents();
// Configure components
configureField(login);
configureField(password);
// Place components
placeComponents();
}
private void placeComponents() {
// Create panel
GridBagLayout layout = new GridBagLayout();
JPanel contentPane = new JPanel(layout);
contentPane.setBackground(new Color(196, 196, 255));
contentPane.setPreferredSize(new Dimension(300, 100));
// Add components
contentPane.add(loginLabel);
contentPane.add(login);
contentPane.add(passwordLabel);
contentPane.add(password);
contentPane.add(okButton);
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.RELATIVE;
layout.setConstraints(loginLabel, c);
layout.setConstraints(passwordLabel, c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 4.0;
layout.setConstraints(login, c);
layout.setConstraints(password, c);
layout.setConstraints(okButton, c);
getRootPane().setContentPane(contentPane);
}
private void createComponents() {
// Login label
loginLabel = new JLabel("Login");
// Login field
login = createLoginField();
// Password label
passwordLabel = new JLabel("Password");
// Password field
password = new JPasswordField();
// OK button
okButton = createOkButton();
}
private JButton createOkButton() {
JButton button = new JButton("OK");
button.setEnabled(false);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(SiiFrame.this, "Login Action", true);
dialog.setLocationRelativeTo(SiiFrame.this);
dialog.add(new Label("Hello " + login.getText()));
dialog.setMinimumSize(new Dimension(300, 200));
dialog.setVisible(true);
}
});
return button;
}
private JTextField createLoginField() {
JTextField field = new JTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
validateInput();
}
@Override
public void removeUpdate(DocumentEvent e) {
validateInput();
}
@Override
public void changedUpdate(DocumentEvent e) {
validateInput();
}
});
return field;
}
private void validateInput() {
if (login.getText().length() <= 0) {
okButton.setEnabled(false);
} else {
okButton.setEnabled(true);
}
}
private void configureField(Component field) {
Dimension size = field.getSize();
size.setSize(100, size.getHeight());
field.setMinimumSize(size);
}
}
| p-ja/javabeginner2017 | workshop/src/eu/sii/pl/SiiFrame.java | Java | mit | 4,015 |
import Vue from 'vue'
import Kanban from './components/kanban-app.vue'
import store from './store.js'
new Vue({
el: '#app',
store,
render: h => h(Kanban)
})
| drayah/xerpa-kanban | src/main.js | JavaScript | mit | 164 |
package controllers
import (
"github.com/labstack/echo"
)
// MakeControllers for main
func MakeControllers(e *echo.Echo) {
e.GET("/api", homeController)
}
| meis5/ms5.me | ms-ui/controllers/index.go | GO | mit | 159 |
#pragma once
#include <QtGlobal>
class Helper
{
public:
static void encodeByte(
char *buffer, quint16 position, char byte, quint8 positionOffset = 0
);
static char decodeByte(
char *buffer, quint16 position, quint8 positionOffset = 0
);
};
| jeremejevs/wav-spi | src/helper.hpp | C++ | mit | 288 |
package dab.common.entity.attributes;
/**
* Enumerable for the possible directions a player will be going.
* Players will either being going left, right, up, down, or even
* nowhere at all.
*
* @author Eli Irvin
*/
public enum Direction
{
LEFT, UP, RIGHT, DOWN, NONE;
}
| An-Huynh/Destroy-All-Baddies | src/main/java/dab/common/entity/attributes/Direction.java | Java | mit | 279 |
import {observable, runInAction, computed, action, reaction, autorun} from "mobx";
import LynlpApi from "../common/lynlp-api"
import _ from "lodash";
class EntityExtractStore {
@observable isFetching = false;
@observable currentItem = '图形展示';
@observable entity = {};
@action
fetchData(content) {
this.isFetching = true;
LynlpApi.entity(content).then((result)=>{
this.entity = result;
this.isFetching = false;
})
}
}
const entityExtractStore = new EntityExtractStore();
export default entityExtractStore
| wangpengzsx/lynlp1 | src/mobx/entity-extract-store.js | JavaScript | mit | 533 |
using CoreGlue.Middleware.CQRS.Settings;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
namespace CoreGlue.CQRS.Query
{
public class QueryableStoreFactory : IQueryableStoreFactory
{
private IDictionary<string, IQueryableStore> QueryStores { get; set; } = new Dictionary<string, IQueryableStore>();
public QueryableStoreFactory(IOptions<QueryOptions> options)
{
ParameterValidation.IsNotNull(options, nameof(options));
QueryOptions queryStores = options.Value;
foreach (ConnectionOptions connection in queryStores.TableStorage)
{
this.QueryStores.Add(connection.Name, new TableQueryableStore(connection));
}
}
public IQueryableStore GetStore(string name)
{
return this.QueryStores[name];
}
}
}
| CoreGlue/coreglue-web | src/CoreGlue/Middleware/CQRS/Query/QueryableStoreFactory.cs | C# | mit | 880 |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanutils
~~~~~~~~~
Provides methods for interacting with a CKAN instance
Examples:
literal blocks::
python example_google.py
Attributes:
CKAN_KEYS (List[str]): available CKAN keyword arguments.
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
import requests
import ckanapi
import itertools as it
from os import environ, path as p
from datetime import datetime as dt
from operator import itemgetter
from pprint import pprint
from ckanapi import NotFound, NotAuthorized, ValidationError
from tabutils import process as pr, io, fntools as ft, convert as cv
__version__ = '0.14.9'
__title__ = 'ckanutils'
__author__ = 'Reuben Cummings'
__description__ = 'Miscellaneous CKAN utility library'
__email__ = 'reubano@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Reuben Cummings'
CKAN_KEYS = ['hash_table', 'remote', 'api_key', 'ua', 'force', 'quiet']
API_KEY_ENV = 'CKAN_API_KEY'
REMOTE_ENV = 'CKAN_REMOTE_URL'
UA_ENV = 'CKAN_USER_AGENT'
DEF_USER_AGENT = 'ckanutils/%s' % __version__
DEF_HASH_PACK = 'hash-table'
DEF_HASH_RES = 'hash-table.csv'
CHUNKSIZE_ROWS = 10 ** 3
CHUNKSIZE_BYTES = 2 ** 20
ENCODING = 'utf-8'
class CKAN(object):
"""Interacts with a CKAN instance.
Attributes:
force (bool): Force.
verbose (bool): Print debug statements.
quiet (bool): Suppress debug statements.
address (str): CKAN url.
hash_table (str): The hash table package id.
keys (List[str]):
"""
def __init__(self, **kwargs):
"""Initialization method.
Args:
**kwargs: Keyword arguments.
Kwargs:
hash_table (str): The hash table package id.
remote (str): The remote ckan url.
api_key (str): The ckan api key.
ua (str): The user agent.
force (bool): Force (default: True).
quiet (bool): Suppress debug statements (default: False).
Returns:
New instance of :class:`CKAN`
Examples:
>>> CKAN() #doctest: +ELLIPSIS
<ckanutils.CKAN object at 0x...>
"""
default_ua = environ.get(UA_ENV, DEF_USER_AGENT)
def_remote = environ.get(REMOTE_ENV)
def_api_key = environ.get(API_KEY_ENV)
remote = kwargs.get('remote', def_remote)
self.api_key = kwargs.get('api_key', def_api_key)
self.force = kwargs.get('force', True)
self.quiet = kwargs.get('quiet')
self.user_agent = kwargs.get('ua', default_ua)
self.verbose = not self.quiet
self.hash_table = kwargs.get('hash_table', DEF_HASH_PACK)
ckan_kwargs = {'apikey': self.api_key, 'user_agent': self.user_agent}
attr = 'RemoteCKAN' if remote else 'LocalCKAN'
ckan = getattr(ckanapi, attr)(remote, **ckan_kwargs)
self.address = ckan.address
self.package_show = ckan.action.package_show
try:
self.hash_table_pack = self.package_show(id=self.hash_table)
except NotFound:
self.hash_table_pack = None
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
self.hash_table_pack = None
else:
raise err
try:
self.hash_table_id = self.hash_table_pack['resources'][0]['id']
except (IndexError, TypeError):
self.hash_table_id = None
# shortcuts
self.datastore_search = ckan.action.datastore_search
self.datastore_create = ckan.action.datastore_create
self.datastore_delete = ckan.action.datastore_delete
self.datastore_upsert = ckan.action.datastore_upsert
self.datastore_search = ckan.action.datastore_search
self.resource_show = ckan.action.resource_show
self.resource_create = ckan.action.resource_create
self.package_create = ckan.action.package_create
self.package_update = ckan.action.package_update
self.package_privatize = ckan.action.bulk_update_private
self.revision_show = ckan.action.revision_show
self.organization_list = ckan.action.organization_list_for_user
self.organization_show = ckan.action.organization_show
self.license_list = ckan.action.license_list
self.group_list = ckan.action.group_list
self.user = ckan.action.get_site_user()
def create_table(self, resource_id, fields, **kwargs):
"""Creates a datastore table for an existing filestore resource.
Args:
resource_id (str): The filestore resource id.
fields (List[dict]): fields/columns and their extra metadata.
**kwargs: Keyword arguments that are passed to datastore_create.
Kwargs:
force (bool): Create resource even if read-only.
aliases (List[str]): name(s) for read only alias(es) of the
resource.
primary_key (List[str]): field(s) that represent a unique key.
indexes (List[str]): index(es) on table.
Returns:
dict: The newly created data object.
Raises:
ValidationError: If unable to validate user on ckan site.
NotFound: If unable to find resource.
Examples:
>>> CKAN(quiet=True).create_table('rid', fields=[{'id': 'field', \
'type': 'text'}])
Traceback (most recent call last):
NotFound: Resource `rid` was not found in filestore.
"""
kwargs.setdefault('force', self.force)
kwargs['resource_id'] = resource_id
kwargs['fields'] = fields
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
if self.verbose:
print('Creating table `%s` in datastore...' % resource_id)
try:
return self.datastore_create(**kwargs)
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound(err_msg)
else:
raise
def delete_table(self, resource_id, **kwargs):
"""Deletes a datastore table.
Args:
resource_id (str): The datastore resource id.
**kwargs: Keyword arguments that are passed to datastore_create.
Kwargs:
force (bool): Delete resource even if read-only.
filters (dict): Filters to apply before deleting, e.g.,
{"name": "fred"}. If missing delete whole table and all
dependent views.
Returns:
dict: Original filters sent if table was found, `None` otherwise.
Raises:
ValidationError: If unable to validate user on ckan site.
Examples:
>>> CKAN(quiet=True).delete_table('rid')
Can't delete. Table `rid` was not found in datastore.
"""
kwargs.setdefault('force', self.force)
kwargs['resource_id'] = resource_id
init_msg = "Can't delete. Table `%s`" % resource_id
err_msg = '%s was not found in datastore.' % init_msg
read_msg = '%s is read only.' % init_msg
if self.verbose:
print('Deleting table `%s` from datastore...' % resource_id)
try:
result = self.datastore_delete(**kwargs)
except NotFound:
print(err_msg)
result = None
except ValidationError as err:
if 'read-only' in err.error_dict:
print(read_msg)
print("Set 'force' to True and try again.")
result = None
elif err.error_dict.get('resource_id') == ['Not found: Resource']:
print(err_msg)
result = None
else:
raise err
return result
def insert_records(self, resource_id, records, **kwargs):
"""Inserts records into a datastore table.
Args:
resource_id (str): The datastore resource id.
records (List[dict]): The records to insert.
**kwargs: Keyword arguments that are passed to datastore_create.
Kwargs:
method (str): Insert method. One of ['update, 'insert', 'upsert']
(default: 'insert').
force (bool): Create resource even if read-only.
start (int): Row number to start from (zero indexed).
stop (int): Row number to stop at (zero indexed).
chunksize (int): Number of rows to write at a time.
Returns:
int: Number of records inserted.
Raises:
NotFound: If unable to find the resource.
Examples:
>>> CKAN(quiet=True).insert_records('rid', [{'field': 'value'}])
Traceback (most recent call last):
NotFound: Resource `rid` was not found in filestore.
"""
recoded = pr.json_recode(records)
chunksize = kwargs.pop('chunksize', 0)
start = kwargs.pop('start', 0)
stop = kwargs.pop('stop', None)
kwargs.setdefault('force', self.force)
kwargs.setdefault('method', 'insert')
kwargs['resource_id'] = resource_id
count = 1
for chunk in ft.chunk(recoded, chunksize, start=start, stop=stop):
length = len(chunk)
if self.verbose:
print(
'Adding records %i - %i to resource %s...' % (
count, count + length - 1, resource_id))
kwargs['records'] = chunk
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
try:
self.datastore_upsert(**kwargs)
except requests.exceptions.ConnectionError as err:
if 'Broken pipe' in err.message[1]:
print('Chunksize too large. Try using a smaller chunksize.')
return 0
else:
raise err
except NotFound:
# Keep exception message consistent with the others
raise NotFound(err_msg)
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound(err_msg)
else:
raise err
count += length
return count
def get_hash(self, resource_id):
"""Gets the hash of a datastore table.
Args:
resource_id (str): The datastore resource id.
Returns:
str: The datastore resource hash.
Raises:
NotFound: If `hash_table_id` isn't set or not in datastore.
NotAuthorized: If unable to authorize ckan user.
Examples:
>>> CKAN(hash_table='hash_jhb34rtj34t').get_hash('rid')
Traceback (most recent call last):
NotFound: {u'item': u'package', u'message': u'Package \
`hash_jhb34rtj34t` was not found!'}
"""
if not self.hash_table_pack:
message = 'Package `%s` was not found!' % self.hash_table
raise NotFound({'message': message, 'item': 'package'})
if not self.hash_table_id:
message = 'No resources found in package `%s`!' % self.hash_table
raise NotFound({'message': message, 'item': 'resource'})
kwargs = {
'resource_id': self.hash_table_id,
'filters': {'datastore_id': resource_id},
'fields': 'hash',
'limit': 1
}
err_msg = 'Resource `%s` was not found' % resource_id
alt_msg = 'Hash table `%s` was not found' % self.hash_table_id
try:
result = self.datastore_search(**kwargs)
resource_hash = result['records'][0]['hash']
except NotFound:
message = '%s in datastore!' % alt_msg
raise NotFound({'message': message, 'item': 'datastore'})
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound('%s in filestore.' % err_msg)
else:
raise err
except IndexError:
print('%s in hash table.' % err_msg)
resource_hash = None
if self.verbose:
print('Resource `%s` hash is `%s`.' % (resource_id, resource_hash))
return resource_hash
def fetch_resource(self, resource_id, user_agent=None, stream=True):
"""Fetches a single resource from filestore.
Args:
resource_id (str): The filestore resource id.
Kwargs:
user_agent (str): The user agent.
stream (bool): Stream content (default: True).
Returns:
obj: requests.Response object.
Raises:
NotFound: If unable to find the resource.
NotAuthorized: If access to fetch resource is denied.
Examples:
>>> CKAN(quiet=True).fetch_resource('rid')
Traceback (most recent call last):
NotFound: Resource `rid` was not found in filestore.
"""
user_agent = user_agent or self.user_agent
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
try:
resource = self.resource_show(id=resource_id)
except NotFound:
raise NotFound(err_msg)
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound(err_msg)
else:
raise err
url = resource.get('perma_link') or resource.get('url')
if self.verbose:
print('Downloading url %s...' % url)
headers = {'User-Agent': user_agent}
r = requests.get(url, stream=stream, headers=headers)
err_msg = 'Access to fetch resource %s was denied.' % resource_id
if any('403' in h.headers.get('x-ckan-error', '') for h in r.history):
raise NotAuthorized(err_msg)
elif r.status_code == 401:
raise NotAuthorized(err_msg)
else:
return r
def get_filestore_update_func(self, resource, **kwargs):
"""Returns the function to create or update a single resource on
filestore. To create a resource, you must supply either `url`,
`filepath`, or `fileobj`.
Args:
resource (dict): The resource passed to resource_create.
**kwargs: Keyword arguments that are passed to resource_create.
Kwargs:
url (str): New file url (for file link, requires `format`).
format (str): New file format (for file link, requires `url`).
fileobj (obj): New file like object (for file upload).
filepath (str): New file path (for file upload).
post (bool): Post data using requests instead of ckanapi.
name (str): The resource name.
description (str): The resource description.
hash (str): The resource hash.
Returns:
tuple: (func, args, data)
where func is `requests.post` if `post` option is specified,
`self.resource_create` otherwise. `args` and `data` should be
passed as *args and **kwargs respectively.
See also:
ckanutils._update_filestore
Examples:
>>> ckan = CKAN(quiet=True)
>>> resource = {
... 'name': 'name', 'package_id': 'pid', 'resource_id': 'rid',
... 'description': 'description', 'hash': 'hash'}
>>> kwargs = {'url': 'http://example.com/file', 'format': 'csv'}
>>> res = ckan.get_filestore_update_func(resource, **kwargs)
>>> func, args, kwargs = res
>>> func(*args, **kwargs)
Traceback (most recent call last):
NotFound: Not found
"""
post = kwargs.pop('post', None)
filepath = kwargs.pop('filepath', None)
fileobj = kwargs.pop('fileobj', None)
f = open(filepath, 'rb') if filepath else fileobj
resource.update(kwargs)
if post:
args = ['%s/api/action/resource_create' % self.address]
hdrs = {
'X-CKAN-API-Key': self.api_key, 'User-Agent': self.user_agent}
data = {'data': resource, 'headers': hdrs}
data.update({'files': {'upload': f}}) if f else None
func = requests.post
else:
args = []
resource.update({'upload': f}) if f else None
data = {
k: v for k, v in resource.items() if not isinstance(v, dict)}
func = self.resource_create
return (func, args, data)
def _update_filestore(self, func, *args, **kwargs):
"""Helps create or update a single resource on filestore.
To create a resource, you must supply either `url`, `filepath`, or
`fileobj`.
Args:
func (func): The resource passed to resource_create.
*args: Postional arguments that are passed to `func`
**kwargs: Keyword arguments that are passed to `func`.
Kwargs:
url (str): New file url (for file link).
fileobj (obj): New file like object (for file upload).
filepath (str): New file path (for file upload).
name (str): The resource name.
description (str): The resource description.
hash (str): The resource hash.
Returns:
obj: requests.Response object if `post` option is specified,
ckan resource object otherwise.
See also:
ckanutils.get_filestore_update_func
Examples:
>>> ckan = CKAN(quiet=True)
>>> url = 'http://example.com/file'
>>> resource = {'package_id': 'pid'}
>>> kwargs = {'name': 'name', 'url': url, 'format': 'csv'}
>>> res = ckan.get_filestore_update_func(resource, **kwargs)
>>> ckan._update_filestore(res[0], *res[1], **res[2])
Package `pid` was not found.
>>> resource['resource_id'] = 'rid'
>>> res = ckan.get_filestore_update_func(resource, **kwargs)
>>> ckan._update_filestore(res[0], *res[1], **res[2])
Resource `rid` was not found in filestore.
"""
data = kwargs.get('data', {})
files = kwargs.get('files', {})
resource_id = kwargs.get('resource_id', data.get('resource_id'))
package_id = kwargs.get('package_id', data.get('package_id'))
f = kwargs.get('upload', files.get('upload'))
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
try:
r = func(*args, **kwargs) or {'id': None}
except NotFound:
pck_msg = 'Package `%s` was not found.' % package_id
print(err_msg if resource_id else pck_msg)
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
print(err_msg)
r = None
else:
raise err
except requests.exceptions.ConnectionError as err:
if 'Broken pipe' in err.message[1]:
print('File size too large. Try uploading a smaller file.')
r = None
else:
raise err
else:
return r
finally:
f.close() if f else None
def create_resource(self, package_id, **kwargs):
"""Creates a single resource on filestore. You must supply either
`url`, `filepath`, or `fileobj`.
Args:
package_id (str): The filestore package id.
**kwargs: Keyword arguments that are passed to resource_create.
Kwargs:
url (str): New file url (for file link).
filepath (str): New file path (for file upload).
fileobj (obj): New file like object (for file upload).
post (bool): Post data using requests instead of ckanapi.
name (str): The resource name (defaults to the filename).
description (str): The resource description.
hash (str): The resource hash.
Returns:
obj: requests.Response object if `post` option is specified,
ckan resource object otherwise.
Raises:
TypeError: If neither `url`, `filepath`, nor `fileobj` are supplied.
Examples:
>>> ckan = CKAN(quiet=True)
>>> ckan.create_resource('pid')
Traceback (most recent call last):
TypeError: You must specify either a `url`, `filepath`, or `fileobj`
>>> ckan.create_resource('pid', url='http://example.com/file')
Package `pid` was not found.
"""
if not any(map(kwargs.get, ['url', 'filepath', 'fileobj'])):
raise TypeError(
'You must specify either a `url`, `filepath`, or `fileobj`')
path = filter(None, map(kwargs.get, ['url', 'filepath', 'fileobj']))[0]
try:
if 'docs.google.com' in path:
def_name = path.split('gid=')[1].split('&')[0]
else:
def_name = p.basename(path)
except AttributeError:
def_name = None
file_format = 'csv'
else:
# copy/pasted from utils... fix later
if 'format=' in path:
file_format = path.split('format=')[1].split('&')[0]
else:
file_format = p.splitext(path)[1].lstrip('.')
kwargs.setdefault('name', def_name)
# Will get `ckan.logic.ValidationError` if url isn't set
kwargs.setdefault('url', 'http://example.com')
kwargs['format'] = file_format
resource = {'package_id': package_id}
if self.verbose:
print('Creating new resource in package %s...' % package_id)
func, args, data = self.get_filestore_update_func(resource, **kwargs)
return self._update_filestore(func, *args, **data)
def update_filestore(self, resource_id, **kwargs):
"""Updates a single resource on filestore.
Args:
resource_id (str): The filestore resource id.
**kwargs: Keyword arguments that are passed to resource_create.
Kwargs:
url (str): New file url (for file link).
filepath (str): New file path (for file upload).
fileobj (obj): New file like object (for file upload).
post (bool): Post data using requests instead of ckanapi.
name (str): The resource name.
description (str): The resource description.
hash (str): The resource hash.
Returns:
obj: requests.Response object if `post` option is specified,
ckan resource object otherwise.
Examples:
>>> CKAN(quiet=True).update_filestore('rid')
Resource `rid` was not found in filestore.
"""
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
try:
resource = self.resource_show(id=resource_id)
except NotFound:
print(err_msg)
return None
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound(err_msg)
else:
raise err
else:
resource['package_id'] = self.get_package_id(resource_id)
if self.verbose:
print('Updating resource %s...' % resource_id)
f, args, data = self.get_filestore_update_func(resource, **kwargs)
return self._update_filestore(f, *args, **data)
def update_datastore(self, resource_id, filepath, **kwargs):
verbose = not kwargs.get('quiet')
chunk_rows = kwargs.get('chunksize_rows')
primary_key = kwargs.get('primary_key')
content_type = kwargs.get('content_type')
type_cast = kwargs.get('type_cast')
method = 'upsert' if primary_key else 'insert'
keys = ['aliases', 'primary_key', 'indexes']
try:
extension = p.splitext(filepath)[1].split('.')[1]
except (IndexError, AttributeError):
# no file extension given, e.g., a tempfile
extension = cv.ctype2ext(content_type)
try:
reader = io.get_reader(extension)
except TypeError:
print('Error: plugin for extension `%s` not found!' % extension)
return False
else:
records = reader(filepath, **kwargs)
first = records.next()
keys = first.keys()
records = it.chain([first], records)
if type_cast:
records, results = pr.detect_types(records)
types = results['types']
casted_records = pr.type_cast(records, types)
else:
types = [{'id': key, 'type': 'text'} for key in keys]
casted_records = records
if verbose:
print('Parsed types:')
pprint(types)
create_kwargs = {k: v for k, v in kwargs.items() if k in keys}
if not primary_key:
self.delete_table(resource_id)
insert_kwargs = {'chunksize': chunk_rows, 'method': method}
self.create_table(resource_id, types, **create_kwargs)
args = [resource_id, casted_records]
return self.insert_records(*args, **insert_kwargs)
def find_ids(self, packages, **kwargs):
default = {'rid': '', 'pname': ''}
kwargs.update({'method': self.query, 'default': default})
return pr.find(packages, **kwargs)
def get_package_id(self, resource_id):
"""Gets the package id of a single resource on filestore.
Args:
resource_id (str): The filestore resource id.
Returns:
str: The package id.
Examples:
>>> CKAN(quiet=True).get_package_id('rid')
Resource `rid` was not found in filestore.
"""
err_msg = 'Resource `%s` was not found in filestore.' % resource_id
try:
resource = self.resource_show(id=resource_id)
except NotFound:
print(err_msg)
return None
except ValidationError as err:
if err.error_dict.get('resource_id') == ['Not found: Resource']:
raise NotFound(err_msg)
else:
raise err
else:
revision = self.revision_show(id=resource['revision_id'])
return revision['packages'][0]
def create_hash_table(self, verbose=False):
kwargs = {
'resource_id': self.hash_table_id,
'fields': [
{'id': 'datastore_id', 'type': 'text'},
{'id': 'hash', 'type': 'text'}],
'primary_key': 'datastore_id'
}
if verbose:
print('Creating hash table...')
self.create_table(**kwargs)
def update_hash_table(self, resource_id, resource_hash, verbose=False):
records = [{'datastore_id': resource_id, 'hash': resource_hash}]
if verbose:
print('Updating hash table...')
self.insert_records(self.hash_table_id, records, method='upsert')
def get_update_date(self, item):
timestamps = {
'revision_timestamp': 'revision',
'last_modified': 'resource',
'metadata_modified': 'package'
}
for key, value in timestamps.items():
if key in item:
timestamp = item[key]
item_type = value
break
else:
keys = timestamps.keys()
msg = 'None of the following keys found in item: %s' % keys
raise TypeError(msg)
if not timestamp and item_type == 'resource':
# print('Resource timestamp is empty. Querying revision.')
timestamp = self.revision_show(id=item['revision_id'])['timestamp']
return dt.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f')
def filter(self, items, tagged=None, named=None, updated=None):
for i in items:
if i['state'] != 'active':
continue
if updated and updated(self.get_update_date(i)):
yield i
continue
if named and named.lower() in i['name'].lower():
yield i
continue
tags = it.imap(itemgetter('name'), i['tags'])
is_tagged = tagged and 'tags' in i
if is_tagged and any(it.ifilter(lambda t: t == tagged, tags)):
yield i
continue
if not (named or tagged or updated):
yield i
def query(self, packages, **kwargs):
pkwargs = {
'named': kwargs.get('pnamed'),
'tagged': kwargs.get('ptagged')}
rkwargs = {
'named': kwargs.get('rnamed'),
'tagged': kwargs.get('rtagged')}
skwargs = {'key': self.get_update_date, 'reverse': True}
filtered_packages = self.filter(packages, **pkwargs)
for pack in sorted(filtered_packages, **skwargs):
package = self.package_show(id=pack['name'])
resources = self.filter(package['resources'], **rkwargs)
for resource in sorted(resources, **skwargs):
yield {'rid': resource['id'], 'pname': package['name']}
| reubano/ckanutils | ckanutils.py | Python | mit | 29,704 |
module Csvify
VERSION = "0.1.0"
end
| khpotenciano/csvify | lib/csvify/version.rb | Ruby | mit | 38 |
#!/usr/bin/env python
# coding: utf-8
from .interactiveapp import InteractiveApplication, ENCODING
class InteractiveLoopApplication(InteractiveApplication):
def __init__(self, name, desc, version,
padding, margin, suffix, encoding=ENCODING):
super(InteractiveLoopApplication, self).__init__(
name, desc, version, padding, margin, suffix, encoding)
# loop status
self.STATUS_EXIT = 0
self.STATUS_CONTINUE = 1
def loop(self, func):
def mainloop():
loop_flag = self.STATUS_CONTINUE
while loop_flag == self.STATUS_CONTINUE:
try:
loop_flag = func()
except KeyboardInterrupt:
self.write_error("Terminated.")
self.exit(0)
self.exit(0)
return mainloop
| alice1017/coadlib | coadlib/loopapp.py | Python | mit | 871 |
import { Inject, Injectable } from '@angular/core';
import { CanActivate, Router } from "@angular/router";
import { AuthService } from "../services/auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _auth: AuthService,
private _router: Router) { }
canActivate(): boolean {
if (!this._auth.isLoggedIn()) {
this._router.navigate(['/login']);
return false;
}
return true;
}
} | yasenm/a4-netcore | A4CoreBlog/A4CoreBlog.Web/ClientApp/app/shared/guards/auth.guard.ts | TypeScript | mit | 501 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'pages';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['materials/(:num)'] = 'materials/show/$1';
$route['sections/show'] = 'pages/show/index';
$route['materials/show'] = 'pages/show/index';
$route['pages/show'] = "pages/show/index";
$route['pages/contact'] = 'pages/show/contact';
$route['sections/articles'] = 'sections/show/articles';
$route['sections/html'] = 'sections/show/html';
$route['sections/php'] = 'sections/show/php';
$route['sections/css'] = 'sections/show/css';
| AntonGud/CI | application/config/routes.php | PHP | mit | 2,425 |
<?php
namespace Artesaos\Defender\Testing;
use Illuminate\View\View;
/**
* Class JavascriptTest.
*/
class JavascriptTest extends AbstractTestCase
{
/**
* Array of service providers.
* @var array
*/
protected $providers = ['Artesaos\Defender\Providers\DefenderServiceProvider'];
/**
* New defender instance.
* @var Defender
*/
protected $defender;
/**
* {@inheritdoc}
*/
public function setUp()
{
parent::setUp();
$this->migrate([
$this->stubsPath('database/migrations'),
$this->resourcePath('migrations'),
]);
$this->seed([
'UserTableSeeder',
]);
$this->app->singleton('Illuminate\Contracts\Debug\ExceptionHandler', 'Orchestra\Testbench\Exceptions\Handler');
$this->defender = new Defender($this->app, $this->app['defender.permission']);
$this->defender->setUser(User::first());
}
/**
* Asserting rended blade view.
*/
public function testShouldRenderJavascript()
{
$javascript = $this->defender->javascript();
/* @var View $script */
$view = $javascript->render();
$viewContent = $view->render();
$data = $view->getData();
$this->assertArrayHasKey('permissions', $data);
$this->assertTrue(is_string($data['permissions']));
/*
* Not empty string, it could be a empty json array string
*/
$this->assertNotEmpty($data['permissions']);
$this->assertJson($data['permissions']);
$this->assertStringMatchesFormatFile(
$this->stubsPath('views/javascript.blade.output.txt'),
$viewContent
);
}
/**
* Asserting created permission and rendered properly.
*/
public function testShouldRenderUserPermissions()
{
$user = $this->defender->getUser();
$permission = $this->defender->createPermission('js.permission');
$user->attachPermission($permission);
/** @var View $view */
$view = $this->defender->javascript()->render();
$data = $view->getData();
$this->assertArrayHasKey('permissions', $data);
$this->assertFalse('[]' == $data['permissions']);
$this->assertStringMatchesFormatFile(
$this->stubsPath('views/javascript-with-permission.blade.output.txt'),
$view->render()
);
}
}
| humantech/defender | tests/Defender/JavascriptTest.php | PHP | mit | 2,460 |
'use strict';
const async = require('async');
const getApp = require('../utils/utils.js').getApp;
module.exports = function(Worker) {
//Worker.validatesPresenceOf('title');
Worker.upsertItem = (data, cb) => {
let res = {};
getApp(Worker)
.then((app) => {
if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'});
if (!!!data.cargos || data.cargos.length === 0
) cb({errCode: 'ERR_WORKER_NO_CARGO'});
console.log(data);
return (!!!data.person.id ?
app.models.person.create(data.person) :
Promise.resolve(data.person)
)
.then((result) => {
res.person = result;
return app.models.worker.upsert({
personId: res.person.id
});
})
.then(results => {
res.worker = results;
res.cargoMapping = [];
return new Promise((resolve, reject) => async.each(data.cargos,
(cargoId, cbInner) => app.models.cargoMapping.create({
cargoId: cargoId,
workerId: res.worker.id
})
.then(r => cbInner(null, res.cargoMapping.push(r)))
.catch(err => async.each(res.cargoMapping,
(itemInner, cbInner2) => cbInner2(null, itemInner.destroy()),
err => cbInner({
errCode: 'ERR_WORKER_FAIL_CARGOS',
message: 'problem to save cargo in worker'
})
)),
err => !!err ? reject(err) : resolve(res)
));
})
.then(res => {
cb(null, res);
})
.catch(err => {
if (!!res.person) res.person.destroy();
if (!!res.worker) res.worker.destroy();
cb({errCode: 'ERR_WORKER_NO_SAVE'});
});
});
};
Worker.remoteMethod('upsertItem', {
description: 'upsert client ',
http: {verb: 'post'},
accepts: {
arg: 'data',
type: 'object',
description: 'data from form to upsert client',
http: {source: 'body'},
required: true
},
returns: {
arg: 'res',
type: 'object',
root: true
}
});
};
| skeiter9/traru | app/common/models/worker.js | JavaScript | mit | 2,093 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("pract-1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("pract-1")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d7f27a2-b9f4-457c-9ed3-4b248b1d57a3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| melnikf/testrepo | melnik-oop/pract-1/Properties/AssemblyInfo.cs | C# | mit | 1,390 |
import { combineReducers } from 'redux'
import auth from './auth'
import watt from './watt'
import locations from './locations'
export default combineReducers({
auth,
watt,
locations
})
| tombatossals/energy | src/reducers/index.js | JavaScript | mit | 193 |
'use strict';
require('./components/dropdown');
require('./components/active-link');
| ravisuhag/jolly | assets/scripts/index.js | JavaScript | mit | 88 |
# coding: utf-8
#
# bmp.rb -- a toolkit for bitmap(BMP) image
#
# Copyright (c) 2014 Yoichi Yokogawa
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#
# ※ BMPファイルのファイルフォーマットについては、
# http://www.kk.iij4u.or.jp/~kondo/bmp/ を参考にしました
class BitMap
def initialize(width, height, dpi = 96)
@width = width
@height = height
@line_size = width * 3 + (4 - (width * 3) % 4) % 4
@buf_size = @line_size * height
@buf = ("\000" * @buf_size).encode('BINARY')
@bit_count = 24
@compression = 0 # 圧縮無し
@size_image = 0
@x_pix_per_meter = (39.375 * dpi).round
@y_pix_per_meter = (39.375 * dpi).round
@clr_used = 0
@cir_important = 0
end
def clear(r = 255, g = 255, b = 255)
line = b.chr * @line_size
@width.times do |x|
line[x * 3 + 1] = g.chr
line[x * 3 + 2] = r.chr
end
@buf = line * @height
end
attr_writer :buf
attr_reader :width, :height
# BMPファイルを出力する
def write(filename)
file_size = 14 + 40 + @buf_size
data_offset = 14 + 40
open(filename, "wb") do |f|
f.print 'BM'
f.print [file_size, 0, data_offset].pack("l*")
f.print [40, @width, @height].pack("l*")
f.print [1, @bit_count].pack("S*")
f.print [@compression, @size_image,
@x_pix_per_meter, @y_pix_per_meter,
@clr_used, @cir_important].pack("l*")
f.print @buf
end
end
# BMPファイルを読み込む
def BitMap.read(filename)
buf = nil
open(filename, "rb") do |f|
buf = f.read
end
if buf[0] != ?B or buf[1] != ?M
raise '[Error] read: Invalid Header'
end
real_buf_size = buf.size
buf_size = (buf[2, 4].unpack("l*"))[0]
if buf_size > real_buf_size
raise '[Error] read: Invalid Buffer Size'
end
data_offset = (buf[10, 4].unpack("l*"))[0]
if data_offset != 54
raise '[Error] read: Invalid Data Offset'
end
width = (buf[18, 4].unpack("l*"))[0]
height = (buf[22, 4].unpack("l*"))[0]
bit_count = (buf[28, 2].unpack("s*"))[0]
if bit_count != 24
raise '[Error] read: Unsupported Color Depth'
end
compression = (buf[30, 4].unpack("l*"))[0]
if compression != 0
raise '[Error] read: Compression Not Supported'
end
pix_per_meter = (buf[38, 4].unpack("l*"))[0]
dpi = pix_per_meter / 39.375
image_buf = buf[54, buf_size]
image = BitMap.new(width, height, dpi)
image.buf = image_buf
return image
end
# (x1, y1) - (x2, y2)の部分画像を取り出す
def clip(x1, y1, x2, y2)
return if x1 > x2
return if y1 > y2
return if x2 < 0
return if y2 < 0
return if x1 >= @width
return if y1 >= @height
x1 = 0 if x1 < 0
y1 = 0 if y1 < 0
x2 = @width - 1 if x2 >= @width
y2 = @height - 1 if y2 >= @height
clip_width = x2 - x1 + 1
clip_height = y2 - y1 + 1
clip_image = BitMap.new(clip_width, clip_height, self.get_dpi)
for y in 0 .. (clip_height - 1)
for x in 0 .. (clip_width - 1)
color = self.pget(x1 + x, y1 + y)
clip_image.pset(x, y, color[0], color[1], color[2])
end
end
return clip_image
end
# 1ピクセル描画
# x, y, r, g, b は整数であることを期待している
def pset(x, y, r, g, b)
return if x < 0 or @width <= x
return if y < 0 or @height <= y
r = 0 if r < 0
g = 0 if g < 0
b = 0 if b < 0
r = 255 if r > 255
g = 255 if g > 255
b = 255 if b > 255
@buf[(@height - 1 - y) * @line_size + x * 3 ] = b.chr
@buf[(@height - 1 - y) * @line_size + x * 3 + 1] = g.chr
@buf[(@height - 1 - y) * @line_size + x * 3 + 2] = r.chr
end
# 1ピクセル読み取り
# x, yは整数であることを期待している
# 戻り値は[r, g, b]な配列
def pget(x, y)
x = 0 if x < 0
x = @width - 1 if x >= @width
y = 0 if y < 0
y = @height - 1 if y >= @height
addr = (@height - 1 - y) * @line_size + x * 3
b = @buf[addr ].ord
g = @buf[addr + 1].ord
r = @buf[addr + 2].ord
return [r, g, b]
end
def get_dpi()
return (@x_pix_per_meter / 39.375).round
end
def set_dpi(dpi)
@x_pix_per_meter = (39.375 * dpi).round
@y_pix_per_meter = @x_pix_per_meter
end
# BMP画像の貼り付け
# x0, y0 は、貼り付ける始点(左上)の座標
def paste(image, x0 = 0, y0 = 0)
return if image == nil
image.height.times do |from_y|
y = y0 + from_y
next if y < 0 or @height <= y
image.width.times do |from_x|
x = x0 + from_x
next if x < 0 or @width <= x
color = image.pget(from_x, from_y)
self.pset(x, y, color[0], color[1], color[2])
end
end
end
end
| yoyoichi/bmp-ruby | bmp.rb | Ruby | mit | 4,875 |
namespace ExpectedObjects
{
public class UnexpectedElement : IUnexpectedElement
{
public UnexpectedElement(object element)
{
Element = element;
}
public object Element { get; set; }
}
} | derekgreer/expectedObjects | src/ExpectedObjects/UnexpectedElement.cs | C# | mit | 256 |
/* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.use(require('dirty-chai'))
const expect = chai.expect
const parallel = require('async/parallel')
const createNode = require('./utils/create-node.js')
const echo = require('./utils/echo')
describe('ping', () => {
let nodeA
let nodeB
before((done) => {
parallel([
(cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => {
expect(err).to.not.exist()
nodeA = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => {
expect(err).to.not.exist()
nodeB = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
], done)
})
after((done) => {
parallel([
(cb) => nodeA.stop(cb),
(cb) => nodeB.stop(cb)
], done)
})
it('should be able to ping another node', (done) => {
nodeA.ping(nodeB.peerInfo, (err, ping) => {
expect(err).to.not.exist()
ping.once('ping', (time) => {
expect(time).to.exist()
ping.stop()
done()
})
ping.start()
})
})
it('should be not be able to ping when stopped', (done) => {
nodeA.stop(() => {
nodeA.ping(nodeB.peerInfo, (err) => {
expect(err).to.exist()
done()
})
})
})
})
| diasdavid/js-libp2p | test/ping.node.js | JavaScript | mit | 1,347 |
<?php
/**
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/skeleton
*/
declare(strict_types=1);
namespace Application\Pages;
/**
* Table of Pages
*
* @package Application\Pages
*
* @method static ?Row findRow($primaryKey)
* @see \Bluz\Db\Table::findRow()
* @method static ?Row findRowWhere($whereList)
* @see \Bluz\Db\Table::findRowWhere()
*/
class Table extends \Bluz\Db\Table
{
/**
* Table
*
* @var string
*/
protected $name = 'pages';
/**
* Primary key(s)
*
* @var array
*/
protected $primary = ['id'];
/**
* Get page by Alias
*
* @param $alias
*
* @return Row
* @throws \Bluz\Db\Exception\DbException
*/
public function getByAlias($alias): ?Row
{
return static::findRowWhere(['alias' => $alias]);
}
/**
* Init table relations
*
* @return void
*/
public function init(): void
{
$this->linkTo('userId', 'Users', 'id');
}
}
| AntonShevchuk/bluz-skeleton | application/models/Pages/Table.php | PHP | mit | 1,035 |
package edu.utah.nanofab.coralapiserver.core;
public class EnableRequest {
private String item;
private String member;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
private String project;
}
| ufabdyop/coralapiserver | src/main/java/edu/utah/nanofab/coralapiserver/core/EnableRequest.java | Java | mit | 518 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace WebApiTemplate.Api
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
DatabaseConfig.Initialize();
AutoMapperConfig.RegisterMappings(Assembly.Load("WebApiTemplate.Api"));
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
| pepinho24/Common | WebApiTemplate/Server/WebApiTemplate.Api/Global.asax.cs | C# | mit | 579 |
'use strict';
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
$scope.create = function() {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
this.title = '';
this.content = '';
};
$scope.remove = function(article) {
if (article) {
article.$remove();
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
} else {
$scope.article.$remove(function() {
$location.path('articles');
});
}
};
$scope.update = function() {
var article = $scope.article;
article.$update(function() {
$location.path('articles/' + article._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.articles = Articles.query();
};
$scope.findOne = function () {
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
};
}
]); | rodrigowirth/IELTS | public/modules/articles/controllers/articles.client.controller.js | JavaScript | mit | 1,352 |
using System;
using CoreGraphics;
using UIKit;
using Foundation;
namespace MonoTouch.Dialog
{
public class ActivityElement : Element {
public ActivityElement():base(""){
}
UIActivityIndicatorView indicator;
public bool Animating {
get {
return indicator.IsAnimating;
}
set {
if (value)
indicator.StartAnimating ();
else
indicator.StopAnimating ();
}
}
static NSString ikey = new NSString ("ActivityElement");
protected override NSString CellKey {
get {
return ikey;
}
}
public override UITableViewCell GetCell (UITableView tv)
{
var cell = tv.DequeueReusableCell (CellKey);
if (cell == null){
cell = new UITableViewCell (UITableViewCellStyle.Default, CellKey);
}
indicator = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
var sbounds = tv.Frame;
var vbounds = indicator.Bounds;
indicator.Frame = new CGRect((sbounds.Width-vbounds.Width)/2, 12, vbounds.Width, vbounds.Height);
indicator.StartAnimating ();
cell.Add (indicator);
return cell;
}
protected override void Dispose (bool disposing)
{
if (disposing){
if (indicator != null){
indicator.Dispose ();
indicator = null;
}
}
base.Dispose (disposing);
}
}
}
| hisystems/MonoTouch.Dialog | MonoTouch.Dialog/Elements/ActivityElement.cs | C# | mit | 1,275 |
'''
This module corresponds to ARDroneLib/Soft/Common/navdata_common.h
'''
import ctypes
import functools
from pyardrone.utils.structure import Structure
uint8_t = ctypes.c_uint8
uint16_t = ctypes.c_uint16
uint32_t = ctypes.c_uint32
int16_t = ctypes.c_int16
int32_t = ctypes.c_int32
bool_t = ctypes.c_uint32 # ARDroneTool's bool is 4 bytes
char = ctypes.c_char
float32_t = ctypes.c_float
NB_GYROS = 3
NB_ACCS = 3
NB_NAVDATA_DETECTION_RESULTS = 4
NB_CORNER_TRACKERS_WIDTH = 5
NB_CORNER_TRACKERS_HEIGHT = 4
DEFAULT_NB_TRACKERS_WIDTH = NB_CORNER_TRACKERS_WIDTH + 1
DEFAULT_NB_TRACKERS_HEIGHT = NB_CORNER_TRACKERS_HEIGHT + 1
NAVDATA_MAX_CUSTOM_TIME_SAVE = 20
_vector31_t = float32_t * 3
_velocities_t = _vector31_t
_vector21_t = float32_t * 2
_screen_point_t = int32_t * 2
_matrix33_t = float32_t * 3 * 3
class OptionHeader(dict):
def register(self, tag):
return functools.partial(self._register, tag)
def _register(self, tag, function):
if tag in self:
raise KeyError('Key {!r} conflict with existing item {}'.format(
tag, self[tag]))
self[tag] = function
return function
index = OptionHeader()
class Metadata(Structure):
'''
Header of :py:class:`~pyardrone.navdata.NavData`.
Available via :py:class:`~pyardrone.navdata.NavData`.metadata
Corresponds to C struct ``navdata_t``.
'''
_pack_ = 1
_attrname = 'metadata'
header = uint32_t #: Should be 0x55667788
#: raw drone state,
#: see also: :py:class:`~pyardrone.navdata.states.DroneState`
state = uint32_t
sequence_number = uint32_t #:
vision_flag = uint32_t #:
class OptionHeader(Structure):
_pack_ = 1
tag = uint16_t
size = uint16_t
@index.register(0)
class Demo(OptionHeader):
'''
Minimal navigation data for all flights.
Corresponds to C struct ``navdata_demo_t``.
'''
_attrname = 'demo'
#: Flying state (landed, flying, hovering, etc.)
#: defined in CTRL_STATES enum.
ctrl_state = uint32_t
vbat_flying_percentage = uint32_t #: battery voltage filtered (mV)
theta = float32_t #: UAV's pitch in milli-degrees
phi = float32_t #: UAV's roll in milli-degrees
psi = float32_t #: UAV's yaw in milli-degrees
altitude = int32_t #: UAV's altitude in centimeters
vx = float32_t #: UAV's estimated linear velocity
vy = float32_t #: UAV's estimated linear velocity
vz = float32_t #: UAV's estimated linear velocity
#: streamed frame index Not used -> To integrate in video stage.
num_frames = uint32_t
# Camera parameters compute by detection
detection_camera_rot = _matrix33_t #: Deprecated ! Don't use !
detection_camera_trans = _vector31_t #: Deprecated ! Don't use !
detection_tag_index = uint32_t #: Deprecated ! Don't use !
detection_camera_type = uint32_t #: Type of tag searched in detection
# Camera parameters compute by drone
drone_camera_rot = _matrix33_t #: Deprecated ! Don't use !
drone_camera_trans = _vector31_t #: Deprecated ! Don't use !
@index.register(1)
class Time(OptionHeader):
'''
Timestamp
Corresponds to C struct ``navdata_time_t``.
'''
_attrname = 'time'
#: 32 bit value where the 11 most significant bits represents the seconds,
#: and the 21 least significant bits are the microseconds.
time = uint32_t
@index.register(2)
class RawMeasures(OptionHeader):
'''
Raw sensors measurements
Corresponds to C struct ``navdata_raw_measures_t``.
'''
_attrname = 'raw_measures'
# +12 bytes
raw_accs = uint16_t * NB_ACCS #: filtered accelerometers
raw_gyros = int16_t * NB_GYROS #: filtered gyrometers
raw_gyros_110 = int16_t * 2 #: gyrometers x/y 110 deg/s
vbat_raw = uint32_t #: battery voltage raw (mV)
us_debut_echo = uint16_t
us_fin_echo = uint16_t
us_association_echo = uint16_t
us_distance_echo = uint16_t
us_courbe_temps = uint16_t
us_courbe_valeur = uint16_t
us_courbe_ref = uint16_t
flag_echo_ini = uint16_t
# TODO: uint16_t frame_number from ARDrone_Magneto
nb_echo = uint16_t
sum_echo = uint32_t
alt_temp_raw = int32_t
gradient = int16_t
@index.register(21)
class PressureRaw(OptionHeader):
'Corresponds to C struct ``navdata_pressure_raw_t``.'
_attrname = 'pressure_raw'
up = int32_t
ut = int16_t
Temperature_meas = int32_t
Pression_meas = int32_t
@index.register(22)
class Magneto(OptionHeader):
'Corresponds to C struct ``navdata_magneto_t``.'
_attrname = 'magneto'
mx = int16_t
my = int16_t
mz = int16_t
magneto_raw = _vector31_t #: magneto in the body frame, in mG
magneto_rectified = _vector31_t
magneto_offset = _vector31_t
heading_unwrapped = float32_t
heading_gyro_unwrapped = float32_t
heading_fusion_unwrapped = float32_t
magneto_calibration_ok = char
magneto_state = uint32_t
magneto_radius = float32_t
error_mean = float32_t
error_var = float32_t
@index.register(23)
class WindSpeed(OptionHeader):
'Corresponds to C struct ``navdata_wind_speed_t``.'
_attrname = 'wind_speed'
wind_speed = float32_t #: estimated wind speed [m/s]
#: estimated wind direction in North-East frame [rad] e.g.
#: if wind_angle is pi/4, wind is from South-West to North-East
wind_angle = float32_t
wind_compensation_theta = float32_t
wind_compensation_phi = float32_t
state_x1 = float32_t
state_x2 = float32_t
state_x3 = float32_t
state_x4 = float32_t
state_x5 = float32_t
state_x6 = float32_t
magneto_debug1 = float32_t
magneto_debug2 = float32_t
magneto_debug3 = float32_t
@index.register(24)
class KalmanPressure(OptionHeader):
'Corresponds to C struct ``navdata_kalman_pressure_t``.'
_attrname = 'kalman_pressure'
offset_pressure = float32_t
est_z = float32_t
est_zdot = float32_t
est_bias_PWM = float32_t
est_biais_pression = float32_t
offset_US = float32_t
prediction_US = float32_t
cov_alt = float32_t
cov_PWM = float32_t
cov_vitesse = float32_t
bool_effet_sol = bool_t
somme_inno = float32_t
flag_rejet_US = bool_t
u_multisinus = float32_t
gaz_altitude = float32_t
Flag_multisinus = bool_t
Flag_multisinus_debut = bool_t
@index.register(27)
class Zimmu3000(OptionHeader):
'Corresponds to C struct ``navdata_zimmu_3000_t``.'
_attrname = 'zimmu_3000'
vzimmuLSB = int32_t
vzfind = float32_t
@index.register(3)
class PhysMeasures(OptionHeader):
'Corresponds to C struct ``navdata_phys_measures_t``.'
_attrname = 'phys_measures'
accs_temp = float32_t
gyro_temp = uint16_t
phys_accs = float32_t * NB_ACCS
phys_gyros = float32_t * NB_GYROS
alim3V3 = uint32_t #: 3.3volt alim [LSB]
vrefEpson = uint32_t #: ref volt Epson gyro [LSB]
vrefIDG = uint32_t #: ref volt IDG gyro [LSB]
@index.register(4)
class GyrosOffsets(OptionHeader):
'Corresponds to C struct ``navdata_gyros_offsets_t``.'
_attrname = 'gyros_offsets'
offset_g = float32_t * NB_GYROS
@index.register(5)
class EulerAngles(OptionHeader):
'Corresponds to C struct ``navdata_euler_angles_t``.'
_attrname = 'eular_angles'
theta_a = float32_t
phi_a = float32_t
@index.register(6)
class References(OptionHeader):
'Corresponds to C struct ``navdata_references_t``.'
_attrname = 'references'
ref_theta = int32_t
ref_phi = int32_t
ref_theta_I = int32_t
ref_phi_I = int32_t
ref_pitch = int32_t
ref_roll = int32_t
ref_yaw = int32_t
ref_psi = int32_t
vx_ref = float32_t
vy_ref = float32_t
theta_mod = float32_t
phi_mod = float32_t
k_v_x = float32_t
k_v_y = float32_t
k_mode = uint32_t
ui_time = float32_t
ui_theta = float32_t
ui_phi = float32_t
ui_psi = float32_t
ui_psi_accuracy = float32_t
ui_seq = int32_t
@index.register(7)
class Trims(OptionHeader):
'Corresponds to C struct ``navdata_trims_t``.'
_attrname = 'trims'
angular_rates_trim_r = float32_t
euler_angles_trim_theta = float32_t
euler_angles_trim_phi = float32_t
@index.register(8)
class RcReferences(OptionHeader):
'Corresponds to C struct ``navdata_rc_references_t``.'
_attrname = 'rc_references'
rc_ref_pitch = int32_t
rc_ref_roll = int32_t
rc_ref_yaw = int32_t
rc_ref_gaz = int32_t
rc_ref_ag = int32_t
@index.register(9)
class Pwm(OptionHeader):
'Corresponds to C struct ``navdata_pwm_t``.'
_attrname = 'pwm'
motor1 = uint8_t
motor2 = uint8_t
motor3 = uint8_t
motor4 = uint8_t
sat_motor1 = uint8_t
sat_motor2 = uint8_t
sat_motor3 = uint8_t
sat_motor4 = uint8_t
gaz_feed_forward = float32_t
gaz_altitude = float32_t
altitude_integral = float32_t
vz_ref = float32_t
u_pitch = int32_t
u_roll = int32_t
u_yaw = int32_t
yaw_u_I = float32_t
u_pitch_planif = int32_t
u_roll_planif = int32_t
u_yaw_planif = int32_t
u_gaz_planif = float32_t
current_motor1 = uint16_t
current_motor2 = uint16_t
current_motor3 = uint16_t
current_motor4 = uint16_t
# WARNING: new navdata (FC 26/07/2011)
altitude_prop = float32_t
altitude_der = float32_t
@index.register(10)
class Altitude(OptionHeader):
'Corresponds to C struct ``navdata_altitude_t``.'
_attrname = 'altitude'
altitude_vision = int32_t
altitude_vz = float32_t
altitude_ref = int32_t
altitude_raw = int32_t
obs_accZ = float32_t
obs_alt = float32_t
obs_x = _vector31_t
obs_state = uint32_t
est_vb = _vector21_t
est_state = uint32_t
@index.register(11)
class VisionRaw(OptionHeader):
'Corresponds to C struct ``navdata_vision_raw_t``.'
_attrname = 'vision_raw'
vision_tx_raw = float32_t
vision_ty_raw = float32_t
vision_tz_raw = float32_t
@index.register(13)
class Vision(OptionHeader):
'Corresponds to C struct ``navdata_vision_t``.'
_attrname = 'vision'
vision_state = uint32_t
vision_misc = int32_t
vision_phi_trim = float32_t
vision_phi_ref_prop = float32_t
vision_theta_trim = float32_t
vision_theta_ref_prop = float32_t
new_raw_picture = int32_t
theta_capture = float32_t
phi_capture = float32_t
psi_capture = float32_t
altitude_capture = int32_t
time_capture = uint32_t #: time in TSECDEC format (see config.h)
body_v = _velocities_t
delta_phi = float32_t
delta_theta = float32_t
delta_psi = float32_t
gold_defined = uint32_t
gold_reset = uint32_t
gold_x = float32_t
gold_y = float32_t
@index.register(14)
class VisionPerf(OptionHeader):
'Corresponds to C struct ``navdata_vision_perf_t``.'
_attrname = 'vision_perf'
time_szo = float32_t
time_corners = float32_t
time_compute = float32_t
time_tracking = float32_t
time_trans = float32_t
time_update = float32_t
time_custom = float32_t * NAVDATA_MAX_CUSTOM_TIME_SAVE
@index.register(15)
class TrackersSend(OptionHeader):
'Corresponds to C struct ``navdata_trackers_send_t``.'
_attrname = 'trackers_send'
locked = int32_t * (DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT)
point = _screen_point_t * (
DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT
)
@index.register(16)
class VisionDetect(OptionHeader):
'Corresponds to C struct ``navdata_vision_detect_t``.'
# Change the function 'navdata_server_reset_vision_detect()'
# if this structure is modified
_attrname = 'vision_detect'
nb_detected = uint32_t
type = uint32_t * NB_NAVDATA_DETECTION_RESULTS
xc = uint32_t * NB_NAVDATA_DETECTION_RESULTS
yc = uint32_t * NB_NAVDATA_DETECTION_RESULTS
width = uint32_t * NB_NAVDATA_DETECTION_RESULTS
height = uint32_t * NB_NAVDATA_DETECTION_RESULTS
dist = uint32_t * NB_NAVDATA_DETECTION_RESULTS
orientation_angle = float32_t * NB_NAVDATA_DETECTION_RESULTS
rotation = _matrix33_t * NB_NAVDATA_DETECTION_RESULTS
translation = _vector31_t * NB_NAVDATA_DETECTION_RESULTS
camera_source = uint32_t * NB_NAVDATA_DETECTION_RESULTS
@index.register(12)
class VisionOf(OptionHeader):
'Corresponds to C struct ``navdata_vision_of_t``.'
_attrname = 'vision_of'
of_dx = float32_t * 5
of_dy = float32_t * 5
@index.register(17)
class Watchdog(OptionHeader):
'Corresponds to C struct ``navdata_watchdog_t``.'
_attrname = 'watchdog'
# +4 bytes
watchdog = int32_t
@index.register(18)
class AdcDataFrame(OptionHeader):
'Corresponds to C struct ``navdata_adc_data_frame_t``.'
_attrname = 'adc_data_frame'
version = uint32_t
data_frame = uint8_t * 32
@index.register(19)
class VideoStream(OptionHeader):
'Corresponds to C struct ``navdata_video_stream_t``.'
_attrname = 'video_stream'
quant = uint8_t #: quantizer reference used to encode frame [1:31]
frame_size = uint32_t #: frame size (bytes)
frame_number = uint32_t #: frame index
atcmd_ref_seq = uint32_t #: atmcd ref sequence number
#: mean time between two consecutive atcmd_ref (ms)
atcmd_mean_ref_gap = uint32_t
atcmd_var_ref_gap = float32_t
atcmd_ref_quality = uint32_t #: estimator of atcmd link quality
# drone2
#: measured out throughput from the video tcp socket
out_bitrate = uint32_t
#: last frame size generated by the video encoder
desired_bitrate = uint32_t
# misc temporary data
data1 = int32_t
data2 = int32_t
data3 = int32_t
data4 = int32_t
data5 = int32_t
# queue usage
tcp_queue_level = uint32_t
fifo_queue_level = uint32_t
@index.register(25)
class HdvideoStream(OptionHeader):
'Corresponds to C struct ``navdata_hdvideo_stream_t``.'
_attrname = 'hdvideo_stream'
hdvideo_state = uint32_t
storage_fifo_nb_packets = uint32_t
storage_fifo_size = uint32_t
usbkey_size = uint32_t #: USB key in kbytes - 0 if no key present
#: USB key free space in kbytes - 0 if no key present
usbkey_freespace = uint32_t
#: 'frame_number' PaVE field of the frame starting to be encoded for the
#: HD stream
frame_number = uint32_t
usbkey_remaining_time = uint32_t #: time in seconds
@index.register(20)
class Games(OptionHeader):
'Corresponds to C struct ``navdata_games_t``.'
_attrname = 'games'
double_tap_counter = uint32_t
finish_line_counter = uint32_t
@index.register(26)
class Wifi(OptionHeader):
'Corresponds to C struct ``navdata_wifi_t``.'
_attrname = 'wifi'
link_quality = uint32_t
@index.register(0xFFFF)
class Cks(OptionHeader):
'Corresponds to C struct ``navdata_cks_t``.'
_attrname = 'cks'
value = uint32_t #: Value of the checksum
| afg984/pyardrone | pyardrone/navdata/options.py | Python | mit | 14,941 |
const express = require("express");
const app = express();
app.set('port', (process.env.PORT || 3000));
const getData = require('./src/server/api/getData');
const setup = require('./src/server/api/setupApi');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use('/assets', express.static('build'));
app.use('/', require('./src/server/routers/index'));
app.get('/api/:chrom', getData);
const server = app.listen(app.get('port'));
setup(server);
| ragingsquirrel3/vrdb | server.js | JavaScript | mit | 483 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace N64Track
{
public static class CustomFontEffect
{
public static readonly BindableProperty FontFileNameProperty = BindableProperty.CreateAttached("FontFileName", typeof(string), typeof(CustomFontEffect), "", propertyChanged: OnFileNameChanged);
public static string GetFontFileName(BindableObject view)
{
return (string)view.GetValue(FontFileNameProperty);
}
/// <summary>
/// Set Font binding based on File Name provided
/// </summary>
/// <param name="view"></param>
/// <param name="value"></param>
public static void SetFontFileName(BindableObject view, string value)
{
view.SetValue(FontFileNameProperty, value);
}
static void OnFileNameChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as View;
if (view == null)
{
return;
}
view.Effects.Add(new FontEffect());
}
class FontEffect : RoutingEffect
{
public FontEffect() : base("Xamarin.FontEffect")
{
}
}
}
} | hackmods/N64Track | N64Track/N64Track/CustomFontEffect.cs | C# | mit | 1,348 |
package com.jetbrains.ther.lexer;
import com.google.common.collect.ImmutableMap;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.jetbrains.ther.psi.TheRElementType;
//deprecated
// DO NOT USE
public class TheRTokenTypes {
/*
* There are five types of constants: integer, logical, numeric, complex and string.
*/
// integer constants
public static final IElementType INTEGER_LITERAL = new TheRElementType("INTEGER_LITERAL");
// logical constants
public static final IElementType TRUE_KEYWORD = new TheRElementType("TRUE_KEYWORD");
public static final IElementType FALSE_KEYWORD = new TheRElementType("FALSE_KEYWORD");
// numeric constants
public static final IElementType NUMERIC_LITERAL = new TheRElementType("NUMERIC_LITERAL");
// complex constants
public static final IElementType COMPLEX_LITERAL = new TheRElementType("COMPLEX_LITERAL");
// string constants
public static final IElementType STRING_LITERAL = new TheRElementType("STRING_LITERAL");
/*
* In addition, there are four special constants
*/
public static final IElementType NULL_KEYWORD = new TheRElementType("NULL_KEYWORD"); // empty object
public static final IElementType INF_KEYWORD = new TheRElementType("INF_KEYWORD"); // infinity
public static final IElementType NAN_KEYWORD = new TheRElementType("NAN_KEYWORD"); // not-a-number in the IEEE floating point calculus (results of the operations respectively 1/0 and 0/0, for instance).
public static final IElementType NA_KEYWORD = new TheRElementType("NA_KEYWORD"); // absent (“Not Available”) data values
/*
The following identifiers have a special meaning and cannot be used for object names
if else repeat while function for in next break
TRUE FALSE NULL Inf NaN
NA NA_integer_ NA_real_ NA_complex_ NA_character_
... ..1 ..2 etc.
*/
// keywords
public static final IElementType NA_INTEGER_KEYWORD = new TheRElementType("NA_INTEGER_KEYWORD");
public static final IElementType NA_REAL_KEYWORD = new TheRElementType("NA_REAL_KEYWORD");
public static final IElementType NA_COMPLEX_KEYWORD = new TheRElementType("NA_COMPLEX_KEYWORD");
public static final IElementType NA_CHARACTER_KEYWORD = new TheRElementType("NA_CHARACTER_KEYWORD");
public static final IElementType TRIPLE_DOTS = new TheRElementType("TRIPLE_DOTS");
public static final IElementType IF_KEYWORD = new TheRElementType("IF_KEYWORD");
public static final IElementType ELSE_KEYWORD = new TheRElementType("ELSE_KEYWORD");
public static final IElementType REPEAT_KEYWORD = new TheRElementType("REPEAT_KEYWORD");
public static final IElementType WHILE_KEYWORD = new TheRElementType("WHILE_KEYWORD");
public static final IElementType FUNCTION_KEYWORD = new TheRElementType("FUNCTION_KEYWORD");
public static final IElementType FOR_KEYWORD = new TheRElementType("FOR_KEYWORD");
public static final IElementType IN_KEYWORD = new TheRElementType("IN_KEYWORD");
public static final IElementType NEXT_KEYWORD = new TheRElementType("NEXT_KEYWORD");
public static final IElementType BREAK_KEYWORD = new TheRElementType("BREAK_KEYWORD");
/*
R contains a number of operators. They are listed in the table below.
- Minus, can be unary or binary
+ Plus, can be unary or binary
! Unary not
~ Tilde, used for model formulae, can be either unary or binary
? Help
: Sequence, binary (in model formulae: interaction)
* Multiplication, binary
/ Division, binary
^ Exponentiation, binary
%x% Special binary operators, x can be replaced by any valid name
%% Modulus, binary
%/% Integer divide, binary
%*% Matrix product, binary
%o% Outer product, binary
%x% Kronecker product, binary
%in% Matching operator, binary (in model formulae: nesting)
< Less than, binary
> Greater than, binary
== Equal to, binary
>= Greater than or equal to, binaryChapter 3: Evaluation of expressions 11
<= Less than or equal to, binary
& And, binary, vectorized
&& And, binary, not vectorized
| Or, binary, vectorized
|| Or, binary, not vectorized
<- Left assignment, binary
-> Right assignment, binary
$ List subset, binary
*/
public static final IElementType MINUS = new TheRElementType("MINUS"); // -
public static final IElementType PLUS = new TheRElementType("PLUS"); // +
public static final IElementType NOT = new TheRElementType("NOT"); // !
public static final IElementType TILDE = new TheRElementType("TILDE"); // ~
public static final IElementType HELP = new TheRElementType("HELP"); // ?
public static final IElementType COLON = new TheRElementType("COLON"); // :
public static final IElementType MULT = new TheRElementType("MULT"); // *
public static final IElementType DIV = new TheRElementType("DIV"); // /
public static final IElementType EXP = new TheRElementType("EXP"); // ^
public static final IElementType MODULUS = new TheRElementType("MODULUS"); // %%
public static final IElementType INT_DIV = new TheRElementType("INT_DIV"); // %/%
public static final IElementType MATRIX_PROD = new TheRElementType("MATRIX_PROD"); // %*%
public static final IElementType OUTER_PROD = new TheRElementType("OUTER_PROD"); // %o%
public static final IElementType MATCHING = new TheRElementType("MATCHING"); // %in%
public static final IElementType KRONECKER_PROD = new TheRElementType("MATCHING"); // %x%
public static final IElementType INFIX_OP = new TheRElementType("INFIX_OP"); // %{character}+%
public static final IElementType LT = new TheRElementType("LT"); // <
public static final IElementType GT = new TheRElementType("GT"); // >
public static final IElementType EQEQ = new TheRElementType("EQEQ"); // ==
public static final IElementType GE = new TheRElementType("GE"); // >=
public static final IElementType LE = new TheRElementType("LE"); // <=
public static final IElementType AND = new TheRElementType("AND"); // &
public static final IElementType ANDAND = new TheRElementType("ANDAND"); // &&
public static final IElementType OR = new TheRElementType("OR"); // |
public static final IElementType OROR = new TheRElementType("OROR"); // ||
public static final IElementType LEFT_ASSIGN = new TheRElementType("LEFT_ASSIGN"); // <-
public static final IElementType RIGHT_ASSIGN = new TheRElementType("RIGHT_ASSIGN"); // ->
public static final IElementType LIST_SUBSET = new TheRElementType("LIST_SUBSET"); // $
public static final IElementType TICK = new TheRElementType("TICK"); // `
public static final IElementType AT = new TheRElementType("AT"); // @
public static final IElementType DOUBLECOLON = new TheRElementType("DOUBLECOLON"); // ::
public static final IElementType TRIPLECOLON = new TheRElementType("TRIPLECOLON"); // :::
public static final IElementType NOTEQ = new TheRElementType("NOTEQ"); // !=
public static final IElementType RIGHT_COMPLEX_ASSING = new TheRElementType("RIGHT_COMPLEX_ASSING"); // ->>
public static final IElementType LEFT_COMPLEX_ASSING = new TheRElementType("LEFT_COMPLEX_ASSING"); // <<-
public static final IElementType LPAR = new TheRElementType("LPAR"); // (
public static final IElementType RPAR = new TheRElementType("RPAR"); // )
public static final IElementType LBRACKET = new TheRElementType("LBRACKET"); // [
public static final IElementType LDBRACKET = new TheRElementType("LDBRACKET"); // [[
public static final IElementType RBRACKET = new TheRElementType("RBRACKET"); // ]
public static final IElementType RDBRACKET = new TheRElementType("RDBRACKET"); // ]]
public static final IElementType LBRACE = new TheRElementType("LBRACE"); // {
public static final IElementType RBRACE = new TheRElementType("RBRACE"); // }
public static final IElementType COMMA = new TheRElementType("COMMA"); // ,
public static final IElementType DOT = new TheRElementType("DOT"); // .
public static final IElementType EQ = new TheRElementType("EQ"); // =
public static final IElementType SEMICOLON = new TheRElementType("SEMICOLON"); // ;
public static final IElementType UNDERSCORE = new TheRElementType("UNDERSCORE"); // _
public static final IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER;
public static final IElementType IDENTIFIER = new TheRElementType("IDENTIFIER");
public static final IElementType LINE_BREAK = new TheRElementType("LINE_BREAK");
public static final IElementType SPACE = new TheRElementType("SPACE");
public static final IElementType TAB = new TheRElementType("TAB");
public static final IElementType FORMFEED = new TheRElementType("FORMFEED");
public static final IElementType END_OF_LINE_COMMENT = new TheRElementType("END_OF_LINE_COMMENT");
public static final TokenSet RESERVED_WORDS = TokenSet
.create(IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD, FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD,
BREAK_KEYWORD);
public static final TokenSet ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING, EQ);
public static final TokenSet LEFT_ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, EQ);
public static final TokenSet RIGHT_ASSIGNMENTS = TokenSet.create(RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING);
public static final TokenSet OPERATORS = TokenSet
.create(MINUS, PLUS, NOT, TILDE, HELP, COLON, MULT, DIV, EXP, MODULUS, INT_DIV, MATRIX_PROD, OUTER_PROD, MATCHING, KRONECKER_PROD,
INFIX_OP, LT, GT, EQEQ, GE, LE, AND, ANDAND, OR, OROR, LEFT_ASSIGN, RIGHT_ASSIGN, LIST_SUBSET, AT, TICK);
public static final TokenSet KEYWORDS = TokenSet.create(NA_INTEGER_KEYWORD, NA_REAL_KEYWORD, NA_COMPLEX_KEYWORD, NA_CHARACTER_KEYWORD,
TRIPLE_DOTS, IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD,
FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD, BREAK_KEYWORD);
public static final TokenSet STATEMENT_START_TOKENS = TokenSet.create(IF_KEYWORD, WHILE_KEYWORD, FOR_KEYWORD, REPEAT_KEYWORD,
BREAK_KEYWORD, NEXT_KEYWORD, LBRACE, FUNCTION_KEYWORD, HELP);
public static final TokenSet COMPARISON_OPERATIONS = TokenSet.create(LT, GT, EQEQ, GE, LE, NOTEQ, MATCHING);
public static final TokenSet NA_KEYWORDS = TokenSet.create(NA_KEYWORD, NA_CHARACTER_KEYWORD, NA_COMPLEX_KEYWORD, NA_INTEGER_KEYWORD,
NA_REAL_KEYWORD);
public static final TokenSet ADDITIVE_OPERATIONS = TokenSet.create(PLUS, MINUS);
public static final TokenSet MULTIPLICATIVE_OPERATIONS = TokenSet.create(MULT, DIV, INT_DIV, MATRIX_PROD, KRONECKER_PROD, OUTER_PROD);
public static final TokenSet POWER_OPERATIONS = TokenSet.create(EXP, MODULUS);
public static final TokenSet UNARY_OPERATIONS = TokenSet.create(PLUS, MINUS, TILDE, NOT);
public static final TokenSet EQUALITY_OPERATIONS = TokenSet.create(EQEQ, NOTEQ);
public static final TokenSet OR_OPERATIONS = TokenSet.create(OR, OROR);
public static final TokenSet AND_OPERATIONS = TokenSet.create(AND, ANDAND);
public static final TokenSet SPECIAL_CONSTANTS = TokenSet.create(NA_KEYWORD, NAN_KEYWORD, INF_KEYWORD, NULL_KEYWORD, TRUE_KEYWORD, FALSE_KEYWORD);
public static final TokenSet WHITESPACE_OR_LINEBREAK = TokenSet.create(SPACE, TAB, FORMFEED, LINE_BREAK);
public static final TokenSet WHITESPACE = TokenSet.create(SPACE, TAB, FORMFEED);
public static final TokenSet OPEN_BRACES = TokenSet.create(LBRACKET, LDBRACKET, LBRACE, LPAR);
public static final TokenSet CLOSE_BRACES = TokenSet.create(RBRACKET, RDBRACKET, RBRACE, RPAR);
public static final TokenSet OPEN_BRACKETS = TokenSet.create(LBRACKET, LDBRACKET);
public static final ImmutableMap<IElementType, IElementType> BRACKER_PAIRS =
ImmutableMap.<IElementType, IElementType>builder().put(LBRACKET, RBRACKET).put(LDBRACKET, RDBRACKET).build();
public static final TokenSet NAMESPACE_ACCESS = TokenSet.create(DOUBLECOLON, TRIPLECOLON);
} | ktisha/TheRPlugin | src/com/jetbrains/ther/lexer/TheRTokenTypes.java | Java | mit | 12,305 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Category Schema
*/
var CategorySchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Category name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Category', CategorySchema); | andela-osogunle/storefront.io | app/models/category.server.model.js | JavaScript | mit | 488 |
// CVDemo.Image.Overlay.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/video.hpp>
#include <stdio.h>
#include <sstream>
#include <stdexcept>
// #include <boost/program_options.hpp>
// #include <boost/filesystem.hpp>
#include "CVDemo.Image.ProgramOptions.hpp"
#include "CVDemo.Image.OverlayProcessor.hpp"
// temporary
#include <Windows.h>
using namespace cv;
using namespace std;
using namespace cvdemo::image;
// namespace po = boost::program_options;
// using namespace boost::filesystem;
// temporary
vector<string> get_all_file_names_within_folder(string folder)
{
vector<string> names;
// ????
string search_path = folder + "/*.png";
WIN32_FIND_DATAA fd;
HANDLE hFind = ::FindFirstFileA(search_path.c_str(), &fd); // ????
if (hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
// names.push_back(fd.cFileName); // ????
names.push_back(folder + "/" + fd.cFileName); // ????
}
} while (::FindNextFileA(hFind, &fd));
::FindClose(hFind);
}
//for (auto i = directory_iterator(folder); i != directory_iterator(); i++)
//{
// if (!is_directory(i->path()))
// {
// names.push_back(i->path().filename().string());
// }
//}
return names;
}
int main(int argc, const char* argv[])
{
// testing...
string configFile = "../cvdemo.image.overlay.cfg";
ProgramOptions options = ProgramOptions(argc, argv, configFile);
if (options.IsForUsageInfo()) {
options.DisplayUsageInfo(cout);
system("pause");
return -1;
}
if (options.IsForVersionInfo()) {
cout << "Version = 0.0.1" << endl;
system("pause");
return -1;
}
if (options.IsForOptionsDisplay()) {
options.DisplayInputOptions(cout);
system("pause");
return -1;
}
if (!options.IsValid()) {
cerr << ">>> Invalid input options." << endl;
options.DisplayUnrecognizedArgs(cerr);
options.DisplayOutputImageType(cerr);
options.DisplayForegroundImageFile(cerr);
options.DisplayForegroundImageFolder(cerr);
options.DisplayBackgroundImageFile(cerr);
options.DisplayBackgroundImageFolder(cerr);
options.DisplayOutputImageFolder(cerr);
options.DisplayUsageInfo(cerr);
system("pause");
return EXIT_FAILURE;
}
if (options.GetForegroundImageFile() != "" && options.GetBackgroundImageFile() != "") {
OverlayProcessor::overlayImages(options.GetForegroundImageFile(), options.GetBackgroundImageFile(), options.GetOutputImageFolder());
}
else {
if (options.GetForegroundImageFolder() != "" && options.GetBackgroundImageFile() != "") {
auto fgFolder = options.GetForegroundImageFolder();
vector<string> fgFiles = get_all_file_names_within_folder(fgFolder);
OverlayProcessor::overlayImages(fgFiles, options.GetBackgroundImageFile(), options.GetOutputImageFolder());
}
else if (options.GetForegroundImageFile() != "" && options.GetBackgroundImageFolder() != "") {
auto bgFolder = options.GetBackgroundImageFolder();
vector<string> bgFiles = get_all_file_names_within_folder(bgFolder);
OverlayProcessor::overlayImages(options.GetForegroundImageFile(), bgFiles, options.GetOutputImageFolder());
}
else {
// ????
}
}
system("pause");
return EXIT_SUCCESS;
}
| cvdemo/image-win32 | CVDemo.Image/CVDemo.Image.Overlay/CVDemo.Image.Overlay.cpp | C++ | mit | 3,416 |
<?php
// autoload_real.php generated by Composer
class ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03', 'loadClassLoader'));
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
$loader->register(true);
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
require $file;
}
return $loader;
}
}
| mu4ddi3/gajdaw-zabytki | vendor/composer/autoload_real.php | PHP | mit | 1,372 |
#include "texture.h"
using namespace gl;
/**
* Constructs a new Texture object, storing the specified textureID for binding
* @param textureID the Integer representing the texture that can be bound
*/
Texture::Texture(std::string associatedFileName, gl::GLuint textureID) : textureID(textureID), associatedFileName(associatedFileName)
{
}
/**
* Binds the texture using GL11. The texture will remain bound until the next bind() call of a different
* texture object, or manual call to GL11.glBindTexture(...)
*/
void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, textureID);
}
| Alec-Sobeck/3D-Game | src/render/texture.cpp | C++ | mit | 591 |
package hammer
import (
"context"
"log"
"github.com/antihax/evedata/internal/datapackages"
)
func init() {
registerConsumer("killmail", killmailConsumer)
}
func killmailConsumer(s *Hammer, parameter interface{}) {
parameters := parameter.([]interface{})
hash := parameters[0].(string)
id := int32(parameters[1].(int))
known := s.inQueue.CheckWorkCompleted("evedata_known_kills", id)
if known {
return
}
kill, _, err := s.esi.ESI.KillmailsApi.GetKillmailsKillmailIdKillmailHash(context.Background(), hash, id, nil)
if err != nil {
log.Println(err)
return
}
s.inQueue.SetWorkCompleted("evedata_known_kills", id)
if err != nil {
log.Println(err)
return
}
// Send out the result, but ignore DUST stuff.
if kill.Victim.ShipTypeId < 65535 {
err = s.QueueResult(&datapackages.Killmail{Hash: hash, Kill: kill}, "killmail")
if err != nil {
log.Println(err)
return
}
}
err = s.AddCharacter(kill.Victim.CharacterId)
if err != nil {
log.Println(err)
return
}
err = s.AddAlliance(kill.Victim.AllianceId)
if err != nil {
log.Println(err)
return
}
err = s.AddCorporation(kill.Victim.CorporationId)
if err != nil {
log.Println(err)
return
}
for _, a := range kill.Attackers {
err = s.AddCharacter(a.CharacterId)
if err != nil {
log.Println(err)
return
}
err = s.AddAlliance(a.AllianceId)
if err != nil {
log.Println(err)
return
}
err = s.AddCorporation(a.CorporationId)
if err != nil {
log.Println(err)
return
}
}
}
| antihax/evedata | services/hammer/killmail.go | GO | mit | 1,513 |
var searchData=
[
['index',['index',['../d8/d33/structsvm__sample.html#a008f6b24c7c76af103e84245fb271506',1,'svm_sample']]],
['initlibirwls',['initLIBIRWLS',['../d4/d54/pythonmodule_8c.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void): pythonmodule.c'],['../d0/da7/pythonmodule_8h.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void): pythonmodule.c']]],
['initmemory',['initMemory',['../d0/d98/ParallelAlgorithms_8h.html#aa6df8c3f4f455d5692b3cb220fc205c7',1,'ParallelAlgorithms.h']]],
['iostructures_2ec',['IOStructures.c',['../dc/dfc/IOStructures_8c.html',1,'']]],
['iostructures_2eh',['IOStructures.h',['../de/d79/IOStructures_8h.html',1,'']]],
['irwlspar',['IRWLSpar',['../d4/d49/budgeted-train_8h.html#ad51d9a46645ad0b0bedb1113a3807d24',1,'budgeted-train.h']]]
];
| RobeDM/LIBIRWLS | docs/html/search/all_7.js | JavaScript | mit | 812 |
module.exports = {
options: {
templateCompilerPath: 'bower_components/ember/ember-template-compiler.js',
handlebarsPath: 'bower_components/handlebars/handlebars.js',
preprocess: function (source) {
return source.replace(/\s+/g, ' ');
},
templateName: function (sourceFile) {
/*
These are how templates will be named based on their folder
structure.
components/[name].hbs ==> components/[name]
partials/[name].hbs ==> _[name]
modules/application/templates/[name].hbs ==> [name]
modules/application/partials/[name].hbs ==> _[name]
modules/[moduleName]/templates/[moduleName].hbs ==> [moduleName]
modules/[moduleName]/templates/[name].hbs ==> [moduleName]/[name]
modules/[moduleName]/partials/[name].hbs ==> [moduleName]/_[name]
Additionally any template that is nested deeper will have that
structure added as well.
modules/[moduleName]/templates/[folder1]/[folder2]/[name] ==> [moduleName]/[folder1]/[folder2]/[name]
*/
var matches = sourceFile.match(new RegExp('(?:app/modules/(.*?)/|app/)(templates|partials)?/?(.*)')),
moduleName = matches[1],
isAppModule = (moduleName === 'application'),
isPartial = (matches[2] === 'partials'),
fileName = matches[3],
prefix = (isPartial ? '_' : ''),
templateName = '';
if (moduleName && !isAppModule) {
if (fileName === moduleName) {
templateName = moduleName;
}
else {
templateName = moduleName + '/' + prefix + fileName;
}
}
else {
templateName = prefix + fileName;
}
console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green);
return templateName;
}
},
compile: {
files: {
'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}']
}
}
};
| geekingreen/generator-anthracite | app/templates/grunt/emberTemplates.js | JavaScript | mit | 1,794 |
class WorkflowSweeper < ActionController::Caching::Sweeper
include InterfaceUtils::Extensions::Sweeper
include Rails.application.routes.url_helpers
include ActionController::Caching::Pages
observe Workflow
def after_save(workflow)
expire_cache(workflow)
end
def after_destroy(workflow)
expire_cache(workflow)
end
def expire_cache(workflow)
expire_full_path_page medium_workflow_url(workflow.medium, :only_path => true, :format => :xml)
end
end
| thl/mms_engine | app/sweepers/workflow_sweeper.rb | Ruby | mit | 490 |
// Copyright 2016 David Lavieri. All rights reserved.
// Use of this source code is governed by a MIT License
// License that can be found in the LICENSE file.
package main
import (
"fmt"
"github.com/falmar/goradix"
)
func main() {
radix := goradix.New(false)
radix.Insert("romanus", 1)
radix.Insert("romane", 100)
radix.Insert("romulus", 1000)
value, err := radix.LookUp("romane")
if err != nil { // No Match Found
return
}
// Output: Found node, Value: 100
fmt.Println("Found node, Value: ", value)
}
| falmar/goradix | examples/lookup/main.go | GO | mit | 524 |
module.exports = api => {
api.cache(true);
return {
presets: [
[
'@babel/preset-env',
{
targets: {
node: '12'
}
}
]
]
};
};
| srod/node-minify | babel.config.js | JavaScript | mit | 207 |
<?php
/*
* This file is part of HabitRPG-GitHub.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace tests;
require_once(__DIR__.'/../scripts/session.php');
require_once(__DIR__.'/../scripts/serviceFunctions.php');
/**
* This class tests the HabitRPGAPI class.
*
* To run:
* phpunit --bootstrap tests/bootstrap.php tests/serviceFunctionsTest
*
* @author Bradley Wogsland <bradley@wogsland.org>
*/
class serviceFunctionsTest
extends \PHPUnit_Framework_TestCase
{
/**
* Tests the newCommit function.
*/
public function test_newCommit () {
$repoName = 'wogsland/HabitRPG-GitHub';
$user = 'wogsland';
$count = 2;
$token = 'cLFWwvNKC2exK';
newCommit($repoName, $user, $count, $token);
//$this->assertEquals($test_name, $test->userId);
//$this->assertEquals($test_token, $test->apiToken);
//$this->assertEquals('https://habitrpg.com/api/v2/', $test->apiURL);
}
}
| HabitRPG/habitrpg-github | tests/serviceFunctionsTest.php | PHP | mit | 1,004 |
cask 'font-monoid-loose-large-dollar-l' do
version :latest
sha256 :no_check
# github.com/larsenwork/monoid was verified as official when first introduced to the cask
url 'https://github.com/larsenwork/monoid/blob/release/Monoid-Loose-Large-Dollar-l.zip?raw=true'
name 'Monoid-Loose-Large-Dollar-l'
homepage 'http://larsenwork.com/monoid/'
font 'Monoid-Bold-Loose-Large-Dollar-l.ttf'
font 'Monoid-Italic-Loose-Large-Dollar-l.ttf'
font 'Monoid-Regular-Loose-Large-Dollar-l.ttf'
font 'Monoid-Retina-Loose-Large-Dollar-l.ttf'
caveats <<~EOS
#{token} is dual licensed with MIT and OFL licenses.
https://github.com/larsenwork/monoid/tree/master#license
EOS
end
| sscotth/homebrew-monoid | Casks/font-monoid-loose-large-dollar-l.rb | Ruby | mit | 690 |
# -*- coding: utf-8 -*-
#!/usr/bin/python
import numpy as np
import scipy
from sklearn import preprocessing
from sklearn.feature_extraction import DictVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from collections import Counter
from scipy.stats.stats import pearsonr
import data_readers
import feature_extractors as fe
import label_transformers as lt
import training_functions as training
import utils
def build_dataset(reader, phi_list, class_func, vectorizer=None, verbose=False):
"""Core general function for building experimental
hand-generated feature datasets.
Parameters
----------
reader : iterator
Should follow the format of data_readers. This is the dataset
we'll be featurizing.
phi_list : array of feature functions (default: [`manual_content_flags`])
Any function that takes a string as input and returns a
bool/int/float-valued dict as output.
class_func : function on the labels
A function that modifies the labels based on the experimental
design. If `class_func` returns None for a label, then that
item is ignored.
vectorizer : sklearn.feature_extraction.DictVectorizer
If this is None, then a new `DictVectorizer` is created and
used to turn the list of dicts created by `phi` into a
feature matrix. This happens when we are training.
If this is not None, then it's assumed to be a `DictVectorizer`
and used to transform the list of dicts. This happens in
assessment, when we take in new instances and need to
featurize them as we did in training.
Returns
-------
dict
A dict with keys 'X' (the feature matrix), 'y' (the list of
labels), 'vectorizer' (the `DictVectorizer`), and
'raw_examples' (the example strings, for error analysis).
"""
labels = []
feat_dicts = []
raw_examples = []
rows = []
for i, (paragraph, parse, label) in enumerate(reader()):
if i % 100 == 0:
print " Starting feature extraction for unit #%d " % (i+1)
cls = class_func(label)
#print label, cls
if cls != None:
labels.append(cls)
raw_examples.append(paragraph)
if verbose:
print cls, ":", paragraph
features = Counter()
for phi in phi_list:
cur_feats = phi(paragraph, parse)
if cur_feats is None:
continue
# If we won't accidentally blow away data, merge 'em.
overlap_feature_names = features.viewkeys() & cur_feats.viewkeys()
if verbose and len(overlap_feature_names) > 0:
print "Note: Overlap features are ", overlap_feature_names
features |= cur_feats
rows.append(cur_feats['row'])
feat_dicts.append(features)
if verbose:
print features
print
print "Completed all feature extraction: %d units" % (i+1)
# In training, we want a new vectorizer, but in
# assessment, we featurize using the existing vectorizer:
feat_matrix = None
if vectorizer == None:
vectorizer = DictVectorizer(sparse=True)
feat_matrix = vectorizer.fit_transform(feat_dicts)
else:
feat_matrix = vectorizer.transform(feat_dicts)
return {'X': feat_matrix,
'y': labels,
'vectorizer': vectorizer,
'raw_examples': raw_examples}
def experiment_features(
train_reader=data_readers.toy,
assess_reader=None,
train_size=0.7,
phi_list=[fe.manual_content_flags],
class_func=lt.identity_class_func,
train_func=training.fit_logistic_at_with_crossvalidation,
score_func=scipy.stats.stats.pearsonr,
verbose=True):
"""Generic experimental framework for hand-crafted features.
Either assesses with a random train/test split of `train_reader`
or with `assess_reader` if it is given.
Parameters
----------
train_reader : data iterator (default: `train_reader`)
Iterator for training data.
assess_reader : iterator or None (default: None)
If None, then the data from `train_reader` are split into
a random train/test split, with the the train percentage
determined by `train_size`. If not None, then this should
be an iterator for assessment data (e.g., `dev_reader`).
train_size : float (default: 0.7)
If `assess_reader` is None, then this is the percentage of
`train_reader` devoted to training. If `assess_reader` is
not None, then this value is ignored.
phi_list : array of feature functions (default: [`manual_content_flags`])
Any function that takes a string as input and returns a
bool/int/float-valued dict as output.
class_func : function on the labels
A function that modifies the labels based on the experimental
design. If `class_func` returns None for a label, then that
item is ignored.
train_func : model wrapper (default: `fit_logistic_at_with_crossvalidation`)
Any function that takes a feature matrix and a label list
as its values and returns a fitted model with a `predict`
function that operates on feature matrices.
score_metric : function name (default: `utils.safe_weighted_f1`)
This should be an `sklearn.metrics` scoring function. The
default is weighted average F1.
verbose : bool (default: True)
Whether to print out the model assessment to standard output.
Prints
-------
To standard output, if `verbose=True`
Model confusion matrix and a model precision/recall/F1 report.
Returns
-------
float
The overall scoring metric for assess set as determined by `score_metric`.
float
The overall Cronbach's alpha for assess set
np.array
The confusion matrix (rows are truth, columns are predictions)
list of dictionaries
A list of {truth:_ , prediction:_, example:_} dicts on the assessment data
"""
# Train dataset:
train = build_dataset(train_reader, phi_list, class_func, vectorizer=None, verbose=verbose)
# Manage the assessment set-up:
indices = np.arange(0, len(train['y']))
X_train = train['X']
y_train = np.array(train['y'])
train_examples = np.array(train['raw_examples'])
X_assess = None
y_assess = None
assess_examples = None
if assess_reader == None:
print " Raw y training distribution:"
print " ", np.bincount(y_train)[1:]
indices_train, indices_assess, y_train, y_assess = train_test_split(
indices, y_train, train_size=train_size, stratify=y_train)
X_assess = X_train[indices_assess]
assess_examples = train_examples[indices_assess]
X_train = X_train[indices_train]
train_examples = train_examples[indices_train]
print " Train y distribution:"
print " ", np.bincount(y_train)[1:]
print " Test y distribution:"
print " ", np.bincount(y_assess)[1:]
else:
assess = build_dataset(
assess_reader,
phi_list,
class_func,
vectorizer=train['vectorizer'])
X_assess, y_assess, assess_examples = assess['X'], assess['y'], np.array(assess['raw_examples'])
# Normalize:
nonzero_cells = len(X_train.nonzero()[0])
total_cells = 1.*X_train.shape[0] * X_train.shape[1]
proportion_nonzero = nonzero_cells/total_cells
print "sparsity: %g/1 are nonzero" % proportion_nonzero
if proportion_nonzero > 0.5: # if dense matrix
X_train = X_train.toarray()
X_assess = X_assess.toarray()
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_assess = scaler.transform(X_assess)
else:
scaler = preprocessing.MaxAbsScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_assess = scaler.transform(X_assess)
# Train:
mod = train_func(X_train, y_train)
# Predictions:
predictions_on_assess = mod.predict(X_assess)
assess_performance = get_score_example_pairs(y_assess, predictions_on_assess, assess_examples)
predictions_on_train = mod.predict(X_train)
train_performance = get_score_example_pairs(y_train, predictions_on_train, train_examples)
# Report:
if verbose:
print "\n-- TRAINING RESULTS --"
print_verbose_overview(y_train, predictions_on_train)
print "\n-- ASSESSMENT RESULTS --"
print_verbose_overview(y_assess, predictions_on_assess)
try:
the_score = score_func(y_assess, predictions_on_assess)
except:
the_score = (0,0)
# Return the overall results on the assessment data:
return the_score, \
utils.cronbach_alpha(y_assess, predictions_on_assess), \
confusion_matrix(y_assess, predictions_on_assess), \
assess_performance
def get_score_example_pairs(y, y_hat, examples):
""" Return a list of dicts: {truth score, predicted score, example} """
paired_results = sorted(zip(y, y_hat), key=lambda x: x[0]-x[1])
performance = []
for i, (truth, prediction) in enumerate(paired_results):
performance.append({"truth": truth, "prediction": prediction, "example": examples[i]})
return performance
def print_verbose_overview(y, yhat):
""" Print a performance overview """
print "Correlation: ", pearsonr(y, yhat)[0]
print "Alpha: ", utils.cronbach_alpha(y, yhat)
print "Classification report:"
print classification_report(y, yhat, digits=3)
print "Confusion matrix:"
print confusion_matrix(y, yhat)
print " (Rows are truth; columns are predictions)"
def experiment_features_iterated(
train_reader=data_readers.toy,
assess_reader=None,
train_size=0.7,
phi_list=[fe.manual_content_flags],
class_func=lt.identity_class_func,
train_func=training.fit_logistic_at_with_crossvalidation,
score_func=utils.safe_weighted_f1,
verbose=True,
iterations=1):
"""
Generic iterated experimental framework for hand-crafted features.
"""
correlation_overall = []
cronbach_overall = []
conf_matrix_overall = None
assess_performance = []
while len(correlation_overall) < iterations:
print "\nStarting iteration: %d/%d" % (len(correlation_overall)+1, iterations)
try:
correlation_local, cronbach_local, conf_matrix_local, perf_local = experiment_features(
train_reader=train_reader,
assess_reader=assess_reader,
train_size=train_size,
phi_list=phi_list,
class_func=class_func,
train_func=train_func,
score_func=score_func,
verbose=verbose)
correlation_overall.append(correlation_local[0])
cronbach_overall.append(cronbach_local)
assess_performance.extend(perf_local)
if conf_matrix_overall is None:
conf_matrix_overall = conf_matrix_local
else:
conf_matrix_overall += conf_matrix_local
except (ValueError,UserWarning) as e:
print e
if verbose:
print "\n-- OVERALL --"
print correlation_overall
print cronbach_overall
print conf_matrix_overall
return correlation_overall, cronbach_overall, conf_matrix_overall, assess_performance
| ptoman/icgauge | icgauge/experiment_frameworks.py | Python | mit | 11,989 |
package com.artbeatte.launchpad;
import com.google.common.collect.ImmutableMap;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Map;
/**
* @author art.beatte
* @version 7/14/15
*/
public class LaunchpadConfiguration extends Configuration {
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@NotNull
private Map<String, Map<String, String>> viewRendererConfiguration = Collections.emptyMap();
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
@JsonProperty("database")
public void setDataSourceFactory(DataSourceFactory dataSourceFactory) {
this.database = dataSourceFactory;
}
@JsonProperty("viewRendererConfiguration")
public Map<String, Map<String, String>> getViewRendererConfiguration() {
return viewRendererConfiguration;
}
@JsonProperty("viewRendererConfiguration")
public void setViewRendererConfiguration(Map<String, Map<String, String>> viewRendererConfiguration) {
ImmutableMap.Builder<String, Map<String, String>> builder = ImmutableMap.builder();
for (Map.Entry<String, Map<String, String>> entry : viewRendererConfiguration.entrySet()) {
builder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue()));
}
this.viewRendererConfiguration = builder.build();
}
}
| abeatte/launchpad | src/main/java/com/artbeatte/launchpad/LaunchpadConfiguration.java | Java | mit | 1,603 |
require 'net/http'
require 'uri'
require 'nokogiri'
module Discover
class Device
attr_reader :ip
attr_reader :port
attr_reader :description_url
attr_reader :server
attr_reader :service_type
attr_reader :usn
attr_reader :url_base
attr_reader :name
attr_reader :manufacturer
attr_reader :manufacturer_url
attr_reader :model_name
attr_reader :model_number
attr_reader :model_description
attr_reader :model_url
attr_reader :serial_number
attr_reader :software_version
attr_reader :hardware_version
def initialize(info)
headers = {}
info[0].split("\r\n").each do |line|
matches = line.match(/^([\w\-]+):(?:\s)*(.*)$/)
next unless matches
headers[matches[1].upcase] = matches[2]
end
@description_url = headers['LOCATION']
@server = headers['SERVER']
@service_type = headers['ST']
@usn = headers['USN']
info = info[1]
@port = info[1]
@ip = info[2]
get_description
end
protected
def get_description
response = Net::HTTP.get_response(URI.parse(description_url))
doc = Nokogiri::XML(response.body)
map = {
name: 'friendlyName',
manufacturer: 'manufacturer',
model_name: 'modelName',
model_number: 'modelNumber',
model_description: 'modelDescription',
model_url: 'modelURL',
software_version: 'softwareVersion',
hardware_version: 'hardwareVersion'
}
map.each do |key, xml_key|
next unless node = doc.css("/root/device/#{xml_key}").first
instance_variable_set("@#{key}".to_sym, node.inner_text)
end
@serial_number = (doc.css('/root/device/serialNumber').first || doc.css('/root/device/serialNum').first).inner_text
end
end
end
| soffes/discover | lib/discover/device.rb | Ruby | mit | 1,828 |
'use strict';
function UserListController(userList) {
var vm = this;
console.log('UserListController');
vm.userList = userList;
}
module.exports = UserListController; | byskr/sample-angular | src/components/user/controller/user-list-controller.js | JavaScript | mit | 181 |
using myOC_WebApp.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace myOC_WebApp.Controllers
{
public class HomeController : Controller, IHomeController
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
this._logger = logger;
_logger.Log("======== Started using injected constructor");
}
public HomeController() : this((ILogger)MyIoC.Resolve(typeof(ILogger))){ }
public ActionResult Index()
{
ViewBag.Message = "The All-Glorious Index Page";
_logger.Log("Visited the index through home controller");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
_logger.Log("Visited the About page through home controller");
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | theamazingfedex/IoCsharp | myOC-WebApp/myOC-WebApp/Controllers/HomeController.cs | C# | mit | 1,124 |
import sys, os, fabric
class PiServicePolicies:
@staticmethod
def is_local():
return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1'])
@staticmethod
def is_pi():
return os.path.isdir('/home/pi')
@staticmethod
def check_local_or_exit():
if not PiServicePolicies.is_local():
print "...only callable on localhost!!!"
sys.exit(-1)
@staticmethod
def check_remote_or_exit():
if PiServicePolicies.is_local():
print "...only callable on remote host!!!"
sys.exit(-1)
def check_installed_or_exit(self):
if not PiServicePolicies.installed(self):
print "...first you have to install this service! fab pi %s:install"
sys.exit(-1)
def installed(self):
ret = self.file_exists('__init__.py')
if not ret: print self.name+' not installed'
return ret
| creative-workflow/pi-setup | lib/piservices/policies.py | Python | mit | 867 |
#include "Core.h"
#include "Async/ActionGraph.h"
#include "ActionGraphImplementation.h"
std::shared_ptr<ActionGraphInterface> ActionGraphInterface::c_graphImp = nullptr;
std::weak_ptr<ActionGraphInterface> ActionGraphInterface::Get()
{
// if it`s not init, just crash.
check(c_graphImp != nullptr);
return c_graphImp;
}
void ActionGraphInterface::Init(const unsigned int& inWorkThreadNum)
{
c_graphImp = std::shared_ptr<ActionGraphInterface>(new ActionGraphImplementation());
c_graphImp->ConstructWorkThread(inWorkThreadNum);
}
| yuletian/IceDogEngine | Core/Private/Async/ActionGraph.cpp | C++ | mit | 536 |
import cv2, numpy as np
from dolphintracker.singlecam_tracker.camera_filter.FindDolphin import SearchBlobs
from dolphintracker.singlecam_tracker.camera_filter.BackGroundDetector import BackGroundDetector
import datetime
class PoolCamera(object):
def __init__(self, videofile, name, scene, maskObjectsNames, filters, frames_range=None):
self.name = name
self.videoCap = cv2.VideoCapture(videofile)
self.scene = scene
self.filters = filters
self.mask = self.create_mask(maskObjectsNames)
self.frames_range = frames_range
self._searchblobs = SearchBlobs()
self._backgrounds = []
self._last_centroid = None
if self.frames_range is not None:
self.videoCap.set(cv2.CAP_PROP_POS_FRAMES, self.frames_range[0])
print('set first frame', self.frames_range)
self._total_frames = self.videoCap.get(7)
self._colors = [(255,0,0),(0,255,0),(0,0,255)]
def create_mask(self, objectsNames):
mask = np.zeros((self.img_height,self.img_width), np.uint8)
for objname in objectsNames:
obj = self.scene.getObject(objname)
ptsProjection = self.points_projection( [p for p in obj.points if p[2]<0.2] )
hull = cv2.convexHull(np.int32(ptsProjection))
cv2.fillPoly(mask, np.int32([hull]), 255)
return mask
def read(self):
res, self.frame = self.videoCap.read()
if res:
self.originalFrame = self.frame.copy()
else:
self.originalFrame = None
return res
def process(self):
if len(self._backgrounds)==0:
for i, colorFilter in enumerate(self.filters):
firstFrame = self.frame_index
bgDetector = BackGroundDetector(capture=self.videoCap, filterFunction=colorFilter.process)
print('Background detection parameters', self._total_frames*0.04, self._total_frames*0.03)
last_frame = self.frames_range[1] if self.frames_range is not None else None
bg = bgDetector.detect(int(self._total_frames*0.04), int(self._total_frames*0.03), 180, last_frame)
bg = cv2.dilate( bg, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (5,5) ), iterations=2 )
bg = 255-bg
bg[bg<255]=0
self._backgrounds.append( cv2.bitwise_and(bg, self.mask) )
self.frame_index = firstFrame
result = []
for i, colorFilter in enumerate(self.filters):
filterResult = colorFilter.filter(self.frame, self._backgrounds[i])
blobs = self._searchblobs.process(filterResult)
res = blobs[0] if len(blobs)>=1 else None
result.append(res)
return result
def create_empty_mask(self): return np.zeros( (self.img_height, self.img_width), np.uint8 )
def points_projection(self, points): cam = self.scene_camera; return [cam.calcPixel(*p) for p in points]
@property
def scene_camera(self): return self.scene.getCamera(self.name)
@property
def img_width(self): return int( self.videoCap.get(cv2.CAP_PROP_FRAME_WIDTH) )
@property
def img_height(self): return int( self.videoCap.get(cv2.CAP_PROP_FRAME_HEIGHT) )
@property
def fps(self): return int( self.videoCap.get(cv2.CAP_PROP_FPS) )
@property
def frame_index(self): return int( self.videoCap.get(cv2.CAP_PROP_POS_FRAMES) )
@frame_index.setter
def frame_index(self, value): self.videoCap.set(cv2.CAP_PROP_POS_FRAMES, value)
@property
def currentTime(self):
milli = self.videoCap.get(cv2.CAP_PROP_POS_MSEC)
return datetime.timedelta(milliseconds=milli)
@property
def totalFrames(self): return self.videoCap.get(cv2.CAP_PROP_FRAME_COUNT) | UmSenhorQualquer/d-track | dolphintracker/singlecam_tracker/pool_camera.py | Python | mit | 3,437 |
import log from 'log';
import Ember from 'ember';
import {registerComponent} from 'ember-utils';
import layout from './confirm-toolbar.hbs!';
export var RheaConfirmToolbar = Ember.Component.extend({
layout,
tagName: '',
actions: {
confirm: function(opID) {
this.sendAction('confirm');
},
cancel: function(opID) {
this.sendAction('cancel');
}
}
});
registerComponent('rhea-confirm-toolbar', RheaConfirmToolbar);
| rhea/rhea | src/components/confirm-toolbar/confirm-toolbar.js | JavaScript | mit | 451 |
class WelcomeController < ApplicationController
def index
@game=Game.new
end
def update_cards_per_player
@max_cards_per_player = Game.get_maximun_cards_per_player(params[:players])
respond_to do |format|
format.js
end
end
def update_game
puts params[:cards_per_players]
@game=Game.new(params[:players],params[:cards_per_player])
render "index"
end
end
| diegopiccinini/random_cards | app/controllers/welcome_controller.rb | Ruby | mit | 380 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Worldpay\Payments\Test\Unit\Controller\Apm;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
class RedirectTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->checkoutSessionMock = $this->getMockBuilder('\Magento\Checkout\Model\Session')
->disableOriginalConstructor()
->setMethods(
[
'clearHelperData',
'getQuote',
'setLastQuoteId',
'setLastSuccessQuoteId',
'setLastOrderId',
'setLastRealOrderId',
]
)
->getMock();
$this->checkoutFactoryMock = $this->getMockBuilder('\Magento\Braintree\Model\CheckoutFactory')
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$this->messageManager = $this->getMock('\Magento\Framework\Message\ManagerInterface');
$this->checkoutMock = $this->getMockBuilder('\Magento\Braintree\Model\Checkout')
->disableOriginalConstructor()
->getMock();
$this->requestMock = $this->getMock('\Magento\Framework\App\Request\Http', [], [], '', '', false);
$this->resultFactoryMock = $this->getMockBuilder('\Magento\Framework\Controller\ResultFactory')
->disableOriginalConstructor()
->getMock();
$contextMock = $this->getMockBuilder('\Magento\Framework\App\Action\Context')
->disableOriginalConstructor()
->getMock();
$contextMock->expects($this->any())
->method('getResultFactory')
->willReturn($this->resultFactoryMock);
$contextMock->expects($this->any())
->method('getRequest')
->willReturn($this->requestMock);
$contextMock->expects($this->any())
->method('getMessageManager')
->willReturn($this->messageManager);
$this->objectManagerHelper = new ObjectManagerHelper($this);
$this->validatorMock = $this->getMock('Magento\Checkout\Api\AgreementsValidatorInterface');
$this->controller = $this->objectManagerHelper->getObject(
'\Magento\Braintree\Controller\PayPal\PlaceOrder',
[
'context' => $contextMock,
'checkoutSession' => $this->checkoutSessionMock,
'checkoutFactory' => $this->checkoutFactoryMock,
'agreementsValidator' => $this->validatorMock
]
);
$this->paymentMock = $this->getMockBuilder('\Magento\Quote\Model\Quote')
->disableOriginalConstructor()
->setMethods(['getMethod'])
->getMock();
$this->paymentMock->expects($this->once())
->method('getMethod')
->willReturn('worldpay_payments_paypal');
}
protected function setupCart()
{
$quoteMock = $this->getMockBuilder('\Magento\Quote\Model\Quote')
->disableOriginalConstructor()
->setMethods(['hasItems', 'getHasError', 'getPayment', 'getId'])
->getMock();
$quoteMock->expects($this->any())
->method('hasItems')
->willReturn(true);
$quoteMock->expects($this->any())
->method('getHasError')
->willReturn(false);
$this->checkoutSessionMock->expects($this->any())
->method('getQuote')
->willReturn($quoteMock);
$this->checkoutSessionMock->expects($this->any())
->method('getPayment')
->willReturn($this->paymentMock);
$this->checkoutFactoryMock->expects($this->any())
->method('create')
->willReturn($this->checkoutMock);
$this->requestMock->expects($this->any())->method('getPost')->willReturn([]);
return $quoteMock;
}
public function testExecute()
{
$quoteId = 123;
$orderId = 'orderId';
$orderIncrementId = 125;
$quoteMock = $this->setupCart();
// $this->validatorMock->expects($this->once())->method('isValid')->willReturn(true);
$quoteMock->expects($this->once())
->method('getPayment')
->willReturn($this->paymentMock);
$this->paymentMock->expects($this->once())
->method('getMethod')
->willReturn('worldpay_payments_paypal');
// $this->checkoutMock->expects($this->once())
// ->method('place')
// ->with(null);
$this->checkoutSessionMock->expects($this->once())
->method('clearHelperData');
$quoteMock->expects($this->once())
->method('getId')
->willReturn($quoteId);
$this->checkoutSessionMock->expects($this->once())
->method('setLastQuoteId')
->with($quoteId)
->willReturnSelf();
$this->checkoutSessionMock->expects($this->once())
->method('setLastSuccessQuoteId')
->with($quoteId)
->willReturnSelf();
$orderMock = $this->getMockBuilder('\Magento\Sales\Model\Order')
->disableOriginalConstructor()
->getMock();
$orderMock->expects($this->once())
->method('getId')
->willReturn($orderId);
$orderMock->expects($this->once())
->method('getIncrementId')
->willReturn($orderIncrementId);
$this->checkoutMock->expects($this->once())
->method('getOrder')
->willReturn($orderMock);
$this->checkoutSessionMock->expects($this->once())
->method('setLastOrderId')
->with($orderId)
->willReturnSelf();
$this->checkoutSessionMock->expects($this->once())
->method('setLastRealOrderId')
->with($orderIncrementId)
->willReturnSelf();
$resultRedirect = $this->getMockBuilder('\Magento\Framework\Controller\Result\Redirect')
->disableOriginalConstructor()
->getMock();
$resultRedirect->expects($this->once())
->method('setPath')
->with('checkout/onepage/success')
->willReturnSelf();
$this->resultFactoryMock->expects($this->once())
->method('create')
->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT)
->willReturn($resultRedirect);
$this->assertEquals($resultRedirect, $this->controller->execute());
}
} | Worldpay/worldpay-magento2 | Test/Unit/Model/Controller/Apm/RedirectTest.php | PHP | mit | 6,661 |
using System;
using wallabag.Common;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace wallabag.Views
{
public sealed partial class AddLink : ContentDialog
{
public ApplicationSettings AppSettings { get { return ApplicationSettings.Instance; } }
public AddLink()
{
this.InitializeComponent();
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
}
}
| wangjun/windows-app | wallabag/wallabag.WindowsPhone/Views/AddLink.xaml.cs | C# | mit | 513 |
/**
* 乘法操作符
*/
define( function ( require, exports, modules ) {
var kity = require( "kity" );
return kity.createClass( 'MultiplicationOperator', {
base: require( "operator/binary-opr/left-right" ),
constructor: function () {
var ltr = new kity.Rect( 0, 20, 43, 3, 3 ).fill( "black"),
rtl = new kity.Rect( 20, 0, 3, 43, 3 ).fill( "black" );
this.callBase( "Multiplication" );
this.addOperatorShape( ltr.setAnchor( 22, 22 ).rotate( 45 ) );
this.addOperatorShape( rtl.setAnchor( 22, 22 ).rotate( 45 ) );
}
} );
} ); | Inzaghi2012/formula | src/operator/binary-opr/multiplication.js | JavaScript | mit | 636 |