code
stringlengths
4
1.01M
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta, abstractmethod from django.core.files import File from six import with_metaclass from django.utils.module_loading import import_string from rest_framework_tus import signals from .settings import TUS_SAVE_HANDLER_CLASS class AbstractUploadSaveHandler(with_metaclass(ABCMeta, object)): def __init__(self, upload): self.upload = upload @abstractmethod def handle_save(self): pass def run(self): # Trigger state change self.upload.start_saving() self.upload.save() # Initialize saving self.handle_save() def finish(self): # Trigger signal signals.saved.send(sender=self.__class__, instance=self) # Finish self.upload.finish() self.upload.save() class DefaultSaveHandler(AbstractUploadSaveHandler): destination_file_field = 'uploaded_file' def handle_save(self): # Save temporary field to file field file_field = getattr(self.upload, self.destination_file_field) file_field.save(self.upload.filename, File(open(self.upload.temporary_file_path))) # Finish upload self.finish() def get_save_handler(import_path=None): return import_string(import_path or TUS_SAVE_HANDLER_CLASS)
<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>
<?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 . '&amp;' . $param . '=${page}">' . $this->getPageCount() . '</a>): '; $result .= $this->isLinkToFirstPageAvailable() ? '<a class="page-first" href="' . $href . '&amp;' . $param . '=1">&laquo; Pierwsza</a> ' #: '<span class="page-first">&laquo; First</span> '; : ''; $result .= $this->isLinkToPreviousPageAvailable() ? '<a class="page-prev" href="' . $href . '&amp;' . $param . '=' . ($this->getPage() - 1) . '">&lsaquo; Poprzednia</a> ' #: '<span class="page-prev">&lsaquo; 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 . '&amp;' . $param . '=' . $page . '">' . $page . '</a>'; $result .= $page < $last ? ' | ' : ' '; } if ($cut && $last != $this->getPageCount()) { $result .= '... '; } $result .= $this->isLinkToNextPageAvailable() ? '<a class="page-next" href="' . $href . '&amp;' . $param . '=' . ($this->getPage() + 1) . '">Następna &rsaquo;</a> ' #: '<span class="page-next">Next &rsaquo;</span> '; : ''; $result .= $this->isLinkToLastPageAvailable() ? '<a class="page-last" href="' . $href . '&amp;' . $param . '=' . $this->getPageCount() . '">Ostatnia &raquo;</a>' #: '<span class="page-last">Last &raquo;</span>'; : ''; return $result; } }
#![allow(dead_code)] #![allow(unused_imports)] extern crate libc; extern crate sysctl; // Import the trait use sysctl::Sysctl; #[cfg(target_os = "freebsd")] const CTLNAME: &str = "net.inet.ip.forwarding"; #[cfg(target_os = "macos")] const CTLNAME: &str = "net.inet.ip.forwarding"; #[cfg(any(target_os = "linux", target_os = "android"))] const CTLNAME: &str = "net.ipv4.ip_forward"; fn main() { assert_eq!( unsafe { libc::geteuid() }, 0, "This example must be run as root" ); let ctl = sysctl::Ctl::new(CTLNAME).expect(&format!("could not get sysctl '{}'", CTLNAME)); let name = ctl.name().expect("could not get sysctl name"); println!("\nFlipping value of sysctl '{}'", name); let old_value = ctl.value_string().expect("could not get sysctl value"); println!("Current value is '{}'", old_value); let target_value = match old_value.as_ref() { "0" => "1", _ => "0", }; println!("Setting value to '{}'...", target_value); let new_value = ctl.set_value_string(target_value).unwrap_or_else(|e| { panic!("Could not set value. Error: {:?}", e); }); assert_eq!(new_value, target_value, "could not set value"); println!("OK. Now restoring old value '{}'...", old_value); let ret = ctl .set_value_string(&old_value) .expect("could not restore old value"); println!("OK. Value restored to {}.", ret); }
/****************************************************************************//** \file memAt25dd041a.c \brief Some commands for at25df041a implementation. \author Atmel Corporation: http://www.atmel.com \n Support email: avr@atmel.com Copyright (c) 2008-2011, Atmel Corporation. All rights reserved. Licensed under Atmel's Limited License Agreement (BitCloudTM). \internal History: 05/10/11 N. Fomin - Created *******************************************************************************/ /****************************************************************************** Includes section ******************************************************************************/ #include <types.h> #include <extMemReader.h> #include <spiMemInterface.h> #if EXTERNAL_MEMORY == AT25DF041A /****************************************************************************** Constants section ******************************************************************************/ const uint32_t imageStartAddress[POSITION_MAX] = {IMAGE1_START_ADDRESS, IMAGE2_START_ADDRESS}; /****************************************************************************** Implementations section ******************************************************************************/ /**************************************************************************//** \brief Check availability of the external flash. Reads vendor and chip ID from the external flash. \return true - correct memory, \n false - other ******************************************************************************/ bool memCheckMem(void) { uint64_t manufacId = RDID; GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_READ, (uint8_t *)&manufacId, sizeof(uint64_t)-3); GPIO_EXT_MEM_CS_set(); if (MANUFACTURER_ID == (uint8_t)(manufacId >> 8)) if ((DEVICE_ID_1 == (uint8_t)(manufacId >> 16)) && (DEVICE_ID_2 == (uint8_t)(manufacId >> 24)) && (EXT_STRING_LENGTH == (uint8_t)(manufacId >> 32))) return true; return false; } /**************************************************************************//** \brief Reads data from memory. \param[in] offset - internal flash address; \param[in] buffer - pointer to the data buffer; \param[in] length - number bytes for reading; ******************************************************************************/ void memReadData(uint32_t offset, uint8_t *data, uint16_t size) { uint8_t instruction = READ; offset = LITTLE_TO_BIG_ENDIAN(offset<<8); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE , &instruction, sizeof(uint8_t)); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE , (uint8_t *)&offset, sizeof(uint32_t)-1); spiMemTransac(SPI_TRANSACTION_TYPE_READ, data, size); GPIO_EXT_MEM_CS_set(); // release spi cs } #endif // EXTERNAL_MEMORY == AT25DF041A // eof memAt25df041a.c
// 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 .
<?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).'&nbsp;'.$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 */ ?>
package io.avalia.samba; import org.junit.Assert; import static org.junit.Assert.assertNotNull; import org.junit.Test; /** * *** IMPORTANT WARNING : DO NOT EDIT THIS FILE *** * * This file is used to specify what you have to implement. To check your work, * we will run our own copy of the automated tests. If you change this file, * then you will introduce a change of specification!!! * * @author Olivier Liechti */ public class IluTest { @Test public void anIluShouldMakeBum() { IInstrument ilu = new Ilu(); String sound = ilu.play(); Assert.assertEquals("bum", sound); } @Test public void anIluShouldBeDarkYellow() { IInstrument ilu = new Ilu(); String color = ilu.getColor(); Assert.assertEquals("dark yellow", color); } @Test public void anIluShouldLouderThanATrumpetAndAFluteCombined() { IInstrument trumpet = new Trumpet(); IInstrument flute = new Flute(); IInstrument ilu = new Ilu(); int trumpetVolume = trumpet.getSoundVolume(); int fluteVolume = flute.getSoundVolume(); int trumpetAndFluteVolumeCombined = fluteVolume + trumpetVolume; int iluVolume = ilu.getSoundVolume(); Assert.assertTrue(iluVolume > trumpetAndFluteVolumeCombined); } }
#!/usr/bin/env python # -*- coding: utf-8 -*- # # face_recognition 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 from unittest.mock import MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() MOCK_MODULES = ['face_recognition_models', 'Click', 'dlib', 'numpy', 'PIL'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # 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('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import face_recognition # -- 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'Face Recognition' copyright = u"2017, Adam Geitgey" # 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 = face_recognition.__version__ # The full version, including alpha/beta/rc tags. release = face_recognition.__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 = 'face_recognitiondoc' # -- 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', 'face_recognition.tex', u'Face Recognition Documentation', u'Adam Geitgey', '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', 'face_recognition', u'Face Recognition Documentation', [u'Adam Geitgey'], 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', 'face_recognition', u'Face Recognition Documentation', u'Adam Geitgey', 'face_recognition', '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
#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
export interface IEvent { EventId: number; Name: string; Description: string; StartTime: Date; EndTime: Date; }
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}".`); } } }
import Data.List import Data.Text hiding (intercalate, map) import System.Hclip import Text.ParserCombinators.Parsec -- | Strip, with Strings instead of Text for arguments trim :: String -> String trim = unpack . strip . pack -- | A single cell of a matrix body :: Parser String body = many1 $ noneOf "&\\" -- | A single row of the matrix row :: Parser [String] row = sepBy body (char '&') -- | A matrix parser (excluding wrappers) matrix :: Parser [[String]] matrix = sepBy row (try (string "\\\\")) -- | A wrapped matrix parser wrappedMatrix :: Parser [[String]] wrappedMatrix = do optional (try $ string "\\begin{bmatrix}") mat <- matrix optional (try $ string "\\end{bmatrix}") return mat -- | Trim every element of the matrix cleanUp :: [[String]] -> [[String]] cleanUp (x : xs) = map trim x : cleanUp xs cleanUp [] = [] -- | Generate a wolfram array from an array of arrays of strings wolfram :: [[String]] -> String wolfram x = "{" ++ wolfram' ++ "}" where wolfram' = intercalate ",\n " (map row x) row y = "{" ++ row' y ++ "}" row' y = intercalate ", " y main :: IO () main = do input <- getClipboard putStrLn $ "Got input: \n" ++ input ++ "\n" let result = parse wrappedMatrix "matrix" $ trim input case result of Left e -> putStrLn $ "Failed to parse input:\n" ++ show e Right mat -> do let s = wolfram $ cleanUp mat setClipboard s putStrLn $ "Success! Copied result to clipboard:\n" ++ s
/*----------------------------------------------------------------------------*/ /* 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); } }
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 }
class LightweightUserAgentParser VERSION = '1.6.0'.freeze end
<div class="grid-row"> <div class="column-two-thirds js-hidden" id="amount"> <br/> <div class="highlighted-event" style="padding: 60px; background-color: #28a197; color: #fff; text-align: center;"> <div style="font-size: 24px; font-weight: bold; clear:both;">Your State Pension will be</div> <div style="font-size: 56px; font-weight: bold;">£113.10 a week</div> </div> <div> <h3 class="heading-small"> How your weekly State Pension is made up: </h3> <table> <tbody> <tr> <td class="heading-small no-border">New State Pension</td> <td class="heading-small no-border align-right">&pound;86.34</td> </tr> <tr> <td>New State Pension is the State Pension Scheme for people who reach State Pension age on or after 6 April 2016. New State Pension amount is the weekly amount you can get based on the National Insurance contributions you have paid or have been credited with up to the full rate of new State Pension.<br/> <br/>National Insurance contributions or credits on your National Insurance record before and after 6 April 2016 have counted towards your new State Pension.</td> <td></td> </tr> <tr> <td class="heading-small no-border">Protected Payment</td> <td class="heading-small no-border">&pound;20.00</td> </tr> <tr> <td>Your Protected Payment is an extra amount on top of the full rate of the new State Pension. You will have a Protected Payment if one of the following applies: <br/> <br/>• Your starting amount was more than the full rate of the new State Pension. Your National Insurance record before 6 April 2016 was used to calculate your starting amount in the new scheme. <br/> <br/>• You have inherited some of your late spouse or civil partner’s State Pension and because of this, the amount of your award is more than the full rate of the new State Pension. </td> <td></td> </tr> <tr> <td class="heading-small no-border">Extra State Pension</td> <td class="heading-small no-border">&pound;6.76</td> </tr> <tr> <td>Extra State Pension because you put off getting your State Pension.</td> <td></td> </tr> </tbody> </table> </div> <fieldset> <legend> <span class="form-label"> </span> </legend> </fieldset> <br/> <div class="form-group"> <input type="submit" class="button" value="Add payment details"> <!-- <a href="bank-details" class="button" value="Submit">Continue</a> --> </div> </div> <!-- </form> --> </div> <div id="waiting"> <center><div class="loader">Loading...</div></div> </div> </div>
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); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>ComponentManger | Demo</title> <link href='https://fonts.googleapis.com/css?family=Crimson+Text' rel='stylesheet' type='text/css'> <style type="text/css"> * { font-family: 'Crimson Text', serif; } button { font-size: 1rem; } </style> <script src="https://code.jquery.com/jquery-3.1.0.slim.min.js" integrity="sha256-cRpWjoSOw5KcyIOaZNo4i6fZ9tKPhYYb6i5T9RSVJG8=" crossorigin="anonymous"></script> <script src="src/manager.js"></script> <script src="demo/jquery.loadKittens.js"></script> <script src="demo/jquery.fakeLatin.js"></script> </head> <body> <h1>Demo</h1> <button id="addComponent">Add random component</button> <button id="removeComponent">Remove last component</button> <div id="component-container"></div> <script type="text/javascript"> // Register the first component: a simple jQuery plugin that loads images of kittens ComponentManager.register( 'loadkittens', function(addedNode) { // If the plugins uses options, those can be passed to the plugin here $(addedNode).loadKittens(); }, function(removedNode) { // Call the destructor to allow the plugin to tear down $(removedNode).data('plugin_loadKittens').destroy(); } ); // Register the second component: a simple jQuery plugin that displays parts of "lorem ipsum" ComponentManager.register( 'fakelatin', function(addedNode) { $(addedNode).fakeLatin(); }, function(removedNode) { $(removedNode).data('plugin_fakeLatin').destroy(); } ); // Tell the component manager to start listening for changes to the DOM ComponentManager.init(); // UI code for this demo var addComponent = function() { var divElement = document.createElement('div'); var componentName = Math.round(Math.random()) === 1 ? 'loadkittens' : 'fakelatin'; divElement.innerHTML = '<div data-component-name="' + componentName + '"></div>'; document.body.querySelector('#component-container').appendChild(divElement); }; var removeComponent = function () { var container = document.body.querySelector('#component-container'); var components = container.childNodes; if (components.length) { container.removeChild(components[components.length - 1]); } }; document.querySelector('#addComponent').addEventListener('click', addComponent, false); document.querySelector('#removeComponent').addEventListener('click', removeComponent, false); </script> </body> </html>
require 'test_helper' describe Softlayer::Mock::Virtual::Guest do before(:each) { configure_connection } describe ".get_create_object_options" do it "return an account" do options = Softlayer::Mock::Virtual::Guest.get_create_object_options options.block_devices[60].item_price.hourly_recurring_fee.must_equal ".043" end end describe ".create_object" do it "return a virtual guest" do virtual_guest_attrs = { "hostname": "host1", "domain": "example.com", "start_cpus": 1, "max_memory": 1024, "hourly_billing_flag": true, "local_disk_flag": true, "operating_system_reference_code": "UBUNTU_LATEST" } virtual_guest = Softlayer::Mock::Virtual::Guest.create_object(virtual_guest_attrs) virtual_guest.must_be_kind_of Softlayer::Virtual::Guest virtual_guest.domain.must_equal "example.com" virtual_guest.hostname.must_equal "host1" end end end
(function(){ ///////////////////////////////////////////////////////////////////////// // // // client/helpers/config.js // // // ///////////////////////////////////////////////////////////////////////// // Accounts.ui.config({ // 1 passwordSignupFields: 'USERNAME_ONLY' // 2 }); // ///////////////////////////////////////////////////////////////////////// }).call(this);
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; } } }
<!DOCTYPE html > <html> <head> <title>InterpolationTag - threesixty.data.tags.InterpolationTag</title> <meta name="description" content="InterpolationTag - threesixty.data.tags.InterpolationTag" /> <meta name="keywords" content="InterpolationTag threesixty.data.tags.InterpolationTag" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'threesixty.data.tags.InterpolationTag'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <img alt="Trait" src="../../../lib/trait_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="threesixty">threesixty</a>.<a href="../package.html" class="extype" name="threesixty.data">data</a>.<a href="package.html" class="extype" name="threesixty.data.tags">tags</a></p> <h1>InterpolationTag</h1><h3><span class="morelinks"><div>Related Doc: <a href="package.html" class="extype" name="threesixty.data.tags">package tags</a> </div></span></h3><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">trait</span> </span> <span class="symbol"> <span class="name">InterpolationTag</span><span class="result"> extends <a href="Tag.html" class="extype" name="threesixty.data.tags.Tag">Tag</a></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p> Identifies whether data is interpolated data or from the original dataset </p></div><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="Tag.html" class="extype" name="threesixty.data.tags.Tag">Tag</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div><div class="toggleContainer block"> <span class="toggle">Known Subclasses</span> <div class="subClasses hiddenContent"><a href="Interpolated$.html" class="extype" name="threesixty.data.tags.Interpolated">Interpolated</a>, <a href="Original$.html" class="extype" name="threesixty.data.tags.Original">Original</a></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="threesixty.data.tags.InterpolationTag"><span>InterpolationTag</span></li><li class="in" name="threesixty.data.tags.Tag"><span>Tag</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@!=(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@##():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@==(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@asInstanceOf[T0]:T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@clone():Object" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@equals(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@finalize():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@getClass():Class[_]" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@hashCode():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@isInstanceOf[T0]:Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@notify():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@notifyAll():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@synchronized[T0](x$1:=&gt;T0):T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@toString():String" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@wait():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#threesixty.data.tags.InterpolationTag@wait(x$1:Long):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="threesixty.data.tags.Tag"> <h3>Inherited from <a href="Tag.html" class="extype" name="threesixty.data.tags.Tag">Tag</a></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
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(); } } }
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; } }
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() }
/** * 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(); } }; })();
# Page ![Sample](https://github.com/nans/devdocs/blob/master/Magestudy/Page.png "Frontend page screenshot") Shows how create simple page (frontend) in Magento 2 Link: http:://YOUR_SITE.domain/index.php/page/test/ License ---- MIT
'use strict'; export default function routes($routeProvider) { 'ngInject'; $routeProvider.when('/new_component', { template: '<about></about>' }); $routeProvider.when('/new_component/:somethingToPrint', { template: '<about></about>' }); }
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
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) ?
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); } } }
<?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; } }
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; } } }
<?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; } }
<?php namespace Doctrine\Tests\Common\Annotations; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\DocParser; use Doctrine\Common\Annotations\Reader; use Doctrine\Tests\Common\Annotations\Fixtures\Annotation\SingleUseAnnotation; use Doctrine\Tests\Common\Annotations\Fixtures\ClassWithFullPathUseStatement; use Doctrine\Tests\Common\Annotations\Fixtures\ClassWithImportedIgnoredAnnotation; use Doctrine\Tests\Common\Annotations\Fixtures\ClassWithPHPCodeSnifferAnnotation; use Doctrine\Tests\Common\Annotations\Fixtures\ClassWithPhpCsSuppressAnnotation; use Doctrine\Tests\Common\Annotations\Fixtures\ClassWithPHPStanGenericsAnnotations; use Doctrine\Tests\Common\Annotations\Fixtures\IgnoredNamespaces\AnnotatedAtClassLevel; use Doctrine\Tests\Common\Annotations\Fixtures\IgnoredNamespaces\AnnotatedAtMethodLevel; use Doctrine\Tests\Common\Annotations\Fixtures\IgnoredNamespaces\AnnotatedAtPropertyLevel; use Doctrine\Tests\Common\Annotations\Fixtures\IgnoredNamespaces\AnnotatedWithAlias; use InvalidArgumentException; use LogicException; use ReflectionClass; use ReflectionFunction; use function class_exists; use function spl_autoload_register; use function spl_autoload_unregister; class AnnotationReaderTest extends AbstractReaderTest { /** * @return AnnotationReader */ protected function getReader(?DocParser $parser = null): Reader { return new AnnotationReader($parser); } public function testMethodAnnotationFromTrait(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassUsesTrait::class); $annotations = $reader->getMethodAnnotations($ref->getMethod('someMethod')); self::assertInstanceOf(Bar\Autoload::class, $annotations[0]); $annotations = $reader->getMethodAnnotations($ref->getMethod('traitMethod')); self::assertInstanceOf(Fixtures\Annotation\Autoload::class, $annotations[0]); } public function testMethodAnnotationFromOverwrittenTrait(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassOverwritesTrait::class); $annotations = $reader->getMethodAnnotations($ref->getMethod('traitMethod')); self::assertInstanceOf(Bar2\Autoload::class, $annotations[0]); } public function testPropertyAnnotationFromTrait(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassUsesTrait::class); $annotations = $reader->getPropertyAnnotations($ref->getProperty('aProperty')); self::assertInstanceOf(Bar\Autoload::class, $annotations[0]); $annotations = $reader->getPropertyAnnotations($ref->getProperty('traitProperty')); self::assertInstanceOf(Fixtures\Annotation\Autoload::class, $annotations[0]); } public function testOmitNotRegisteredAnnotation(): void { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $reader = $this->getReader($parser); $ref = new ReflectionClass(Fixtures\ClassWithNotRegisteredAnnotationUsed::class); $annotations = $reader->getMethodAnnotations($ref->getMethod('methodWithNotRegisteredAnnotation')); self::assertEquals([], $annotations); } public function testClassAnnotationSupportsSelfAccessorForConstants(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassWithAnnotationWithSelfConstantReference::class); $annotations = $reader->getClassAnnotations($ref); self::assertCount(1, $annotations); $annotation = $annotations[0]; self::assertInstanceOf(Fixtures\AnnotationWithConstants::class, $annotation); self::assertEquals( $annotation->value, Fixtures\ClassWithAnnotationWithSelfConstantReference::VALUE_FOR_CLASS ); } public function testPropertyAnnotationSupportsSelfAccessorForConstants(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassWithAnnotationWithSelfConstantReference::class); $classProperty = $ref->getProperty('classProperty'); $classAnnotation = $reader->getPropertyAnnotation($classProperty, Fixtures\AnnotationWithConstants::class); self::assertNotNull($classAnnotation); self::assertEquals( $classAnnotation->value, Fixtures\ClassWithAnnotationWithSelfConstantReference::VALUE_FOR_CLASS ); $traitProperty = $ref->getProperty('traitProperty'); $traitAnnotation = $reader->getPropertyAnnotation($traitProperty, Fixtures\AnnotationWithConstants::class); self::assertNotNull($traitAnnotation); self::assertEquals( $traitAnnotation->value, Fixtures\ClassWithAnnotationWithSelfConstantReference::VALUE_FOR_TRAIT ); } public function testMethodAnnotationSupportsSelfAccessorForConstants(): void { $reader = $this->getReader(); $ref = new ReflectionClass(Fixtures\ClassWithAnnotationWithSelfConstantReference::class); $classMethod = $ref->getMethod('classMethod'); $classAnnotation = $reader->getMethodAnnotation($classMethod, Fixtures\AnnotationWithConstants::class); self::assertNotNull($classAnnotation); self::assertEquals( $classAnnotation->value, Fixtures\ClassWithAnnotationWithSelfConstantReference::VALUE_FOR_CLASS ); $traitMethod = $ref->getMethod('traitMethod'); $traitAnnotation = $reader->getMethodAnnotation($traitMethod, Fixtures\AnnotationWithConstants::class); self::assertNotNull($traitAnnotation); self::assertEquals( $traitAnnotation->value, Fixtures\ClassWithAnnotationWithSelfConstantReference::VALUE_FOR_TRAIT ); } /** * @group 45 * @runInSeparateProcess */ public function testClassAnnotationIsIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(AnnotatedAtClassLevel::class); $reader::addGlobalIgnoredNamespace('SomeClassAnnotationNamespace'); self::assertEmpty($reader->getClassAnnotations($ref)); } /** * @group 45 * @runInSeparateProcess */ public function testMethodAnnotationIsIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(AnnotatedAtMethodLevel::class); $reader::addGlobalIgnoredNamespace('SomeMethodAnnotationNamespace'); self::assertEmpty($reader->getMethodAnnotations($ref->getMethod('test'))); } /** * @group 45 * @runInSeparateProcess */ public function testPropertyAnnotationIsIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(AnnotatedAtPropertyLevel::class); $reader::addGlobalIgnoredNamespace('SomePropertyAnnotationNamespace'); self::assertEmpty($reader->getPropertyAnnotations($ref->getProperty('property'))); } /** * @group 244 * @runInSeparateProcess */ public function testAnnotationWithAliasIsIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(AnnotatedWithAlias::class); $reader::addGlobalIgnoredNamespace('SomePropertyAnnotationNamespace'); self::assertEmpty($reader->getPropertyAnnotations($ref->getProperty('property'))); } public function testClassWithFullPathUseStatement(): void { if (class_exists(SingleUseAnnotation::class, false)) { throw new LogicException( 'The SingleUseAnnotation must not be used in other tests for this test to be useful.' . 'If the class is already loaded then the code path that finds the class to load is not used and ' . 'this test becomes useless.' ); } $reader = $this->getReader(); $ref = new ReflectionClass(ClassWithFullPathUseStatement::class); $annotations = $reader->getClassAnnotations($ref); self::assertInstanceOf(SingleUseAnnotation::class, $annotations[0]); } public function testPhpCsSuppressAnnotationIsIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(ClassWithPhpCsSuppressAnnotation::class); self::assertEmpty($reader->getMethodAnnotations($ref->getMethod('foo'))); } public function testGloballyIgnoredAnnotationNotIgnored(): void { $reader = $this->getReader(); $class = new ReflectionClass(Fixtures\ClassDDC1660::class); $testLoader = static function (string $className): bool { if ($className === 'since') { throw new InvalidArgumentException( 'Globally ignored annotation names should never be passed to an autoloader.' ); } return false; }; spl_autoload_register($testLoader, true, true); try { self::assertEmpty($reader->getClassAnnotations($class)); } finally { spl_autoload_unregister($testLoader); } } public function testPHPCodeSnifferAnnotationsAreIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(ClassWithPHPCodeSnifferAnnotation::class); self::assertEmpty($reader->getClassAnnotations($ref)); } public function testPHPStanGenericsAnnotationsAreIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(ClassWithPHPStanGenericsAnnotations::class); self::assertEmpty($reader->getClassAnnotations($ref)); self::assertEmpty($reader->getPropertyAnnotations($ref->getProperty('bar'))); self::assertEmpty($reader->getMethodAnnotations($ref->getMethod('foo'))); $this->expectException('\Doctrine\Common\Annotations\AnnotationException'); $this->expectExceptionMessage( '[Semantical Error] The annotation "@Template" in method' . ' Doctrine\Tests\Common\Annotations\Fixtures\ClassWithPHPStanGenericsAnnotations' . '::twigTemplateFunctionName() was never imported.' ); self::assertEmpty($reader->getMethodAnnotations($ref->getMethod('twigTemplateFunctionName'))); } public function testImportedIgnoredAnnotationIsStillIgnored(): void { $reader = $this->getReader(); $ref = new ReflectionClass(ClassWithImportedIgnoredAnnotation::class); self::assertEmpty($reader->getMethodAnnotations($ref->getMethod('something'))); } public function testFunctionsAnnotation(): void { $reader = $this->getReader(); $ref = new ReflectionFunction('Doctrine\Tests\Common\Annotations\Fixtures\foo'); $annotations = $reader->getFunctionAnnotations($ref); self::assertCount(1, $annotations); self::assertInstanceOf(Fixtures\Annotation\Autoload::class, $annotations[0]); } public function testFunctionAnnotation(): void { $reader = $this->getReader(); $ref = new ReflectionFunction('Doctrine\Tests\Common\Annotations\Fixtures\foo'); $annotation = $reader->getFunctionAnnotation($ref, Fixtures\Annotation\Autoload::class); self::assertInstanceOf(Fixtures\Annotation\Autoload::class, $annotation); } }
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()); } }
/* 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; };
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(); }
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
## Prerequisites Before you begin: * [Sign up for and configure an account with Salesforce](https://www.salesforce.com/). * [Create a Salesforce Sandbox](https://help.salesforce.com/articleView?id=data_sandbox_create.htm&type=5).
'use strict'; angular.module('springangularwayApp') .config(function ($stateProvider) { $stateProvider .state('configuration', { parent: 'admin', url: '/configuration', data: { roles: ['ROLE_ADMIN'], pageTitle: 'configuration.title' }, views: { 'content@': { templateUrl: 'scripts/app/admin/configuration/configuration.html', controller: 'ConfigurationController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('configuration'); return $translate.refresh(); }] } }); });
{% extends 'base.html' %} {% load i18n %} {% block title %}{% trans "Signup" %} wtf{% endblock %} {% block content %} <div class="panel panel-primary"> <div class="panel-heading">Sign up</div> <div class="panel-body"> <form action='' method="post" class="form-horizontal"> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} {{ field.errors }} {% comment %} Displaying checkboxes differently {% endcomment %} {% if field.name == 'tos' %} <p class="checkbox"> <label for="id_{{ field.name }}">{{ field }} {{ field.label }}</label> </p> {% else %} <div class="form-group"> <div class='col-md-3'> {{ field.label_tag }} </div> <div class="col-md-3"> {{ field }} </div> </div> {% endif %} {% endfor %} <input class="btn btn-info" type="submit" value="{% trans "Signup"%}" /> </form> </div> </div> {% endblock %}
<!DOCTYPE html> <!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) --> <!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca --> <head> <!-- Title begins / Début du titre --> <title> Dalley Froggatt Heritage Conservation Services - Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada </title> <!-- Title ends / Fin du titre --> <!-- Meta-data begins / Début des métadonnées --> <meta charset="utf-8" /> <meta name="dcterms.language" title="ISO639-2" content="eng" /> <meta name="dcterms.title" content="" /> <meta name="description" content="" /> <meta name="dcterms.description" content="" /> <meta name="dcterms.type" content="report, data set" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.issued" title="W3CDTF" content="" /> <meta name="dcterms.modified" title="W3CDTF" content="" /> <meta name="keywords" content="" /> <meta name="dcterms.creator" content="" /> <meta name="author" content="" /> <meta name="dcterms.created" title="W3CDTF" content="" /> <meta name="dcterms.publisher" content="" /> <meta name="dcterms.audience" title="icaudience" content="" /> <meta name="dcterms.spatial" title="ISO3166-1" content="" /> <meta name="dcterms.spatial" title="gcgeonames" content="" /> <meta name="dcterms.format" content="HTML" /> <meta name="dcterms.identifier" title="ICsiteProduct" content="536" /> <!-- EPI-11240 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- MCG-202 --> <meta content="width=device-width,initial-scale=1" name="viewport"> <!-- EPI-11567 --> <meta name = "format-detection" content = "telephone=no"> <!-- EPI-12603 --> <meta name="robots" content="noarchive"> <!-- EPI-11190 - Webtrends --> <script> var startTime = new Date(); startTime = startTime.getTime(); </script> <!--[if gte IE 9 | !IE ]><!--> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css"> <!--<![endif]--> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css"> <!--[if lt IE 9]> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" /> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script> <![endif]--> <!--[if lte IE 9]> <![endif]--> <noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <script>dataLayer1 = [];</script> <!-- End Google Tag Manager --> <!-- EPI-11235 --> <link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body class="home" vocab="http://schema.org/" typeof="WebPage"> <!-- EPIC HEADER BEGIN --> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script> <!-- End Google Tag Manager --> <!-- EPI-12801 --> <span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span> <ul id="wb-tphp"> <li class="wb-slc"> <a class="wb-sl" href="#wb-cont">Skip to main content</a> </li> <li class="wb-slc visible-sm visible-md visible-lg"> <a class="wb-sl" href="#wb-info">Skip to "About this site"</a> </li> </ul> <header role="banner"> <div id="wb-bnr" class="container"> <section id="wb-lng" class="visible-md visible-lg text-right"> <h2 class="wb-inv">Language selection</h2> <div class="row"> <div class="col-md-12"> <ul class="list-inline mrgn-bttm-0"> <li><a href="nvgt.do?V_TOKEN=1492279328057&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=12837&V_SEARCH.docsStart=12836&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/rgstr.sec?_flId?_flxKy=e1s1&amp;estblmntNo=234567041301&amp;profileId=61&amp;_evId=bck&amp;lang=eng&amp;V_SEARCH.showStricts=false&amp;prtl=1&amp;_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li> </ul> </div> </div> </section> <div class="row"> <div class="brand col-xs-8 col-sm-9 col-md-6"> <a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a> </div> <section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn"> <h2>Search and menus</h2> <ul class="list-inline text-right chvrn"> <li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li> </ul> <div id="mb-pnl"></div> </section> <!-- Site Search Removed --> </div> </div> <nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement"> <h2 class="wb-inv">Topics menu</h2> <div class="container nvbar"> <div class="row"> <ul class="list-inline menu"> <li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li> <li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li> <li><a href="https://travel.gc.ca/">Travel</a></li> <li><a href="https://www.canada.ca/en/services/business.html">Business</a></li> <li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li> <li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li> <li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li> <li><a href="https://www.canada.ca/en/services.html">More services</a></li> </ul> </div> </div> </nav> <!-- EPIC BODY BEGIN --> <nav role="navigation" id="wb-bc" class="" property="breadcrumb"> <h2 class="wb-inv">You are here:</h2> <div class="container"> <div class="row"> <ol class="breadcrumb"> <li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li> <li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li> <li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li> </ol> </div> </div> </nav> </header> <main id="wb-cont" role="main" property="mainContentOfPage" class="container"> <!-- End Header --> <!-- Begin Body --> <!-- Begin Body Title --> <!-- End Body Title --> <!-- Begin Body Head --> <!-- End Body Head --> <!-- Begin Body Content --> <br> <!-- Complete Profile --> <!-- Company Information above tabbed area--> <input id="showMore" type="hidden" value='more'/> <input id="showLess" type="hidden" value='less'/> <h1 id="wb-cont"> Company profile - Canadian Company Capabilities </h1> <div class="profileInfo hidden-print"> <ul class="list-inline"> <li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&amp;rstBtn.x=" class="btn btn-link">New Search</a>&nbsp;|</li> <li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do"> <input type="hidden" name="lang" value="eng" /> <input type="hidden" name="profileId" value="" /> <input type="hidden" name="prtl" value="1" /> <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" /> <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" /> <input type="hidden" name="V_SEARCH.depth" value="1" /> <input type="hidden" name="V_SEARCH.showStricts" value="false" /> <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" /> </form></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=12835&amp;V_DOCUMENT.docRank=12836&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492279346568&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567106505&amp;profileId=&amp;key.newSearchLabel=">Previous Company</a></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=12837&amp;V_DOCUMENT.docRank=12838&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492279346568&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567002397&amp;profileId=&amp;key.newSearchLabel=">Next Company</a></li> </ul> </div> <details> <summary>Third-Party Information Liability Disclaimer</summary> <p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p> </details> <h2> Dalley Froggatt Heritage Conservation Services </h2> <div class="row"> <div class="col-md-5"> <h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2> <p>Dalley Froggatt Heritage Conservation Services</p> <div class="mrgn-tp-md"></div> <p class="mrgn-bttm-0" ><a href="http://www.dfhcs.com" target="_blank" title="Website URL">http://www.dfhcs.com</a></p> <p><a href="mailto:dfhcs@mts.net" title="dfhcs@mts.net">dfhcs@mts.net</a></p> </div> <div class="col-md-4 mrgn-sm-sm"> <h2 class="h5 mrgn-bttm-0">Mailing Address:</h2> <address class="mrgn-bttm-md"> 217 Lipton St<br/> WINNIPEG, Manitoba<br/> R3G 2G8 <br/> </address> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (204) 223-3056 </p> <p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>: (204) 261-4827</p> </div> <div class="col-md-3 mrgn-tp-md"> </div> </div> <div class="row mrgn-tp-md mrgn-bttm-md"> <div class="col-md-12"> <h2 class="wb-inv">Company Profile</h2> <br> DFHCS provides expert conservation services and high quality products that assist in the preservation, display and accessibility of heritage, private, and archival collections.<br> </div> </div> <!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> --> <div class="wb-tabs ignore-session"> <div class="tabpanels"> <details id="details-panel1"> <summary> Full profile </summary> <!-- Tab 1 --> <h2 class="wb-invisible"> Full profile </h2> <!-- Contact Information --> <h3 class="page-header"> Contact information </h3> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Jane Dalley </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Director </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (204) 223-3056 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (204) 261-4827 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> dfhcs@mts.net </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Company Description --> <h3 class="page-header"> Company description </h3> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 541690 - Other Scientific and Technical Consulting Services </div> </div> <div class="row"> <div class="col-md-5"> <strong> Alternate Industries (NAICS): </strong> </div> <div class="col-md-7"> 541619 - Other Management Consulting Services<br> </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> </section> <!-- Products / Services / Licensing --> <h3 class="page-header"> Product / Service / Licensing </h3> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> Storage and Display Products<br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> Products for the preservation, display and accessibility of heritage, private and archival collections. <br> <br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Conservation of cultural heritage <br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> The staff of DFHCS assist museum, archival and other heritage professionals in preserving buildings, sites, collections and holdings in a practical and cost-effective manner through planning and assessment. <br> •We offer environmental monitoring and control, pest management, disaster response and business resumption, and the conservation treatment of museum and archival collections. <br> <br> <br> </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Technology Profile --> <!-- Market Profile --> <!-- Sector Information --> <details class="mrgn-tp-md mrgn-bttm-md"> <summary> Third-Party Information Liability Disclaimer </summary> <p> Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements. </p> </details> </details> <details id="details-panel2"> <summary> Contacts </summary> <h2 class="wb-invisible"> Contact information </h2> <!-- Contact Information --> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Jane Dalley </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Director </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (204) 223-3056 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (204) 261-4827 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> dfhcs@mts.net </div> </div> </section> </details> <details id="details-panel3"> <summary> Description </summary> <h2 class="wb-invisible"> Company description </h2> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 541690 - Other Scientific and Technical Consulting Services </div> </div> <div class="row"> <div class="col-md-5"> <strong> Alternate Industries (NAICS): </strong> </div> <div class="col-md-7"> 541619 - Other Management Consulting Services<br> </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> </section> </details> <details id="details-panel4"> <summary> Products, services and licensing </summary> <h2 class="wb-invisible"> Product / Service / Licensing </h2> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> Storage and Display Products<br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> Products for the preservation, display and accessibility of heritage, private and archival collections. <br> <br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Conservation of cultural heritage <br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> The staff of DFHCS assist museum, archival and other heritage professionals in preserving buildings, sites, collections and holdings in a practical and cost-effective manner through planning and assessment. <br> •We offer environmental monitoring and control, pest management, disaster response and business resumption, and the conservation treatment of museum and archival collections. <br> <br> <br> </div> </div> </section> </details> </div> </div> <div class="row"> <div class="col-md-12 text-right"> Last Update Date 2016-04-19 </div> </div> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z --> <!-- End Body Content --> <!-- Begin Body Foot --> <!-- End Body Foot --> <!-- END MAIN TABLE --> <!-- End body --> <!-- Begin footer --> <div class="row pagedetails"> <div class="col-sm-5 col-xs-12 datemod"> <dl id="wb-dtmd"> <dt class=" hidden-print">Date Modified:</dt> <dd class=" hidden-print"> <span><time>2017-03-02</time></span> </dd> </dl> </div> <div class="clear visible-xs"></div> <div class="col-sm-4 col-xs-6"> </div> <div class="col-sm-3 col-xs-6 text-right"> </div> <div class="clear visible-xs"></div> </div> </main> <footer role="contentinfo" id="wb-info"> <nav role="navigation" class="container wb-navcurr"> <h2 class="wb-inv">About government</h2> <!-- EPIC FOOTER BEGIN --> <!-- EPI-11638 Contact us --> <ul class="list-unstyled colcount-sm-2 colcount-md-3"> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&amp;from=Industries">Contact us</a></li> <li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li> <li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li> <li><a href="https://www.canada.ca/en/news.html">News</a></li> <li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li> <li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li> <li><a href="http://pm.gc.ca/eng">Prime Minister</a></li> <li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li> <li><a href="http://open.canada.ca/en/">Open government</a></li> </ul> </nav> <div class="brand"> <div class="container"> <div class="row"> <nav class="col-md-10 ftr-urlt-lnk"> <h2 class="wb-inv">About this site</h2> <ul> <li><a href="https://www.canada.ca/en/social.html">Social media</a></li> <li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li> <li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li> </ul> </nav> <div class="col-xs-6 visible-sm visible-xs tofpg"> <a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a> </div> <div class="col-xs-6 col-md-2 text-right"> <object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object> </div> </div> </div> </div> </footer> <!--[if gte IE 9 | !IE ]><!--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script> <!-- EPI-10519 --> <span class="wb-sessto" data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span> <script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script> <!-- EPI-11190 - Webtrends --> <script src="/eic/home.nsf/js/webtrends.js"></script> <script>var endTime = new Date();</script> <noscript> <div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&amp;WT.js=No&amp;WT.tv=9.4.0&amp;dcssip=www.ic.gc.ca"/></div> </noscript> <!-- /Webtrends --> <!-- JS deps --> <script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script> <!-- EPI-11262 - Util JS --> <script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script> <!-- EPI-11383 --> <script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script> <span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span> </body></html> <!-- End Footer --> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z -->
var path = require('path') var webpack = require('webpack') // Phaser webpack config var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/') var phaser = path.join(phaserModule, 'build/custom/phaser-split.js') var pixi = path.join(phaserModule, 'build/custom/pixi.js') var p2 = path.join(phaserModule, 'build/custom/p2.js') var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')) }) module.exports = { entry: { app: [ 'babel-polyfill', path.resolve(__dirname, 'src/main.js') ], vendor: ['pixi', 'p2', 'phaser', 'webfontloader', 'react'] }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: 'bundle.js' }, plugins: [ definePlugin, new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.optimize.UglifyJsPlugin({ drop_console: true, minimize: true, output: { comments: false } }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor'/* chunkName= */, filename: 'vendor.bundle.js'/* filename= */}) ], module: { rules: [ { test: /\.js$/, use: ['babel-loader'], include: path.join(__dirname, 'src') }, { test: /pixi\.js/, use: ['expose-loader?PIXI'] }, { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] }, { test: /p2\.js/, use: ['expose-loader?p2'] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['react', 'es2015']} } ] }, node: { fs: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { 'phaser': phaser, 'pixi': pixi, 'p2': p2 } } }
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
/**** JQuery Mobile default overriding ****/ .ui-block-a, .ui-block-b, .ui-block-c, .ui-block-d, .ui-block-e { padding: 3px; } .label-value { font-weight: 700; } .device_container { /* background-color: red; */ border: 2pt solid; // #38f; border-radius: 0.4em; }
# Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. Fixes # (issue) ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update # How Has This Been Tested? Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration # Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] Any dependent changes have been merged and published in downstream modules
* { text-indent:-9999px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } html { background:black; color:black; } body { display:block; position:fixed; color:#DDD; overflow:hidden; width: 100%; height: 100%; top: 0px; right: 0px; display: flex; justify-content: center; /* align horizontal */ align-items: center; /* align vertical */ } h1 { text-indent:0px; font-family: 'Montserrat', sans-serif; font-weight: bold; line-height:0px; font-size:280px; text-align: center; } a { color:white; text-decoration:none; text-align: center; } code { text-indent:0px; display:block; font-size:20px; }
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(); }); });
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; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="/static/img/ruby.ico" /> <title>笨方法学Ruby第二十七天 - LJZN</title> <meta name="author" content="LJZN" /> <meta name="description" content="笨方法学Ruby第二十七天" /> <meta name="keywords" content="笨方法学Ruby第二十七天, LJZN, LRTHW" /> <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml"> <!-- syntax highlighting CSS --> <link rel="stylesheet" href="/static/css/syntax.css"> <!-- Bootstrap core CSS --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link rel="stylesheet" href="/static/css/main.css"> </head> <body> <div class="container"> <div class="col-sm-3"> <a href="/"><img id="about" src="/static/img/ruby.png" height="75px" width="75px" /></a> <h1 class="author-name">LJZN</h1> <div id="about"> 每天更新Rails练习项目到Github~ </div> <hr size=2> &raquo; <a href="/">Home</a> <br /> &raquo; <a href="/category/original">Category</a> <br /> &raquo; <a class="about" href="/about/">About Me</a><br /> &raquo; <a class="about" href="https://github.com/ljzn">Github</a><br /> </div> <div class="col-sm-8 col-offset-1"> <h1>笨方法学Ruby第二十七天</h1> <span class="time">28 Jun 2016</span> <span class="categories"> &raquo; <a href="/category/LRTHW">LRTHW</a> </span> <div class="content"> <div class="post"> <figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># 或非什么都不会才是真的</span> <span class="c1"># 与非什么都会才是假的</span></code></pre></figure> </div> </div> <div class="panel-body"> <h4>Related Posts</h4> <ul> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/10/lrhw-50.html">50sinatra建造网站</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/09/lrhw-49.html">49创建句子</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-48.html">48进阶用户输入</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-47.html">47自动化测试</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/06/lrhw-46.html">46项目骨架</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> <li class="relatedPost"> <a href="https://ljzn.github.io/lrthw/2016/07/05/lrhw-45.html">45制作一个游戏</a> (Categories: <a href="/category/LRTHW">LRTHW</a>) </li> </ul> </div> <div class="PageNavigation"> <a class="prev" href="/lrthw/2016/06/28/lrhw-26.html">&laquo; 笨方法学Ruby第二十六天</a> <a class="next" href="/lrthw/2016/06/28/lrhw-28.html">笨方法学Ruby第二十八天 &raquo;</a> </div> <div class="disqus-comments"> <div id="disqus_thread"></div> <script> (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//ljzn.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript> </div> <footer> &copy; LJZN - <a href="https://github.com/ljzn">https://github.com/ljzn</a> - Powered by Jekyll. </footer> </div><!-- end /.col-sm-8 --> </div><!-- end /.container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script id="dsq-count-scr" src="//ljzn.disqus.com/count.js" async></script> </body> </html>
module GeoCalculator VERSION = '0.0.1' end
{% include head.html %} {% include sidebar.html %} <div class="content"> <main id="main"> <header role="banner" class="header"> <h1 class="heading"><span class="heading__intro">{{ page.intro }}</span>{{ page.heading }}</h1> </header> {{ content }} </main> {% include footer.html %} </div> <!-- Script includes --> <script src="../assets/js/main.min.js"></script> <!-- Cookie banner JS --> <script> window.addEventListener("load", function(){ window.cookieconsent.initialise({})}); </script> <!-- <script> (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//cathyduttoncouk.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> --> <!-- <script id="dsq-count-scr" src="//cathydutton.disqus.com/count.js" async></script> --> <!-- <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> --> <!-- New blog --> <!-- <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5080086399779144" data-ad-slot="8794319910" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> --> <script> if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/serviceWorker.js').then(function(registration) { }).catch(function(err) { }); }); } </script> </body> </html>
<!DOCTYPE html> <html> {% include head.html %} <body> <header> {% include header.html %} </header> <main> <div id="main-content"> {{ content }} {% include footer.html %} </div> </main> <div class="ripple-wrapper"> <div class="ripple"></div> </div> {% include js.html %} </body> </html>
/** <slate_header> author: Kishore Reddy url: https://github.com/kishorereddy/scala-slate copyright: 2015 Kishore Reddy license: https://github.com/kishorereddy/scala-slate/blob/master/LICENSE.md desc: a scala micro-framework usage: Please refer to license on github for more info. </slate_header> */ package slate.http import akka.http.scaladsl.model.HttpRequest /** * Akka Http utilities */ object HttpUtils { def buildUriParts(req: HttpRequest): String = { val nl = "\r\n" val result = "uri.host : " + req.getUri().host() + nl + "uri.path : " + req.getUri().path() + nl + "uri.port : " + req.getUri().port() + nl + "uri.params : " + buildParams(req.getUri() ) + nl + "uri.query : " + req.getUri().queryString() + nl + "uri.scheme : " + req.getUri().scheme() + nl + "uri.userinfo : " + req.getUri().userInfo() + nl result } def buildParams( uri: akka.http.javadsl.model.Uri ) : String = { val params = uri.parameterMap() if(params.containsKey("name")) return params.get("name") "none" } }
<?php namespace Tech\TBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class PersonarelformControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/PersonaForm/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /PersonaForm/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'tech_tbundle_personarelformtype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'tech_tbundle_personarelformtype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
# -*- 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,), ), ]
/****************************************************************************/ /* imaxdiv v15.12.3 */ /* */ /* Copyright (c) 2003-2016 Texas Instruments Incorporated */ /* http://www.ti.com/ */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* */ /* Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* */ /* Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* Neither the name of Texas Instruments Incorporated nor the names */ /* of its contributors may be used to endorse or promote products */ /* derived from this software without specific prior written */ /* permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */ /* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */ /* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */ /* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */ /* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */ /* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */ /* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /****************************************************************************/ #include <inttypes.h> imaxdiv_t imaxdiv(intmax_t num, intmax_t den) { imaxdiv_t rv; rv.quot = num / den; rv.rem = num - (rv.quot * den); return rv; }
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
/** * @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
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
 $MyPath = Split-Path $MyInvocation.MyCommand.Path $AWSPath = 'D:\Nana\Official\AWS' $ModulesFolder = 'D:\Nana\Content\Modules' $BakeryFolder = 'D:\Nana\Content\BakeryWebsite' $KeyFilePath = 'D:\Nana\Official\AWS\NanasTestKeyPair.pem' #endregion Initialization . "$MyPath\Install-WMF.ps1"
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" /> <title>DataBuffer | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto+Condensed"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../../../../../assets/css/default.css?v=5" rel="stylesheet" type="text/css"> <!-- FULLSCREEN STYLESHEET --> <link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../../../../../"; var metaTags = []; var devsite = false; </script> <script src="../../../../../../../assets/js/docs.js?v=3" type="text/javascript"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-5831155-1', 'android.com'); ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker); ga('send', 'pageview'); ga('universal.send', 'pageview'); // Send page view for new tracker. </script> </head> <body class="gc-documentation develop reference" itemscope itemtype="http://schema.org/Article"> <div id="doc-api-level" class="" style="display:none"></div> <a name="top"></a> <a name="top"></a> <!-- dialog to prompt lang pref change when loaded from hardcoded URL <div id="langMessage" style="display:none"> <div> <div class="lang en"> <p>You requested a page in English, would you like to proceed with this language setting?</p> </div> <div class="lang es"> <p>You requested a page in Spanish (Español), would you like to proceed with this language setting?</p> </div> <div class="lang ja"> <p>You requested a page in Japanese (日本語), would you like to proceed with this language setting?</p> </div> <div class="lang ko"> <p>You requested a page in Korean (한국어), would you like to proceed with this language setting?</p> </div> <div class="lang ru"> <p>You requested a page in Russian (Русский), would you like to proceed with this language setting?</p> </div> <div class="lang zh-cn"> <p>You requested a page in Simplified Chinese (简体中文), would you like to proceed with this language setting?</p> </div> <div class="lang zh-tw"> <p>You requested a page in Traditional Chinese (繁體中文), would you like to proceed with this language setting?</p> </div> <a href="#" class="button yes" onclick="return false;"> <span class="lang en">Yes</span> <span class="lang es">Sí</span> <span class="lang ja">Yes</span> <span class="lang ko">Yes</span> <span class="lang ru">Yes</span> <span class="lang zh-cn">是的</span> <span class="lang zh-tw">没有</span> </a> <a href="#" class="button" onclick="$('#langMessage').hide();return false;"> <span class="lang en">No</span> <span class="lang es">No</span> <span class="lang ja">No</span> <span class="lang ko">No</span> <span class="lang ru">No</span> <span class="lang zh-cn">没有</span> <span class="lang zh-tw">没有</span> </a> </div> </div> --> <!-- Header --> <div id="header-wrapper"> <div id="header"> <div class="wrap" id="header-wrap"> <div class="col-3 logo"> <a href="../../../../../../../index.html"> <img src="../../../../../../../assets/images/dac_logo.png" srcset="../../../../../../../assets/images/dac_logo@2x.png 2x" width="123" height="25" alt="Android Developers" /> </a> <div class="btn-quicknav" id="btn-quicknav"> <a href="#" class="arrow-inactive">Quicknav</a> <a href="#" class="arrow-active">Quicknav</a> </div> </div> <ul class="nav-x col-9"> <li class="design"> <a href="../../../../../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar" >Design</a></li> <li class="develop"><a href="../../../../../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar" >Develop</a></li> <li class="distribute last"><a href="../../../../../../../distribute/googleplay/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <div class="menu-container"> <div class="moremenu"> <div id="more-btn"></div> </div> <div class="morehover" id="moremenu"> <div class="top"></div> <div class="mid"> <div class="header">Links</div> <ul> <li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li> <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li> <li><a href="../../../../../../../about/index.html">About Android</a></li> </ul> <div class="header">Android Sites</div> <ul> <li><a href="http://www.android.com">Android.com</a></li> <li class="active"><a>Android Developers</a></li> <li><a href="http://source.android.com">Android Open Source Project</a></li> </ul> <br class="clearfix" /> </div><!-- end 'mid' --> <div class="bottom"></div> </div><!-- end 'moremenu' --> <div class="search" id="search-container"> <div class="search-inner"> <div id="search-btn"></div> <div class="left"></div> <form onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../../../../')" onkeyup="return search_changed(event, false, '../../../../../../../')" /> </form> <div class="right"></div> <a class="close hide">close</a> <div class="left"></div> <div class="right"></div> </div><!-- end search-inner --> </div><!-- end search-container --> <div class="search_filtered_wrapper reference"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> </div> <div class="search_filtered_wrapper docs"> <div class="suggest-card dummy no-display">&nbsp;</div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> <div class="child-card samples no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> </div><!-- end menu-container (search and menu widget) --> <!-- Expanded quicknav --> <div id="quicknav" class="col-13"> <ul> <li class="about"> <ul> <li><a href="../../../../../../../about/index.html">About</a></li> <li><a href="../../../../../../../wear/index.html">Wear</a></li> <li><a href="../../../../../../../tv/index.html">TV</a></li> <li><a href="../../../../../../../auto/index.html">Auto</a></li> </ul> </li> <li class="design"> <ul> <li><a href="../../../../../../../design/index.html">Get Started</a></li> <li><a href="../../../../../../../design/devices.html">Devices</a></li> <li><a href="../../../../../../../design/style/index.html">Style</a></li> <li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li> <li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li> <li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li> <li><a href="../../../../../../../design/videos/index.html">Videos</a></li> </ul> </li> <li class="develop"> <ul> <li><a href="../../../../../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li><a href="../../../../../../../guide/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li><a href="../../../../../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li><a href="../../../../../../../sdk/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> </li> <li><a href="../../../../../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../../../../../distribute/googleplay/index.html">Google Play</a></li> <li><a href="../../../../../../../distribute/essentials/index.html">Essentials</a></li> <li><a href="../../../../../../../distribute/users/index.html">Get Users</a></li> <li><a href="../../../../../../../distribute/engage/index.html">Engage &amp; Retain</a></li> <li><a href="../../../../../../../distribute/monetize/index.html">Monetize</a></li> <li><a href="../../../../../../../distribute/analyze/index.html">Analyze</a></li> <li><a href="../../../../../../../distribute/tools/index.html">Tools &amp; Reference</a></li> <li><a href="../../../../../../../distribute/stories/index.html">Developer Stories</a></li> </ul> </li> </ul> </div><!-- /Expanded quicknav --> </div><!-- end header-wrap.wrap --> </div><!-- end header --> <!-- Secondary x-nav --> <div id="nav-x"> <div class="wrap" style="position:relative;z-index:1"> <ul class="nav-x col-9 develop" style="width:100%"> <li class="training"><a href="../../../../../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li class="guide"><a href="../../../../../../../guide/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li class="reference"><a href="../../../../../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li class="tools"><a href="../../../../../../../sdk/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a></li> <li class="google"><a href="../../../../../../../google/index.html" >Google Services</a> </li> </ul> </div> </div> <!-- /Sendondary x-nav DEVELOP --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> </div> <!--end header-wrapper --> <div id="sticky-header"> <div> <a class="logo" href="#top"></a> <a class="top" href="#top"></a> <ul class="breadcrumb"> <li class="current">DataBuffer</li> </ul> </div> </div> <div class="wrap clearfix" id="body-content"> <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav"> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled" title="Select your target API level to dim unavailable APIs">API level: </label> <div class="select-wrapper"> <select id="apiLevelSelector"> <!-- option elements added by buildApiLevelSelector() --> </select> </div> </div><!-- end toggle --> <div id="api-nav-title">Android APIs</div> </div><!-- end nav header --> <script> var SINCE_DATA = [ ]; buildApiLevelSelector(); </script> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav" class="scroll-pane"> <ul> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li> <li class="selected api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/fitness/package-summary.html">com.google.android.gms.fitness</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/fitness/data/package-summary.html">com.google.android.gms.fitness.data</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/fitness/request/package-summary.html">com.google.android.gms.fitness.request</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/fitness/result/package-summary.html">com.google.android.gms.fitness.result</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/fitness/service/package-summary.html">com.google.android.gms.fitness.service</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/location/places/package-summary.html">com.google.android.gms.location.places</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/location/places/ui/package-summary.html">com.google.android.gms.location.places.ui</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/nearby/package-summary.html">com.google.android.gms.nearby</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/nearby/connection/package-summary.html">com.google.android.gms.nearby.connection</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/safetynet/package-summary.html">com.google.android.gms.safetynet</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li> <li class="api apilevel-"> <a href="../../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li> </ul><br/> </div> <!-- end packages-nav --> </div> <!-- end resize-packages --> <div id="classes-nav" class="scroll-pane"> <ul> <li><h2>Interfaces</h2> <ul> <li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html">DataBuffer</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBufferObserver.html">DataBufferObserver</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBufferObserver.Observable.html">DataBufferObserver.Observable</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/Freezable.html">Freezable</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBufferObserverSet.html">DataBufferObserverSet</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBufferUtils.html">DataBufferUtils</a></li> <li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/common/data/FreezableUtils.html">FreezableUtils</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none" class="scroll-pane"> <div id="tree-list"></div> </div><!-- end nav-tree --> </div><!-- end swapper --> <div id="nav-swap"> <a class="fullscreen">fullscreen</a> <a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a> </div> </div> <!-- end devdoc-nav --> </div> <!-- end side-nav --> <script type="text/javascript"> // init fullscreen based on user pref var fullscreen = readCookie("fullscreen"); if (fullscreen != 0) { if (fullscreen == "false") { toggleFullscreen(false); } else { toggleFullscreen(true); } } // init nav version for mobile if (isMobile) { swapNav(); // tree view should be used on mobile $('#nav-swap').hide(); } else { chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../../../../"); } } // scroll the selected page into view $(document).ready(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); </script> <div class="col-12" id="doc-col"> <div id="api-info-block"> <div class="sum-details-links"> Summary: <a href="#pubmethods">Methods</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public interface <h1 itemprop="name">DataBuffer</h1> implements <a href="http://developer.android.com/reference/java/lang/Iterable.html">Iterable</a>&lt;T&gt; <a href="../../../../../../../reference/com/google/android/gms/common/api/Releasable.html">Releasable</a> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <table class="jd-inheritance-table"> <tr> <td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.common.data.DataBuffer&lt;T&gt;</td> </tr> </table> <table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;"> <a href="#" onclick="return toggleInherited(this, null)" id="subclasses-indirect" class="jd-expando-trigger closed" ><img id="subclasses-indirect-trigger" src="../../../../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a>Known Indirect Subclasses <div id="subclasses-indirect"> <div id="subclasses-indirect-list" class="jd-inheritedlinks" > <a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a>&lt;T&gt;, <a href="../../../../../../../reference/com/google/android/gms/games/achievement/AchievementBuffer.html">AchievementBuffer</a>, <a href="../../../../../../../reference/com/google/android/gms/appstate/AppStateBuffer.html">AppStateBuffer</a>, <a href="../../../../../../../reference/com/google/android/gms/location/places/AutocompletePredictionBuffer.html">AutocompletePredictionBuffer</a>, <a href="../../../../../../../reference/com/google/android/gms/wearable/DataEventBuffer.html">DataEventBuffer</a>, <a href="../../../../../../../reference/com/google/android/gms/wearable/DataItemBuffer.html">DataItemBuffer</a>, and <a href="#" onclick="return toggleInherited(document.getElementById('subclasses-indirect', null))">8 others.</a> </div> <div id="subclasses-indirect-summary" style="display: none;" > <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a>&lt;T&gt;</td> <td class="jd-descrcol" width="100%"> Default implementation of DataBuffer.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/achievement/AchievementBuffer.html">AchievementBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of achievements.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/appstate/AppStateBuffer.html">AppStateBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of app states.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/location/places/AutocompletePredictionBuffer.html">AutocompletePredictionBuffer</a></td> <td class="jd-descrcol" width="100%"> A <code>DataBuffer</code> that represents a list of AutocompletePredictionEntitys.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/wearable/DataEventBuffer.html">DataEventBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure holding references to a set of events.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/wearable/DataItemBuffer.html">DataItemBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure holding reference to a set of <code><a href="../../../../../../../reference/com/google/android/gms/wearable/DataItem.html">DataItem</a></code>s.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/event/EventBuffer.html">EventBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of events.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/GameBuffer.html">GameBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of games.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/request/GameRequestBuffer.html">GameRequestBuffer</a></td> <td class="jd-descrcol" width="100%"> EntityBuffer implementation containing Request details.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationBuffer.html">InvitationBuffer</a></td> <td class="jd-descrcol" width="100%"> EntityBuffer implementation containing Invitation data.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/LeaderboardBuffer.html">LeaderboardBuffer</a></td> <td class="jd-descrcol" width="100%"> EntityBuffer containing Leaderboard data.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/LeaderboardScoreBuffer.html">LeaderboardScoreBuffer</a></td> <td class="jd-descrcol" width="100%"> <code><a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a></code> containing LeaderboardScore data.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/drive/MetadataBuffer.html">MetadataBuffer</a></td> <td class="jd-descrcol" width="100%"> A data buffer that points to Metadata entries.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/quest/MilestoneBuffer.html">MilestoneBuffer</a></td> <td class="jd-descrcol" width="100%"> <code><a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a></code> implementation containing quest milestone data.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/MomentBuffer.html">MomentBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of <code><a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/Moment.html">Moment</a></code> objects.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantBuffer.html">ParticipantBuffer</a></td> <td class="jd-descrcol" width="100%"> <code><a href="../../../../../../../reference/com/google/android/gms/common/data/AbstractDataBuffer.html">AbstractDataBuffer</a></code> implementation containing match participant data.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/plus/model/people/PersonBuffer.html">PersonBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of <code><a href="../../../../../../../reference/com/google/android/gms/plus/model/people/Person.html">Person</a></code> objects.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/location/places/PlaceBuffer.html">PlaceBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of <code><a href="../../../../../../../reference/com/google/android/gms/location/places/Place.html">Places</a></code>.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/location/places/PlaceLikelihoodBuffer.html">PlaceLikelihoodBuffer</a></td> <td class="jd-descrcol" width="100%"> A <code>DataBuffer</code> that represents a list of <code>PlaceLikelihood</code>s.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/PlayerBuffer.html">PlayerBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of players.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/quest/QuestBuffer.html">QuestBuffer</a></td> <td class="jd-descrcol" width="100%"> EntityBuffer implementation containing Quest details.&nbsp; </td> </tr> <tr class=" api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/snapshot/SnapshotMetadataBuffer.html">SnapshotMetadataBuffer</a></td> <td class="jd-descrcol" width="100%"> Data structure providing access to a list of snapshots.&nbsp; </td> </tr> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/TurnBasedMatchBuffer.html">TurnBasedMatchBuffer</a></td> <td class="jd-descrcol" width="100%"> EntityBuffer implementation containing TurnBasedMatch details.&nbsp; </td> </tr> </table> </div> </div> </td></tr></table> <div class="jd-descr"> <h2>Class Overview</h2> <p itemprop="articleBody">Interface for a buffer of typed data. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#close()">close</a></span>()</nobr> <div class="jd-descrdiv"> <em> This method is deprecated. use <code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#release()">release()</a></code> instead </em> </div> </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"><nobr> abstract T</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#get(int)">get</a></span>(int position)</nobr> <div class="jd-descrdiv"> Returns an element on specified position. </div> </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#getCount()">getCount</a></span>()</nobr> </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"><nobr> abstract boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#isClosed()">isClosed</a></span>()</nobr> <div class="jd-descrdiv"> <em> This method is deprecated. <code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#release()">release()</a></code> is idempotent, and so is safe to call multiple times </em> </div> </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract <a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a>&lt;T&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#iterator()">iterator</a></span>()</nobr> </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"><nobr> abstract void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#release()">release</a></span>()</nobr> <div class="jd-descrdiv"> Releases resources used by the buffer. </div> </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract <a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a>&lt;T&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#singleRefIterator()">singleRefIterator</a></span>()</nobr> <div class="jd-descrdiv"> In order to use this iterator it should be supported by particular <code>DataBuffer</code>. </div> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Iterable" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Iterable-trigger" src="../../../../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From interface <a href="http://developer.android.com/reference/java/lang/Iterable.html">java.lang.Iterable</a> <div id="inherited-methods-java.lang.Iterable"> <div id="inherited-methods-java.lang.Iterable-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Iterable-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract <a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a>&lt;T&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad">iterator</span>()</nobr> </td></tr> </table> </div> </div> </td></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.google.android.gms.common.api.Releasable" class="jd-expando-trigger closed" ><img id="inherited-methods-com.google.android.gms.common.api.Releasable-trigger" src="../../../../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From interface <a href="../../../../../../../reference/com/google/android/gms/common/api/Releasable.html">com.google.android.gms.common.api.Releasable</a> <div id="inherited-methods-com.google.android.gms.common.api.Releasable"> <div id="inherited-methods-com.google.android.gms.common.api.Releasable-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-com.google.android.gms.common.api.Releasable-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-typecol"><nobr> abstract void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/common/api/Releasable.html#release()">release</a></span>()</nobr> </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <A NAME="close()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract void </span> <span class="sympad">close</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <p> <p class="caution"><strong> This method is deprecated.</strong><br/> use <code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#release()">release()</a></code> instead </p> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <A NAME="get(int)"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract T </span> <span class="sympad">get</span> <span class="normal">(int position)</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Returns an element on specified position. </p></div> </div> </div> <A NAME="getCount()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract int </span> <span class="sympad">getCount</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <A NAME="isClosed()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract boolean </span> <span class="sympad">isClosed</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <p> <p class="caution"><strong> This method is deprecated.</strong><br/> <code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html#release()">release()</a></code> is idempotent, and so is safe to call multiple times </p> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <A NAME="iterator()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract <a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a>&lt;T&gt; </span> <span class="sympad">iterator</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <A NAME="release()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract void </span> <span class="sympad">release</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Releases resources used by the buffer. This method is idempotent. </p></div> </div> </div> <A NAME="singleRefIterator()"></A> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract <a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a>&lt;T&gt; </span> <span class="sympad">singleRefIterator</span> <span class="normal">()</span> </h4> <div class="api-level"> <div></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>In order to use this iterator it should be supported by particular <code>DataBuffer</code>. Be careful: there will be single reference while iterating. If you are not sure - DO NOT USE this iterator. </p></div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <A NAME="navbar_top"></A> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. For details and restrictions, see the <a href="../../../../../../../license.html"> Content License</a>. </div> <div id="build_info"> Android GmsCore 1784785&nbsp;r &mdash; <script src="../../../../../../../timestamp.js" type="text/javascript"></script> <script>document.write(BUILD_TIMESTAMP)</script> </div> <div id="footerlinks"> <p> <a href="../../../../../../../about/index.html">About Android</a>&nbsp;&nbsp;|&nbsp; <a href="../../../../../../../legal.html">Legal</a>&nbsp;&nbsp;|&nbsp; <a href="../../../../../../../support.html">Support</a> </p> </div> </div> <!-- end footer --> </div> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
'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() {} };
/* -------------------------------------------------------------------------------------------- * 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;
local t = Def.ActorFrame{ InitCommand = function(self) self:delayedFadeIn(6) end, OffCommand = function(self) self:sleep(0.05) self:smooth(0.2) self:diffusealpha(0) end } local frameX = SCREEN_CENTER_X/2 local frameY = SCREEN_CENTER_Y+100 local maxMeter = 30 local frameWidth = capWideScale(get43size(390),390) local frameHeight = 110 local frameHeightShort = 61 local song local course local ctags = {} local filterTags = {} local function wheelSearch() local search = GHETTOGAMESTATE:getMusicSearch() GHETTOGAMESTATE:getSSM():GetMusicWheel():SongSearch(search) end local function updateTagFilter(tag) local ptags = tags:get_data().playerTags local charts = {} local playertags = {} for k,v in pairs(ptags) do playertags[#playertags+1] = k end local filterTags = tag if filterTags then local toFilterTags = {} toFilterTags[1] = filterTags local inCharts = {} for k, v in pairs(ptags[toFilterTags[1]]) do inCharts[k] = 1 end toFilterTags[1] = nil for k, v in pairs(toFilterTags) do for key, val in pairs(inCharts) do if ptags[v][key] == nil then inCharts[key] = nil end end end for k, v in pairs(inCharts) do charts[#charts + 1] = k end end local out = {} if tag ~= nil then out[tag] = 1 end GHETTOGAMESTATE:setFilterTags(out) GHETTOGAMESTATE:getSSM():GetMusicWheel():FilterByStepKeys(charts) wheelSearch() end local steps = { PlayerNumber_P1 } local trail = { PlayerNumber_P1 } local profile = { PlayerNumber_P1 } local topScore = { PlayerNumber_P1 } local hsTable = { PlayerNumber_P1 } local function generalFrame(pn) local t = Def.ActorFrame{ SetCommand = function(self) self:xy(frameX,frameY) self:visible(GAMESTATE:IsPlayerEnabled(pn)) end, UpdateInfoCommand = function(self) song = GAMESTATE:GetCurrentSong() for _,pn in pairs(GAMESTATE:GetEnabledPlayers()) do profile[pn] = GetPlayerOrMachineProfile(pn) steps[pn] = GAMESTATE:GetCurrentSteps(pn) topScore[pn] = getBestScore(pn, 0, getCurRate()) if song and steps[pn] then ptags = tags:get_data().playerTags chartkey = steps[pn]:GetChartKey() ctags = {} for k,v in pairs(ptags) do if ptags[k][chartkey] then ctags[#ctags + 1] = k end end end end self:RunCommandsOnChildren(function(self) self:playcommand("Set") end) end, BeginCommand = function(self) self:playcommand('Set') end, PlayerJoinedMessageCommand = function(self) self:playcommand("UpdateInfo") end, PlayerUnjoinedMessageCommand = function(self) self:playcommand("UpdateInfo") end, CurrentSongChangedMessageCommand = function(self) self:playcommand("UpdateInfo") end, CurrentStepsP1ChangedMessageCommand = function(self) self:playcommand("UpdateInfo") end, CurrentRateChangedMessageCommand = function(self) self:playcommand("UpdateInfo") end } --Upper Bar t[#t+1] = quadButton(2) .. { InitCommand = function(self) self:zoomto(frameWidth,frameHeight) self:valign(0) self:diffuse(getMainColor("frame")) self:diffusealpha(0.8) end } if not IsUsingWideScreen() then t[#t+1] = Def.Quad { InitCommand = function(self) self:halign(0):valign(0) self:xy(frameX-14,frameHeight/2) self:zoomto(65,frameHeight/2) self:diffuse(getMainColor("frame")) self:diffusealpha(0.8) end } end -- Avatar background frame t[#t+1] = Def.Quad{ InitCommand = function(self) self:xy(25+10-(frameWidth/2),5) self:zoomto(56,56) self:diffuse(color("#000000")) self:diffusealpha(0.8) end, SetCommand = function(self) self:stoptweening() self:smooth(0.5) self:diffuse(getBorderColor()) end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = Def.Quad{ InitCommand = function(self) self:xy(25+10-(frameWidth/2),5) self:zoomto(56,56) self:diffusealpha(0.8) end, BeginCommand = function(self) self:diffuseramp() self:effectcolor2(color("1,1,1,0.6")) self:effectcolor1(color("1,1,1,0")) self:effecttiming(2,1,0,0) end } t[#t+1] = quadButton(3) .. { InitCommand = function(self) self:xy(25+10-(frameWidth/2),5) self:zoomto(50,50) self:visible(false) end, MouseDownCommand = function(self, params) if params.button == "DeviceButton_left mouse button" then SCREENMAN:AddNewScreenToTop("ScreenPlayerProfile") end end } -- Avatar t[#t+1] = Def.Sprite { InitCommand = function (self) self:xy(25+10-(frameWidth/2),5):playcommand("ModifyAvatar") end, PlayerJoinedMessageCommand = function(self) self:queuecommand('ModifyAvatar') end, PlayerUnjoinedMessageCommand = function(self) self:queuecommand('ModifyAvatar') end, AvatarChangedMessageCommand = function(self) self:queuecommand('ModifyAvatar') end, ModifyAvatarCommand = function(self) self:visible(true) self:Load(getAvatarPath(PLAYER_1)) self:zoomto(50,50) end } -- Player name t[#t+1] = LoadFont("Common Bold")..{ InitCommand = function(self) self:xy(69-frameWidth/2,9) self:zoom(0.6) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local text = "" if profile[pn] ~= nil then text = getCurrentUsername(pn) if text == "" then text = pn == PLAYER_1 and "Player 1" or "Player 2" end end self:settext(text) end, BeginCommand = function(self) self:queuecommand('Set') end, PlayerJoinedMessageCommand = function(self) self:queuecommand('Set') end, LoginMessageCommand = function(self) self:queuecommand('Set') end, LogOutMessageCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(69-frameWidth/2,20) self:zoom(0.3) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local rating = 0 local rank = 0 local localrating = 0 if DLMAN:IsLoggedIn() then rank = DLMAN:GetSkillsetRank("Overall") rating = DLMAN:GetSkillsetRating("Overall") localrating = profile[pn]:GetPlayerRating() self:settextf("Skill Rating: %0.2f (%0.2f #%d Online)", localrating, rating, rank) self:AddAttribute(#"Skill Rating:", {Length = 7, Zoom =0.3 ,Diffuse = getMSDColor(localrating)}) self:AddAttribute(#"Skill Rating: 00.00 ", {Length = -1, Zoom =0.3 ,Diffuse = getMSDColor(rating)}) else if profile[pn] ~= nil then localrating = profile[pn]:GetPlayerRating() self:settextf("Skill Rating: %0.2f",localrating) self:AddAttribute(#"Skill Rating:", {Length = -1, Zoom =0.3 ,Diffuse = getMSDColor(localrating)}) end end end, BeginCommand = function(self) self:queuecommand('Set') end, PlayerJoinedMessageCommand = function(self) self:queuecommand('Set') end, LoginMessageCommand = function(self) self:queuecommand('Set') end, LogOutMessageCommand = function(self) self:queuecommand('Set') end, OnlineUpdateMessageCommand = function(self) self:queuecommand('Set') end } -- Level and exp t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(69-frameWidth/2,29) self:zoom(0.3) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) if profile[pn] ~= nil then local level = getLevel(getProfileExp(pn)) local currentExp = getProfileExp(pn) - getLvExp(level) local nextExp = getNextLvExp(level) self:settextf("Lv.%d (%d/%d)",level, currentExp, nextExp) end end, BeginCommand = function(self) self:queuecommand('Set') end, PlayerJoinedMessageCommand = function(self) self:queuecommand('Set') end } --Score Date t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(frameWidth/2-5,3) self:zoom(0.35) self:halign(1):valign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)):diffusealpha(0.5) end, SetCommand = function(self) if getScoreDate(topScore[pn]) == "" then self:settext("Date Achieved: 0000-00-00 00:00:00") else self:settext("Date Achieved: "..getScoreDate(topScore[pn])) end end, BeginCommand = function(self) self:queuecommand('Set') end } -- Steps info t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(5-frameWidth/2,40) self:zoom(0.3) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local diff,stype local notes,holds,rolls,mines,lifts = 0 local difftext = "" if steps[pn] ~= nil then notes = steps[pn]:GetRadarValues(pn):GetValue("RadarCategory_Notes") holds = steps[pn]:GetRadarValues(pn):GetValue("RadarCategory_Holds") rolls = steps[pn]:GetRadarValues(pn):GetValue("RadarCategory_Rolls") mines = steps[pn]:GetRadarValues(pn):GetValue("RadarCategory_Mines") lifts = steps[pn]:GetRadarValues(pn):GetValue("RadarCategory_Lifts") diff = steps[pn]:GetDifficulty() stype = ToEnumShortString(steps[pn]:GetStepsType()):gsub("%_"," ") self:settextf("Notes:%s // Holds:%s // Rolls:%s // Mines:%s // Lifts:%s",notes,holds,rolls,mines,lifts) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal")..{ Name="StepsAndMeter", InitCommand = function(self) self:xy(frameWidth/2-5,38) self:zoom(0.5) self:halign(1) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) if steps[pn] ~= nil then local diff = steps[pn]:GetDifficulty() local stype = ToEnumShortString(steps[pn]:GetStepsType()):gsub("%_"," ") local meter = steps[pn]:GetMSD(getCurRateValue(),1) if meter == 0 then meter = steps[pn]:GetMeter() end meter = math.max(0,meter) local difftext if diff == 'Difficulty_Edit' and IsUsingWideScreen() then difftext = steps[pn]:GetDescription() difftext = difftext == '' and getDifficulty(diff) or difftext else difftext = getDifficulty(diff) end if IsUsingWideScreen() then self:settextf("%s %s %5.2f", stype, difftext, meter) else self:settextf("%s %5.2f", difftext, meter) end self:diffuse(getDifficultyColor(GetCustomDifficulty(steps[pn]:GetStepsType(),steps[pn]:GetDifficulty()))) else self:settext("") end end } t[#t+1] = LoadFont("Common Normal")..{ Name="MSDAvailability", InitCommand = function(self) self:xy(frameWidth/2-5,27) self:zoom(0.3) self:halign(1) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) if steps[pn] ~= nil then local meter = math.floor(steps[pn]:GetMSD(getCurRateValue(),1)) if meter == 0 then self:settext("Default") self:diffuse(color(colorConfig:get_data().main.disabled)) else self:settext("MSD") self:diffuse(color(colorConfig:get_data().main.enabled)) end else self:settext("") end end } t[#t+1] = Def.Quad{ InitCommand = function(self) self:xy(5-(frameWidth/2),50) self:zoomto(frameWidth-10,10) self:halign(0) self:diffusealpha(1) self:diffuse(getMainColor("background")) end } -- Stepstype and Difficulty meter t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(frameWidth-10-frameWidth/2-2,50) self:zoom(0.3) self:settext(maxMeter) end, SetCommand = function(self) if steps[pn] ~= nil then local diff = getDifficulty(steps[pn]:GetDifficulty()) local stype = ToEnumShortString(steps[pn]:GetStepsType()):gsub("%_"," ") self:diffuse(getDifficultyColor(GetCustomDifficulty(steps[pn]:GetStepsType(),steps[pn]:GetDifficulty()))) end end } t[#t+1] = Def.Quad{ InitCommand = function(self) self:xy(5-(frameWidth/2),50) self:halign(0) self:zoomy(10) self:diffuse(getMainColor("highlight")) end, SetCommand = function(self) self:stoptweening() self:decelerate(0.5) local meter = 0 local enabled = GAMESTATE:IsPlayerEnabled(pn) if enabled and steps[pn] ~= nil then meter = steps[pn]:GetMSD(getCurRateValue(),1) if meter == 0 then meter = steps[pn]:GetMeter() end self:zoomx((math.min(1,meter/maxMeter))*(frameWidth-10)) self:diffuse(getDifficultyColor(GetCustomDifficulty(steps[pn]:GetStepsType(),steps[pn]:GetDifficulty()))) else self:zoomx(0) end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(frameWidth/2-5,18) self:settext("Negative BPMs") self:zoom(0.4) self:halign(1) self:visible(false) end, SetCommand = function(self) if song and steps and steps[pn] then if steps[pn]:GetTimingData():HasWarps() then self:visible(true) return end end self:visible(false) end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:y(50):zoom(0.3) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) self:stoptweening() self:decelerate(0.5) local meter = 0 local enabled = GAMESTATE:IsPlayerEnabled(pn) if enabled and steps[pn] ~= nil then meter = steps[pn]:GetMSD(getCurRateValue(),1) if meter == 0 then meter = steps[pn]:GetMeter() end meter = math.max(1,meter) self:settextf("%0.2f", meter) self:x((math.min(1,meter/maxMeter))*(frameWidth-15)-frameWidth/2-3) else self:settext(0) end end, BeginCommand = function(self) self:queuecommand('Set') end } --Grades t[#t+1] = LoadFont("Common BLarge")..{ InitCommand = function(self) self:xy(60-frameWidth/2,frameHeight-35) self:zoom(0.6) self:maxwidth(110/0.6) end, SetCommand = function(self) local grade = 'Grade_None' if topScore[pn] ~= nil then grade = topScore[pn]:GetWifeGrade() end self:settext(THEME:GetString("Grade",ToEnumShortString(grade))) self:diffuse(getGradeColor(grade)) end, BeginCommand = function(self) self:queuecommand('Set') end } --ClearType t[#t+1] = LoadFont("Common Bold")..{ InitCommand = function(self) self:xy(60-frameWidth/2,frameHeight-15) self:zoom(0.4) self:maxwidth(110/0.4) end, SetCommand = function(self) self:stoptweening() local scoreList local clearType if profile[pn] ~= nil and song ~= nil and steps[pn] ~= nil then scoreList = getScoreTable(pn, getCurRate()) clearType = getHighestClearType(pn,steps[pn],scoreList,0) self:settext(getClearTypeText(clearType)) self:diffuse(getClearTypeColor(clearType)) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } -- Percentage Score t[#t+1] = LoadFont("Common BLarge")..{ InitCommand= function(self) self:xy(190-frameWidth/2,frameHeight-36) self:zoom(0.45):halign(1):maxwidth(75/0.45) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local scorevalue = 0 if topScore[pn] ~= nil then scorevalue = getScore(topScore[pn], steps[pn], true) end self:settextf("%.2f%%",math.floor((scorevalue)*10000)/100) end, BeginCommand = function(self) self:queuecommand('Set') end } --Player DP/Exscore / Max DP/Exscore t[#t+1] = LoadFont("Common Normal")..{ Name = "score", InitCommand= function(self) self:xy(177-frameWidth/2,frameHeight-18) self:zoom(0.5):halign(1):maxwidth(26/0.5) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) self:settext(getMaxScore(pn,0)) end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand= function(self) self:xy(177-frameWidth/2,frameHeight-18) self:zoom(0.5):halign(1):maxwidth(50/0.5) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) self:x(self:GetParent():GetChild("score"):GetX()-(math.min(self:GetParent():GetChild("score"):GetWidth(),27/0.5)*0.5)) local scoreValue = 0 if topScore[pn] ~= nil then scoreValue = getScore(topScore[pn], steps[pn], false) end self:settextf("%.0f/",scoreValue) end, BeginCommand = function(self) self:queuecommand('Set') end } --ScoreType superscript(?) t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(178-frameWidth/2,frameHeight-19) self:zoom(0.3) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, BeginCommand = function(self) self:queuecommand("Set") end, SetCommand = function(self) local version = 3 if topScore[pn] ~= nil then version = topScore[pn]:GetWifeVers() end self:settextf("Wife%d", version) end } --MaxCombo t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(210-frameWidth/2,frameHeight-40) self:zoom(0.4) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local score = getBestMaxCombo(pn,0, getCurRate()) local maxCombo = 0 maxCombo = getScoreMaxCombo(score) self:settextf("Max Combo: %d",maxCombo) end, BeginCommand = function(self) self:queuecommand('Set') end } --MissCount t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(210-frameWidth/2,frameHeight-28) self:zoom(0.4) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) local score = getBestMissCount(pn, 0, getCurRate()) if score ~= nil then self:settext("Miss Count: "..getScoreMissCount(score)) else self:settext("Miss Count: -") end end, BeginCommand = function(self) self:queuecommand('Set') end } -- EO rank placeholder t[#t+1] = LoadFont("Common Normal")..{ InitCommand = function(self) self:xy(210-frameWidth/2,frameHeight-16) self:zoom(0.4) self:halign(0) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) end, SetCommand = function(self) self:settextf("Ranking: %d/%d",0,0) end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = quadButton(6) .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3,0) self:valign(1) self:halign(1) self:zoomto((frameWidth-75)/3,16) self:diffuse(getMainColor("frame")) self:diffusealpha(0) end, SetCommand = function(self) if song and ctags[3] then if ctags[3] == GHETTOGAMESTATE.SSMTag then self:diffusealpha(0.6) else self:diffusealpha(0.8) end else self:diffusealpha(0) end end, BeginCommand = function(self) self:queuecommand("Set") end, MouseDownCommand = function(self, params) if song and ctags[3] then if ctags[3] == GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_right mouse button" then GHETTOGAMESTATE.SSMTag = nil self:linear(0.1):diffusealpha(0.8) updateTagFilter(nil) elseif ctags[3] ~= GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_left mouse button" then GHETTOGAMESTATE.SSMTag = ctags[3] self:linear(0.1):diffusealpha(0.6) updateTagFilter(ctags[3]) end end end } t[#t+1] = quadButton(6) .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3 - (frameWidth-75)/3 - 2,0) self:valign(1) self:halign(1) self:zoomto((frameWidth-75)/3,16) self:diffuse(getMainColor("frame")) self:diffusealpha(0) end, SetCommand = function(self) if song and ctags[2] then if ctags[2] == GHETTOGAMESTATE.SSMTag then self:diffusealpha(0.6) else self:diffusealpha(0.8) end else self:diffusealpha(0) end end, BeginCommand = function(self) self:queuecommand("Set") end, MouseDownCommand = function(self, params) if song and ctags[2] then if ctags[2] == GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_right mouse button" then GHETTOGAMESTATE.SSMTag = nil self:linear(0.1):diffusealpha(0.8) updateTagFilter(nil) elseif ctags[2] ~= GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_left mouse button" then GHETTOGAMESTATE.SSMTag = ctags[2] self:linear(0.1):diffusealpha(0.6) updateTagFilter(ctags[2]) end end end } t[#t+1] = quadButton(6) .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3 - (frameWidth-75)/3*2 - 4,0) self:valign(1) self:halign(1) self:zoomto((frameWidth-75)/3,16) self:diffuse(getMainColor("frame")) self:diffusealpha(0) end, SetCommand = function(self) if song and ctags[1] then if ctags[1] == GHETTOGAMESTATE.SSMTag then self:diffusealpha(0.6) else self:diffusealpha(0.8) end else self:diffusealpha(0) end end, BeginCommand = function(self) self:queuecommand("Set") end, MouseDownCommand = function(self, params) if song and ctags[1] then if ctags[1] == GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_right mouse button" then GHETTOGAMESTATE.SSMTag = nil self:linear(0.1):diffusealpha(0.8) updateTagFilter(nil) elseif ctags[1] ~= GHETTOGAMESTATE.SSMTag and params.button == "DeviceButton_left mouse button" then GHETTOGAMESTATE.SSMTag = ctags[1] self:linear(0.1):diffusealpha(0.6) updateTagFilter(ctags[1]) end end end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(260 - frameWidth/5, frameHeight-40) self:zoom(0.4) self:halign(1) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(200) end, SetCommand = function(self) if song and steps[pn] then self:settext(steps[pn]:GetRelevantSkillsetsByMSDRank(getCurRateValue(), 1)) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(260 - frameWidth/5, frameHeight-28) self:zoom(0.4) self:halign(1) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(200) end, SetCommand = function(self) if song and steps[pn] then self:settext(steps[pn]:GetRelevantSkillsetsByMSDRank(getCurRateValue(), 2)) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(260 - frameWidth/5, frameHeight-16) self:zoom(0.4) self:halign(1) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(200) end, SetCommand = function(self) if song and steps[pn] then self:settext(steps[pn]:GetRelevantSkillsetsByMSDRank(getCurRateValue(), 3)) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3 - (frameWidth-75)/3*2 - 4 - (frameWidth-75)/6, -8) self:zoom(0.4) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(((frameWidth-75)/3-capWideScale(5,10))/0.4) end, SetCommand = function(self) if song and ctags[1] then self:settext(ctags[1]) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3 - (frameWidth-75)/3 - 2 - (frameWidth-75)/6, -8) self:zoom(0.4) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(((frameWidth-75)/3-capWideScale(5,10))/0.4) end, SetCommand = function(self) if song and ctags[2] then self:settext(ctags[2]) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } t[#t+1] = LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(capWideScale(68,85) + (frameWidth-75)/3 - (frameWidth-75)/6, -8) self:zoom(0.4) self:diffuse(color(colorConfig:get_data().selectMusic.ProfileCardText)) self:maxwidth(((frameWidth-75)/3-capWideScale(5,10))/0.4) end, SetCommand = function(self) if song and ctags[3] then self:settext(ctags[3]) else self:settext("") end end, BeginCommand = function(self) self:queuecommand('Set') end } return t end t[#t+1] = generalFrame(PLAYER_1) return t
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'); }, };
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"); } } }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"/> <title>+Ramboia</title> <link href="css/app.min.css" rel="stylesheet"/> <script src="/js/libs/modernizr.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> </head> <body id="ramboia"> <header class="application-header"> <h1 class="application-title">+Ramboia</h1> </header> <main class="application"> <div class="video-container-wrapper"> <div class="video-container"> <div class="wrapper"> <div id="player" class="video-player"></div> </div> <div class="video-player-controls"> <button class="video-mute" id="video-mute">Mute</button> <p class="video-time"> <span class="video-time-current" id="video-time-current">0:00</span>/<span class="video-time-total" id="video-time-total">0:00</span> </p> </div> </div> </div> <ul class="playlist" id="playlist"> <!-- <li class="playlist-entry" title="Video Title (Requested by Username)"> <a href="http://youtube.com" target="_blank"> <img class="playlist-entry-background" src="http://placehold.it/854x480"/> <h1 class="playlist-entry-title">Video Title</h1> </a> </li> --> </ul> </main> <script src="/js/libs/polyfill.min.js"></script> <script src="/js/main.min.js"></script> <script> mais_ramboia.start(); </script> </body> </html>
### New in 0.0.2 (Release 2014/07/23) * Updated README to reflect actual SessionFactory implementation * Improved Key generation to ensure proper sorting when using long, int, short or byte ids * Added First<T>() to ISession to fetch the first document of a type * Added Last<T>() to ISession to fetch the last document of a type * Added Get<T>(object[] id) to ISession for retrieving documents for multiple keys * Added Get<T>(int skip, int take) to ISession for document paging * Added performance and unit test coverage ### New in 0.0.1.1 (Release 2014/07/22) * Fixed nuget package (Added assembly to 'lib' folder) ### New in 0.0.1 (Released 2014/07/22) * First release of DocLite.
/** * Copyright 2012 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.store; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.StoredBlock; public class ReplayableBlockStoreTest { @Test public void testBasicStorage() throws Exception { File temporaryBlockStore = File.createTempFile("ReplayableBlockStore-testBasicStorage", null, null); System.out.println(temporaryBlockStore.getAbsolutePath()); temporaryBlockStore.deleteOnExit(); NetworkParameters networkParameters = NetworkParameters.unitTests(); Address toAddress1 = new ECKey().toAddress(networkParameters); Address toAddress2 = new ECKey().toAddress(networkParameters); ReplayableBlockStore store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, true); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); assertEquals(networkParameters.genesisBlock, genesis.getHeader()); // Build a new block. StoredBlock block1 = genesis.build(genesis.getHeader().createNextBlock(toAddress1).cloneAsHeader()); store.put(block1); store.setChainHead(block1); // Check we can get it back out again if we rebuild the store object. store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, false); StoredBlock block1reborn = store.get(block1.getHeader().getHash()); assertEquals(block1, block1reborn); // Check the chain head was stored correctly also. assertEquals(block1, store.getChainHead()); // Build another block. StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(toAddress2).cloneAsHeader()); store.put(block2); store.setChainHead(block2); // Check we can get it back out again if we rebuild the store object. store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, false); StoredBlock block2reborn = store.get(block2.getHeader().getHash()); assertEquals(block2, block2reborn); // Check the chain head was stored correctly also. assertEquals(block2, store.getChainHead()); } @Test public void testChainheadToPastTruncates() throws Exception { // this functionality is used in blockchain replay File temporaryBlockStore = File.createTempFile("ReplayableBlockStore-testReplay", null, null); System.out.println(temporaryBlockStore.getAbsolutePath()); temporaryBlockStore.deleteOnExit(); NetworkParameters networkParameters = NetworkParameters.unitTests(); Address toAddress1 = new ECKey().toAddress(networkParameters); Address toAddress2 = new ECKey().toAddress(networkParameters); ReplayableBlockStore store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, true); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); assertEquals(networkParameters.genesisBlock, genesis.getHeader()); // Build a new block. StoredBlock block1 = genesis.build(genesis.getHeader().createNextBlock(toAddress1).cloneAsHeader()); store.put(block1); store.setChainHead(block1); // remember the size of the blockstore after adding the first block long blockSizeAfterFirstBlockAdded = temporaryBlockStore.length(); System.out.println("blockSizeAfterFirstBlockAdded = " + blockSizeAfterFirstBlockAdded); // Build another block. StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(toAddress2).cloneAsHeader()); store.put(block2); store.setChainHead(block2); long blockSizeAfterSecondBlockAdded = temporaryBlockStore.length(); System.out.println("blockSizeAfterSecondBlockAdded = " + blockSizeAfterSecondBlockAdded); store.setChainHeadAndTruncate(block1); long blockSizeAfterSetChainHeadAndTruncate = temporaryBlockStore.length(); System.out.println("blockSizeAfterSetChainHeadAndTruncate = " + blockSizeAfterSetChainHeadAndTruncate); assertEquals("setChainHeadAndTruncate did not roll back blockstore", blockSizeAfterFirstBlockAdded, blockSizeAfterSetChainHeadAndTruncate); } }
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; } }
<?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; } }
# -*- 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
"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> ); } }
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()
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(); } }
# UIjson.js Objects in Bootstrap Interface ## Demo [http://www.scriptrain.com/projects/uijson/UIjson.js-demo-page.html](http://www.scriptrain.com/projects/uijson/UIjson.js-demo-page.html) Full Api here : [http://www.scriptrain.com/projects/uijson/API](http://www.scriptrain.com/projects/uijson/API) ## What is UIjson.js UIjson.js is a plugin written in Jquery which uses Bootstrap's classes to render properties of Objects and their values to predefined HTML elements. It is dependant from jquery and bootstrap ## Motivation Most of the times in programming we have the need to output data of different types, which are just declared somewhere or they come from a process.Here comes the question of how we will represent them to the end user,in which format and how to manipulate the free space.Here UIjson.js came out.UIjson.js is a jquery plug-in which offers some predefined ways to render,edit and create data from JSON models.It makes use of most popular HTML, CSS, framework: BOOTSTRAP for interface and Javascript,Jquery for functionality.A lot of people love Boostrap because it makes them to not worry about cross browser/platform css compability issues. So since UIjson is expandable, to ensure future compability I decided to use it here to keep you still free of worries. For the same reason I used Jquery.Both have great support, years of life ,great documentations , stability and many places to ask if you need any help. . ## Configuration First you need to include following files in head of your page for bootstrap,Jquery ### a) Include files in &lt;head&gt;&lt;/head&gt; 1. Files 1. UIjson.js 2. UIjson.min.js - a minified version of UIjson.js ##### Dependencies : - bootstrap v3.1 - jquery v2.2.3 - jquery-ui v1.11.4 if you want to make use of sortable and draggable to manipulate array items from interface ```html <script src="http://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script> <script src="js/jquery-ui.min.js"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link rel="stylesheet" href="css/bootstrap.css"> <script src="UIjson.js"></script> ``` ### b) Understanding Dataholders The main subject of UIjson are the properties which hold data.These 'dataholder' properties can have value of type string,number,boolean or an array of these types. Other properties will be ignored. ```js var example = { name: 'Julian', age: '20', country: 'USA', past_jobs: [ 'Philips', 'ikea', 'apple', 'microsoft' ], children: [ { name: '' }, { name: '' } ], job: {} }; ``` Properties : **job** and **childen** of example are not dataholder - properties because their values are not strings ### c) Defining Dataholder properties To configure UIjson you will need to define a dataholder object for each property you want to import. Undefined properties will not be removed as they are part of your model, but you will not able to render or edit them.They will be ignored from all UIjson's functionality. ```js //To define a dataholder Object you need at least to set these 2 properties, 'property' and 'assignTo' var dataHolder = { property: 'name' , assignTo: 'input_field' }; //And here the full options of dataholder Object var dataHolder = { property: 'name', // the property path: '', // Path may be used when you add a nested object which is part of a bigger instance, to separate this dataholder from others if they have same properties. assignTo: 'input_field', // How this property will be rendered in HTML.There a list of UI types in code architecture section of documentation. tabName: 'Bio', // Default tab is 'General'. Only if tab with label 'Bio' is active you will be able to see the UI element for this property. label: 'Person"s Name', // Label text goes to "control-label" element of bootstrap. options: [], // Options required if assignTo is "select_list", "radio" or "checkbox" arrEach: false, // If true means that if the value of the object is an array of strings,each element of the array will be a seperate UI element in HTML array_Api: { // It has meaning only if arrEach = true sortable: true, // If true You can sort elements. This requires jquery-ui. add: true, // If true You can add new elements by clicking a symbol. remove: true // If true You can remove an UI element from the array by clicking a symbol. } }; ``` ### d) Calling UIjson.js Lets configure and call UIjson now for model : exampleOb ```html //Our HTML: //The bound selector to UIjson must contain an empty element for tabs with class : 'UIjson nav-tabs' //and an empty element for sections with class 'UIjson sections' //Dont forget that all UI_elements of UIjson.js use bootstrap's Grid system in HTML and bootstrap's classes. <div id="MyUI" class="col-md-10 col-lg-10 col-sm-10"> <ul role="tablist" class="nav UIjson nav-tabs"></ul> <div class="tab-content UIjson sections"></div> </div> ``` ```js var exampleOb = { name: 'Julian', age: '20', country: 'USA', past_jobs: [ 'Philips', 'ikea', 'apple', 'microsoft' ] }; var config = { "properties": [ { property: 'name', assignTo: 'input_field', label: 'Persons Name' }, { property: 'age', assignTo: 'input_field', label: 'Persons Age' }, { property: 'country', assignTo: 'select_list', label: 'Country', options: [ 'SPAIN', 'USA', 'Brazil', 'Canada' ] }, { property: 'past_jobs' , assignTo: 'textarea_field', label: 'Portfolio' }, ], "_Objects" : [ { obj: exampleOb, path: '' } ] }; $('#MyUI').UIjson(config); ``` ## Progress - Behind the scenes So how it works: **a)** You define some properties in configuration or using defineProp( .. ) method. The objects you use to define them including some other properties are the Dataholder Objects of UIjson.js. All dataholder Objects are stored in Dataholders array of UIjson Instance. **b)** You import some Objects using _Objects in configuration or using ImportObject( .. ) method. Lets say you import the object var **AA = { };** Once imported , AA will be converted to UIjson Objectand can be used from UIjson methods and events. Below you can see how UIjson Objects look like : ```js var UIjsonObject = { obj: exampleOb, // A reference to the Imported Object. ui_wrapper: null, // It is a Jquery element and it will not be null only if this Object is rendered. dataholders: [], // This array is filled from Obj_initDataholders( .. ) method path: '' // comes from user's definition } ``` All UIjson Objects exist in _Objects array of the Instance. **c)** Filling UIjson_Object.dataholders array. All properties of AA will be compared by name and path with the defined Dataholders.Matches will be pushed to UIjson_Object.dataholders array **d)** Now everytime AA is going to be rendered, some objects of UIjson_Object.dataholders array will have "elements" property filled with some Jquery Selectors. ## Code Architecture #### Contructor ```js $.UIjson.Instance = function () { this.Settings = '', this.Element = null, this._Objects = [], this.ActiveTab = 'General', this.Tabs = {}, this.Sections = {}, this.Dataholders = [] }; ``` #### Defaults ```js $.UIjson.defaults = { binders: { tabs: '.UIjson.nav-tabs' , sections: '.UIjson.sections' , obj: '.UIjson.obj_UI' }, dataHolder : { tabName: 'General' , path: false, label: '&nbsp', arrEach: false, options: false, array_Api: { sortable: true, add: true, remove: true } } }; ``` #### UI HTML Elements All UI elements exist as properties in **$.UIjson.UI_Elements**. Each name must be unique. - **_HTML** contains HTML of element as string - **Val_Method** sets or returns value of target element. - **AttachEv** attach events - **detachEv** removes attached events **Use one of following names in configuration of dataholders to 'assignTo'** 1. input_field 2. textarea_field 3. select_list 4. checkbox 5. radio 6. thumbnail 7. blockquote ## License UIjson.js Copyright (c) 2016 Chris B MIT
/* * * 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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Function ReadMap | TPS Broadcast</title> <link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="namespace-None.html"> None </a> </li> <li> <a href="namespace-PHP.html"> PHP </a> </li> <li> <a href="namespace-TPS.html"> TPS </a> </li> </ul> </div> <hr> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-Barcode.html" class="invalid">Barcode</a></li> <li><a href="class-Barcode11.html" class="invalid">Barcode11</a></li> <li><a href="class-Barcode128.html" class="invalid">Barcode128</a></li> <li><a href="class-Barcode39.html" class="invalid">Barcode39</a></li> <li><a href="class-Barcode93.html" class="invalid">Barcode93</a></li> <li><a href="class-BarcodeCodabar.html" class="invalid">BarcodeCodabar</a></li> <li><a href="class-BarcodeDatamatrix.html" class="invalid">BarcodeDatamatrix</a></li> <li><a href="class-BarcodeEAN.html" class="invalid">BarcodeEAN</a></li> <li><a href="class-BarcodeI25.html" class="invalid">BarcodeI25</a></li> <li><a href="class-BarcodeMSI.html" class="invalid">BarcodeMSI</a></li> <li><a href="class-BarcodeUPC.html" class="invalid">BarcodeUPC</a></li> <li><a href="class-BCGBarcode.html">BCGBarcode</a></li> <li><a href="class-BCGBarcode1D.html">BCGBarcode1D</a></li> <li><a href="class-BCGcodabar.html">BCGcodabar</a></li> <li><a href="class-BCGcode11.html">BCGcode11</a></li> <li><a href="class-BCGcode128.html">BCGcode128</a></li> <li><a href="class-BCGcode39.html">BCGcode39</a></li> <li><a href="class-BCGcode39extended.html">BCGcode39extended</a></li> <li><a href="class-BCGcode93.html">BCGcode93</a></li> <li><a href="class-BCGColor.html">BCGColor</a></li> <li><a href="class-BCGDraw.html">BCGDraw</a></li> <li><a href="class-BCGDrawing.html">BCGDrawing</a></li> <li><a href="class-BCGDrawJPG.html">BCGDrawJPG</a></li> <li><a href="class-BCGDrawPNG.html">BCGDrawPNG</a></li> <li><a href="class-BCGean13.html">BCGean13</a></li> <li><a href="class-BCGean8.html">BCGean8</a></li> <li><a href="class-BCGFontFile.html">BCGFontFile</a></li> <li><a href="class-BCGFontPhp.html">BCGFontPhp</a></li> <li><a href="class-BCGgs1128.html">BCGgs1128</a></li> <li><a href="class-BCGi25.html">BCGi25</a></li> <li><a href="class-BCGintelligentmail.html">BCGintelligentmail</a></li> <li><a href="class-BCGisbn.html">BCGisbn</a></li> <li><a href="class-BCGLabel.html">BCGLabel</a></li> <li><a href="class-BCGmsi.html">BCGmsi</a></li> <li><a href="class-BCGothercode.html">BCGothercode</a></li> <li><a href="class-BCGpostnet.html">BCGpostnet</a></li> <li><a href="class-BCGs25.html">BCGs25</a></li> <li><a href="class-BCGupca.html">BCGupca</a></li> <li><a href="class-BCGupce.html">BCGupce</a></li> <li><a href="class-BCGupcext2.html">BCGupcext2</a></li> <li><a href="class-BCGupcext5.html">BCGupcext5</a></li> <li><a href="class-JoinDraw.html">JoinDraw</a></li> <li><a href="class-LibraryAPI.html">LibraryAPI</a></li> <li><a href="class-playing.html">playing</a></li> <li><a href="class-standardResult.html">standardResult</a></li> <li><a href="class-TPS_Cron.html">TPS_Cron</a></li> </ul> <h3>Interfaces</h3> <ul> <li><a href="class-BCGFont.html">BCGFont</a></li> </ul> <h3>Exceptions</h3> <ul> <li><a href="class-BCGArgumentException.html">BCGArgumentException</a></li> <li><a href="class-BCGDrawException.html">BCGDrawException</a></li> <li><a href="class-BCGParseException.html">BCGParseException</a></li> </ul> <h3>Functions</h3> <ul> <li><a href="function-absolute_include.html">absolute_include</a></li> <li><a href="function-ApplyUpdate.html">ApplyUpdate</a></li> <li><a href="function-baseCustomSetup.html">baseCustomSetup</a></li> <li><a href="function-checkbrute.html">checkbrute</a></li> <li><a href="function-CheckStorage.html">CheckStorage</a></li> <li><a href="function-CheckTTF.html" class="invalid">CheckTTF</a></li> <li><a href="function-CheckUpdate.html">CheckUpdate</a></li> <li><a href="function-CheckUpdateStatus.html">CheckUpdateStatus</a></li> <li><a href="function-convertTime.html" class="invalid">convertTime</a></li> <li><a href="function-customSetup.html" class="invalid">customSetup</a></li> <li><a href="function-DatabaseUpdateApply.html">DatabaseUpdateApply</a></li> <li><a href="function-DatabaseUpdateCheck.html">DatabaseUpdateCheck</a></li> <li><a href="function-DB_Auth.html">DB_Auth</a></li> <li><a href="function-db_close.html">db_close</a></li> <li><a href="function-db_conn.html">db_conn</a></li> <li><a href="function-decrypt.html">decrypt</a></li> <li><a href="function-drawCross.html" class="invalid">drawCross</a></li> <li><a href="function-easy_crypt.html">easy_crypt</a></li> <li><a href="function-easy_decrypt.html">easy_decrypt</a></li> <li><a href="function-encrypt.html">encrypt</a></li> <li><a href="function-esc_url.html">esc_url</a></li> <li><a href="function-Extensions.html">Extensions</a></li> <li><a href="function-file_put_contents.html" class="invalid">file_put_contents</a></li> <li><a href="function-findHOME.html">findHOME</a></li> <li><a href="function-findLocal.html">findLocal</a></li> <li><a href="function-findValueFromKey.html">findValueFromKey</a></li> <li><a href="function-gen_trivial_password.html">gen_trivial_password</a></li> <li><a href="function-getBrowser.html" class="invalid">getBrowser</a></li> <li><a href="function-getButton.html">getButton</a></li> <li><a href="function-getCheckboxHtml.html">getCheckboxHtml</a></li> <li><a href="function-getElementHtml.html">getElementHtml</a></li> <li><a href="function-getImageKeys.html">getImageKeys</a></li> <li><a href="function-getInputTextHtml.html">getInputTextHtml</a></li> <li><a href="function-GetLabelbyId.html" class="deprecated">GetLabelbyId</a></li> <li><a href="function-GetLibraryfull.html" class="deprecated">GetLibraryfull</a></li> <li><a href="function-GetLibraryRefcode.html" class="deprecated">GetLibraryRefcode</a></li> <li><a href="function-getOptionGroup.html">getOptionGroup</a></li> <li><a href="function-getOptionHtml.html">getOptionHtml</a></li> <li><a href="function-getRealIpAddr.html" class="invalid">getRealIpAddr</a></li> <li><a href="function-GetResponse.html">GetResponse</a></li> <li><a href="function-getSelectHtml.html">getSelectHtml</a></li> <li><a href="function-GetWebsitesbyRefCode.html" class="deprecated">GetWebsitesbyRefCode</a></li> <li><a href="function-is_session_started.html">is_session_started</a></li> <li><a href="function-LDAP_AUTH.html">LDAP_AUTH</a></li> <li><a href="function-listbarcodes.html">listbarcodes</a></li> <li><a href="function-listfonts.html">listfonts</a></li> <li><a href="function-ListLibrary.html" class="deprecated">ListLibrary</a></li> <li><a href="function-LoadStorage.html">LoadStorage</a></li> <li><a href="function-login.html">login</a></li> <li><a href="function-login_check.html">login_check</a></li> <li><a href="function-MakeFont.html" class="invalid">MakeFont</a></li> <li><a href="function-MakeFontDescriptor.html" class="invalid">MakeFontDescriptor</a></li> <li><a href="function-MakeFontEncoding.html" class="invalid">MakeFontEncoding</a></li> <li><a href="function-MakeWidthArray.html" class="invalid">MakeWidthArray</a></li> <li><a href="function-ReadAFM.html" class="invalid">ReadAFM</a></li> <li><a href="function-ReadLong.html" class="invalid">ReadLong</a></li> <li class="active"><a href="function-ReadMap.html" class="invalid">ReadMap</a></li> <li><a href="function-ReadShort.html" class="invalid">ReadShort</a></li> <li><a href="function-registerImageKey.html">registerImageKey</a></li> <li><a href="function-remove_utf8_bom.html">remove_utf8_bom</a></li> <li><a href="function-SaveStorage.html">SaveStorage</a></li> <li><a href="function-SaveToFile.html" class="invalid">SaveToFile</a></li> <li><a href="function-SearchLibrary.html">SearchLibrary</a></li> <li><a href="function-sec_session_start.html">sec_session_start</a></li> <li><a href="function-set_db_params.html">set_db_params</a></li> <li><a href="function-showError.html">showError</a></li> <li><a href="function-to12hour.html" class="invalid">to12hour</a></li> <li><a href="function-to24hour.html" class="invalid">to24hour</a></li> <li><a href="function-track_can_play.html">track_can_play</a></li> <li><a href="function-UPCAbarcode.html">UPCAbarcode</a></li> <li><a href="function-UpdateMeta.html">UpdateMeta</a></li> <li><a href="function-validate_EAN13Barcode.html">validate_EAN13Barcode</a></li> <li><a href="function-validate_UPCABarcode.html">validate_UPCABarcode</a></li> <li><a href="function-Versions.html">Versions</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li> <a href="namespace-None.html" title="Summary of None"><span>Namespace</span></a> </li> <li class="active"> <span>Function</span> </li> </ul> <ul> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> <li> <a href="annotation-group-todo.html" title="List of elements with todo annotation"> <span>Todo</span> </a> </li> </ul> <ul> </ul> </div> <div id="content" class="function"> <h1>Function ReadMap</h1> <div class="invalid"> <p> Documentation of this function could not be generated. </p> <p> Function was originally declared in oep/EPV3/PHP/font/makefont/makefont.php and is invalid because of: </p> <ul> </ul> </div> </div> <div id="footer"> TPS Broadcast API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js?f700aafc2c9e22e0635535bb7de0c40d6e0a03bf"></script> <script src="elementlist.js?a785c24267a6ce47f6feba5a12569f64f5b90772"></script> </body> </html>
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); } }
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) })
// +build websocket /* * ws_test.go * * Copyright 2017 Bill Zissimopoulos */ /* * This file is part of netchan. * * It is licensed under the MIT license. The full license text can be found * in the License.txt file at the root of this project. */ package netchan import ( "net/url" "testing" "time" ) func TestWsTransport(t *testing.T) { marshaler := NewJsonMarshaler() transport := NewWsTransport( marshaler, &url.URL{ Scheme: "ws", Host: ":25000", }, nil, nil) defer func() { transport.Close() time.Sleep(100 * time.Millisecond) }() testTransport(t, transport, "ws") }
package controllers import ( "github.com/labstack/echo" ) // MakeControllers for main func MakeControllers(e *echo.Echo) { e.GET("/api", homeController) }
<?php /** * Copyright (c) 2017 DarkWeb Design * * 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 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. */ declare(strict_types=1); namespace DarkWebDesign\PublicKeyCryptographyBundle\Tests\File; use DarkWebDesign\PublicKeyCryptographyBundle\Exception\FileNotValidException; use DarkWebDesign\PublicKeyCryptographyBundle\Exception\FormatNotValidException; use DarkWebDesign\PublicKeyCryptographyBundle\Exception\PrivateKeyPassPhraseEmptyException; use DarkWebDesign\PublicKeyCryptographyBundle\File\PrivateKeyFile; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Exception\ProcessFailedException; class PrivateKeyFileTest extends TestCase { const TEST_PASSPHRASE = 'test'; const TEST_EMPTYPASSPHRASE = ''; /** @var string */ private $file; protected function setUp(): void { $this->file = tempnam(sys_get_temp_dir(), 'php'); } protected function tearDown(): void { if (file_exists($this->file)) { unlink($this->file); } } /** * @dataProvider providerPrivateKeys */ public function testNewInstance(string $path): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $this->assertInstanceOf(PrivateKeyFile::class, $privateKeyFile); } /** * @dataProvider providerNotPrivateKeys */ public function testNewInstanceNotPrivateKey(string $path): void { $this->expectException(FileNotValidException::class); copy($path, $this->file); new PrivateKeyFile($this->file); } /** * @dataProvider providerPrivateKeysAndPassPhrases */ public function testSanitize(string $path, string $passPhrase = null): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile = $privateKeyFile->sanitize($passPhrase); $this->assertInstanceOf(PrivateKeyFile::class, $privateKeyFile); } public function testSanitizeEmptyPassPhrase(): void { $this->expectException(PrivateKeyPassPhraseEmptyException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->sanitize(static::TEST_EMPTYPASSPHRASE); } public function testSanitizeProcessFailed(): void { $this->expectException(ProcessFailedException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->sanitize('invalid-passphrase'); } /** * @dataProvider providerPrivateKeysAndFormats */ public function testGetFormat(string $path, string $format): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $this->assertSame($format, $privateKeyFile->getFormat()); } /** * @dataProvider providerConvertFormat */ public function testConvertFormat(string $path, string $format, string $passPhrase = null): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile = $privateKeyFile->convertFormat($format, $passPhrase); $this->assertInstanceOf(PrivateKeyFile::class, $privateKeyFile); $this->assertSame($format, $privateKeyFile->getFormat()); $this->assertSame(null !== $passPhrase, $privateKeyFile->hasPassPhrase()); } public function testConvertFormatInvalidFormat(): void { $this->expectException(FormatNotValidException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->convertFormat('invalid-format'); } public function testConvertFormatEmptyPassPhrase(): void { $this->expectException(PrivateKeyPassPhraseEmptyException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->convertFormat(PrivateKeyFile::FORMAT_DER, static::TEST_EMPTYPASSPHRASE); } public function testConvertFormatProcessFailed(): void { $this->expectException(ProcessFailedException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->convertFormat(PrivateKeyFile::FORMAT_DER, 'invalid-passphrase'); } /** * @dataProvider providerHasPassPhrase */ public function testHasPassPhrase(string $path, bool $hasPassphrase): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $this->assertSame($hasPassphrase, $privateKeyFile->hasPassphrase()); } /** * @dataProvider providerPrivateKeysHavingPassPhrases */ public function testVerifyPassPhrase(string $path): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $this->assertTrue($privateKeyFile->verifyPassPhrase(static::TEST_PASSPHRASE)); $this->assertFalse($privateKeyFile->verifyPassPhrase('invalid-passphrase')); } /** * @dataProvider providerPrivateKeysNotHavingPassPhrases */ public function testAddPassPhrase(string $path): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->addPassPhrase(static::TEST_PASSPHRASE); $this->assertTrue($privateKeyFile->hasPassPhrase()); $this->assertTrue($privateKeyFile->verifyPassPhrase(static::TEST_PASSPHRASE)); } public function testAddPassPhraseEmptyPassPhrase(): void { $this->expectException(PrivateKeyPassPhraseEmptyException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->addPassPhrase(static::TEST_EMPTYPASSPHRASE); } public function testAddPassPhraseProcessFailed(): void { $this->expectException(ProcessFailedException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); unlink($this->file); $privateKeyFile->addPassPhrase(static::TEST_PASSPHRASE); } /** * @dataProvider providerPrivateKeysHavingPassPhrases */ public function testRemovePassPhrase(string $path): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->removePassPhrase(static::TEST_PASSPHRASE); $this->assertFalse($privateKeyFile->hasPassPhrase()); } public function testRemovePassPhraseProcessFailed(): void { $this->expectException(ProcessFailedException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->removePassPhrase('invalid-passphrase'); } /** * @dataProvider providerPrivateKeysHavingPassPhrases */ public function testChangePassPhrase(string $path): void { copy($path, $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->changePassPhrase(static::TEST_PASSPHRASE, 'new-passphrase'); $verified = $privateKeyFile->verifyPassPhrase('new-passphrase'); $this->assertTrue($verified); } public function testChangePassPhraseEmptyPassPhrase(): void { $this->expectException(PrivateKeyPassPhraseEmptyException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->changePassPhrase(static::TEST_PASSPHRASE, static::TEST_EMPTYPASSPHRASE); } public function testChangePassPhraseProcessFailed(): void { $this->expectException(ProcessFailedException::class); copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile->changePassPhrase('invalid-passphrase', 'new-passphrase'); } public function testMove(): void { copy(__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', $this->file); $privateKeyFile = new PrivateKeyFile($this->file); $privateKeyFile = $privateKeyFile->move($privateKeyFile->getPath(), $privateKeyFile->getFilename()); $this->assertInstanceOf(PrivateKeyFile::class, $privateKeyFile); } public function providerPrivateKeys(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key'], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key'], ]; } public function providerPrivateKeysAndPassPhrases(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', static::TEST_PASSPHRASE], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key', static::TEST_PASSPHRASE], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key', static::TEST_PASSPHRASE], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key'], ]; } public function providerPrivateKeysAndFormats(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key', PrivateKeyFile::FORMAT_DER], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key', PrivateKeyFile::FORMAT_PEM], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key', PrivateKeyFile::FORMAT_DER], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key', PrivateKeyFile::FORMAT_DER], ]; } public function providerPrivateKeysHavingPassPhrases(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key'], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key'], ]; } public function providerPrivateKeysNotHavingPassPhrases(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key'], // [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key'], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key'], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key'], ]; } public function providerNotPrivateKeys(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs12-pass.p12'], [__DIR__ . '/../Fixtures/Certificates/pkcs12-emptypass.p12'], [__DIR__ . '/../Fixtures/Certificates/pem-pass.pem'], [__DIR__ . '/../Fixtures/Certificates/pem-nopass.pem'], [__DIR__ . '/../Fixtures/Certificates/x509-pem.crt'], [__DIR__ . '/../Fixtures/Certificates/x509-der.crt'], ]; } public function providerConvertFormat(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', PrivateKeyFile::FORMAT_PEM, static::TEST_PASSPHRASE], // [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', PrivateKeyFile::FORMAT_DER, static::TEST_PASSPHRASE], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key', PrivateKeyFile::FORMAT_DER], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key', PrivateKeyFile::FORMAT_DER], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key', PrivateKeyFile::FORMAT_PEM, static::TEST_PASSPHRASE], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key', PrivateKeyFile::FORMAT_DER, static::TEST_PASSPHRASE], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key', PrivateKeyFile::FORMAT_PEM, static::TEST_PASSPHRASE], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key', PrivateKeyFile::FORMAT_DER, static::TEST_PASSPHRASE], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key', PrivateKeyFile::FORMAT_DER], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key', PrivateKeyFile::FORMAT_PEM], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key', PrivateKeyFile::FORMAT_DER], ]; } public function providerHasPassPhrase(): array { return [ [__DIR__ . '/../Fixtures/Certificates/pkcs1-pass-pem.key', true], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-pem.key', false], [__DIR__ . '/../Fixtures/Certificates/pkcs1-nopass-der.key', false], [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-pem.key', true], // [__DIR__ . '/../Fixtures/Certificates/pkcs8-pass-der.key', true], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-pem.key', false], [__DIR__ . '/../Fixtures/Certificates/pkcs8-nopass-der.key', false], ]; } }
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} module Test.Hspec.Wai.Internal ( WaiExpectation , WaiSession(..) , runWaiSession , runWithState , withApplication , getApp , getState , formatHeader ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Network.Wai (Application) import Network.Wai.Test hiding (request) import Test.Hspec.Core.Spec import Test.Hspec.Wai.Util (formatHeader) #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail #endif -- | An expectation in the `WaiSession` monad. Failing expectations are -- communicated through exceptions (similar to `Test.Hspec.Expectations.Expectation` and -- `Test.HUnit.Base.Assertion`). type WaiExpectation st = WaiSession st () -- | A <http://www.yesodweb.com/book/web-application-interface WAI> test -- session that carries the `Application` under test and some client state. newtype WaiSession st a = WaiSession {unWaiSession :: ReaderT st Session a} deriving (Functor, Applicative, Monad, MonadIO #if MIN_VERSION_base(4,9,0) , MonadFail #endif ) runWaiSession :: WaiSession () a -> Application -> IO a runWaiSession action app = runWithState action ((), app) runWithState :: WaiSession st a -> (st, Application) -> IO a runWithState action (st, app) = runSession (flip runReaderT st $ unWaiSession action) app withApplication :: Application -> WaiSession () a -> IO a withApplication = flip runWaiSession instance Example (WaiExpectation st) where type Arg (WaiExpectation st) = (st, Application) evaluateExample e p action = evaluateExample (action $ runWithState e) p ($ ()) getApp :: WaiSession st Application getApp = WaiSession (lift ask) getState :: WaiSession st st getState = WaiSession ask
#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 ); };
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; }
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SQLTransactionErrorCallback (newSQLTransactionErrorCallback, newSQLTransactionErrorCallbackSync, newSQLTransactionErrorCallbackAsync, SQLTransactionErrorCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation> newSQLTransactionErrorCallback :: (MonadDOM m) => (SQLError -> JSM ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallback callback = liftDOM (SQLTransactionErrorCallback . Callback <$> function (\ _ _ [error] -> fromJSValUnchecked error >>= \ error' -> callback error')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation> newSQLTransactionErrorCallbackSync :: (MonadDOM m) => (SQLError -> JSM ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackSync callback = liftDOM (SQLTransactionErrorCallback . Callback <$> function (\ _ _ [error] -> fromJSValUnchecked error >>= \ error' -> callback error')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation> newSQLTransactionErrorCallbackAsync :: (MonadDOM m) => (SQLError -> JSM ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackAsync callback = liftDOM (SQLTransactionErrorCallback . Callback <$> asyncFunction (\ _ _ [error] -> fromJSValUnchecked error >>= \ error' -> callback error'))
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
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]; } } }
# -*- 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']}
module Csvify VERSION = "0.1.0" end
# Automaton [![Hex.pm](https://img.shields.io/hexpm/v/automaton.svg)](https://hex.pm/packages/automaton) [![Build Status](https://semaphoreci.com/api/v1/tslim/automaton/branches/master/shields_badge.svg)](https://semaphoreci.com/tslim/automaton) [![Coverage Status](https://coveralls.io/repos/github/flexnode/automaton/badge.svg?branch=master)](https://coveralls.io/github/flexnode/automaton?branch=master) > Note: This library is still under heavy development. Automaton is an Elixir library that manages the conversation between your chat bot and the user by maintaining the messages and context in a GenServer. This is useful as most messaging platforms (webhooks) and NLP services (REST API) communicates with your backend in the typical Request/Response mode. Automaton aims to be the glue/framework/library to help you focus on your backend instead of messing around with the plumbing of maintaining chat bots. ## Quick Start ```elixir # In your config/config.exs file config :sample, Sample.Bot, adapter: Automaton.Console.Adapter # In your application code # Define your bot defmodule Sample.Bot do use Automaton.Bot, otp_app: :sample # Echo backs whatever you said def process(sender_id, message, context) do reply(sender_id, message, context) end end # In an IEx session iex> Sample.Bot.converse("Hello World") Hello World :ok ``` ## Installation Add Automaton in your `mix.exs` dependencies: ```elixir def deps do [{:automaton, "~> 0.1.0"}] end ``` ## Adapters Platform | Automaton adapter :-----------------| :------------------------ Facebook Messenger| [Automaton.FacebookMessenger.Adapter](https://github.com/flexnode/automaton_fb_messenger) Telegram | Automaton.Telegram.Adapter Slack | Automaton.Slack.Adapter Console (Included)| Automaton.Console.Adapter Configure your adapter in `config/config.exs` file: ```elixir config :sample, Sample.Bot, adapter: Automaton.FacebookMessenger.Adapter # adapter config (api keys, etc.) ``` You can also define custom adapters by implementing callbacks defined in [adapter.ex](https://github.com/flexnode/automaton/blob/master/lib/automaton/adapter.ex) ## Proposed Roadmap - [x] Stores conversation message and context - [x] Adapter layer to support different messaging platforms - [x] Simple callback to process messages/context - [ ] Access to conversation context - [ ] Terminates stale conversation and logs it - [ ] Callback for conversation termination for custom behavior - [ ] Tracks simple metrics like conversation/messages counts ## Documentation More documentation can be found on [hexdocs](https://hex.pm/automaton). You can also find it in the source and it's accessible from iex. ## License Plug source code is released under MIT License. Check [LICENSE](https://github.com/flexnode/automaton/blob/master/LICENSE.md) file for more information.
#!/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
--- layout: post title: mysql导入大文件 categories: 工具使用 mysql tags: ssh --- * content {:toc} ## 说明 使用mysql客户端导入数据量过大的sql文件,速度是非常慢点。使用命令行就可以轻松导入比较大的文件. ## 操作 1. 使用mysql source 不推荐 ```mysql use dbtest; set names utf8; source D:/www/sql/back.sql; ``` source被设计成运行少量的sql语句并显示输出,并不适合导入大量数据。 2. 直接执行命令 * 确保mysql正在运行,登录到mysql shell * 执行命令:`mysql -u root -p database_name < database_dump_file.sql` 替换成你的数据库和要导入的文件 * 输入密码
<div class="container"> <h5 style="display: inline">Remain energy </h5><h5 style="display: inline">{{remainEnergy| number:'1.2-2'}} watts</h5><h5 style="display: inline">, used energy </h5><h5 style="display: inline">{{usedEnergy| number:'1.2-2'}}</h5><h5 style="display: inline">, for day.</h5> </div> <div> <div class="container row"> <table class="table table-striped col s5" [mfData]="data" #mf="mfDataTable" [mfRowsOnPage]="5"> <thead> <tr> <th style="width: 80%"> <mfDefaultSorter by="name">Name</mfDefaultSorter> </th> <th style="width: 20%"> <mfDefaultSorter by="watts">Watts</mfDefaultSorter> </th> </tr> </thead> <tbody> <tr style="cursor: pointer;" *ngFor="let item of toDos" (click)="addTodo(item)"> <td>{{item.name}}</td> <td>{{item.watts}}</td> </tr> </tbody> <tfoot> <tr> <td colspan="4"> <mfBootstrapPaginator [rowsOnPageSet]="[5,10,25]"></mfBootstrapPaginator> </td> </tr> </tfoot> </table> <div class="col s1"></div> <table class="table table-striped col s5" [mfData]="data" #mf="mfDataTable" [mfRowsOnPage]="5"> <thead> <tr> <th style="width: 50%"> <mfDefaultSorter by="name">Name</mfDefaultSorter> </th> <th style="width: 22%"> <mfDefaultSorter by="minutes">Minutes</mfDefaultSorter> </th> <th style="width: 22%"> <mfDefaultSorter by="watts">Watts</mfDefaultSorter> </th> <th style="width: 6%"> <mfDefaultSorter>Remove</mfDefaultSorter> </th> </tr> </thead> <tbody> <tr *ngFor="let item of myTodos"> <td>{{item.name}}</td> <td><input style="margin:0;border-bottom: none; height: inherit;" [(ngModel)]="item.minutes" (change)="changeMyTodo(item)"></td> <td>{{item.sumWatts| number:'1.2-2'}}</td> <td style="float: right; color: red; cursor: pointer;" (click)="deleteTodo(item)">x</td> </tr> </tbody> <tfoot> <tr> <td colspan="4"> <mfBootstrapPaginator [rowsOnPageSet]="[5,10,25]"></mfBootstrapPaginator> </td> </tr> </tfoot> </table> </div> </div>
import re import datetime import time #niru's git commit while True: #open the file for reading file = open("test.txt") content = file.read() #Get timestamp ts = time.time() ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') #open file for read and close it neatly(wrap code in try/except) #with open('test.txt', 'r') as r: #content = r.read() #print content #Search the entire content for '@' and replace it with time stamp. new_content = re.sub(r'@.*', ist, content) print new_content #open file for write and close it neatly(wrap code in try/except) with open('test.txt', 'w') as f: f.write(new_content) print "torpid loop complete" time.sleep(5)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>higman-s: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / higman-s - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> higman-s <small> 8.5.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2019-11-30 21:22:11 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2019-11-30 21:22:11 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/higman-s&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/HigmanS&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:higman&#39;s lemma&quot; &quot;keyword:well quasi ordering&quot; &quot;category:Mathematics/Combinatorics and Graph Theory&quot; &quot;date:2007-09-14&quot; ] authors: [ &quot;William Delobel &lt;william.delobel@lif.univ-mrs.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/higman-s/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/higman-s.git&quot; synopsis: &quot;Higman&#39;s lemma on an unrestricted alphabet&quot; description: &quot;This proof is more or less the proof given by Monika Seisenberger in \&quot;An Inductive Version of Nash-Williams&#39; Minimal-Bad-Sequence Argument for Higman&#39;s Lemma\&quot;.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/higman-s/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=3f304e5b60fe9760b55d0d3ed2ca8d51&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-higman-s.8.5.0 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-higman-s -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-higman-s.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>