code
stringlengths
4
991k
repo_name
stringlengths
6
116
path
stringlengths
4
249
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
4
991k
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
/* * Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.core.jdk17; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import com.oracle.svm.core.jdk.JDK17OrLater; @TargetClass(className = "jdk.internal.loader.BootLoader", onlyWith = JDK17OrLater.class) final class Target_jdk_internal_loader_BootLoader_JDK17OrLater { @SuppressWarnings("unused") @Substitute private static void loadLibrary(String name) { System.loadLibrary(name); } }
smarr/Truffle
substratevm/src/com.oracle.svm.core.jdk17/src/com/oracle/svm/core/jdk17/Target_jdk_internal_loader_BootLoader_JDK17OrLater.java
Java
gpl-2.0
1,689
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 12609, 1010, 12609, 1010, 14721, 1998, 1013, 2030, 2049, 18460, 1012, 2035, 2916, 9235, 1012, 1008, 2079, 2025, 11477, 2030, 6366, 9385, 14444, 2030, 2023, 5371, 20346, 1012, 1008, 1008, 2023...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE) // // This file is part of Olena. // // Olena is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free // Software Foundation, version 2 of the License. // // Olena is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Olena. If not, see <http://www.gnu.org/licenses/>. // // As a special exception, you may use this file as part of a free // software project without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to produce // an executable, this file does not by itself cause the resulting // executable to be covered by the GNU General Public License. This // exception does not however invalidate any other reasons why the // executable file might be covered by the GNU General Public License. #include <mln/util/lemmings.hh> #include <mln/core/image/image2d.hh> int main () { using namespace mln; typedef image2d<int> I; int vals[4][4] = {{2, 2, 6, 6}, {2, 2, 6, 6}, {3, 3, 4, 4}, {3, 3, 4, 4}}; I ima = make::image<int>(vals); point2d pt1(1, 0), pt2(0, 2), pt3(2, 3), pt4(3, 1), pt5(1, 1); int vl1 = ima(pt1), vl2 = ima(pt2), vl3 = ima(pt3), vl4 = ima(pt4), vl5 = ima(pt5); point2d ptl1 = util::lemmings(ima, pt1, right, vl1), ptl2 = util::lemmings(ima, pt2, down, vl2), ptl3 = util::lemmings(ima, pt3, left, vl3), ptl4 = util::lemmings(ima, pt4, up, vl4), ptl5 = util::lemmings(ima, pt5, up, vl5); mln_assertion(ptl1 == point2d(1, 2)); mln_assertion(ptl2 == point2d(2, 2)); mln_assertion(ptl3 == point2d(2, 1)); mln_assertion(ptl4 == point2d(1, 1)); mln_assertion(ptl5 == point2d(-1, 1)); }
codingforfun/Olena-Mirror
milena/tests/util/lemmings.cc
C++
gpl-2.0
2,176
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2289, 1010, 2263, 1010, 2268, 4958, 6590, 2470, 1998, 2458, 5911, 1006, 1048, 25547, 1007, 1013, 1013, 1013, 1013, 2023, 5371, 2003, 2112, 1997, 15589, 2532, 1012, 1013, 1013, 1013, 1013, 15589, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import io import string import random # Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'. # # roll := die {('+' | '-') die} ('+' | '-') modifier # die := number 'd' number # modifier := number class StringBuf(object): def __init__(self, s): self.s = s self.pos = 0 def peek(self): return self.s[self.pos] def getc(self): c = self.peek() self.pos += 1 return c def ungetc(self): self.pos -= 1 def tell(self): return self.pos class Symbol(object): NUMBER = 0 D = 1 PLUS = 2 MINUS = 3 def __init__(self, type_, pos, value) def next_symbol(s): c = s.getc() while c in string.whitespace: c = s.getc() if c in string.digits: # start of a number literal = c c = s.getc() while c in string.digits: literal += c c = s.getc() s.ungetc() sym = (Symbol.NUMBER, elif c == 'd': # die indicator pass elif c == '+': # plus sign pass elif c == '-': # minus sign pass else: # unrecognized input raise ValueError('Syntax error at position ' + s.tell()) return ()
jcarreiro/jmc-python
imp/dice.py
Python
mit
1,405
[ 30522, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 7619, 1035, 12324, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 2407, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 6140, 1035, 3853, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 27260, 1035, 18204...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Grunion Contact Form * Add a contact form to any post, page or text widget. * Emails will be sent to the post's author by default, or any email address you choose. * * @package Jetpack */ use Automattic\Jetpack\Assets; use Automattic\Jetpack\Blocks; use Automattic\Jetpack\Sync\Settings; define( 'GRUNION_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'GRUNION_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); if ( is_admin() ) { require_once GRUNION_PLUGIN_DIR . 'admin.php'; } add_action( 'rest_api_init', 'grunion_contact_form_require_endpoint' ); function grunion_contact_form_require_endpoint() { require_once GRUNION_PLUGIN_DIR . 'class-grunion-contact-form-endpoint.php'; } /** * Sets up various actions, filters, post types, post statuses, shortcodes. */ class Grunion_Contact_Form_Plugin { /** * @var string The Widget ID of the widget currently being processed. Used to build the unique contact-form ID for forms embedded in widgets. */ public $current_widget_id; static $using_contact_form_field = false; /** * @var int The last Feedback Post ID Erased as part of the Personal Data Eraser. * Helps with pagination. */ private $pde_last_post_id_erased = 0; /** * @var string The email address for which we are deleting/exporting all feedbacks * as part of a Personal Data Eraser or Personal Data Exporter request. */ private $pde_email_address = ''; static function init() { static $instance = false; if ( ! $instance ) { $instance = new Grunion_Contact_Form_Plugin(); // Schedule our daily cleanup add_action( 'wp_scheduled_delete', array( $instance, 'daily_akismet_meta_cleanup' ) ); } return $instance; } /** * Runs daily to clean up spam detection metadata after 15 days. Keeps your DB squeaky clean. */ public function daily_akismet_meta_cleanup() { global $wpdb; $feedback_ids = $wpdb->get_col( "SELECT p.ID FROM {$wpdb->posts} as p INNER JOIN {$wpdb->postmeta} as m on m.post_id = p.ID WHERE p.post_type = 'feedback' AND m.meta_key = '_feedback_akismet_values' AND DATE_SUB(NOW(), INTERVAL 15 DAY) > p.post_date_gmt LIMIT 10000" ); if ( empty( $feedback_ids ) ) { return; } /** * Fires right before deleting the _feedback_akismet_values post meta on $feedback_ids * * @module contact-form * * @since 6.1.0 * * @param array $feedback_ids list of feedback post ID */ do_action( 'jetpack_daily_akismet_meta_cleanup_before', $feedback_ids ); foreach ( $feedback_ids as $feedback_id ) { delete_post_meta( $feedback_id, '_feedback_akismet_values' ); } /** * Fires right after deleting the _feedback_akismet_values post meta on $feedback_ids * * @module contact-form * * @since 6.1.0 * * @param array $feedback_ids list of feedback post ID */ do_action( 'jetpack_daily_akismet_meta_cleanup_after', $feedback_ids ); } /** * Strips HTML tags from input. Output is NOT HTML safe. * * @param mixed $data_with_tags * @return mixed */ public static function strip_tags( $data_with_tags ) { if ( is_array( $data_with_tags ) ) { foreach ( $data_with_tags as $index => $value ) { $index = sanitize_text_field( (string) $index ); $value = wp_kses( (string) $value, array() ); $value = str_replace( '&amp;', '&', $value ); // undo damage done by wp_kses_normalize_entities() $data_without_tags[ $index ] = $value; } } else { $data_without_tags = wp_kses( $data_with_tags, array() ); $data_without_tags = str_replace( '&amp;', '&', $data_without_tags ); // undo damage done by wp_kses_normalize_entities() } return $data_without_tags; } /** * Class uses singleton pattern; use Grunion_Contact_Form_Plugin::init() to initialize. */ protected function __construct() { $this->add_shortcode(); // While generating the output of a text widget with a contact-form shortcode, we need to know its widget ID. add_action( 'dynamic_sidebar', array( $this, 'track_current_widget' ) ); // Add a "widget" shortcode attribute to all contact-form shortcodes embedded in widgets add_filter( 'widget_text', array( $this, 'widget_atts' ), 0 ); // If Text Widgets don't get shortcode processed, hack ours into place. if ( version_compare( get_bloginfo( 'version' ), '4.9-z', '<=' ) && ! has_filter( 'widget_text', 'do_shortcode' ) ) { add_filter( 'widget_text', array( $this, 'widget_shortcode_hack' ), 5 ); } add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_blocklist' ), 10, 2 ); add_filter( 'jetpack_contact_form_in_comment_disallowed_list', array( $this, 'is_in_disallowed_list' ), 10, 2 ); // Akismet to the rescue if ( defined( 'AKISMET_VERSION' ) || function_exists( 'akismet_http_post' ) ) { add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_akismet' ), 10, 2 ); add_action( 'contact_form_akismet', array( $this, 'akismet_submit' ), 10, 2 ); } add_action( 'loop_start', array( 'Grunion_Contact_Form', '_style_on' ) ); add_action( 'pre_amp_render_post', array( 'Grunion_Contact_Form', '_style_on' ) ); add_action( 'wp_ajax_grunion-contact-form', array( $this, 'ajax_request' ) ); add_action( 'wp_ajax_nopriv_grunion-contact-form', array( $this, 'ajax_request' ) ); // GDPR: personal data exporter & eraser. add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'register_personal_data_exporter' ) ); add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_personal_data_eraser' ) ); // Export to CSV feature if ( is_admin() ) { add_action( 'admin_init', array( $this, 'download_feedback_as_csv' ) ); add_action( 'admin_footer-edit.php', array( $this, 'export_form' ) ); add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'current_screen', array( $this, 'unread_count' ) ); } // custom post type we'll use to keep copies of the feedback items register_post_type( 'feedback', array( 'labels' => array( 'name' => __( 'Feedback', 'jetpack' ), 'singular_name' => __( 'Feedback', 'jetpack' ), 'search_items' => __( 'Search Feedback', 'jetpack' ), 'not_found' => __( 'No feedback found', 'jetpack' ), 'not_found_in_trash' => __( 'No feedback found', 'jetpack' ), ), 'menu_icon' => 'dashicons-feedback', 'show_ui' => true, 'show_in_admin_bar' => false, 'public' => false, 'rewrite' => false, 'query_var' => false, 'capability_type' => 'page', 'show_in_rest' => true, 'rest_controller_class' => 'Grunion_Contact_Form_Endpoint', 'capabilities' => array( 'create_posts' => 'do_not_allow', 'publish_posts' => 'publish_pages', 'edit_posts' => 'edit_pages', 'edit_others_posts' => 'edit_others_pages', 'delete_posts' => 'delete_pages', 'delete_others_posts' => 'delete_others_pages', 'read_private_posts' => 'read_private_pages', 'edit_post' => 'edit_page', 'delete_post' => 'delete_page', 'read_post' => 'read_page', ), 'map_meta_cap' => true, ) ); // Add to REST API post type allowed list. add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_feedback_rest_api_type' ) ); // Add "spam" as a post status register_post_status( 'spam', array( 'label' => 'Spam', 'public' => false, 'exclude_from_search' => true, 'show_in_admin_all_list' => false, 'label_count' => _n_noop( 'Spam <span class="count">(%s)</span>', 'Spam <span class="count">(%s)</span>', 'jetpack' ), 'protected' => true, '_builtin' => false, ) ); // POST handler if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['action'] ) && 'grunion-contact-form' == $_POST['action'] && isset( $_POST['contact-form-id'] ) ) { add_action( 'template_redirect', array( $this, 'process_form_submission' ) ); } /* Can be dequeued by placing the following in wp-content/themes/yourtheme/functions.php * * function remove_grunion_style() { * wp_deregister_style('grunion.css'); * } * add_action('wp_print_styles', 'remove_grunion_style'); */ wp_register_style( 'grunion.css', GRUNION_PLUGIN_URL . 'css/grunion.css', array(), JETPACK__VERSION ); wp_style_add_data( 'grunion.css', 'rtl', 'replace' ); self::register_contact_form_blocks(); } private static function register_contact_form_blocks() { Blocks::jetpack_register_block( 'jetpack/contact-form', array( 'render_callback' => array( __CLASS__, 'gutenblock_render_form' ), ) ); // Field render methods. Blocks::jetpack_register_block( 'jetpack/field-text', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_text' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-name', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_name' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-email', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_email' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-url', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_url' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-date', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_date' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-telephone', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_telephone' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-textarea', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_textarea' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-checkbox', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_checkbox' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-checkbox-multiple', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_checkbox_multiple' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-radio', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_radio' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-select', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_select' ), ) ); Blocks::jetpack_register_block( 'jetpack/field-consent', array( 'parent' => array( 'jetpack/contact-form' ), 'render_callback' => array( __CLASS__, 'gutenblock_render_field_consent' ), ) ); } public static function gutenblock_render_form( $atts, $content ) { // Render fallback in other contexts than frontend (i.e. feed, emails, API, etc.), unless the form is being submitted. if ( ! jetpack_is_frontend() && ! isset( $_POST['contact-form-id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing return sprintf( '<div class="%1$s"><a href="%2$s" target="_blank" rel="noopener noreferrer">%3$s</a></div>', esc_attr( Blocks::classes( 'contact-form', $atts ) ), esc_url( get_the_permalink() ), esc_html__( 'Submit a form.', 'jetpack' ) ); } return Grunion_Contact_Form::parse( $atts, do_blocks( $content ) ); } public static function block_attributes_to_shortcode_attributes( $atts, $type ) { $atts['type'] = $type; if ( isset( $atts['className'] ) ) { $atts['class'] = $atts['className']; unset( $atts['className'] ); } if ( isset( $atts['defaultValue'] ) ) { $atts['default'] = $atts['defaultValue']; unset( $atts['defaultValue'] ); } return $atts; } public static function gutenblock_render_field_text( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'text' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_name( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'name' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_email( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'email' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_url( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'url' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_date( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'date' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_telephone( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'telephone' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_textarea( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'textarea' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_checkbox( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'checkbox' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_checkbox_multiple( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'checkbox-multiple' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_radio( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'radio' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } public static function gutenblock_render_field_select( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'select' ); return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } /** * Render the consent field. * * @param string $atts consent attributes. * @param string $content html content. */ public static function gutenblock_render_field_consent( $atts, $content ) { $atts = self::block_attributes_to_shortcode_attributes( $atts, 'consent' ); if ( ! isset( $atts['implicitConsentMessage'] ) ) { $atts['implicitConsentMessage'] = __( "By submitting your information, you're giving us permission to email you. You may unsubscribe at any time.", 'jetpack' ); } if ( ! isset( $atts['explicitConsentMessage'] ) ) { $atts['explicitConsentMessage'] = __( 'Can we send you an email from time to time?', 'jetpack' ); } return Grunion_Contact_Form::parse_contact_field( $atts, $content ); } /** * Add the 'Export' menu item as a submenu of Feedback. */ public function admin_menu() { add_submenu_page( 'edit.php?post_type=feedback', __( 'Export feedback as CSV', 'jetpack' ), __( 'Export CSV', 'jetpack' ), 'export', 'feedback-export', array( $this, 'export_form' ) ); } /** * Add to REST API post type allowed list. */ function allow_feedback_rest_api_type( $post_types ) { $post_types[] = 'feedback'; return $post_types; } /** * Display the count of new feedback entries received. It's reset when user visits the Feedback screen. * * @since 4.1.0 * * @param object $screen Information about the current screen. */ function unread_count( $screen ) { if ( isset( $screen->post_type ) && 'feedback' == $screen->post_type ) { update_option( 'feedback_unread_count', 0 ); } else { global $menu; if ( isset( $menu ) && is_array( $menu ) && ! empty( $menu ) ) { foreach ( $menu as $index => $menu_item ) { if ( 'edit.php?post_type=feedback' == $menu_item[2] ) { $unread = get_option( 'feedback_unread_count', 0 ); if ( $unread > 0 ) { $unread_count = current_user_can( 'publish_pages' ) ? " <span class='feedback-unread count-{$unread} awaiting-mod'><span class='feedback-unread-count'>" . number_format_i18n( $unread ) . '</span></span>' : ''; $menu[ $index ][0] .= $unread_count; } break; } } } } } /** * Handles all contact-form POST submissions * * Conditionally attached to `template_redirect` */ function process_form_submission() { // Add a filter to replace tokens in the subject field with sanitized field values add_filter( 'contact_form_subject', array( $this, 'replace_tokens_with_input' ), 10, 2 ); $id = stripslashes( $_POST['contact-form-id'] ); $hash = isset( $_POST['contact-form-hash'] ) ? $_POST['contact-form-hash'] : ''; $hash = preg_replace( '/[^\da-f]/i', '', $hash ); if ( ! is_string( $id ) || ! is_string( $hash ) ) { return false; } if ( is_user_logged_in() ) { check_admin_referer( "contact-form_{$id}" ); } $is_widget = 0 === strpos( $id, 'widget-' ); $form = false; if ( $is_widget ) { // It's a form embedded in a text widget $this->current_widget_id = substr( $id, 7 ); // remove "widget-" $widget_type = implode( '-', array_slice( explode( '-', $this->current_widget_id ), 0, -1 ) ); // Remove trailing -# // Is the widget active? $sidebar = is_active_widget( false, $this->current_widget_id, $widget_type ); // This is lame - no core API for getting a widget by ID $widget = isset( $GLOBALS['wp_registered_widgets'][ $this->current_widget_id ] ) ? $GLOBALS['wp_registered_widgets'][ $this->current_widget_id ] : false; if ( $sidebar && $widget && isset( $widget['callback'] ) ) { // prevent PHP notices by populating widget args $widget_args = array( 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ); // This is lamer - no API for outputting a given widget by ID ob_start(); // Process the widget to populate Grunion_Contact_Form::$last call_user_func( $widget['callback'], $widget_args, $widget['params'][0] ); ob_end_clean(); } } else { // It's a form embedded in a post $post = get_post( $id ); // Process the content to populate Grunion_Contact_Form::$last if ( $post ) { /** This filter is already documented in core. wp-includes/post-template.php */ apply_filters( 'the_content', $post->post_content ); } } $form = isset( Grunion_Contact_Form::$forms[ $hash ] ) ? Grunion_Contact_Form::$forms[ $hash ] : null; // No form may mean user is using do_shortcode, grab the form using the stored post meta if ( ! $form && is_numeric( $id ) && $hash ) { // Get shortcode from post meta $shortcode = get_post_meta( $id, "_g_feedback_shortcode_{$hash}", true ); // Format it if ( $shortcode != '' ) { // Get attributes from post meta. $parameters = ''; $attributes = get_post_meta( $id, "_g_feedback_shortcode_atts_{$hash}", true ); if ( ! empty( $attributes ) && is_array( $attributes ) ) { foreach ( array_filter( $attributes ) as $param => $value ) { $parameters .= " $param=\"$value\""; } } $shortcode = '[contact-form' . $parameters . ']' . $shortcode . '[/contact-form]'; do_shortcode( $shortcode ); // Recreate form $form = Grunion_Contact_Form::$last; } } if ( ! $form ) { return false; } if ( is_wp_error( $form->errors ) && $form->errors->get_error_codes() ) { return $form->errors; } // Process the form return $form->process_submission(); } function ajax_request() { $submission_result = self::process_form_submission(); if ( ! $submission_result ) { header( 'HTTP/1.1 500 Server Error', 500, true ); echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">'; esc_html_e( 'An error occurred. Please try again later.', 'jetpack' ); echo '</li></ul></div>'; } elseif ( is_wp_error( $submission_result ) ) { header( 'HTTP/1.1 400 Bad Request', 403, true ); echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">'; echo esc_html( $submission_result->get_error_message() ); echo '</li></ul></div>'; } else { echo '<h3>' . esc_html__( 'Message Sent', 'jetpack' ) . '</h3>' . $submission_result; } die; } /** * Ensure the post author is always zero for contact-form feedbacks * Attached to `wp_insert_post_data` * * @see Grunion_Contact_Form::process_submission() * * @param array $data the data to insert * @param array $postarr the data sent to wp_insert_post() * @return array The filtered $data to insert */ function insert_feedback_filter( $data, $postarr ) { if ( $data['post_type'] == 'feedback' && $postarr['post_type'] == 'feedback' ) { $data['post_author'] = 0; } return $data; } /* * Adds our contact-form shortcode * The "child" contact-field shortcode is enabled as needed by the contact-form shortcode handler */ function add_shortcode() { add_shortcode( 'contact-form', array( 'Grunion_Contact_Form', 'parse' ) ); add_shortcode( 'contact-field', array( 'Grunion_Contact_Form', 'parse_contact_field' ) ); } static function tokenize_label( $label ) { return '{' . trim( preg_replace( '#^\d+_#', '', $label ) ) . '}'; } static function sanitize_value( $value ) { return preg_replace( '=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $value ); } /** * Replaces tokens like {city} or {City} (case insensitive) with the value * of an input field of that name * * @param string $subject * @param array $field_values Array with field label => field value associations * * @return string The filtered $subject with the tokens replaced */ function replace_tokens_with_input( $subject, $field_values ) { // Wrap labels into tokens (inside {}) $wrapped_labels = array_map( array( 'Grunion_Contact_Form_Plugin', 'tokenize_label' ), array_keys( $field_values ) ); // Sanitize all values $sanitized_values = array_map( array( 'Grunion_Contact_Form_Plugin', 'sanitize_value' ), array_values( $field_values ) ); foreach ( $sanitized_values as $k => $sanitized_value ) { if ( is_array( $sanitized_value ) ) { $sanitized_values[ $k ] = implode( ', ', $sanitized_value ); } } // Search for all valid tokens (based on existing fields) and replace with the field's value $subject = str_ireplace( $wrapped_labels, $sanitized_values, $subject ); return $subject; } /** * Tracks the widget currently being processed. * Attached to `dynamic_sidebar` * * @see $current_widget_id * * @param array $widget The widget data */ function track_current_widget( $widget ) { $this->current_widget_id = $widget['id']; } /** * Adds a "widget" attribute to every contact-form embedded in a text widget. * Used to tell the difference between post-embedded contact-forms and widget-embedded contact-forms * Attached to `widget_text` * * @param string $text The widget text * @return string The filtered widget text */ function widget_atts( $text ) { Grunion_Contact_Form::style( true ); return preg_replace( '/\[contact-form([^a-zA-Z_-])/', '[contact-form widget="' . $this->current_widget_id . '"\\1', $text ); } /** * For sites where text widgets are not processed for shortcodes, we add this hack to process just our shortcode * Attached to `widget_text` * * @param string $text The widget text * @return string The contact-form filtered widget text */ function widget_shortcode_hack( $text ) { if ( ! preg_match( '/\[contact-form([^a-zA-Z_-])/', $text ) ) { return $text; } $old = $GLOBALS['shortcode_tags']; remove_all_shortcodes(); Grunion_Contact_Form_Plugin::$using_contact_form_field = true; $this->add_shortcode(); $text = do_shortcode( $text ); Grunion_Contact_Form_Plugin::$using_contact_form_field = false; $GLOBALS['shortcode_tags'] = $old; return $text; } /** * Check if a submission matches the Comment Blocklist. * The Comment Blocklist is a means to moderate discussion, and contact * forms are 1:1 discussion forums, ripe for abuse by users who are being * removed from the public discussion. * Attached to `jetpack_contact_form_is_spam` * * @param bool $is_spam * @param array $form * @return bool TRUE => spam, FALSE => not spam */ public function is_spam_blocklist( $is_spam, $form = array() ) { if ( $is_spam ) { return $is_spam; } return $this->is_in_disallowed_list( false, $form ); } /** * Check if a submission matches the comment disallowed list. * Attached to `jetpack_contact_form_in_comment_disallowed_list`. * * @param boolean $in_disallowed_list Whether the feedback is in the disallowed list. * @param array $form The form array. * @return bool Returns true if the form submission matches the disallowed list and false if it doesn't. */ public function is_in_disallowed_list( $in_disallowed_list, $form = array() ) { if ( $in_disallowed_list ) { return $in_disallowed_list; } if ( wp_check_comment_disallowed_list( $form['comment_author'], $form['comment_author_email'], $form['comment_author_url'], $form['comment_content'], $form['user_ip'], $form['user_agent'] ) ) { return true; } return false; } /** * Populate an array with all values necessary to submit a NEW contact-form feedback to Akismet. * Note that this includes the current user_ip etc, so this should only be called when accepting a new item via $_POST * * @param array $form Contact form feedback array * @return array feedback array with additional data ready for submission to Akismet */ function prepare_for_akismet( $form ) { $form['comment_type'] = 'contact_form'; $form['user_ip'] = $_SERVER['REMOTE_ADDR']; $form['user_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : ''; $form['referrer'] = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : ''; $form['blog'] = get_option( 'home' ); foreach ( $_SERVER as $key => $value ) { if ( ! is_string( $value ) ) { continue; } if ( in_array( $key, array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'HTTP_USER_AGENT', 'HTTP_REFERER' ) ) ) { // We don't care about cookies, and the UA and Referrer were caught above. continue; } elseif ( in_array( $key, array( 'REMOTE_ADDR', 'REQUEST_URI', 'DOCUMENT_URI' ) ) ) { // All three of these are relevant indicators and should be passed along. $form[ $key ] = $value; } elseif ( wp_startswith( $key, 'HTTP_' ) ) { // Any other HTTP header indicators. // `wp_startswith()` is a wpcom helper function and is included in Jetpack via `functions.compat.php` $form[ $key ] = $value; } } return $form; } /** * Submit contact-form data to Akismet to check for spam. * If you're accepting a new item via $_POST, run it Grunion_Contact_Form_Plugin::prepare_for_akismet() first * Attached to `jetpack_contact_form_is_spam` * * @param bool $is_spam * @param array $form * @return bool|WP_Error TRUE => spam, FALSE => not spam, WP_Error => stop processing entirely */ function is_spam_akismet( $is_spam, $form = array() ) { global $akismet_api_host, $akismet_api_port; // The signature of this function changed from accepting just $form. // If something only sends an array, assume it's still using the old // signature and work around it. if ( empty( $form ) && is_array( $is_spam ) ) { $form = $is_spam; $is_spam = false; } // If a previous filter has alrady marked this as spam, trust that and move on. if ( $is_spam ) { return $is_spam; } if ( ! function_exists( 'akismet_http_post' ) && ! defined( 'AKISMET_VERSION' ) ) { return false; } $query_string = http_build_query( $form ); if ( method_exists( 'Akismet', 'http_post' ) ) { $response = Akismet::http_post( $query_string, 'comment-check' ); } else { $response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port ); } $result = false; if ( isset( $response[0]['x-akismet-pro-tip'] ) && 'discard' === trim( $response[0]['x-akismet-pro-tip'] ) && get_option( 'akismet_strictness' ) === '1' ) { $result = new WP_Error( 'feedback-discarded', __( 'Feedback discarded.', 'jetpack' ) ); } elseif ( isset( $response[1] ) && 'true' == trim( $response[1] ) ) { // 'true' is spam $result = true; } /** * Filter the results returned by Akismet for each submitted contact form. * * @module contact-form * * @since 1.3.1 * * @param WP_Error|bool $result Is the submitted feedback spam. * @param array|bool $form Submitted feedback. */ return apply_filters( 'contact_form_is_spam_akismet', $result, $form ); } /** * Submit a feedback as either spam or ham * * @param string $as Either 'spam' or 'ham'. * @param array $form the contact-form data */ function akismet_submit( $as, $form ) { global $akismet_api_host, $akismet_api_port; if ( ! in_array( $as, array( 'ham', 'spam' ) ) ) { return false; } $query_string = ''; if ( is_array( $form ) ) { $query_string = http_build_query( $form ); } if ( method_exists( 'Akismet', 'http_post' ) ) { $response = Akismet::http_post( $query_string, "submit-{$as}" ); } else { $response = akismet_http_post( $query_string, $akismet_api_host, "/1.1/submit-{$as}", $akismet_api_port ); } return trim( $response[1] ); } /** * Prints the menu */ function export_form() { $current_screen = get_current_screen(); if ( ! in_array( $current_screen->id, array( 'edit-feedback', 'feedback_page_feedback-export' ) ) ) { return; } if ( ! current_user_can( 'export' ) ) { return; } // if there aren't any feedbacks, bail out if ( ! (int) wp_count_posts( 'feedback' )->publish ) { return; } ?> <div id="feedback-export" style="display:none"> <h2><?php _e( 'Export feedback as CSV', 'jetpack' ); ?></h2> <div class="clear"></div> <form action="<?php echo admin_url( 'admin-post.php' ); ?>" method="post" class="form"> <?php wp_nonce_field( 'feedback_export', 'feedback_export_nonce' ); ?> <input name="action" value="feedback_export" type="hidden"> <label for="post"><?php _e( 'Select feedback to download', 'jetpack' ); ?></label> <select name="post"> <option value="all"><?php esc_html_e( 'All posts', 'jetpack' ); ?></option> <?php echo $this->get_feedbacks_as_options(); ?> </select> <br><br> <input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_html_e( 'Download', 'jetpack' ); ?>"> </form> </div> <?php // There aren't any usable actions in core to output the "export feedback" form in the correct place, // so this inline JS moves it from the top of the page to the bottom. ?> <script type='text/javascript'> var menu = document.getElementById( 'feedback-export' ), wrapper = document.getElementsByClassName( 'wrap' )[0]; <?php if ( 'edit-feedback' === $current_screen->id ) : ?> wrapper.appendChild(menu); <?php endif; ?> menu.style.display = 'block'; </script> <?php } /** * Fetch post content for a post and extract just the comment. * * @param int $post_id The post id to fetch the content for. * * @return string Trimmed post comment. * * @codeCoverageIgnore */ public function get_post_content_for_csv_export( $post_id ) { $post_content = get_post_field( 'post_content', $post_id ); $content = explode( '<!--more-->', $post_content ); return trim( $content[0] ); } /** * Get `_feedback_extra_fields` field from post meta data. * * @param int $post_id Id of the post to fetch meta data for. * * @return mixed */ public function get_post_meta_for_csv_export( $post_id ) { $md = get_post_meta( $post_id, '_feedback_extra_fields', true ); $md['feedback_date'] = get_the_date( DATE_RFC3339, $post_id ); $content_fields = self::parse_fields_from_content( $post_id ); $md['feedback_ip'] = ( isset( $content_fields['_feedback_ip'] ) ) ? $content_fields['_feedback_ip'] : 0; // add the email_marketing_consent to the post meta. $md['email_marketing_consent'] = 0; if ( isset( $content_fields['_feedback_all_fields'] ) ) { $all_fields = $content_fields['_feedback_all_fields']; // check if the email_marketing_consent field exists. if ( isset( $all_fields['email_marketing_consent'] ) ) { $md['email_marketing_consent'] = $all_fields['email_marketing_consent']; } } return $md; } /** * Get parsed feedback post fields. * * @param int $post_id Id of the post to fetch parsed contents for. * * @return array * * @codeCoverageIgnore - No need to be covered. */ public function get_parsed_field_contents_of_post( $post_id ) { return self::parse_fields_from_content( $post_id ); } /** * Properly maps fields that are missing from the post meta data * to names, that are similar to those of the post meta. * * @param array $parsed_post_content Parsed post content * * @see parse_fields_from_content for how the input data is generated. * * @return array Mapped fields. */ public function map_parsed_field_contents_of_post_to_field_names( $parsed_post_content ) { $mapped_fields = array(); $field_mapping = array( '_feedback_subject' => __( 'Contact Form', 'jetpack' ), '_feedback_author' => '1_Name', '_feedback_author_email' => '2_Email', '_feedback_author_url' => '3_Website', '_feedback_main_comment' => '4_Comment', '_feedback_author_ip' => '5_IP', ); foreach ( $field_mapping as $parsed_field_name => $field_name ) { if ( isset( $parsed_post_content[ $parsed_field_name ] ) && ! empty( $parsed_post_content[ $parsed_field_name ] ) ) { $mapped_fields[ $field_name ] = $parsed_post_content[ $parsed_field_name ]; } } return $mapped_fields; } /** * Registers the personal data exporter. * * @since 6.1.1 * * @param array $exporters An array of personal data exporters. * * @return array $exporters An array of personal data exporters. */ public function register_personal_data_exporter( $exporters ) { $exporters['jetpack-feedback'] = array( 'exporter_friendly_name' => __( 'Feedback', 'jetpack' ), 'callback' => array( $this, 'personal_data_exporter' ), ); return $exporters; } /** * Registers the personal data eraser. * * @since 6.1.1 * * @param array $erasers An array of personal data erasers. * * @return array $erasers An array of personal data erasers. */ public function register_personal_data_eraser( $erasers ) { $erasers['jetpack-feedback'] = array( 'eraser_friendly_name' => __( 'Feedback', 'jetpack' ), 'callback' => array( $this, 'personal_data_eraser' ), ); return $erasers; } /** * Exports personal data. * * @since 6.1.1 * * @param string $email Email address. * @param int $page Page to export. * * @return array $return Associative array with keys expected by core. */ public function personal_data_exporter( $email, $page = 1 ) { return $this->_internal_personal_data_exporter( $email, $page ); } /** * Internal method for exporting personal data. * * Allows us to have a different signature than core expects * while protecting against future core API changes. * * @internal * @since 6.5 * * @param string $email Email address. * @param int $page Page to export. * @param int $per_page Number of feedbacks to process per page. Internal use only (testing) * * @return array Associative array with keys expected by core. */ public function _internal_personal_data_exporter( $email, $page = 1, $per_page = 250 ) { $export_data = array(); $post_ids = $this->personal_data_post_ids_by_email( $email, $per_page, $page ); foreach ( $post_ids as $post_id ) { $post_fields = $this->get_parsed_field_contents_of_post( $post_id ); if ( ! is_array( $post_fields ) || empty( $post_fields['_feedback_subject'] ) ) { continue; // Corrupt data. } $post_fields['_feedback_main_comment'] = $this->get_post_content_for_csv_export( $post_id ); $post_fields = $this->map_parsed_field_contents_of_post_to_field_names( $post_fields ); if ( ! is_array( $post_fields ) || empty( $post_fields ) ) { continue; // No fields to export. } $post_meta = $this->get_post_meta_for_csv_export( $post_id ); $post_meta = is_array( $post_meta ) ? $post_meta : array(); $post_export_data = array(); $post_data = array_merge( $post_fields, $post_meta ); ksort( $post_data ); foreach ( $post_data as $post_data_key => $post_data_value ) { $post_export_data[] = array( 'name' => preg_replace( '/^[0-9]+_/', '', $post_data_key ), 'value' => $post_data_value, ); } $export_data[] = array( 'group_id' => 'feedback', 'group_label' => __( 'Feedback', 'jetpack' ), 'item_id' => 'feedback-' . $post_id, 'data' => $post_export_data, ); } return array( 'data' => $export_data, 'done' => count( $post_ids ) < $per_page, ); } /** * Erases personal data. * * @since 6.1.1 * * @param string $email Email address. * @param int $page Page to erase. * * @return array Associative array with keys expected by core. */ public function personal_data_eraser( $email, $page = 1 ) { return $this->_internal_personal_data_eraser( $email, $page ); } /** * Internal method for erasing personal data. * * Allows us to have a different signature than core expects * while protecting against future core API changes. * * @internal * @since 6.5 * * @param string $email Email address. * @param int $page Page to erase. * @param int $per_page Number of feedbacks to process per page. Internal use only (testing) * * @return array Associative array with keys expected by core. */ public function _internal_personal_data_eraser( $email, $page = 1, $per_page = 250 ) { $removed = false; $retained = false; $messages = array(); $option_name = sprintf( '_jetpack_pde_feedback_%s', md5( $email ) ); $last_post_id = 1 === $page ? 0 : get_option( $option_name, 0 ); $post_ids = $this->personal_data_post_ids_by_email( $email, $per_page, $page, $last_post_id ); foreach ( $post_ids as $post_id ) { /** * Filters whether to erase a particular Feedback post. * * @since 6.3.0 * * @param bool|string $prevention_message Whether to apply erase the Feedback post (bool). * Custom prevention message (string). Default true. * @param int $post_id Feedback post ID. */ $prevention_message = apply_filters( 'grunion_contact_form_delete_feedback_post', true, $post_id ); if ( true !== $prevention_message ) { if ( $prevention_message && is_string( $prevention_message ) ) { $messages[] = esc_html( $prevention_message ); } else { $messages[] = sprintf( // translators: %d: Post ID. __( 'Feedback ID %d could not be removed at this time.', 'jetpack' ), $post_id ); } $retained = true; continue; } if ( wp_delete_post( $post_id, true ) ) { $removed = true; } else { $retained = true; $messages[] = sprintf( // translators: %d: Post ID. __( 'Feedback ID %d could not be removed at this time.', 'jetpack' ), $post_id ); } } $done = count( $post_ids ) < $per_page; if ( $done ) { delete_option( $option_name ); } else { update_option( $option_name, (int) $post_id ); } return array( 'items_removed' => $removed, 'items_retained' => $retained, 'messages' => $messages, 'done' => $done, ); } /** * Queries personal data by email address. * * @since 6.1.1 * * @param string $email Email address. * @param int $per_page Post IDs per page. Default is `250`. * @param int $page Page to query. Default is `1`. * @param int $last_post_id Page to query. Default is `0`. If non-zero, used instead of $page. * * @return array An array of post IDs. */ public function personal_data_post_ids_by_email( $email, $per_page = 250, $page = 1, $last_post_id = 0 ) { add_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) ); $this->pde_last_post_id_erased = $last_post_id; $this->pde_email_address = $email; $post_ids = get_posts( array( 'post_type' => 'feedback', 'post_status' => 'publish', // This search parameter gets overwritten in ->personal_data_search_filter() 's' => '..PDE..AUTHOR EMAIL:..PDE..', 'sentence' => true, 'order' => 'ASC', 'orderby' => 'ID', 'fields' => 'ids', 'posts_per_page' => $per_page, 'paged' => $last_post_id ? 1 : $page, 'suppress_filters' => false, ) ); $this->pde_last_post_id_erased = 0; $this->pde_email_address = ''; remove_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) ); return $post_ids; } /** * Filters searches by email address. * * @since 6.1.1 * * @param string $search SQL where clause. * * @return array Filtered SQL where clause. */ public function personal_data_search_filter( $search ) { global $wpdb; /* * Limits search to `post_content` only, and we only match the * author's email address whenever it's on a line by itself. */ if ( $this->pde_email_address && false !== strpos( $search, '..PDE..AUTHOR EMAIL:..PDE..' ) ) { $search = $wpdb->prepare( " AND ( {$wpdb->posts}.post_content LIKE %s OR {$wpdb->posts}.post_content LIKE %s )", // `chr( 10 )` = `\n`, `chr( 13 )` = `\r` '%' . $wpdb->esc_like( chr( 10 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 10 ) ) . '%', '%' . $wpdb->esc_like( chr( 13 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 13 ) ) . '%' ); if ( $this->pde_last_post_id_erased ) { $search .= $wpdb->prepare( " AND {$wpdb->posts}.ID > %d", $this->pde_last_post_id_erased ); } } return $search; } /** * Prepares feedback post data for CSV export. * * @param array $post_ids Post IDs to fetch the data for. These need to be Feedback posts. * * @return array */ public function get_export_data_for_posts( $post_ids ) { $posts_data = array(); $field_names = array(); $result = array(); /** * Fetch posts and get the possible field names for later use */ foreach ( $post_ids as $post_id ) { /** * Fetch post main data, because we need the subject and author data for the feedback form. */ $post_real_data = $this->get_parsed_field_contents_of_post( $post_id ); /** * If `$post_real_data` is not an array or there is no `_feedback_subject` set, * then something must be wrong with the feedback post. Skip it. */ if ( ! is_array( $post_real_data ) || ! isset( $post_real_data['_feedback_subject'] ) ) { continue; } /** * Fetch main post comment. This is from the default textarea fields. * If it is non-empty, then we add it to data, otherwise skip it. */ $post_comment_content = $this->get_post_content_for_csv_export( $post_id ); if ( ! empty( $post_comment_content ) ) { $post_real_data['_feedback_main_comment'] = $post_comment_content; } /** * Map parsed fields to proper field names */ $mapped_fields = $this->map_parsed_field_contents_of_post_to_field_names( $post_real_data ); /** * Fetch post meta data. */ $post_meta_data = $this->get_post_meta_for_csv_export( $post_id ); /** * If `$post_meta_data` is not an array or if it is empty, then there is no * extra feedback to work with. Create an empty array. */ if ( ! is_array( $post_meta_data ) || empty( $post_meta_data ) ) { $post_meta_data = array(); } /** * Prepend the feedback subject to the list of fields. */ $post_meta_data = array_merge( $mapped_fields, $post_meta_data ); /** * Save post metadata for later usage. */ $posts_data[ $post_id ] = $post_meta_data; /** * Save field names, so we can use them as header fields later in the CSV. */ $field_names = array_merge( $field_names, array_keys( $post_meta_data ) ); } /** * Make sure the field names are unique, because we don't want duplicate data. */ $field_names = array_unique( $field_names ); /** * Sort the field names by the field id number */ sort( $field_names, SORT_NUMERIC ); /** * Loop through every post, which is essentially CSV row. */ foreach ( $posts_data as $post_id => $single_post_data ) { /** * Go through all the possible fields and check if the field is available * in the current post. * * If it is - add the data as a value. * If it is not - add an empty string, which is just a placeholder in the CSV. */ foreach ( $field_names as $single_field_name ) { if ( isset( $single_post_data[ $single_field_name ] ) && ! empty( $single_post_data[ $single_field_name ] ) ) { $result[ $single_field_name ][] = trim( $single_post_data[ $single_field_name ] ); } else { $result[ $single_field_name ][] = ''; } } } return $result; } /** * download as a csv a contact form or all of them in a csv file */ function download_feedback_as_csv() { if ( empty( $_POST['feedback_export_nonce'] ) ) { return; } check_admin_referer( 'feedback_export', 'feedback_export_nonce' ); if ( ! current_user_can( 'export' ) ) { return; } $args = array( 'posts_per_page' => -1, 'post_type' => 'feedback', 'post_status' => 'publish', 'order' => 'ASC', 'fields' => 'ids', 'suppress_filters' => false, ); $filename = date( 'Y-m-d' ) . '-feedback-export.csv'; // Check if we want to download all the feedbacks or just a certain contact form if ( ! empty( $_POST['post'] ) && $_POST['post'] !== 'all' ) { $args['post_parent'] = (int) $_POST['post']; $filename = date( 'Y-m-d' ) . '-' . str_replace( '&nbsp;', '-', get_the_title( (int) $_POST['post'] ) ) . '.csv'; } $feedbacks = get_posts( $args ); if ( empty( $feedbacks ) ) { return; } $filename = sanitize_file_name( $filename ); /** * Prepare data for export. */ $data = $this->get_export_data_for_posts( $feedbacks ); /** * If `$data` is empty, there's nothing we can do below. */ if ( ! is_array( $data ) || empty( $data ) ) { return; } /** * Extract field names from `$data` for later use. */ $fields = array_keys( $data ); /** * Count how many rows will be exported. */ $row_count = count( reset( $data ) ); // Forces the download of the CSV instead of echoing header( 'Content-Disposition: attachment; filename=' . $filename ); header( 'Pragma: no-cache' ); header( 'Expires: 0' ); header( 'Content-Type: text/csv; charset=utf-8' ); $output = fopen( 'php://output', 'w' ); /** * Print CSV headers */ fputcsv( $output, $fields ); /** * Print rows to the output. */ for ( $i = 0; $i < $row_count; $i ++ ) { $current_row = array(); /** * Put all the fields in `$current_row` array. */ foreach ( $fields as $single_field_name ) { $current_row[] = $this->esc_csv( $data[ $single_field_name ][ $i ] ); } /** * Output the complete CSV row */ fputcsv( $output, $current_row ); } fclose( $output ); } /** * Escape a string to be used in a CSV context * * Malicious input can inject formulas into CSV files, opening up the possibility for phishing attacks and * disclosure of sensitive information. * * Additionally, Excel exposes the ability to launch arbitrary commands through the DDE protocol. * * @see https://www.contextis.com/en/blog/comma-separated-vulnerabilities * * @param string $field * * @return string */ public function esc_csv( $field ) { $active_content_triggers = array( '=', '+', '-', '@' ); if ( in_array( mb_substr( $field, 0, 1 ), $active_content_triggers, true ) ) { $field = "'" . $field; } return $field; } /** * Returns a string of HTML <option> items from an array of posts * * @return string a string of HTML <option> items */ protected function get_feedbacks_as_options() { $options = ''; // Get the feedbacks' parents' post IDs $feedbacks = get_posts( array( 'fields' => 'id=>parent', 'posts_per_page' => 100000, 'post_type' => 'feedback', 'post_status' => 'publish', 'suppress_filters' => false, ) ); $parents = array_unique( array_values( $feedbacks ) ); $posts = get_posts( array( 'orderby' => 'ID', 'posts_per_page' => 1000, 'post_type' => 'any', 'post__in' => array_values( $parents ), 'suppress_filters' => false, ) ); // creates the string of <option> elements foreach ( $posts as $post ) { $options .= sprintf( '<option value="%s">%s</option>', esc_attr( $post->ID ), esc_html( $post->post_title ) ); } return $options; } /** * Get the names of all the form's fields * * @param array|int $posts the post we want the fields of * * @return array the array of fields * * @deprecated As this is no longer necessary as of the CSV export rewrite. - 2015-12-29 */ protected function get_field_names( $posts ) { $posts = (array) $posts; $all_fields = array(); foreach ( $posts as $post ) { $fields = self::parse_fields_from_content( $post ); if ( isset( $fields['_feedback_all_fields'] ) ) { $extra_fields = array_keys( $fields['_feedback_all_fields'] ); $all_fields = array_merge( $all_fields, $extra_fields ); } } $all_fields = array_unique( $all_fields ); return $all_fields; } public static function parse_fields_from_content( $post_id ) { static $post_fields; if ( ! is_array( $post_fields ) ) { $post_fields = array(); } if ( isset( $post_fields[ $post_id ] ) ) { return $post_fields[ $post_id ]; } $all_values = array(); $post_content = get_post_field( 'post_content', $post_id ); $content = explode( '<!--more-->', $post_content ); $lines = array(); if ( count( $content ) > 1 ) { $content = str_ireplace( array( '<br />', ')</p>' ), '', $content[1] ); $one_line = preg_replace( '/\s+/', ' ', $content ); $one_line = preg_replace( '/.*Array \( (.*)\)/', '$1', $one_line ); preg_match_all( '/\[([^\]]+)\] =\&gt\; ([^\[]+)/', $one_line, $matches ); if ( count( $matches ) > 1 ) { $all_values = array_combine( array_map( 'trim', $matches[1] ), array_map( 'trim', $matches[2] ) ); } $lines = array_filter( explode( "\n", $content ) ); } $var_map = array( 'AUTHOR' => '_feedback_author', 'AUTHOR EMAIL' => '_feedback_author_email', 'AUTHOR URL' => '_feedback_author_url', 'SUBJECT' => '_feedback_subject', 'IP' => '_feedback_ip', ); $fields = array(); foreach ( $lines as $line ) { $vars = explode( ': ', $line, 2 ); if ( ! empty( $vars ) ) { if ( isset( $var_map[ $vars[0] ] ) ) { $fields[ $var_map[ $vars[0] ] ] = self::strip_tags( trim( $vars[1] ) ); } } } $fields['_feedback_all_fields'] = $all_values; $post_fields[ $post_id ] = $fields; return $fields; } /** * Creates a valid csv row from a post id * * @param int $post_id The id of the post * @param array $fields An array containing the names of all the fields of the csv * @return String The csv row * * @deprecated This is no longer needed, as of the CSV export rewrite. */ protected static function make_csv_row_from_feedback( $post_id, $fields ) { $content_fields = self::parse_fields_from_content( $post_id ); $all_fields = array(); if ( isset( $content_fields['_feedback_all_fields'] ) ) { $all_fields = $content_fields['_feedback_all_fields']; } // Overwrite the parsed content with the content we stored in post_meta in a better format. $extra_fields = get_post_meta( $post_id, '_feedback_extra_fields', true ); foreach ( $extra_fields as $extra_field => $extra_value ) { $all_fields[ $extra_field ] = $extra_value; } // The first element in all of the exports will be the subject $row_items[] = $content_fields['_feedback_subject']; // Loop the fields array in order to fill the $row_items array correctly foreach ( $fields as $field ) { if ( $field === __( 'Contact Form', 'jetpack' ) ) { // the first field will ever be the contact form, so we can continue continue; } elseif ( array_key_exists( $field, $all_fields ) ) { $row_items[] = $all_fields[ $field ]; } else { $row_items[] = ''; } } return $row_items; } public static function get_ip_address() { return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null; } } /** * Generic shortcode class. * Does nothing other than store structured data and output the shortcode as a string * * Not very general - specific to Grunion. */ class Crunion_Contact_Form_Shortcode { /** * @var string the name of the shortcode: [$shortcode_name /] */ public $shortcode_name; /** * @var array key => value pairs for the shortcode's attributes: [$shortcode_name key="value" ... /] */ public $attributes; /** * @var array key => value pair for attribute defaults */ public $defaults = array(); /** * @var null|string Null for selfclosing shortcodes. Hhe inner content of otherwise: [$shortcode_name]$content[/$shortcode_name] */ public $content; /** * @var array Associative array of inner "child" shortcodes equivalent to the $content: [$shortcode_name][child 1/][child 2/][/$shortcode_name] */ public $fields; /** * @var null|string The HTML of the parsed inner "child" shortcodes". Null for selfclosing shortcodes. */ public $body; /** * @param array $attributes An associative array of shortcode attributes. @see shortcode_atts() * @param null|string $content Null for selfclosing shortcodes. The inner content otherwise. */ function __construct( $attributes, $content = null ) { $this->attributes = $this->unesc_attr( $attributes ); if ( is_array( $content ) ) { $string_content = ''; foreach ( $content as $field ) { $string_content .= (string) $field; } $this->content = $string_content; } else { $this->content = $content; } $this->parse_content( $this->content ); } /** * Processes the shortcode's inner content for "child" shortcodes * * @param string $content The shortcode's inner content: [shortcode]$content[/shortcode] */ function parse_content( $content ) { if ( is_null( $content ) ) { $this->body = null; } $this->body = do_shortcode( $content ); } /** * Returns the value of the requested attribute. * * @param string $key The attribute to retrieve * @return mixed */ function get_attribute( $key ) { return isset( $this->attributes[ $key ] ) ? $this->attributes[ $key ] : null; } function esc_attr( $value ) { if ( is_array( $value ) ) { return array_map( array( $this, 'esc_attr' ), $value ); } $value = Grunion_Contact_Form_Plugin::strip_tags( $value ); $value = _wp_specialchars( $value, ENT_QUOTES, false, true ); // Shortcode attributes can't contain "]" $value = str_replace( ']', '', $value ); $value = str_replace( ',', '&#x002c;', $value ); // store commas encoded $value = strtr( $value, array( '%' => '%25', '&' => '%26', ) ); // shortcode_parse_atts() does stripcslashes() $value = addslashes( $value ); return $value; } function unesc_attr( $value ) { if ( is_array( $value ) ) { return array_map( array( $this, 'unesc_attr' ), $value ); } // For back-compat with old Grunion encoding // Also, unencode commas $value = strtr( $value, array( '%26' => '&', '%25' => '%', ) ); $value = preg_replace( array( '/&#x0*22;/i', '/&#x0*27;/i', '/&#x0*26;/i', '/&#x0*2c;/i' ), array( '"', "'", '&', ',' ), $value ); $value = htmlspecialchars_decode( $value, ENT_QUOTES ); $value = Grunion_Contact_Form_Plugin::strip_tags( $value ); return $value; } /** * Generates the shortcode */ function __toString() { $r = "[{$this->shortcode_name} "; foreach ( $this->attributes as $key => $value ) { if ( ! $value ) { continue; } if ( isset( $this->defaults[ $key ] ) && $this->defaults[ $key ] == $value ) { continue; } if ( 'id' == $key ) { continue; } $value = $this->esc_attr( $value ); if ( is_array( $value ) ) { $value = join( ',', $value ); } if ( false === strpos( $value, "'" ) ) { $value = "'$value'"; } elseif ( false === strpos( $value, '"' ) ) { $value = '"' . $value . '"'; } else { // Shortcodes can't contain both '"' and "'". Strip one. $value = str_replace( "'", '', $value ); $value = "'$value'"; } $r .= "{$key}={$value} "; } $r = rtrim( $r ); if ( $this->fields ) { $r .= ']'; foreach ( $this->fields as $field ) { $r .= (string) $field; } $r .= "[/{$this->shortcode_name}]"; } else { $r .= '/]'; } return $r; } } /** * Class for the contact-form shortcode. * Parses shortcode to output the contact form as HTML * Sends email and stores the contact form response (a.k.a. "feedback") */ class Grunion_Contact_Form extends Crunion_Contact_Form_Shortcode { public $shortcode_name = 'contact-form'; /** * @var WP_Error stores form submission errors */ public $errors; /** * @var string The SHA1 hash of the attributes that comprise the form. */ public $hash; /** * @var Grunion_Contact_Form The most recent (inclusive) contact-form shortcode processed */ static $last; /** * @var Whatever form we are currently looking at. If processed, will become $last */ static $current_form; /** * @var array All found forms, indexed by hash. */ static $forms = array(); /** * @var bool Whether to print the grunion.css style when processing the contact-form shortcode */ static $style = false; /** * @var array When printing the submit button, what tags are allowed */ static $allowed_html_tags_for_submit_button = array( 'br' => array() ); function __construct( $attributes, $content = null ) { global $post; $this->hash = sha1( json_encode( $attributes ) . $content ); self::$forms[ $this->hash ] = $this; // Set up the default subject and recipient for this form. $default_to = ''; $default_subject = '[' . get_option( 'blogname' ) . ']'; if ( ! isset( $attributes ) || ! is_array( $attributes ) ) { $attributes = array(); } if ( ! empty( $attributes['widget'] ) && $attributes['widget'] ) { $default_to .= get_option( 'admin_email' ); $attributes['id'] = 'widget-' . $attributes['widget']; $default_subject = sprintf( _x( '%1$s Sidebar', '%1$s = blog name', 'jetpack' ), $default_subject ); } elseif ( $post ) { $attributes['id'] = $post->ID; $default_subject = sprintf( _x( '%1$s %2$s', '%1$s = blog name, %2$s = post title', 'jetpack' ), $default_subject, Grunion_Contact_Form_Plugin::strip_tags( $post->post_title ) ); $post_author = get_userdata( $post->post_author ); $default_to .= $post_author->user_email; } // Keep reference to $this for parsing form fields. self::$current_form = $this; $this->defaults = array( 'to' => $default_to, 'subject' => $default_subject, 'show_subject' => 'no', // only used in back-compat mode 'widget' => 0, // Not exposed to the user. Works with Grunion_Contact_Form_Plugin::widget_atts() 'id' => null, // Not exposed to the user. Set above. 'submit_button_text' => __( 'Submit', 'jetpack' ), // These attributes come from the block editor, so use camel case instead of snake case. 'customThankyou' => '', // Whether to show a custom thankyou response after submitting a form. '' for no, 'message' for a custom message, 'redirect' to redirect to a new URL. 'customThankyouMessage' => __( 'Thank you for your submission!', 'jetpack' ), // The message to show when customThankyou is set to 'message'. 'customThankyouRedirect' => '', // The URL to redirect to when customThankyou is set to 'redirect'. 'jetpackCRM' => true, // Whether Jetpack CRM should store the form submission. ); $attributes = shortcode_atts( $this->defaults, $attributes, 'contact-form' ); // We only enable the contact-field shortcode temporarily while processing the contact-form shortcode. Grunion_Contact_Form_Plugin::$using_contact_form_field = true; parent::__construct( $attributes, $content ); // There were no fields in the contact form. The form was probably just [contact-form /]. Build a default form. if ( empty( $this->fields ) ) { // same as the original Grunion v1 form. $default_form = ' [contact-field label="' . __( 'Name', 'jetpack' ) . '" type="name" required="true" /] [contact-field label="' . __( 'Email', 'jetpack' ) . '" type="email" required="true" /] [contact-field label="' . __( 'Website', 'jetpack' ) . '" type="url" /]'; if ( 'yes' == strtolower( $this->get_attribute( 'show_subject' ) ) ) { $default_form .= ' [contact-field label="' . __( 'Subject', 'jetpack' ) . '" type="subject" /]'; } $default_form .= ' [contact-field label="' . __( 'Message', 'jetpack' ) . '" type="textarea" /]'; $this->parse_content( $default_form ); // Store the shortcode. $this->store_shortcode( $default_form, $attributes, $this->hash ); } else { // Store the shortcode. $this->store_shortcode( $content, $attributes, $this->hash ); } // $this->body and $this->fields have been setup. We no longer need the contact-field shortcode. Grunion_Contact_Form_Plugin::$using_contact_form_field = false; } /** * Store shortcode content for recall later * - used to receate shortcode when user uses do_shortcode * * @param string $content * @param array $attributes * @param string $hash */ static function store_shortcode( $content = null, $attributes = null, $hash = null ) { if ( $content != null and isset( $attributes['id'] ) ) { if ( empty( $hash ) ) { $hash = sha1( json_encode( $attributes ) . $content ); } $shortcode_meta = get_post_meta( $attributes['id'], "_g_feedback_shortcode_{$hash}", true ); if ( $shortcode_meta != '' or $shortcode_meta != $content ) { update_post_meta( $attributes['id'], "_g_feedback_shortcode_{$hash}", $content ); // Save attributes to post_meta for later use. They're not available later in do_shortcode situations. update_post_meta( $attributes['id'], "_g_feedback_shortcode_atts_{$hash}", $attributes ); } } } /** * Toggle for printing the grunion.css stylesheet * * @param bool $style */ static function style( $style ) { $previous_style = self::$style; self::$style = (bool) $style; return $previous_style; } /** * Turn on printing of grunion.css stylesheet * * @see ::style() * @internal * @param bool $style */ static function _style_on() { return self::style( true ); } /** * The contact-form shortcode processor * * @param array $attributes Key => Value pairs as parsed by shortcode_parse_atts() * @param string|null $content The shortcode's inner content: [contact-form]$content[/contact-form] * @return string HTML for the concat form. */ static function parse( $attributes, $content ) { if ( Settings::is_syncing() ) { return ''; } // Create a new Grunion_Contact_Form object (this class) $form = new Grunion_Contact_Form( $attributes, $content ); $id = $form->get_attribute( 'id' ); if ( ! $id ) { // something terrible has happened return '[contact-form]'; } if ( is_feed() ) { return '[contact-form]'; } self::$last = $form; // Enqueue the grunion.css stylesheet if self::$style allows it if ( self::$style && ( empty( $_REQUEST['action'] ) || $_REQUEST['action'] != 'grunion_shortcode_to_json' ) ) { // Enqueue the style here instead of printing it, because if some other plugin has run the_post()+rewind_posts(), // (like VideoPress does), the style tag gets "printed" the first time and discarded, leaving the contact form unstyled. // when WordPress does the real loop. wp_enqueue_style( 'grunion.css' ); } $r = ''; $r .= "<div id='contact-form-$id'>\n"; if ( is_wp_error( $form->errors ) && $form->errors->get_error_codes() ) { // There are errors. Display them $r .= "<div class='form-error'>\n<h3>" . __( 'Error!', 'jetpack' ) . "</h3>\n<ul class='form-errors'>\n"; foreach ( $form->errors->get_error_messages() as $message ) { $r .= "\t<li class='form-error-message'>" . esc_html( $message ) . "</li>\n"; } $r .= "</ul>\n</div>\n\n"; } if ( isset( $_GET['contact-form-id'] ) && (int) $_GET['contact-form-id'] === (int) self::$last->get_attribute( 'id' ) && isset( $_GET['contact-form-sent'], $_GET['contact-form-hash'] ) && is_string( $_GET['contact-form-hash'] ) && hash_equals( $form->hash, $_GET['contact-form-hash'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended // The contact form was submitted. Show the success message/results. $feedback_id = (int) $_GET['contact-form-sent']; $back_url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce' ) ); $r_success_message = '<h3>' . __( 'Message Sent', 'jetpack' ) . ' (<a href="' . esc_url( $back_url ) . '">' . esc_html__( 'go back', 'jetpack' ) . '</a>)' . "</h3>\n\n"; // Don't show the feedback details unless the nonce matches if ( $feedback_id && wp_verify_nonce( stripslashes( $_GET['_wpnonce'] ), "contact-form-sent-{$feedback_id}" ) ) { $r_success_message .= self::success_message( $feedback_id, $form ); } /** * Filter the message returned after a successful contact form submission. * * @module contact-form * * @since 1.3.1 * * @param string $r_success_message Success message. */ $r .= apply_filters( 'grunion_contact_form_success_message', $r_success_message ); } else { // Nothing special - show the normal contact form if ( $form->get_attribute( 'widget' ) ) { // Submit form to the current URL $url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', 'action', '_wpnonce' ) ); } else { // Submit form to the post permalink $url = get_permalink(); } // For SSL/TLS page. See RFC 3986 Section 4.2 $url = set_url_scheme( $url ); // May eventually want to send this to admin-post.php... /** * Filter the contact form action URL. * * @module contact-form * * @since 1.3.1 * * @param string $contact_form_id Contact form post URL. * @param $post $GLOBALS['post'] Post global variable. * @param int $id Contact Form ID. */ $url = apply_filters( 'grunion_contact_form_form_action', "{$url}#contact-form-{$id}", $GLOBALS['post'], $id ); $has_submit_button_block = ! ( false === strpos( $content, 'wp-block-jetpack-button' ) ); $form_classes = 'contact-form commentsblock'; if ( $has_submit_button_block ) { $form_classes .= ' wp-block-jetpack-contact-form'; } $r .= "<form action='" . esc_url( $url ) . "' method='post' class='" . esc_attr( $form_classes ) . "'>\n"; $r .= $form->body; // In new versions of the contact form block the button is an inner block // so the button does not need to be constructed server-side. if ( ! $has_submit_button_block ) { $r .= "\t<p class='contact-submit'>\n"; $gutenberg_submit_button_classes = ''; if ( ! empty( $attributes['submitButtonClasses'] ) ) { $gutenberg_submit_button_classes = ' ' . $attributes['submitButtonClasses']; } /** * Filter the contact form submit button class attribute. * * @module contact-form * * @since 6.6.0 * * @param string $class Additional CSS classes for button attribute. */ $submit_button_class = apply_filters( 'jetpack_contact_form_submit_button_class', 'pushbutton-wide' . $gutenberg_submit_button_classes ); $submit_button_styles = ''; if ( ! empty( $attributes['customBackgroundButtonColor'] ) ) { $submit_button_styles .= 'background-color: ' . $attributes['customBackgroundButtonColor'] . '; '; } if ( ! empty( $attributes['customTextButtonColor'] ) ) { $submit_button_styles .= 'color: ' . $attributes['customTextButtonColor'] . ';'; } if ( ! empty( $attributes['submitButtonText'] ) ) { $submit_button_text = $attributes['submitButtonText']; } else { $submit_button_text = $form->get_attribute( 'submit_button_text' ); } $r .= "\t\t<button type='submit' class='" . esc_attr( $submit_button_class ) . "'"; if ( ! empty( $submit_button_styles ) ) { $r .= " style='" . esc_attr( $submit_button_styles ) . "'"; } $r .= ">"; $r .= wp_kses( $submit_button_text, self::$allowed_html_tags_for_submit_button ) . "</button>"; } if ( is_user_logged_in() ) { $r .= "\t\t" . wp_nonce_field( 'contact-form_' . $id, '_wpnonce', true, false ) . "\n"; // nonce and referer } if ( isset( $attributes['hasFormSettingsSet'] ) && $attributes['hasFormSettingsSet'] ) { $r .= "\t\t<input type='hidden' name='is_block' value='1' />\n"; } $r .= "\t\t<input type='hidden' name='contact-form-id' value='$id' />\n"; $r .= "\t\t<input type='hidden' name='action' value='grunion-contact-form' />\n"; $r .= "\t\t<input type='hidden' name='contact-form-hash' value='" . esc_attr( $form->hash ) . "' />\n"; if ( ! $has_submit_button_block ) { $r .= "\t</p>\n"; } $r .= "</form>\n"; } $r .= '</div>'; return $r; } /** * Returns a success message to be returned if the form is sent via AJAX. * * @param int $feedback_id * @param object Grunion_Contact_Form $form * * @return string $message */ static function success_message( $feedback_id, $form ) { if ( 'message' === $form->get_attribute( 'customThankyou' ) ) { $message = wpautop( $form->get_attribute( 'customThankyouMessage' ) ); } else { $message = '<blockquote class="contact-form-submission">' . '<p>' . join( '</p><p>', self::get_compiled_form( $feedback_id, $form ) ) . '</p>' . '</blockquote>'; } return wp_kses( $message, array( 'br' => array(), 'blockquote' => array( 'class' => array() ), 'p' => array(), ) ); } /** * Returns a compiled form with labels and values in a form of an array * of lines. * * @param int $feedback_id * @param object Grunion_Contact_Form $form * * @return array $lines */ static function get_compiled_form( $feedback_id, $form ) { $feedback = get_post( $feedback_id ); $field_ids = $form->get_field_ids(); $content_fields = Grunion_Contact_Form_Plugin::parse_fields_from_content( $feedback_id ); // Maps field_ids to post_meta keys $field_value_map = array( 'name' => 'author', 'email' => 'author_email', 'url' => 'author_url', 'subject' => 'subject', 'textarea' => false, // not a post_meta key. This is stored in post_content ); $compiled_form = array(); // "Standard" field allowed list. foreach ( $field_value_map as $type => $meta_key ) { if ( isset( $field_ids[ $type ] ) ) { $field = $form->fields[ $field_ids[ $type ] ]; if ( $meta_key ) { if ( isset( $content_fields[ "_feedback_{$meta_key}" ] ) ) { $value = $content_fields[ "_feedback_{$meta_key}" ]; } } else { // The feedback content is stored as the first "half" of post_content $value = $feedback->post_content; list( $value ) = explode( '<!--more-->', $value ); $value = trim( $value ); } $field_index = array_search( $field_ids[ $type ], $field_ids['all'] ); $compiled_form[ $field_index ] = sprintf( '<b>%1$s:</b> %2$s<br /><br />', wp_kses( $field->get_attribute( 'label' ), array() ), self::escape_and_sanitize_field_value( $value ) ); } } // "Non-standard" fields if ( $field_ids['extra'] ) { // array indexed by field label (not field id) $extra_fields = get_post_meta( $feedback_id, '_feedback_extra_fields', true ); /** * Only get data for the compiled form if `$extra_fields` is a valid and non-empty array. */ if ( is_array( $extra_fields ) && ! empty( $extra_fields ) ) { $extra_field_keys = array_keys( $extra_fields ); $i = 0; foreach ( $field_ids['extra'] as $field_id ) { $field = $form->fields[ $field_id ]; $field_index = array_search( $field_id, $field_ids['all'] ); $label = $field->get_attribute( 'label' ); $compiled_form[ $field_index ] = sprintf( '<b>%1$s:</b> %2$s<br /><br />', wp_kses( $label, array() ), self::escape_and_sanitize_field_value( $extra_fields[ $extra_field_keys[ $i ] ] ) ); $i++; } } } // Sorting lines by the field index ksort( $compiled_form ); return $compiled_form; } static function escape_and_sanitize_field_value( $value ) { $value = str_replace( array( '[' , ']' ) , array( '&#91;' , '&#93;' ) , $value ); return nl2br( wp_kses( $value, array() ) ); } /** * Only strip out empty string values and keep all the other values as they are. * * @param $single_value * * @return bool */ static function remove_empty( $single_value ) { return ( $single_value !== '' ); } /** * Escape a shortcode value. * * Shortcode attribute values have a number of unfortunate restrictions, which fortunately we * can get around by adding some extra HTML encoding. * * The output HTML will have a few extra escapes, but that makes no functional difference. * * @since 9.1.0 * @param string $val Value to escape. * @return string */ private static function esc_shortcode_val( $val ) { return strtr( esc_html( $val ), array( // Brackets in attribute values break the shortcode parser. '[' => '&#091;', ']' => '&#093;', // Shortcode parser screws up backslashes too, thanks to calls to `stripcslashes`. '\\' => '&#092;', // The existing code here represents arrays as comma-separated strings. // Rather than trying to change representations now, just escape the commas in values. ',' => '&#044;', ) ); } /** * The contact-field shortcode processor * We use an object method here instead of a static Grunion_Contact_Form_Field class method to parse contact-field shortcodes so that we can tie them to the contact-form object. * * @param array $attributes Key => Value pairs as parsed by shortcode_parse_atts() * @param string|null $content The shortcode's inner content: [contact-field]$content[/contact-field] * @return HTML for the contact form field */ static function parse_contact_field( $attributes, $content ) { // Don't try to parse contact form fields if not inside a contact form if ( ! Grunion_Contact_Form_Plugin::$using_contact_form_field ) { $att_strs = array(); if ( ! isset( $attributes['label'] ) ) { $type = isset( $attributes['type'] ) ? $attributes['type'] : null; $attributes['label'] = self::get_default_label_from_type( $type ); } foreach ( $attributes as $att => $val ) { if ( is_numeric( $att ) ) { // Is a valueless attribute $att_strs[] = self::esc_shortcode_val( $val ); } elseif ( isset( $val ) ) { // A regular attr - value pair if ( ( $att === 'options' || $att === 'values' ) && is_string( $val ) ) { // remove any empty strings $val = explode( ',', $val ); } if ( is_array( $val ) ) { $val = array_filter( $val, array( __CLASS__, 'remove_empty' ) ); // removes any empty strings $att_strs[] = esc_html( $att ) . '="' . implode( ',', array_map( array( __CLASS__, 'esc_shortcode_val' ), $val ) ) . '"'; } elseif ( is_bool( $val ) ) { $att_strs[] = esc_html( $att ) . '="' . ( $val ? '1' : '' ) . '"'; } else { $att_strs[] = esc_html( $att ) . '="' . self::esc_shortcode_val( $val ) . '"'; } } } $html = '[contact-field ' . implode( ' ', $att_strs ); if ( isset( $content ) && ! empty( $content ) ) { // If there is content, let's add a closing tag $html .= ']' . esc_html( $content ) . '[/contact-field]'; } else { // Otherwise let's add a closing slash in the first tag $html .= '/]'; } return $html; } $form = Grunion_Contact_Form::$current_form; $field = new Grunion_Contact_Form_Field( $attributes, $content, $form ); $field_id = $field->get_attribute( 'id' ); if ( $field_id ) { $form->fields[ $field_id ] = $field; } else { $form->fields[] = $field; } if ( isset( $_POST['action'] ) && 'grunion-contact-form' === $_POST['action'] && isset( $_POST['contact-form-id'] ) && $form->get_attribute( 'id' ) == $_POST['contact-form-id'] && isset( $_POST['contact-form-hash'] ) && hash_equals( $form->hash, $_POST['contact-form-hash'] ) ) { // If we're processing a POST submission for this contact form, validate the field value so we can show errors as necessary. $field->validate(); } // Output HTML return $field->render(); } static function get_default_label_from_type( $type ) { $str = null; switch ( $type ) { case 'text': $str = __( 'Text', 'jetpack' ); break; case 'name': $str = __( 'Name', 'jetpack' ); break; case 'email': $str = __( 'Email', 'jetpack' ); break; case 'url': $str = __( 'Website', 'jetpack' ); break; case 'date': $str = __( 'Date', 'jetpack' ); break; case 'telephone': $str = __( 'Phone', 'jetpack' ); break; case 'textarea': $str = __( 'Message', 'jetpack' ); break; case 'checkbox': $str = __( 'Checkbox', 'jetpack' ); break; case 'checkbox-multiple': $str = __( 'Choose several', 'jetpack' ); break; case 'radio': $str = __( 'Choose one', 'jetpack' ); break; case 'select': $str = __( 'Select one', 'jetpack' ); break; case 'consent': $str = __( 'Consent', 'jetpack' ); break; default: $str = null; } return $str; } /** * Loops through $this->fields to generate a (structured) list of field IDs. * * Important: Currently the allowed fields are defined as follows: * `name`, `email`, `url`, `subject`, `textarea` * * If you need to add new fields to the Contact Form, please don't add them * to the allowed fields and leave them as extra fields. * * The reasoning behind this is that both the admin Feedback view and the CSV * export will not include any fields that are added to the list of * allowed fields without taking proper care to add them to all the * other places where they accessed/used/saved. * * The safest way to add new fields is to add them to the dropdown and the * HTML list ( @see Grunion_Contact_Form_Field::render ) and don't add them * to the list of allowed fields. This way they will become a part of the * `extra fields` which are saved in the post meta and will be properly * handled by the admin Feedback view and the CSV Export without any extra * work. * * If there is need to add a field to the allowed fields, then please * take proper care to add logic to handle the field in the following places: * * - Below in the switch statement - so the field is recognized as allowed. * * - Grunion_Contact_Form::process_submission - validation and logic. * * - Grunion_Contact_Form::process_submission - add the field as an additional * field in the `post_content` when saving the feedback content. * * - Grunion_Contact_Form_Plugin::parse_fields_from_content - add mapping * for the field, defined in the above method. * * - Grunion_Contact_Form_Plugin::map_parsed_field_contents_of_post_to_field_names - * add mapping of the field for the CSV Export. Otherwise it will be missing * from the exported data. * * - admin.php / grunion_manage_post_columns - add the field to the render logic. * Otherwise it will be missing from the admin Feedback view. * * @return array */ function get_field_ids() { $field_ids = array( 'all' => array(), // array of all field_ids. 'extra' => array(), // array of all non-allowed field IDs. // Allowed "standard" field IDs: // 'email' => field_id, // 'name' => field_id, // 'url' => field_id, // 'subject' => field_id, // 'textarea' => field_id, ); foreach ( $this->fields as $id => $field ) { $field_ids['all'][] = $id; $type = $field->get_attribute( 'type' ); if ( isset( $field_ids[ $type ] ) ) { // This type of field is already present in our allowed list of "standard" fields for this form // Put it in extra $field_ids['extra'][] = $id; continue; } /** * See method description before modifying the switch cases. */ switch ( $type ) { case 'email': case 'name': case 'url': case 'subject': case 'textarea': case 'consent': $field_ids[ $type ] = $id; break; default: // Put everything else in extra $field_ids['extra'][] = $id; } } return $field_ids; } /** * Process the contact form's POST submission * Stores feedback. Sends email. */ function process_submission() { global $post; $plugin = Grunion_Contact_Form_Plugin::init(); $id = $this->get_attribute( 'id' ); $to = $this->get_attribute( 'to' ); $widget = $this->get_attribute( 'widget' ); $contact_form_subject = $this->get_attribute( 'subject' ); $email_marketing_consent = false; $to = str_replace( ' ', '', $to ); $emails = explode( ',', $to ); $valid_emails = array(); foreach ( (array) $emails as $email ) { if ( ! is_email( $email ) ) { continue; } if ( function_exists( 'is_email_address_unsafe' ) && is_email_address_unsafe( $email ) ) { continue; } $valid_emails[] = $email; } // No one to send it to, which means none of the "to" attributes are valid emails. // Use default email instead. if ( ! $valid_emails ) { $valid_emails = $this->defaults['to']; } $to = $valid_emails; // Last ditch effort to set a recipient if somehow none have been set. if ( empty( $to ) ) { $to = get_option( 'admin_email' ); } // Make sure we're processing the form we think we're processing... probably a redundant check. if ( $widget ) { if ( 'widget-' . $widget != $_POST['contact-form-id'] ) { return false; } } else { if ( $post->ID != $_POST['contact-form-id'] ) { return false; } } $field_ids = $this->get_field_ids(); // Initialize all these "standard" fields to null $comment_author_email = $comment_author_email_label = // v $comment_author = $comment_author_label = // v $comment_author_url = $comment_author_url_label = // v $comment_content = $comment_content_label = null; // For each of the "standard" fields, grab their field label and value. if ( isset( $field_ids['name'] ) ) { $field = $this->fields[ $field_ids['name'] ]; $comment_author = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( /** This filter is already documented in core/wp-includes/comment-functions.php */ apply_filters( 'pre_comment_author_name', addslashes( $field->value ) ) ) ); $comment_author_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) ); } if ( isset( $field_ids['email'] ) ) { $field = $this->fields[ $field_ids['email'] ]; $comment_author_email = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( /** This filter is already documented in core/wp-includes/comment-functions.php */ apply_filters( 'pre_comment_author_email', addslashes( $field->value ) ) ) ); $comment_author_email_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) ); } if ( isset( $field_ids['url'] ) ) { $field = $this->fields[ $field_ids['url'] ]; $comment_author_url = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( /** This filter is already documented in core/wp-includes/comment-functions.php */ apply_filters( 'pre_comment_author_url', addslashes( $field->value ) ) ) ); if ( 'http://' == $comment_author_url ) { $comment_author_url = ''; } $comment_author_url_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) ); } if ( isset( $field_ids['textarea'] ) ) { $field = $this->fields[ $field_ids['textarea'] ]; $comment_content = trim( Grunion_Contact_Form_Plugin::strip_tags( $field->value ) ); $comment_content_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) ); } if ( isset( $field_ids['subject'] ) ) { $field = $this->fields[ $field_ids['subject'] ]; if ( $field->value ) { $contact_form_subject = Grunion_Contact_Form_Plugin::strip_tags( $field->value ); } } if ( isset( $field_ids['consent'] ) ) { $field = $this->fields[ $field_ids['consent'] ]; if ( $field->value ) { $email_marketing_consent = true; } } $all_values = $extra_values = array(); $i = 1; // Prefix counter for stored metadata // For all fields, grab label and value foreach ( $field_ids['all'] as $field_id ) { $field = $this->fields[ $field_id ]; $label = $i . '_' . $field->get_attribute( 'label' ); $value = $field->value; $all_values[ $label ] = $value; $i++; // Increment prefix counter for the next field } // For the "non-standard" fields, grab label and value // Extra fields have their prefix starting from count( $all_values ) + 1 foreach ( $field_ids['extra'] as $field_id ) { $field = $this->fields[ $field_id ]; $label = $i . '_' . $field->get_attribute( 'label' ); $value = $field->value; if ( is_array( $value ) ) { $value = implode( ', ', $value ); } $extra_values[ $label ] = $value; $i++; // Increment prefix counter for the next extra field } if ( isset( $_REQUEST['is_block'] ) && $_REQUEST['is_block'] ) { $extra_values['is_block'] = true; } $contact_form_subject = trim( $contact_form_subject ); $comment_author_IP = Grunion_Contact_Form_Plugin::get_ip_address(); $vars = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'contact_form_subject', 'comment_author_IP' ); foreach ( $vars as $var ) { $$var = str_replace( array( "\n", "\r" ), '', $$var ); } // Ensure that Akismet gets all of the relevant information from the contact form, // not just the textarea field and predetermined subject. $akismet_vars = compact( $vars ); $akismet_vars['comment_content'] = $comment_content; foreach ( array_merge( $field_ids['all'], $field_ids['extra'] ) as $field_id ) { $field = $this->fields[ $field_id ]; // Skip any fields that are just a choice from a pre-defined list. They wouldn't have any value // from a spam-filtering point of view. if ( in_array( $field->get_attribute( 'type' ), array( 'select', 'checkbox', 'checkbox-multiple', 'radio' ) ) ) { continue; } // Normalize the label into a slug. $field_slug = trim( // Strip all leading/trailing dashes. preg_replace( // Normalize everything to a-z0-9_- '/[^a-z0-9_]+/', '-', strtolower( $field->get_attribute( 'label' ) ) // Lowercase ), '-' ); $field_value = ( is_array( $field->value ) ) ? trim( implode( ', ', $field->value ) ) : trim( $field->value ); // Skip any values that are already in the array we're sending. if ( $field_value && in_array( $field_value, $akismet_vars ) ) { continue; } $akismet_vars[ 'contact_form_field_' . $field_slug ] = $field_value; } $spam = ''; $akismet_values = $plugin->prepare_for_akismet( $akismet_vars ); // Is it spam? /** This filter is already documented in modules/contact-form/admin.php */ $is_spam = apply_filters( 'jetpack_contact_form_is_spam', false, $akismet_values ); if ( is_wp_error( $is_spam ) ) { // WP_Error to abort return $is_spam; // abort } elseif ( $is_spam === true ) { // TRUE to flag a spam $spam = '***SPAM*** '; } /** * Filter whether a submitted contact form is in the comment disallowed list. * * @module contact-form * * @since 8.9.0 * * @param bool $result Is the submitted feedback in the disallowed list. * @param array $akismet_values Feedack values returned by the Akismet plugin. */ $in_comment_disallowed_list = apply_filters( 'jetpack_contact_form_in_comment_disallowed_list', false, $akismet_values ); if ( ! $comment_author ) { $comment_author = $comment_author_email; } /** * Filter the email where a submitted feedback is sent. * * @module contact-form * * @since 1.3.1 * * @param string|array $to Array of valid email addresses, or single email address. */ $to = (array) apply_filters( 'contact_form_to', $to ); $reply_to_addr = $to[0]; // get just the address part before the name part is added foreach ( $to as $to_key => $to_value ) { $to[ $to_key ] = Grunion_Contact_Form_Plugin::strip_tags( $to_value ); $to[ $to_key ] = self::add_name_to_address( $to_value ); } $blog_url = wp_parse_url( site_url() ); $from_email_addr = 'wordpress@' . $blog_url['host']; if ( ! empty( $comment_author_email ) ) { $reply_to_addr = $comment_author_email; } $headers = 'From: "' . $comment_author . '" <' . $from_email_addr . ">\r\n" . 'Reply-To: "' . $comment_author . '" <' . $reply_to_addr . ">\r\n"; $all_values['email_marketing_consent'] = $email_marketing_consent; // Build feedback reference $feedback_time = current_time( 'mysql' ); $feedback_title = "{$comment_author} - {$feedback_time}"; $feedback_id = md5( $feedback_title ); $entry_values = array( 'entry_title' => the_title_attribute( 'echo=0' ), 'entry_permalink' => esc_url( get_permalink( get_the_ID() ) ), 'feedback_id' => $feedback_id, ); $all_values = array_merge( $all_values, $entry_values ); /** This filter is already documented in modules/contact-form/admin.php */ $subject = apply_filters( 'contact_form_subject', $contact_form_subject, $all_values ); $url = $widget ? home_url( '/' ) : get_permalink( $post->ID ); $date_time_format = _x( '%1$s \a\t %2$s', '{$date_format} \a\t {$time_format}', 'jetpack' ); $date_time_format = sprintf( $date_time_format, get_option( 'date_format' ), get_option( 'time_format' ) ); $time = date_i18n( $date_time_format, current_time( 'timestamp' ) ); // Keep a copy of the feedback as a custom post type. if ( $in_comment_disallowed_list ) { $feedback_status = 'trash'; } elseif ( $is_spam ) { $feedback_status = 'spam'; } else { $feedback_status = 'publish'; } foreach ( (array) $akismet_values as $av_key => $av_value ) { $akismet_values[ $av_key ] = Grunion_Contact_Form_Plugin::strip_tags( $av_value ); } foreach ( (array) $all_values as $all_key => $all_value ) { $all_values[ $all_key ] = Grunion_Contact_Form_Plugin::strip_tags( $all_value ); } foreach ( (array) $extra_values as $ev_key => $ev_value ) { $extra_values[ $ev_key ] = Grunion_Contact_Form_Plugin::strip_tags( $ev_value ); } /* We need to make sure that the post author is always zero for contact * form submissions. This prevents export/import from trying to create * new users based on form submissions from people who were logged in * at the time. * * Unfortunately wp_insert_post() tries very hard to make sure the post * author gets the currently logged in user id. That is how we ended up * with this work around. */ add_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10, 2 ); $post_id = wp_insert_post( array( 'post_date' => addslashes( $feedback_time ), 'post_type' => 'feedback', 'post_status' => addslashes( $feedback_status ), 'post_parent' => (int) $post->ID, 'post_title' => addslashes( wp_kses( $feedback_title, array() ) ), 'post_content' => addslashes( wp_kses( $comment_content . "\n<!--more-->\n" . "AUTHOR: {$comment_author}\nAUTHOR EMAIL: {$comment_author_email}\nAUTHOR URL: {$comment_author_url}\nSUBJECT: {$subject}\nIP: {$comment_author_IP}\n" . @print_r( $all_values, true ), array() ) ), // so that search will pick up this data 'post_name' => $feedback_id, ) ); // once insert has finished we don't need this filter any more remove_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10 ); update_post_meta( $post_id, '_feedback_extra_fields', $this->addslashes_deep( $extra_values ) ); if ( 'publish' == $feedback_status ) { // Increase count of unread feedback. $unread = get_option( 'feedback_unread_count', 0 ) + 1; update_option( 'feedback_unread_count', $unread ); } if ( defined( 'AKISMET_VERSION' ) ) { update_post_meta( $post_id, '_feedback_akismet_values', $this->addslashes_deep( $akismet_values ) ); } /** * Fires after the feedback post for the contact form submission has been inserted. * * @module contact-form * * @since 8.6.0 * * @param integer $post_id The post id that contains the contact form data. * @param array $this->fields An array containg the form's Grunion_Contact_Form_Field objects. * @param boolean $is_spam Whether the form submission has been identified as spam. * @param array $entry_values The feedback entry values. */ do_action( 'grunion_after_feedback_post_inserted', $post_id, $this->fields, $is_spam, $entry_values ); $message = self::get_compiled_form( $post_id, $this ); array_push( $message, '<br />', '<hr />', __( 'Time:', 'jetpack' ) . ' ' . $time . '<br />', __( 'IP Address:', 'jetpack' ) . ' ' . $comment_author_IP . '<br />', __( 'Contact Form URL:', 'jetpack' ) . ' ' . $url . '<br />' ); if ( is_user_logged_in() ) { array_push( $message, sprintf( '<p>' . __( 'Sent by a verified %s user.', 'jetpack' ) . '</p>', isset( $GLOBALS['current_site']->site_name ) && $GLOBALS['current_site']->site_name ? $GLOBALS['current_site']->site_name : '"' . get_option( 'blogname' ) . '"' ) ); } else { array_push( $message, '<p>' . __( 'Sent by an unverified visitor to your site.', 'jetpack' ) . '</p>' ); } $message = join( '', $message ); /** * Filters the message sent via email after a successful form submission. * * @module contact-form * * @since 1.3.1 * * @param string $message Feedback email message. */ $message = apply_filters( 'contact_form_message', $message ); // This is called after `contact_form_message`, in order to preserve back-compat $message = self::wrap_message_in_html_tags( $message ); update_post_meta( $post_id, '_feedback_email', $this->addslashes_deep( compact( 'to', 'message' ) ) ); /** * Fires right before the contact form message is sent via email to * the recipient specified in the contact form. * * @module contact-form * * @since 1.3.1 * * @param integer $post_id Post contact form lives on * @param array $all_values Contact form fields * @param array $extra_values Contact form fields not included in $all_values */ do_action( 'grunion_pre_message_sent', $post_id, $all_values, $extra_values ); // schedule deletes of old spam feedbacks if ( ! wp_next_scheduled( 'grunion_scheduled_delete' ) ) { wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete' ); } if ( $is_spam !== true && /** * Filter to choose whether an email should be sent after each successful contact form submission. * * @module contact-form * * @since 2.6.0 * * @param bool true Should an email be sent after a form submission. Default to true. * @param int $post_id Post ID. */ true === apply_filters( 'grunion_should_send_email', true, $post_id ) ) { self::wp_mail( $to, "{$spam}{$subject}", $message, $headers ); } elseif ( true === $is_spam && /** * Choose whether an email should be sent for each spam contact form submission. * * @module contact-form * * @since 1.3.1 * * @param bool false Should an email be sent after a spam form submission. Default to false. */ apply_filters( 'grunion_still_email_spam', false ) == true ) { // don't send spam by default. Filterable. self::wp_mail( $to, "{$spam}{$subject}", $message, $headers ); } /** * Fires an action hook right after the email(s) have been sent. * * @module contact-form * * @since 7.3.0 * * @param int $post_id Post contact form lives on. * @param string|array $to Array of valid email addresses, or single email address. * @param string $subject Feedback email subject. * @param string $message Feedback email message. * @param string|array $headers Optional. Additional headers. * @param array $all_values Contact form fields. * @param array $extra_values Contact form fields not included in $all_values */ do_action( 'grunion_after_message_sent', $post_id, $to, $subject, $message, $headers, $all_values, $extra_values ); if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return self::success_message( $post_id, $this ); } $redirect = ''; $custom_redirect = false; if ( 'redirect' === $this->get_attribute( 'customThankyou' ) ) { $custom_redirect = true; $redirect = esc_url( $this->get_attribute( 'customThankyouRedirect' ) ); } if ( ! $redirect ) { $custom_redirect = false; $redirect = wp_get_referer(); } if ( ! $redirect ) { // wp_get_referer() returns false if the referer is the same as the current page. $custom_redirect = false; $redirect = $_SERVER['REQUEST_URI']; } if ( ! $custom_redirect ) { $redirect = add_query_arg( urlencode_deep( array( 'contact-form-id' => $id, 'contact-form-sent' => $post_id, 'contact-form-hash' => $this->hash, '_wpnonce' => wp_create_nonce( "contact-form-sent-{$post_id}" ), // wp_nonce_url HTMLencodes :( . ) ), $redirect ); } /** * Filter the URL where the reader is redirected after submitting a form. * * @module contact-form * * @since 1.9.0 * * @param string $redirect Post submission URL. * @param int $id Contact Form ID. * @param int $post_id Post ID. */ $redirect = apply_filters( 'grunion_contact_form_redirect_url', $redirect, $id, $post_id ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- We intentially allow external redirects here. wp_redirect( $redirect ); exit; } /** * Wrapper for wp_mail() that enables HTML messages with text alternatives * * @param string|array $to Array or comma-separated list of email addresses to send message. * @param string $subject Email subject. * @param string $message Message contents. * @param string|array $headers Optional. Additional headers. * @param string|array $attachments Optional. Files to attach. * * @return bool Whether the email contents were sent successfully. */ public static function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) { add_filter( 'wp_mail_content_type', __CLASS__ . '::get_mail_content_type' ); add_action( 'phpmailer_init', __CLASS__ . '::add_plain_text_alternative' ); $result = wp_mail( $to, $subject, $message, $headers, $attachments ); remove_filter( 'wp_mail_content_type', __CLASS__ . '::get_mail_content_type' ); remove_action( 'phpmailer_init', __CLASS__ . '::add_plain_text_alternative' ); return $result; } /** * Add a display name part to an email address * * SpamAssassin doesn't like addresses in HTML messages that are missing display names (e.g., `foo@bar.org` * instead of `"Foo Bar" <foo@bar.org>`. * * @param string $address * * @return string */ function add_name_to_address( $address ) { // If it's just the address, without a display name if ( is_email( $address ) ) { $address_parts = explode( '@', $address ); $address = sprintf( '"%s" <%s>', $address_parts[0], $address ); } return $address; } /** * Get the content type that should be assigned to outbound emails * * @return string */ static function get_mail_content_type() { return 'text/html'; } /** * Wrap a message body with the appropriate in HTML tags * * This helps to ensure correct parsing by clients, and also helps avoid triggering spam filtering rules * * @param string $body * * @return string */ static function wrap_message_in_html_tags( $body ) { // Don't do anything if the message was already wrapped in HTML tags // That could have be done by a plugin via filters if ( false !== strpos( $body, '<html' ) ) { return $body; } $html_message = sprintf( // The tabs are just here so that the raw code is correctly formatted for developers // They're removed so that they don't affect the final message sent to users str_replace( "\t", '', '<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <body> %s </body> </html>' ), $body ); return $html_message; } /** * Add a plain-text alternative part to an outbound email * * This makes the message more accessible to mail clients that aren't HTML-aware, and decreases the likelihood * that the message will be flagged as spam. * * @param PHPMailer $phpmailer */ static function add_plain_text_alternative( $phpmailer ) { // Add an extra break so that the extra space above the <p> is preserved after the <p> is stripped out $alt_body = str_replace( '<p>', '<p><br />', $phpmailer->Body ); // Convert <br> to \n breaks, to preserve the space between lines that we want to keep $alt_body = str_replace( array( '<br>', '<br />' ), "\n", $alt_body ); // Convert <hr> to an plain-text equivalent, to preserve the integrity of the message $alt_body = str_replace( array( '<hr>', '<hr />' ), "----\n", $alt_body ); // Trim the plain text message to remove the \n breaks that were after <doctype>, <html>, and <body> $phpmailer->AltBody = trim( strip_tags( $alt_body ) ); } function addslashes_deep( $value ) { if ( is_array( $value ) ) { return array_map( array( $this, 'addslashes_deep' ), $value ); } elseif ( is_object( $value ) ) { $vars = get_object_vars( $value ); foreach ( $vars as $key => $data ) { $value->{$key} = $this->addslashes_deep( $data ); } return $value; } return addslashes( $value ); } } // end class Grunion_Contact_Form /** * Class for the contact-field shortcode. * Parses shortcode to output the contact form field as HTML. * Validates input. */ class Grunion_Contact_Form_Field extends Crunion_Contact_Form_Shortcode { public $shortcode_name = 'contact-field'; /** * @var Grunion_Contact_Form parent form */ public $form; /** * @var string default or POSTed value */ public $value; /** * @var bool Is the input invalid? */ public $error = false; /** * @param array $attributes An associative array of shortcode attributes. @see shortcode_atts() * @param null|string $content Null for selfclosing shortcodes. The inner content otherwise. * @param Grunion_Contact_Form $form The parent form */ function __construct( $attributes, $content = null, $form = null ) { $attributes = shortcode_atts( array( 'label' => null, 'type' => 'text', 'required' => false, 'options' => array(), 'id' => null, 'default' => null, 'values' => null, 'placeholder' => null, 'class' => null, 'width' => null, 'consenttype' => null, 'implicitconsentmessage' => null, 'explicitconsentmessage' => null, ), $attributes, 'contact-field' ); // special default for subject field if ( 'subject' == $attributes['type'] && is_null( $attributes['default'] ) && ! is_null( $form ) ) { $attributes['default'] = $form->get_attribute( 'subject' ); } // allow required=1 or required=true if ( '1' == $attributes['required'] || 'true' == strtolower( $attributes['required'] ) ) { $attributes['required'] = true; } else { $attributes['required'] = false; } // parse out comma-separated options list (for selects, radios, and checkbox-multiples) if ( ! empty( $attributes['options'] ) && is_string( $attributes['options'] ) ) { $attributes['options'] = array_map( 'trim', explode( ',', $attributes['options'] ) ); if ( ! empty( $attributes['values'] ) && is_string( $attributes['values'] ) ) { $attributes['values'] = array_map( 'trim', explode( ',', $attributes['values'] ) ); } } if ( $form ) { // make a unique field ID based on the label, with an incrementing number if needed to avoid clashes $form_id = $form->get_attribute( 'id' ); $id = isset( $attributes['id'] ) ? $attributes['id'] : false; $unescaped_label = $this->unesc_attr( $attributes['label'] ); $unescaped_label = str_replace( '%', '-', $unescaped_label ); // jQuery doesn't like % in IDs? $unescaped_label = preg_replace( '/[^a-zA-Z0-9.-_:]/', '', $unescaped_label ); if ( empty( $id ) ) { $id = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label ); $i = 0; $max_tries = 99; while ( isset( $form->fields[ $id ] ) ) { $i++; $id = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label . '-' . $i ); if ( $i > $max_tries ) { break; } } } $attributes['id'] = $id; } parent::__construct( $attributes, $content ); // Store parent form $this->form = $form; } /** * This field's input is invalid. Flag as invalid and add an error to the parent form * * @param string $message The error message to display on the form. */ function add_error( $message ) { $this->is_error = true; if ( ! is_wp_error( $this->form->errors ) ) { $this->form->errors = new WP_Error; } $this->form->errors->add( $this->get_attribute( 'id' ), $message ); } /** * Is the field input invalid? * * @see $error * * @return bool */ function is_error() { return $this->error; } /** * Validates the form input */ function validate() { // If it's not required, there's nothing to validate if ( ! $this->get_attribute( 'required' ) ) { return; } $field_id = $this->get_attribute( 'id' ); $field_type = $this->get_attribute( 'type' ); $field_label = $this->get_attribute( 'label' ); if ( isset( $_POST[ $field_id ] ) ) { if ( is_array( $_POST[ $field_id ] ) ) { $field_value = array_map( 'stripslashes', $_POST[ $field_id ] ); } else { $field_value = stripslashes( $_POST[ $field_id ] ); } } else { $field_value = ''; } switch ( $field_type ) { case 'email': // Make sure the email address is valid if ( ! is_string( $field_value ) || ! is_email( $field_value ) ) { /* translators: %s is the name of a form field */ $this->add_error( sprintf( __( '%s requires a valid email address', 'jetpack' ), $field_label ) ); } break; case 'checkbox-multiple': // Check that there is at least one option selected if ( empty( $field_value ) ) { /* translators: %s is the name of a form field */ $this->add_error( sprintf( __( '%s requires at least one selection', 'jetpack' ), $field_label ) ); } break; default: // Just check for presence of any text if ( ! is_string( $field_value ) || ! strlen( trim( $field_value ) ) ) { /* translators: %s is the name of a form field */ $this->add_error( sprintf( __( '%s is required', 'jetpack' ), $field_label ) ); } } } /** * Check the default value for options field * * @param string value * @param int index * @param string default value * * @return string */ public function get_option_value( $value, $index, $options ) { if ( empty( $value[ $index ] ) ) { return $options; } return $value[ $index ]; } /** * Outputs the HTML for this form field * * @return string HTML */ function render() { global $current_user, $user_identity; $field_id = $this->get_attribute( 'id' ); $field_type = $this->get_attribute( 'type' ); $field_label = $this->get_attribute( 'label' ); $field_required = $this->get_attribute( 'required' ); $field_placeholder = $this->get_attribute( 'placeholder' ); $field_width = $this->get_attribute( 'width' ); $class = 'date' === $field_type ? 'jp-contact-form-date' : $this->get_attribute( 'class' ); if ( ! empty( $field_width ) ) { $class .= ' grunion-field-width-' . $field_width; } /** * Filters the "class" attribute of the contact form input * * @module contact-form * * @since 6.6.0 * * @param string $class Additional CSS classes for input class attribute. */ $field_class = apply_filters( 'jetpack_contact_form_input_class', $class ); if ( isset( $_POST[ $field_id ] ) ) { if ( is_array( $_POST[ $field_id ] ) ) { $this->value = array_map( 'stripslashes', $_POST[ $field_id ] ); } else { $this->value = stripslashes( (string) $_POST[ $field_id ] ); } } elseif ( isset( $_GET[ $field_id ] ) ) { $this->value = stripslashes( (string) $_GET[ $field_id ] ); } elseif ( is_user_logged_in() && ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) || /** * Allow third-party tools to prefill the contact form with the user's details when they're logged in. * * @module contact-form * * @since 3.2.0 * * @param bool false Should the Contact Form be prefilled with your details when you're logged in. Default to false. */ true === apply_filters( 'jetpack_auto_fill_logged_in_user', false ) ) ) { // Special defaults for logged-in users switch ( $this->get_attribute( 'type' ) ) { case 'email': $this->value = $current_user->data->user_email; break; case 'name': $this->value = $user_identity; break; case 'url': $this->value = $current_user->data->user_url; break; default: $this->value = $this->get_attribute( 'default' ); } } else { $this->value = $this->get_attribute( 'default' ); } $field_value = Grunion_Contact_Form_Plugin::strip_tags( $this->value ); $field_label = Grunion_Contact_Form_Plugin::strip_tags( $field_label ); $rendered_field = $this->render_field( $field_type, $field_id, $field_label, $field_value, $field_class, $field_placeholder, $field_required ); /** * Filter the HTML of the Contact Form. * * @module contact-form * * @since 2.6.0 * * @param string $rendered_field Contact Form HTML output. * @param string $field_label Field label. * @param int|null $id Post ID. */ return apply_filters( 'grunion_contact_form_field_html', $rendered_field, $field_label, ( in_the_loop() ? get_the_ID() : null ) ); } public function render_label( $type, $id, $label, $required, $required_field_text ) { $type_class = $type ? ' ' .$type : ''; return "<label for='" . esc_attr( $id ) . "' class='grunion-field-label{$type_class}" . ( $this->is_error() ? ' form-error' : '' ) . "' >" . esc_html( $label ) . ( $required ? '<span>' . $required_field_text . '</span>' : '' ) . "</label>\n"; } function render_input_field( $type, $id, $value, $class, $placeholder, $required ) { return "<input type='". esc_attr( $type ) ."' name='" . esc_attr( $id ) . "' id='" . esc_attr( $id ) . "' value='" . esc_attr( $value ) . "' " . $class . $placeholder . ' ' . ( $required ? "required aria-required='true'" : '' ) . " />\n"; } function render_email_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder ) { $field = $this->render_label( 'email', $id, $label, $required, $required_field_text ); $field .= $this->render_input_field( 'email', $id, $value, $class, $placeholder, $required ); return $field; } function render_telephone_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder ) { $field = $this->render_label( 'telephone', $id, $label, $required, $required_field_text ); $field .= $this->render_input_field( 'tel', $id, $value, $class, $placeholder, $required ); return $field; } function render_url_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder ) { $field = $this->render_label( 'url', $id, $label, $required, $required_field_text ); $field .= $this->render_input_field( 'url', $id, $value, $class, $placeholder, $required ); return $field; } function render_textarea_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder ) { $field = $this->render_label( 'textarea', 'contact-form-comment-' . $id, $label, $required, $required_field_text ); $field .= "<textarea name='" . esc_attr( $id ) . "' id='contact-form-comment-" . esc_attr( $id ) . "' rows='20' " . $class . $placeholder . ' ' . ( $required ? "required aria-required='true'" : '' ) . '>' . esc_textarea( $value ) . "</textarea>\n"; return $field; } function render_radio_field( $id, $label, $value, $class, $required, $required_field_text ) { $field = $this->render_label( '', $id, $label, $required, $required_field_text ); foreach ( (array) $this->get_attribute( 'options' ) as $optionIndex => $option ) { $option = Grunion_Contact_Form_Plugin::strip_tags( $option ); if ( $option ) { $field .= "\t\t<label class='grunion-radio-label radio" . ( $this->is_error() ? ' form-error' : '' ) . "'>"; $field .= "<input type='radio' name='" . esc_attr( $id ) . "' value='" . esc_attr( $this->get_option_value( $this->get_attribute( 'values' ), $optionIndex, $option ) ) . "' " . $class . checked( $option, $value, false ) . ' ' . ( $required ? "required aria-required='true'" : '' ) . '/> '; $field .= esc_html( $option ) . "</label>\n"; $field .= "\t\t<div class='clear-form'></div>\n"; } } return $field; } function render_checkbox_field( $id, $label, $value, $class, $required, $required_field_text ) { $field = "<label class='grunion-field-label checkbox" . ( $this->is_error() ? ' form-error' : '' ) . "'>"; $field .= "\t\t<input type='checkbox' name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack' ) . "' " . $class . checked( (bool) $value, true, false ) . ' ' . ( $required ? "required aria-required='true'" : '' ) . "/> \n"; $field .= "\t\t" . esc_html( $label ) . ( $required ? '<span>' . $required_field_text . '</span>' : '' ); $field .= "</label>\n"; $field .= "<div class='clear-form'></div>\n"; return $field; } /** * Render the consent field. * * @param string $id field id. * @param string $class html classes (can be set by the admin). */ private function render_consent_field( $id, $class ) { $consent_type = 'explicit' === $this->get_attribute( 'consenttype' ) ? 'explicit' : 'implicit'; $consent_message = 'explicit' === $consent_type ? $this->get_attribute( 'explicitconsentmessage' ) : $this->get_attribute( 'implicitconsentmessage' ); $field = "<label class='grunion-field-label consent consent-" . $consent_type . "'>"; if ( 'implicit' === $consent_type ) { $field .= "\t\t<input aria-hidden='true' type='checkbox' checked name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack' ) . "' style='display:none;' /> \n"; } else { $field .= "\t\t<input type='checkbox' name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack' ) . "' " . $class . "/> \n"; } $field .= "\t\t" . esc_html( $consent_message ); $field .= "</label>\n"; $field .= "<div class='clear-form'></div>\n"; return $field; } function render_checkbox_multiple_field( $id, $label, $value, $class, $required, $required_field_text ) { $field = $this->render_label( '', $id, $label, $required, $required_field_text ); foreach ( (array) $this->get_attribute( 'options' ) as $optionIndex => $option ) { $option = Grunion_Contact_Form_Plugin::strip_tags( $option ); if ( $option ) { $field .= "\t\t<label class='grunion-checkbox-multiple-label checkbox-multiple" . ( $this->is_error() ? ' form-error' : '' ) . "'>"; $field .= "<input type='checkbox' name='" . esc_attr( $id ) . "[]' value='" . esc_attr( $this->get_option_value( $this->get_attribute( 'values' ), $optionIndex, $option ) ) . "' " . $class . checked( in_array( $option, (array) $value ), true, false ) . ' /> '; $field .= esc_html( $option ) . "</label>\n"; $field .= "\t\t<div class='clear-form'></div>\n"; } } return $field; } function render_select_field( $id, $label, $value, $class, $required, $required_field_text ) { $field = $this->render_label( 'select', $id, $label, $required, $required_field_text ); $field .= "\t<select name='" . esc_attr( $id ) . "' id='" . esc_attr( $id ) . "' " . $class . ( $required ? "required aria-required='true'" : '' ) . ">\n"; foreach ( (array) $this->get_attribute( 'options' ) as $optionIndex => $option ) { $option = Grunion_Contact_Form_Plugin::strip_tags( $option ); if ( $option ) { $field .= "\t\t<option" . selected( $option, $value, false ) . " value='" . esc_attr( $this->get_option_value( $this->get_attribute( 'values' ), $optionIndex, $option ) ) . "'>" . esc_html( $option ) . "</option>\n"; } } $field .= "\t</select>\n"; return $field; } function render_date_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder ) { $field = $this->render_label( 'date', $id, $label, $required, $required_field_text ); $field .= $this->render_input_field( 'text', $id, $value, $class, $placeholder, $required ); /* For AMP requests, use amp-date-picker element: https://amp.dev/documentation/components/amp-date-picker */ if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) { return sprintf( '<%1$s mode="overlay" layout="container" type="single" input-selector="[name=%2$s]">%3$s</%1$s>', 'amp-date-picker', esc_attr( $id ), $field ); } wp_enqueue_script( 'grunion-frontend', Assets::get_file_url_for_environment( '_inc/build/contact-form/js/grunion-frontend.min.js', 'modules/contact-form/js/grunion-frontend.js' ), array( 'jquery', 'jquery-ui-datepicker' ) ); wp_enqueue_style( 'jp-jquery-ui-datepicker', plugins_url( 'css/jquery-ui-datepicker.css', __FILE__ ), array( 'dashicons' ), '1.0' ); // Using Core's built-in datepicker localization routine wp_localize_jquery_ui_datepicker(); return $field; } function render_default_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $type ) { $field = $this->render_label( $type, $id, $label, $required, $required_field_text ); $field .= $this->render_input_field( 'text', $id, $value, $class, $placeholder, $required ); return $field; } function render_field( $type, $id, $label, $value, $class, $placeholder, $required ) { $field_placeholder = ( ! empty( $placeholder ) ) ? "placeholder='" . esc_attr( $placeholder ) . "'" : ''; $field_class = "class='" . trim( esc_attr( $type ) . ' ' . esc_attr( $class ) ) . "' "; $wrap_classes = empty( $class ) ? '' : implode( '-wrap ', array_filter( explode( ' ', $class ) ) ) . '-wrap'; // this adds $shell_field_class = "class='grunion-field-wrap grunion-field-" . trim( esc_attr( $type ) . '-wrap ' . esc_attr( $wrap_classes ) ) . "' "; /** /** * Filter the Contact Form required field text * * @module contact-form * * @since 3.8.0 * * @param string $var Required field text. Default is "(required)". */ $required_field_text = esc_html( apply_filters( 'jetpack_required_field_text', __( '(required)', 'jetpack' ) ) ); $field = "\n<div {$shell_field_class} >\n"; // new in Jetpack 6.8.0 // If they are logged in, and this is their site, don't pre-populate fields if ( current_user_can( 'manage_options' ) ) { $value = ''; } switch ( $type ) { case 'email': $field .= $this->render_email_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'telephone': $field .= $this->render_telephone_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'url': $field .= $this->render_url_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'textarea': $field .= $this->render_textarea_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'radio': $field .= $this->render_radio_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'checkbox': $field .= $this->render_checkbox_field( $id, $label, $value, $field_class, $required, $required_field_text ); break; case 'checkbox-multiple': $field .= $this->render_checkbox_multiple_field( $id, $label, $value, $field_class, $required, $required_field_text ); break; case 'select': $field .= $this->render_select_field( $id, $label, $value, $field_class, $required, $required_field_text ); break; case 'date': $field .= $this->render_date_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder ); break; case 'consent': $field .= $this->render_consent_field( $id, $field_class ); break; default: // text field $field .= $this->render_default_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $type ); break; } $field .= "\t</div>\n"; return $field; } } add_action( 'init', array( 'Grunion_Contact_Form_Plugin', 'init' ), 9 ); add_action( 'grunion_scheduled_delete', 'grunion_delete_old_spam' ); /** * Deletes old spam feedbacks to keep the posts table size under control */ function grunion_delete_old_spam() { global $wpdb; $grunion_delete_limit = 100; $now_gmt = current_time( 'mysql', 1 ); $sql = $wpdb->prepare( " SELECT `ID` FROM $wpdb->posts WHERE DATE_SUB( %s, INTERVAL 15 DAY ) > `post_date_gmt` AND `post_type` = 'feedback' AND `post_status` = 'spam' LIMIT %d ", $now_gmt, $grunion_delete_limit ); $post_ids = $wpdb->get_col( $sql ); foreach ( (array) $post_ids as $post_id ) { // force a full delete, skip the trash wp_delete_post( $post_id, true ); } if ( /** * Filter if the module run OPTIMIZE TABLE on the core WP tables. * * @module contact-form * * @since 1.3.1 * @since 6.4.0 Set to false by default. * * @param bool $filter Should Jetpack optimize the table, defaults to false. */ apply_filters( 'grunion_optimize_table', false ) ) { $wpdb->query( "OPTIMIZE TABLE $wpdb->posts" ); } // if we hit the max then schedule another run if ( count( $post_ids ) >= $grunion_delete_limit ) { wp_schedule_single_event( time() + 700, 'grunion_scheduled_delete' ); } } /** * Send an event to Tracks on form submission. * * @param int $post_id - the post_id for the CPT that is created. * @param array $all_values - fields from the default contact form. * @param array $extra_values - extra fields added to from the contact form. * * @return null|void */ function jetpack_tracks_record_grunion_pre_message_sent( $post_id, $all_values, $extra_values ) { // Do not do anything if the submission is not from a block. if ( ! isset( $extra_values['is_block'] ) || ! $extra_values['is_block'] ) { return; } /* * Event details. */ $event_user = wp_get_current_user(); $event_name = 'contact_form_block_message_sent'; $event_props = array( 'entry_permalink' => esc_url( $all_values['entry_permalink'] ), 'feedback_id' => esc_attr( $all_values['feedback_id'] ), ); /* * Record event. * We use different libs on wpcom and Jetpack. */ if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $event_name = 'wpcom_' . $event_name; $event_props['blog_id'] = get_current_blog_id(); // If the form was sent by a logged out visitor, record event with blog owner. if ( empty( $event_user->ID ) ) { $event_user_id = wpcom_get_blog_owner( $event_props['blog_id'] ); $event_user = get_userdata( $event_user_id ); } jetpack_require_lib( 'tracks/client' ); tracks_record_event( $event_user, $event_name, $event_props ); } else { // If the form was sent by a logged out visitor, record event with Jetpack master user. if ( empty( $event_user->ID ) ) { $master_user_id = Jetpack_Options::get_option( 'master_user' ); if ( ! empty( $master_user_id ) ) { $event_user = get_userdata( $master_user_id ); } } $tracking = new Automattic\Jetpack\Tracking(); $tracking->record_user_event( $event_name, $event_props, $event_user ); } } add_action( 'grunion_pre_message_sent', 'jetpack_tracks_record_grunion_pre_message_sent', 12, 3 );
Automattic/vip-go-mu-plugins
jetpack-9.4/modules/contact-form/grunion-contact-form.php
PHP
gpl-2.0
127,971
[ 30522, 1026, 1029, 25718, 1013, 1013, 25718, 6169, 1024, 8568, 2773, 20110, 1012, 6764, 1012, 5371, 18442, 1012, 19528, 26266, 8873, 20844, 4168, 1013, 1008, 1008, 1008, 24665, 19496, 2239, 3967, 2433, 1008, 5587, 1037, 3967, 2433, 2000, 21...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#region MIT // /*The MIT License (MIT) // // Copyright 2016 lizs lizs4ever@163.com // // 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. // * */ #endregion using System; using System.Collections.Generic; namespace Pi.Framework { public interface IProperty { #region Êý¾Ý²Ù×÷ void Inject(IEnumerable<IBlock> blocks); List<T> GetList<T>(short pid); bool Inject(IBlock block); bool Inc<T>(short pid, T delta); bool Inc(short pid, object delta); bool Inc<T>(short pid, T delta, out T overflow); bool Inc(short pid, object delta, out object overflow); bool IncTo<T>(short pid, T target); bool IncTo(short pid, object target); bool Set<T>(short pid, T value); bool Set(short pid, object value); int IndexOf<T>(short pid, T item); int IndexOf<T>(short pid, Predicate<T> condition); T GetByIndex<T>(short pid, int idx); bool Add<T>(short pid, T value); bool Add(short pid, object value); bool AddRange<T>(short pid, List<T> items); bool Remove<T>(short pid, T item); bool Remove(short pid, object item); bool RemoveAll<T>(short pid, Predicate<T> predicate); bool RemoveAll<T>(short pid, Predicate<T> predicate, out int count); bool RemoveAll(short pid); bool RemoveAll(short pid, out int count); bool Insert<T>(short pid, int idx, T item); bool Insert(short pid, int idx, object item); bool Replace<T>(short pid, int idx, T item); bool Swap<T>(short pid, int idxA, int idxB); #endregion } }
lizs/Pi
Pi.Framework/ecs/entity/IProperty.cs
C#
mit
2,676
[ 30522, 1001, 2555, 10210, 1013, 1013, 1013, 1008, 1996, 10210, 6105, 1006, 10210, 1007, 1013, 1013, 1013, 1013, 9385, 2355, 9056, 2015, 9056, 2015, 2549, 22507, 1030, 17867, 1012, 4012, 1013, 1013, 1013, 1013, 6656, 2003, 2182, 3762, 4379, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>12. windows.alpc – Advanced Local Procedure Call &#8212; PythonForWindows 0.6 documentation</title> <link rel="stylesheet" href="_static/classic.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="_static/css/mbasic.css" /> <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/language_data.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="13. windows.rpc – ALPC-based Windows RPC" href="rpc.html" /> <link rel="prev" title="11. windows.crypto – CryptoAPI" href="crypto.html" /> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="rpc.html" title="13. windows.rpc – ALPC-based Windows RPC" accesskey="N">next</a> |</li> <li class="right" > <a href="crypto.html" title="11. windows.crypto – CryptoAPI" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="index.html">PythonForWindows 0.6 documentation</a> &#187;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="module-windows.alpc"> <span id="windows-alpc-advanced-local-procedure-call"></span><h1>12. <code class="docutils literal notranslate"><span class="pre">windows.alpc</span></code> – Advanced Local Procedure Call<a class="headerlink" href="#module-windows.alpc" title="Permalink to this headline">¶</a></h1> <p>The <a class="reference internal" href="#module-windows.alpc" title="windows.alpc"><code class="xref py py-mod docutils literal notranslate"><span class="pre">windows.alpc</span></code></a> module regroups the classes that permits to send and receive ALPC messages over an ALPC port and the classes representing these messages.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>See samples:</p> <blockquote class="last"> <div><ul class="simple"> <li><a class="reference internal" href="sample.html#sample-alpc"><span class="std std-ref">simple alpc communication</span></a></li> <li><a class="reference internal" href="sample.html#sample-advanced-alpc"><span class="std std-ref">advanced alpc communication</span></a></li> </ul> </div></blockquote> </div> <div class="section" id="alpc-message"> <h2>12.1. ALPC Message<a class="headerlink" href="#alpc-message" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="windows.alpc.AlpcMessage"> <em class="property">class </em><code class="descclassname">windows.alpc.</code><code class="descname">AlpcMessage</code><span class="sig-paren">(</span><em>msg_or_size=4096</em>, <em>attributes=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcMessage"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcMessage" title="Permalink to this definition">¶</a></dt> <dd><p>Represent a full ALPC Message: a <a class="reference internal" href="#windows.alpc.AlpcMessagePort" title="windows.alpc.AlpcMessagePort"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessagePort</span></code></a> and a <a class="reference internal" href="#windows.alpc.MessageAttribute" title="windows.alpc.MessageAttribute"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageAttribute</span></code></a></p> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.allocated_attributes"> <code class="descname">allocated_attributes</code><a class="headerlink" href="#windows.alpc.AlpcMessage.allocated_attributes" title="Permalink to this definition">¶</a></dt> <dd><p>The list of allocated attributes</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body">[<a class="reference internal" href="generated.html#windows.generated_def.Flag" title="windows.generated_def.Flag"><code class="xref py py-class docutils literal notranslate"><span class="pre">Flag</span></code></a>]</td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.context_attribute"> <code class="descname">context_attribute</code><a class="headerlink" href="#windows.alpc.AlpcMessage.context_attribute" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_CONTEXT_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_CONTEXT_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_CONTEXT_ATTRIBUTE</span></code></a> of the message:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body"><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_CONTEXT_ATTR</span></code></td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.context_is_valid"> <code class="descname">context_is_valid</code><a class="headerlink" href="#windows.alpc.AlpcMessage.context_is_valid" title="Permalink to this definition">¶</a></dt> <dd><p>True if <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_CONTEXT_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_CONTEXT_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_CONTEXT_ATTRIBUTE</span></code></a> is a ValidAttributes</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.data"> <code class="descname">data</code><a class="headerlink" href="#windows.alpc.AlpcMessage.data" title="Permalink to this definition">¶</a></dt> <dd><p>The data of the message (located after the PORT_MESSAGE header)</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.handle_attribute"> <code class="descname">handle_attribute</code><a class="headerlink" href="#windows.alpc.AlpcMessage.handle_attribute" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_HANDLE_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_HANDLE_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_HANDLE_ATTRIBUTE</span></code></a> of the message:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body"><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_HANDLE_ATTR</span></code></td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.handle_is_valid"> <code class="descname">handle_is_valid</code><a class="headerlink" href="#windows.alpc.AlpcMessage.handle_is_valid" title="Permalink to this definition">¶</a></dt> <dd><p>True if <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_HANDLE_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_HANDLE_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_HANDLE_ATTRIBUTE</span></code></a> is a ValidAttributes</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.security_attribute"> <code class="descname">security_attribute</code><a class="headerlink" href="#windows.alpc.AlpcMessage.security_attribute" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_SECURITY_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_SECURITY_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_SECURITY_ATTRIBUTE</span></code></a> of the message</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body"><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_SECURITY_ATTR</span></code></td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.security_is_valid"> <code class="descname">security_is_valid</code><a class="headerlink" href="#windows.alpc.AlpcMessage.security_is_valid" title="Permalink to this definition">¶</a></dt> <dd><p>True if <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_SECURITY_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_SECURITY_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_SECURITY_ATTRIBUTE</span></code></a> is a ValidAttributes</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.type"> <code class="descname">type</code><a class="headerlink" href="#windows.alpc.AlpcMessage.type" title="Permalink to this definition">¶</a></dt> <dd><p>The type of the message (<code class="docutils literal notranslate"><span class="pre">PORT_MESSAGE.u2.s2.Type</span></code>)</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.valid_attributes"> <code class="descname">valid_attributes</code><a class="headerlink" href="#windows.alpc.AlpcMessage.valid_attributes" title="Permalink to this definition">¶</a></dt> <dd><p>The list of valid attributes</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body">[<a class="reference internal" href="generated.html#windows.generated_def.Flag" title="windows.generated_def.Flag"><code class="xref py py-class docutils literal notranslate"><span class="pre">Flag</span></code></a>]</td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.view_attribute"> <code class="descname">view_attribute</code><a class="headerlink" href="#windows.alpc.AlpcMessage.view_attribute" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_VIEW_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_VIEW_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_VIEW_ATTRIBUTE</span></code></a> of the message:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body"><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_DATA_VIEW_ATTR</span></code></td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessage.view_is_valid"> <code class="descname">view_is_valid</code><a class="headerlink" href="#windows.alpc.AlpcMessage.view_is_valid" title="Permalink to this definition">¶</a></dt> <dd><p>True if <a class="reference internal" href="windef_generated.html#windows.generated_def.ALPC_MESSAGE_VIEW_ATTRIBUTE" title="windows.generated_def.ALPC_MESSAGE_VIEW_ATTRIBUTE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ALPC_MESSAGE_VIEW_ATTRIBUTE</span></code></a> is a ValidAttributes</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="windows.alpc.AlpcMessagePort"> <em class="property">class </em><code class="descclassname">windows.alpc.</code><code class="descname">AlpcMessagePort</code><a class="reference internal" href="_modules/windows/alpc.html#AlpcMessagePort"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcMessagePort" title="Permalink to this definition">¶</a></dt> <dd><p>The effective ALPC Message composed of a <code class="docutils literal notranslate"><span class="pre">PORT_MESSAGE</span></code> structure followed by the data</p> <dl class="attribute"> <dt id="windows.alpc.AlpcMessagePort.data"> <code class="descname">data</code><a class="headerlink" href="#windows.alpc.AlpcMessagePort.data" title="Permalink to this definition">¶</a></dt> <dd><p>The data of the message (located after the header)</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcMessagePort.datalen"> <code class="descname">datalen</code><a class="headerlink" href="#windows.alpc.AlpcMessagePort.datalen" title="Permalink to this definition">¶</a></dt> <dd><p>The length of the data</p> </dd></dl> <dl class="classmethod"> <dt id="windows.alpc.AlpcMessagePort.from_buffer"> <em class="property">classmethod </em><code class="descname">from_buffer</code><span class="sig-paren">(</span><em>object</em>, <em>offset=0</em><span class="sig-paren">)</span> &#x2192; C instance<a class="reference internal" href="_modules/windows/alpc.html#AlpcMessagePort.from_buffer"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcMessagePort.from_buffer" title="Permalink to this definition">¶</a></dt> <dd><p>create a C instance from a writeable buffer</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="windows.alpc.MessageAttribute"> <em class="property">class </em><code class="descclassname">windows.alpc.</code><code class="descname">MessageAttribute</code><a class="reference internal" href="_modules/windows/alpc.html#MessageAttribute"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.MessageAttribute" title="Permalink to this definition">¶</a></dt> <dd><p>The attributes of an ALPC message</p> <dl class="attribute"> <dt id="windows.alpc.MessageAttribute.allocated_list"> <code class="descname">allocated_list</code><a class="headerlink" href="#windows.alpc.MessageAttribute.allocated_list" title="Permalink to this definition">¶</a></dt> <dd><p>The list of allocated attributes</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body">[<a class="reference internal" href="generated.html#windows.generated_def.Flag" title="windows.generated_def.Flag"><code class="xref py py-class docutils literal notranslate"><span class="pre">Flag</span></code></a>]</td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.MessageAttribute.is_allocated"> <code class="descname">is_allocated</code><span class="sig-paren">(</span><em>attribute</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#MessageAttribute.is_allocated"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.MessageAttribute.is_allocated" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <code class="docutils literal notranslate"><span class="pre">attribute</span></code> is allocated</p> </dd></dl> <dl class="method"> <dt id="windows.alpc.MessageAttribute.is_valid"> <code class="descname">is_valid</code><span class="sig-paren">(</span><em>attribute</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#MessageAttribute.is_valid"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.MessageAttribute.is_valid" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <code class="docutils literal notranslate"><span class="pre">attribute</span></code> is valid</p> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.MessageAttribute.valid_list"> <code class="descname">valid_list</code><a class="headerlink" href="#windows.alpc.MessageAttribute.valid_list" title="Permalink to this definition">¶</a></dt> <dd><p>The list of valid attributes</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Type:</th><td class="field-body">[<a class="reference internal" href="generated.html#windows.generated_def.Flag" title="windows.generated_def.Flag"><code class="xref py py-class docutils literal notranslate"><span class="pre">Flag</span></code></a>]</td> </tr> </tbody> </table> </dd></dl> <dl class="classmethod"> <dt id="windows.alpc.MessageAttribute.with_all_attributes"> <em class="property">classmethod </em><code class="descname">with_all_attributes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#MessageAttribute.with_all_attributes"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.MessageAttribute.with_all_attributes" title="Permalink to this definition">¶</a></dt> <dd><p>Create a new <a class="reference internal" href="#windows.alpc.MessageAttribute" title="windows.alpc.MessageAttribute"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageAttribute</span></code></a> with the following attributes allocated:</p> <ul class="simple"> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_SECURITY_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_VIEW_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_CONTEXT_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_HANDLE_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_TOKEN_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_DIRECT_ATTRIBUTE</span></code></li> <li><code class="xref py py-class docutils literal notranslate"><span class="pre">ALPC_MESSAGE_WORK_ON_BEHALF_ATTRIBUTE</span></code></li> </ul> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body"><a class="reference internal" href="#windows.alpc.MessageAttribute" title="windows.alpc.MessageAttribute"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageAttribute</span></code></a></td> </tr> </tbody> </table> </dd></dl> <dl class="classmethod"> <dt id="windows.alpc.MessageAttribute.with_attributes"> <em class="property">classmethod </em><code class="descname">with_attributes</code><span class="sig-paren">(</span><em>attributes</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#MessageAttribute.with_attributes"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.MessageAttribute.with_attributes" title="Permalink to this definition">¶</a></dt> <dd><p>Create a new <a class="reference internal" href="#windows.alpc.MessageAttribute" title="windows.alpc.MessageAttribute"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageAttribute</span></code></a> with <code class="docutils literal notranslate"><span class="pre">attributes</span></code> allocated</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body"><a class="reference internal" href="#windows.alpc.MessageAttribute" title="windows.alpc.MessageAttribute"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageAttribute</span></code></a></td> </tr> </tbody> </table> </dd></dl> </dd></dl> </div> <div class="section" id="alpc-client"> <h2>12.2. ALPC client<a class="headerlink" href="#alpc-client" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="windows.alpc.AlpcClient"> <em class="property">class </em><code class="descclassname">windows.alpc.</code><code class="descname">AlpcClient</code><span class="sig-paren">(</span><em>port_name=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcClient"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcClient" title="Permalink to this definition">¶</a></dt> <dd><p>An ALPC client able to connect to a port and send/receive messages</p> <dl class="method"> <dt id="windows.alpc.AlpcClient.connect_to_port"> <code class="descname">connect_to_port</code><span class="sig-paren">(</span><em>port_name</em>, <em>connect_message=None</em>, <em>port_attr=None</em>, <em>port_attr_flags=65536</em>, <em>obj_attr=None</em>, <em>flags=ALPC_MSGFLG_SYNC_REQUEST(0x20000)</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcClient.connect_to_port"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcClient.connect_to_port" title="Permalink to this definition">¶</a></dt> <dd><p>Connect to the ALPC port <code class="docutils literal notranslate"><span class="pre">port_name</span></code>. Most of the parameters have defauls value is <code class="docutils literal notranslate"><span class="pre">None</span></code> is passed.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>connect_message</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a>) – The message send with the connection request, if not <code class="docutils literal notranslate"><span class="pre">None</span></code> the function will return an <a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessage</span></code></a></li> <li><strong>port_attr</strong> (<em>ALPC_PORT_ATTRIBUTES</em>) – The port attributes, one with default value will be used if this parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code></li> <li><strong>port_attr_flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – <code class="docutils literal notranslate"><span class="pre">ALPC_PORT_ATTRIBUTES.Flags</span></code> used if <code class="docutils literal notranslate"><span class="pre">port_attr</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (MUTUALY EXCLUSINVE WITH <code class="docutils literal notranslate"><span class="pre">port_attr</span></code>)</li> <li><strong>obj_attr</strong> (<a class="reference internal" href="winstructs_generated.html#windows.generated_def.winstructs.OBJECT_ATTRIBUTES" title="windows.generated_def.winstructs.OBJECT_ATTRIBUTES"><em>OBJECT_ATTRIBUTES</em></a>) – The attributes of the port (can be None)</li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcConnectPort()</span></code></li> <li><strong>timeout</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The timeout of the request</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="windows.alpc.AlpcClient.port_name"> <code class="descname">port_name</code><em class="property"> = None</em><a class="headerlink" href="#windows.alpc.AlpcClient.port_name" title="Permalink to this definition">¶</a></dt> <dd><p>The name of the ALPC port the client is connect to.</p> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcClient.recv"> <code class="descname">recv</code><span class="sig-paren">(</span><em>receive_msg=None</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcClient.recv" title="Permalink to this definition">¶</a></dt> <dd><p>Receive a message into <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> with <code class="docutils literal notranslate"><span class="pre">flags</span></code>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>receive_msg</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/constants.html#None" title="(in Python v2.7)"><em>None</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">receive_msg</span></code> is a <code class="docutils literal notranslate"><span class="pre">None</span></code> it create and return a simple <a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessage</span></code></a></li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcClient.send"> <code class="descname">send</code><span class="sig-paren">(</span><em>alpc_message</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcClient.send" title="Permalink to this definition">¶</a></dt> <dd><p>Send the <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> with <code class="docutils literal notranslate"><span class="pre">flags</span></code></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>alpc_message</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> is a <a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> it build an AlpcMessage with the message as data.</li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcClient.send_receive"> <code class="descname">send_receive</code><span class="sig-paren">(</span><em>alpc_message</em>, <em>receive_msg=None</em>, <em>flags=ALPC_MSGFLG_SYNC_REQUEST(0x20000)</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcClient.send_receive" title="Permalink to this definition">¶</a></dt> <dd><p>Send and receive a message with <code class="docutils literal notranslate"><span class="pre">flags</span></code>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>alpc_message</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> is a <a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> it build an AlpcMessage with the message as data.</li> <li><strong>receive_msg</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/constants.html#None" title="(in Python v2.7)"><em>None</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">receive_msg</span></code> is a <code class="docutils literal notranslate"><span class="pre">None</span></code> it create and return a simple <a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessage</span></code></a></li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> </div> <div class="section" id="alpc-server"> <h2>12.3. ALPC Server<a class="headerlink" href="#alpc-server" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="windows.alpc.AlpcServer"> <em class="property">class </em><code class="descclassname">windows.alpc.</code><code class="descname">AlpcServer</code><span class="sig-paren">(</span><em>port_name=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcServer"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcServer" title="Permalink to this definition">¶</a></dt> <dd><p>An ALPC server able to create a port, accept connections and send/receive messages</p> <dl class="method"> <dt id="windows.alpc.AlpcServer.accept_connection"> <code class="descname">accept_connection</code><span class="sig-paren">(</span><em>msg</em>, <em>port_attr=None</em>, <em>port_context=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcServer.accept_connection"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcServer.accept_connection" title="Permalink to this definition">¶</a></dt> <dd><p>Accept the connection for a <code class="docutils literal notranslate"><span class="pre">LPC_CONNECTION_REQUEST</span></code> message. <code class="docutils literal notranslate"><span class="pre">msg.MessageId</span></code> must be the same as the connection requesting message.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>msg</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a>) – The response message.</li> <li><strong>port_attr</strong> (<em>ALPC_PORT_ATTRIBUTES</em>) – The attributes of the port, one with default value will be used if this parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code></li> <li><strong>port_context</strong> (<em>PVOID</em>) – A value that will be copied in <code class="docutils literal notranslate"><span class="pre">ALPC_CONTEXT_ATTR.PortContext</span></code> of every message on this connection.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcServer.create_port"> <code class="descname">create_port</code><span class="sig-paren">(</span><em>port_name</em>, <em>msglen=None</em>, <em>port_attr_flags=0</em>, <em>obj_attr=None</em>, <em>port_attr=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/windows/alpc.html#AlpcServer.create_port"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#windows.alpc.AlpcServer.create_port" title="Permalink to this definition">¶</a></dt> <dd><p>Create the ALPC port <code class="docutils literal notranslate"><span class="pre">port_name</span></code>. Most of the parameters have defauls value is <code class="docutils literal notranslate"><span class="pre">None</span></code> is passed.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>port_name</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – The port’s name to create.</li> <li><strong>msglen</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – <code class="docutils literal notranslate"><span class="pre">ALPC_PORT_ATTRIBUTES.MaxMessageLength</span></code> used if <code class="docutils literal notranslate"><span class="pre">port_attr</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (MUTUALY EXCLUSINVE WITH <code class="docutils literal notranslate"><span class="pre">port_attr</span></code>)</li> <li><strong>port_attr_flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – <code class="docutils literal notranslate"><span class="pre">ALPC_PORT_ATTRIBUTES.Flags</span></code> used if <code class="docutils literal notranslate"><span class="pre">port_attr</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (MUTUALY EXCLUSINVE WITH <code class="docutils literal notranslate"><span class="pre">port_attr</span></code>)</li> <li><strong>obj_attr</strong> (<a class="reference internal" href="winstructs_generated.html#windows.generated_def.winstructs.OBJECT_ATTRIBUTES" title="windows.generated_def.winstructs.OBJECT_ATTRIBUTES"><em>OBJECT_ATTRIBUTES</em></a>) – The attributes of the port, one with default value will be used if this parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code></li> <li><strong>port_attr</strong> (<em>ALPC_PORT_ATTRIBUTES</em>) – The port attributes, one with default value will be used if this parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcServer.recv"> <code class="descname">recv</code><span class="sig-paren">(</span><em>receive_msg=None</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcServer.recv" title="Permalink to this definition">¶</a></dt> <dd><p>Receive a message into <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> with <code class="docutils literal notranslate"><span class="pre">flags</span></code>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>receive_msg</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/constants.html#None" title="(in Python v2.7)"><em>None</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">receive_msg</span></code> is a <code class="docutils literal notranslate"><span class="pre">None</span></code> it create and return a simple <a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessage</span></code></a></li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcServer.send"> <code class="descname">send</code><span class="sig-paren">(</span><em>alpc_message</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcServer.send" title="Permalink to this definition">¶</a></dt> <dd><p>Send the <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> with <code class="docutils literal notranslate"><span class="pre">flags</span></code></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>alpc_message</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> is a <a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> it build an AlpcMessage with the message as data.</li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="windows.alpc.AlpcServer.send_receive"> <code class="descname">send_receive</code><span class="sig-paren">(</span><em>alpc_message</em>, <em>receive_msg=None</em>, <em>flags=ALPC_MSGFLG_SYNC_REQUEST(0x20000)</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#windows.alpc.AlpcServer.send_receive" title="Permalink to this definition">¶</a></dt> <dd><p>Send and receive a message with <code class="docutils literal notranslate"><span class="pre">flags</span></code>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>alpc_message</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">alpc_message</span></code> is a <a class="reference external" href="https://docs.python.org/2.7/library/functions.html#str" title="(in Python v2.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> it build an AlpcMessage with the message as data.</li> <li><strong>receive_msg</strong> (<a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><em>AlpcMessage</em></a><em> or </em><a class="reference external" href="https://docs.python.org/2.7/library/constants.html#None" title="(in Python v2.7)"><em>None</em></a>) – The message to send. If <code class="docutils literal notranslate"><span class="pre">receive_msg</span></code> is a <code class="docutils literal notranslate"><span class="pre">None</span></code> it create and return a simple <a class="reference internal" href="#windows.alpc.AlpcMessage" title="windows.alpc.AlpcMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">AlpcMessage</span></code></a></li> <li><strong>flags</strong> (<a class="reference external" href="https://docs.python.org/2.7/library/functions.html#int" title="(in Python v2.7)"><em>int</em></a>) – The flags for <code class="xref py py-func docutils literal notranslate"><span class="pre">NtAlpcSendWaitReceivePort()</span></code></li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="index.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">12. <code class="docutils literal notranslate"><span class="pre">windows.alpc</span></code> – Advanced Local Procedure Call</a><ul> <li><a class="reference internal" href="#alpc-message">12.1. ALPC Message</a></li> <li><a class="reference internal" href="#alpc-client">12.2. ALPC client</a></li> <li><a class="reference internal" href="#alpc-server">12.3. ALPC Server</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="crypto.html" title="previous chapter">11. <code class="docutils literal notranslate"><span class="pre">windows.crypto</span></code> – CryptoAPI</a></p> <h4>Next topic</h4> <p class="topless"><a href="rpc.html" title="next chapter">13. <code class="docutils literal notranslate"><span class="pre">windows.rpc</span></code> – ALPC-based Windows RPC</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/alpc.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="rpc.html" title="13. windows.rpc – ALPC-based Windows RPC" >next</a> |</li> <li class="right" > <a href="crypto.html" title="11. windows.crypto – CryptoAPI" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="index.html">PythonForWindows 0.6 documentation</a> &#187;</li> </ul> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2015-2020, Clement Rouault. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.8.5. </div> </body> </html>
hakril/PythonForWindows
docs/build/html/alpc.html
HTML
bsd-3-clause
47,008
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 1060, 11039, 19968, 1015, 1012, 1014, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#ifndef __LINUX_MEMORY_HOTPLUG_H #define __LINUX_MEMORY_HOTPLUG_H #include <linux/mmzone.h> #include <linux/spinlock.h> #include <linux/notifier.h> #include <linux/bug.h> struct page; struct zone; struct pglist_data; struct mem_section; struct memory_block; #ifdef CONFIG_MEMORY_HOTPLUG /* * Types for free bootmem stored in page->lru.next. These have to be in * some random range in unsigned long space for debugging purposes. */ enum { MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE = 12, SECTION_INFO = MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE, MIX_SECTION_INFO, NODE_INFO, MEMORY_HOTPLUG_MAX_BOOTMEM_TYPE = NODE_INFO, }; /* Types for control the zone type of onlined memory */ enum { ONLINE_KEEP, ONLINE_KERNEL, ONLINE_MOVABLE, }; /* * pgdat resizing functions */ static inline void pgdat_resize_lock(struct pglist_data *pgdat, unsigned long *flags) { spin_lock_irqsave(&pgdat->node_size_lock, *flags); } static inline void pgdat_resize_unlock(struct pglist_data *pgdat, unsigned long *flags) { spin_unlock_irqrestore(&pgdat->node_size_lock, *flags); } static inline void pgdat_resize_init(struct pglist_data *pgdat) { spin_lock_init(&pgdat->node_size_lock); } /* * Zone resizing functions * * Note: any attempt to resize a zone should has pgdat_resize_lock() * zone_span_writelock() both held. This ensure the size of a zone * can't be changed while pgdat_resize_lock() held. */ static inline unsigned zone_span_seqbegin(struct zone *zone) { return read_seqbegin(&zone->span_seqlock); } static inline int zone_span_seqretry(struct zone *zone, unsigned iv) { return read_seqretry(&zone->span_seqlock, iv); } static inline void zone_span_writelock(struct zone *zone) { write_seqlock(&zone->span_seqlock); } static inline void zone_span_writeunlock(struct zone *zone) { write_sequnlock(&zone->span_seqlock); } static inline void zone_seqlock_init(struct zone *zone) { seqlock_init(&zone->span_seqlock); } extern int zone_grow_free_lists(struct zone *zone, unsigned long new_nr_pages); extern int zone_grow_waitqueues(struct zone *zone, unsigned long nr_pages); extern int add_one_highpage(struct page *page, int pfn, int bad_ppro); /* VM interface that may be used by firmware interface */ extern int online_pages(unsigned long, unsigned long, int); extern void __offline_isolated_pages(unsigned long, unsigned long); typedef void (*online_page_callback_t)(struct page *page); extern int set_online_page_callback(online_page_callback_t callback); extern int restore_online_page_callback(online_page_callback_t callback); extern void __online_page_set_limits(struct page *page); extern void __online_page_increment_counters(struct page *page); extern void __online_page_free(struct page *page); #ifdef CONFIG_MEMORY_HOTREMOVE extern bool is_pageblock_removable_nolock(struct page *page); extern int arch_remove_memory(u64 start, u64 size); extern int __remove_pages(struct zone *zone, unsigned long start_pfn, unsigned long nr_pages); #endif /* CONFIG_MEMORY_HOTREMOVE */ /* reasonably generic interface to expand the physical pages in a zone */ extern int __add_pages(int nid, struct zone *zone, unsigned long start_pfn, unsigned long nr_pages); #ifdef CONFIG_NUMA extern int memory_add_physaddr_to_nid(u64 start); #else static inline int memory_add_physaddr_to_nid(u64 start) { return 0; } #endif #ifdef CONFIG_HAVE_ARCH_NODEDATA_EXTENSION /* * For supporting node-hotadd, we have to allocate a new pgdat. * * If an arch has generic style NODE_DATA(), * node_data[nid] = kzalloc() works well. But it depends on the architecture. * * In general, generic_alloc_nodedata() is used. * Now, arch_free_nodedata() is just defined for error path of node_hot_add. * */ extern pg_data_t *arch_alloc_nodedata(int nid); extern void arch_free_nodedata(pg_data_t *pgdat); extern void arch_refresh_nodedata(int nid, pg_data_t *pgdat); #else /* CONFIG_HAVE_ARCH_NODEDATA_EXTENSION */ #define arch_alloc_nodedata(nid) generic_alloc_nodedata(nid) #define arch_free_nodedata(pgdat) generic_free_nodedata(pgdat) #ifdef CONFIG_NUMA /* * If ARCH_HAS_NODEDATA_EXTENSION=n, this func is used to allocate pgdat. * XXX: kmalloc_node() can't work well to get new node's memory at this time. * Because, pgdat for the new node is not allocated/initialized yet itself. * To use new node's memory, more consideration will be necessary. */ #define generic_alloc_nodedata(nid) \ ({ \ kzalloc(sizeof(pg_data_t), GFP_KERNEL); \ }) /* * This definition is just for error path in node hotadd. * For node hotremove, we have to replace this. */ #define generic_free_nodedata(pgdat) kfree(pgdat) extern pg_data_t *node_data[]; static inline void arch_refresh_nodedata(int nid, pg_data_t *pgdat) { node_data[nid] = pgdat; } #else /* !CONFIG_NUMA */ /* never called */ static inline pg_data_t *generic_alloc_nodedata(int nid) { BUG(); return NULL; } static inline void generic_free_nodedata(pg_data_t *pgdat) { } static inline void arch_refresh_nodedata(int nid, pg_data_t *pgdat) { } #endif /* CONFIG_NUMA */ #endif /* CONFIG_HAVE_ARCH_NODEDATA_EXTENSION */ #ifdef CONFIG_HAVE_BOOTMEM_INFO_NODE extern void register_page_bootmem_info_node(struct pglist_data *pgdat); #else static inline void register_page_bootmem_info_node(struct pglist_data *pgdat) { } #endif extern void put_page_bootmem(struct page *page); extern void get_page_bootmem(unsigned long ingo, struct page *page, unsigned long type); /* * Lock for memory hotplug guarantees 1) all callbacks for memory hotplug * notifier will be called under this. 2) offline/online/add/remove memory * will not run simultaneously. */ void lock_memory_hotplug(void); void unlock_memory_hotplug(void); #else /* ! CONFIG_MEMORY_HOTPLUG */ /* * Stub functions for when hotplug is off */ static inline void pgdat_resize_lock(struct pglist_data *p, unsigned long *f) {} static inline void pgdat_resize_unlock(struct pglist_data *p, unsigned long *f) {} static inline void pgdat_resize_init(struct pglist_data *pgdat) {} static inline unsigned zone_span_seqbegin(struct zone *zone) { return 0; } static inline int zone_span_seqretry(struct zone *zone, unsigned iv) { return 0; } static inline void zone_span_writelock(struct zone *zone) {} static inline void zone_span_writeunlock(struct zone *zone) {} static inline void zone_seqlock_init(struct zone *zone) {} static inline int mhp_notimplemented(const char *func) { printk(KERN_WARNING "%s() called, with CONFIG_MEMORY_HOTPLUG disabled\n", func); dump_stack(); return -ENOSYS; } static inline void register_page_bootmem_info_node(struct pglist_data *pgdat) { } static inline void lock_memory_hotplug(void) {} static inline void unlock_memory_hotplug(void) {} #endif /* ! CONFIG_MEMORY_HOTPLUG */ #ifdef CONFIG_MEMORY_HOTREMOVE extern int is_mem_section_removable(unsigned long pfn, unsigned long nr_pages); extern void try_offline_node(int nid); #else static inline int is_mem_section_removable(unsigned long pfn, unsigned long nr_pages) { return 0; } static inline void try_offline_node(int nid) {} #endif /* CONFIG_MEMORY_HOTREMOVE */ extern int mem_online_node(int nid); extern int add_memory(int nid, u64 start, u64 size); extern int arch_add_memory(int nid, u64 start, u64 size); extern int offline_pages(unsigned long start_pfn, unsigned long nr_pages); extern int offline_memory_block(struct memory_block *mem); extern bool is_memblock_offlined(struct memory_block *mem); extern int remove_memory(int nid, u64 start, u64 size); extern int sparse_add_one_section(struct zone *zone, unsigned long start_pfn, int nr_pages); extern void sparse_remove_one_section(struct zone *zone, struct mem_section *ms); extern struct page *sparse_decode_mem_map(unsigned long coded_mem_map, unsigned long pnum); #endif /* __LINUX_MEMORY_HOTPLUG_H */
prasidh09/cse506
unionfs-3.10.y/include/linux/memory_hotplug.h
C
gpl-2.0
7,812
[ 30522, 1001, 2065, 13629, 2546, 1035, 1035, 11603, 1035, 3638, 1035, 2980, 24759, 15916, 1035, 1044, 1001, 9375, 1035, 1035, 11603, 1035, 3638, 1035, 2980, 24759, 15916, 1035, 1044, 1001, 2421, 1026, 11603, 1013, 3461, 15975, 1012, 1044, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!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 / released</a></li> <li class="active"><a href="">8.7.1+2 / higman-s - 8.6.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.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-11-21 02:02:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-21 02:02:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.7.1+2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@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.6&quot; &amp; &lt; &quot;8.7~&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.6.0.tar.gz&quot; checksum: &quot;md5=16dee76d75e5bb21e16f246c52272afc&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.6.0 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2). The following dependencies couldn&#39;t be met: - coq-higman-s -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) 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.6.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"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </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>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1+2/higman-s/8.6.0.html
HTML
mit
6,978
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import Marked from 'marked' import hljs from 'highlight.js' const renderer = new Marked.Renderer() export const toc = [] renderer.heading = function(text, level) { var slug = text.toLowerCase().replace(/\s+/g, '-') toc.push({ level: level, slug: slug, title: text }) return `<h${level}><a href='#${slug}' id='${slug}' class='anchor'></a><a href='#${slug}'>${text}</a></h${level}>` } Marked.setOptions({ highlight: function(code, lang) { if (hljs.getLanguage(lang)) { return hljs.highlight(lang, code).value } else { return hljs.highlightAuto(code).value } }, renderer }) export const marked = text => { var tok = Marked.lexer(text) text = Marked.parser(tok).replace(/<pre>/ig, '<pre class="hljs">') return text }
Smallpath/Blog
admin/src/components/utils/marked.js
JavaScript
apache-2.0
773
[ 30522, 12324, 4417, 2013, 1005, 4417, 1005, 12324, 1044, 2140, 22578, 2013, 1005, 12944, 1012, 1046, 2015, 1005, 9530, 3367, 17552, 2121, 1027, 2047, 4417, 1012, 17552, 2121, 1006, 1007, 9167, 9530, 3367, 2000, 2278, 1027, 1031, 1033, 17552...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>max</title> <link rel="stylesheet" type="text/css" href="csound.css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" /> <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" /> <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" /> <link rel="prev" href="massign.html" title="massign" /> <link rel="next" href="maxabs.html" title="maxabs" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">max</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="massign.html">Précédent</a> </td> <th width="60%" align="center">Opcodes et opérateurs de l'orchestre</th> <td width="20%" align="right"> <a accesskey="n" href="maxabs.html">Suivant</a></td> </tr> </table> <hr /> </div> <div class="refentry"> <a id="max"></a> <div class="titlepage"></div> <a id="IndexMax" class="indexterm"></a> <div class="refnamediv"> <h2> <span class="refentrytitle">max</span> </h2> <p>max — Produit un signal qui est le maximum de tous les signaux d'entrée. </p> </div> <div class="refsect1"> <a id="idm47887660865136"></a> <h2>Description</h2> <p> L'opcode <span class="emphasis"><em>max</em></span> prend en entrée n'importe quel nombre de signaux de taux-a, de taux-k ou de taux-i (tous au même taux), et retourne un signal du même taux qui est le maximum de toutes les entrées. Pour les signaux de taux-a, les entrées sont comparées échantillon par échantillon (c-à-d que <span class="emphasis"><em>max</em></span> n'examine pas une période <span class="emphasis"><em>ksmps</em></span> entière du signal pour trouver son maximum local comme l'opcode <span class="emphasis"><em>max_k</em></span> le fait). </p> </div> <div class="refsect1"> <a id="idm47887660861424"></a> <h2>Syntaxe</h2> <pre class="synopsis">amax <span class="command"><strong>max</strong></span> ain1, ain2 [, ain3] [, ain4] [...]</pre> <pre class="synopsis">kmax <span class="command"><strong>max</strong></span> kin1, kin2 [, kin3] [, kin4] [...]</pre> <pre class="synopsis">imax <span class="command"><strong>max</strong></span> iin1, iin2 [, iin3] [, iin4] [...]</pre> </div> <div class="refsect1"> <a id="idm47887660856448"></a> <h2>Exécution</h2> <p> <span class="emphasis"><em>ain1, ain2, ...</em></span> -- signaux de taux-a à comparer. </p> <p> <span class="emphasis"><em>kin1, kin2, ...</em></span> -- signaux de taux-k à comparer. </p> <p> <span class="emphasis"><em>iin1, iin2, ...</em></span> -- signaux de taux-i à comparer. </p> </div> <div class="refsect1"> <a id="idm47887660852960"></a> <h2>Exemples</h2> <p> Voici un exemple de l'opcode max. Il utilise le fichier <a class="ulink" href="examples/max.csd" target="_top"><em class="citetitle">max.csd</em></a>. </p> <div class="example"> <a id="idm47887660851184"></a> <p class="title"> <strong>Exemple 495. Exemple de l'opcode max.</strong> </p> <div class="example-contents"> <p>Voir les sections <a class="link" href="UsingRealTime.html" title="Audio en temps réel"><em class="citetitle">Audio en Temps Réel</em></a> et <a class="link" href="CommandFlags.html" title="Ligne de commande de Csound"><em class="citetitle">Options de la Ligne de Commande</em></a> pour plus d'information sur l'utilisation des options de la ligne de commande.</p> <div class="refsect1"> <a id="idm47887516508560"></a> <pre class="programlisting"> <span class="csdtag">&lt;CsoundSynthesizer&gt;</span> <span class="csdtag">&lt;CsOptions&gt;</span> <span class="comment">; Select audio/midi flags here according to platform</span> -odac <span class="comment">;;;realtime audio out</span> <span class="comment">;-iadc ;;;uncomment -iadc if realtime audio input is needed too</span> <span class="comment">; For Non-realtime ouput leave only the line below:</span> <span class="comment">; -o max.wav -W ;;; for file output any platform</span> <span class="csdtag">&lt;/CsOptions&gt;</span> <span class="csdtag">&lt;CsInstruments&gt;</span> <span class="ohdr">sr</span> <span class="op">=</span> 44100 <span class="ohdr">ksmps</span> <span class="op">=</span> 32 <span class="ohdr">nchnls</span> <span class="op">=</span> 2 <span class="ohdr">0dbfs</span> <span class="op">=</span> 1 <span class="oblock">instr</span> 1 k1 <span class="opc">oscili</span> 1, 10.0, 1 <span class="comment">;combine 3 sinusses</span> k2 <span class="opc">oscili</span> 1, 1.0, 1 <span class="comment">;at different rates</span> k3 <span class="opc">oscili</span> 1, 3.0, 1 kmax <span class="opc">max</span> k1, k2, k3 kmax <span class="op">=</span> kmax<span class="op">*</span>250 <span class="comment">;scale kmax</span> <span class="opc">printk2</span> kmax <span class="comment">;check the values</span> aout <span class="opc">vco2</span> .5, 220, 6 <span class="comment">;sawtooth</span> asig <span class="opc">moogvcf2</span> aout, 600<span class="op">+</span>kmax, .5 <span class="comment">;change filter around 600 Hz </span> <span class="opc">outs</span> asig, asig <span class="oblock">endin</span> <span class="csdtag">&lt;/CsInstruments&gt;</span> <span class="csdtag">&lt;CsScore&gt;</span> <span class="stamnt">f</span>1 0 32768 10 1 <span class="stamnt">i</span>1 0 5 <span class="stamnt">e</span> <span class="csdtag">&lt;/CsScore&gt;</span> <span class="csdtag">&lt;/CsoundSynthesizer&gt;</span> </pre> </div> </div> </div> <p><br class="example-break" /> </p> </div> <div class="refsect1"> <a id="idm47887660846816"></a> <h2>Voir aussi</h2> <p> <a class="link" href="min.html" title="min"><em class="citetitle">min</em></a>, <a class="link" href="maxabs.html" title="maxabs"><em class="citetitle">maxabs</em></a>, <a class="link" href="minabs.html" title="minabs"><em class="citetitle">minabs</em></a>, <a class="link" href="maxaccum.html" title="maxaccum"><em class="citetitle">maxaccum</em></a>, <a class="link" href="minaccum.html" title="minaccum"><em class="citetitle">minaccum</em></a>, <a class="link" href="maxabsaccum.html" title="maxabsaccum"><em class="citetitle">maxabsaccum</em></a>, <a class="link" href="minabsaccum.html" title="minabsaccum"><em class="citetitle">minabsaccum</em></a>, <a class="link" href="max_k.html" title="max_k"><em class="citetitle">max_k</em></a> </p> </div> <div class="refsect1"> <a id="idm47887660838112"></a> <h2>Crédits</h2> <p> </p> <table border="0" summary="Simple list" class="simplelist"> <tr> <td>Auteur : Anthony Kozar</td> </tr> <tr> <td>Mars 2006</td> </tr> </table> <p> </p> <p>Nouveau dans la version 5.01 de Csound ; taux-i ajouté dans la version 6.04</p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="massign.html">Précédent</a> </td> <td width="20%" align="center"> <a accesskey="u" href="OpcodesTop.html">Niveau supérieur</a> </td> <td width="40%" align="right"> <a accesskey="n" href="maxabs.html">Suivant</a></td> </tr> <tr> <td width="40%" align="left" valign="top">massign </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Sommaire</a> </td> <td width="40%" align="right" valign="top"> maxabs</td> </tr> </table> </div> </body> </html>
ketchupok/csound.github.io
docs/manual-fr/max.html
HTML
mit
8,629
[ 30522, 1026, 1029, 20950, 2544, 1027, 1000, 1015, 1012, 1014, 1000, 17181, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 26609, 1027, 1000, 2053, 1000, 1029, 1028, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// // AAAreaspline.h // AAChartKit // // Created by An An on 17/3/15. // Copyright © 2017年 An An. All rights reserved. //*************** ...... SOURCE CODE ...... *************** //***...................................................*** //*** https://github.com/AAChartModel/AAChartKit *** //*** https://github.com/AAChartModel/AAChartKit-Swift *** //***...................................................*** //*************** ...... SOURCE CODE ...... *************** /* * ------------------------------------------------------------------------------- * * 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔 * * Please contact me on GitHub,if there are any problems encountered in use. * GitHub Issues : https://github.com/AAChartModel/AAChartKit/issues * ------------------------------------------------------------------------------- * And if you want to contribute for this project, please contact me as well * GitHub : https://github.com/AAChartModel * StackOverflow : https://stackoverflow.com/users/12302132/codeforu * JianShu : https://www.jianshu.com/u/f1e6753d4254 * SegmentFault : https://segmentfault.com/u/huanghunbieguan * * ------------------------------------------------------------------------------- */ #import <Foundation/Foundation.h> @class AADataLabels; @interface AAAreaspline : NSObject AAPropStatementAndPropSetFuncStatement(strong, AAAreaspline, AADataLabels *, dataLabels) @end
AAChartModel/AAChartKit
AAChartKitLib/AAOptionsModel/AAAreaspline.h
C
mit
1,490
[ 30522, 1013, 1013, 1013, 1013, 13360, 16416, 13102, 4179, 1012, 1044, 1013, 1013, 9779, 7507, 5339, 23615, 1013, 1013, 1013, 1013, 2580, 2011, 2019, 2019, 2006, 2459, 1013, 1017, 1013, 2321, 1012, 1013, 1013, 9385, 1075, 2418, 1840, 2019, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
function Get-TraverseTest { <# .SYNOPSIS Retrieves Traverse Tests based on specified criteria. .DESCRIPTION This command leverages the Traverse APIs to gather information about tests in Traverse. .EXMPLE Get-TraverseTest Device1 Gets all tests from device Device1 .EXAMPLE Get-TraverseTest -TestName '*disk*' -DeviceName * Gets all tests from devices whos name contains the word "disk" .EXAMPLE Get-TraverseDevice "*dc*" | Get-TraverseTest -subtype ping Get all tests of type "ping" from the devices whos name contains the letters "dc" #> [CmdletBinding(DefaultParameterSetName="testName")] param ( #Name of the test you want to retrieve. Regular expressions are supported. [Parameter(ParameterSetName="testName",ValueFromPipelinebyPropertyName)][Alias("TestName")][String]$Name = '*', #Name of the device that you wish to retrieve the test from. If specified alone, gets all tests associated with this device [Parameter(Position=0,ParameterSetName="testName",Mandatory,ValueFromPipelinebyPropertyName)] [Parameter(ParameterSetName="deviceName",Mandatory)][String]$DeviceName, #Specify the individual serial number of the test you wish to retrieve [Parameter(ParameterSetName="testSerial",Mandatory,ValueFromPipeline,ValueFromPipelinebyPropertyName)][int]$TestSerial, #Filter by the type of test (wmi, snmp, ping, etc.) [String]$testType, #Filter by the test subtype (cpu, disk, pl, rtt, etc.) [String]$subType, #[SUPERUSER ONLY] Restrict scope of search to what the specified user can see [String]$RunAs, #Show the unencrypted cleartext password used for the test, if applicable [Switch]$ShowPWs ) # Param process { $argumentList = @{} switch ($PSCmdlet.ParameterSetName) { "testName" { $argumentList.testName = $Name if ($DeviceName) {$argumentList.deviceName = $DeviceName -replace ' ','*'} } "deviceName" { $argumentList.deviceName = $DeviceName -replace ' ','*' } "testSerial" {$argumentList.testSerial = $testSerial} } if ($RunAs) {$argumentList.userName = $RunAs} if ($testType) {$argumentList.testType = $testType} if ($subType) {$argumentList.subType = $subType} if ($ShowPWs) {$argumentList.showPassword = 'true'} Invoke-TraverseCommand test.list $argumentList -Verbose:($PSBoundParameters['Verbose'] -eq $true) } } #Get-TraverseDevice
JustinGrote/Traverse
Disabled/Get-TraverseTest.ps1
PowerShell
mit
2,625
[ 30522, 3853, 2131, 1011, 20811, 22199, 1063, 1026, 1001, 1012, 19962, 22599, 12850, 2015, 20811, 5852, 2241, 2006, 9675, 9181, 1012, 1012, 6412, 2023, 3094, 21155, 2015, 1996, 20811, 17928, 2015, 2000, 8587, 2592, 2055, 5852, 1999, 20811, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#ifndef __MAIN_HPP__ #define __MAIN_HPP__ #include <iostream> #include <unistd.h> #include <string> #include <vector> #include <stdint.h> // Para usar uint64_t #include "hanoi.hpp" #include "statistical.hpp" #include "ClaseTiempo.hpp" #define cls() system("clear"); long long combinatorio_iterativo(const int &n,const int &k){ long double fact_n = 1, fact_k = 1, fact_nk = 1; for( long double i = 2 ; i <= n ; ++i ) fact_n *= i; for( long double i = 2 ; i <= k ; ++i ) fact_k *= i; for( long double i = 2 ; i <= (n-k) ; ++i ) fact_nk *= i; return fact_n/fact_k/fact_nk; } long long combinatorio_recursivo(const int &n, const int &k){ if(k == 0 || k == n){ return 1; } return combinatorio_recursivo(n-1, k-1) + combinatorio_recursivo(n-1, k); } long long combinatorio_recursivo_2(const int &n, const int &k, std::vector<std::vector< long long > > &aux){ int a; if(k == 0 || k == n) return 1; if( aux[n-1][k-1] != -1 ){ a = aux[n-1][k-1]; } else{ a = combinatorio_recursivo_2(n-1, k-1, aux) + combinatorio_recursivo_2(n-1, k, aux); aux[n-1][k-1] = a; } return a; } /** * @brief Cabecera que se mostrará durante la ejecución del programa. */ void cabecera(){ cls(); std::cout << "\e[1;92m###############################" << std::endl; std::cout << "###############################" << std::endl; std::cout << "#### ####" << std::endl; std::cout << "#### \e[96mPrograma\e[92m ####" << std::endl; std::cout << "#### ####" << std::endl; std::cout << "###############################" << std::endl; std::cout << "###############################\e[0m" << std::endl << std::endl; } /** * @brief Mensaje que se muestra al final de cada opción del menú. * @note En la función aplicarFloyd() se llama también para dar paso al submenú. * @param count Número de veces a ejecutar std::cin.ignore() * @param mensaje Mensaje a mostar. Por defecto mostrará: "Presiona ENTER para volver al menú." */ void volver(const int &count = 2, const std::string &mensaje="Presiona ENTER para volver al menú."){ std::cout << std::endl << mensaje; for( int i = 0 ; i < count ; ++i) std::cin.ignore(); } /** * @brief Muestra un error personalizado por pantalla. * @note Con 2 segundos de sleep da tiempo a leer los errores. * @param er Error a mostrar. */ void error(const std::string &er){ std::cout << std::endl << "\e[31;1m[ERROR]\e[0m - " << er << std::endl; fflush(stdout); sleep(2); } /** * @brief Muestra las opciones del menú e interactua con el usuario. * @return Opción del menú a ejecutar. * @sa cabecera() * @sa error() */ uint opciones(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Menú combinatoria." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Menú Hanoi." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Salir del programa." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>2){ error("Opción no válida. Volviendo al menú principal..."); } }while(opcion<0 || opcion>2); return opcion; } /** * @brief Función para despedirse. * @note Con el Adiós en grande mejoramos la experiencia del usuario. * @sa cabecera() */ void despedida(){ cabecera(); std::cout << "Gracias por usar el programa, ¡hasta la próxima!\e[1m" << std::endl; std::cout << " _ _ __ " << std::endl << "\ /\\ | (_) /_/ " << std::endl << "\ / \\ __| |_ ___ ___ " << std::endl << "\ / /\\ \\ / _` | |/ _ \\/ __|" << std::endl << "\ / ____ \\ (_| | | (_) \\__ \\" << std::endl << "\ /_/ \\_\\__,_|_|\\___/|___/" << std::endl << "\ " << std::endl << "\ \e[0m" << std::endl; } void mostrar_determinacion(al::Statistical &stats){ cabecera(); std::cout << std::endl << "Coeficiente de determinación: " << stats.get_coef() << std::endl; volver(); } void mostrar_ecuacion(al::Statistical &stats){ cabecera(); bool lineal = stats.get_lineal(); std::vector<long double> aux = stats.get_params_value(); std::cout << "Ecuación de estimación:" << std::endl << "\tt(n) = "; if(lineal){ for (int i = 0; i < aux.size(); ++i) { std::cout << ((i == 0) ? aux[i] : std::abs(aux[i])) << "*n^" << i; if( i < (aux.size()-1)) aux[i]>0?std::cout<<" + ":std::cout<<" - "; } } else{ std::cout << aux[0] << (aux[1]>0?" + ":" - ") << std::abs(aux[1]) << "*2^n" << std::endl; } volver(); } void mostrar_grafica(const std::string &f_name){ cabecera(); std::string cmd = "xdg-open " + f_name + " 2> /dev/null"; FILE * aux = popen(cmd.c_str(), "r"); pclose(aux); volver(); } void estimar_tiempos(al::Statistical &stats, const std::string &x){ cabecera(); int tam; long double res = 0; std::vector<long double> params = stats.get_params_value(); bool lineal = stats.get_lineal(); std::cout << "Introduce el " << x << " a calcular: "; std::cin >> tam; if(lineal){ for( int i = 0 ; i < params.size() ; ++i ){ res += params[i] * pow(tam, i); } } else{ res = params[0] + params[1] * pow(2, tam); } std::cout << std::endl << "Taradría " << (lineal?res*pow(10,-6)/(60*60):res*(pow(10, -6)/(3600*24))) << (lineal? " horas.":" años.") << std::endl; volver(); } int opciones_comb(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Algoritmo recursivo." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Algoritmo recursivo con tabla de valores." << std::endl; std::cout << "\t\e[33;1m[3]\e[0m - Algoritmo iterativo." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>3){ error("Opción no válida. Volviendo al menú..."); } }while(opcion<0 || opcion>3); return opcion; } int opciones_stats(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Mostrar coeficiente de determinación." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Mostrar ecuación de estimación." << std::endl; std::cout << "\t\e[33;1m[3]\e[0m - Mostrar gráfico generado." << std::endl; std::cout << "\t\e[33;1m[4]\e[0m - Estimar tiempos." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>4){ error("Opción no válida. Volviendo..."); } }while(opcion<0 || opcion>4); return opcion; } void menu_combinatoria(const int &type){ cabecera(); int mayor, menor, incremento, n_rpt, opcion; Clock timer; std::string dat_name, eps_name; uint64_t aux_timer1, aux_timer2; al::Statistical stats(true); std::cout << "Introduce el menor número a calcular: "; std::cin >> menor; std::cout << "Introduce el mayor número a calcular: "; std::cin >> mayor; std::cout << "Introduce el incremento: "; std::cin >> incremento; std::cout << "Veces a repetir: "; std::cin >> n_rpt; if(menor > mayor){ menor += mayor; mayor = menor - mayor; menor -= mayor; } if(incremento > (mayor-menor)){ std::cerr << "\e[1;31m[Error]\e[m. The increment mustn't be higher than the upper number minus the lower number." << std::endl; exit(1); } std::cout << std::endl << "Procesando..." << std::endl; for( int i = menor ; i <= mayor ; i+=incremento ){ aux_timer1 = 0; for( int j = 0 ; j <= i ; ++j ){ aux_timer2 = 0; for( int k = 0 ; k < n_rpt ; ++k ){ long long res; std::vector<std::vector< long long > > v = std::vector<std::vector< long long > >(i, std::vector<long long>(j)); if(type == 2){ for( int z = 0 ; z < i ; ++z ){ for( int t = 0 ; t < j ; ++t ) v[z][t] = -1; } } timer.start(); switch (type){ case 1: res = combinatorio_recursivo(i, j); break; case 2: res = combinatorio_recursivo_2(i, j, v); break; case 3: res = combinatorio_iterativo(i, j); break; } timer.stop(); aux_timer2 += timer.elapsed(); } // t(i,0) + t(i,1) .. t(i,i) aux_timer1 += aux_timer2/n_rpt; } stats.add_test_size(i); // t(i) = (t(i,0) + t(i,1) .. t(i,i)) / (i+1) stats.add_elapsed_time(aux_timer1/(i+1)); } stats.estimate_times(4); switch (type){ case 1: dat_name = "comb_rec.dat"; eps_name = "comb_rec.eps"; break; case 2: dat_name = "comb_rec2.dat"; eps_name = "comb_rec2.eps"; break; case 3: dat_name = "comb_iter.dat"; eps_name = "comb_iter.eps"; break; } stats.dump_stats(dat_name.c_str()); bool salir = false; do{ opcion = opciones_stats(); switch (opcion){ case 0: salir = true; break; case 1: mostrar_determinacion(stats); break; case 2: mostrar_ecuacion(stats); break; case 3: mostrar_grafica(eps_name); break; case 4: estimar_tiempos(stats, "tamaño de combinatorio"); break; } }while(!salir); } void menu_combinatoria(){ int opcion; bool salir = false; do{ opcion = opciones_comb(); switch(opcion){ case 0: salir = true; break; default: menu_combinatoria(opcion); } }while(!salir); } int opciones_hanoi(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Cálculo de movimientos con n discos." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Representación gráfica." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>2){ error("Opción no válida. Volviendo al menú..."); } }while(opcion<0 || opcion>2); return opcion; } void calculo_hanoi(){ cabecera(); int tam, n_rpt, opcion; Clock timer; al::Statistical stats(false); uint64_t aux_timer; std::cout << "Introduce el tamaño máximo de discos a utilizar: "; std::cin >> tam; std::cout << "Veces a repetir: "; std::cin >> n_rpt; for(int i = 0 ; i < tam ; ++i){ aux_timer = 0; for (int j = 0; j < n_rpt ; ++j) { al::Hanoi h(i); timer.start(); h.solve_hanoi(); timer.stop(); aux_timer += timer.elapsed(); } stats.add_test_size(i); stats.add_elapsed_time(aux_timer/n_rpt); } stats.estimate_times(2); stats.dump_stats("hanoi.dat"); bool salir = false; do{ opcion = opciones_stats(); switch (opcion){ case 0: salir = true; break; case 1: mostrar_determinacion(stats); break; case 2: mostrar_ecuacion(stats); break; case 3: mostrar_grafica("hanoi.eps"); break; case 4: estimar_tiempos(stats, "número de discos de hanoi"); break; } }while(!salir); } void hanoi_grafico(){ cabecera(); int tam; std::cout << "Introduce el número de discos (entre 1 y 8): "; std::cin >> tam; al::Hanoi h(tam); cls(); std::cout << std::endl << std::endl << h << std::endl << "Estado inicial, pulsa ENTER para continuar";; std::cin.ignore(); std::cin.ignore(); usleep(500000); h.solve_hanoi(true); std::cout << std::endl << "Hanoi resuelto en " << h.get_moves() << " movimientos." << std::endl; volver(1); } void menu_hanoi(){ int opcion; bool salir = false; do{ opcion = opciones_hanoi(); switch(opcion){ case 1: calculo_hanoi(); break; case 2: hanoi_grafico(); break; case 3: break; case 0: salir = true; break; } }while(!salir); } #endif
i32ropie/Algoritmica
p2/main.hpp
C++
gpl-3.0
13,742
[ 30522, 1001, 2065, 13629, 2546, 1035, 1035, 2364, 1035, 6522, 2361, 1035, 1035, 1001, 9375, 1035, 1035, 2364, 1035, 6522, 2361, 1035, 1035, 1001, 2421, 1026, 16380, 25379, 1028, 1001, 2421, 1026, 4895, 2923, 2094, 1012, 1044, 1028, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>One minute tutorial</title> <link rel="stylesheet" href="../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../index.html" title="Chapter&#160;1.&#160;Boost.Bimap"> <link rel="up" href="../index.html" title="Chapter&#160;1.&#160;Boost.Bimap"> <link rel="prev" href="introduction.html" title="Introduction"> <link rel="next" href="the_tutorial.html" title="The tutorial"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="introduction.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="the_tutorial.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="boost_bimap.one_minute_tutorial"></a><a class="link" href="one_minute_tutorial.html" title="One minute tutorial">One minute tutorial</a> </h2></div></div></div> <a name="boost_bimap.one_minute_tutorial.what_is_a_bimap_"></a><h4> <a name="id769586"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.what_is_a_bimap_">What is a bimap?</a> </h4> <p> A Bimap is a data structure that represents bidirectional relations between elements of two collections. The container is designed to work as two opposed STL maps. A bimap between a collection <code class="computeroutput"><span class="identifier">X</span></code> and a collection <code class="computeroutput"><span class="identifier">Y</span></code> can be viewed as a map from <code class="computeroutput"><span class="identifier">X</span></code> to <code class="computeroutput"><span class="identifier">Y</span></code> (this view will be called the <span class="emphasis"><em>left map view</em></span>) or as a map from <code class="computeroutput"><span class="identifier">Y</span></code> to <code class="computeroutput"><span class="identifier">X</span></code> (known as the <span class="emphasis"><em>right map view</em></span>). Additionally, the bimap can also be viewed as a set of relations between <code class="computeroutput"><span class="identifier">X</span></code> and <code class="computeroutput"><span class="identifier">Y</span></code> (named the <span class="emphasis"><em>collection of relations view</em></span>). </p> <p> The following code creates an empty bimap container: </p> <pre class="programlisting"><span class="keyword">typedef</span> <span class="identifier">bimap</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;</span> <span class="identifier">bm_type</span><span class="special">;</span> <span class="identifier">bm_type</span> <span class="identifier">bm</span><span class="special">;</span> </pre> <p> Given this code, the following is the complete description of the resulting bimap. <sup>[<a name="id769748" href="#ftn.id769748" class="footnote">1</a>]</sup> </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"> <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span></code> is signature-compatible with <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;</span></code> </li> <li class="listitem"> <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span></code> is signature-compatible with <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span><span class="identifier">Y</span><span class="special">,</span><span class="identifier">X</span><span class="special">&gt;</span></code> </li> <li class="listitem"> <code class="computeroutput"><span class="identifier">bm</span></code> is signature-compatible with <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">set</span><span class="special">&lt;</span> <span class="identifier">relation</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;</span> <span class="special">&gt;</span></code> </li> </ul></div> <p> <span class="inlinemediaobject"><img src="../images/bimap/simple.bimap.png" alt="simple.bimap"></span> </p> <p> You can see how a bimap container offers three views over the same collection of bidirectional relations. </p> <p> If we have any generic function that work with maps </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">class</span> <span class="identifier">MapType</span> <span class="special">&gt;</span> <span class="keyword">void</span> <span class="identifier">print_map</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">MapType</span> <span class="special">&amp;</span> <span class="identifier">m</span><span class="special">)</span> <span class="special">{</span> <span class="keyword">typedef</span> <span class="keyword">typename</span> <span class="identifier">MapType</span><span class="special">::</span><span class="identifier">const_iterator</span> <span class="identifier">const_iterator</span><span class="special">;</span> <span class="keyword">for</span><span class="special">(</span> <span class="identifier">const_iterator</span> <span class="identifier">iter</span> <span class="special">=</span> <span class="identifier">m</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">iend</span> <span class="special">=</span> <span class="identifier">m</span><span class="special">.</span><span class="identifier">end</span><span class="special">();</span> <span class="identifier">iter</span> <span class="special">!=</span> <span class="identifier">iend</span><span class="special">;</span> <span class="special">++</span><span class="identifier">iter</span> <span class="special">)</span> <span class="special">{</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">iter</span><span class="special">-&gt;</span><span class="identifier">first</span> <span class="special">&lt;&lt;</span> <span class="string">"--&gt;"</span> <span class="special">&lt;&lt;</span> <span class="identifier">iter</span><span class="special">-&gt;</span><span class="identifier">second</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> <span class="special">}</span> </pre> <p> We can use the <span class="emphasis"><em>left map view</em></span> and the <span class="emphasis"><em>right map view</em></span> with it </p> <pre class="programlisting"><span class="identifier">bimap</span><span class="special">&lt;</span> <span class="keyword">int</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="special">&gt;</span> <span class="identifier">bm</span><span class="special">;</span> <span class="special">...</span> <span class="identifier">print_map</span><span class="special">(</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span> <span class="special">);</span> <span class="identifier">print_map</span><span class="special">(</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span> <span class="special">);</span> </pre> <p> And the output will be </p> <pre class="programlisting"><code class="literal">1 --&gt; one</code> <code class="literal">2 --&gt; two</code> ... <code class="literal">one --&gt; 1</code> <code class="literal">two --&gt; 2</code> ... </pre> <a name="boost_bimap.one_minute_tutorial.layout_of_the_relation_and_the_pairs_of_a_bimap"></a><h4> <a name="id770430"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.layout_of_the_relation_and_the_pairs_of_a_bimap">Layout of the relation and the pairs of a bimap</a> </h4> <p> The <code class="computeroutput"><span class="identifier">relation</span></code> class represents two related elements. The two values are named left and right to express the symmetry of this type. The bimap pair classes are signature-compatible with <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pairs</span></code>. </p> <p> <span class="inlinemediaobject"><img src="../images/bimap/relation.and.pair.png" alt="relation.and.pair"></span> </p> <a name="boost_bimap.one_minute_tutorial.step_by_step"></a><h4> <a name="id770497"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.step_by_step">Step by step</a> </h4> <p> A convinience header is avaiable in the boost directory: </p> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">bimap</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> </pre> <p> Lets define a bidirectional map between integers and strings: </p> <p> </p> <pre class="programlisting"><span class="keyword">typedef</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">bimap</span><span class="special">&lt;</span> <span class="keyword">int</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="special">&gt;</span> <span class="identifier">bm_type</span><span class="special">;</span> <span class="identifier">bm_type</span> <span class="identifier">bm</span><span class="special">;</span> </pre> <p> </p> <a name="boost_bimap.one_minute_tutorial.the_collection_of_relations_view"></a><h4> <a name="id770643"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.the_collection_of_relations_view">The collection of relations view</a> </h4> <p> Remember that <code class="computeroutput"><span class="identifier">bm</span></code> alone can be used as a set of relations. We can insert elements or iterate over them using this view. </p> <p> </p> <pre class="programlisting"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span><span class="number">1</span><span class="special">,</span> <span class="string">"one"</span> <span class="special">)</span> <span class="special">);</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span><span class="number">2</span><span class="special">,</span> <span class="string">"two"</span> <span class="special">)</span> <span class="special">);</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"There are "</span> <span class="special">&lt;&lt;</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">size</span><span class="special">()</span> <span class="special">&lt;&lt;</span> <span class="string">"relations"</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="keyword">for</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">const_iterator</span> <span class="identifier">iter</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">iend</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">end</span><span class="special">();</span> <span class="identifier">iter</span> <span class="special">!=</span> <span class="identifier">iend</span><span class="special">;</span> <span class="special">++</span><span class="identifier">iter</span> <span class="special">)</span> <span class="special">{</span> <span class="comment">// iter-&gt;left : data : int </span> <span class="comment">// iter-&gt;right : data : std::string </span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">iter</span><span class="special">-&gt;</span><span class="identifier">left</span> <span class="special">&lt;&lt;</span> <span class="string">" &lt;--&gt; "</span> <span class="special">&lt;&lt;</span> <span class="identifier">iter</span><span class="special">-&gt;</span><span class="identifier">right</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> </pre> <p> </p> <a name="boost_bimap.one_minute_tutorial.the_left_map_view"></a><h4> <a name="id771089"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.the_left_map_view">The left map view</a> </h4> <p> <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span></code> works like a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span> <span class="keyword">int</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="special">&gt;</span></code>. We use it in the same way we will use a standard map. </p> <p> </p> <pre class="programlisting"><a class="co" name="boost_bimap0co" href="one_minute_tutorial.html#boost_bimap0"><img src="../../../../../doc/src/images/callouts/1.png" alt="1" border="0"></a><span class="keyword">typedef</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_map</span><span class="special">::</span><span class="identifier">const_iterator</span> <span class="identifier">left_const_iterator</span><span class="special">;</span> <span class="keyword">for</span><span class="special">(</span> <span class="identifier">left_const_iterator</span> <span class="identifier">left_iter</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">iend</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span><span class="special">.</span><span class="identifier">end</span><span class="special">();</span> <span class="identifier">left_iter</span> <span class="special">!=</span> <span class="identifier">iend</span><span class="special">;</span> <span class="special">++</span><span class="identifier">left_iter</span> <span class="special">)</span> <span class="special">{</span> <span class="comment">// left_iter-&gt;first : key : int </span> <span class="comment">// left_iter-&gt;second : data : std::string </span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">left_iter</span><span class="special">-&gt;</span><span class="identifier">first</span> <span class="special">&lt;&lt;</span> <span class="string">" --&gt; "</span> <span class="special">&lt;&lt;</span> <span class="identifier">left_iter</span><span class="special">-&gt;</span><span class="identifier">second</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> <a class="co" name="boost_bimap1co" href="one_minute_tutorial.html#boost_bimap1"><img src="../../../../../doc/src/images/callouts/2.png" alt="2" border="0"></a><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_const_iterator</span> <span class="identifier">left_iter</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span><span class="special">.</span><span class="identifier">find</span><span class="special">(</span><span class="number">2</span><span class="special">);</span> <span class="identifier">assert</span><span class="special">(</span> <span class="identifier">left_iter</span><span class="special">-&gt;</span><span class="identifier">second</span> <span class="special">==</span> <span class="string">"two"</span> <span class="special">);</span> <a class="co" name="boost_bimap2co" href="one_minute_tutorial.html#boost_bimap2"><img src="../../../../../doc/src/images/callouts/3.png" alt="3" border="0"></a><span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_value_type</span><span class="special">(</span> <span class="number">3</span><span class="special">,</span> <span class="string">"three"</span> <span class="special">)</span> <span class="special">);</span> </pre> <p> </p> <div class="calloutlist"><table border="0" summary="Callout list"> <tr> <td width="5%" valign="top" align="left"><p><a name="boost_bimap0"></a><a href="#boost_bimap0co"><img src="../../../../../doc/src/images/callouts/1.png" alt="1" border="0"></a> </p></td> <td valign="top" align="left"><p> The type of <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span></code> is <code class="computeroutput"><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_map</span></code> and the type of <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span></code> is <code class="computeroutput"><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">right_map</span></code> </p></td> </tr> <tr> <td width="5%" valign="top" align="left"><p><a name="boost_bimap1"></a><a href="#boost_bimap1co"><img src="../../../../../doc/src/images/callouts/2.png" alt="2" border="0"></a> </p></td> <td valign="top" align="left"><p> <code class="computeroutput"><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_</span></code>-type- can be used as a shortcut for the more verbose <code class="computeroutput"><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">left_map</span><span class="special">::</span></code>-type- </p></td> </tr> <tr> <td width="5%" valign="top" align="left"><p><a name="boost_bimap2"></a><a href="#boost_bimap2co"><img src="../../../../../doc/src/images/callouts/3.png" alt="3" border="0"></a> </p></td> <td valign="top" align="left"><p> This line produces the same effect of <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span><span class="number">3</span><span class="special">,</span><span class="string">"three"</span><span class="special">)</span> <span class="special">);</span></code> </p></td> </tr> </table></div> <a name="boost_bimap.one_minute_tutorial.the_right_map_view"></a><h4> <a name="id771810"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.the_right_map_view">The right map view</a> </h4> <p> <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span></code> works like a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">,</span> <span class="keyword">int</span> <span class="special">&gt;</span></code>. It is important to note that the key is the first type and the data is the second one, exactly as with standard maps. </p> <p> </p> <pre class="programlisting"><span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">right_const_iterator</span> <span class="identifier">right_iter</span> <span class="special">=</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span><span class="special">.</span><span class="identifier">find</span><span class="special">(</span><span class="string">"two"</span><span class="special">);</span> <span class="comment">// right_iter-&gt;first : key : std::string </span><span class="comment">// right_iter-&gt;second : data : int </span> <span class="identifier">assert</span><span class="special">(</span> <span class="identifier">right_iter</span><span class="special">-&gt;</span><span class="identifier">second</span> <span class="special">==</span> <span class="number">2</span> <span class="special">);</span> <span class="identifier">assert</span><span class="special">(</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span><span class="special">.</span><span class="identifier">at</span><span class="special">(</span><span class="string">"one"</span><span class="special">)</span> <span class="special">==</span> <span class="number">1</span> <span class="special">);</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span><span class="special">.</span><span class="identifier">erase</span><span class="special">(</span><span class="string">"two"</span><span class="special">);</span> <a class="co" name="boost_bimap3co" href="one_minute_tutorial.html#boost_bimap3"><img src="../../../../../doc/src/images/callouts/1.png" alt="1" border="0"></a><span class="identifier">bm</span><span class="special">.</span><span class="identifier">right</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">right_value_type</span><span class="special">(</span> <span class="string">"four"</span><span class="special">,</span> <span class="number">4</span> <span class="special">)</span> <span class="special">);</span> </pre> <p> </p> <div class="calloutlist"><table border="0" summary="Callout list"><tr> <td width="5%" valign="top" align="left"><p><a name="boost_bimap3"></a><a href="#boost_bimap3co"><img src="../../../../../doc/src/images/callouts/1.png" alt="1" border="0"></a> </p></td> <td valign="top" align="left"><p> This line produces the same effect of <code class="computeroutput"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span><span class="number">4</span><span class="special">,</span><span class="string">"four"</span><span class="special">)</span> <span class="special">);</span></code> </p></td> </tr></table></div> <a name="boost_bimap.one_minute_tutorial.differences_with_std__map"></a><h4> <a name="id772245"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.differences_with_std__map">Differences with std::map</a> </h4> <p> The main difference between bimap views and their standard containers counterparts is that, because of the bidirectional nature of a bimap, the values stored in it can not be modified directly using iterators. For example, when a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;</span></code> iterator is dereferenced the return type is <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special">&lt;</span><span class="keyword">const</span> <span class="identifier">X</span><span class="special">,</span> <span class="identifier">Y</span><span class="special">&gt;</span></code>, so the following code is valid: <code class="computeroutput"><span class="identifier">m</span><span class="special">.</span><span class="identifier">begin</span><span class="special">()-&gt;</span><span class="identifier">second</span> <span class="special">=</span> <span class="identifier">new_value</span><span class="special">;</span></code>. However dereferencing a <code class="computeroutput"><span class="identifier">bimap</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;::</span><span class="identifier">left_iterator</span></code> returns a type that is <span class="emphasis"><em>signature-compatible</em></span> with a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special">&lt;</span><span class="keyword">const</span> <span class="identifier">X</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">Y</span><span class="special">&gt;</span></code> </p> <pre class="programlisting"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">left</span><span class="special">.</span><span class="identifier">find</span><span class="special">(</span><span class="number">1</span><span class="special">)-&gt;</span><span class="identifier">second</span> <span class="special">=</span> <span class="string">"1"</span><span class="special">;</span> <span class="comment">// Compilation error </span></pre> <p> If you insert <code class="computeroutput"><span class="special">(</span><span class="number">1</span><span class="special">,</span><span class="string">"one"</span><span class="special">)</span></code> and <code class="computeroutput"><span class="special">(</span><span class="number">1</span><span class="special">,</span><span class="string">"1"</span><span class="special">)</span></code> in a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">map</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">,</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">&gt;</span></code> the second insertion will have no effect. In a <code class="computeroutput"><span class="identifier">bimap</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">,</span><span class="identifier">Y</span><span class="special">&gt;</span></code> both keys have to remain unique. The insertion may fail in other situtions too. Lets see an example </p> <pre class="programlisting"><span class="identifier">bm</span><span class="special">.</span><span class="identifier">clear</span><span class="special">();</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span> <span class="number">1</span><span class="special">,</span> <span class="string">"one"</span> <span class="special">)</span> <span class="special">);</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span> <span class="number">1</span><span class="special">,</span> <span class="string">"1"</span> <span class="special">)</span> <span class="special">);</span> <span class="comment">// No effect! </span><span class="identifier">bm</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">bm_type</span><span class="special">::</span><span class="identifier">value_type</span><span class="special">(</span> <span class="number">2</span><span class="special">,</span> <span class="string">"one"</span> <span class="special">)</span> <span class="special">);</span> <span class="comment">// No effect! </span> <span class="identifier">assert</span><span class="special">(</span> <span class="identifier">bm</span><span class="special">.</span><span class="identifier">size</span><span class="special">()</span> <span class="special">==</span> <span class="number">1</span> <span class="special">);</span> </pre> <a name="boost_bimap.one_minute_tutorial.a_simple_example"></a><h4> <a name="id772905"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.a_simple_example">A simple example</a> </h4> <p> Look how you can reuse code that is intend to be used with std::maps, like the print_map function in this example. </p> <p> <a href="../../../example/simple_bimap.cpp" target="_top">Go to source code</a> </p> <p> </p> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">string</span><span class="special">&gt;</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">iostream</span><span class="special">&gt;</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">bimap</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">class</span> <span class="identifier">MapType</span> <span class="special">&gt;</span> <span class="keyword">void</span> <span class="identifier">print_map</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">MapType</span> <span class="special">&amp;</span> <span class="identifier">map</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="special">&amp;</span> <span class="identifier">separator</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">ostream</span> <span class="special">&amp;</span> <span class="identifier">os</span> <span class="special">)</span> <span class="special">{</span> <span class="keyword">typedef</span> <span class="keyword">typename</span> <span class="identifier">MapType</span><span class="special">::</span><span class="identifier">const_iterator</span> <span class="identifier">const_iterator</span><span class="special">;</span> <span class="keyword">for</span><span class="special">(</span> <span class="identifier">const_iterator</span> <span class="identifier">i</span> <span class="special">=</span> <span class="identifier">map</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">iend</span> <span class="special">=</span> <span class="identifier">map</span><span class="special">.</span><span class="identifier">end</span><span class="special">();</span> <span class="identifier">i</span> <span class="special">!=</span> <span class="identifier">iend</span><span class="special">;</span> <span class="special">++</span><span class="identifier">i</span> <span class="special">)</span> <span class="special">{</span> <span class="identifier">os</span> <span class="special">&lt;&lt;</span> <span class="identifier">i</span><span class="special">-&gt;</span><span class="identifier">first</span> <span class="special">&lt;&lt;</span> <span class="identifier">separator</span> <span class="special">&lt;&lt;</span> <span class="identifier">i</span><span class="special">-&gt;</span><span class="identifier">second</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> <span class="special">}</span> <span class="keyword">int</span> <span class="identifier">main</span><span class="special">()</span> <span class="special">{</span> <span class="comment">// Soccer World cup </span> <span class="keyword">typedef</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">bimap</span><span class="special">&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">,</span> <span class="keyword">int</span> <span class="special">&gt;</span> <span class="identifier">results_bimap</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">results_bimap</span><span class="special">::</span><span class="identifier">value_type</span> <span class="identifier">position</span><span class="special">;</span> <span class="identifier">results_bimap</span> <span class="identifier">results</span><span class="special">;</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">position</span><span class="special">(</span><span class="string">"Argentina"</span> <span class="special">,</span><span class="number">1</span><span class="special">)</span> <span class="special">);</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">position</span><span class="special">(</span><span class="string">"Spain"</span> <span class="special">,</span><span class="number">2</span><span class="special">)</span> <span class="special">);</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">position</span><span class="special">(</span><span class="string">"Germany"</span> <span class="special">,</span><span class="number">3</span><span class="special">)</span> <span class="special">);</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span> <span class="identifier">position</span><span class="special">(</span><span class="string">"France"</span> <span class="special">,</span><span class="number">4</span><span class="special">)</span> <span class="special">);</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"The number of countries is "</span> <span class="special">&lt;&lt;</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">size</span><span class="special">()</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"The winner is "</span> <span class="special">&lt;&lt;</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">right</span><span class="special">.</span><span class="identifier">at</span><span class="special">(</span><span class="number">1</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"Countries names ordered by their final position:"</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="comment">// results.right works like a std::map&lt; int, std::string &gt; </span> <span class="identifier">print_map</span><span class="special">(</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">right</span><span class="special">,</span> <span class="string">") "</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">);</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span> <span class="special">&lt;&lt;</span> <span class="string">"Countries names ordered alphabetically along with"</span> <span class="string">"their final position:"</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="comment">// results.left works like a std::map&lt; std::string, int &gt; </span> <span class="identifier">print_map</span><span class="special">(</span> <span class="identifier">results</span><span class="special">.</span><span class="identifier">left</span><span class="special">,</span> <span class="string">" ends in position "</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">);</span> <span class="keyword">return</span> <span class="number">0</span><span class="special">;</span> <span class="special">}</span> </pre> <p> </p> <p> The output of this program will be the following: </p> <pre class="programlisting"><code class="literal">The number of countries is 4</code> <code class="literal">The winner is Argentina</code> <code class="literal">Countries names ordered by their final position:</code> <code class="literal">1) Argentina</code> <code class="literal">2) Spain</code> <code class="literal">3) Germany</code> <code class="literal">4) France</code> <code class="literal">Countries names ordered alphabetically along with their final position:</code> <code class="literal">Argentina ends in position 1</code> <code class="literal">France ends in position 4</code> <code class="literal">Germany ends in position 3</code> <code class="literal">Spain ends in position 2</code> </pre> <a name="boost_bimap.one_minute_tutorial.continuing_the_journey"></a><h4> <a name="id774177"></a> <a class="link" href="one_minute_tutorial.html#boost_bimap.one_minute_tutorial.continuing_the_journey">Continuing the journey</a> </h4> <p> For information on function signatures, see any standard library documentation or read the <a class="link" href="reference.html" title="Reference">reference</a> section of this documentation. </p> <div class="caution"><table border="0" summary="Caution"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Caution]" src="../../../../../doc/src/images/caution.png"></td> <th align="left">Caution</th> </tr> <tr><td align="left" valign="top"><p> Be aware that a bidirectional map is only signature-compatible with standard containers. Some functions may give different results, such as in the case of inserting a pair into the left map where the second value conflicts with a stored relation in the container. The functions may be slower in a bimap because of the duplicated constraints. It is strongly recommended that you read <a class="link" href="the_tutorial.html" title="The tutorial">The full tutorial</a> if you intend to use a bimap in a serious project. </p></td></tr> </table></div> <div class="footnotes"> <br><hr width="100" align="left"> <div class="footnote"><p><sup>[<a id="ftn.id769748" href="#id769748" class="para">1</a>] </sup> A type is <span class="emphasis"><em>signature-compatible</em></span> with other type if it has the same signature for functions and metadata. Preconditions, postconditions and the order of operations need not be the same. </p></div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2006 -2007 Matias Capeletto<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="introduction.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="the_tutorial.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
djsedulous/namecoind
libs/boost_1_50_0/libs/bimap/doc/html/boost_bimap/one_minute_tutorial.html
HTML
mit
45,884
[ 30522, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 1027, 1000, 4180, 1011, 2828, 1000, 4180, 1027, 1000, 3793, 1013, 16129, 1025, 25869, 13462, 1027, 2149, 1011, 2004, 6895, 2072, 1000, 1028, 1026, 2516,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { var item = $($(this).attr("href")); if (item.length) { return item; } }); //Get width of container var containerWidth = $('.section .container').width(); //Resize animated triangle $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); //resize $(window).resize(function () { containerWidth = $('.container').width(); $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); }); //mask $('.has-mask').each( function() { var $this = $( this ), mask = $this.data( 'aria-mask' ); $this.mask( mask ); }); //Initialize header slider. $('#da-slider').cslider(); //Initial mixitup, used for animated filtering portgolio. $('#portfolio-grid').mixitup({ 'onMixStart': function (config) { $('div.toggleDiv').hide(); } }); //Initial Out clients slider in client section $('#clint-slider').bxSlider({ pager: false, minSlides: 1, maxSlides: 5, moveSlides: 2, slideWidth: 210, slideMargin: 25, prevSelector: $('#client-prev'), nextSelector: $('#client-next'), prevText: '<i class="icon-left-open"></i>', nextText: '<i class="icon-right-open"></i>' }); $('input, textarea').placeholder(); // Bind to scroll $(window).scroll(function () { //Display or hide scroll to top button if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } if ($(this).scrollTop() > 100) { $('.navbar').addClass('navbar-fixed-top animated fadeInDown'); } else { $('.navbar').removeClass('navbar-fixed-top animated fadeInDown'); } // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight + 10; // Get id of current scroll item var cur = scrollItems.map(function () { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href=#" + id + "]").parent().addClass("active"); } }); /* Function for scroliing to top ************************************/ $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 600); return false; }); /* Sand newsletter **********************************************************************/ $('#subscribe').click(function () { var error = false; var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-subscribe').show(500); $('#err-subscribe').delay(4000); $('#err-subscribe').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error === false) { $.ajax({ type: 'POST', url: 'php/newsletter.php', data: { email: $('#nlmail').val() }, error: function (request, error) { alert("An error occurred"); }, success: function (response) { if (response == 'OK') { $('#success-subscribe').show(); $('#nlmail').val('') } else { alert("An error occurred"); } } }); } return false; }); /* Sand mail **********************************************************************/ $("#send-mail").click(function () { var name = $('input#name').val(); // get the value of the input field var error = false; if (name == "" || name == " ") { $('#err-name').show(500); $('#err-name').delay(4000); $('#err-name').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#email').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-email').show(500); $('#err-email').delay(4000); $('#err-email').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var comment = $('textarea#comment').val(); // get the value of the input field if (comment == "" || comment == " ") { $('#err-comment').show(500); $('#err-comment').delay(4000); $('#err-comment').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error == false) { var dataString = $('#contact-form').serialize(); // Collect data from form $.ajax({ type: "POST", url: $('#contact-form').attr('action'), data: dataString, timeout: 6000, error: function (request, error) { }, success: function (response) { response = $.parseJSON(response); if (response.success) { $('#successSend').show(); $("#name").val(''); $("#email").val(''); $("#comment").val(''); } else { $('#errorSend').show(); } } }); return false; } return false; // stops user browser being directed to the php file }); //Function for show or hide portfolio desctiption. $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing); var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; //Initial Show/Hide portfolio element. $('div.toggleDiv').hide(); /************************ Animate elements *************************/ //Animate thumbnails jQuery('.thumbnail').one('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate triangles jQuery('.triangle').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //animate first team member jQuery('#first-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#first-person').addClass("animated pulse"); } else { jQuery('#first-person').removeClass("animated pulse"); } }); //animate sectond team member jQuery('#second-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#second-person').addClass("animated pulse"); } else { jQuery('#second-person').removeClass("animated pulse"); } }); //animate thrid team member jQuery('#third-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#third-person').addClass("animated pulse"); } else { jQuery('#third-person').removeClass("animated pulse"); } }); //Animate price columns jQuery('.price-column, .testimonial').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate contact form jQuery('.contact-form').bind('inview', function (event, visible) { if (visible == true) { jQuery('.contact-form').addClass("animated bounceIn"); } else { jQuery('.contact-form').removeClass("animated bounceIn"); } }); //Animate skill bars jQuery('.skills > li > span').one('inview', function (event, visible) { if (visible == true) { jQuery(this).each(function () { jQuery(this).animate({ width: jQuery(this).attr('data-width') }, 3000); }); } }); //initialize pluging $("a[rel^='prettyPhoto']").prettyPhoto(); //contact form function enviainfocurso() { $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); } //analytics (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-62932901-1', 'auto'); ga('send', 'pageview'); }); // end ready() $(window).load(function () { function filterPath(string) { return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, ''); } $('a[href*=#]').each(function () { if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) { var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { e.preventDefault(); //Hack collapse top navigation after clicking // topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation $('.navbar .btn-navbar').addClass('collapsed'); var targetOffset = $target.offset().top - 63; $('html, body').animate({ scrollTop: targetOffset }, 800); return false; }); } } }); }); //Initialize google map for contact setion with your location. function initializeMap() { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, disableDefaultUI: true, center: new google.maps.LatLng(lat, centerLon), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Bind map to elemet with id map-canvas var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lon), }); //var infowindow = new google.maps.InfoWindow(); //google.maps.event.addListener(marker, 'click', function () { // infowindow.open(map, marker); //}); // infowindow.open(map, marker); } }
SamuelRocha2015/ch-v3
assets/js/app.js
JavaScript
mit
14,062
[ 30522, 1005, 2224, 9384, 1005, 1025, 1046, 4226, 2854, 1006, 6254, 1007, 1012, 3201, 1006, 3853, 1006, 1002, 1007, 1063, 13075, 2197, 3593, 1010, 2327, 3549, 2226, 1027, 1002, 1006, 1000, 1001, 2327, 1011, 9163, 1000, 1007, 1010, 2327, 35...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package npanday.executable.compiler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import npanday.executable.ExecutionException; /** * Exception thrown when the framework either does not recognize the target artifact (module, library, exe, winexe) or * the target artifact is not valid for the compiler. * * @author Shane Isbell */ public class InvalidArtifactException extends ExecutionException { static final long serialVersionUID = -3214341783478731432L; /** * Constructs an <code>InvalidArtifactException</code> with no exception message. */ public InvalidArtifactException() { super(); } /** * Constructs an <code>InvalidArtifactException</code> with the specified exception message. * * @param message the exception message */ public InvalidArtifactException( String message ) { super( message ); } /** * Constructs an <code>InvalidArtifactException</code> with the specified exception message and cause of the exception. * * @param message the exception message * @param cause the cause of the exception */ public InvalidArtifactException( String message, Throwable cause ) { super( message, cause ); } /** * Constructs an <code>InvalidArtifactException</code> with the cause of the exception. * * @param cause the cause of the exception */ public InvalidArtifactException( Throwable cause ) { super( cause ); } }
apache/npanday
components/dotnet-executable/src/main/java/npanday/executable/compiler/InvalidArtifactException.java
Java
apache-2.0
2,278
[ 30522, 7427, 27937, 13832, 2100, 1012, 4654, 8586, 23056, 1012, 21624, 1025, 1013, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 1008, 2030, 2062, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 1008...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule View * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const NativeMethodsMixin = require('NativeMethodsMixin'); const NativeModules = require('NativeModules'); const Platform = require('Platform'); const React = require('React'); const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const ViewStylePropTypes = require('ViewStylePropTypes'); const invariant = require('fbjs/lib/invariant'); const { AccessibilityComponentTypes, AccessibilityTraits, } = require('ViewAccessibility'); var TVViewPropTypes = {}; if (Platform.isTVOS) { TVViewPropTypes = require('TVViewPropTypes'); } const requireNativeComponent = require('requireNativeComponent'); const PropTypes = React.PropTypes; const stylePropType = StyleSheetPropType(ViewStylePropTypes); const forceTouchAvailable = (NativeModules.IOSConstants && NativeModules.IOSConstants.forceTouchAvailable) || false; const statics = { AccessibilityTraits, AccessibilityComponentType: AccessibilityComponentTypes, /** * Is 3D Touch / Force Touch available (i.e. will touch events include `force`) * @platform ios */ forceTouchAvailable, }; /** * The most fundamental component for building a UI, `View` is a container that supports layout with * [flexbox](docs/flexbox.html), [style](docs/style.html), * [some touch handling](docs/handling-touches.html), and * [accessibility](docs/accessibility.html) controls. `View` maps directly to the * native view equivalent on whatever platform React Native is running on, whether that is a * `UIView`, `<div>`, `android.view`, etc. * * `View` is designed to be nested inside other views and can have 0 to many children of any type. * * This example creates a `View` that wraps two colored boxes and a text component in a row with * padding. * * ```javascript * class ViewColoredBoxesWithText extends Component { * render() { * return ( * <View style={{flexDirection: 'row', height: 100, padding: 20}}> * <View style={{backgroundColor: 'blue', flex: 0.3}} /> * <View style={{backgroundColor: 'red', flex: 0.5}} /> * <Text>Hello World!</Text> * </View> * ); * } * } * ``` * * > `View`s are designed to be used with [`StyleSheet`](docs/style.html) for clarity * > and performance, although inline styles are also supported. * * ### Synthetic Touch Events * * For `View` responder props (e.g., `onResponderMove`), the synthetic touch event passed to them * are of the following form: * * - `nativeEvent` * - `changedTouches` - Array of all touch events that have changed since the last event. * - `identifier` - The ID of the touch. * - `locationX` - The X position of the touch, relative to the element. * - `locationY` - The Y position of the touch, relative to the element. * - `pageX` - The X position of the touch, relative to the root element. * - `pageY` - The Y position of the touch, relative to the root element. * - `target` - The node id of the element receiving the touch event. * - `timestamp` - A time identifier for the touch, useful for velocity calculation. * - `touches` - Array of all current touches on the screen. */ const View = React.createClass({ // TODO: We should probably expose the mixins, viewConfig, and statics publicly. For example, // one of the props is of type AccessibilityComponentType. That is defined as a const[] above, // but it is not rendered by the docs, since `statics` below is not rendered. So its Possible // values had to be hardcoded. mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'RCTView', validAttributes: ReactNativeViewAttributes.RCTView }, statics: { ...statics, }, propTypes: { ...TVViewPropTypes, /** * When `true`, indicates that the view is an accessibility element. By default, * all the touchable elements are accessible. */ accessible: PropTypes.bool, /** * Overrides the text that's read by the screen reader when the user interacts * with the element. By default, the label is constructed by traversing all the * children and accumulating all the `Text` nodes separated by space. */ accessibilityLabel: PropTypes.node, /** * Indicates to accessibility services to treat UI component like a * native one. Works for Android only. * * Possible values are one of: * * - `'none'` * - `'button'` * - `'radiobutton_checked'` * - `'radiobutton_unchecked'` * * @platform android */ accessibilityComponentType: PropTypes.oneOf(AccessibilityComponentTypes), /** * Indicates to accessibility services whether the user should be notified * when this view changes. Works for Android API >= 19 only. * Possible values: * * - `'none'` - Accessibility services should not announce changes to this view. * - `'polite'`- Accessibility services should announce changes to this view. * - `'assertive'` - Accessibility services should interrupt ongoing speech to immediately announce changes to this view. * * See the [Android `View` docs](http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion) * for reference. * * @platform android */ accessibilityLiveRegion: PropTypes.oneOf([ 'none', 'polite', 'assertive', ]), /** * Controls how view is important for accessibility which is if it * fires accessibility events and if it is reported to accessibility services * that query the screen. Works for Android only. * * Possible values: * * - `'auto'` - The system determines whether the view is important for accessibility - * default (recommended). * - `'yes'` - The view is important for accessibility. * - `'no'` - The view is not important for accessibility. * - `'no-hide-descendants'` - The view is not important for accessibility, * nor are any of its descendant views. * * See the [Android `importantForAccessibility` docs](http://developer.android.com/reference/android/R.attr.html#importantForAccessibility) * for reference. * * @platform android */ importantForAccessibility: PropTypes.oneOf([ 'auto', 'yes', 'no', 'no-hide-descendants', ]), /** * Provides additional traits to screen reader. By default no traits are * provided unless specified otherwise in element. * * You can provide one trait or an array of many traits. * * Possible values for `AccessibilityTraits` are: * * - `'none'` - The element has no traits. * - `'button'` - The element should be treated as a button. * - `'link'` - The element should be treated as a link. * - `'header'` - The element is a header that divides content into sections. * - `'search'` - The element should be treated as a search field. * - `'image'` - The element should be treated as an image. * - `'selected'` - The element is selected. * - `'plays'` - The element plays sound. * - `'key'` - The element should be treated like a keyboard key. * - `'text'` - The element should be treated as text. * - `'summary'` - The element provides app summary information. * - `'disabled'` - The element is disabled. * - `'frequentUpdates'` - The element frequently changes its value. * - `'startsMedia'` - The element starts a media session. * - `'adjustable'` - The element allows adjustment over a range of values. * - `'allowsDirectInteraction'` - The element allows direct touch interaction for VoiceOver users. * - `'pageTurn'` - Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element. * * See the [Accessibility guide](docs/accessibility.html#accessibilitytraits-ios) * for more information. * * @platform ios */ accessibilityTraits: PropTypes.oneOfType([ PropTypes.oneOf(AccessibilityTraits), PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)), ]), /** * When `accessible` is true, the system will try to invoke this function * when the user performs accessibility tap gesture. */ onAccessibilityTap: PropTypes.func, /** * When `accessible` is `true`, the system will invoke this function when the * user performs the magic tap gesture. */ onMagicTap: PropTypes.func, /** * Used to locate this view in end-to-end tests. * * > This disables the 'layout-only view removal' optimization for this view! */ testID: PropTypes.string, /** * For most touch interactions, you'll simply want to wrap your component in * `TouchableHighlight` or `TouchableOpacity`. Check out `Touchable.js`, * `ScrollResponder.js` and `ResponderEventPlugin.js` for more discussion. */ /** * The View is now responding for touch events. This is the time to highlight and show the user * what is happening. * * `View.props.onResponderGrant: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderGrant: PropTypes.func, /** * The user is moving their finger. * * `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderMove: PropTypes.func, /** * Another responder is already active and will not release it to that `View` asking to be * the responder. * * `View.props.onResponderReject: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderReject: PropTypes.func, /** * Fired at the end of the touch. * * `View.props.onResponderRelease: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderRelease: PropTypes.func, /** * The responder has been taken from the `View`. Might be taken by other views after a call to * `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens * with control center/ notification center on iOS) * * `View.props.onResponderTerminate: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderTerminate: PropTypes.func, /** * Some other `View` wants to become responder and is asking this `View` to release its * responder. Returning `true` allows its release. * * `View.props.onResponderTerminationRequest: (event) => {}`, where `event` is a synthetic touch * event as described above. */ onResponderTerminationRequest: PropTypes.func, /** * Does this view want to become responder on the start of a touch? * * `View.props.onStartShouldSetResponder: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onStartShouldSetResponder: PropTypes.func, /** * If a parent `View` wants to prevent a child `View` from becoming responder on a touch start, * it should have this handler which returns `true`. * * `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onStartShouldSetResponderCapture: PropTypes.func, /** * Does this view want to "claim" touch responsiveness? This is called for every touch move on * the `View` when it is not the responder. * * `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onMoveShouldSetResponder: PropTypes.func, /** * If a parent `View` wants to prevent a child `View` from becoming responder on a move, * it should have this handler which returns `true`. * * `View.props.onMoveShouldSetResponderCapture: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onMoveShouldSetResponderCapture: PropTypes.func, /** * This defines how far a touch event can start away from the view. * Typical interface guidelines recommend touch targets that are at least * 30 - 40 points/density-independent pixels. * * For example, if a touchable view has a height of 20 the touchable height can be extended to * 40 with `hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}` * * > The touch area never extends past the parent view bounds and the Z-index * > of sibling views always takes precedence if a touch hits two overlapping * > views. */ hitSlop: EdgeInsetsPropType, /** * Invoked on mount and layout changes with: * * `{nativeEvent: { layout: {x, y, width, height}}}` * * This event is fired immediately once the layout has been calculated, but * the new layout may not yet be reflected on the screen at the time the * event is received, especially if a layout animation is in progress. */ onLayout: PropTypes.func, /** * Controls whether the `View` can be the target of touch events. * * - `'auto'`: The View can be the target of touch events. * - `'none'`: The View is never the target of touch events. * - `'box-none'`: The View is never the target of touch events but it's * subviews can be. It behaves like if the view had the following classes * in CSS: * ``` * .box-none { * pointer-events: none; * } * .box-none * { * pointer-events: all; * } * ``` * - `'box-only'`: The view can be the target of touch events but it's * subviews cannot be. It behaves like if the view had the following classes * in CSS: * ``` * .box-only { * pointer-events: all; * } * .box-only * { * pointer-events: none; * } * ``` * > Since `pointerEvents` does not affect layout/appearance, and we are * > already deviating from the spec by adding additional modes, we opt to not * > include `pointerEvents` on `style`. On some platforms, we would need to * > implement it as a `className` anyways. Using `style` or not is an * > implementation detail of the platform. */ pointerEvents: PropTypes.oneOf([ 'box-none', 'none', 'box-only', 'auto', ]), style: stylePropType, /** * This is a special performance property exposed by `RCTView` and is useful * for scrolling content when there are many subviews, most of which are * offscreen. For this property to be effective, it must be applied to a * view that contains many subviews that extend outside its bound. The * subviews must also have `overflow: hidden`, as should the containing view * (or one of its superviews). */ removeClippedSubviews: PropTypes.bool, /** * Whether this `View` should render itself (and all of its children) into a * single hardware texture on the GPU. * * On Android, this is useful for animations and interactions that only * modify opacity, rotation, translation, and/or scale: in those cases, the * view doesn't have to be redrawn and display lists don't need to be * re-executed. The texture can just be re-used and re-composited with * different parameters. The downside is that this can use up limited video * memory, so this prop should be set back to false at the end of the * interaction/animation. * * @platform android */ renderToHardwareTextureAndroid: PropTypes.bool, /** * Whether this `View` should be rendered as a bitmap before compositing. * * On iOS, this is useful for animations and interactions that do not * modify this component's dimensions nor its children; for example, when * translating the position of a static view, rasterization allows the * renderer to reuse a cached bitmap of a static view and quickly composite * it during each frame. * * Rasterization incurs an off-screen drawing pass and the bitmap consumes * memory. Test and measure when using this property. * * @platform ios */ shouldRasterizeIOS: PropTypes.bool, /** * Views that are only used to layout their children or otherwise don't draw * anything may be automatically removed from the native hierarchy as an * optimization. Set this property to `false` to disable this optimization and * ensure that this `View` exists in the native view hierarchy. * * @platform android */ collapsable: PropTypes.bool, /** * Whether this `View` needs to rendered offscreen and composited with an alpha * in order to preserve 100% correct colors and blending behavior. The default * (`false`) falls back to drawing the component and its children with an alpha * applied to the paint used to draw each element instead of rendering the full * component offscreen and compositing it back with an alpha value. This default * may be noticeable and undesired in the case where the `View` you are setting * an opacity on has multiple overlapping elements (e.g. multiple overlapping * `View`s, or text and a background). * * Rendering offscreen to preserve correct alpha behavior is extremely * expensive and hard to debug for non-native developers, which is why it is * not turned on by default. If you do need to enable this property for an * animation, consider combining it with renderToHardwareTextureAndroid if the * view **contents** are static (i.e. it doesn't need to be redrawn each frame). * If that property is enabled, this View will be rendered off-screen once, * saved in a hardware texture, and then composited onto the screen with an alpha * each frame without having to switch rendering targets on the GPU. * * @platform android */ needsOffscreenAlphaCompositing: PropTypes.bool, }, contextTypes: { isInAParentText: React.PropTypes.bool, }, render: function() { invariant( !(this.context.isInAParentText && Platform.OS === 'android'), 'Nesting of <View> within <Text> is not supported on Android.'); // WARNING: This method will not be used in production mode as in that mode we // replace wrapper component View with generated native wrapper RCTView. Avoid // adding functionality this component that you'd want to be available in both // dev and prod modes. return <RCTView {...this.props} />; }, }); const RCTView = requireNativeComponent('RCTView', View, { nativeOnly: { nativeBackgroundAndroid: true, nativeForegroundAndroid: true, } }); if (__DEV__) { const UIManager = require('UIManager'); const viewConfig = UIManager.viewConfigs && UIManager.viewConfigs.RCTView || {}; for (const prop in viewConfig.nativeProps) { const viewAny: any = View; // Appease flow if (!viewAny.propTypes[prop] && !ReactNativeStyleAttributes[prop]) { throw new Error( 'View is missing propType for native prop `' + prop + '`' ); } } } let ViewToExport = RCTView; if (__DEV__) { ViewToExport = View; } else { Object.assign(RCTView, statics); } module.exports = ViewToExport;
htc2u/react-native
Libraries/Components/View/View.js
JavaScript
bsd-3-clause
20,196
[ 30522, 1013, 1008, 1008, 1008, 9385, 1006, 1039, 1007, 2325, 1011, 2556, 1010, 9130, 1010, 4297, 1012, 1008, 2035, 2916, 9235, 1012, 1008, 1008, 2023, 3120, 3642, 2003, 7000, 2104, 1996, 18667, 2094, 1011, 2806, 6105, 2179, 1999, 1996, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package PACMethod_remote_tty; ################################################################## # This file is part of PAC( Perl Auto Connector) # # Copyright (C) 2010-2014 David Torrejon Vaquerizas # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ################################################################### $|++; ################################################################### # Import Modules # Standard use strict; use warnings; use FindBin qw ( $RealBin $Bin $Script ); #use Data::Dumper; # GTK2 use Gtk2 '-init'; # END: Import Modules ################################################################### ################################################################### # Define GLOBAL CLASS variables my $RES_DIR = $RealBin . '/res'; # END: Define GLOBAL CLASS variables ################################################################### ################################################################### # START: Public class methods sub new { my $class = shift; my $self = {}; $self -> {container} = shift; $self -> {cfg} = undef; $self -> {gui} = undef; $self -> {frame} = {}; _buildGUI( $self ); bless( $self, $class ); return $self; } sub update { my $self = shift; my $cfg = shift; defined $cfg and $$self{cfg} = $cfg; my $options = _parseCfgToOptions( $$self{cfg} ); $$self{gui}{chRestricted} -> set_active( $$options{'restricted'} ); $$self{gui}{ch7Bit} -> set_active( $$options{'7Bit'} ); return 1; } sub get_cfg { my $self = shift; my %options; $options{'restricted'} = $$self{gui}{chRestricted} -> get_active; $options{'7Bit'} = $$self{gui}{ch7Bit} -> get_active; return _parseOptionsToCfg( \%options ); } # END: Public class methods ################################################################### ################################################################### # START: Private functions definitions sub _parseCfgToOptions { my $cmd_line = shift; my %hash; $hash{passive} = 0; $hash{noInteractive} = 0; my @opts = split( '-', $cmd_line ); foreach my $opt ( @opts ) { next unless $opt ne ''; $opt =~ s/\s+$//go; $opt eq 'r' and $hash{restricted} = 1; $opt eq '7' and $hash{'7Bit'} = 1; } return \%hash; } sub _parseOptionsToCfg { my $hash = shift; my $txt = ''; $txt .= ' -r' if $$hash{restricted} ; $txt .= ' -7' if $$hash{'7Bit'} ; return $txt; } sub embed { my $self = shift; return 0; } sub _buildGUI { my $self = shift; my $container = $self -> {container}; my $cfg = $self -> {cfg}; my %w; $w{vbox} = $container; $w{chRestricted} = Gtk2::CheckButton -> new_with_label( 'Set restricted mode' ); $w{vbox} -> pack_start( $w{chRestricted}, 0, 1, 0 ); $w{chRestricted} -> set_tooltip_text( "[-r] : Don't allow changing of logging status, suspending of remote-tty or setting of line options" ); $w{ch7Bit} = Gtk2::CheckButton -> new_with_label( 'Set 7bit mode' ); $w{vbox} -> pack_start( $w{ch7Bit}, 0, 1, 0 ); $w{ch7Bit} -> set_tooltip_text( '[-7] : Set 7bit connection mode' ); $$self{gui} = \%w; return 1; } # END: Private functions definitions ################################################################### 1;
CharellKing/pac
lib/method/PACMethod_remote_tty.pm
Perl
gpl-3.0
3,805
[ 30522, 7427, 14397, 11368, 6806, 2094, 1035, 6556, 1035, 23746, 2100, 1025, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 30524, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- # # MAVProxy documentation build configuration file, created by # sphinx-quickstart on Wed Aug 19 05:17:36 2015. # # 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 import shlex # 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('.')) # -- 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.todo', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] 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'last_letter' copyright = u'2014, George Zogopoulos - Papaliakos' author = u'George Zogopoulos - Papaliakos' # 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 = '0.5' # The full version, including alpha/beta/rc tags. release = '0.5' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. 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 = [] # 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 # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- 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 = 'sphinx_rtd_theme' # 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 = ["_static/themes", ] # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # 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 = False # If false, no index is generated. html_use_index = False # 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 = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = False # 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 # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'last_letter_doc' # -- 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': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'last_letter.tex', u'last_letter Documentation', u'George Zogopoulos - Papaliakos', '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 = [ (master_doc, 'last_letter', u'last_letter Documentation', [author], 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 = [ (master_doc, 'last_letter', u'last_letter Documentation', author, 'last_letter', 'A collection of ROS packages for UAV simulation and autopilot development.', '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 # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. #epub_basename = project # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the Pillow. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True
Georacer/last_letter
documentation/source/conf.py
Python
gpl-3.0
11,461
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 1001, 5003, 2615, 21572, 18037, 12653, 3857, 30524, 1012, 1001, 1001, 2023, 5371, 2003, 4654, 8586, 8873, 2571, 1006, 1007, 1040, 2007, 1996, 2783,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" #ifdef GRPC_WINSOCK_SOCKET #include "src/core/lib/iomgr/sockaddr_windows.h" #include <grpc/support/log.h> #include "src/core/lib/iomgr/iocp_windows.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/pollset_windows.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/socket_windows.h" #include "src/core/lib/iomgr/tcp_client.h" #include "src/core/lib/iomgr/tcp_server.h" #include "src/core/lib/iomgr/timer.h" extern grpc_tcp_server_vtable grpc_windows_tcp_server_vtable; extern grpc_tcp_client_vtable grpc_windows_tcp_client_vtable; extern grpc_timer_vtable grpc_generic_timer_vtable; extern grpc_pollset_vtable grpc_windows_pollset_vtable; extern grpc_pollset_set_vtable grpc_windows_pollset_set_vtable; extern grpc_address_resolver_vtable grpc_windows_resolver_vtable; /* Windows' io manager is going to be fully designed using IO completion ports. All of what we're doing here is basically make sure that Windows sockets are initialized in and out. */ static void winsock_init(void) { WSADATA wsaData; int status = WSAStartup(MAKEWORD(2, 0), &wsaData); GPR_ASSERT(status == 0); } static void winsock_shutdown(void) { int status = WSACleanup(); GPR_ASSERT(status == 0); } static void iomgr_platform_init(void) { winsock_init(); grpc_iocp_init(); grpc_pollset_global_init(); } static void iomgr_platform_flush(void) { grpc_iocp_flush(); } static void iomgr_platform_shutdown(void) { grpc_pollset_global_shutdown(); grpc_iocp_shutdown(); winsock_shutdown(); } static void iomgr_platform_shutdown_background_closure(void) {} static bool iomgr_platform_is_any_background_poller_thread(void) { return false; } static grpc_iomgr_platform_vtable vtable = { iomgr_platform_init, iomgr_platform_flush, iomgr_platform_shutdown, iomgr_platform_shutdown_background_closure, iomgr_platform_is_any_background_poller_thread}; void grpc_set_default_iomgr_platform() { grpc_set_tcp_client_impl(&grpc_windows_tcp_client_vtable); grpc_set_tcp_server_impl(&grpc_windows_tcp_server_vtable); grpc_set_timer_impl(&grpc_generic_timer_vtable); grpc_set_pollset_vtable(&grpc_windows_pollset_vtable); grpc_set_pollset_set_vtable(&grpc_windows_pollset_set_vtable); grpc_set_resolver_impl(&grpc_windows_resolver_vtable); grpc_set_iomgr_platform_vtable(&vtable); } bool grpc_iomgr_run_in_background() { return false; } #endif /* GRPC_WINSOCK_SOCKET */
carl-mastrangelo/grpc
src/core/lib/iomgr/iomgr_windows.cc
C++
apache-2.0
3,126
[ 30522, 1013, 1008, 1008, 1008, 9385, 2325, 24665, 15042, 6048, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * CharArrayUnserializer.java * * * * char array unserializer class for Java. * * * * LastModified: Aug 3, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package hprose.io.unserialize; import static hprose.io.HproseTags.TagEmpty; import static hprose.io.HproseTags.TagList; import static hprose.io.HproseTags.TagString; import static hprose.io.HproseTags.TagUTF8Char; import java.io.IOException; import java.lang.reflect.Type; public final class CharArrayUnserializer extends BaseUnserializer<char[]> { public final static CharArrayUnserializer instance = new CharArrayUnserializer(); @Override public char[] unserialize(Reader reader, int tag, Type type) throws IOException { switch (tag) { case TagEmpty: return new char[0]; case TagUTF8Char: return new char[] { ValueReader.readChar(reader) }; case TagList: return ReferenceReader.readCharArray(reader); case TagString: return ReferenceReader.readChars(reader); } return super.unserialize(reader, tag, type); } public char[] read(Reader reader) throws IOException { return read(reader, char[].class); } }
hprose/hprose-java
src/main/java/hprose/io/unserialize/CharArrayUnserializer.java
Java
mit
2,104
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/python """ Program that parses standard format results, compute and check regression bug. :copyright: Red Hat 2011-2012 :author: Amos Kong <akong@redhat.com> """ import os import sys import re import commands import warnings import ConfigParser import MySQLdb def exec_sql(cmd, conf="../../global_config.ini"): config = ConfigParser.ConfigParser() config.read(conf) user = config.get("AUTOTEST_WEB", "user") passwd = config.get("AUTOTEST_WEB", "password") db = config.get("AUTOTEST_WEB", "database") db_type = config.get("AUTOTEST_WEB", "db_type") if db_type != 'mysql': print "regression.py: only support mysql database!" sys.exit(1) conn = MySQLdb.connect(host="localhost", user=user, passwd=passwd, db=db) cursor = conn.cursor() cursor.execute(cmd) rows = cursor.fetchall() lines = [] for row in rows: line = [] for c in row: line.append(str(c)) lines.append(" ".join(line)) cursor.close() conn.close() return lines def get_test_keyval(jobid, keyname, default=''): idx = exec_sql("select job_idx from tko_jobs where afe_job_id=%s" % jobid)[-1] test_idx = exec_sql('select test_idx from tko_tests where job_idx=%s' % idx)[3] try: return exec_sql('select value from tko_test_attributes' ' where test_idx=%s and attribute="%s"' % (test_idx, keyname))[-1] except: return default class Sample(object): """ Collect test results in same environment to a sample """ def __init__(self, sample_type, arg): def generate_raw_table(test_dict): ret_dict = [] tmp = [] sample_type = category = None for i in test_dict: line = i.split('|')[1:] if not sample_type: sample_type = line[0:2] if sample_type != line[0:2]: ret_dict.append('|'.join(sample_type + tmp)) sample_type = line[0:2] tmp = [] if "e+" in line[-1]: tmp.append("%f" % float(line[-1])) elif 'e-' in line[-1]: tmp.append("%f" % float(line[-1])) elif not (re.findall("[a-zA-Z]", line[-1]) or is_int(line[-1])): tmp.append("%f" % float(line[-1])) else: tmp.append(line[-1]) if category != i.split('|')[0]: category = i.split('|')[0] ret_dict.append("Category:" + category.strip()) ret_dict.append(self.categories) ret_dict.append('|'.join(sample_type + tmp)) return ret_dict if sample_type == 'filepath': files = arg.split() self.files_dict = [] for i in range(len(files)): fd = open(files[i], "r") f = [] for l in fd.readlines(): l = l.strip() if re.findall("^### ", l): if "kvm-userspace-ver" in l: self.kvmver = l.split(':')[-1] elif "kvm_version" in l: self.hostkernel = l.split(':')[-1] elif "guest-kernel-ver" in l: self.guestkernel = l.split(':')[-1] elif "session-length" in l: self.len = l.split(':')[-1] else: f.append(l.strip()) self.files_dict.append(f) fd.close() sysinfodir = os.path.join(os.path.dirname(files[0]), "../../sysinfo/") sysinfodir = os.path.realpath(sysinfodir) cpuinfo = commands.getoutput("cat %s/cpuinfo" % sysinfodir) lscpu = commands.getoutput("cat %s/lscpu" % sysinfodir) meminfo = commands.getoutput("cat %s/meminfo" % sysinfodir) lspci = commands.getoutput("cat %s/lspci_-vvnn" % sysinfodir) partitions = commands.getoutput("cat %s/partitions" % sysinfodir) fdisk = commands.getoutput("cat %s/fdisk_-l" % sysinfodir) status_path = os.path.join(os.path.dirname(files[0]), "../status") status_file = open(status_path, 'r') content = status_file.readlines() self.testdata = re.findall("localtime=(.*)\t", content[-1])[-1] cpunum = len(re.findall("processor\s+: \d", cpuinfo)) cpumodel = re.findall("Model name:\s+(.*)", lscpu) socketnum = int(re.findall("Socket\(s\):\s+(\d+)", lscpu)[0]) corenum = int(re.findall("Core\(s\) per socket:\s+(\d+)", lscpu)[0]) * socketnum threadnum = int(re.findall("Thread\(s\) per core:\s+(\d+)", lscpu)[0]) * corenum numanodenum = int(re.findall("NUMA node\(s\):\s+(\d+)", lscpu)[0]) memnum = float(re.findall("MemTotal:\s+(\d+)", meminfo)[0]) / 1024 / 1024 nicnum = len(re.findall("\d+:\d+\.0 Ethernet", lspci)) disknum = re.findall("sd\w+\S", partitions) fdiskinfo = re.findall("Disk\s+(/dev/sd.*\s+GiB),", fdisk) elif sample_type == 'database': jobid = arg self.kvmver = get_test_keyval(jobid, "kvm-userspace-ver") self.hostkernel = get_test_keyval(jobid, "kvm_version") self.guestkernel = get_test_keyval(jobid, "guest-kernel-ver") self.len = get_test_keyval(jobid, "session-length") self.categories = get_test_keyval(jobid, "category") idx = exec_sql("select job_idx from tko_jobs where afe_job_id=%s" % jobid)[-1] data = exec_sql("select test_idx,iteration_key,iteration_value" " from tko_perf_view where job_idx=%s" % idx) testidx = None job_dict = [] test_dict = [] for l in data: s = l.split() if not testidx: testidx = s[0] if testidx != s[0]: job_dict.append(generate_raw_table(test_dict)) test_dict = [] testidx = s[0] test_dict.append(' | '.join(s[1].split('--')[0:] + s[-1:])) job_dict.append(generate_raw_table(test_dict)) self.files_dict = job_dict self.version = " userspace: %s\n host kernel: %s\n guest kernel: %s" % ( self.kvmver, self.hostkernel, self.guestkernel) nrepeat = len(self.files_dict) if nrepeat < 2: print "`nrepeat' should be larger than 1!" sys.exit(1) self.desc = """<hr>Machine Info: o CPUs(%s * %s), Cores(%s), Threads(%s), Sockets(%s), o NumaNodes(%s), Memory(%.1fG), NICs(%s) o Disks(%s | %s) Please check sysinfo directory in autotest result to get more details. (eg: http://autotest-server.com/results/5057-autotest/host1/sysinfo/) <hr>""" % (cpunum, cpumodel, corenum, threadnum, socketnum, numanodenum, memnum, nicnum, fdiskinfo, disknum) self.desc += """ - Every Avg line represents the average value based on *%d* repetitions of the same test, and the following SD line represents the Standard Deviation between the *%d* repetitions. - The Standard deviation is displayed as a percentage of the average. - The significance of the differences between the two averages is calculated using unpaired T-test that takes into account the SD of the averages. - The paired t-test is computed for the averages of same category. """ % (nrepeat, nrepeat) def getAvg(self, avg_update=None): return self._process_files(self.files_dict, self._get_list_avg, avg_update=avg_update) def getAvgPercent(self, avgs_dict): return self._process_files(avgs_dict, self._get_augment_rate) def getSD(self): return self._process_files(self.files_dict, self._get_list_sd) def getSDRate(self, sds_dict): return self._process_files(sds_dict, self._get_rate) def getTtestPvalue(self, fs_dict1, fs_dict2, paired=None, ratio=None): """ scipy lib is used to compute p-value of Ttest scipy: http://www.scipy.org/ t-test: http://en.wikipedia.org/wiki/Student's_t-test """ try: from scipy import stats import numpy as np except ImportError: print "No python scipy/numpy library installed!" return None ret = [] s1 = self._process_files(fs_dict1, self._get_list_self, merge=False) s2 = self._process_files(fs_dict2, self._get_list_self, merge=False) # s*[line][col] contians items (line*col) of all sample files for line in range(len(s1)): tmp = [] if type(s1[line]) != list: tmp = s1[line] else: if len(s1[line][0]) < 2: continue for col in range(len(s1[line])): avg1 = self._get_list_avg(s1[line][col]) avg2 = self._get_list_avg(s2[line][col]) sample1 = np.array(s1[line][col]) sample2 = np.array(s2[line][col]) warnings.simplefilter("ignore", RuntimeWarning) if (paired): if (ratio): (_, p) = stats.ttest_rel(np.log(sample1), np.log(sample2)) else: (_, p) = stats.ttest_rel(sample1, sample2) else: (_, p) = stats.ttest_ind(sample1, sample2) flag = "+" if float(avg1) > float(avg2): flag = "-" tmp.append(flag + "%f" % (1 - p)) tmp = "|".join(tmp) ret.append(tmp) return ret def _get_rate(self, data): """ num2 / num1 * 100 """ result = "0.0" if len(data) == 2 and float(data[0]) != 0: result = float(data[1]) / float(data[0]) * 100 if result > 100: result = "%.2f%%" % result else: result = "%.4f%%" % result return result def _get_augment_rate(self, data): """ (num2 - num1) / num1 * 100 """ result = "+0.0" if len(data) == 2 and float(data[0]) != 0: result = (float(data[1]) - float(data[0])) / float(data[0]) * 100 if result > 100: result = "%+.2f%%" % result else: result = "%+.4f%%" % result return result def _get_list_sd(self, data): """ sumX = x1 + x2 + ... + xn avgX = sumX / n sumSquareX = x1^2 + ... + xn^2 SD = sqrt([sumSquareX - (n * (avgX ^ 2))] / (n - 1)) """ o_sum = sqsum = 0.0 n = len(data) for i in data: o_sum += float(i) sqsum += float(i) ** 2 avg = o_sum / n if avg == 0 or n == 1 or sqsum - (n * avg ** 2) <= 0: return "0.0" return "%f" % (((sqsum - (n * avg ** 2)) / (n - 1)) ** 0.5) def _get_list_avg(self, data): """ Compute the average of list entries """ o_sum = 0.0 for i in data: o_sum += float(i) return "%f" % (o_sum / len(data)) def _get_list_self(self, data): """ Use this to convert sample dicts """ return data def _process_lines(self, files_dict, row, func, avg_update, merge): """ Use unified function to process same lines of different samples """ lines = [] ret = [] for i in range(len(files_dict)): lines.append(files_dict[i][row].split("|")) for col in range(len(lines[0])): data_list = [] for i in range(len(lines)): tmp = lines[i][col].strip() if is_int(tmp): data_list.append(int(tmp)) else: data_list.append(float(tmp)) ret.append(func(data_list)) if avg_update: for i in avg_update.split('|'): l = i.split(',') ret[int(l[0])] = "%f" % (float(ret[int(l[1])]) / float(ret[int(l[2])])) if merge: return "|".join(ret) return ret def _process_files(self, files_dict, func, avg_update=None, merge=True): """ Process dicts of sample files with assigned function, func has one list augment. """ ret_lines = [] for i in range(len(files_dict[0])): if re.findall("[a-zA-Z]", files_dict[0][i]): ret_lines.append(files_dict[0][i].strip()) else: line = self._process_lines(files_dict, i, func, avg_update, merge) ret_lines.append(line) return ret_lines def display(lists, rates, allpvalues, f, ignore_col, o_sum="Augment Rate", prefix0=None, prefix1=None, prefix2=None, prefix3=None): """ Display lists data to standard format param lists: row data lists param rates: augment rates lists param f: result output filepath param ignore_col: do not display some columns param o_sum: compare result summary param prefix0: output prefix in head lines param prefix1: output prefix in Avg/SD lines param prefix2: output prefix in Diff Avg/P-value lines param prefix3: output prefix in total Sign line """ def str_ignore(out, split=False): out = out.split("|") for i in range(ignore_col): out[i] = " " if split: return "|".join(out[ignore_col:]) return "|".join(out) def tee_line(content, filepath, n=None): fd = open(filepath, "a") print content out = "" out += "<TR ALIGN=CENTER>" content = content.split("|") for i in range(len(content)): if not is_int(content[i]) and is_float(content[i]): if "+" in content[i] or "-" in content[i]: if float(content[i]) > 100: content[i] = "%+.2f" % float(content[i]) else: content[i] = "%+.4f" % float(content[i]) elif float(content[i]) > 100: content[i] = "%.2f" % float(content[i]) else: content[i] = "%.4f" % float(content[i]) if n and i >= 2 and i < ignore_col + 2: out += "<TD ROWSPAN=%d WIDTH=1%% >%.0f</TD>" % (n, float(content[i])) else: out += "<TD WIDTH=1%% >%s</TD>" % content[i] out += "</TR>" fd.write(out + "\n") fd.close() for l in range(len(lists[0])): if not re.findall("[a-zA-Z]", lists[0][l]): break tee("<TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1 width=10%><TBODY>", f) tee("<h3>== %s " % o_sum + "==</h3>", f) category = 0 for i in range(len(lists[0])): for n in range(len(lists)): is_diff = False for j in range(len(lists)): if lists[0][i] != lists[j][i]: is_diff = True if len(lists) == 1 and not re.findall("[a-zA-Z]", lists[j][i]): is_diff = True pfix = prefix1[0] if len(prefix1) != 1: pfix = prefix1[n] if is_diff: if n == 0: tee_line(pfix + lists[n][i], f, n=len(lists) + len(rates)) else: tee_line(pfix + str_ignore(lists[n][i], True), f) if not is_diff and n == 0: if '|' in lists[n][i]: tee_line(prefix0 + lists[n][i], f) elif "Category:" in lists[n][i]: if category != 0 and prefix3: if len(allpvalues[category - 1]) > 0: tee_line(prefix3 + str_ignore( allpvalues[category - 1][0]), f) tee("</TBODY></TABLE>", f) tee("<br>", f) tee("<TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1 " "width=10%><TBODY>", f) category += 1 tee("<TH colspan=3 >%s</TH>" % lists[n][i], f) else: tee("<TH colspan=3 >%s</TH>" % lists[n][i], f) for n in range(len(rates)): if lists[0][i] != rates[n][i] and (not re.findall("[a-zA-Z]", rates[n][i]) or "nan" in rates[n][i]): tee_line(prefix2[n] + str_ignore(rates[n][i], True), f) if prefix3 and len(allpvalues[-1]) > 0: tee_line(prefix3 + str_ignore(allpvalues[category - 1][0]), f) tee("</TBODY></TABLE>", f) def analyze(test, sample_type, arg1, arg2, configfile): """ Compute averages/p-vales of two samples, print results nicely """ config = ConfigParser.ConfigParser() config.read(configfile) ignore_col = int(config.get(test, "ignore_col")) avg_update = config.get(test, "avg_update") desc = config.get(test, "desc") def get_list(directory): result_file_pattern = config.get(test, "result_file_pattern") cmd = 'find %s|grep "%s.*/%s"' % (directory, test, result_file_pattern) print cmd return commands.getoutput(cmd) if sample_type == 'filepath': arg1 = get_list(arg1) arg2 = get_list(arg2) commands.getoutput("rm -f %s.*html" % test) s1 = Sample(sample_type, arg1) avg1 = s1.getAvg(avg_update=avg_update) sd1 = s1.getSD() s2 = Sample(sample_type, arg2) avg2 = s2.getAvg(avg_update=avg_update) sd2 = s2.getSD() sd1 = s1.getSDRate([avg1, sd1]) sd2 = s1.getSDRate([avg2, sd2]) avgs_rate = s1.getAvgPercent([avg1, avg2]) navg1 = [] navg2 = [] allpvalues = [] tmp1 = [] tmp2 = [] for i in range(len(avg1)): if not re.findall("[a-zA-Z]", avg1[i]): tmp1.append([avg1[i]]) tmp2.append([avg2[i]]) elif 'Category' in avg1[i] and i != 0: navg1.append(tmp1) navg2.append(tmp2) tmp1 = [] tmp2 = [] navg1.append(tmp1) navg2.append(tmp2) for i in range(len(navg1)): allpvalues.append(s1.getTtestPvalue(navg1[i], navg2[i], True, True)) pvalues = s1.getTtestPvalue(s1.files_dict, s2.files_dict, False) rlist = [avgs_rate] if pvalues: # p-value list isn't null rlist.append(pvalues) desc = desc % s1.len tee("<pre>####1. Description of setup#1\n%s\n test data: %s</pre>" % (s1.version, s1.testdata), "%s.html" % test) tee("<pre>####2. Description of setup#2\n%s\n test data: %s</pre>" % (s2.version, s2.testdata), "%s.html" % test) tee("<pre>" + '\n'.join(desc.split('\\n')) + "</pre>", test + ".html") tee("<pre>" + s1.desc + "</pre>", test + ".html") display([avg1, sd1, avg2, sd2], rlist, allpvalues, test + ".html", ignore_col, o_sum="Regression Testing: %s" % test, prefix0="#|Tile|", prefix1=["1|Avg|", " |%SD|", "2|Avg|", " |%SD|"], prefix2=["-|%Diff between Avg|", "-|Significance|"], prefix3="-|Total Significance|") display(s1.files_dict, [avg1], [], test + ".avg.html", ignore_col, o_sum="Raw data of sample 1", prefix0="#|Tile|", prefix1=[" | |"], prefix2=["-|Avg |"], prefix3="") display(s2.files_dict, [avg2], [], test + ".avg.html", ignore_col, o_sum="Raw data of sample 2", prefix0="#|Tile|", prefix1=[" | |"], prefix2=["-|Avg |"], prefix3="") def is_int(n): try: int(n) return True except ValueError: return False def is_float(n): try: float(n) return True except ValueError: return False def tee(content, filepath): """ Write content to standard output and filepath """ fd = open(filepath, "a") fd.write(content + "\n") fd.close() print content if __name__ == "__main__": if len(sys.argv) != 5: this = os.path.basename(sys.argv[0]) print 'Usage: %s <testname> filepath <dir1> <dir2>' % this print ' or %s <testname> db <jobid1> <jobid2>' % this sys.exit(1) analyze(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], 'perf.conf')
will-Do/avocado-vt
scripts/regression.py
Python
gpl-2.0
20,876
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 18750, 1000, 1000, 1000, 2565, 2008, 11968, 8583, 3115, 4289, 3463, 1010, 24134, 1998, 4638, 26237, 11829, 1012, 1024, 30524, 1011, 2262, 1024, 3166, 1024, 13744, 4290, 1026, 17712, 5063...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * This file is part of FunctionInjector project. * You are using it at your own risk and you are fully responsible for everything that code will do. * * Copyright (c) 2016 Grzegorz Zdanowski <grzegorz@noflash.pl> * * For the full copyright and license information, please view the LICENSE file distributed with this source code. */ namespace noFlash\FunctionsManipulator\Exception; use Exception; use noFlash\FunctionsManipulator\NameValidator; class InvalidFunctionNameException extends \InvalidArgumentException { public function __construct($functionName, $reasonCode, Exception $previous = null) { $message = sprintf( 'Function name "%s" is invalid - %s.', $functionName, NameValidator::getErrorFromCode($reasonCode) ); parent::__construct($message, 0, $previous); } }
kiler129/FunctionInjector
src/Exception/InvalidFunctionNameException.php
PHP
mit
866
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 3853, 2378, 20614, 2953, 2622, 1012, 1008, 2017, 2024, 2478, 2009, 2012, 2115, 2219, 3891, 1998, 2017, 2024, 3929, 3625, 2005, 2673, 2008, 3642, 2097, 30524, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// @allowjs: true // @checkjs: true // @noemit: true // @strict: true // @filename: thisPropertyAssignmentComputed.js this["a" + "b"] = 0
Microsoft/TypeScript
tests/cases/conformance/salsa/thisPropertyAssignmentComputed.ts
TypeScript
apache-2.0
138
[ 30522, 1013, 1013, 1030, 3499, 22578, 1024, 2995, 1013, 1013, 1030, 4638, 22578, 1024, 2995, 1013, 1013, 1030, 2053, 23238, 2102, 1024, 2995, 1013, 1013, 1030, 9384, 1024, 2995, 1013, 1013, 1030, 5371, 18442, 1024, 2023, 21572, 4842, 21426,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.animation; import javax.annotation.Nullable; import android.view.View; import com.facebook.infer.annotation.Assertions; /** * Base class for various catalyst animation engines. Subclasses of this class should implement * {@link #run} method which should bootstrap the animation. Then in each animation frame we expect * animation engine to call {@link #onUpdate} with a float progress which then will be transferred * to the underlying {@link AnimationPropertyUpdater} instance. * * Animation engine should support animation cancelling by monitoring the returned value of * {@link #onUpdate}. In case of returning false, animation should be considered cancelled and * engine should not attempt to call {@link #onUpdate} again. */ public abstract class Animation { private final int mAnimationID; private final AnimationPropertyUpdater mPropertyUpdater; private volatile boolean mCancelled = false; private volatile boolean mIsFinished = false; private @Nullable AnimationListener mAnimationListener; private @Nullable View mAnimatedView; public Animation(int animationID, AnimationPropertyUpdater propertyUpdater) { mAnimationID = animationID; mPropertyUpdater = propertyUpdater; } public void setAnimationListener(AnimationListener animationListener) { mAnimationListener = animationListener; } public final void start(View view) { mAnimatedView = view; mPropertyUpdater.prepare(view); run(); } public abstract void run(); /** * Animation engine should call this method for every animation frame passing animation progress * value as a parameter. Animation progress should be within the range 0..1 (the exception here * would be a spring animation engine which may slightly exceed start and end progress values). * * This method will return false if the animation has been cancelled. In that case animation * engine should not attempt to call this method again. Otherwise this method will return true */ protected final boolean onUpdate(float value) { Assertions.assertCondition(!mIsFinished, "Animation must not already be finished!"); if (!mCancelled) { mPropertyUpdater.onUpdate(Assertions.assertNotNull(mAnimatedView), value); } return !mCancelled; } /** * Animation engine should call this method when the animation is finished. Should be called only * once */ protected final void finish() { Assertions.assertCondition(!mIsFinished, "Animation must not already be finished!"); mIsFinished = true; if (!mCancelled) { if (mAnimatedView != null) { mPropertyUpdater.onFinish(mAnimatedView); } if (mAnimationListener != null) { mAnimationListener.onFinished(); } } } /** * Cancels the animation. * * It is possible for this to be called after finish() and should handle that gracefully. */ public final void cancel() { if (mIsFinished || mCancelled) { // If we were already finished, ignore return; } mCancelled = true; if (mAnimationListener != null) { mAnimationListener.onCancel(); } } public int getAnimationID() { return mAnimationID; } }
prayuditb/tryout-01
websocket/client/Client/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/animation/Animation.java
Java
mit
3,540
[ 30522, 1013, 1008, 1008, 1008, 9385, 1006, 1039, 1007, 2325, 1011, 2556, 1010, 9130, 1010, 4297, 1012, 1008, 2035, 2916, 9235, 1012, 1008, 1008, 2023, 3120, 3642, 2003, 7000, 2104, 1996, 18667, 2094, 1011, 2806, 6105, 2179, 1999, 1996, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright 2007 Wei-ju Wu * * This file is part of TinyUML. * * TinyUML is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * TinyUML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TinyUML; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package test.mdauml.umldraw.shared; import org.jmock.Mock; import org.jmock.cglib.MockObjectTestCase; import com.nilledom.draw.CompositeNode; import com.nilledom.model.RelationEndType; import com.nilledom.model.RelationType; import com.nilledom.model.UmlRelation; import com.nilledom.umldraw.clazz.ClassElement; import com.nilledom.umldraw.shared.NoteConnection; import com.nilledom.umldraw.shared.NoteElement; /** * A test class for NoteElement. * @author Wei-ju Wu * @version 1.0 */ public class NoteElementTest extends MockObjectTestCase { /** * Tests the clone() method. */ public void testClone() { Mock mockParent1 = mock(CompositeNode.class); NoteElement note = NoteElement.getPrototype(); assertNull(note.getParent()); assertNull(note.getModelElement()); note.setOrigin(0, 0); note.setSize(100, 80); note.setLabelText("oldlabel"); note.setParent((CompositeNode) mockParent1.proxy()); NoteElement cloned = (NoteElement) note.clone(); assertTrue(note != cloned); assertEquals(note.getParent(), cloned.getParent()); assertEquals("oldlabel", cloned.getLabelText()); note.setLabelText("mylabel"); assertFalse(cloned.getLabelText() == note.getLabelText()); // now test the label mockParent1.expects(atLeastOnce()).method("getAbsoluteX1") .will(returnValue(0.0)); mockParent1.expects(atLeastOnce()).method("getAbsoluteY1") .will(returnValue(0.0)); assertNotNull(cloned.getLabelAt(20, 20)); assertNull(cloned.getLabelAt(-1.0, -2.0)); assertTrue(cloned.getLabelAt(20.0, 20.0) != note.getLabelAt(20.0, 20.0)); assertTrue(cloned.getLabelAt(20.0, 20.0).getSource() == cloned); assertTrue(cloned.getLabelAt(20.0, 20.0).getParent() == cloned); } /** * Tests the NoteConnection class. */ public void testNoteConnection() { // relation has no effect NoteConnection connection = NoteConnection.getPrototype(); connection.setRelation(new UmlRelation()); assertNull(connection.getModelElement()); } }
proyectos-fiuba-romera/nilledom
src/test/java/test/mdauml/umldraw/shared/NoteElementTest.java
Java
gpl-2.0
2,826
[ 30522, 1013, 1008, 1008, 1008, 9385, 2289, 11417, 1011, 18414, 8814, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 4714, 2819, 2140, 1012, 1008, 1008, 4714, 2819, 2140, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var $ = require('jquery'); var CoreView = require('backbone/core-view'); var checkAndBuildOpts = require('builder/helpers/required-opts'); var REQUIRED_OPTS = [ 'el' ]; module.exports = CoreView.extend({ events: { 'click .js-foo': '_fooHandler' }, initialize: function (opts) { checkAndBuildOpts(opts, REQUIRED_OPTS, this); this._onWindowScroll = this._onWindowScroll.bind(this); this._topBoundary = this.$el.offset().top; this._initBinds(); }, _initBinds: function () { this._bindScroll(); }, _onWindowScroll: function () { this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary); }, _unbindScroll: function () { $(window).unbind('scroll', this._onWindowScroll); }, _bindScroll: function () { this._unbindScroll(); $(window).bind('scroll', this._onWindowScroll); }, clean: function () { this._unbindScroll(); } });
CartoDB/cartodb
lib/assets/javascripts/dashboard/helpers/scroll-tofixed-view.js
JavaScript
bsd-3-clause
920
[ 30522, 13075, 1002, 1027, 5478, 1006, 1005, 1046, 4226, 2854, 1005, 1007, 1025, 13075, 4563, 8584, 1027, 5478, 1006, 1005, 21505, 1013, 4563, 1011, 3193, 1005, 1007, 1025, 13075, 4638, 5685, 8569, 4014, 3527, 22798, 1027, 5478, 1006, 1005, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
.game-canvas { border: 3px solid #999; border-radius: 3px; margin: auto; display: block; background-image:url('./images/background.png'); -webkit-box-shadow: 3px 3px 5px 1px rgba(0,0,0,0.32); -moz-box-shadow: 3px 3px 5px 1px rgba(0,0,0,0.32); box-shadow: 3px 3px 5px 1px rgba(0,0,0,0.32); margin-left:52px; }
haveanicedavid/socket-scrabble
style.css
CSS
mit
326
[ 30522, 1012, 2208, 1011, 10683, 1063, 3675, 1024, 1017, 2361, 2595, 5024, 1001, 25897, 1025, 3675, 1011, 12177, 1024, 1017, 2361, 2595, 1025, 7785, 1024, 8285, 1025, 4653, 1024, 3796, 1025, 4281, 1011, 3746, 1024, 24471, 2140, 1006, 1005, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* $Id: UIWizardCloneVMPageBasic3.h $ */ /** @file * VBox Qt GUI - UIWizardCloneVMPageBasic3 class declaration. */ /* * Copyright (C) 2011-2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef __UIWizardCloneVMPageBasic3_h__ #define __UIWizardCloneVMPageBasic3_h__ /* GUI includes: */ #include "UIWizardPage.h" /* COM includes: */ #include "COMEnums.h" /* Forward declaration: */ class QRadioButton; class QIRichTextLabel; /* 3rd page of the Clone Virtual Machine wizard (base part): */ class UIWizardCloneVMPage3 : public UIWizardPageBase { protected: /* Constructor: */ UIWizardCloneVMPage3(bool fShowChildsOption); /* Stuff for 'cloneMode' field: */ KCloneMode cloneMode() const; void setCloneMode(KCloneMode cloneMode); /* Variables: */ bool m_fShowChildsOption; /* Widgets: */ QRadioButton *m_pMachineRadio; QRadioButton *m_pMachineAndChildsRadio; QRadioButton *m_pAllRadio; }; /* 3rd page of the Clone Virtual Machine wizard (basic extension): */ class UIWizardCloneVMPageBasic3 : public UIWizardPage, public UIWizardCloneVMPage3 { Q_OBJECT; Q_PROPERTY(KCloneMode cloneMode READ cloneMode WRITE setCloneMode); public: /* Constructor: */ UIWizardCloneVMPageBasic3(bool fShowChildsOption); private: /* Translation stuff: */ void retranslateUi(); /* Prepare stuff: */ void initializePage(); /* Validation stuff: */ bool validatePage(); /* Widgets: */ QIRichTextLabel *m_pLabel; }; #endif // __UIWizardCloneVMPageBasic3_h__
sobomax/virtualbox_64bit_edd
src/VBox/Frontends/VirtualBox/src/wizards/clonevm/UIWizardCloneVMPageBasic3.h
C
gpl-2.0
2,009
[ 30522, 1013, 1008, 1002, 8909, 1024, 21318, 9148, 26154, 20464, 5643, 2615, 8737, 4270, 22083, 2594, 2509, 1012, 1044, 1002, 1008, 1013, 1013, 1008, 1008, 1030, 5371, 1008, 1058, 8758, 1053, 2102, 26458, 1011, 21318, 9148, 26154, 20464, 564...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System.Collections.ObjectModel; using System.ComponentModel; namespace FG5eParserModels.Utility_Modules { public class ReferenceManual : INotifyPropertyChanged { private string ChapterName { get; set; } public ObservableCollection<string> SubchapterNameList { get; set; } public ObservableCollection<ReferenceNote> ReferenceNoteList { get; set; } public string _ChapterName { get { return ChapterName; } set { ChapterName = value; OnPropertyChanged("_ChapterName"); } } //constructor public ReferenceManual() { ReferenceNoteList = new ObservableCollection<ReferenceNote>(); SubchapterNameList = new ObservableCollection<string>(); } #region PROPERTY CHANGES // Declare the interface event public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event public void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } public class ReferenceNote : INotifyPropertyChanged { private string Title { get; set; } private string Details { get; set; } private string SubchapterName { get; set; } public string _Title { get { return Title; } set { Title = value; OnPropertyChanged("_Title"); } } public string _Details { get { return Details; } set { Details = value; OnPropertyChanged("_Details"); } } public string _SubchapterName { get { return SubchapterName; } set { SubchapterName = value; OnPropertyChanged("_SubchapterName"); } } #region PROPERTY CHANGES // Declare the interface event public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event public void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } }
kay9911/FG5EParser
FG5eParserModels/Utility Modules/ReferenceManual.cs
C#
mit
2,850
[ 30522, 2478, 2291, 1012, 6407, 1012, 4874, 5302, 9247, 1025, 2478, 2291, 1012, 6922, 5302, 9247, 1025, 3415, 15327, 1042, 2290, 2629, 13699, 11650, 2121, 5302, 9247, 2015, 1012, 9710, 1035, 14184, 1063, 2270, 2465, 4431, 2386, 8787, 1024, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbpOven.Templates.Application { interface IEntityAppService { } }
eramosr16/AbpOven
Templates/Application/IEntityAppService.cs
C#
gpl-3.0
208
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025, 3415, 15327, 11113, 6873, 8159, 1012, 23561, 2015, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
class Svg2pdf < Formula homepage "http://cairographics.org/" url "http://cairographics.org/snapshots/svg2pdf-0.1.3.tar.gz" sha256 "854a870722a9d7f6262881e304a0b5e08a1c61cecb16c23a8a2f42f2b6a9406b" bottle do cellar :any sha256 "0ff81cf4177cd94c385c98b89c9620235c78fc154a6781996b4146d3777d4c5f" => :yosemite sha256 "ec23a2efe2fe015c475e42ceb44674e1ec4ba944081e9ce212e87ce25403fef5" => :mavericks sha256 "9d1880e5e4bfbc3ef676415a3c8f0480c312c3619b07efdb3249191e8f9d47a0" => :mountain_lion end depends_on "pkg-config" => :build depends_on "libsvg-cairo" resource("svg.svg") do url "https://raw.githubusercontent.com/mathiasbynens/small/master/svg.svg" sha256 "900fbe934249ad120004bd24adf66aad8817d89586273c0cc50e187bddebb601" end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do resource("svg.svg").stage do system "#{bin}/svg2pdf", "svg.svg", "test.pdf" assert File.exist? "test.pdf" end end end
mbi/homebrew
Library/Formula/svg2pdf.rb
Ruby
bsd-2-clause
1,168
[ 30522, 2465, 17917, 2290, 2475, 17299, 2546, 1026, 5675, 2188, 13704, 1000, 8299, 1024, 1013, 1013, 11096, 14773, 2015, 1012, 8917, 1013, 1000, 24471, 2140, 1000, 8299, 1024, 1013, 1013, 11096, 14773, 2015, 1012, 8917, 1013, 20057, 12326, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Server/client environment: argument handling, config file parsing, * thread wrappers, startup time */ #ifndef BITCOIN_UTIL_SYSTEM_H #define BITCOIN_UTIL_SYSTEM_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <attributes.h> #include <compat.h> #include <compat/assumptions.h> #include <fs.h> #include <logging.h> #include <sync.h> #include <tinyformat.h> #include <util/memory.h> #include <util/threadnames.h> #include <util/time.h> #include <exception> #include <map> #include <set> #include <stdint.h> #include <string> #include <utility> #include <vector> #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted // Application startup time (used for uptime calculation) int64_t GetStartupTime(); extern const char * const BITCOIN_CONF_FILENAME; void SetupEnvironment(); bool SetupNetworking(); template<typename... Args> bool error(const char* fmt, const Args&... args) { LogPrintf("ERROR: %s\n", tfm::format(fmt, args...)); return false; } void PrintExceptionContinue(const std::exception *pex, const char* pszThread); bool FileCommit(FILE *file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(fs::path src, fs::path dest); bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false); void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name); bool DirIsWritable(const fs::path& directory); bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0); /** Release all directory locks. This is used for unit testing only, at runtime * the global destructor will take care of the locks. */ void ReleaseDirectoryLocks(); bool TryCreateDirectories(const fs::path& p); fs::path GetDefaultDataDir(); // The blocks directory is always net specific. const fs::path &GetBlocksDir(); const fs::path &GetDataDir(bool fNetSpecific = true); // Return true if -datadir option points to a valid directory or is not specified. bool CheckDataDirOption(); /** Tests only */ void ClearDatadirCache(); fs::path GetConfigFile(const std::string& confPath); #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif #if HAVE_SYSTEM void runCommand(const std::string& strCommand); #endif /** * Most paths passed as configuration arguments are treated as relative to * the datadir if they are not absolute. * * @param path The path to be conditionally prefixed with datadir. * @param net_specific Forwarded to GetDataDir(). * @return The normalized path. */ fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true); inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } enum class OptionsCategory { OPTIONS, CONNECTION, WALLET, WALLET_DEBUG_TEST, ZMQ, DEBUG_TEST, CHAINPARAMS, NODE_RELAY, BLOCK_CREATION, RPC, GUI, COMMANDS, REGISTER_COMMANDS, HIDDEN // Always the last option to avoid printing these in the help }; struct SectionInfo { std::string m_name; std::string m_file; int m_line; }; class ArgsManager { public: enum Flags { NONE = 0x00, // Boolean options can accept negation syntax -noOPTION or -noOPTION=1 ALLOW_BOOL = 0x01, ALLOW_INT = 0x02, ALLOW_STRING = 0x04, ALLOW_ANY = ALLOW_BOOL | ALLOW_INT | ALLOW_STRING, DEBUG_ONLY = 0x100, /* Some options would cause cross-contamination if values for * mainnet were used while running on regtest/testnet (or vice-versa). * Setting them as NETWORK_ONLY ensures that sharing a config file * between mainnet and regtest/testnet won't cause problems due to these * parameters by accident. */ NETWORK_ONLY = 0x200, }; protected: friend class ArgsManagerHelper; struct Arg { std::string m_help_param; std::string m_help_text; unsigned int m_flags; }; mutable CCriticalSection cs_args; std::map<std::string, std::vector<std::string>> m_override_args GUARDED_BY(cs_args); std::map<std::string, std::vector<std::string>> m_config_args GUARDED_BY(cs_args); std::string m_network GUARDED_BY(cs_args); std::set<std::string> m_network_only_args GUARDED_BY(cs_args); std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args); std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args); NODISCARD bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false); public: ArgsManager(); /** * Select the network in use */ void SelectConfigNetwork(const std::string& network); NODISCARD bool ParseParameters(int argc, const char* const argv[], std::string& error); NODISCARD bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false); /** * Log warnings for options in m_section_only_args when * they are specified in the default section but not overridden * on the command line or in a network-specific section in the * config file. */ const std::set<std::string> GetUnsuitableSectionOnlyArgs() const; /** * Log warnings for unrecognized section names in the config file. */ const std::list<SectionInfo> GetUnrecognizedSections() const; /** * Return a vector of strings of the given argument * * @param strArg Argument to get (e.g. "-foo") * @return command-line arguments */ std::vector<std::string> GetArgs(const std::string& strArg) const; /** * Return true if the given argument has been manually set * * @param strArg Argument to get (e.g. "-foo") * @return true if the argument has been set */ bool IsArgSet(const std::string& strArg) const; /** * Return true if the argument was originally passed as a negated option, * i.e. -nofoo. * * @param strArg Argument to get (e.g. "-foo") * @return true if the argument was passed negated */ bool IsArgNegated(const std::string& strArg) const; /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param strDefault (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault) const; /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param nDefault (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault) const; /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param fDefault (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault) const; /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already // been set. Also called directly in testing. void ForceSetArg(const std::string& strArg, const std::string& strValue); /** * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. * @return CBaseChainParams::MAIN by default; raises runtime error if an invalid combination is given. */ std::string GetChainName() const; /** * Add argument */ void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat); /** * Add many hidden arguments */ void AddHiddenArgs(const std::vector<std::string>& args); /** * Clear available arguments */ void ClearArgs() { LOCK(cs_args); m_available_args.clear(); m_network_only_args.clear(); } /** * Get the help string */ std::string GetHelpMessage() const; /** * Return Flags for known arg. * Return ArgsManager::NONE for unknown arg. */ unsigned int FlagsOfKnownArg(const std::string& key) const; }; extern ArgsManager gArgs; /** * @return true if help has been requested via a command-line arg */ bool HelpRequested(const ArgsManager& args); /** Add help options to the args manager */ void SetupHelpOptions(ArgsManager& args); /** * Format a string to be used as group of options in help messages * * @param message Group name (e.g. "RPC server options:") * @return the formatted string */ std::string HelpMessageGroup(const std::string& message); /** * Format a string to be used as option description in help messages * * @param option Option message (e.g. "-rpcuser=<user>") * @param message Option description (e.g. "Username for JSON-RPC connections") * @return the formatted string */ std::string HelpMessageOpt(const std::string& option, const std::string& message); /** * Return the number of cores available on the current system. * @note This does count virtual cores, such as those provided by HyperThreading. */ int GetNumCores(); /** * .. and a wrapper that just calls func once */ template <typename Callable> void TraceThread(const char* name, Callable func) { util::ThreadRename(name); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (const boost::thread_interrupted&) { LogPrintf("%s thread interrupt\n", name); throw; } catch (const std::exception& e) { PrintExceptionContinue(&e, name); throw; } catch (...) { PrintExceptionContinue(nullptr, name); throw; } } std::string CopyrightHolders(const std::string& strPrefix); /** * On platforms that support it, tell the kernel the calling thread is * CPU-intensive and non-interactive. See SCHED_BATCH in sched(7) for details. * * @return The return value of sched_setschedule(), or 1 on systems without * sched_setschedule(). */ int ScheduleBatchPriority(); namespace util { //! Simplification of std insertion template <typename Tdst, typename Tsrc> inline void insert(Tdst& dst, const Tsrc& src) { dst.insert(dst.begin(), src.begin(), src.end()); } template <typename TsetT, typename Tsrc> inline void insert(std::set<TsetT>& dst, const Tsrc& src) { dst.insert(src.begin(), src.end()); } #ifdef WIN32 class WinCmdLineArgs { public: WinCmdLineArgs(); ~WinCmdLineArgs(); std::pair<int, char**> get(); private: int argc; char** argv; std::vector<std::string> args; }; #endif } // namespace util #endif // BITCOIN_UTIL_SYSTEM_H
CryptArc/bitcoin
src/util/system.h
C
mit
11,747
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2268, 1011, 2230, 20251, 6182, 17823, 22591, 3406, 1013, 1013, 9385, 1006, 1039, 1007, 2268, 1011, 10476, 1996, 2978, 3597, 2378, 4563, 9797, 1013, 1013, 5500, 2104, 1996, 10210, 4007, 6105, 1010, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# frozen_string_literal: true require 'spec_helper' describe User do describe '#steam_profile_url' do it 'creates a steam profile url based on the uid' do subject.stub(uid: '123') subject.steam_profile_url.should eql 'http://steamcommunity.com/profiles/123' end end describe '.find_for_steam_auth' do before do @auth = double(provider: 'steam', uid: '321', info: double(name: 'Kees', nickname: 'Killer')) end context 'new user' do it "creates and returns a new user if it can't find an existing one" do expect { User.find_for_steam_auth(@auth) }.to change { User.count }.from(0).to(1) end # JRuby and utf8mb4 don't play well together it 'cleans up crazy names when trying to create a new user' do @auth.stub(info: double(name: 'this.XKLL 🎂', nickname: 'this.XKLL 🎂')) expect { User.find_for_steam_auth(@auth) }.to change { User.count }.from(0).to(1) end end context 'existing user' do it 'returns an existing user if it could find one by uid' do create(:user, uid: '321') expect { User.find_for_steam_auth(@auth) }.not_to change { User.count } end it 'updates an existing user with new information' do user = create(:user, name: 'Karel', uid: '321') expect { User.find_for_steam_auth(@auth) }.not_to change { User.count } user.reload.name.should eql 'Kees' end it 'cleans up the nickname when trying to update an existing user' do user = create(:user, name: 'Karel', uid: '321') @auth.stub(uid: '321', provider: 'steam', info: double(name: 'this.XKLL 🎂', nickname: 'this.XKLL 🎂')) expect { User.find_for_steam_auth(@auth) }.not_to change { User.count } user.reload.name.should eql 'this.XKLL 🎂' end end end describe '#total_reservation_seconds' do it 'calculates the amount of time a user has reserved servers' do user = create(:user) create(:reservation, user: user, starts_at: 1.hour.from_now, ends_at: 2.hours.from_now) user.total_reservation_seconds.should == 3600 end end describe '#top10?' do it 'returns if a user is in the top 10' do user = create(:user) create(:reservation, user: user) user.should be_top10 end end describe '#donator?' do it 'is no longer a donator if the membership expired' do user = create(:user) user.groups << Group.donator_group user.group_users.last.update_attribute(:expires_at, 1.day.ago) user.reload.should_not be_donator end it 'is a donator when the membership is eternal' do user = create(:user) user.groups << Group.donator_group user.group_users.last.update_attribute(:expires_at, nil) user.reload.should be_donator end it 'is a donator when the membership expires in future' do user = create(:user) user.groups << Group.donator_group user.group_users.last.update_attribute(:expires_at, 1.day.from_now) user.reload.should be_donator end end describe '#donator_until' do it 'knows how long it is still a donator' do user = create(:user) user.groups << Group.donator_group expiration = 1.day.from_now user.group_users.last.update_attribute(:expires_at, 1.day.from_now) user.donator_until.to_date.should == expiration.to_date end end describe '#admin?' do it 'is an admin when in the admin group' do user = create(:user) user.groups << Group.admin_group user.should be_admin end end describe '#league_admin?' do it 'is a league admin when in the league admin group' do user = create(:user) user.groups << Group.league_admin_group user.should be_league_admin end end end
Arie/serveme
spec/models/user_spec.rb
Ruby
apache-2.0
3,905
[ 30522, 1001, 7708, 1035, 5164, 1035, 18204, 1024, 2995, 5478, 1005, 28699, 1035, 2393, 2121, 1005, 6235, 30524, 1037, 5492, 6337, 24471, 2140, 2241, 2006, 1996, 21318, 2094, 1005, 2079, 3395, 1012, 24646, 2497, 1006, 21318, 2094, 1024, 1005...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Test import macro import Import: encap, @imports using Base.Test @imports "./a/index" @test a == 1 @test b == 2 @test_throws UndefVarError c @imports "./a/index" a b c @test a == 1 @test b == 2 @test c == 3 # aliasing @imports "./a/index" a => f b c @test f == 1 @imports "./a" a=>f b=>g c=>h @test f == 1 @test g == 2 @test h == 3 @imports "eval"
openbohemians/Import.jl
test/testimport.jl
Julia
mit
358
[ 30522, 1001, 3231, 12324, 26632, 12324, 12324, 1024, 4372, 17695, 1010, 1030, 17589, 2478, 2918, 1012, 3231, 1030, 17589, 1000, 1012, 1013, 1037, 1013, 5950, 1000, 1030, 3231, 1037, 1027, 1027, 1015, 1030, 3231, 1038, 1027, 1027, 1016, 1030...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.trees.ScaleSelBranchLengths; import java.util.*; import java.awt.*; import mesquite.lib.*; import mesquite.lib.duties.*; /* ======================================================================== */ public class ScaleSelBranchLengths extends BranchLengthsAlterer { double resultNum; double scale = 0; /*.................................................................................................................*/ public boolean startJob(String arguments, Object condition, boolean hiredByName) { scale = MesquiteDouble.queryDouble(containerOfModule(), "Scale lengths of selected branches", "Multiply all branch lengths by", 1.0); return true; } /*.................................................................................................................*/ /** returns whether this module is requesting to appear as a primary choice */ public boolean requestPrimaryChoice(){ return true; } /*.................................................................................................................*/ public boolean isSubstantive(){ return true; } /*.................................................................................................................*/ public boolean isPrerelease(){ return false; } /*.................................................................................................................*/ public boolean transformTree(AdjustableTree tree, MesquiteString resultString, boolean notify){ if (MesquiteDouble.isCombinable(scale) && tree instanceof MesquiteTree) { if (tree.hasBranchLengths()){ ((MesquiteTree)tree).doCommand("scaleLengthSelectedBranches", MesquiteDouble.toString(scale), CommandChecker.defaultChecker); if (notify && tree instanceof Listened) ((Listened)tree).notifyListeners(this, new Notification(MesquiteListener.BRANCHLENGTHS_CHANGED)); return true; } else discreetAlert( "Branch lengths of tree are all unassigned. Cannot scale selected branch lengths."); } return false; } /*.................................................................................................................*/ public String getName() { return "Scale Selected Branch Lengths"; } /*.................................................................................................................*/ public String getNameForMenuItem() { return "Scale Selected Branch Lengths..."; } /*.................................................................................................................*/ /** returns an explanation of what the module does.*/ public String getExplanation() { return "Adjusts lengths of a tree's selected branches by multiplying them by an amount." ; } }
MesquiteProject/MesquiteCore
Source/mesquite/trees/ScaleSelBranchLengths/ScaleSelBranchLengths.java
Java
lgpl-3.0
3,540
[ 30522, 1013, 1008, 2033, 2015, 15549, 2618, 3120, 3642, 1012, 9385, 2722, 1998, 15834, 1010, 1059, 1012, 5506, 10521, 2239, 1998, 1040, 1012, 5506, 10521, 2239, 1012, 5860, 19771, 5017, 1024, 1996, 2033, 2015, 15549, 2618, 3120, 3642, 2003,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
USE [BDQuality] GO /****** Object: UserDefinedFunction [dbo].[funGetSumaPorDigitos] Script Date: 23/07/2015 18:29:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[funGetSumaPorDigitos]( @pCadena VARCHAR(500)) RETURNS numeric(38,0) AS BEGIN DECLARE @vPivote numeric(38,0)=2; DECLARE @vLongitudCadena numeric(38,0); DECLARE @vCantidadTotal numeric(38,0)=0; DECLARE @i numeric(38,0)=1; DECLARE @vTemporal numeric(38,0); SET @vLongitudCadena=LEN(@pCadena); WHILE @i <= @vLongitudCadena BEGIN IF @vPivote= 8 BEGIN SET @vPivote=2; END SET @vTemporal =cast(SUBSTRING(@pCadena,@i,1) as numeric(38,0)); SET @vTemporal =@vTemporal *@vPivote; SET @vPivote =@vPivote +1; SET @vCantidadTotal=@vCantidadTotal+@vTemporal; SET @i =@i +1; END; SET @vCantidadTotal=11-(@vCantidadTotal %11); RETURN @vCantidadTotal; END ; GO
jorjoluiso/quijotelu
quijotelu/sqlserver/sql/funGetSumaPorDigitos.sql
SQL
gpl-3.0
1,035
[ 30522, 2224, 1031, 1038, 2094, 26426, 3012, 1033, 2175, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 4874, 1024, 5310, 3207, 23460, 20952, 4609, 7542, 1031, 16962, 2080, 1033, 1012, 1031, 4569, 18150, 17421, 9331, 8551, 8004, 9956, 2015, 1033,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Event\Step; use Event\Controller\EventUpdateRecordController; class OutcomeUpdateStep extends OutcomeStep implements UpdateStep { private $eventId; /** * The route for this step. * * @return mixed */ public function route() { return sprintf('%s/outcome', EventUpdateRecordController::ROUTE_UPDATE); } public function routeParams() { return [ 'type' => $this->getEntityType(), 'id' => $this->getEntityId(), 'eventId' => $this->getEventId(), ]; } /** * @return mixed */ public function getEventId() { return $this->eventId; } /** * @param mixed $eventId */ public function setEventId($eventId) { $this->eventId = $eventId; } }
dvsa/mot
mot-web-frontend/module/Event/src/Event/Step/OutcomeUpdateStep.php
PHP
mit
828
[ 30522, 1026, 1029, 25718, 3415, 15327, 2724, 1032, 3357, 1025, 2224, 2724, 1032, 11486, 1032, 2724, 6279, 13701, 2890, 27108, 16409, 12162, 26611, 1025, 2465, 9560, 6279, 27122, 2618, 2361, 8908, 13105, 2618, 2361, 22164, 14409, 2618, 2361, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */ #endif /* BEE_MODULE_H_INCLUDED */
venkatarajasekhar/bee
src/trivia/bee_footer.h
C
bsd-2-clause
114
[ 30522, 1001, 2065, 4225, 1006, 1035, 1035, 18133, 7393, 24759, 2271, 1007, 1065, 1013, 1008, 4654, 16451, 1000, 1039, 1000, 1008, 1013, 1001, 2203, 10128, 1013, 1008, 4225, 1006, 1035, 1035, 18133, 7393, 24759, 2271, 1007, 1008, 1013, 1001,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// This file is part of SVO - Semi-direct Visual Odometry. // // Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch> // (Robotics and Perception Group, University of Zurich, Switzerland). // // SVO is free software: you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the Free Software // Foundation, either version 3 of the License, or any later version. // // SVO is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <stdexcept> #include <svo/frame.h> #include <svo/feature.h> #include <svo/point.h> #include <svo/config.h> #include <boost/bind.hpp> #include <vikit/math_utils.h> #include <vikit/vision.h> #include <vikit/performance_monitor.h> #include <fast/fast.h> namespace svo { int Frame::frame_counter_ = 0; Frame::Frame(vk::AbstractCamera* cam, const cv::Mat& img, double timestamp) : id_(frame_counter_++), timestamp_(timestamp), cam_(cam), key_pts_(5), is_keyframe_(false), v_kf_(NULL), last_published_ts_(-1) { initFrame(img); } Frame::~Frame() { std::for_each(fts_.begin(), fts_.end(), [&](Feature* i){delete i;}); // if(id_) // cout<<"Frame "<<id_<<" released.\n"; } void Frame::initFrame(const cv::Mat& img) { // check image if(img.empty() || img.type() != CV_8UC1 || img.cols != cam_->width() || img.rows != cam_->height()) throw std::runtime_error("Frame: provided image has not the same size as the camera model or image is not grayscale"); // Set keypoints to NULL std::for_each(key_pts_.begin(), key_pts_.end(), [&](Feature* ftr){ ftr=NULL; }); // Build Image Pyramid frame_utils::createImgPyramid(img, max(Config::nPyrLevels(), Config::kltMaxLevel()+1), img_pyr_); } void Frame::setKeyframe() { is_keyframe_ = true; setKeyPoints(); } void Frame::addFeature(Feature* ftr) { fts_.push_back(ftr); } void Frame::setKeyPoints() { for(size_t i = 0; i < 5; ++i) if(key_pts_[i] != NULL) if(key_pts_[i]->point == NULL) key_pts_[i] = NULL; std::for_each(fts_.begin(), fts_.end(), [&](Feature* ftr){ if(ftr->point != NULL) checkKeyPoints(ftr); }); } void Frame::checkKeyPoints(Feature* ftr) { const int cu = cam_->width()/2; const int cv = cam_->height()/2; // center pixel if(key_pts_[0] == NULL) key_pts_[0] = ftr; else if(std::max(std::fabs(ftr->px[0]-cu), std::fabs(ftr->px[1]-cv)) < std::max(std::fabs(key_pts_[0]->px[0]-cu), std::fabs(key_pts_[0]->px[1]-cv))) key_pts_[0] = ftr; if(ftr->px[0] >= cu && ftr->px[1] >= cv) { if(key_pts_[1] == NULL) key_pts_[1] = ftr; else if((ftr->px[0]-cu) * (ftr->px[1]-cv) > (key_pts_[1]->px[0]-cu) * (key_pts_[1]->px[1]-cv)) key_pts_[1] = ftr; } if(ftr->px[0] >= cu && ftr->px[1] < cv) { if(key_pts_[2] == NULL) key_pts_[2] = ftr; else if((ftr->px[0]-cu) * (ftr->px[1]-cv) > (key_pts_[2]->px[0]-cu) * (key_pts_[2]->px[1]-cv)) key_pts_[2] = ftr; } if(ftr->px[0] < cv && ftr->px[1] < cv) { if(key_pts_[3] == NULL) key_pts_[3] = ftr; else if((ftr->px[0]-cu) * (ftr->px[1]-cv) > (key_pts_[3]->px[0]-cu) * (key_pts_[3]->px[1]-cv)) key_pts_[3] = ftr; } if(ftr->px[0] < cv && ftr->px[1] >= cv) { if(key_pts_[4] == NULL) key_pts_[4] = ftr; else if((ftr->px[0]-cu) * (ftr->px[1]-cv) > (key_pts_[4]->px[0]-cu) * (key_pts_[4]->px[1]-cv)) key_pts_[4] = ftr; } } void Frame::removeKeyPoint(Feature* ftr) { bool found = false; std::for_each(key_pts_.begin(), key_pts_.end(), [&](Feature*& i){ if(i == ftr) { i = NULL; found = true; } }); if(found) setKeyPoints(); } bool Frame::isVisible(const Vector3d& xyz_w) const { Vector3d xyz_f = T_f_w_*xyz_w; if(xyz_f.z() < 0.0) return false; // point is behind the camera Vector2d px = f2c(xyz_f); if(px[0] >= 0.0 && px[1] >= 0.0 && px[0] < cam_->width() && px[1] < cam_->height()) return true; return false; } /// Utility functions for the Frame class namespace frame_utils { void createImgPyramid(const cv::Mat& img_level_0, int n_levels, ImgPyr& pyr) { pyr.resize(n_levels); pyr[0] = img_level_0; for(int i=1; i<n_levels; ++i) { pyr[i] = cv::Mat(pyr[i-1].rows/2, pyr[i-1].cols/2, CV_8U); vk::halfSample(pyr[i-1], pyr[i]); } } bool getSceneDepth(const Frame& frame, double& depth_mean, double& depth_min) { vector<double> depth_vec; depth_vec.reserve(frame.fts_.size()); depth_min = std::numeric_limits<double>::max(); for(auto it=frame.fts_.begin(), ite=frame.fts_.end(); it!=ite; ++it) { if((*it)->point != NULL) { const double z = frame.w2f((*it)->point->pos_).z(); depth_vec.push_back(z); depth_min = fmin(z, depth_min); } } if(depth_vec.empty()) { SVO_WARN_STREAM("Cannot set scene depth. Frame has no point-observations!"); return false; } depth_mean = vk::getMedian(depth_vec); return true; } } // namespace frame_utils } // namespace svo
zdzhaoyong/PIL
Thirdparty/svo/src/frame.cpp
C++
lgpl-3.0
5,332
[ 30522, 1013, 1013, 2023, 5371, 2003, 2112, 1997, 17917, 2080, 1011, 4100, 1011, 3622, 5107, 1051, 26173, 11129, 1012, 1013, 1013, 1013, 1013, 9385, 1006, 1039, 1007, 2297, 3017, 21316, 1026, 21316, 2012, 2065, 2072, 11089, 1057, 27922, 1108...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.actions; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.core.resources.*; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.runtime.IPluginService; import org.jkiss.dbeaver.ui.ActionUtils; /** * GlobalPropertyTester */ public class GlobalPropertyTester extends PropertyTester { //static final Log log = LogFactory.get vLog(ObjectPropertyTester.class); public static final String NAMESPACE = "org.jkiss.dbeaver.core.global"; public static final String PROP_STANDALONE = "standalone"; public static final String PROP_HAS_ACTIVE_PROJECT = "hasActiveProject"; public static final String PROP_HAS_MULTI_PROJECTS = "hasMultipleProjects"; @Override public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { switch (property) { case PROP_HAS_MULTI_PROJECTS: return DBWorkbench.getPlatform().getWorkspace().getProjects().size() > 1; case PROP_HAS_ACTIVE_PROJECT: return DBWorkbench.getPlatform().getWorkspace().getActiveProject() != null; case PROP_STANDALONE: return DBWorkbench.getPlatform().getApplication().isStandalone(); } return false; } public static void firePropertyChange(String propName) { ActionUtils.evaluatePropertyState(NAMESPACE + "." + propName); } public static class ResourceListener implements IPluginService, IResourceChangeListener { @Override public void activateService() { ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } @Override public void deactivateService() { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); } @Override public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.POST_CHANGE) { for (IResourceDelta childDelta : event.getDelta().getAffectedChildren()) { if (childDelta.getResource() instanceof IProject) { if (childDelta.getKind() == IResourceDelta.ADDED || childDelta.getKind() == IResourceDelta.REMOVED) { firePropertyChange(GlobalPropertyTester.PROP_HAS_MULTI_PROJECTS); } } } } } } }
liuyuanyuan/dbeaver
plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/actions/GlobalPropertyTester.java
Java
apache-2.0
3,123
[ 30522, 1013, 1008, 1008, 16962, 5243, 6299, 1011, 5415, 7809, 3208, 1008, 9385, 1006, 1039, 1007, 2230, 1011, 10476, 21747, 7945, 1006, 21747, 1030, 1046, 14270, 2015, 1012, 8917, 1007, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content="A calculator written in javascript"> <meta name="author" content="Chris Wilson"> <!--<link rel="icon" href="favicon.ico"> TODO favicon--> <title>JavaScript Calculator</title> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap theme --> <link href="css/bootstrap-theme.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/theme.css" rel="stylesheet"> <!-- Custom styles for this document --> <link href="css/fcc_javascript_calculator.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[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 role="document"> <!-- Fixed navbar --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">JavaScript Calculator</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="https://blockbeard.github.io/">Home</a></li> <li><a data-toggle="modal" data-target="#projectModal">This Project</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Chris Wilson <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="https://blockbeard.github.io/#about">About me</a></li> <li><a href="https://blockbeard.github.io/#contact">Contact me</a></li> <li><a href="https://github.com/blockbeard">My Github</a></li> <li><a href="https://blockbeard.github.io/#portfolio">My code portfolio</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <!-- project Modal --> <div class="modal fade" id="projectModal" tabindex="-1" role="dialog" aria-labelledby="projectModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="aboutModalLabel">JavaScript Calculator</h4> </div> <div class="modal-body"> A basic calculator powered by JavaScript, written for the Free Code Camp course. <br> <a href="https://github.com/blockbeard/fcc_javascript_calculator">Find this project on Github</a> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- /project Modal --> <div class="container theme-showcase calculator" role="main"> <div class="row"> <div class="col-lg-4 col-sm-8 col-xs-12 text-center"> <h1 id="display"></h1> </div> </div> <div class="row"> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-block btn-default btn" onclick="buttonPress(7)">7</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-block btn-default btn" onclick="buttonPress(8)">8</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-block btn-default btn" onclick="buttonPress(9)">9</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-block btn-default btn" onclick="operation(1)">+</button> </div> </div> <div class="row"> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(4)">4</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(5)">5</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(6)">6</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="operation(2)">-</button> </div> </div> <div class="row"> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(1)">1</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(2)">2</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(3)">3</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="operation(3)">*</button> </div> </div> <div class="row"> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="decimal()">.</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="buttonPress(0)">0</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="posNeg()">+/-</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="operation(4)">/</button> </div> </div> <div class="row"> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="ac()">AC</button> </div> <div class="col-lg-1 col-sm-2 col-xs-3 text-center"> <button class="btn-default btn-block btn" onclick="ce()">CE</button> </div> <div class="col-lg-2 col-sm-4 col-xs-6 text-center"> <button class="btn-default btn-block btn" onclick="equals()">=</button> </div> </div> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script> <script src="js/bootstrap.min.js"></script> <script src="js/docs.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="js/ie10-viewport-bug-workaround.js"></script> <!-- JavaScript for this project --> <script src="js/fcc_javascript_calculator.js"></script> </body> </html>
blockbeard/blockbeard.github.io
fcc_javascript_calculator.html
HTML
mit
8,590
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 1027, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<p align="center"> <img src="IntrinsicEd/media/logo_small.png"/> </p> # Intrinsic [![Contribute!](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/begla/Intrinsic/issues) <a href='https://ko-fi.com/A815CV2' target='_blank'><img height='20' style='border:0px;height:20px;' src='https://az743702.vo.msecnd.net/cdn/kofi1.png?v=0' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a> **NOTE:** *I'm working on this project in my sparetime and thus the development activity might vary from time to time. This project is not abandoned and I'm certainly planning to continue working on it in the future.* Intrinsic is a Vulkan based cross-platform game and rendering engine. The project is currently in an early stage of development. The Intrinsic repository is hosted on [GitHub](http://www.github.com/begla/Intrinsic). You can find some simple build and setup instructions in `GETTING_STARTED.md`. Contributions and general support are welcome at any time. # Build Status | Platform | Build Status | |:--------:|:------------:| | Windows (Visual Studio 2017) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/eevcf6gfm77309ud?svg=true)](https://ci.appveyor.com/project/begla/intrinsic) | | Linux (GCC 6.0 / Clang 4.0) | [![Linux Build Status](https://travis-ci.org/begla/Intrinsic.svg?branch=master)](https://travis-ci.org/begla/Intrinsic) | # Screenshots ![Intrinsic](media/screenshot_0.jpg) ![IntrinsicEd](media/screenshot_1.jpg) ![IntrinsicEd](media/screenshot_3.jpg) ![IntrinsicEd](media/screenshot_2.jpg) # License ``` // Copyright 2017 Benjamin Glatzel // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ```
begla/Intrinsic
README.md
Markdown
apache-2.0
2,198
[ 30522, 1026, 1052, 25705, 1027, 1000, 2415, 1000, 1028, 1026, 10047, 2290, 5034, 2278, 1027, 1000, 23807, 2098, 1013, 2865, 1013, 8154, 1035, 2235, 1012, 1052, 3070, 1000, 1013, 1028, 1026, 1013, 1052, 1028, 1001, 23807, 1031, 999, 1031, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using CatalokoService.Helpers.DTO; using CatalokoService.Helpers.FacebookAuth; using CatalokoService.Models; using System; using System.Web.Mvc; namespace CatalokoService.Controllers { public class HomeController : Controller { CatalokoEntities bd = new CatalokoEntities(); public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
albertoroque/cataloko
service/CatalokoService/CatalokoService/Controllers/ClienteController/HomeController.cs
C#
gpl-3.0
439
[ 30522, 2478, 4937, 23067, 15710, 2121, 7903, 2063, 1012, 2393, 2545, 1012, 26718, 2080, 1025, 2478, 4937, 23067, 15710, 2121, 7903, 2063, 1012, 2393, 2545, 1012, 9130, 4887, 2705, 1025, 2478, 4937, 23067, 15710, 2121, 7903, 2063, 1012, 4275...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient', field=models.EmailField(db_index=True, max_length=254), ), ]
JustinWingChungHui/okKindred
emailer/migrations/0008_auto_20151224_1528.py
Python
gpl-2.0
467
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 7013, 2011, 6520, 23422, 1015, 1012, 1023, 2006, 2325, 1011, 2260, 1011, 2484, 2321, 1024, 2654, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 27260, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file ai_cargolist.cpp Implementation of AICargoList and friends. */ #include "ai_cargolist.hpp" #include "ai_industry.hpp" #include "../../cargotype.h" #include "../../industry.h" AICargoList::AICargoList() { const CargoSpec *cs; FOR_ALL_CARGOSPECS(cs) { this->AddItem(cs->Index()); } } AICargoList_IndustryAccepting::AICargoList_IndustryAccepting(IndustryID industry_id) { if (!AIIndustry::IsValidIndustry(industry_id)) return; Industry *ind = ::Industry::Get(industry_id); for (uint i = 0; i < lengthof(ind->accepts_cargo); i++) { CargoID cargo_id = ind->accepts_cargo[i]; if (cargo_id != CT_INVALID) { this->AddItem(cargo_id); } } } AICargoList_IndustryProducing::AICargoList_IndustryProducing(IndustryID industry_id) { if (!AIIndustry::IsValidIndustry(industry_id)) return; Industry *ind = ::Industry::Get(industry_id); for (uint i = 0; i < lengthof(ind->produced_cargo); i++) { CargoID cargo_id = ind->produced_cargo[i]; if (cargo_id != CT_INVALID) { this->AddItem(cargo_id); } } }
jemmyw/openttd
src/ai/api/ai_cargolist.cpp
C++
gpl-2.0
1,623
[ 30522, 1013, 1008, 1002, 8909, 1002, 1008, 1013, 1013, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 2330, 4779, 2094, 1012, 1008, 2330, 4779, 2094, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 199...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Tue May 29 00:11:55 CEST 2012 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> javax.microedition.sensor (leJOS NXJ API documentation) </TITLE> <META NAME="keywords" CONTENT="javax.microedition.sensor package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../javax/microedition/sensor/package-summary.html" target="classFrame">javax.microedition.sensor</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Channel.html" title="interface in javax.microedition.sensor" target="classFrame"><I>Channel</I></A> <BR> <A HREF="ChannelInfo.html" title="interface in javax.microedition.sensor" target="classFrame"><I>ChannelInfo</I></A> <BR> <A HREF="Condition.html" title="interface in javax.microedition.sensor" target="classFrame"><I>Condition</I></A> <BR> <A HREF="ConditionListener.html" title="interface in javax.microedition.sensor" target="classFrame"><I>ConditionListener</I></A> <BR> <A HREF="Data.html" title="interface in javax.microedition.sensor" target="classFrame"><I>Data</I></A> <BR> <A HREF="DataListener.html" title="interface in javax.microedition.sensor" target="classFrame"><I>DataListener</I></A> <BR> <A HREF="SensorConnection.html" title="interface in javax.microedition.sensor" target="classFrame"><I>SensorConnection</I></A> <BR> <A HREF="SensorInfo.html" title="interface in javax.microedition.sensor" target="classFrame"><I>SensorInfo</I></A> <BR> <A HREF="SensorListener.html" title="interface in javax.microedition.sensor" target="classFrame"><I>SensorListener</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AccelerationChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">AccelerationChannelInfo</A> <BR> <A HREF="BatteryChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">BatteryChannelInfo</A> <BR> <A HREF="BatterySensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">BatterySensorInfo</A> <BR> <A HREF="ColorChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">ColorChannelInfo</A> <BR> <A HREF="ColorIndexChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">ColorIndexChannelInfo</A> <BR> <A HREF="ColorRGBChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">ColorRGBChannelInfo</A> <BR> <A HREF="GyroChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">GyroChannelInfo</A> <BR> <A HREF="HeadingChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">HeadingChannelInfo</A> <BR> <A HREF="HiTechnicColorSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">HiTechnicColorSensorInfo</A> <BR> <A HREF="HiTechnicCompassSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">HiTechnicCompassSensorInfo</A> <BR> <A HREF="HiTechnicGyroSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">HiTechnicGyroSensorInfo</A> <BR> <A HREF="LightChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">LightChannelInfo</A> <BR> <A HREF="LightSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">LightSensorInfo</A> <BR> <A HREF="LimitCondition.html" title="class in javax.microedition.sensor" target="classFrame">LimitCondition</A> <BR> <A HREF="MeasurementRange.html" title="class in javax.microedition.sensor" target="classFrame">MeasurementRange</A> <BR> <A HREF="MindsensorsAccelerationSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">MindsensorsAccelerationSensorInfo</A> <BR> <A HREF="NXTActiveCondition.html" title="class in javax.microedition.sensor" target="classFrame">NXTActiveCondition</A> <BR> <A HREF="NXTActiveData.html" title="class in javax.microedition.sensor" target="classFrame">NXTActiveData</A> <BR> <A HREF="NXTADSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">NXTADSensorInfo</A> <BR> <A HREF="NXTChannel.html" title="class in javax.microedition.sensor" target="classFrame">NXTChannel</A> <BR> <A HREF="NXTChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">NXTChannelInfo</A> <BR> <A HREF="NXTData.html" title="class in javax.microedition.sensor" target="classFrame">NXTData</A> <BR> <A HREF="NXTSensorConnection.html" title="class in javax.microedition.sensor" target="classFrame">NXTSensorConnection</A> <BR> <A HREF="NXTSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">NXTSensorInfo</A> <BR> <A HREF="ObjectCondition.html" title="class in javax.microedition.sensor" target="classFrame">ObjectCondition</A> <BR> <A HREF="OperatorTest.html" title="class in javax.microedition.sensor" target="classFrame">OperatorTest</A> <BR> <A HREF="RangeCondition.html" title="class in javax.microedition.sensor" target="classFrame">RangeCondition</A> <BR> <A HREF="RCXLightSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">RCXLightSensorInfo</A> <BR> <A HREF="RCXTemperatureSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">RCXTemperatureSensorInfo</A> <BR> <A HREF="SensorManager.html" title="class in javax.microedition.sensor" target="classFrame">SensorManager</A> <BR> <A HREF="SensorURL.html" title="class in javax.microedition.sensor" target="classFrame">SensorURL</A> <BR> <A HREF="SoundChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">SoundChannelInfo</A> <BR> <A HREF="SoundSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">SoundSensorInfo</A> <BR> <A HREF="TemperatureChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">TemperatureChannelInfo</A> <BR> <A HREF="TiltChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">TiltChannelInfo</A> <BR> <A HREF="TouchChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">TouchChannelInfo</A> <BR> <A HREF="TouchSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">TouchSensorInfo</A> <BR> <A HREF="UltrasonicChannelInfo.html" title="class in javax.microedition.sensor" target="classFrame">UltrasonicChannelInfo</A> <BR> <A HREF="UltrasonicSensorInfo.html" title="class in javax.microedition.sensor" target="classFrame">UltrasonicSensorInfo</A> <BR> <A HREF="Unit.html" title="class in javax.microedition.sensor" target="classFrame">Unit</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
gusDuarte/enchanting-usb3
leJOS_NXJ_0.9.1beta-3/docs/nxt/javax/microedition/sensor/package-frame.html
HTML
gpl-2.0
7,088
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg)
umrashrf/scrapy
scrapy/utils/test.py
Python
bsd-3-clause
3,020
[ 30522, 1000, 1000, 1000, 2023, 11336, 3397, 2070, 4632, 15613, 4972, 2109, 1999, 5852, 1000, 1000, 1000, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 7619, 1035, 12324, 12324, 9808, 2013, 12324, 29521, 12324, 12324, 1035, 11336, 2013, 6389, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Test class for Piwik Application * * @package PhpSecInfo * @author Piwik */ /** * require the PhpSecInfo_Test_Application class */ require_once(PHPSECINFO_BASE_DIR.'/Test/Test_Application.php'); /** * Test class for Piwik application * * Checks Piwik version * * @package PhpSecInfo * @author Piwik */ class PhpSecInfo_Test_Application_Piwik extends PhpSecInfo_Test_Application { var $test_name = "Piwik"; var $recommended_value = null; function _retrieveCurrentValue() { $this->current_value = Piwik_Version::VERSION; $this->recommended_value = Piwik_GetOption(Piwik_UpdateCheck::LATEST_VERSION); } function _execTest() { if (version_compare($this->current_value, '0.5') < 0) { return PHPSECINFO_TEST_RESULT_WARN; } if (empty($this->recommended_value)) { return PHPSECINFO_TEST_RESULT_ERROR; } if (version_compare($this->current_value, $this->recommended_value) >= 0) { return PHPSECINFO_TEST_RESULT_OK; } return PHPSECINFO_TEST_RESULT_NOTICE; } function _setMessages() { parent::_setMessages(); $this->setMessageForResult(PHPSECINFO_TEST_RESULT_OK, 'en', "You are running Piwik ".$this->current_value." (the latest version)."); $this->setMessageForResult(PHPSECINFO_TEST_RESULT_NOTICE, 'en', "You are running Piwik ".$this->current_value.". The latest version of Piwik is ".$this->recommended_value."."); $this->setMessageForResult(PHPSECINFO_TEST_RESULT_WARN, 'en', "You are running Piwik ".$this->current_value." which is no longer supported by the Piwik developers. We recommend running the latest (stable) version of Piwik which includes numerous enhancements, bug fixes, and security fixes."); $this->setMessageForResult(PHPSECINFO_TEST_RESULT_ERROR, 'en', "Unable to determine the latest version of Piwik available."); } }
wret36/Philmepa
piwik/plugins/SecurityInfo/PhpSecInfo/Test/Application/piwik.php
PHP
gpl-2.0
1,814
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 3231, 2465, 2005, 14255, 9148, 2243, 4646, 1008, 1008, 1030, 7427, 25718, 3366, 15459, 14876, 1008, 1030, 3166, 14255, 9148, 2243, 1008, 1013, 1013, 1008, 1008, 1008, 5478, 1996, 25718, 3366...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * The file lifecycle.js.js Create with WebStorm * @Author gaosi * @Email angus_gaosi@163.com * @Date 2014/10/13 15:49:00 * To change this template use File | Setting |File Template */ var pomelo = require('pomelo'); var logger = require('pomelo/node_modules/pomelo-logger').getLogger('lifecycle', __filename); var utils = require('./../../tools/utils'); module.exports.beforeStartup = function (app, cb) { logger = require('pomelo/node_modules/pomelo-logger').getLogger(pomelo.app.getServerId(), __filename); logger.fatal('beforeStartup.'); cb(); }; module.exports.afterStartup = function (app, cb) { logger.fatal('afterStartup.'); utils.waitingForRpc('dbcache', true, function () { var main = require('../../js/main'); main.InitServer() .then(function () { utils.waitingForRpc('connector', true, function () { utils.notifyStatus('connector', true, cb); }); }); }); }; module.exports.beforeShutdown = function (app, cb) { logger.fatal('beforeShutdown.'); var main = require('../../pvp/main'); var playerManager = require('../../js/player/playerManager'); var utils = require('../../tools/utils'); utils.waitingForRpc('ps', false, function () { playerManager.Down(new Date(), function () { return cb(); }); }); /* utils.waitingFor(function () { return !playerManager.GetNumPlayer(1, 0).length; }, function () { logger.fatal('beforeShutdown no players on this js, shutdown.'); cb(); });*/ }; module.exports.afterStartAll = function (app) { logger.fatal('afterStartAll.'); };
huojiecs/game1
game-server/app/servers/js/lifecycle.js
JavaScript
gpl-2.0
1,747
[ 30522, 1013, 1008, 1008, 1008, 1996, 5371, 2166, 23490, 1012, 1046, 2015, 1012, 1046, 2015, 3443, 2007, 4773, 19718, 1008, 1030, 3166, 17377, 5332, 1008, 1030, 10373, 13682, 1035, 17377, 5332, 1030, 17867, 1012, 4012, 1008, 1030, 3058, 2297...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.library.items; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.smarthome.core.items.GenericItem; import org.eclipse.smarthome.core.library.CoreItemFactory; import org.eclipse.smarthome.core.library.types.DateTimeType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * A DateTimeItem stores a timestamp including a valid time zone. * * @author Thomas.Eichstaedt-Engelen * @author Kai Kreuzer - Initial contribution and API * */ public class DateTimeItem extends GenericItem { private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>(); private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>(); static { acceptedDataTypes.add((DateTimeType.class)); acceptedDataTypes.add(UnDefType.class); acceptedCommandTypes.add(RefreshType.class); acceptedCommandTypes.add(DateTimeType.class); } public DateTimeItem(String name) { super(CoreItemFactory.DATETIME, name); } @Override public List<Class<? extends State>> getAcceptedDataTypes() { return Collections.unmodifiableList(acceptedDataTypes); } @Override public List<Class<? extends Command>> getAcceptedCommandTypes() { return Collections.unmodifiableList(acceptedCommandTypes); } public void send(DateTimeType command) { internalSend(command); } }
ibaton/smarthome
bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DateTimeItem.java
Java
epl-1.0
2,055
[ 30522, 1013, 1008, 1008, 1008, 9385, 1006, 1039, 1007, 2297, 1011, 2325, 2330, 25459, 1057, 2290, 1006, 5292, 6199, 5575, 19022, 2229, 2818, 16652, 8950, 2102, 1007, 1998, 2500, 1012, 1008, 2035, 2916, 9235, 1012, 2023, 2565, 1998, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -------------------------------------------------------------------------- # # Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # require 'opennebula' ############################################################################## # This class represents a generic Cloud Server using the OpenNebula Cloud # API (OCA). Any cloud implementation should derive from this class ############################################################################## class CloudServer ########################################################################## # Class Constants. Define the OpenNebula Error and HTTP codes mapping ########################################################################## HTTP_ERROR_CODE = { OpenNebula::Error::EAUTHENTICATION => 401, OpenNebula::Error::EAUTHORIZATION => 403, OpenNebula::Error::ENO_EXISTS => 404, OpenNebula::Error::EACTION => 500, OpenNebula::Error::EXML_RPC_API => 500, OpenNebula::Error::EINTERNAL => 500, OpenNebula::Error::ENOTDEFINED => 500 } ########################################################################## # Public attributes ########################################################################## attr_reader :config # Initializes the Cloud server based on a config file # config_file:: _String_ for the server. MUST include the following # variables: # AUTH # VM_TYPE # XMLRPC def initialize(config, logger=nil) # --- Load the Cloud Server configuration file --- @config = config @@logger = logger end def self.logger return @@logger end def logger return @@logger end # # Prints the configuration of the server # def self.print_configuration(config) puts "--------------------------------------" puts " Server configuration " puts "--------------------------------------" pp config puts "--------------------------------------" puts STDOUT.flush end # Finds out if a port is available on ip # ip:: _String_ IP address where the port to check is # port:: _String_ port to find out whether is open # [return] _Boolean_ Newly created image object def self.is_port_open?(ip, port) begin Timeout::timeout(2) do begin s = TCPSocket.new(ip, port) s.close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error end return false end end module CloudLogger require 'logger' DEBUG_LEVEL = [ Logger::ERROR, # 0 Logger::WARN, # 1 Logger::INFO, # 2 Logger::DEBUG # 3 ] # Mon Feb 27 06:02:30 2012 [Clo] [E]: Error message example MSG_FORMAT = %{%s [%s]: %s\n} # Mon Feb 27 06:02:30 2012 DATE_FORMAT = "%a %b %d %H:%M:%S %Y" # Patch logger class to be compatible with Rack::CommonLogger class CloudLogger < Logger def initialize(path) super(path) end def write(msg) info msg.chop end def add(severity, message = nil, progname = nil, &block) rc = super(severity, message, progname, &block) @logdev.dev.flush rc end end def enable_logging(path=nil, debug_level=3) path ||= $stdout logger = CloudLogger.new(path) logger.level = DEBUG_LEVEL[debug_level] logger.formatter = proc do |severity, datetime, progname, msg| MSG_FORMAT % [ datetime.strftime(DATE_FORMAT), severity[0..0], msg ] end # Add the logger instance to the Sinatra settings set :logger, logger # The logging will be configured in Rack, not in Sinatra disable :logging # Use the logger instance in the Rack methods use Rack::CommonLogger, logger helpers do def logger settings.logger end end logger end end
gargamelcat/ONE4
src/cloud/common/CloudServer.rb
Ruby
apache-2.0
5,292
[ 30522, 1001, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Algorithm by Donald Knuth. */ #include <stdio.h> #include <stdlib.h> void main( void) { int i, j=1, k, n, *c, x; printf( "Enter n,k: "); scanf( "%d,%d", &n, &k); c = malloc( (k+3) * sizeof(int)); for (i=1; i <= k; i++) c[i] = i; c[k+1] = n+1; c[k+2] = 0; j = k; visit: for (i=k; i >= 1; i--) printf( "%3d", c[i]); printf( "\n"); if (j > 0) {x = j+1; goto incr;} if (c[1] + 1 < c[2]) { c[1] += 1; goto visit; } j = 2; do_more: c[j-1] = j-1; x = c[j] + 1; if (x == c[j+1]) {j++; goto do_more;} if (j > k) exit(0); incr: c[j] = x; j--; goto visit; }
sespiros/various-projects
USACO/comb/knu.c
C
mit
584
[ 30522, 1013, 1008, 9896, 2011, 6221, 14161, 14317, 1012, 1008, 1013, 1001, 2421, 1026, 2358, 20617, 1012, 1044, 1028, 1001, 2421, 1026, 2358, 19422, 12322, 1012, 1044, 1028, 11675, 2364, 1006, 11675, 1007, 1063, 20014, 1045, 1010, 1046, 102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#if defined (_MSC_VER) && !defined (_WIN64) #pragma warning(disable:4244) // boost::number_distance::distance() // converts 64 to 32 bits integers #endif #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/IO/read_xyz_points.h> #include <CGAL/Point_with_normal_3.h> #include <CGAL/property_map.h> #include <CGAL/Shape_detection_3.h> #include <CGAL/Timer.h> #include <iostream> #include <fstream> // Type declarations typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal; typedef std::vector<Point_with_normal> Pwn_vector; typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map; typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map; // In Shape_detection_traits the basic types, i.e., Point and Vector types // as well as iterator type and property maps, are defined. typedef CGAL::Shape_detection_3::Shape_detection_traits <Kernel, Pwn_vector, Point_map, Normal_map> Traits; typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac; typedef CGAL::Shape_detection_3::Region_growing<Traits> Region_growing; typedef CGAL::Shape_detection_3::Plane<Traits> Plane; struct Timeout_callback { mutable int nb; mutable CGAL::Timer timer; const double limit; Timeout_callback(double limit) : nb(0), limit(limit) { timer.start(); } bool operator()(double advancement) const { // Avoid calling time() at every single iteration, which could // impact performances very badly ++ nb; if (nb % 1000 != 0) return true; // If the limit is reach, interrupt the algorithm if (timer.time() > limit) { std::cerr << "Algorithm takes too long, exiting (" << 100. * advancement << "% done)" << std::endl; return false; } return true; } }; // This program both works for RANSAC and Region Growing template <typename ShapeDetection> int run(const char* filename) { Pwn_vector points; std::ifstream stream(filename); if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()). normal_map(Normal_map()))) { std::cerr << "Error: cannot read file cube.pwn" << std::endl; return EXIT_FAILURE; } ShapeDetection shape_detection; shape_detection.set_input(points); shape_detection.template add_shape_factory<Plane>(); // Create callback that interrupts the algorithm if it takes more than half a second Timeout_callback timeout_callback(0.5); // Detects registered shapes with default parameters. shape_detection.detect(typename ShapeDetection::Parameters(), timeout_callback); return EXIT_SUCCESS; } int main (int argc, char** argv) { if (argc > 1 && std::string(argv[1]) == "-r") { std::cout << "Efficient RANSAC" << std::endl; return run<Efficient_ransac> ((argc > 2) ? argv[2] : "data/cube.pwn"); } std::cout << "Region Growing" << std::endl; return run<Region_growing> ((argc > 1) ? argv[1] : "data/cube.pwn"); }
FEniCS/mshr
3rdparty/CGAL/examples/Point_set_shape_detection_3/shape_detection_with_callback.cpp
C++
gpl-3.0
3,227
[ 30522, 1001, 2065, 4225, 1006, 1035, 23794, 1035, 2310, 2099, 1007, 1004, 1004, 999, 4225, 1006, 1035, 2663, 21084, 1007, 1001, 10975, 8490, 2863, 5432, 1006, 4487, 19150, 1024, 4413, 22932, 1007, 1013, 1013, 12992, 1024, 1024, 2193, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_ #include <map> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_base_factory.h" class Profile; namespace base { class SequencedTaskRunner; } namespace content { class BrowserContext; } namespace policy { class UserCloudPolicyManagerChromeOS; // BrowserContextKeyedBaseFactory implementation // for UserCloudPolicyManagerChromeOS instances that initialize per-profile // cloud policy settings on ChromeOS. // // UserCloudPolicyManagerChromeOS is handled different than other // KeyedServices because it is a dependency of PrefService. // Therefore, lifetime of instances is managed by Profile, Profile startup code // invokes CreateForProfile() explicitly, takes ownership, and the instance // is only deleted after PrefService destruction. // // TODO(mnissler): Remove the special lifetime management in favor of // PrefService directly depending on UserCloudPolicyManagerChromeOS once the // former has been converted to a KeyedService. // See also http://crbug.com/131843 and http://crbug.com/131844. class UserCloudPolicyManagerFactoryChromeOS : public BrowserContextKeyedBaseFactory { public: // Returns an instance of the UserCloudPolicyManagerFactoryChromeOS singleton. static UserCloudPolicyManagerFactoryChromeOS* GetInstance(); // Returns the UserCloudPolicyManagerChromeOS instance associated with // |profile|. static UserCloudPolicyManagerChromeOS* GetForProfile(Profile* profile); // Creates an instance for |profile|. Note that the caller is responsible for // managing the lifetime of the instance. Subsequent calls to GetForProfile() // will return the created instance as long as it lives. // // If |force_immediate_load| is true, policy is loaded synchronously from // UserCloudPolicyStore at startup. static scoped_ptr<UserCloudPolicyManagerChromeOS> CreateForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner); private: friend struct DefaultSingletonTraits<UserCloudPolicyManagerFactoryChromeOS>; UserCloudPolicyManagerFactoryChromeOS(); virtual ~UserCloudPolicyManagerFactoryChromeOS(); // See comments for the static versions above. UserCloudPolicyManagerChromeOS* GetManagerForProfile(Profile* profile); scoped_ptr<UserCloudPolicyManagerChromeOS> CreateManagerForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner); // BrowserContextKeyedBaseFactory: virtual void BrowserContextShutdown( content::BrowserContext* context) OVERRIDE; virtual void BrowserContextDestroyed( content::BrowserContext* context) OVERRIDE; virtual void SetEmptyTestingFactory( content::BrowserContext* context) OVERRIDE; virtual void CreateServiceNow(content::BrowserContext* context) OVERRIDE; typedef std::map<Profile*, UserCloudPolicyManagerChromeOS*> ManagerMap; ManagerMap managers_; DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerFactoryChromeOS); }; } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_
patrickm/chromium.src
chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h
C
bsd-3-clause
3,587
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2286, 1996, 10381, 21716, 30524, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, 1013, 1013, 2179, 1999, 1996, 6105, 5371, 1012, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir)
quantumlib/ReCirq
recirq/readout_scan/tasks.py
Python
apache-2.0
4,314
[ 30522, 1001, 9385, 12609, 8224, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1001, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12646, 2007, 1996, 6105, 1012, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-google-v7) on Fri Jul 21 13:02:32 PDT 2017 --> <title>Resetter</title> <meta name="date" content="2017-07-21"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Resetter"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/annotation/RealObject.html" title="annotation in org.robolectric.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/annotation/Resetter.html" target="_top">Frames</a></li> <li><a href="Resetter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li>Optional</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Element</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.robolectric.annotation</div> <h2 title="Annotation Type Resetter" class="title">Annotation Type Resetter</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>@Documented @Retention(value=RUNTIME) @Target(value=METHOD) public @interface <span class="memberNameLabel">Resetter</span></pre> <div class="block"><p>Indicates that the annotated method is used to reset static state in a shadow.</p></div> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><script type="text/javascript" src="../../../highlight.pack.js"></script> <script type="text/javascript"><!-- hljs.initHighlightingOnLoad(); //--></script></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/annotation/RealObject.html" title="annotation in org.robolectric.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/annotation/Resetter.html" target="_top">Frames</a></li> <li><a href="Resetter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li>Optional</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Element</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
robolectric/robolectric.github.io
javadoc/3.4/org/robolectric/annotation/Resetter.html
HTML
mit
5,317
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * SuccessTest * * PHP version 5 * * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ /** * Coupons Api * * TrustAndUse coupons api in the swagger-2.0 specification * * OpenAPI spec version: 1.0.0 * Contact: sp@7indigo.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the model. */ namespace Swagger\Client; /** * SuccessTest Class Doc Comment * * @category Class */ // * @description Success /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ class SuccessTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test case */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test "Success" */ public function testSuccess() { } /** * Test attribute "success" */ public function testPropertySuccess() { } }
chanturia/TAU_PHP_API_CLIENT
test/Model/SuccessTest.php
PHP
apache-2.0
2,314
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 3112, 22199, 1008, 1008, 25718, 2544, 1019, 1008, 1008, 1030, 4696, 2465, 1008, 1030, 7427, 25430, 27609, 1032, 7396, 1008, 1030, 3166, 8299, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
"""Chapter 22 Practice Questions Answers Chapter 22 Practice Questions via Python code. """ from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage def main(): # 1. How many prime numbers are there? # Hint: Check page 322 message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES" #print(decryptMessage(blank, blank)) # Fill in the blanks # 2. What are integers that are not prime called? # Hint: Check page 323 message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS" #print(decryptMessage(blank, blank)) # Fill in the blanks # 3. What are two algorithms for finding prime numbers? # Hint: Check page 323 # Encrypted with key "ALGORITHMS" message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr." #print(decryptMessage(blank, blank)) # Fill in the blanks # If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
JoseALermaIII/python-tutorials
pythontutorials/books/CrackingCodes/Ch22/PracticeQuestions.py
Python
mit
1,117
[ 30522, 1000, 1000, 1000, 3127, 2570, 3218, 3980, 6998, 3127, 2570, 3218, 3980, 3081, 18750, 3642, 1012, 1000, 1000, 1000, 2013, 18750, 8525, 29469, 9777, 1012, 2808, 1012, 15729, 23237, 1012, 10381, 15136, 1012, 6819, 6914, 7869, 6895, 2792...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.webcurator.ui.target.controller; import static org.junit.Assert.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.webcurator.test.*; import org.webcurator.ui.common.Constants; import org.webcurator.ui.target.command.LogReaderCommand; import org.webcurator.core.harvester.coordinator.*; import org.webcurator.core.scheduler.*; import org.webcurator.domain.model.core.*; public class LogReaderControllerTest extends BaseWCTTest<LogReaderController>{ private TargetInstanceManager tim = null; private HarvestCoordinator hc = null; public LogReaderControllerTest() { super(LogReaderController.class, "src/test/java/org/webcurator/ui/target/controller/LogReaderControllerTest.xml"); } public void setUp() throws Exception { super.setUp(); tim = new MockTargetInstanceManager(testFile); hc = new MockHarvestCoordinator(); } private int countReturnedLines(String[] result) { assertNotNull(result); assertTrue(result.length == 2); if(result[0].equals("")) { return 0; } else { String[] lines = result[0].split("\n"); return lines.length; } } @Test public final void testHandleHead() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_HEAD); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTail() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TAIL); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,6), "4602. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleFromLine() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_FROM_LINE); aCmd.setFilter("5000"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 302); assertEquals(result[0].substring(0,6), "5000. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp1() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("2008-06-18T06:25:29"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp2() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("2008-06-18"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp3() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("18/06/2008 06:25:29"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp4() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("18/06/2008"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp5() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("20080618062529"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp6() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("bad format"); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 0); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertNotNull((String)mav.getModel().get(Constants.MESSAGE_TEXT)); assertTrue(((String)mav.getModel().get(Constants.MESSAGE_TEXT)).equals("bad format is not a valid date/time format")); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexMatch() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_MATCH); aCmd.setShowLineNumbers(false); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 1); assertFalse("1. ".equals(result[0].substring(0,3))); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexMatchLineNumbers() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_MATCH); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 1); assertEquals(result[0].substring(0,6), "5280. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexContain() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_CONTAIN); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 22); assertEquals(result[0].substring(0,6), "5280. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexIndent() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("local-errors.log"); aCmd.setFilter(".*SocketTimeoutException.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_INDENT); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 24); assertEquals(result[0].substring(0,4), "21. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testSetHarvestCoordinator() { try { testInstance.setHarvestCoordinator(hc); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testSetTargetInstanceManager() { try { testInstance.setTargetInstanceManager(tim); } catch(Exception e) { fail(e.getMessage()); } } }
DIA-NZ/webcurator
wct-core/src/test/java/org/webcurator/ui/target/controller/LogReaderControllerTest.java
Java
apache-2.0
17,452
[ 30522, 7427, 8917, 1012, 4773, 10841, 16259, 1012, 21318, 1012, 4539, 1012, 11486, 1025, 12324, 10763, 8917, 1012, 12022, 4183, 1012, 20865, 1012, 1008, 1025, 12324, 9262, 2595, 1012, 14262, 2615, 7485, 1012, 8299, 1012, 16770, 2121, 2615, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* runemacs --- Simple program to start Emacs with its console window hidden. Copyright (C) 2001-2021 Free Software Foundation, Inc. This file is part of GNU Emacs. GNU Emacs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GNU Emacs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */ /* Simple program to start Emacs with its console window hidden. This program is provided purely for convenience, since most users will use Emacs in windowing (GUI) mode, and will not want to have an extra console window lying around. */ /* You may want to define this if you want to be able to install updated emacs binaries even when other users are using the current version. The problem with some file servers (notably Novell) is that an open file cannot be overwritten, deleted, or even renamed. So if someone is running emacs.exe already, you cannot install a newer version. By defining CHOOSE_NEWEST_EXE, you can name your new emacs.exe something else which matches "emacs*.exe", and runemacs will automatically select the newest emacs executable in the bin directory. (So you'll probably be able to delete the old version some hours/days later). */ /* #define CHOOSE_NEWEST_EXE */ #define DEFER_MS_W32_H #include <config.h> #include <windows.h> #include <string.h> #include <malloc.h> static void set_user_model_id (void); static int ensure_unicows_dll (void); int WINAPI WinMain (HINSTANCE hSelf, HINSTANCE hPrev, LPSTR cmdline, int nShow) { STARTUPINFO start; SECURITY_ATTRIBUTES sec_attrs; PROCESS_INFORMATION child; int wait_for_child = FALSE; DWORD priority_class = NORMAL_PRIORITY_CLASS; DWORD ret_code = 0; char *new_cmdline; char *p; char modname[MAX_PATH]; static const char iconic_opt[] = "--iconic ", maximized_opt[] = "--maximized "; if (!ensure_unicows_dll ()) goto error; set_user_model_id (); if (!GetModuleFileName (NULL, modname, MAX_PATH)) goto error; if ((p = strrchr (modname, '\\')) == NULL) goto error; *p = 0; new_cmdline = alloca (MAX_PATH + strlen (cmdline) + ((nShow == SW_SHOWMINNOACTIVE || nShow == SW_SHOWMAXIMIZED) ? max (sizeof (iconic_opt), sizeof (maximized_opt)) : 0) + 3); /* Quote executable name in case of spaces in the path. */ *new_cmdline = '"'; strcpy (new_cmdline + 1, modname); /* Detect and handle un-installed runemacs.exe in nt/ subdirectory, while emacs.exe is in src/. */ if ((p = strrchr (new_cmdline, '\\')) != NULL && stricmp (p, "\\nt") == 0) strcpy (p, "\\src"); #ifdef CHOOSE_NEWEST_EXE { /* Silly hack to allow new versions to be installed on server even when current version is in use. */ char * best_name = alloca (MAX_PATH + 1); FILETIME best_time = {0,0}; WIN32_FIND_DATA wfd; HANDLE fh; p = new_cmdline + strlen (new_cmdline); strcpy (p, "\\emacs*.exe\" "); fh = FindFirstFile (new_cmdline, &wfd); if (fh == INVALID_HANDLE_VALUE) goto error; do { if (wfd.ftLastWriteTime.dwHighDateTime > best_time.dwHighDateTime || (wfd.ftLastWriteTime.dwHighDateTime == best_time.dwHighDateTime && wfd.ftLastWriteTime.dwLowDateTime > best_time.dwLowDateTime)) { best_time = wfd.ftLastWriteTime; strcpy (best_name, wfd.cFileName); } } while (FindNextFile (fh, &wfd)); FindClose (fh); *p++ = '\\'; strcpy (p, best_name); strcat (p, " "); } #else strcat (new_cmdline, "\\emacs.exe\" "); #endif /* Append original arguments if any; first look for arguments we recognize (-wait, -high, and -low), and apply them ourselves. */ while (cmdline[0] == '-' || cmdline[0] == '/') { if (strncmp (cmdline+1, "wait", 4) == 0) { wait_for_child = TRUE; cmdline += 5; } else if (strncmp (cmdline+1, "high", 4) == 0) { priority_class = HIGH_PRIORITY_CLASS; cmdline += 5; } else if (strncmp (cmdline+1, "low", 3) == 0) { priority_class = IDLE_PRIORITY_CLASS; cmdline += 4; } else break; /* Look for next argument. */ while (*++cmdline == ' '); } /* If the desktop shortcut properties tell to invoke runemacs minimized, or if they invoked runemacs via "start /min", pass '--iconic' to Emacs, as that's what users will expect. Likewise with invoking runemacs maximized: pass '--maximized' to Emacs. */ if (nShow == SW_SHOWMINNOACTIVE) strcat (new_cmdline, iconic_opt); else if (nShow == SW_SHOWMAXIMIZED) strcat (new_cmdline, maximized_opt); strcat (new_cmdline, cmdline); /* Set emacs_dir variable if runemacs was in "%emacs_dir%\bin". */ if ((p = strrchr (modname, '\\')) && stricmp (p, "\\bin") == 0) { *p = 0; for (p = modname; *p; p++) if (*p == '\\') *p = '/'; SetEnvironmentVariable ("emacs_dir", modname); } memset (&start, 0, sizeof (start)); start.cb = sizeof (start); start.dwFlags = STARTF_USESHOWWINDOW | STARTF_USECOUNTCHARS; start.wShowWindow = SW_HIDE; /* Ensure that we don't waste memory if the user has specified a huge default screen buffer for command windows. */ start.dwXCountChars = 80; start.dwYCountChars = 25; sec_attrs.nLength = sizeof (sec_attrs); sec_attrs.lpSecurityDescriptor = NULL; sec_attrs.bInheritHandle = FALSE; if (CreateProcess (NULL, new_cmdline, &sec_attrs, NULL, TRUE, priority_class, NULL, NULL, &start, &child)) { if (wait_for_child) { WaitForSingleObject (child.hProcess, INFINITE); GetExitCodeProcess (child.hProcess, &ret_code); } CloseHandle (child.hThread); CloseHandle (child.hProcess); } else goto error; return (int) ret_code; error: MessageBox (NULL, "Could not start Emacs.", "Error", MB_ICONSTOP); return 1; } void set_user_model_id (void) { HMODULE shell; HRESULT (WINAPI * set_user_model) (const wchar_t * id); /* On Windows 7 and later, we need to set the user model ID to associate emacsclient launched files with Emacs frames in the UI. */ shell = LoadLibrary ("shell32.dll"); if (shell) { set_user_model = (void *) GetProcAddress (shell, "SetCurrentProcessExplicitAppUserModelID"); /* If the function is defined, then we are running on Windows 7 or newer, and the UI uses this to group related windows together. Since emacs, runemacs, emacsclient are related, we want them grouped even though the executables are different, so we need to set a consistent ID between them. */ if (set_user_model) set_user_model (L"GNU.Emacs"); FreeLibrary (shell); } } static int ensure_unicows_dll (void) { OSVERSIONINFO os_ver; HMODULE h; ZeroMemory (&os_ver, sizeof (OSVERSIONINFO)); os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (!GetVersionEx (&os_ver)) return 0; if (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { h = LoadLibrary ("Unicows.dll"); if (!h) { int button; button = MessageBox (NULL, "Emacs cannot load the UNICOWS.DLL library.\n" "This library is essential for using Emacs\n" "on this system. You need to install it.\n\n" "Emacs will exit when you click OK.", "Emacs cannot load UNICOWS.DLL", MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_OK); switch (button) { case IDOK: default: return 0; } } FreeLibrary (h); return 1; } return 1; }
emacs-mirror/emacs
nt/runemacs.c
C
gpl-3.0
7,976
[ 30522, 1013, 1008, 23276, 22911, 2015, 1011, 1011, 1011, 3722, 2565, 2000, 2707, 7861, 6305, 2015, 2007, 2049, 10122, 3332, 5023, 1012, 9385, 1006, 1039, 1007, 2541, 1011, 25682, 2489, 4007, 3192, 1010, 4297, 1012, 2023, 5371, 2003, 2112, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/bin/bash FN="HsAgilentDesign026652.db_3.2.3.tar.gz" URLS=( "https://bioconductor.org/packages/3.11/data/annotation/src/contrib/HsAgilentDesign026652.db_3.2.3.tar.gz" "https://bioarchive.galaxyproject.org/HsAgilentDesign026652.db_3.2.3.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz" ) MD5="dcd2c748bf9d7c002611cd5cf2ff38c0" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
roryk/recipes
recipes/bioconductor-hsagilentdesign026652.db/post-link.sh
Shell
mit
1,510
[ 30522, 1001, 999, 1013, 8026, 1013, 24234, 1042, 2078, 1027, 1000, 26236, 22974, 16136, 6155, 23773, 2692, 23833, 26187, 2475, 1012, 16962, 1035, 1017, 1012, 1016, 1012, 1017, 1012, 16985, 1012, 1043, 2480, 1000, 24471, 4877, 1027, 1006, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
jQuery.fn.nextInArray = function(element) { var nextId = 0; for(var i = 0; i < this.length; i++) { if(this[i] == element) { nextId = i + 1; break; } } if(nextId > this.length-1) nextId = 0; return this[nextId]; }; jQuery.fn.clearForm = function() { return this.each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form') return jQuery(':input', this).clearForm(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; jQuery.fn.tagName = function() { return this.get(0).tagName; }; jQuery.fn.exists = function(){ return (jQuery(this).size() > 0 ? true : false); }; function isNumber(val) { return /^\d+/.test(val); } jQuery.fn.serializeAnything = function(addData) { var toReturn = []; var els = jQuery(this).find(':input').get(); jQuery.each(els, function() { if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) { var val = jQuery(this).val(); toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) ); } }); if(typeof(addData) != 'undefined') { for(var key in addData) toReturn.push(key + "=" + addData[key]); } return toReturn.join("&").replace(/%20/g, "+"); }; jQuery.fn.hasScrollBarH = function() { return this.get(0).scrollHeight > this.height(); }; jQuery.fn.hasScrollBarV = function() { console.log(this.get(0).scrollWidth, this.width(), this.get(0).scrollHeight, this.height()); return this.get(0).scrollWidth > this.width(); }; function str_replace(haystack, needle, replacement) { var temp = haystack.split(needle); return temp.join(replacement); } /** * @see php html::nameToClassId($name) method **/ function nameToClassId(name) { return str_replace( str_replace(name, ']', ''), '[', '' ); } function strpos( haystack, needle, offset){ var i = haystack.indexOf( needle, offset ); // returns -1 return i >= 0 ? i : false; } function extend(Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; } function toeRedirect(url) { document.location.href = url; } function toeReload() { document.location.reload(); } jQuery.fn.toeRebuildSelect = function(data, useIdAsValue, val) { if(jQuery(this).tagName() == 'SELECT' && typeof(data) == 'object') { if(jQuery(data).size() > 0) { if(typeof(val) == 'undefined') val = false; if(jQuery(this).children('option').length) { jQuery(this).children('option').remove(); } if(typeof(useIdAsValue) == 'undefined') useIdAsValue = false; var selected = ''; for(var id in data) { selected = ''; if(val && ((useIdAsValue && id == val) || (data[id] == val))) selected = 'selected'; jQuery(this).append('<option value="'+ (useIdAsValue ? id : data[id])+ '" '+ selected+ '>'+ data[id]+ '</option>'); } } } } /** * We will not use just jQUery.inArray because it is work incorrect for objects * @return mixed - key that was found element or -1 if not */ function toeInArray(needle, haystack) { if(typeof(haystack) == 'object') { for(var k in haystack) { if(haystack[ k ] == needle) return k; } } else if(typeof(haystack) == 'array') { return jQuery.inArray(needle, haystack); } return -1; } jQuery.fn.setReadonly = function() { jQuery(this).addClass('toeReadonly').attr('readonly', 'readonly'); } jQuery.fn.unsetReadonly = function() { jQuery(this).removeClass('toeReadonly').removeAttr('readonly', 'readonly'); } jQuery.fn.getClassId = function(pref, test) { var classId = jQuery(this).attr('class'); classId = classId.substr( strpos(classId, pref+ '_') ); if(strpos(classId, ' ')) classId = classId.substr( 0, strpos(classId, ' ') ); classId = classId.split('_'); classId = classId[1]; return classId; } function toeTextIncDec(textFieldId, inc) { var value = parseInt(jQuery('#'+ textFieldId).val()); if(isNaN(value)) value = 0; if(!(inc < 0 && value < 1)) { value += inc; } jQuery('#'+ textFieldId).val(value); } /** * Make first letter of string in upper case * @param str string - string to convert * @return string converted string - first letter in upper case */ function toeStrFirstUp(str) { str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); } function parseStr (str, array) { // http://kevin.vanzonneveld.net // + original by: Cagri Ekin // + improved by: Michael White (http://getsprink.com) // + tweaked by: Jack // + bugfixed by: Onno Marsman // + reimplemented by: stag019 // + bugfixed by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: stag019 // + input by: Dreamer // + bugfixed by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/) // + input by: Zaide (http://zaidesthings.com/) // + input by: David Pesta (http://davidpesta.com/) // + input by: jeicquest // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: When no argument is specified, will put variables in global scope. // % note 1: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c // * example 1: var arr = {}; // * example 1: parse_str('first=foo&second=bar', arr); // * results 1: arr == { first: 'foo', second: 'bar' } // * example 2: var arr = {}; // * example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr); // * results 2: arr == { str_a: "Jack and Jill didn't see the well." } // * example 3: var abc = {3:'a'}; // * example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5'); // * results 3: JSON.stringify(abc) === '{"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}'; var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&'), sal = strArr.length, i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value, postLeftBracketPos, keys, keysLen, fixStr = function (str) { return decodeURIComponent(str.replace(/\+/g, '%20')); }; // Comented by Alexey Bolotov /* if (!array) { array = this.window; }*/ if (!array) { array = {}; } for (i = 0; i < sal; i++) { tmp = strArr[i].split('='); key = fixStr(tmp[0]); value = (tmp.length < 2) ? '' : fixStr(tmp[1]); while (key.charAt(0) === ' ') { key = key.slice(1); } if (key.indexOf('\x00') > -1) { key = key.slice(0, key.indexOf('\x00')); } if (key && key.charAt(0) !== '[') { keys = []; postLeftBracketPos = 0; for (j = 0; j < key.length; j++) { if (key.charAt(j) === '[' && !postLeftBracketPos) { postLeftBracketPos = j + 1; } else if (key.charAt(j) === ']') { if (postLeftBracketPos) { if (!keys.length) { keys.push(key.slice(0, postLeftBracketPos - 1)); } keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos)); postLeftBracketPos = 0; if (key.charAt(j + 1) !== '[') { break; } } } } if (!keys.length) { keys = [key]; } for (j = 0; j < keys[0].length; j++) { chr = keys[0].charAt(j); if (chr === ' ' || chr === '.' || chr === '[') { keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1); } if (chr === '[') { break; } } obj = array; for (j = 0, keysLen = keys.length; j < keysLen; j++) { key = keys[j].replace(/^['"]/, '').replace(/['"]$/, ''); lastIter = j !== keys.length - 1; lastObj = obj; if ((key !== '' && key !== ' ') || j === 0) { if (obj[key] === undef) { obj[key] = {}; } obj = obj[key]; } else { // To insert new dimension ct = -1; for (p in obj) { if (obj.hasOwnProperty(p)) { if (+p > ct && p.match(/^\d+$/g)) { ct = +p; } } } key = ct + 1; } } lastObj[key] = value; } } return array; } function toeListable(params) { this.params = jQuery.extend({}, params); this.table = jQuery(this.params.table); this.paging = jQuery(this.params.paging); this.perPage = this.params.perPage; this.list = this.params.list; this.count = this.params.count; this.page = this.params.page; this.pagingCallback = this.params.pagingCallback; var self = this; this.draw = function(list, count) { this.table.find('tr').not('.gmpExample, .gmpTblHeader').remove(); var exampleRow = this.table.find('.gmpExample'); for(var i in list) { var newRow = exampleRow.clone(); for(var key in list[i]) { var element = newRow.find('.'+ key); if(element.size()) { var valueTo = element.attr('valueTo'); if(valueTo) { var newValue = list[i][key]; var prevValue = element.attr(valueTo); if(prevValue) newValue = prevValue+ ' '+ newValue; element.attr(valueTo, newValue); } else element.html(list[i][key]); } } newRow.removeClass('gmpExample').show(); this.table.append(newRow); } if(this.paging) { this.paging.html(''); if(count && count > list.length && this.perPage) { for(var i = 1; i <= Math.ceil(count/this.perPage); i++) { var newPageId = i-1 , newElement = (newPageId == this.page) ? jQuery('<b/>') : jQuery('<a/>'); if(newPageId != this.page) { newElement.attr('href', '#'+ newPageId) .click(function(){ if(self.pagingCallback && typeof(self.pagingCallback) == 'function') { self.pagingCallback(parseInt(jQuery(this).attr('href').replace('#', ''))); return false; } }); } newElement.addClass('toePagingElement').html(i); this.paging.append(newElement); } } } } if(this.list) this.draw(this.list, this.count); } function setCookieGmp(c_name, value, exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function getCookieGmp(name) { var parts = document.cookie.split(name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); return null; } function getImgSize(url, callback) { jQuery('<img/>').attr('src', url).load(function(){ callback({w: this.width, h: this.height}); }); } function callUserFuncArray(cb, parameters) { // http://kevin.vanzonneveld.net // + original by: Thiago Mata (http://thiagomata.blog.com) // + revised by: Jon Hohle // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Diplom@t (http://difane.com/) // + improved by: Brett Zamir (http://brett-zamir.me) // * example 1: call_user_func_array('isNaN', ['a']); // * returns 1: true // * example 2: call_user_func_array('isNaN', [1]); // * returns 2: false var func; if (typeof cb === 'string') { func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))(); } else if (Object.prototype.toString.call(cb) === '[object Array]') { func = (typeof cb[0] == 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]]; } else if (typeof cb === 'function') { func = cb; } if (typeof func !== 'function') { throw new Error(func + ' is not a valid function'); } return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply(null, parameters) : func.apply(cb[0], parameters); }
nikakoss/arsenal-media.net
wp-content/plugins/google-maps-ready/js/common.js
JavaScript
gpl-2.0
12,013
[ 30522, 1046, 4226, 2854, 1012, 1042, 2078, 1012, 2279, 3981, 11335, 2100, 1027, 3853, 1006, 5783, 1007, 1063, 13075, 2279, 3593, 1027, 1014, 1025, 2005, 1006, 13075, 1045, 1027, 1014, 1025, 1045, 1026, 2023, 1012, 3091, 1025, 1045, 1009, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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. * * Authors: * Jackie Li<yaodong.li@intel.com> */ #include <linux/freezer.h> #include "mdfld_dsi_output.h" #include "mdfld_dsi_pkg_sender.h" #include "mdfld_dsi_dbi.h" #include "mdfld_dsi_dpi.h" #define MDFLD_DSI_DBI_FIFO_TIMEOUT 1000 #define MDFLD_DSI_MAX_RETURN_PACKET_SIZE 512 #define MDFLD_DSI_READ_MAX_COUNT 10000 const char *dsi_errors[] = { "[ 0:RX SOT Error]", "[ 1:RX SOT Sync Error]", "[ 2:RX EOT Sync Error]", "[ 3:RX Escape Mode Entry Error]", "[ 4:RX LP TX Sync Error", "[ 5:RX HS Receive Timeout Error]", "[ 6:RX False Control Error]", "[ 7:RX ECC Single Bit Error]", "[ 8:RX ECC Multibit Error]", "[ 9:RX Checksum Error]", "[10:RX DSI Data Type Not Recognised]", "[11:RX DSI VC ID Invalid]", "[12:TX False Control Error]", "[13:TX ECC Single Bit Error]", "[14:TX ECC Multibit Error]", "[15:TX Checksum Error]", "[16:TX DSI Data Type Not Recognised]", "[17:TX DSI VC ID invalid]", "[18:High Contention]", "[19:Low contention]", "[20:DPI FIFO Under run]", "[21:HS TX Timeout]", "[22:LP RX Timeout]", "[23:Turn Around ACK Timeout]", "[24:ACK With No Error]", "[25:RX Invalid TX Length]", "[26:RX Prot Violation]", "[27:HS Generic Write FIFO Full]", "[28:LP Generic Write FIFO Full]", "[29:Generic Read Data Avail]", "[30:Special Packet Sent]", "[31:Tearing Effect]", }; static inline int wait_for_gen_fifo_empty(struct mdfld_dsi_pkg_sender *sender, u32 mask) { struct drm_device *dev = sender->dev; u32 gen_fifo_stat_reg = sender->mipi_gen_fifo_stat_reg; int retry = 10000; while (retry--) { if ((mask & REG_READ(gen_fifo_stat_reg)) == mask) return 0; udelay(3); } DRM_ERROR("fifo is NOT empty 0x%08x\n", REG_READ(gen_fifo_stat_reg)); sender->status = MDFLD_DSI_CONTROL_ABNORMAL; return -EIO; } static int wait_for_all_fifos_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_gen_fifo_empty(sender, (BIT2 | BIT10 | BIT18 | BIT26 | BIT27 | BIT28)); } static int wait_for_lp_fifos_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_gen_fifo_empty(sender, (BIT10 | BIT26)); } static int wait_for_hs_fifos_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_gen_fifo_empty(sender, (BIT2 | BIT18)); } static int wait_for_dbi_fifo_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_gen_fifo_empty(sender, (BIT27)); } static int wait_for_dpi_fifo_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_gen_fifo_empty(sender, (BIT28)); } static int dsi_error_handler(struct mdfld_dsi_pkg_sender *sender) { struct drm_device *dev = sender->dev; u32 intr_stat_reg = sender->mipi_intr_stat_reg; int i; u32 mask; int err = 0; int count = 0; u32 intr_stat; intr_stat = REG_READ(intr_stat_reg); if (!intr_stat) return 0; for (i = 0; i < 32; i++) { mask = (0x00000001UL) << i; if (!(intr_stat & mask)) continue; switch (mask) { case BIT0: case BIT1: case BIT2: case BIT3: case BIT4: case BIT5: case BIT6: case BIT7: case BIT8: case BIT9: case BIT10: case BIT11: case BIT12: case BIT13: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT14: DRM_INFO("dsi status %s\n", dsi_errors[i]); break; case BIT15: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT16: DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT17: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT18: REG_WRITE(MIPIA_EOT_DISABLE_REG, REG_READ(MIPIA_EOT_DISABLE_REG)|0x30); while ((REG_READ(intr_stat_reg) & BIT18)) { count++; /* * Per silicon feedback, if this bit cannot be * cleared by 3 times, it should be a real * High Contention error. */ if (count == 4) { DRM_INFO("dsi status %s\n", dsi_errors[i]); break; } REG_WRITE(intr_stat_reg, mask); } break; case BIT19: DRM_INFO("dsi status %s\n", dsi_errors[i]); break; case BIT20: /*No Action required.*/ DRM_DEBUG("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT21: DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); err = wait_for_all_fifos_empty(sender); break; case BIT22: DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); err = wait_for_all_fifos_empty(sender); break; case BIT23: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT24: /*No Action required.*/ DRM_DEBUG("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT25: case BIT26: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); break; case BIT27: DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); err = wait_for_hs_fifos_empty(sender); break; case BIT28: DRM_INFO("dsi status %s\n", dsi_errors[i]); REG_WRITE(intr_stat_reg, mask); err = wait_for_lp_fifos_empty(sender); break; case BIT29: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); break; case BIT30: break; case BIT31: /*No Action required.*/ DRM_INFO("dsi status %s\n", dsi_errors[i]); break; } } return err; } static inline int dbi_cmd_sent(struct mdfld_dsi_pkg_sender *sender) { struct drm_device *dev = sender->dev; u32 retry = 0xffff; u32 dbi_cmd_addr_reg = sender->mipi_cmd_addr_reg; int ret = 0; /*query the command execution status*/ while (retry--) { if (!(REG_READ(dbi_cmd_addr_reg) & BIT0)) break; } if (!retry) { DRM_ERROR("Timeout waiting for DBI Command status\n"); ret = -EAGAIN; } return ret; } /** * NOTE: this interface is abandoned expect for write_mem_start DCS * other DCS are sent via generic pkg interfaces */ static int send_dcs_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { struct drm_device *dev = sender->dev; struct mdfld_dsi_dcs_pkg *dcs_pkg = &pkg->pkg.dcs_pkg; u32 dbi_cmd_len_reg = sender->mipi_cmd_len_reg; u32 dbi_cmd_addr_reg = sender->mipi_cmd_addr_reg; u32 cb_phy = sender->dbi_cb_phy; u32 index = 0; u8 *cb = (u8 *)sender->dbi_cb_addr; int i; int ret; if (!sender->dbi_pkg_support) { DRM_ERROR("Trying to send DCS on a non DBI output, abort!\n"); return -ENOTSUPP; } PSB_DEBUG_MIPI("Sending DCS pkg 0x%x...\n", dcs_pkg->cmd); /*wait for DBI fifo empty*/ wait_for_dbi_fifo_empty(sender); *(cb + (index++)) = dcs_pkg->cmd; if (dcs_pkg->param_num) { for (i = 0; i < dcs_pkg->param_num; i++) { *(cb + (index++)) = *(dcs_pkg->param + i); } } REG_WRITE(dbi_cmd_len_reg, (1 + dcs_pkg->param_num)); REG_WRITE(dbi_cmd_addr_reg, (cb_phy << CMD_MEM_ADDR_OFFSET) | BIT0 | ((dcs_pkg->data_src == CMD_DATA_SRC_PIPE) ? BIT1 : 0)); ret = dbi_cmd_sent(sender); if (ret) { DRM_ERROR("command 0x%x not complete\n", dcs_pkg->cmd); return -EAGAIN; } PSB_DEBUG_MIPI("sent DCS pkg 0x%x...\n", dcs_pkg->cmd); return 0; } static int __send_short_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { struct drm_device *dev = sender->dev; u32 hs_gen_ctrl_reg = sender->mipi_hs_gen_ctrl_reg; u32 lp_gen_ctrl_reg = sender->mipi_lp_gen_ctrl_reg; u32 gen_ctrl_val = 0; struct mdfld_dsi_gen_short_pkg *short_pkg = &pkg->pkg.short_pkg; gen_ctrl_val |= short_pkg->cmd << MCS_COMMANDS_POS; gen_ctrl_val |= 0 << DCS_CHANNEL_NUMBER_POS; gen_ctrl_val |= pkg->pkg_type; gen_ctrl_val |= short_pkg->param << MCS_PARAMETER_POS; if (pkg->transmission_type == MDFLD_DSI_HS_TRANSMISSION) { /*wait for hs fifo empty*/ wait_for_dbi_fifo_empty(sender); wait_for_hs_fifos_empty(sender); /*send pkg*/ REG_WRITE(hs_gen_ctrl_reg, gen_ctrl_val); } else if (pkg->transmission_type == MDFLD_DSI_LP_TRANSMISSION) { wait_for_dbi_fifo_empty(sender); wait_for_lp_fifos_empty(sender); /*send pkg*/ REG_WRITE(lp_gen_ctrl_reg, gen_ctrl_val); } else { DRM_ERROR("Unknown transmission type %d\n", pkg->transmission_type); return -EINVAL; } return 0; } static int __send_long_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { struct drm_device *dev = sender->dev; u32 hs_gen_ctrl_reg = sender->mipi_hs_gen_ctrl_reg; u32 hs_gen_data_reg = sender->mipi_hs_gen_data_reg; u32 lp_gen_ctrl_reg = sender->mipi_lp_gen_ctrl_reg; u32 lp_gen_data_reg = sender->mipi_lp_gen_data_reg; u32 gen_ctrl_val = 0; u8 *dp = NULL; u32 reg_val = 0; int i; int dword_count = 0, remain_byte_count = 0; struct mdfld_dsi_gen_long_pkg *long_pkg = &pkg->pkg.long_pkg; dp = long_pkg->data; /** * Set up word count for long pkg * FIXME: double check word count field. * currently, using the byte counts of the payload as the word count. * ------------------------------------------------------------ * | DI | WC | ECC| PAYLOAD |CHECKSUM| * ------------------------------------------------------------ */ gen_ctrl_val |= (long_pkg->len) << WORD_COUNTS_POS; gen_ctrl_val |= 0 << DCS_CHANNEL_NUMBER_POS; gen_ctrl_val |= pkg->pkg_type; if (pkg->transmission_type == MDFLD_DSI_HS_TRANSMISSION) { /*wait for hs ctrl and data fifos to be empty*/ wait_for_dbi_fifo_empty(sender); wait_for_hs_fifos_empty(sender); dword_count = long_pkg->len / 4; remain_byte_count = long_pkg->len % 4; for (i = 0; i < dword_count * 4; i = i + 4) { reg_val = 0; reg_val = *(dp + i); reg_val |= *(dp + i + 1) << 8; reg_val |= *(dp + i + 2) << 16; reg_val |= *(dp + i + 3) << 24; PSB_DEBUG_MIPI("HS Sending data 0x%08x\n", reg_val); REG_WRITE(hs_gen_data_reg, reg_val); } if (remain_byte_count) { reg_val = 0; for (i = 0; i < remain_byte_count; i++) reg_val |= *(dp + dword_count * 4 + i) << (8 * i); PSB_DEBUG_MIPI("HS Sending data 0x%08x\n", reg_val); REG_WRITE(hs_gen_data_reg, reg_val); } REG_WRITE(hs_gen_ctrl_reg, gen_ctrl_val); } else if (pkg->transmission_type == MDFLD_DSI_LP_TRANSMISSION) { wait_for_dbi_fifo_empty(sender); wait_for_lp_fifos_empty(sender); dword_count = long_pkg->len / 4; remain_byte_count = long_pkg->len % 4; for (i = 0; i < dword_count * 4; i = i + 4) { reg_val = 0; reg_val = *(dp + i); reg_val |= *(dp + i + 1) << 8; reg_val |= *(dp + i + 2) << 16; reg_val |= *(dp + i + 3) << 24; PSB_DEBUG_MIPI("LP Sending data 0x%08x\n", reg_val); REG_WRITE(lp_gen_data_reg, reg_val); } if (remain_byte_count) { reg_val = 0; for (i = 0; i < remain_byte_count; i++) { reg_val |= *(dp + dword_count * 4 + i) << (8 * i); } PSB_DEBUG_MIPI("LP Sending data 0x%08x\n", reg_val); REG_WRITE(lp_gen_data_reg, reg_val); } REG_WRITE(lp_gen_ctrl_reg, gen_ctrl_val); } else { DRM_ERROR("Unknown transmission type %d\n", pkg->transmission_type); return -EINVAL; } return 0; } static int send_mcs_short_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { PSB_DEBUG_MIPI("Sending MCS short pkg...\n"); return __send_short_pkg(sender, pkg); } static int send_mcs_long_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { PSB_DEBUG_MIPI("Sending MCS long pkg...\n"); return __send_long_pkg(sender, pkg); } static int send_gen_short_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { PSB_DEBUG_MIPI("Sending GEN short pkg...\n"); return __send_short_pkg(sender, pkg); } static int send_gen_long_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { PSB_DEBUG_MIPI("Sending GEN long pkg...\n"); return __send_long_pkg(sender, pkg); } static int send_dpi_spk_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { struct drm_device *dev = sender->dev; u32 dpi_control_reg = sender->mipi_dpi_control_reg; u32 intr_stat_reg = sender->mipi_intr_stat_reg; u32 dpi_control_val = 0; u32 dpi_control_current_setting = 0; struct mdfld_dsi_dpi_spk_pkg *spk_pkg = &pkg->pkg.spk_pkg; int retry = 10000; dpi_control_val = spk_pkg->cmd; if (pkg->transmission_type == MDFLD_DSI_LP_TRANSMISSION) dpi_control_val |= BIT6; /*Wait for DPI fifo empty*/ wait_for_dpi_fifo_empty(sender); /*clean spk packet sent interrupt*/ REG_WRITE(intr_stat_reg, BIT30); dpi_control_current_setting = REG_READ(dpi_control_reg); /*send out spk packet*/ if (dpi_control_current_setting != dpi_control_val) { REG_WRITE(dpi_control_reg, dpi_control_val); /*wait for spk packet sent interrupt*/ while (--retry && !(REG_READ(intr_stat_reg) & BIT30)) udelay(3); if (!retry) { DRM_ERROR("Fail to send SPK Packet 0x%x\n", spk_pkg->cmd); return -EINVAL; } } else /*For SHUT_DOWN and TURN_ON, it is better called by symmetrical. so skip duplicate called*/ printk(KERN_WARNING "skip duplicate setting of DPI control\n"); return 0; } static int send_pkg_prepare(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { u8 cmd; u8 *data; PSB_DEBUG_MIPI("Prepare to Send type 0x%x pkg\n", pkg->pkg_type); switch (pkg->pkg_type) { case MDFLD_DSI_PKG_DCS: cmd = pkg->pkg.dcs_pkg.cmd; break; case MDFLD_DSI_PKG_MCS_SHORT_WRITE_0: case MDFLD_DSI_PKG_MCS_SHORT_WRITE_1: cmd = pkg->pkg.short_pkg.cmd; break; case MDFLD_DSI_PKG_MCS_LONG_WRITE: data = (u8 *)pkg->pkg.long_pkg.data; cmd = *data; break; default: return 0; } /*this prevents other package sending while doing msleep*/ sender->status = MDFLD_DSI_PKG_SENDER_BUSY; return 0; } static int send_pkg_done(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { u8 cmd; u8 *data = NULL; PSB_DEBUG_MIPI("Sent type 0x%x pkg\n", pkg->pkg_type); switch (pkg->pkg_type) { case MDFLD_DSI_PKG_DCS: cmd = pkg->pkg.dcs_pkg.cmd; break; case MDFLD_DSI_PKG_MCS_SHORT_WRITE_0: case MDFLD_DSI_PKG_MCS_SHORT_WRITE_1: cmd = pkg->pkg.short_pkg.cmd; break; case MDFLD_DSI_PKG_MCS_LONG_WRITE: case MDFLD_DSI_PKG_GEN_LONG_WRITE: data = (u8 *)pkg->pkg.long_pkg.data; cmd = *data; break; default: return 0; } /*update panel status*/ if (unlikely(cmd == enter_sleep_mode)) sender->panel_mode |= MDFLD_DSI_PANEL_MODE_SLEEP; else if (unlikely(cmd == exit_sleep_mode)) sender->panel_mode &= ~MDFLD_DSI_PANEL_MODE_SLEEP; if (sender->status != MDFLD_DSI_CONTROL_ABNORMAL) sender->status = MDFLD_DSI_PKG_SENDER_FREE; /*after sending pkg done, free the data buffer for mcs long pkg*/ if (pkg->pkg_type == MDFLD_DSI_PKG_MCS_LONG_WRITE || pkg->pkg_type == MDFLD_DSI_PKG_GEN_LONG_WRITE) { if (data != NULL) kfree(data); } return 0; } static int do_send_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { int ret = 0; PSB_DEBUG_MIPI("Sending type 0x%x pkg\n", pkg->pkg_type); if (sender->status == MDFLD_DSI_PKG_SENDER_BUSY) { DRM_ERROR("sender is busy\n"); return -EAGAIN; } ret = send_pkg_prepare(sender, pkg); if (ret) { DRM_ERROR("send_pkg_prepare error\n"); return ret; } switch (pkg->pkg_type) { case MDFLD_DSI_PKG_DCS: ret = send_dcs_pkg(sender, pkg); break; case MDFLD_DSI_PKG_GEN_SHORT_WRITE_0: case MDFLD_DSI_PKG_GEN_SHORT_WRITE_1: case MDFLD_DSI_PKG_GEN_SHORT_WRITE_2: case MDFLD_DSI_PKG_GEN_READ_0: case MDFLD_DSI_PKG_GEN_READ_1: case MDFLD_DSI_PKG_GEN_READ_2: ret = send_gen_short_pkg(sender, pkg); break; case MDFLD_DSI_PKG_GEN_LONG_WRITE: ret = send_gen_long_pkg(sender, pkg); break; case MDFLD_DSI_PKG_MCS_SHORT_WRITE_0: case MDFLD_DSI_PKG_MCS_SHORT_WRITE_1: case MDFLD_DSI_PKG_MCS_READ: ret = send_mcs_short_pkg(sender, pkg); break; case MDFLD_DSI_PKG_MCS_LONG_WRITE: ret = send_mcs_long_pkg(sender, pkg); break; case MDFLD_DSI_DPI_SPK: ret = send_dpi_spk_pkg(sender, pkg); break; default: DRM_ERROR("Invalid pkg type 0x%x\n", pkg->pkg_type); ret = -EINVAL; } send_pkg_done(sender, pkg); return ret; } static int send_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { int err = 0; /*handle DSI error*/ err = dsi_error_handler(sender); if (err) { DRM_ERROR("Error handling failed\n"); err = -EAGAIN; goto send_pkg_err; } /*send pkg*/ err = do_send_pkg(sender, pkg); if (err) { DRM_ERROR("sent pkg failed\n"); dsi_error_handler(sender); err = -EAGAIN; goto send_pkg_err; } /*FIXME: should I query complete and fifo empty here?*/ send_pkg_err: return err; } static struct mdfld_dsi_pkg * pkg_sender_get_pkg_locked(struct mdfld_dsi_pkg_sender *sender) { struct mdfld_dsi_pkg *pkg; if (list_empty(&sender->free_list)) { DRM_ERROR("No free pkg left\n"); return NULL; } pkg = list_first_entry(&sender->free_list, struct mdfld_dsi_pkg, entry); /*detach from free list*/ list_del_init(&pkg->entry); return pkg; } static void pkg_sender_put_pkg_locked(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg) { memset(pkg, 0, sizeof(struct mdfld_dsi_pkg)); INIT_LIST_HEAD(&pkg->entry); list_add_tail(&pkg->entry, &sender->free_list); } static int mdfld_dbi_cb_init(struct mdfld_dsi_pkg_sender *sender, struct psb_gtt *pg, int pipe) { uint32_t phy; void *virt_addr = NULL; switch (pipe) { case 0: phy = pg->gtt_phys_start - 0x1000; break; case 2: phy = pg->gtt_phys_start - 0x800; break; default: DRM_ERROR("Unsupported channel\n"); return -EINVAL; } /*mapping*/ virt_addr = ioremap_nocache(phy, 0x800); if (!virt_addr) { DRM_ERROR("Map DBI command buffer error\n"); return -ENOMEM; } sender->dbi_cb_phy = phy; sender->dbi_cb_addr = virt_addr; PSB_DEBUG_ENTRY("DBI command buffer initailized. phy %x, addr %p\n", phy, virt_addr); return 0; } static void mdfld_dbi_cb_destroy(struct mdfld_dsi_pkg_sender *sender) { PSB_DEBUG_ENTRY("\n"); if (sender && sender->dbi_cb_addr) iounmap(sender->dbi_cb_addr); } static inline void pkg_sender_queue_pkg(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg, int delay) { unsigned long flags; if (pkg->transmission_type == MDFLD_DSI_HS_TRANSMISSION) wait_for_hs_fifos_empty(sender); else if (pkg->transmission_type == MDFLD_DSI_LP_TRANSMISSION) wait_for_lp_fifos_empty(sender); spin_lock_irqsave(&sender->lock, flags); if (!delay) { send_pkg(sender, pkg); pkg_sender_put_pkg_locked(sender, pkg); } else { /*queue it*/ list_add_tail(&pkg->entry, &sender->pkg_list); } spin_unlock_irqrestore(&sender->lock, flags); } static inline int process_pkg_list(struct mdfld_dsi_pkg_sender *sender) { struct mdfld_dsi_pkg *pkg; unsigned long flags; int ret = 0; spin_lock_irqsave(&sender->lock, flags); while (!list_empty(&sender->pkg_list)) { pkg = list_first_entry(&sender->pkg_list, struct mdfld_dsi_pkg, entry); ret = send_pkg(sender, pkg); if (ret) { DRM_INFO("Returning eror from process_pkg_lisgt"); goto errorunlock; } list_del_init(&pkg->entry); pkg_sender_put_pkg_locked(sender, pkg); } spin_unlock_irqrestore(&sender->lock, flags); return 0; errorunlock: spin_unlock_irqrestore(&sender->lock, flags); return ret; } static int mdfld_dsi_send_mcs_long(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, u8 transmission, int delay) { struct mdfld_dsi_pkg *pkg; unsigned long flags; u8 *pdata = NULL; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } /* alloc a data buffer to save the long pkg data, * free the buffer when send_pkg_done. * */ pdata = kmalloc(sizeof(u8) * len, GFP_KERNEL); if (!pdata) { DRM_ERROR("No memory for long_pkg data\n"); return -ENOMEM; } memcpy(pdata, data, len * sizeof(u8)); pkg->pkg_type = MDFLD_DSI_PKG_MCS_LONG_WRITE; pkg->transmission_type = transmission; pkg->pkg.long_pkg.data = pdata; pkg->pkg.long_pkg.len = len; INIT_LIST_HEAD(&pkg->entry); pkg_sender_queue_pkg(sender, pkg, delay); return 0; } static int mdfld_dsi_send_mcs_short(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 param, u8 param_num, u8 transmission, int delay) { struct mdfld_dsi_pkg *pkg; unsigned long flags; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } if (param_num) { pkg->pkg_type = MDFLD_DSI_PKG_MCS_SHORT_WRITE_1; pkg->pkg.short_pkg.param = param; } else { pkg->pkg_type = MDFLD_DSI_PKG_MCS_SHORT_WRITE_0; pkg->pkg.short_pkg.param = 0; } pkg->transmission_type = transmission; pkg->pkg.short_pkg.cmd = cmd; INIT_LIST_HEAD(&pkg->entry); pkg_sender_queue_pkg(sender, pkg, delay); return 0; } static int mdfld_dsi_send_gen_short(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, u8 transmission, int delay) { struct mdfld_dsi_pkg *pkg; unsigned long flags; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } switch (param_num) { case 0: pkg->pkg_type = MDFLD_DSI_PKG_GEN_SHORT_WRITE_0; pkg->pkg.short_pkg.cmd = 0; pkg->pkg.short_pkg.param = 0; break; case 1: pkg->pkg_type = MDFLD_DSI_PKG_GEN_SHORT_WRITE_1; pkg->pkg.short_pkg.cmd = param0; pkg->pkg.short_pkg.param = 0; break; case 2: pkg->pkg_type = MDFLD_DSI_PKG_GEN_SHORT_WRITE_2; pkg->pkg.short_pkg.cmd = param0; pkg->pkg.short_pkg.param = param1; break; } pkg->transmission_type = transmission; INIT_LIST_HEAD(&pkg->entry); pkg_sender_queue_pkg(sender, pkg, delay); return 0; } static int mdfld_dsi_send_gen_long(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, u8 transmission, int delay) { struct mdfld_dsi_pkg *pkg; unsigned long flags; u8 *pdata = NULL; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } /* alloc a data buffer to save the long pkg data, * free the buffer when send_pkg_done. * */ pdata = kmalloc(sizeof(u8)*len, GFP_KERNEL); if (!pdata) { DRM_ERROR("No memory for long_pkg data\n"); return -ENOMEM; } memcpy(pdata, data, len*sizeof(u8)); pkg->pkg_type = MDFLD_DSI_PKG_GEN_LONG_WRITE; pkg->transmission_type = transmission; pkg->pkg.long_pkg.data = pdata; pkg->pkg.long_pkg.len = len; INIT_LIST_HEAD(&pkg->entry); pkg_sender_queue_pkg(sender, pkg, delay); return 0; } static int __read_panel_data(struct mdfld_dsi_pkg_sender *sender, struct mdfld_dsi_pkg *pkg, u8 *data, u32 len) { unsigned long flags; struct drm_device *dev = sender->dev; int i; u32 gen_data_reg; u32 gen_data_value; int retry = MDFLD_DSI_READ_MAX_COUNT; u8 transmission = pkg->transmission_type; int dword_count = 0, remain_byte_count = 0; /*Check the len. Max value is 0x40 based on the generic read FIFO size*/ if (len * sizeof(*data) > 0x40) { len = 0x40 / sizeof(*data); DRM_ERROR("Bigger than Max.Set the len to Max 0x40 bytes\n"); } /** * do reading. * 0) set the max return pack size * 1) send out generic read request * 2) polling read data avail interrupt * 3) read data */ spin_lock_irqsave(&sender->lock, flags); /*Set the Max return pack size*/ wait_for_all_fifos_empty(sender); REG_WRITE(MIPIA_MAX_RETURN_PACK_SIZE_REG, (len*sizeof(*data)) & 0x3FF); wait_for_all_fifos_empty(sender); REG_WRITE(sender->mipi_intr_stat_reg, BIT29); if ((REG_READ(sender->mipi_intr_stat_reg) & BIT29)) DRM_ERROR("Can NOT clean read data valid interrupt\n"); /*send out read request*/ send_pkg(sender, pkg); pkg_sender_put_pkg_locked(sender, pkg); /*polling read data avail interrupt*/ while (--retry && !(REG_READ(sender->mipi_intr_stat_reg) & BIT29)) udelay(3); if (!retry) { spin_unlock_irqrestore(&sender->lock, flags); return -ETIMEDOUT; } REG_WRITE(sender->mipi_intr_stat_reg, BIT29); /*read data*/ if (transmission == MDFLD_DSI_HS_TRANSMISSION) gen_data_reg = sender->mipi_hs_gen_data_reg; else if (transmission == MDFLD_DSI_LP_TRANSMISSION) gen_data_reg = sender->mipi_lp_gen_data_reg; else { DRM_ERROR("Unknown transmission"); spin_unlock_irqrestore(&sender->lock, flags); return -EINVAL; } dword_count = len / 4; remain_byte_count = len % 4; for (i = 0; i < dword_count * 4; i = i + 4) { gen_data_value = REG_READ(gen_data_reg); *(data + i) = gen_data_value & 0x000000FF; *(data + i + 1) = (gen_data_value >> 8) & 0x000000FF; *(data + i + 2) = (gen_data_value >> 16) & 0x000000FF; *(data + i + 3) = (gen_data_value >> 24) & 0x000000FF; } if (remain_byte_count) { gen_data_value = REG_READ(gen_data_reg); for (i = 0; i < remain_byte_count; i++) { *(data + dword_count * 4 + i) = (gen_data_value >> (8 * i)) & 0x000000FF; } } spin_unlock_irqrestore(&sender->lock, flags); return len; } static int mdfld_dsi_read_gen(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, u8 *data, u32 len, u8 transmission) { struct mdfld_dsi_pkg *pkg; unsigned long flags; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } switch (param_num) { case 0: pkg->pkg_type = MDFLD_DSI_PKG_GEN_READ_0; pkg->pkg.short_pkg.cmd = 0; pkg->pkg.short_pkg.param = 0; break; case 1: pkg->pkg_type = MDFLD_DSI_PKG_GEN_READ_1; pkg->pkg.short_pkg.cmd = param0; pkg->pkg.short_pkg.param = 0; break; case 2: pkg->pkg_type = MDFLD_DSI_PKG_GEN_READ_2; pkg->pkg.short_pkg.cmd = param0; pkg->pkg.short_pkg.param = param1; break; } pkg->transmission_type = transmission; INIT_LIST_HEAD(&pkg->entry); return __read_panel_data(sender, pkg, data, len); } static int mdfld_dsi_read_mcs(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 *data, u32 len, u8 transmission) { struct mdfld_dsi_pkg *pkg; unsigned long flags; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } pkg->pkg_type = MDFLD_DSI_PKG_MCS_READ; pkg->pkg.short_pkg.cmd = cmd; pkg->pkg.short_pkg.param = 0; pkg->transmission_type = transmission; INIT_LIST_HEAD(&pkg->entry); return __read_panel_data(sender, pkg, data, len); } static int mdfld_dsi_send_dpi_spk_pkg(struct mdfld_dsi_pkg_sender *sender, u32 spk_pkg, u8 transmission) { struct mdfld_dsi_pkg *pkg; unsigned long flags; spin_lock_irqsave(&sender->lock, flags); pkg = pkg_sender_get_pkg_locked(sender); spin_unlock_irqrestore(&sender->lock, flags); if (!pkg) { DRM_ERROR("No memory\n"); return -ENOMEM; } pkg->pkg_type = MDFLD_DSI_DPI_SPK; pkg->transmission_type = transmission; pkg->pkg.spk_pkg.cmd = spk_pkg; INIT_LIST_HEAD(&pkg->entry); pkg_sender_queue_pkg(sender, pkg, 0); return 0; } void dsi_controller_dbi_init(struct mdfld_dsi_config *dsi_config, int pipe) { struct drm_device *dev = dsi_config->dev; u32 reg_offset = pipe ? MIPIC_REG_OFFSET : 0; int lane_count = dsi_config->lane_count; u32 val = 0; PSB_DEBUG_ENTRY("Init DBI interface on pipe %d...\n", pipe); /*un-ready device*/ REG_WRITE((MIPIA_DEVICE_READY_REG + reg_offset), 0x00000000); /*init dsi adapter before kicking off*/ REG_WRITE((MIPIA_CONTROL_REG + reg_offset), 0x00000018); /*TODO: figure out how to setup these registers*/ REG_WRITE((MIPIA_DPHY_PARAM_REG + reg_offset), 0x150c3408); REG_WRITE((MIPIA_CLK_LANE_SWITCH_TIME_CNT_REG + reg_offset), 0x000a0014); REG_WRITE((MIPIA_DBI_BW_CTRL_REG + reg_offset), 0x00000400); REG_WRITE((MIPIA_DBI_FIFO_THROTTLE_REG + reg_offset), 0x00000001); REG_WRITE((MIPIA_HS_LS_DBI_ENABLE_REG + reg_offset), 0x00000000); /*enable all interrupts*/ REG_WRITE((MIPIA_INTR_EN_REG + reg_offset), 0xffffffff); /*max value: 20 clock cycles of txclkesc*/ REG_WRITE((MIPIA_TURN_AROUND_TIMEOUT_REG + reg_offset), 0x0000001f); /*min 21 txclkesc, max: ffffh*/ REG_WRITE((MIPIA_DEVICE_RESET_TIMER_REG + reg_offset), 0x0000ffff); /*min: 7d0 max: 4e20*/ REG_WRITE((MIPIA_INIT_COUNT_REG + reg_offset), 0x00000fa0); /*set up max return packet size*/ REG_WRITE((MIPIA_MAX_RETURN_PACK_SIZE_REG + reg_offset), MDFLD_DSI_MAX_RETURN_PACKET_SIZE); /*set up func_prg*/ val |= lane_count; val |= (dsi_config->channel_num << DSI_DBI_VIRT_CHANNEL_OFFSET); val |= DSI_DBI_COLOR_FORMAT_OPTION2; REG_WRITE((MIPIA_DSI_FUNC_PRG_REG + reg_offset), val); REG_WRITE((MIPIA_HS_TX_TIMEOUT_REG + reg_offset), 0x3fffff); REG_WRITE((MIPIA_LP_RX_TIMEOUT_REG + reg_offset), 0xffff); REG_WRITE((MIPIA_HIGH_LOW_SWITCH_COUNT_REG + reg_offset), 0x46); REG_WRITE((MIPIA_EOT_DISABLE_REG + reg_offset), 0x00000000); REG_WRITE((MIPIA_LP_BYTECLK_REG + reg_offset), 0x00000004); REG_WRITE((MIPIA_DEVICE_READY_REG + reg_offset), 0x00000001); } int mdfld_dsi_cmds_kick_out(struct mdfld_dsi_pkg_sender *sender) { return process_pkg_list(sender); } int mdfld_dsi_status_check(struct mdfld_dsi_pkg_sender *sender) { return dsi_error_handler(sender); } int mdfld_dsi_check_fifo_empty(struct mdfld_dsi_pkg_sender *sender) { struct drm_device *dev = sender->dev; if (!sender) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } if (!sender->dbi_pkg_support) { DRM_ERROR("No DBI pkg sending on this sender\n"); return -ENOTSUPP; } return REG_READ(sender->mipi_gen_fifo_stat_reg) & BIT27; } int mdfld_dsi_send_dcs(struct mdfld_dsi_pkg_sender *sender, u8 dcs, u8 *param, u32 param_num, u8 data_src, int delay) { u32 cb_phy = sender->dbi_cb_phy; struct drm_device *dev = sender->dev; u32 index = 0; u8 *cb = (u8 *)sender->dbi_cb_addr; int retry; u8 *dst = NULL; u8 *pSendparam = NULL; int err = 0; if (!sender) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } if (!sender->dbi_pkg_support) { DRM_ERROR("No DBI pkg sending on this sender\n"); return -ENOTSUPP; } /* * If dcs is write_mem_start, send it directly using * DSI adapter interface */ if (dcs == write_mem_start) { spin_lock(&sender->lock); /** * check the whether is there any write_mem_start already being * sent in this between current te_seq and next te. * if yes, simply reject the rest of write_mem_start because it * is unnecessary. otherwise, go ahead and kick of a * write_mem_start. */ if (atomic64_read(&sender->last_screen_update) == atomic64_read(&sender->te_seq)) { spin_unlock(&sender->lock); DRM_INFO("reject write_mem_start\n"); return 0; } /** * query whether DBI FIFO is empty, * if not wait it becoming empty */ retry = MDFLD_DSI_DBI_FIFO_TIMEOUT; while (retry && !(REG_READ(sender->mipi_gen_fifo_stat_reg) & BIT27)) { udelay(500); retry--; } /*if DBI FIFO timeout, drop this frame*/ if (!retry) { DRM_ERROR("DBI FIFO timeout, drop frame\n"); spin_unlock(&sender->lock); return 0; } /*wait for generic fifo*/ if (REG_READ(HS_LS_DBI_ENABLE_REG) & BIT0) wait_for_lp_fifos_empty(sender); else wait_for_hs_fifos_empty(sender); /*record the last screen update timestamp*/ atomic64_set(&sender->last_screen_update, atomic64_read(&sender->te_seq)); *(cb + (index++)) = write_mem_start; REG_WRITE(sender->mipi_cmd_len_reg, 1); REG_WRITE(sender->mipi_cmd_addr_reg, cb_phy | BIT0 | BIT1); retry = MDFLD_DSI_DBI_FIFO_TIMEOUT; while (retry && (REG_READ(sender->mipi_cmd_addr_reg) & BIT0)) { udelay(1); retry--; } spin_unlock(&sender->lock); return 0; } if (param_num == 0) err = mdfld_dsi_send_mcs_short_hs(sender, dcs, 0, 0, delay); else if (param_num == 1) err = mdfld_dsi_send_mcs_short_hs(sender, dcs, param[0], 1, delay); else if (param_num > 1) { /*transfer to dcs package*/ pSendparam = kmalloc(sizeof(u8) * (param_num + 1), GFP_KERNEL); if (!pSendparam) { DRM_ERROR("No memory\n"); return -ENOMEM; } (*pSendparam) = dcs; dst = pSendparam + 1; memcpy(dst, param, param_num); err = mdfld_dsi_send_mcs_long_hs(sender, pSendparam, param_num + 1, delay); /*free pkg*/ kfree(pSendparam); } return err; } int mdfld_dsi_send_mcs_short_hs(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 param, u8 param_num, int delay) { if (!sender) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } return mdfld_dsi_send_mcs_short(sender, cmd, param, param_num, MDFLD_DSI_HS_TRANSMISSION, delay); } int mdfld_dsi_send_mcs_short_lp(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 param, u8 param_num, int delay) { if (!sender) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } return mdfld_dsi_send_mcs_short(sender, cmd, param, param_num, MDFLD_DSI_LP_TRANSMISSION, delay); } int mdfld_dsi_send_mcs_long_hs(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, int delay) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_mcs_long(sender, data, len, MDFLD_DSI_HS_TRANSMISSION, delay); } int mdfld_dsi_send_mcs_long_lp(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, int delay) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_mcs_long(sender, data, len, MDFLD_DSI_LP_TRANSMISSION, delay); } int mdfld_dsi_send_gen_short_hs(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, int delay) { if (!sender) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } return mdfld_dsi_send_gen_short(sender, param0, param1, param_num, MDFLD_DSI_HS_TRANSMISSION, delay); } int mdfld_dsi_send_gen_short_lp(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, int delay) { if (!sender || param_num < 0 || param_num > 2) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } return mdfld_dsi_send_gen_short(sender, param0, param1, param_num, MDFLD_DSI_LP_TRANSMISSION, delay); } int mdfld_dsi_send_gen_long_hs(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, int delay) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_gen_long(sender, data, len, MDFLD_DSI_HS_TRANSMISSION, delay); } int mdfld_dsi_send_gen_long_lp(struct mdfld_dsi_pkg_sender *sender, u8 *data, u32 len, int delay) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_gen_long(sender, data, len, MDFLD_DSI_LP_TRANSMISSION, delay); } int mdfld_dsi_read_gen_hs(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, u8 *data, u32 len) { if (!sender || !data || param_num < 0 || param_num > 2 || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_read_gen(sender, param0, param1, param_num, data, len, MDFLD_DSI_HS_TRANSMISSION); } int mdfld_dsi_read_gen_lp(struct mdfld_dsi_pkg_sender *sender, u8 param0, u8 param1, u8 param_num, u8 *data, u32 len) { if (!sender || !data || param_num < 0 || param_num > 2 || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_read_gen(sender, param0, param1, param_num, data, len, MDFLD_DSI_LP_TRANSMISSION); } int mdfld_dsi_read_mcs_hs(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 *data, u32 len) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_read_mcs(sender, cmd, data, len, MDFLD_DSI_HS_TRANSMISSION); } int mdfld_dsi_read_mcs_lp(struct mdfld_dsi_pkg_sender *sender, u8 cmd, u8 *data, u32 len) { if (!sender || !data || !len) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_read_mcs(sender, cmd, data, len, MDFLD_DSI_LP_TRANSMISSION); } int mdfld_dsi_send_dpi_spk_pkg_hs(struct mdfld_dsi_pkg_sender *sender, u32 spk_pkg) { if (!sender) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_dpi_spk_pkg(sender, spk_pkg, MDFLD_DSI_HS_TRANSMISSION); } int mdfld_dsi_send_dpi_spk_pkg_lp(struct mdfld_dsi_pkg_sender *sender, u32 spk_pkg) { if (!sender) { DRM_ERROR("Invalid parameters\n"); return -EINVAL; } return mdfld_dsi_send_dpi_spk_pkg(sender, spk_pkg, MDFLD_DSI_LP_TRANSMISSION); } int mdfld_dsi_wait_for_fifos_empty(struct mdfld_dsi_pkg_sender *sender) { return wait_for_all_fifos_empty(sender); } void mdfld_dsi_report_te(struct mdfld_dsi_pkg_sender *sender) { if (sender) atomic64_inc(&sender->te_seq); } int mdfld_dsi_pkg_sender_init(struct mdfld_dsi_connector *dsi_connector, int pipe) { int ret; struct mdfld_dsi_pkg_sender *pkg_sender; struct mdfld_dsi_config *dsi_config = mdfld_dsi_get_config(dsi_connector); struct drm_device *dev = dsi_config->dev; struct drm_psb_private *dev_priv = dev->dev_private; struct psb_gtt *pg = dev_priv->pg; int i; struct mdfld_dsi_pkg *pkg, *tmp; PSB_DEBUG_ENTRY("\n"); if (!dsi_connector) { DRM_ERROR("Invalid parameter\n"); return -EINVAL; } pkg_sender = dsi_connector->pkg_sender; if (!pkg_sender || IS_ERR(pkg_sender)) { pkg_sender = kzalloc(sizeof(struct mdfld_dsi_pkg_sender), GFP_KERNEL); if (!pkg_sender) { DRM_ERROR("Create DSI pkg sender failed\n"); return -ENOMEM; } dsi_connector->pkg_sender = (void *)pkg_sender; } pkg_sender->dev = dev; pkg_sender->dsi_connector = dsi_connector; pkg_sender->pipe = pipe; pkg_sender->pkg_num = 0; pkg_sender->panel_mode = 0; pkg_sender->status = MDFLD_DSI_PKG_SENDER_FREE; /*int dbi command buffer*/ if (dsi_config->type == MDFLD_DSI_ENCODER_DBI) { pkg_sender->dbi_pkg_support = 1; ret = mdfld_dbi_cb_init(pkg_sender, pg, pipe); if (ret) { DRM_ERROR("DBI command buffer map failed\n"); goto mapping_err; } } /*init regs*/ if (pipe == 0) { pkg_sender->dpll_reg = MRST_DPLL_A; pkg_sender->dspcntr_reg = DSPACNTR; pkg_sender->pipeconf_reg = PIPEACONF; pkg_sender->dsplinoff_reg = DSPALINOFF; pkg_sender->dspsurf_reg = DSPASURF; pkg_sender->pipestat_reg = PIPEASTAT; pkg_sender->mipi_intr_stat_reg = MIPIA_INTR_STAT_REG; pkg_sender->mipi_lp_gen_data_reg = MIPIA_LP_GEN_DATA_REG; pkg_sender->mipi_hs_gen_data_reg = MIPIA_HS_GEN_DATA_REG; pkg_sender->mipi_lp_gen_ctrl_reg = MIPIA_LP_GEN_CTRL_REG; pkg_sender->mipi_hs_gen_ctrl_reg = MIPIA_HS_GEN_CTRL_REG; pkg_sender->mipi_gen_fifo_stat_reg = MIPIA_GEN_FIFO_STAT_REG; pkg_sender->mipi_data_addr_reg = MIPIA_DATA_ADD_REG; pkg_sender->mipi_data_len_reg = MIPIA_DATA_LEN_REG; pkg_sender->mipi_cmd_addr_reg = MIPIA_CMD_ADD_REG; pkg_sender->mipi_cmd_len_reg = MIPIA_CMD_LEN_REG; pkg_sender->mipi_dpi_control_reg = MIPIA_DPI_CONTROL_REG; } else if (pipe == 2) { pkg_sender->dpll_reg = MRST_DPLL_A; pkg_sender->dspcntr_reg = DSPCCNTR; pkg_sender->pipeconf_reg = PIPECCONF; pkg_sender->dsplinoff_reg = DSPCLINOFF; pkg_sender->dspsurf_reg = DSPCSURF; pkg_sender->pipestat_reg = 72024; pkg_sender->mipi_intr_stat_reg = MIPIA_INTR_STAT_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_lp_gen_data_reg = MIPIA_LP_GEN_DATA_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_hs_gen_data_reg = MIPIA_HS_GEN_DATA_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_lp_gen_ctrl_reg = MIPIA_LP_GEN_CTRL_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_hs_gen_ctrl_reg = MIPIA_HS_GEN_CTRL_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_gen_fifo_stat_reg = MIPIA_GEN_FIFO_STAT_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_data_addr_reg = MIPIA_DATA_ADD_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_data_len_reg = MIPIA_DATA_LEN_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_cmd_addr_reg = MIPIA_CMD_ADD_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_cmd_len_reg = MIPIA_CMD_LEN_REG + MIPIC_REG_OFFSET; pkg_sender->mipi_dpi_control_reg = MIPIA_DPI_CONTROL_REG + MIPIC_REG_OFFSET; } /*init pkg list*/ INIT_LIST_HEAD(&pkg_sender->pkg_list); INIT_LIST_HEAD(&pkg_sender->free_list); /*init lock*/ spin_lock_init(&pkg_sender->lock); /*allocate free pkg pool*/ for (i = 0; i < MDFLD_MAX_PKG_NUM; i++) { pkg = kzalloc(sizeof(struct mdfld_dsi_pkg), GFP_KERNEL); if (!pkg) { ret = -ENOMEM; goto pkg_alloc_err; } INIT_LIST_HEAD(&pkg->entry); /*append to free list*/ list_add_tail(&pkg->entry, &pkg_sender->free_list); } /*init te & screen update seqs*/ atomic64_set(&pkg_sender->te_seq, 0); atomic64_set(&pkg_sender->last_screen_update, 0); PSB_DEBUG_ENTRY("initialized\n"); return 0; pkg_alloc_err: list_for_each_entry_safe(pkg, tmp, &pkg_sender->free_list, entry) { list_del(&pkg->entry); kfree(pkg); } /*free mapped command buffer*/ mdfld_dbi_cb_destroy(pkg_sender); mapping_err: kfree(pkg_sender); dsi_connector->pkg_sender = NULL; return ret; } void mdfld_dsi_pkg_sender_destroy(struct mdfld_dsi_pkg_sender *sender) { struct mdfld_dsi_pkg *pkg, *tmp; if (!sender || IS_ERR(sender)) return; /*free pkg pool*/ list_for_each_entry_safe(pkg, tmp, &sender->free_list, entry) { list_del(&pkg->entry); kfree(pkg); } /*free pkg list*/ list_for_each_entry_safe(pkg, tmp, &sender->pkg_list, entry) { list_del(&pkg->entry); kfree(pkg); } /*free mapped command buffer*/ mdfld_dbi_cb_destroy(sender); /*free*/ kfree(sender); PSB_DEBUG_ENTRY("destroyed\n"); }
nels83/android_kernel_samsung_santos10
drivers/staging/mrfl/drv/mdfld_dsi_pkg_sender.c
C
gpl-2.0
42,957
[ 30522, 1013, 1008, 1008, 9385, 1075, 2230, 13420, 3840, 1008, 1008, 6656, 2003, 2182, 3762, 4379, 1010, 2489, 1997, 3715, 1010, 2000, 2151, 2711, 11381, 1037, 1008, 6100, 1997, 2023, 4007, 1998, 3378, 12653, 6764, 1006, 1996, 1000, 4007, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*******************************************************************\ Module: Type Naming for C Author: Daniel Kroening, kroening@cs.cmu.edu \*******************************************************************/ #include <ctype.h> #include <i2string.h> #include <std_types.h> #include "type2name.h" /*******************************************************************\ Function: type2name Inputs: Outputs: Purpose: \*******************************************************************/ std::string type2name(const typet &type) { std::string result; if(type.id()=="") throw "Empty type encountered."; else if(type.id()=="empty") result+="V"; else if(type.id()=="signedbv") result+="S" + type.width().as_string(); else if(type.id()=="unsignedbv") result+="U" + type.width().as_string(); else if(type.is_bool()) result+="B"; else if(type.id()=="integer") result+="I"; else if(type.id()=="real") result+="R"; else if(type.id()=="complex") result+="C"; else if(type.id()=="float") result+="F"; else if(type.id()=="floatbv") result+="F" + type.width().as_string(); else if(type.id()=="fixed") result+="X"; else if(type.id()=="fixedbv") result+="X" + type.width().as_string(); else if(type.id()=="natural") result+="N"; else if(type.id()=="pointer") result+="*"; else if(type.id()=="reference") result+="&"; else if(type.is_code()) { const code_typet &t = to_code_type(type); const code_typet::argumentst arguments = t.arguments(); result+="P("; for (code_typet::argumentst::const_iterator it = arguments.begin(); it!=arguments.end(); it++) { result+=type2name(it->type()); result+="'" + it->get_identifier().as_string() + "'|"; } result.resize(result.size()-1); result+=")"; } else if(type.is_array()) { const array_typet &t = to_array_type(type); result+="ARR" + t.size().value().as_string(); } else if(type.id()=="incomplete_array") { result+="ARR?"; } else if(type.id()=="symbol") { result+="SYM#" + type.identifier().as_string() + "#"; } else if(type.id()=="struct" || type.id()=="union") { if(type.id()=="struct") result +="ST"; if(type.id()=="union") result +="UN"; const struct_typet &t = to_struct_type(type); const struct_typet::componentst &components = t.components(); result+="["; for(struct_typet::componentst::const_iterator it = components.begin(); it!=components.end(); it++) { result+=type2name(it->type()); result+="'" + it->name().as_string() + "'|"; } result.resize(result.size()-1); result+="]"; } else if(type.id()=="incomplete_struct") result +="ST?"; else if(type.id()=="incomplete_union") result +="UN?"; else if(type.id()=="c_enum") result +="EN" + type.width().as_string(); else if(type.id()=="incomplete_c_enum") result +="EN?"; else if(type.id()=="c_bitfield") { result+="BF" + type.size().as_string(); } else { throw (std::string("Unknown type '") + type.id().as_string() + "' encountered."); } if(type.has_subtype()) { result+="{"; result+=type2name(type.subtype()); result+="}"; } if(type.has_subtypes()) { result+="$"; forall_subtypes(it, type) { result+=type2name(*it); result+="|"; } result.resize(result.size()-1); result+="$"; } return result; }
ssvlab/esbmc-gpu
ansi-c/type2name.cpp
C++
apache-2.0
3,566
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 30524, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/SLD/v1.js * @requires OpenLayers/Format/Filter/v1_0_0.js */ /** * Class: OpenLayers.Format.SLD.v1_0_0 * Write SLD version 1.0.0. * * Inherits from: * - <OpenLayers.Format.SLD.v1> */ OpenLayers.Format.SLD.v1_0_0 = OpenLayers.Class( OpenLayers.Format.SLD.v1, { /** * Constant: VERSION * {String} 1.0.0 */ VERSION: "1.0.0", /** * Property: schemaLocation * {String} http://www.opengis.net/sld * http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd */ schemaLocation: "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd", /** * Constructor: OpenLayers.Format.SLD.v1_0_0 * Instances of this class are not created directly. Use the * <OpenLayers.Format.SLD> constructor instead. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ CLASS_NAME: "OpenLayers.Format.SLD.v1_0_0" });
B3Partners/geo-ov
src/main/webapp/openlayers/lib/OpenLayers/Format/SLD/v1_0_0.js
JavaScript
agpl-3.0
1,351
[ 30522, 1013, 1008, 9385, 1006, 1039, 1007, 2294, 1011, 2262, 2011, 2330, 24314, 2015, 16884, 1006, 2156, 6048, 1012, 19067, 2102, 2005, 1008, 2440, 2862, 1997, 16884, 1007, 1012, 2405, 2104, 1996, 1016, 1011, 11075, 18667, 2094, 6105, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Pachygenium longibracteatum (Pabst) Szlach., R.González & Rutk. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Pelexia/Pelexia longibracteata/ Syn. Pachygenium longibracteatum/README.md
Markdown
apache-2.0
221
[ 30522, 1001, 14397, 10536, 6914, 5007, 2146, 12322, 22648, 27058, 11667, 1006, 6643, 5910, 2102, 1007, 1055, 2480, 2721, 2818, 1012, 1010, 1054, 1012, 10121, 1004, 21766, 2102, 2243, 1012, 2427, 1001, 1001, 1001, 1001, 3570, 10675, 1001, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{% extends "sitewide/flat_ui_template.html" %} {% load custom_tags %} {% load static %} {% block title %}All Controllers{% endblock %} {% block header_scripts %} <link href="{% static "css/dashboard_revised.css" %}" rel="stylesheet"> {% endblock %} {% block content %} <h1>Devices</h1> {% if not all_devices %} No fermentation devices configured yet. To get started, add a new device: <ul> <li><a href="{% url 'device_guided_select_device' %}">Add new device (guided)</a></li> <li><a href="{% url 'device_add' %}">Add new device (advanced)</a></li> </ul> {% else %} <!-- Start vue LCD container --> <div id="lcdapp"> <!-- Start vue LCD loop div --> <div v-for="lcd in lcds"> <!-- Start row for LCD --> <div class="row"> <!-- Start LCD Display Box --> <div class="col-lg-4 col-md-12" style="text-align: center"> <div class="dashpanel dashpanel-top bg-black" style="height: 125px;"> <div style="width: 290px"> <div id="lcd.device_name" class="lcddisplay"> <span class="lcd-text"> <span class="lcd-line" id="lcd-line-0" v-html="lcd.lcd_data[0]"></span> <span class="lcd-line" id="lcd-line-1" v-html="lcd.lcd_data[1]"></span> <span class="lcd-line" id="lcd-line-2" v-html="lcd.lcd_data[2]"></span> <span class="lcd-line" id="lcd-line-3" v-html="lcd.lcd_data[3]"></span> </span> </div> </div> </div> </div> <!-- End LCD Display Box --> <!-- Start Beer Name Header --> <div class="col-lg-5 col-md-6"> <!-- TODO - Figure if I can get this to snap above the previous pane on resize --> <a v-bind:href="lcd.device_url"> <div class="dashpanel dashpanel-top bg-carrot"> <div class="dash-icon dash-icon-lg" style="right: 15; left: inherit;"><i class="fa fa-tasks fa-fw"></i></div> {# Vue.js uses the same template tags ({{ and }}) as does Django. Use verbatim to escape. #} <div class="dash-data" style="text-align: left">Device: {% verbatim %}{{ lcd.device_name }}{% endverbatim %}</div> <div class="dashpanel-divider"></div> <div class="dash-desc"> <div class="pull-left"> View Dashboard</div> <div class="pull-right"><i class="fa fa-arrow-circle-right"></i></div> <div class="clearfix"></div> </div> </div> </a> </div> <!-- End Beer Name Header --> <!-- Start Mode Control Box --> <div class="col-lg-3 col-md-6"> <a href="#" data-toggle="modal" v-bind:data-target="lcd.modal_name"> <div class="dashpanel dashpanel-top bg-concrete" style="height: 125px"> <div class="dash-icon dash-icon-lg"><i class="fa fa-bolt fa-fw"></i></div> {# <div class="dashpanel-title">Control Mode</div>#} {# TODO - Get this to show the actual temperature control mode #} {# <div class="dash-data" id="dashControlMode">Beer Profile</div>#} <div class="dash-data">Control Mode</div> <div class="dashpanel-divider"></div> <div class="dash-desc"> {# <div class="pull-left" >Change Mode</div>#} <div class="pull-left" >Set Mode</div> <div class="pull-right"><i class="fa fa-arrow-circle-right"></i></div> <div class="clearfix"></div> </div> </div> </a> </div> <!-- End Mode Control Box --> </div> <!-- End row for LCD --> </div> <!-- End vue LCD loop div --> </div> <!-- End vue application container --> {# Add all the modals for controlling temperatures #} {% for this_device in all_devices %} {% temp_control_modal this_device %} {% endfor %} {% endif %} {% endblock %} {% block scripts %} {% load static %} <script type="text/javascript" src="{% static "vendor/vue/js/vue.min.js" %}"></script> <script type="text/javascript" src="{% static "js/lcd.js" %}"></script> {% endblock %}
thorrak/fermentrack
app/templates/device_lcd_list.html
HTML
mit
4,941
[ 30522, 1063, 1003, 8908, 1000, 2609, 22517, 1013, 4257, 1035, 21318, 1035, 23561, 1012, 16129, 1000, 1003, 1065, 1063, 1003, 7170, 7661, 1035, 22073, 1003, 1065, 1063, 30524, 20116, 2015, 1000, 1003, 1065, 1000, 2128, 2140, 1027, 1000, 6782...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from django.apps import AppConfig class JcvrbaseappConfig(AppConfig): name = 'jcvrbaseapp'
jucapoco/baseSiteGanttChart
jcvrbaseapp/apps.py
Python
mit
97
[ 30522, 2013, 6520, 23422, 1012, 18726, 12324, 10439, 8663, 8873, 2290, 2465, 29175, 19716, 15058, 29098, 8663, 8873, 2290, 1006, 10439, 8663, 8873, 2290, 1007, 1024, 2171, 1027, 1005, 29175, 19716, 15058, 29098, 1005, 102, 0, 0, 0, 0, 0, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python ''' Copyright (c) 2013 Potential Ventures Ltd Copyright (c) 2013 SolarFlare Communications Inc All rights reserved. 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 Potential Ventures Ltd, SolarFlare Communications Inc 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 POTENTIAL VENTURES LTD 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. ''' """ Collection of Ethernet Packet generators to use for testdata generation Most generators take the keyword argument "payload" which can be used to control the payload contents if required. Defaults to random data. """ import random from scapy.all import Ether, IP, UDP # Supress SCAPY warning messages import logging logging.getLogger("scapy").setLevel(logging.ERROR) from cocotb.decorators import public from cocotb.generators.byte import get_bytes, random_data _default_payload = random_data # UDP packet generators @public def udp_all_sizes(max_size=1500, payload=_default_payload()): """UDP packets of every supported size""" header = Ether() / IP() / UDP() for size in range(0, max_size - len(header)): yield header / get_bytes(size, payload) @public def udp_random_sizes(npackets=100, payload=_default_payload()): """UDP packets with random sizes""" header = Ether() / IP() / UDP() max_size = 1500 - len(header) for pkt in range(npackets): yield header / get_bytes(random.randint(0, max_size), payload) # IPV4 generator @public def ipv4_small_packets(npackets=100, payload=_default_payload()): """Small (<100bytes payload) IPV4 packets""" for pkt in range(npackets): yield Ether() / IP() / get_bytes(random.randint(0, 100), payload)
stuarthodgson/cocotb
cocotb/generators/packet.py
Python
bsd-3-clause
2,962
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 1005, 1005, 1005, 9385, 1006, 1039, 1007, 2286, 4022, 13252, 5183, 9385, 1006, 1039, 1007, 2286, 5943, 10258, 12069, 4806, 4297, 2035, 2916, 9235, 1012, 25707, 1998, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Makefile for project $(NAME) # Distribute under GPLv2, use with care. # # 2008-09-25, jw NAME = matrix8x8 CFILES = blink.c # $(NAME).c eeprom.c i2c_slave_cb.c CPU = mega8 #PROG_HW = stk200 PROG_HW = usbasp #PROG_SW = avrdude PROG_SW = sudo avrdude TOP_DIR = . include $(TOP_DIR)/avr_common.mk distclean:: rm -f download* ee_data.* ## header file dependencies ############################# include depend.mk
jnweiger/led_matrix8x8
Makefile
Makefile
gpl-2.0
473
[ 30522, 1001, 2191, 8873, 2571, 2005, 2622, 1002, 1006, 2171, 1007, 1001, 16062, 2104, 14246, 2140, 2615, 2475, 1010, 2224, 2007, 2729, 1012, 1001, 1001, 2263, 1011, 5641, 1011, 2423, 1010, 1046, 2860, 2171, 1027, 8185, 2620, 2595, 2620, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// SPDX-License-Identifier: GPL-2.0-only /* * tifm_core.c - TI FlashMedia driver * * Copyright (C) 2006 Alex Dubov <oakad@yahoo.com> */ #include <linux/tifm.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/idr.h> #include <linux/module.h> #define DRIVER_NAME "tifm_core" #define DRIVER_VERSION "0.8" static struct workqueue_struct *workqueue; static DEFINE_IDR(tifm_adapter_idr); static DEFINE_SPINLOCK(tifm_adapter_lock); static const char *tifm_media_type_name(unsigned char type, unsigned char nt) { const char *card_type_name[3][3] = { { "SmartMedia/xD", "MemoryStick", "MMC/SD" }, { "XD", "MS", "SD"}, { "xd", "ms", "sd"} }; if (nt > 2 || type < 1 || type > 3) return NULL; return card_type_name[nt][type - 1]; } static int tifm_dev_match(struct tifm_dev *sock, struct tifm_device_id *id) { if (sock->type == id->type) return 1; return 0; } static int tifm_bus_match(struct device *dev, struct device_driver *drv) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); struct tifm_driver *fm_drv = container_of(drv, struct tifm_driver, driver); struct tifm_device_id *ids = fm_drv->id_table; if (ids) { while (ids->type) { if (tifm_dev_match(sock, ids)) return 1; ++ids; } } return 0; } static int tifm_uevent(struct device *dev, struct kobj_uevent_env *env) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); if (add_uevent_var(env, "TIFM_CARD_TYPE=%s", tifm_media_type_name(sock->type, 1))) return -ENOMEM; return 0; } static int tifm_device_probe(struct device *dev) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver, driver); int rc = -ENODEV; get_device(dev); if (dev->driver && drv->probe) { rc = drv->probe(sock); if (!rc) return 0; } put_device(dev); return rc; } static void tifm_dummy_event(struct tifm_dev *sock) { return; } static void tifm_device_remove(struct device *dev) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver, driver); if (dev->driver && drv->remove) { sock->card_event = tifm_dummy_event; sock->data_event = tifm_dummy_event; drv->remove(sock); sock->dev.driver = NULL; } put_device(dev); } #ifdef CONFIG_PM static int tifm_device_suspend(struct device *dev, pm_message_t state) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver, driver); if (dev->driver && drv->suspend) return drv->suspend(sock, state); return 0; } static int tifm_device_resume(struct device *dev) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver, driver); if (dev->driver && drv->resume) return drv->resume(sock); return 0; } #else #define tifm_device_suspend NULL #define tifm_device_resume NULL #endif /* CONFIG_PM */ static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *buf) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); return sprintf(buf, "%x", sock->type); } static DEVICE_ATTR_RO(type); static struct attribute *tifm_dev_attrs[] = { &dev_attr_type.attr, NULL, }; ATTRIBUTE_GROUPS(tifm_dev); static struct bus_type tifm_bus_type = { .name = "tifm", .dev_groups = tifm_dev_groups, .match = tifm_bus_match, .uevent = tifm_uevent, .probe = tifm_device_probe, .remove = tifm_device_remove, .suspend = tifm_device_suspend, .resume = tifm_device_resume }; static void tifm_free(struct device *dev) { struct tifm_adapter *fm = container_of(dev, struct tifm_adapter, dev); kfree(fm); } static struct class tifm_adapter_class = { .name = "tifm_adapter", .dev_release = tifm_free }; struct tifm_adapter *tifm_alloc_adapter(unsigned int num_sockets, struct device *dev) { struct tifm_adapter *fm; fm = kzalloc(sizeof(struct tifm_adapter) + sizeof(struct tifm_dev*) * num_sockets, GFP_KERNEL); if (fm) { fm->dev.class = &tifm_adapter_class; fm->dev.parent = dev; device_initialize(&fm->dev); spin_lock_init(&fm->lock); fm->num_sockets = num_sockets; } return fm; } EXPORT_SYMBOL(tifm_alloc_adapter); int tifm_add_adapter(struct tifm_adapter *fm) { int rc; idr_preload(GFP_KERNEL); spin_lock(&tifm_adapter_lock); rc = idr_alloc(&tifm_adapter_idr, fm, 0, 0, GFP_NOWAIT); if (rc >= 0) fm->id = rc; spin_unlock(&tifm_adapter_lock); idr_preload_end(); if (rc < 0) return rc; dev_set_name(&fm->dev, "tifm%u", fm->id); rc = device_add(&fm->dev); if (rc) { spin_lock(&tifm_adapter_lock); idr_remove(&tifm_adapter_idr, fm->id); spin_unlock(&tifm_adapter_lock); } return rc; } EXPORT_SYMBOL(tifm_add_adapter); void tifm_remove_adapter(struct tifm_adapter *fm) { unsigned int cnt; flush_workqueue(workqueue); for (cnt = 0; cnt < fm->num_sockets; ++cnt) { if (fm->sockets[cnt]) device_unregister(&fm->sockets[cnt]->dev); } spin_lock(&tifm_adapter_lock); idr_remove(&tifm_adapter_idr, fm->id); spin_unlock(&tifm_adapter_lock); device_del(&fm->dev); } EXPORT_SYMBOL(tifm_remove_adapter); void tifm_free_adapter(struct tifm_adapter *fm) { put_device(&fm->dev); } EXPORT_SYMBOL(tifm_free_adapter); void tifm_free_device(struct device *dev) { struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev); kfree(sock); } EXPORT_SYMBOL(tifm_free_device); struct tifm_dev *tifm_alloc_device(struct tifm_adapter *fm, unsigned int id, unsigned char type) { struct tifm_dev *sock = NULL; if (!tifm_media_type_name(type, 0)) return sock; sock = kzalloc(sizeof(struct tifm_dev), GFP_KERNEL); if (sock) { spin_lock_init(&sock->lock); sock->type = type; sock->socket_id = id; sock->card_event = tifm_dummy_event; sock->data_event = tifm_dummy_event; sock->dev.parent = fm->dev.parent; sock->dev.bus = &tifm_bus_type; sock->dev.dma_mask = fm->dev.parent->dma_mask; sock->dev.release = tifm_free_device; dev_set_name(&sock->dev, "tifm_%s%u:%u", tifm_media_type_name(type, 2), fm->id, id); printk(KERN_INFO DRIVER_NAME ": %s card detected in socket %u:%u\n", tifm_media_type_name(type, 0), fm->id, id); } return sock; } EXPORT_SYMBOL(tifm_alloc_device); void tifm_eject(struct tifm_dev *sock) { struct tifm_adapter *fm = dev_get_drvdata(sock->dev.parent); fm->eject(fm, sock); } EXPORT_SYMBOL(tifm_eject); int tifm_has_ms_pif(struct tifm_dev *sock) { struct tifm_adapter *fm = dev_get_drvdata(sock->dev.parent); return fm->has_ms_pif(fm, sock); } EXPORT_SYMBOL(tifm_has_ms_pif); int tifm_map_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents, int direction) { return pci_map_sg(to_pci_dev(sock->dev.parent), sg, nents, direction); } EXPORT_SYMBOL(tifm_map_sg); void tifm_unmap_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents, int direction) { pci_unmap_sg(to_pci_dev(sock->dev.parent), sg, nents, direction); } EXPORT_SYMBOL(tifm_unmap_sg); void tifm_queue_work(struct work_struct *work) { queue_work(workqueue, work); } EXPORT_SYMBOL(tifm_queue_work); int tifm_register_driver(struct tifm_driver *drv) { drv->driver.bus = &tifm_bus_type; return driver_register(&drv->driver); } EXPORT_SYMBOL(tifm_register_driver); void tifm_unregister_driver(struct tifm_driver *drv) { driver_unregister(&drv->driver); } EXPORT_SYMBOL(tifm_unregister_driver); static int __init tifm_init(void) { int rc; workqueue = create_freezable_workqueue("tifm"); if (!workqueue) return -ENOMEM; rc = bus_register(&tifm_bus_type); if (rc) goto err_out_wq; rc = class_register(&tifm_adapter_class); if (!rc) return 0; bus_unregister(&tifm_bus_type); err_out_wq: destroy_workqueue(workqueue); return rc; } static void __exit tifm_exit(void) { class_unregister(&tifm_adapter_class); bus_unregister(&tifm_bus_type); destroy_workqueue(workqueue); } subsys_initcall(tifm_init); module_exit(tifm_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alex Dubov"); MODULE_DESCRIPTION("TI FlashMedia core driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRIVER_VERSION);
tprrt/linux-stable
drivers/misc/tifm_core.c
C
gpl-2.0
8,290
[ 30522, 1013, 1013, 23772, 2595, 1011, 6105, 1011, 8909, 4765, 18095, 1024, 14246, 2140, 1011, 1016, 1012, 1014, 1011, 2069, 1013, 1008, 1008, 14841, 16715, 1035, 4563, 1012, 1039, 1011, 14841, 5956, 16969, 4062, 1008, 1008, 9385, 1006, 1039...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* 'aes_xcbc.c' Obfuscated by COBF (Version 1.06 2006-01-07 by BB) at Mon Jun 10 09:48:00 2013 */ #include"cobf.h" #ifdef _WIN32 #if defined( UNDER_CE) && defined( bb344) || ! defined( bb338) #define bb340 1 #define bb336 1 #else #define bb351 bb357 #define bb330 1 #define bb352 1 #endif #define bb353 1 #include"uncobf.h" #include<ndis.h> #include"cobf.h" #ifdef UNDER_CE #include"uncobf.h" #include<ndiswan.h> #include"cobf.h" #endif #include"uncobf.h" #include<stdio.h> #include<basetsd.h> #include"cobf.h" bba bbs bbl bbf, *bb1;bba bbs bbe bbq, *bb94;bba bb135 bb124, *bb337; bba bbs bbl bb39, *bb72;bba bbs bb135 bbk, *bb59;bba bbe bbu, *bb133; bba bbh bbf*bb89; #ifdef bb308 bba bbd bb60, *bb122; #endif #else #include"uncobf.h" #include<linux/module.h> #include<linux/ctype.h> #include<linux/time.h> #include<linux/slab.h> #include"cobf.h" #ifndef bb116 #define bb116 #ifdef _WIN32 #include"uncobf.h" #include<wtypes.h> #include"cobf.h" #else #ifdef bb117 #include"uncobf.h" #include<linux/types.h> #include"cobf.h" #else #include"uncobf.h" #include<stddef.h> #include<sys/types.h> #include"cobf.h" #endif #endif #ifdef _WIN32 bba bb111 bb256; #else bba bbe bbu, *bb133, *bb279; #define bb201 1 #define bb202 0 bba bb284 bb227, *bb217, *bb229;bba bbe bb263, *bb250, *bb287;bba bbs bbq, *bb94, *bb289;bba bb6 bb223, *bb285;bba bbs bb6 bb214, *bb259; bba bb6 bb118, *bb238;bba bbs bb6 bb64, *bb241;bba bb64 bb258, *bb228 ;bba bb64 bb276, *bb255;bba bb118 bb111, *bb249;bba bb290 bb264;bba bb208 bb124;bba bb271 bb83;bba bb115 bb114;bba bb115 bb274; #ifdef bb226 bba bb235 bb39, *bb72;bba bb254 bbk, *bb59;bba bb248 bbd, *bb29;bba bb270 bb56, *bb113; #else bba bb246 bb39, *bb72;bba bb257 bbk, *bb59;bba bb278 bbd, *bb29;bba bb206 bb56, *bb113; #endif bba bb39 bbf, *bb1, *bb224;bba bbk bb243, *bb209, *bb221;bba bbk bb275 , *bb210, *bb245;bba bbd bb60, *bb122, *bb252;bba bb83 bb37, *bb267, * bb240;bba bbd bb234, *bb211, *bb222;bba bb114 bb251, *bb269, *bb231; bba bb56 bb225, *bb280, *bb273; #define bb141 bbb bba bbb*bb212, *bb77;bba bbh bbb*bb230;bba bbl bb207;bba bbl*bb232; bba bbh bbl*bb82; #if defined( bb117) bba bbe bb112; #endif bba bb112 bb19;bba bb19*bb233;bba bbh bb19*bb188; #if defined( bb283) || defined( bb236) bba bb19 bb36;bba bb19 bb120; #else bba bbl bb36;bba bbs bbl bb120; #endif bba bbh bb36*bb262;bba bb36*bb268;bba bb60 bb266, *bb216;bba bbb* bb107;bba bb107*bb237; #define bb215( bb35) bbi bb35##__ { bbe bb219; }; bba bbi bb35##__ * \ bb35 bba bbi{bb37 bb190,bb265,bb239,bb244;}bb272, *bb281, *bb261;bba bbi{ bb37 bb8,bb193;}bb292, *bb242, *bb277;bba bbi{bb37 bb218,bb247;}bb220 , *bb213, *bb260; #endif bba bbh bbf*bb89; #endif bba bbf bb101; #define IN #define OUT #ifdef _DEBUG #define bb146( bbc) bb32( bbc) #else #define bb146( bbc) ( bbb)( bbc) #endif bba bbe bb161, *bb173; #define bb288 0 #define bb312 1 #define bb296 2 #define bb323 3 #define bb343 4 bba bbe bb349;bba bbb*bb121; #endif #ifdef _WIN32 #ifndef UNDER_CE #define bb31 bb341 #define bb43 bb346 bba bbs bb6 bb31;bba bb6 bb43; #endif #else #endif #ifdef _WIN32 bbb*bb128(bb31 bb47);bbb bb109(bbb* );bbb*bb137(bb31 bb159,bb31 bb47); #else #define bb128( bbc) bb147(1, bbc, bb140) #define bb109( bbc) bb331( bbc) #define bb137( bbc, bbn) bb147( bbc, bbn, bb140) #endif #ifdef _WIN32 #define bb32( bbc) bb339( bbc) #else #ifdef _DEBUG bbe bb144(bbh bbl*bb95,bbh bbl*bb25,bbs bb286); #define bb32( bbc) ( bbb)(( bbc) || ( bb144(# bbc, __FILE__, __LINE__ \ ))) #else #define bb32( bbc) (( bbb)0) #endif #endif bb43 bb302(bb43*bb324); #ifndef _WIN32 bbe bb328(bbh bbl*bbg);bbe bb321(bbh bbl*bb20,...); #endif #ifdef _WIN32 bba bb342 bb96; #define bb139( bbc) bb354( bbc) #define bb142( bbc) bb329( bbc) #define bb134( bbc) bb348( bbc) #define bb132( bbc) bb332( bbc) #else bba bb334 bb96; #define bb139( bbc) ( bbb)( * bbc = bb356( bbc)) #define bb142( bbc) (( bbb)0) #define bb134( bbc) bb333( bbc) #define bb132( bbc) bb358( bbc) #endif #ifdef __cplusplus bbr"\x43"{ #endif #ifdef __cplusplus bbr"\x43"{ #endif bba bbi{bbq bb447;bbd bb417[4 * (14 +1 )];}bb364;bbb bb1099(bb364*bbj, bbh bbb*bb71,bbq bb143);bbb bb1736(bb364*bbj,bbh bbb*bb71,bbq bb143); bbb bb1035(bb364*bbj,bbb*bb14,bbh bbb*bb5);bbb bb1775(bb364*bbj,bbb* bb14,bbh bbb*bb5); #ifdef __cplusplus } #endif bba bbi{bb364 bb2117;bbq bb9;bbf bb102[16 ];bbf bb1926[16 ];bbf bb1928[ 16 ];bbf bb1842[16 ];}bb939;bbb bb2042(bb939*bbj,bbh bbb*bb71,bbq bb143 );bbb bb2092(bb939*bbj,bbh bbb*bb5,bbq bb9);bbb bb2103(bb939*bbj,bbb* bb14); #ifdef __cplusplus } #endif bbb bb2042(bb939*bbj,bbh bbb*bb71,bbq bb143){bb364 bb2147;bbf bb2181[ 16 ];bbj->bb9=0 ;bb32(bb143==16 );bb1099(&bb2147,bb71,bb143);bb998(bbj-> bb1842,0 ,16 );bb998(bb2181,1 ,16 );bb1035(&bb2147,bb2181,bb2181);bb998( bbj->bb1926,2 ,16 );bb1035(&bb2147,bbj->bb1926,bbj->bb1926);bb998(bbj-> bb1928,3 ,16 );bb1035(&bb2147,bbj->bb1928,bbj->bb1928);bb1099(&bbj-> bb2117,bb2181,bb143);}bb41 bbb bb1254(bb939*bbj,bbh bbf*bb5){bbq bbz; bb90(bbz=0 ;bbz<16 ;bbz++)bbj->bb1842[bbz]^=bb5[bbz];bb1035(&bbj-> bb2117,bbj->bb1842,bbj->bb1842);}bbb bb2092(bb939*bbj,bbh bbb*bb498, bbq bb9){bbh bbf*bb5=(bbh bbf* )bb498;bbq bb383=bbj->bb9?(bbj->bb9-1 )% 16 +1 :0 ;bbj->bb9+=bb9;bbm(bb383){bbq bb11=16 -bb383;bb81(bbj->bb102+ bb383,bb5,((bb9)<(bb11)?(bb9):(bb11)));bbm(bb9<=bb11)bb2;bb5+=bb11; bb9-=bb11;bb1254(bbj,bbj->bb102);}bb90(;bb9>16 ;bb9-=16 ,bb5+=16 )bb1254 (bbj,bb5);bb81(bbj->bb102,bb5,bb9);}bbb bb2103(bb939*bbj,bbb*bb14){ bb1 bb3;bbq bbz,bb383=bbj->bb9?(bbj->bb9-1 )%16 +1 :0 ;bbm(bb383<16 ){bbj ->bb102[bb383++]=0x80 ;bb998(bbj->bb102+bb383,0 ,16 -bb383);bb3=bbj-> bb1928;}bb54 bb3=bbj->bb1926;bb90(bbz=0 ;bbz<16 ;bbz++)bbj->bb102[bbz] ^=bb3[bbz];bb1254(bbj,bbj->bb102);bb81(bb14,bbj->bb1842,16 );}
xpaum/kernel_stock_g3815
drivers/net/wireless/ipsecdrvtl/ac.c
C
gpl-2.0
5,718
[ 30522, 1013, 1008, 1005, 29347, 2015, 1035, 1060, 27421, 2278, 1012, 1039, 1005, 27885, 25608, 12921, 2011, 2522, 29292, 1006, 2544, 1015, 1012, 5757, 2294, 1011, 5890, 1011, 5718, 2011, 22861, 1007, 2012, 12256, 12022, 2184, 5641, 1024, 44...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def create_site(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Site = apps.get_model('sites', 'Site') db_alias = schema_editor.connection.alias Site.objects.using(db_alias).get_or_create( pk=1, defaults= { "pk": 1, "domain": "us.pycon.org", "name": "PyCon 2017" } ) class Migration(migrations.Migration): dependencies = [ ('conference', '0001_initial'), ('sites', '0001_initial'), ] operations = [ migrations.RunPython(create_site), ]
SaptakS/pune.pycon.org
symposion/conference/migrations/0002_create_site.py
Python
bsd-3-clause
753
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 27260, 1035, 18204, 2015, 2013, 6520, 23422, 1012, 16962, 12324, 4275, 1010, 9230, 2015, 13366, 3443, 1035, 26...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # Hendrix Costa <hendrix.costa@kmee.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp.addons.financial.tests.financial_test_classes import \ FinancialTestCase class ManualFinancialProcess(FinancialTestCase): def setUp(self): self.financial_model = self.env['financial.move'] super(ManualFinancialProcess, self).setUp() def test_01_check_return_views(self): """Check if view is correctly called for python code""" # test for len(financial.move) == 1 financial_move_id = self.financial_model.search([], limit=1) action = financial_move_id.action_view_financial('2receive') self.assertEqual( action.get('display_name'), 'financial.move.debt.2receive.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) action = financial_move_id.action_view_financial('2pay') self.assertEqual( action.get('display_name'), 'financial.move.debt.2pay.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) # test for len(financial.move) > 1 financial_move_id = self.financial_model.search([], limit=2) action = financial_move_id.action_view_financial('2pay') self.assertEqual(action.get('domain')[0][2], financial_move_id.ids) # test for len(financial.move) < 1 action = self.financial_model.action_view_financial('2pay') self.assertEqual(action.get('type'), 'ir.actions.act_window_close')
thinkopensolutions/l10n-brazil
financial/tests/test_financial_move.py
Python
agpl-3.0
1,651
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 9385, 2418, 2463, 4402, 1001, 20645, 6849, 1026, 20645, 1012, 6849, 1030, 2463, 4402, 1012, 4012, 1012, 7987, 1028, 1001, 6105, 12943, 24759, 1011,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package cassandra // read statements var selectIntStmt = ` SELECT metric_timestamp, value FROM metrics_int WHERE metric_name = ? AND tags = ? ` var selectIntByStartEndTimeStmt = ` SELECT metric_timestamp, value FROM metrics_int WHERE metric_name = ? AND tags = ? AND metric_timestamp >= ? AND metric_timestamp <= ? ` // write statements var insertIntStmt = ` INSERT INTO metrics_int (metric_name, metric_timestamp, tags, value) VALUES (?, ?, ?, ?) ` var insertDoubleStmt = ` INSERT INTO metrics_double (metric_name, metric_timestamp, tags, value) VALUES (?, ?, ?, ?) `
xephonhq/xephon-k
_legacy/pkg/storage/cassandra/stmt.go
GO
mit
583
[ 30522, 7427, 15609, 1013, 1013, 3191, 8635, 13075, 7276, 18447, 3367, 20492, 1027, 1036, 7276, 12046, 1035, 2335, 15464, 2361, 1010, 3643, 2013, 12046, 2015, 1035, 20014, 2073, 12046, 1035, 2171, 1027, 1029, 1998, 22073, 1027, 1029, 1036, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyIlmbase(AutotoolsPackage): """The PyIlmBase libraries provides python bindings for the IlmBase libraries.""" homepage = "https://github.com/AcademySoftwareFoundation/openexr/tree/v2.3.0/PyIlmBase" url = "https://github.com/AcademySoftwareFoundation/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz" version('2.3.0', sha256='9c898bb16e7bc916c82bebdf32c343c0f2878fc3eacbafa49937e78f2079a425') depends_on('ilmbase') depends_on('boost+python') # https://github.com/AcademySoftwareFoundation/openexr/issues/336 parallel = False def configure_args(self): spec = self.spec args = [ '--with-boost-python-libname=boost_python{0}'.format( spec['python'].version.up_to(2).joined) ] return args
LLNL/spack
var/spack/repos/builtin/packages/py-ilmbase/package.py
Python
lgpl-2.1
1,026
[ 30522, 1001, 9385, 2286, 1011, 25682, 5623, 11290, 5974, 2120, 3036, 1010, 11775, 1998, 2060, 1001, 12403, 3600, 2622, 9797, 1012, 2156, 1996, 2327, 1011, 2504, 9385, 5371, 2005, 4751, 1012, 1001, 1001, 23772, 2595, 1011, 6105, 1011, 8909, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: post title: Objetos Validadores date: 2017-07-03 permalink: /:title description: Veja como fazer validações utilizando Objetos ao invés de utilizar programação procedural. image: /images/2017/photo-scott-webb-59043.jpg categories: - OO tags: - validação keywords: - freepascal - fpc - delphi - lazarus - pascal - object-pascal - object-oriented - oop - mdbs99 - validation - validação - teste - testing - validando --- Veja como fazer validações utilizando Objetos ao invés de utilizar programação procedural. <!--more--> ![Unsplash image]({{ page.image }}) ## Introdução {#introducao} Na Orientação a Objetos a codificação deve ser declarativa. Isso quer dizer que, num mundo ideal, iríamos criar os Objetos agrupando-os entre si e, com uma única [mensagem]({% post_url 2016-11-14-diga-me-algo-sobre-voce %}#mensagens), o trabalho a ser realizado seria iniciado e cada Objeto iria realizar parte desse trabalho. Tudo em perfeita harmonia. No entanto, não vivemos num mundo ideal e problemas podem ocorrer. Se pudermos validar o *input* dos dados no nosso sistema antes de iniciar um processo mais elaborado, isso tornaria o processamento menos custoso, menos demorado e menos propenso a erros. No entanto, se devemos codificar de forma declarativa, ou seja, sem condicionais que validem passo-a-passo o que está sendo processado — o *modus operandis* da programação procedural — como seria possível fazer isso utilizando Objetos para deixar o código mais seguro e fazer um tratamento mais adequado para cada problema ou decisão, antes que uma exceção possa ocorrer? ## Validações {#validacoes} Imagine um Formulário onde há diversos campos para o usuário preencher antes de clicar em algum botão que irá fazer algo com os dados preenchidos nos *widgets*. Sempre temos que validar o *input* antes de processá-lo, certo? Tenho trabalhado com desenvolvimento de *software* a muitos anos. Grande parte desse tempo eu codifiquei a validação de campos utilizando o mesmo "padrão" que até hoje é utilizado, independentemente da linguagem utilizada. Vejamos como é esse padrão: <script src="https://gist.github.com/mdbs99/1d990d474d0a15a7543c54c5c02b370a.js"></script> O exemplo acima é sobre um Formulário que contém alguns campos, dentre esses campos temos `Name` e `Birthday`. O primeiro é *string* e não pode estar em branco. Já o segundo deveria ser uma data válida, então o código utiliza a função padrão `SysUtils.TryStrToDate` que verifica se é uma data válida e retorna o valor na variável `MyDate`. Quem nunca fez isso? Pois é. Há problemas demais com essa abordagem: 1. Não podemos reutilizar as validações. Em cada Formulário haverá uma possível cópia do mesmo código; 2. As variáveis locais podem aumentar consideravelmente caso haja mais testes que necessitem de variáveis; 3. O código é totalmente procedural; 4. Não posso utilizar as informações de aviso ao usuário em outra aplicação Web, por exemplo, visto que as *strings* estão codificadas dentro de funções `ShowMessage` (ou qualquer outra função de mensagem para Desktop); 5. O Formulário ficou complexo, visto que há muito código num único evento — e não adianta apenas criar vários métodos privados para cada teste, pois o Formulário irá continuar fazendo coisas demais. Há variantes dessa abordagem acima, porém acredito que todos nós já vimos algo assim ou mesmo estamos codificando dessa maneira ainda hoje. O que podemos fazer para simplificar o código, obter a reutilização das validações e ainda codificar utilizando Orientação a Objetos? ## Constraints {#constraints} *Constraints* são Objetos que tem por função a validação de algum dado ou mesmo a validação de outro Objeto. Cada *constraint* valida apenas 1 artefato. Assim podemos reutilizar a validação em muitos outros lugares. Vamos definir algumas [Interfaces]({% post_url 2016-01-18-interfaces-em-todo-lugar %}): <script src="https://gist.github.com/mdbs99/c668747123d651298e9f40d0e10af5b4.js"></script> Vamos entender cada Interface: 1. `[guids]`: São necessários para *casting* de Interfaces. 2. `IDataInformation`: Representa uma infomação. 3. `IDataInformations`: Representa uma lista de informações. 4. `IDataResult`: Representa um resultado de uma restrição. 5. `IDataConstraint`: Representa uma restrição. 6. `IDataConstraints`: Representa uma lista de restrições. Não estou utilizando *Generics*. Apenas Classes que podem ser reescritas em praticamente qualquer versão do Lazarus ou Delphi. Bem simples. Agora veremos a implementação das Interfaces — por questões de breviedade, vou apresentar somente as assinaturas das Classes: <script src="https://gist.github.com/mdbs99/b254ff882ce27ce9fa4e8219c63e3e96.js"></script> Essas são Classes utilizadas em projetos reais. <del>Em breve</del> todo o código <del>estará</del> já está disponível no [Projeto James](https://github.com/mdbs99/james). Você poderá obter esse código acompanhando a [Issue #17](https://github.com/mdbs99/james/issues/17) do mesmo projeto. Na implementação acima não tem nenhuma Classe que implemente a Interface `IDataConstraint`. O motivo disso é que você, programador, irá criar suas próprias *constraints*. Vejamos um exemplo de como reescrever o código procedural do primeiro exemplo. Precisamos criar duas Classes que implementam `IDataConstraint`. Como só há apenas 1 método nessa Interface, e para não deixar esse artigo ainda maior, vou mostrar o código de apenas uma implementação: <script src="https://gist.github.com/mdbs99/62040307d41fbc45c0f15605acc541b5.js"></script> O código acima mostra como seria a implementação para a *constraint* `TNameConstraint`. O código está *procedural* e ainda pode *melhorar* muito. As variáveis locais poderiam ser retiradas, bastando adicionar mais um *overload* do método `New` na Classe `TDataResult` — você consegue ver essa possibilidade? Conseguiria implementá-la? Abaixo o código de como utilizar todos esses Objetos em conjunto: <script src="https://gist.github.com/mdbs99/5dc64c57916d86d01de561077d831aaf.js"></script> Se nas validações acima o nome estivesse *em branco* mas a data de aniverário tivesse sido digitada *corretamente* — o resultado do método `OK` será verdadeiro se apenas todas as validações passarem no teste — o resultado do `ShowMessage` poderia ser: - Name: Name is empty - Birthday: OK Essa seria apenas uma versão da implementação de como mostrar as informações. Poderia haver muitos outros *decoradores* para mostrar a informação em outros formatos como, por exemplo, HTML numa aplicação Web. ## Conclusão {#conclusao} O código não está completo, mas acredito que posso ter aberto sua mente a novas possibilidades quando se trata de validações. O resultado final de `SaveButtonClick`, mesmo utilizando a Classe `TDataConstraints`, também não foi implementada complemente seguindo o paradigma da Orientação a Objetos — para deixar o código mais sucinto — pois tem um `IF` lá que não deixa o código tão elegante quanto deveria, mas eu acho que dá para você visualizar as possibilidades de uso. A instância de `TDataConstraints` e seus itens poderia ser utilizada em muitos outros lugares do código. A combinação de tais Objetos é virtualmente infinita e seu será o mesmo em *todo* código. O código é *reutilizável* em qualquer tipo de aplicação. Nenhuma informação ou mensagem ao usuário seria duplicada no código. Haverá apenas um *único* lugar, uma única Classe, para fazer a manutenção de cada validação. E a exibição da mensagem poderia ser em qualquer formato, bastando utilizar outros Objetos *decoradores* para ler as *informations*, formatando como quiser. Até logo.
delfire/opp
_posts/2017/2017-07-03-objetos-validadores.md
Markdown
mit
7,933
[ 30522, 1011, 1011, 1011, 9621, 1024, 2695, 2516, 1024, 27885, 15759, 2891, 9398, 26467, 2229, 3058, 1024, 2418, 1011, 5718, 1011, 6021, 2566, 9067, 19839, 1024, 1013, 1024, 2516, 6412, 1024, 2310, 3900, 18609, 6904, 6290, 9398, 22684, 2229,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file. using System; namespace NullConditional { class LoggingDemo { static void Main() { int x = 10; Logger logger = new Logger(); logger.Debug?.Log($"Debug log entry"); logger.Info?.Log($"Info at {DateTime.UtcNow}; x={x}"); } } }
krazymirk/cs7
CS7/CS7/NullConditional/LoggingDemo.cs
C#
gpl-3.0
460
[ 30522, 1013, 1013, 9385, 2418, 6285, 15315, 15558, 1012, 2035, 2916, 9235, 1012, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1996, 15895, 6105, 1016, 1012, 1014, 1010, 2004, 2179, 1999, 1996, 6105, 1012, 19067, 2102, 5371, 1012, 2478, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * generated by Xtext */ package uk.ac.kcl.inf.robotics.ui.quickfix; import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider; /** * Custom quickfixes. * * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#quick-fixes */ @SuppressWarnings("all") public class RigidBodiesQuickfixProvider extends DefaultQuickfixProvider { }
szschaler/RigidBodies
uk.ac.kcl.inf.robotics.rigid_bodies.ui/xtend-gen/uk/ac/kcl/inf/robotics/ui/quickfix/RigidBodiesQuickfixProvider.java
Java
mit
366
[ 30522, 1013, 1008, 1008, 1008, 7013, 2011, 1060, 18209, 1008, 1013, 7427, 2866, 1012, 9353, 1012, 21117, 2140, 1012, 1999, 2546, 1012, 21331, 1012, 21318, 1012, 4248, 8873, 2595, 1025, 12324, 8917, 1012, 13232, 1012, 1060, 18209, 1012, 2131...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!doctype html> <html> <head> <meta charset='utf-8'> <title>Manual Column Freeze - Handsontable</title> <!-- Loading Handsontable (full distribution that includes all dependencies) --> <link data-jsfiddle="common" rel="stylesheet" media="screen" href="../dist/handsontable.css"> <link data-jsfiddle="common" rel="stylesheet" media="screen" href="../dist/pikaday/pikaday.css"> <script data-jsfiddle="common" src="../dist/pikaday/pikaday.js"></script> <script data-jsfiddle="common" src="../dist/moment/moment.js"></script> <script data-jsfiddle="common" src="../dist/zeroclipboard/ZeroClipboard.js"></script> <script data-jsfiddle="common" src="../dist/handsontable.js"></script> <!-- Loading demo dependencies. They are used here only to enhance the examples on this page --> <link data-jsfiddle="common" rel="stylesheet" media="screen" href="css/samples.css?20140331"> <script src="js/samples.js"></script> <script src="js/highlight/highlight.pack.js"></script> <link rel="stylesheet" media="screen" href="js/highlight/styles/github.css"> <link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css"> <!-- Facebook open graph. Don't copy this to your project :) --> <meta property="og:title" content="Manual Column Freeze"> <meta property="og:description" content="This page shows how to configure Handsontable Manual Column Freeze Plugin"> <meta property="og:url" content="http://handsontable.com/demo/column_freeze.html"> <meta property="og:image" content="http://handsontable.com/demo/image/og-image.png"> <meta property="og:image:type" content="image/png"> <meta property="og:image:width" content="409"> <meta property="og:image:height" content="164"> <link rel="canonical" href="http://handsontable.com/demo/column_freeze.html"> <!-- Google Analytics for GitHub Page. Don't copy this to your project :) --> <script src="js/ga.js"></script> </head> <body> <div class="wrapper"> <div class="wrapper-row"> <div id="global-menu-clone"> <h1><a href="../index.html">Handsontable</a></h1> </div> <div id="container"> <div class="columnLayout"> <div class="rowLayout"> <div class="descLayout"> <div class="pad" data-jsfiddle="example1"> <h2>Manual Column Freeze</h2> <p>In order to manually freeze a column (in another words - make it fixed), you need to set the <code>manualColumnFreeze</code> config item to <code>true</code> in Handsontable initialization.</p> <p>When the Manual Column Freeze plugin is enabled, you can freeze any non-fixed column and unfreeze any fixed column in your Handsontable instance using the Context Menu.</p> <p>Note: to properly use this plugin, you need to have the Context Menu plugin enabled.</p> <div id="example1" style="width: 400px; height: 300px; overflow: hidden;"></div> <p> <button name="dump" data-instance="ht" data-dump="#example1" title="Prints current data source to Firebug/Chrome Dev Tools"> Dump data to console </button> </p> </div> </div> <div class="codeLayout"> <div class="pad"> <div class="jsFiddle"> <button class="jsFiddleLink" data-runfiddle="example1">Edit in jsFiddle</button> </div> <script data-jsfiddle="example1"> var myData = Handsontable.helper.createSpreadsheetData(1000, 100); var container = document.getElementById('example1'); var ht = new Handsontable(container, { data: myData, rowHeaders: true, colHeaders: true, fixedColumnsLeft: 2, contextMenu: true, manualColumnFreeze: true }); </script> </div> </div> </div> <div class="footer-text"> </div> </div> </div> </div> </div> <div id="outside-links-wrapper"></div> </body> </html>
siansell/perch-cms-fieldtype-piechart
simona_piechart/handsontable-0.19.0/demo/column_freeze.html
HTML
mit
4,220
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1005, 21183, 2546, 1011, 1022, 1005, 1028, 1026, 2516, 1028, 6410, 5930, 13184, 1011, 2398, 12162, 3085, 1026, 1013, 30524, 21...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
\hypertarget{structParticleSystem_1_1GravObj}{\section{Particle\-System\-:\-:Grav\-Obj Strukturreferenz} \label{structParticleSystem_1_1GravObj}\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}} } {\ttfamily \#include $<$Particle\-System.\-h$>$} \subsection*{Öffentliche Attribute} \begin{DoxyCompactItemize} \item cl\-\_\-float \hyperlink{structParticleSystem_1_1GravObj_af8b40c8baac8ffc87c2ff94da520e6e6}{x} \item cl\-\_\-float \hyperlink{structParticleSystem_1_1GravObj_a61f790d3ed600fe93af533abee250297}{y} \item cl\-\_\-float \hyperlink{structParticleSystem_1_1GravObj_aa8d66d46d2ec63bbdcc8b451e2283278}{z} \item cl\-\_\-float \hyperlink{structParticleSystem_1_1GravObj_adbf1a8e24d75b5826eea902b063bcb1c}{mass} \end{DoxyCompactItemize} \subsection{Ausführliche Beschreibung} Definiert in Zeile 49 der Datei Particle\-System.\-h. \subsection{Dokumentation der Datenelemente} \hypertarget{structParticleSystem_1_1GravObj_adbf1a8e24d75b5826eea902b063bcb1c}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!mass@{mass}} \index{mass@{mass}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}} \subsubsection[{mass}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::mass}}\label{structParticleSystem_1_1GravObj_adbf1a8e24d75b5826eea902b063bcb1c} Definiert in Zeile 53 der Datei Particle\-System.\-h. \hypertarget{structParticleSystem_1_1GravObj_af8b40c8baac8ffc87c2ff94da520e6e6}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!x@{x}} \index{x@{x}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}} \subsubsection[{x}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::x}}\label{structParticleSystem_1_1GravObj_af8b40c8baac8ffc87c2ff94da520e6e6} Definiert in Zeile 50 der Datei Particle\-System.\-h. \hypertarget{structParticleSystem_1_1GravObj_a61f790d3ed600fe93af533abee250297}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!y@{y}} \index{y@{y}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}} \subsubsection[{y}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::y}}\label{structParticleSystem_1_1GravObj_a61f790d3ed600fe93af533abee250297} Definiert in Zeile 51 der Datei Particle\-System.\-h. \hypertarget{structParticleSystem_1_1GravObj_aa8d66d46d2ec63bbdcc8b451e2283278}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!z@{z}} \index{z@{z}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}} \subsubsection[{z}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::z}}\label{structParticleSystem_1_1GravObj_aa8d66d46d2ec63bbdcc8b451e2283278} Definiert in Zeile 52 der Datei Particle\-System.\-h. Die Dokumentation für diese Struktur wurde erzeugt aufgrund der Datei\-:\begin{DoxyCompactItemize} \item /daten/\-Projekte/eclipse\-\_\-workspace/\-C\-L\-G\-L\-\_\-test/\hyperlink{CLGL__test_2ParticleSystem_8h}{Particle\-System.\-h}\end{DoxyCompactItemize}
vroland/SimpleAnalyzer
doc/latex/structParticleSystem_1_1GravObj.tex
TeX
agpl-3.0
3,081
[ 30522, 1032, 23760, 7559, 18150, 1063, 2358, 6820, 6593, 19362, 4588, 4244, 30524, 1011, 1024, 24665, 11431, 1032, 1011, 27885, 3501, 2358, 6820, 25509, 3126, 2890, 7512, 2368, 2480, 1065, 1032, 3830, 1063, 2358, 6820, 6593, 19362, 4588, 42...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
window.WebServiceClientTest = new Class( { Implements : [Events, JsTestClass, Options], Binds : ['onDocumentReady', 'onDocumentError'], options : { testMethods : [ { method : 'initialize_', isAsynchron : false }] }, constants : { }, initialize : function( options ) { this.setOptions( options ); this.webServiceClient; }, beforeEachTest : function(){ this.webServiceClient = new WebServiceClient({ }); }, afterEachTest : function (){ this.webServiceClient = null; }, initialize_ : function() { assertThat( this.webServiceClient, JsHamcrest.Matchers.instanceOf( WebServiceClient )); } });
ZsZs/ProcessPuzzleUI
Implementation/WebTier/WebContent/JavaScript/ObjectTests/WebServiceClient/WebServiceClientTest.js
JavaScript
agpl-3.0
736
[ 30522, 3332, 1012, 4773, 8043, 7903, 8586, 8751, 3372, 22199, 1027, 2047, 2465, 1006, 1063, 22164, 1024, 1031, 2824, 1010, 1046, 13473, 3367, 26266, 1010, 7047, 1033, 1010, 20817, 1024, 1031, 1005, 2006, 3527, 24894, 4765, 16416, 5149, 1005...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=.6, maximum-scale=1, user-scalable=no"> <!-- Angular --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.min.js"></script> <!-- Firebase --> <script src="https://cdn.firebase.com/js/client/2.1.0/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/0.9.1/angularfire.min.js"></script> <script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script> <!-- https://github.com/gajus/angular-swing --> <script src="./js/lib/angular-swing.min.js"></script> <!-- GreekCards App --> <script src="./js/controller/card-stack.js"></script> <script src="./js/controller/modals.js"></script> <!-- Google Analitics --> <script src="./js/lib/ga.js"></script> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.2.js"></script> <!-- GreekCards App CSS --> <link rel="stylesheet" href="./css/card-stack.css"> </head> <body ng-app="studystack"> <header ng-controller="DropdownCtrl"> <nav ng-include="'views/nav.html'"> </nav> </header> <main ng-view></main> </body> </html>
bryanjimenez/studystack
index.html
HTML
gpl-2.0
1,572
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 4180, 1027, 1000, 9381, 1027, 5080...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2004-2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== // TODO(omaha): this code should be updated according to code published by // Microsoft at http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx. // We need a more rigorous clasification of versions. #ifndef OMAHA_BASE_SYSTEM_INFO_H_ #define OMAHA_BASE_SYSTEM_INFO_H_ #include <windows.h> #include <tchar.h> namespace omaha { // TODO(omaha): refactor to use a namespace. class SystemInfo { public: // Find out if the OS is at least Windows 2000 // Service pack 4. If OS version is less than that // will return false, all other cases true. static bool OSWin2KSP4OrLater() { // Use GetVersionEx to get OS and Service Pack information. OSVERSIONINFOEX osviex; ::ZeroMemory(&osviex, sizeof(osviex)); osviex.dwOSVersionInfoSize = sizeof(osviex); BOOL success = ::GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&osviex)); // If this failed we're on Win9X or a pre NT4SP6 OS. if (!success) { return false; } if (osviex.dwMajorVersion < 5) { return false; } if (osviex.dwMajorVersion > 5) { return true; // way beyond Windows XP. } if (osviex.dwMinorVersion >= 1) { return true; // Windows XP or better. } if (osviex.wServicePackMajor >= 4) { return true; // Windows 2000 SP4. } return false; // Windows 2000, < SP4. } // Returns true if the OS is at least XP SP2. static bool OSWinXPSP2OrLater(); // CategorizeOS returns a categorization of what operating system is running, // and the service pack level. // NOTE: Please keep this in the order of increasing OS versions enum OSVersionType { OS_WINDOWS_UNKNOWN = 1, OS_WINDOWS_9X_OR_NT, OS_WINDOWS_2000, OS_WINDOWS_XP, OS_WINDOWS_SERVER_2003, OS_WINDOWS_VISTA, OS_WINDOWS_7 }; static HRESULT CategorizeOS(OSVersionType* os_version, DWORD* service_pack); static const wchar_t* OSVersionTypeAsString(OSVersionType t); // Returns true if the current operating system is Windows 2000. static bool IsRunningOnW2K(); // Are we running on Windows XP or later. static bool IsRunningOnXPOrLater(); // Are we running on Windows XP SP1 or later. static bool IsRunningOnXPSP1OrLater(); // Are we running on Windows Vista or later. static bool IsRunningOnVistaOrLater(); static bool IsRunningOnVistaRTM(); // Returns the version and the name of the operating system. static bool GetSystemVersion(int* major_version, int* minor_version, int* service_pack_major, int* service_pack_minor, TCHAR* name_buf, size_t name_buf_len); // Returns the processor architecture. We use wProcessorArchitecture in // SYSTEM_INFO returned by ::GetNativeSystemInfo() to detect the processor // architecture of the installed operating system. Note the "Native" in the // function name - this is important. See // http://msdn.microsoft.com/en-us/library/ms724340.aspx. static DWORD GetProcessorArchitecture(); // Returns whether this is a 64-bit Windows system. static bool Is64BitWindows(); }; } // namespace omaha #endif // OMAHA_BASE_SYSTEM_INFO_H_
priaonehaha/omaha
base/system_info.h
C
apache-2.0
3,921
[ 30522, 1013, 1013, 9385, 2432, 1011, 2268, 8224, 4297, 1012, 1013, 1013, 1013, 1013, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1013, 1013, 2017, 2089, 2025, 2224, 2023, 5371, 32...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
jsonp({"cep":"79831335","logradouro":"Rua Projetada JA","bairro":"Jardim Ayde","cidade":"Dourados","uf":"MS","estado":"Mato Grosso do Sul"});
lfreneda/cepdb
api/v1/79831335.jsonp.js
JavaScript
cc0-1.0
142
[ 30522, 1046, 3385, 2361, 1006, 1063, 1000, 8292, 2361, 1000, 1024, 1000, 6535, 2620, 21486, 22394, 2629, 1000, 1010, 1000, 8833, 12173, 8162, 2080, 1000, 1024, 1000, 21766, 2050, 4013, 15759, 8447, 14855, 1000, 1010, 1000, 21790, 18933, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickSettingsTests { public class TheSetDefineMethod { [Fact] public void ShouldSetTheDefine() { using (var image = new MagickImage()) { image.Settings.SetDefine(MagickFormat.Jpeg, "optimize-coding", "test"); Assert.Equal("test", image.Settings.GetDefine(MagickFormat.Jpg, "optimize-coding")); Assert.Equal("test", image.Settings.GetDefine(MagickFormat.Jpeg, "optimize-coding")); } } [Fact] public void ShouldChangeTheBooleanToString() { using (var image = new MagickImage()) { image.Settings.SetDefine(MagickFormat.Jpeg, "optimize-coding", true); Assert.Equal("true", image.Settings.GetDefine(MagickFormat.Jpeg, "optimize-coding")); } } [Fact] public void ShouldChangeTheIntToString() { using (var image = new MagickImage()) { image.Settings.SetDefine(MagickFormat.Jpeg, "optimize-coding", 42); Assert.Equal("42", image.Settings.GetDefine(MagickFormat.Jpeg, "optimize-coding")); } } [Fact] public void ShouldUseTheSpecifiedName() { using (var image = new MagickImage()) { image.Settings.SetDefine("profile:skip", "ICC"); Assert.Equal("ICC", image.Settings.GetDefine("profile:skip")); } } } } }
dlemstra/Magick.NET
tests/Magick.NET.Tests/Settings/MagickSettingsTests/TheSetDefineMethod.cs
C#
apache-2.0
1,906
[ 30522, 1013, 1013, 9385, 17594, 3393, 5244, 6494, 16770, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012, 1013, 21469, 6633, 20528, 1013, 3894, 2243, 1012, 5658, 1012, 1013, 1013, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const Cogl = imports.gi.Cogl; const GLib = imports.gi.GLib; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Meta = imports.gi.Meta; const Pango = imports.gi.Pango; const St = imports.gi.St; const Shell = imports.gi.Shell; const Signals = imports.signals; const Lang = imports.lang; const Mainloop = imports.mainloop; const System = imports.system; const History = imports.misc.history; const ExtensionSystem = imports.ui.extensionSystem; const ExtensionUtils = imports.misc.extensionUtils; const ShellEntry = imports.ui.shellEntry; const Tweener = imports.ui.tweener; const Main = imports.ui.main; const JsParse = imports.misc.jsParse; const CHEVRON = '>>> '; /* Imports...feel free to add here as needed */ var commandHeader = 'const Clutter = imports.gi.Clutter; ' + 'const GLib = imports.gi.GLib; ' + 'const GObject = imports.gi.GObject; ' + 'const Gio = imports.gi.Gio; ' + 'const Gtk = imports.gi.Gtk; ' + 'const Mainloop = imports.mainloop; ' + 'const Meta = imports.gi.Meta; ' + 'const Shell = imports.gi.Shell; ' + 'const Tp = imports.gi.TelepathyGLib; ' + 'const Main = imports.ui.main; ' + 'const Lang = imports.lang; ' + 'const Tweener = imports.ui.tweener; ' + /* Utility functions...we should probably be able to use these * in the shell core code too. */ 'const stage = global.stage; ' + /* Special lookingGlass functions */ 'const inspect = Lang.bind(Main.lookingGlass, Main.lookingGlass.inspect); ' + 'const it = Main.lookingGlass.getIt(); ' + 'const r = Lang.bind(Main.lookingGlass, Main.lookingGlass.getResult); '; const HISTORY_KEY = 'looking-glass-history'; // Time between tabs for them to count as a double-tab event const AUTO_COMPLETE_DOUBLE_TAB_DELAY = 500; const AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION = 0.2; const AUTO_COMPLETE_GLOBAL_KEYWORDS = _getAutoCompleteGlobalKeywords(); function _getAutoCompleteGlobalKeywords() { const keywords = ['true', 'false', 'null', 'new']; // Don't add the private properties of window (i.e., ones starting with '_') const windowProperties = Object.getOwnPropertyNames(window).filter(function(a){ return a.charAt(0) != '_' }); const headerProperties = JsParse.getDeclaredConstants(commandHeader); return keywords.concat(windowProperties).concat(headerProperties); } const AutoComplete = new Lang.Class({ Name: 'AutoComplete', _init: function(entry) { this._entry = entry; this._entry.connect('key-press-event', Lang.bind(this, this._entryKeyPressEvent)); this._lastTabTime = global.get_current_time(); }, _processCompletionRequest: function(event) { if (event.completions.length == 0) { return; } // Unique match = go ahead and complete; multiple matches + single tab = complete the common starting string; // multiple matches + double tab = emit a suggest event with all possible options if (event.completions.length == 1) { this.additionalCompletionText(event.completions[0], event.attrHead); this.emit('completion', { completion: event.completions[0], type: 'whole-word' }); } else if (event.completions.length > 1 && event.tabType === 'single') { let commonPrefix = JsParse.getCommonPrefix(event.completions); if (commonPrefix.length > 0) { this.additionalCompletionText(commonPrefix, event.attrHead); this.emit('completion', { completion: commonPrefix, type: 'prefix' }); this.emit('suggest', { completions: event.completions}); } } else if (event.completions.length > 1 && event.tabType === 'double') { this.emit('suggest', { completions: event.completions}); } }, _entryKeyPressEvent: function(actor, event) { let cursorPos = this._entry.clutter_text.get_cursor_position(); let text = this._entry.get_text(); if (cursorPos != -1) { text = text.slice(0, cursorPos); } if (event.get_key_symbol() == Clutter.Tab) { let [completions, attrHead] = JsParse.getCompletions(text, commandHeader, AUTO_COMPLETE_GLOBAL_KEYWORDS); let currTime = global.get_current_time(); if ((currTime - this._lastTabTime) < AUTO_COMPLETE_DOUBLE_TAB_DELAY) { this._processCompletionRequest({ tabType: 'double', completions: completions, attrHead: attrHead }); } else { this._processCompletionRequest({ tabType: 'single', completions: completions, attrHead: attrHead }); } this._lastTabTime = currTime; } return Clutter.EVENT_PROPAGATE; }, // Insert characters of text not already included in head at cursor position. i.e., if text="abc" and head="a", // the string "bc" will be appended to this._entry additionalCompletionText: function(text, head) { let additionalCompletionText = text.slice(head.length); let cursorPos = this._entry.clutter_text.get_cursor_position(); this._entry.clutter_text.insert_text(additionalCompletionText, cursorPos); } }); Signals.addSignalMethods(AutoComplete.prototype); const Notebook = new Lang.Class({ Name: 'Notebook', _init: function() { this.actor = new St.BoxLayout({ vertical: true }); this.tabControls = new St.BoxLayout({ style_class: 'labels' }); this._selectedIndex = -1; this._tabs = []; }, appendPage: function(name, child) { let labelBox = new St.BoxLayout({ style_class: 'notebook-tab', reactive: true, track_hover: true }); let label = new St.Button({ label: name }); label.connect('clicked', Lang.bind(this, function () { this.selectChild(child); return true; })); labelBox.add(label, { expand: true }); this.tabControls.add(labelBox); let scrollview = new St.ScrollView({ x_fill: true, y_fill: true }); scrollview.get_hscroll_bar().hide(); scrollview.add_actor(child); let tabData = { child: child, labelBox: labelBox, label: label, scrollView: scrollview, _scrollToBottom: false }; this._tabs.push(tabData); scrollview.hide(); this.actor.add(scrollview, { expand: true }); let vAdjust = scrollview.vscroll.adjustment; vAdjust.connect('changed', Lang.bind(this, function () { this._onAdjustScopeChanged(tabData); })); vAdjust.connect('notify::value', Lang.bind(this, function() { this._onAdjustValueChanged(tabData); })); if (this._selectedIndex == -1) this.selectIndex(0); }, _unselect: function() { if (this._selectedIndex < 0) return; let tabData = this._tabs[this._selectedIndex]; tabData.labelBox.remove_style_pseudo_class('selected'); tabData.scrollView.hide(); this._selectedIndex = -1; }, selectIndex: function(index) { if (index == this._selectedIndex) return; if (index < 0) { this._unselect(); this.emit('selection', null); return; } // Focus the new tab before unmapping the old one let tabData = this._tabs[index]; if (!tabData.scrollView.navigate_focus(null, Gtk.DirectionType.TAB_FORWARD, false)) this.actor.grab_key_focus(); this._unselect(); tabData.labelBox.add_style_pseudo_class('selected'); tabData.scrollView.show(); this._selectedIndex = index; this.emit('selection', tabData.child); }, selectChild: function(child) { if (child == null) this.selectIndex(-1); else { for (let i = 0; i < this._tabs.length; i++) { let tabData = this._tabs[i]; if (tabData.child == child) { this.selectIndex(i); return; } } } }, scrollToBottom: function(index) { let tabData = this._tabs[index]; tabData._scrollToBottom = true; }, _onAdjustValueChanged: function (tabData) { let vAdjust = tabData.scrollView.vscroll.adjustment; if (vAdjust.value < (vAdjust.upper - vAdjust.lower - 0.5)) tabData._scrolltoBottom = false; }, _onAdjustScopeChanged: function (tabData) { if (!tabData._scrollToBottom) return; let vAdjust = tabData.scrollView.vscroll.adjustment; vAdjust.value = vAdjust.upper - vAdjust.page_size; }, nextTab: function() { let nextIndex = this._selectedIndex; if (nextIndex < this._tabs.length - 1) { ++nextIndex; } this.selectIndex(nextIndex); }, prevTab: function() { let prevIndex = this._selectedIndex; if (prevIndex > 0) { --prevIndex; } this.selectIndex(prevIndex); } }); Signals.addSignalMethods(Notebook.prototype); function objectToString(o) { if (typeof(o) == typeof(objectToString)) { // special case this since the default is way, way too verbose return '<js function>'; } else { return '' + o; } } const ObjLink = new Lang.Class({ Name: 'ObjLink', _init: function(lookingGlass, o, title) { let text; if (title) text = title; else text = objectToString(o); text = GLib.markup_escape_text(text, -1); this._obj = o; this.actor = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: text }); this.actor.get_child().single_line_mode = true; this.actor.connect('clicked', Lang.bind(this, this._onClicked)); this._lookingGlass = lookingGlass; }, _onClicked: function (link) { this._lookingGlass.inspectObject(this._obj, this.actor); } }); const Result = new Lang.Class({ Name: 'Result', _init: function(lookingGlass, command, o, index) { this.index = index; this.o = o; this.actor = new St.BoxLayout({ vertical: true }); this._lookingGlass = lookingGlass; let cmdTxt = new St.Label({ text: command }); cmdTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END; this.actor.add(cmdTxt); let box = new St.BoxLayout({}); this.actor.add(box); let resultTxt = new St.Label({ text: 'r(' + index + ') = ' }); resultTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END; box.add(resultTxt); let objLink = new ObjLink(this._lookingGlass, o); box.add(objLink.actor); } }); const WindowList = new Lang.Class({ Name: 'WindowList', _init: function(lookingGlass) { this.actor = new St.BoxLayout({ name: 'Windows', vertical: true, style: 'spacing: 8px' }); let tracker = Shell.WindowTracker.get_default(); this._updateId = Main.initializeDeferredWork(this.actor, Lang.bind(this, this._updateWindowList)); global.display.connect('window-created', Lang.bind(this, this._updateWindowList)); tracker.connect('tracked-windows-changed', Lang.bind(this, this._updateWindowList)); this._lookingGlass = lookingGlass; }, _updateWindowList: function() { this.actor.destroy_all_children(); let windows = global.get_window_actors(); let tracker = Shell.WindowTracker.get_default(); for (let i = 0; i < windows.length; i++) { let metaWindow = windows[i].metaWindow; // Avoid multiple connections if (!metaWindow._lookingGlassManaged) { metaWindow.connect('unmanaged', Lang.bind(this, this._updateWindowList)); metaWindow._lookingGlassManaged = true; } let box = new St.BoxLayout({ vertical: true }); this.actor.add(box); let windowLink = new ObjLink(this._lookingGlass, metaWindow, metaWindow.title); box.add(windowLink.actor, { x_align: St.Align.START, x_fill: false }); let propsBox = new St.BoxLayout({ vertical: true, style: 'padding-left: 6px;' }); box.add(propsBox); propsBox.add(new St.Label({ text: 'wmclass: ' + metaWindow.get_wm_class() })); let app = tracker.get_window_app(metaWindow); if (app != null && !app.is_window_backed()) { let icon = app.create_icon_texture(22); let propBox = new St.BoxLayout({ style: 'spacing: 6px; ' }); propsBox.add(propBox); propBox.add(new St.Label({ text: 'app: ' }), { y_fill: false }); let appLink = new ObjLink(this._lookingGlass, app, app.get_id()); propBox.add(appLink.actor, { y_fill: false }); propBox.add(icon, { y_fill: false }); } else { propsBox.add(new St.Label({ text: '<untracked>' })); } } } }); Signals.addSignalMethods(WindowList.prototype); const ObjInspector = new Lang.Class({ Name: 'ObjInspector', _init: function(lookingGlass) { this._obj = null; this._previousObj = null; this._parentList = []; this.actor = new St.ScrollView({ pivot_point: new Clutter.Point({ x: 0.5, y: 0.5 }), x_fill: true, y_fill: true }); this.actor.get_hscroll_bar().hide(); this._container = new St.BoxLayout({ name: 'LookingGlassPropertyInspector', style_class: 'lg-dialog', vertical: true }); this.actor.add_actor(this._container); this._lookingGlass = lookingGlass; }, selectObject: function(obj, skipPrevious) { if (!skipPrevious) this._previousObj = this._obj; else this._previousObj = null; this._obj = obj; this._container.destroy_all_children(); let hbox = new St.BoxLayout({ style_class: 'lg-obj-inspector-title' }); this._container.add_actor(hbox); let label = new St.Label({ text: 'Inspecting: %s: %s'.format(typeof(obj), objectToString(obj)) }); label.single_line_mode = true; hbox.add(label, { expand: true, y_fill: false }); let button = new St.Button({ label: 'Insert', style_class: 'lg-obj-inspector-button' }); button.connect('clicked', Lang.bind(this, this._onInsert)); hbox.add(button); if (this._previousObj != null) { button = new St.Button({ label: 'Back', style_class: 'lg-obj-inspector-button' }); button.connect('clicked', Lang.bind(this, this._onBack)); hbox.add(button); } button = new St.Button({ style_class: 'window-close' }); button.connect('clicked', Lang.bind(this, this.close)); hbox.add(button); if (typeof(obj) == typeof({})) { let properties = []; for (let propName in obj) { properties.push(propName); } properties.sort(); for (let i = 0; i < properties.length; i++) { let propName = properties[i]; let valueStr; let link; try { let prop = obj[propName]; link = new ObjLink(this._lookingGlass, prop).actor; } catch (e) { link = new St.Label({ text: '<error>' }); } let hbox = new St.BoxLayout(); let propText = propName + ': ' + valueStr; hbox.add(new St.Label({ text: propName + ': ' })); hbox.add(link); this._container.add_actor(hbox); } } }, open: function(sourceActor) { if (this._open) return; this._previousObj = null; this._open = true; this.actor.show(); if (sourceActor) { this.actor.set_scale(0, 0); Tweener.addTween(this.actor, { scale_x: 1, scale_y: 1, transition: 'easeOutQuad', time: 0.2 }); } else { this.actor.set_scale(1, 1); } }, close: function() { if (!this._open) return; this._open = false; this.actor.hide(); this._previousObj = null; this._obj = null; }, _onInsert: function() { let obj = this._obj; this.close(); this._lookingGlass.insertObject(obj); }, _onBack: function() { this.selectObject(this._previousObj, true); } }); const RedBorderEffect = new Lang.Class({ Name: 'RedBorderEffect', Extends: Clutter.Effect, vfunc_paint: function() { let actor = this.get_actor(); actor.continue_paint(); let color = new Cogl.Color(); color.init_from_4ub(0xff, 0, 0, 0xc4); Cogl.set_source_color(color); let geom = actor.get_allocation_geometry(); let width = 2; // clockwise order Cogl.rectangle(0, 0, geom.width, width); Cogl.rectangle(geom.width - width, width, geom.width, geom.height); Cogl.rectangle(0, geom.height, geom.width - width, geom.height - width); Cogl.rectangle(0, geom.height - width, width, width); }, }); const Inspector = new Lang.Class({ Name: 'Inspector', _init: function(lookingGlass) { let container = new Shell.GenericContainer({ width: 0, height: 0 }); container.connect('allocate', Lang.bind(this, this._allocate)); Main.uiGroup.add_actor(container); let eventHandler = new St.BoxLayout({ name: 'LookingGlassDialog', vertical: false, reactive: true }); this._eventHandler = eventHandler; container.add_actor(eventHandler); this._displayText = new St.Label(); eventHandler.add(this._displayText, { expand: true }); eventHandler.connect('key-press-event', Lang.bind(this, this._onKeyPressEvent)); eventHandler.connect('button-press-event', Lang.bind(this, this._onButtonPressEvent)); eventHandler.connect('scroll-event', Lang.bind(this, this._onScrollEvent)); eventHandler.connect('motion-event', Lang.bind(this, this._onMotionEvent)); Clutter.grab_pointer(eventHandler); Clutter.grab_keyboard(eventHandler); // this._target is the actor currently shown by the inspector. // this._pointerTarget is the actor directly under the pointer. // Normally these are the same, but if you use the scroll wheel // to drill down, they'll diverge until you either scroll back // out, or move the pointer outside of _pointerTarget. this._target = null; this._pointerTarget = null; this._lookingGlass = lookingGlass; }, _allocate: function(actor, box, flags) { if (!this._eventHandler) return; let primary = Main.layoutManager.primaryMonitor; let [minWidth, minHeight, natWidth, natHeight] = this._eventHandler.get_preferred_size(); let childBox = new Clutter.ActorBox(); childBox.x1 = primary.x + Math.floor((primary.width - natWidth) / 2); childBox.x2 = childBox.x1 + natWidth; childBox.y1 = primary.y + Math.floor((primary.height - natHeight) / 2); childBox.y2 = childBox.y1 + natHeight; this._eventHandler.allocate(childBox, flags); }, _close: function() { Clutter.ungrab_pointer(); Clutter.ungrab_keyboard(); this._eventHandler.destroy(); this._eventHandler = null; this.emit('closed'); }, _onKeyPressEvent: function (actor, event) { if (event.get_key_symbol() == Clutter.Escape) this._close(); return Clutter.EVENT_STOP; }, _onButtonPressEvent: function (actor, event) { if (this._target) { let [stageX, stageY] = event.get_coords(); this.emit('target', this._target, stageX, stageY); } this._close(); return Clutter.EVENT_STOP; }, _onScrollEvent: function (actor, event) { switch (event.get_scroll_direction()) { case Clutter.ScrollDirection.UP: // select parent let parent = this._target.get_parent(); if (parent != null) { this._target = parent; this._update(event); } break; case Clutter.ScrollDirection.DOWN: // select child if (this._target != this._pointerTarget) { let child = this._pointerTarget; while (child) { let parent = child.get_parent(); if (parent == this._target) break; child = parent; } if (child) { this._target = child; this._update(event); } } break; default: break; } return Clutter.EVENT_STOP; }, _onMotionEvent: function (actor, event) { this._update(event); return Clutter.EVENT_STOP; }, _update: function(event) { let [stageX, stageY] = event.get_coords(); let target = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, stageX, stageY); if (target != this._pointerTarget) this._target = target; this._pointerTarget = target; let position = '[inspect x: ' + stageX + ' y: ' + stageY + ']'; this._displayText.text = ''; this._displayText.text = position + ' ' + this._target; this._lookingGlass.setBorderPaintTarget(this._target); } }); Signals.addSignalMethods(Inspector.prototype); const Extensions = new Lang.Class({ Name: 'Extensions', _init: function(lookingGlass) { this._lookingGlass = lookingGlass; this.actor = new St.BoxLayout({ vertical: true, name: 'lookingGlassExtensions' }); this._noExtensions = new St.Label({ style_class: 'lg-extensions-none', text: _("No extensions installed") }); this._numExtensions = 0; this._extensionsList = new St.BoxLayout({ vertical: true, style_class: 'lg-extensions-list' }); this._extensionsList.add(this._noExtensions); this.actor.add(this._extensionsList); for (let uuid in ExtensionUtils.extensions) this._loadExtension(null, uuid); ExtensionSystem.connect('extension-loaded', Lang.bind(this, this._loadExtension)); }, _loadExtension: function(o, uuid) { let extension = ExtensionUtils.extensions[uuid]; // There can be cases where we create dummy extension metadata // that's not really a proper extension. Don't bother with these. if (!extension.metadata.name) return; let extensionDisplay = this._createExtensionDisplay(extension); if (this._numExtensions == 0) this._extensionsList.remove_actor(this._noExtensions); this._numExtensions ++; this._extensionsList.add(extensionDisplay); }, _onViewSource: function (actor) { let extension = actor._extension; let uri = extension.dir.get_uri(); Gio.app_info_launch_default_for_uri(uri, global.create_app_launch_context(0, -1)); this._lookingGlass.close(); }, _onWebPage: function (actor) { let extension = actor._extension; Gio.app_info_launch_default_for_uri(extension.metadata.url, global.create_app_launch_context(0, -1)); this._lookingGlass.close(); }, _onViewErrors: function (actor) { let extension = actor._extension; let shouldShow = !actor._isShowing; if (shouldShow) { let errors = extension.errors; let errorDisplay = new St.BoxLayout({ vertical: true }); if (errors && errors.length) { for (let i = 0; i < errors.length; i ++) errorDisplay.add(new St.Label({ text: errors[i] })); } else { /* Translators: argument is an extension UUID. */ let message = _("%s has not emitted any errors.").format(extension.uuid); errorDisplay.add(new St.Label({ text: message })); } actor._errorDisplay = errorDisplay; actor._parentBox.add(errorDisplay); actor.label = _("Hide Errors"); } else { actor._errorDisplay.destroy(); actor._errorDisplay = null; actor.label = _("Show Errors"); } actor._isShowing = shouldShow; }, _stateToString: function(extensionState) { switch (extensionState) { case ExtensionSystem.ExtensionState.ENABLED: return _("Enabled"); case ExtensionSystem.ExtensionState.DISABLED: case ExtensionSystem.ExtensionState.INITIALIZED: return _("Disabled"); case ExtensionSystem.ExtensionState.ERROR: return _("Error"); case ExtensionSystem.ExtensionState.OUT_OF_DATE: return _("Out of date"); case ExtensionSystem.ExtensionState.DOWNLOADING: return _("Downloading"); } return 'Unknown'; // Not translated, shouldn't appear }, _createExtensionDisplay: function(extension) { let box = new St.BoxLayout({ style_class: 'lg-extension', vertical: true }); let name = new St.Label({ style_class: 'lg-extension-name', text: extension.metadata.name }); box.add(name, { expand: true }); let description = new St.Label({ style_class: 'lg-extension-description', text: extension.metadata.description || 'No description' }); box.add(description, { expand: true }); let metaBox = new St.BoxLayout({ style_class: 'lg-extension-meta' }); box.add(metaBox); let stateString = this._stateToString(extension.state); let state = new St.Label({ style_class: 'lg-extension-state', text: this._stateToString(extension.state) }); metaBox.add(state); let viewsource = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("View Source") }); viewsource._extension = extension; viewsource.connect('clicked', Lang.bind(this, this._onViewSource)); metaBox.add(viewsource); if (extension.metadata.url) { let webpage = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("Web Page") }); webpage._extension = extension; webpage.connect('clicked', Lang.bind(this, this._onWebPage)); metaBox.add(webpage); } let viewerrors = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("Show Errors") }); viewerrors._extension = extension; viewerrors._parentBox = box; viewerrors._isShowing = false; viewerrors.connect('clicked', Lang.bind(this, this._onViewErrors)); metaBox.add(viewerrors); return box; } }); const LookingGlass = new Lang.Class({ Name: 'LookingGlass', _init : function() { this._borderPaintTarget = null; this._redBorderEffect = new RedBorderEffect(); this._open = false; this._offset = 0; this._results = []; // Sort of magic, but...eh. this._maxItems = 150; this.actor = new St.BoxLayout({ name: 'LookingGlassDialog', style_class: 'lg-dialog', vertical: true, visible: false, reactive: true }); this.actor.connect('key-press-event', Lang.bind(this, this._globalKeyPressEvent)); this._interfaceSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.interface' }); this._interfaceSettings.connect('changed::monospace-font-name', Lang.bind(this, this._updateFont)); this._updateFont(); // We want it to appear to slide out from underneath the panel Main.uiGroup.add_actor(this.actor); Main.uiGroup.set_child_below_sibling(this.actor, Main.layoutManager.panelBox); Main.layoutManager.panelBox.connect('allocation-changed', Lang.bind(this, this._queueResize)); Main.layoutManager.keyboardBox.connect('allocation-changed', Lang.bind(this, this._queueResize)); this._objInspector = new ObjInspector(this); Main.uiGroup.add_actor(this._objInspector.actor); this._objInspector.actor.hide(); let toolbar = new St.BoxLayout({ name: 'Toolbar' }); this.actor.add_actor(toolbar); let inspectIcon = new St.Icon({ icon_name: 'gtk-color-picker', icon_size: 24 }); toolbar.add_actor(inspectIcon); inspectIcon.reactive = true; inspectIcon.connect('button-press-event', Lang.bind(this, function () { let inspector = new Inspector(this); inspector.connect('target', Lang.bind(this, function(i, target, stageX, stageY) { this._pushResult('inspect(' + Math.round(stageX) + ', ' + Math.round(stageY) + ')', target); })); inspector.connect('closed', Lang.bind(this, function() { this.actor.show(); global.stage.set_key_focus(this._entry); })); this.actor.hide(); return Clutter.EVENT_STOP; })); let gcIcon = new St.Icon({ icon_name: 'gnome-fs-trash-full', icon_size: 24 }); toolbar.add_actor(gcIcon); gcIcon.reactive = true; gcIcon.connect('button-press-event', Lang.bind(this, function () { gcIcon.icon_name = 'gnome-fs-trash-empty'; System.gc(); this._timeoutId = Mainloop.timeout_add(500, Lang.bind(this, function () { gcIcon.icon_name = 'gnome-fs-trash-full'; this._timeoutId = 0; return GLib.SOURCE_REMOVE; })); GLib.Source.set_name_by_id(this._timeoutId, '[gnome-shell] gcIcon.icon_name = \'gnome-fs-trash-full\''); return Clutter.EVENT_PROPAGATE; })); let notebook = new Notebook(); this._notebook = notebook; this.actor.add(notebook.actor, { expand: true }); let emptyBox = new St.Bin(); toolbar.add(emptyBox, { expand: true }); toolbar.add_actor(notebook.tabControls); this._evalBox = new St.BoxLayout({ name: 'EvalBox', vertical: true }); notebook.appendPage('Evaluator', this._evalBox); this._resultsArea = new St.BoxLayout({ name: 'ResultsArea', vertical: true }); this._evalBox.add(this._resultsArea, { expand: true }); this._entryArea = new St.BoxLayout({ name: 'EntryArea' }); this._evalBox.add_actor(this._entryArea); let label = new St.Label({ text: CHEVRON }); this._entryArea.add(label); this._entry = new St.Entry({ can_focus: true }); ShellEntry.addContextMenu(this._entry); this._entryArea.add(this._entry, { expand: true }); this._windowList = new WindowList(this); notebook.appendPage('Windows', this._windowList.actor); this._extensions = new Extensions(this); notebook.appendPage('Extensions', this._extensions.actor); this._entry.clutter_text.connect('activate', Lang.bind(this, function (o, e) { // Hide any completions we are currently showing this._hideCompletions(); let text = o.get_text(); // Ensure we don't get newlines in the command; the history file is // newline-separated. text = text.replace('\n', ' '); // Strip leading and trailing whitespace text = text.replace(/^\s+/g, '').replace(/\s+$/g, ''); if (text == '') return true; this._evaluate(text); return true; })); this._history = new History.HistoryManager({ gsettingsKey: HISTORY_KEY, entry: this._entry.clutter_text }); this._autoComplete = new AutoComplete(this._entry); this._autoComplete.connect('suggest', Lang.bind(this, function(a,e) { this._showCompletions(e.completions); })); // If a completion is completed unambiguously, the currently-displayed completion // suggestions become irrelevant. this._autoComplete.connect('completion', Lang.bind(this, function(a,e) { if (e.type == 'whole-word') this._hideCompletions(); })); this._resize(); }, _updateFont: function() { let fontName = this._interfaceSettings.get_string('monospace-font-name'); let fontDesc = Pango.FontDescription.from_string(fontName); // We ignore everything but size and style; you'd be crazy to set your system-wide // monospace font to be bold/oblique/etc. Could easily be added here. this.actor.style = 'font-size: ' + fontDesc.get_size() / 1024. + (fontDesc.get_size_is_absolute() ? 'px' : 'pt') + ';' + 'font-family: "' + fontDesc.get_family() + '";'; }, setBorderPaintTarget: function(obj) { if (this._borderPaintTarget != null) this._borderPaintTarget.remove_effect(this._redBorderEffect); this._borderPaintTarget = obj; if (this._borderPaintTarget != null) this._borderPaintTarget.add_effect(this._redBorderEffect); }, _pushResult: function(command, obj) { let index = this._results.length + this._offset; let result = new Result(this, CHEVRON + command, obj, index); this._results.push(result); this._resultsArea.add(result.actor); if (obj instanceof Clutter.Actor) this.setBorderPaintTarget(obj); let children = this._resultsArea.get_children(); if (children.length > this._maxItems) { this._results.shift(); children[0].destroy(); this._offset++; } this._it = obj; // Scroll to bottom this._notebook.scrollToBottom(0); }, _showCompletions: function(completions) { if (!this._completionActor) { this._completionActor = new St.Label({ name: 'LookingGlassAutoCompletionText', style_class: 'lg-completions-text' }); this._completionActor.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; this._completionActor.clutter_text.line_wrap = true; this._evalBox.insert_child_below(this._completionActor, this._entryArea); } this._completionActor.set_text(completions.join(', ')); // Setting the height to -1 allows us to get its actual preferred height rather than // whatever was last given in set_height by Tweener. this._completionActor.set_height(-1); let [minHeight, naturalHeight] = this._completionActor.get_preferred_height(this._resultsArea.get_width()); // Don't reanimate if we are already visible if (this._completionActor.visible) { this._completionActor.height = naturalHeight; } else { this._completionActor.show(); Tweener.removeTweens(this._completionActor); Tweener.addTween(this._completionActor, { time: AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / St.get_slow_down_factor(), transition: 'easeOutQuad', height: naturalHeight, opacity: 255 }); } }, _hideCompletions: function() { if (this._completionActor) { Tweener.removeTweens(this._completionActor); Tweener.addTween(this._completionActor, { time: AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / St.get_slow_down_factor(), transition: 'easeOutQuad', height: 0, opacity: 0, onComplete: Lang.bind(this, function () { this._completionActor.hide(); }) }); } }, _evaluate : function(command) { this._history.addItem(command); let fullCmd = commandHeader + command; let resultObj; try { resultObj = eval(fullCmd); } catch (e) { resultObj = '<exception ' + e + '>'; } this._pushResult(command, resultObj); this._entry.text = ''; }, inspect: function(x, y) { return global.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y); }, getIt: function () { return this._it; }, getResult: function(idx) { return this._results[idx - this._offset].o; }, toggle: function() { if (this._open) this.close(); else this.open(); }, _queueResize: function() { Meta.later_add(Meta.LaterType.BEFORE_REDRAW, Lang.bind(this, function () { this._resize(); })); }, _resize: function() { let primary = Main.layoutManager.primaryMonitor; let myWidth = primary.width * 0.7; let availableHeight = primary.height - Main.layoutManager.keyboardBox.height; let myHeight = Math.min(primary.height * 0.7, availableHeight * 0.9); this.actor.x = primary.x + (primary.width - myWidth) / 2; this._hiddenY = primary.y + Main.layoutManager.panelBox.height - myHeight - 4; // -4 to hide the top corners this._targetY = this._hiddenY + myHeight; this.actor.y = this._hiddenY; this.actor.width = myWidth; this.actor.height = myHeight; this._objInspector.actor.set_size(Math.floor(myWidth * 0.8), Math.floor(myHeight * 0.8)); this._objInspector.actor.set_position(this.actor.x + Math.floor(myWidth * 0.1), this._targetY + Math.floor(myHeight * 0.1)); }, insertObject: function(obj) { this._pushResult('<insert>', obj); }, inspectObject: function(obj, sourceActor) { this._objInspector.open(sourceActor); this._objInspector.selectObject(obj); }, // Handle key events which are relevant for all tabs of the LookingGlass _globalKeyPressEvent : function(actor, event) { let symbol = event.get_key_symbol(); let modifierState = event.get_state(); if (symbol == Clutter.Escape) { if (this._objInspector.actor.visible) { this._objInspector.close(); } else { this.close(); } return Clutter.EVENT_STOP; } // Ctrl+PgUp and Ctrl+PgDown switches tabs in the notebook view if (modifierState & Clutter.ModifierType.CONTROL_MASK) { if (symbol == Clutter.KEY_Page_Up) { this._notebook.prevTab(); } else if (symbol == Clutter.KEY_Page_Down) { this._notebook.nextTab(); } } return Clutter.EVENT_PROPAGATE; }, open : function() { if (this._open) return; if (!Main.pushModal(this._entry, { keybindingMode: Shell.KeyBindingMode.LOOKING_GLASS })) return; this._notebook.selectIndex(0); this.actor.show(); this._open = true; this._history.lastItem(); Tweener.removeTweens(this.actor); // We inverse compensate for the slow-down so you can change the factor // through LookingGlass without long waits. Tweener.addTween(this.actor, { time: 0.5 / St.get_slow_down_factor(), transition: 'easeOutQuad', y: this._targetY }); }, close : function() { if (!this._open) return; this._objInspector.actor.hide(); this._open = false; Tweener.removeTweens(this.actor); this.setBorderPaintTarget(null); Main.popModal(this._entry); Tweener.addTween(this.actor, { time: Math.min(0.5 / St.get_slow_down_factor(), 0.5), transition: 'easeOutQuad', y: this._hiddenY, onComplete: Lang.bind(this, function () { this.actor.hide(); }) }); } }); Signals.addSignalMethods(LookingGlass.prototype);
Devyani-Divs/gnome-shell
js/ui/lookingGlass.js
JavaScript
gpl-2.0
43,481
[ 30522, 1013, 1013, 1011, 1008, 1011, 5549, 1024, 1046, 2015, 1025, 1046, 2015, 1011, 27427, 4765, 1011, 2504, 1024, 1018, 1025, 27427, 4765, 1011, 21628, 2015, 1011, 5549, 1024, 9152, 2140, 1011, 1008, 1011, 9530, 3367, 18856, 26878, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
hmm = [ "https://media3.giphy.com/media/TPl5N4Ci49ZQY/giphy.gif", "https://media0.giphy.com/media/l14qxlCgJ0zUk/giphy.gif", "https://media4.giphy.com/media/MsWnkCVSXz73i/giphy.gif", "https://media1.giphy.com/media/l2JJEIMLgrXPEbDGM/giphy.gif", "https://media0.giphy.com/media/dgK22exekwOLm/giphy.gif" ]
garr741/mr_meeseeks
rtmbot/plugins/hmm.py
Python
mit
322
[ 30522, 17012, 1027, 1031, 1000, 16770, 1024, 1013, 1013, 2865, 2509, 1012, 21025, 21281, 1012, 4012, 1013, 2865, 1013, 1056, 24759, 2629, 2078, 2549, 6895, 26224, 2480, 4160, 2100, 1013, 21025, 21281, 1012, 21025, 2546, 1000, 1010, 1000, 16...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Created by PhpStorm. * User: wuqi * Date: 16/6/1 * Time: 下午5:56 * @author wuqi */ use yii\widgets\ActiveForm; use yii\helpers\Html; ?> <div class="modal inmodal" id="markInfo" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content animated bounceInRight"> <div class="modal-body"> <div class="form-horizontal"> <?php $form = ActiveForm::begin([ 'id' => $model->formName(), 'method' => 'post', 'fieldConfig' => [ 'template' => '{label}<div class="col-sm-5">{input}{error}</div>', 'labelOptions' => ['class' => 'col-sm-4 control-label'], 'inputOptions' => ['class' => 'form-control'] ], ]); ?> <?= $form->field($model, 'description')->textarea(['cols' => 10, 'rows' => 8, 'disabled' => true]) ?> <div class="form-group text-center"> <?= Html::button('取消', ['type' => "button", 'class' => "btn btn-white col-sm-offset-1", 'data-dismiss' => 'modal']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div> </div> </div>
zhangjianr/shop
backend/views/integral/_mark.php
PHP
bsd-3-clause
1,401
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 2580, 2011, 25718, 19718, 1012, 1008, 5310, 1024, 8814, 14702, 1008, 3058, 1024, 2385, 1013, 1020, 1013, 1015, 1008, 2051, 1024, 1743, 100, 1019, 1024, 5179, 1008, 1030, 3166, 8814, 14702, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * */ package cn.sefa.test.combinator; /** * @author Lionel * */ public class Result { private String recognized ; private String remaining; private boolean succeeded ; private Result(String recognized , String remaining , boolean succeeded){ this.recognized = recognized; this.remaining = remaining; this.succeeded = succeeded; } /** * @return the recognized */ public String getRecognized() { return recognized; } /** * @param recognized the recognized to set */ public void setRecognized(String recognized) { this.recognized = recognized; } /** * @return the remaining */ public String getRemaining() { return remaining; } public void setRemaining(String remaining) { this.remaining = remaining; } public boolean isSucceeded() { return succeeded; } public void setSucceeded(boolean succeeded) { this.succeeded = succeeded; } public static Result succeed(String recognized , String remaining){ return new Result(recognized,remaining,true); } public static Result fail(){ return new Result("","",false); } }
LLionel/sefa
src/cn/sefa/test/combinator/Result.java
Java
mit
1,109
[ 30522, 1013, 1008, 1008, 1008, 1008, 1013, 7427, 27166, 1012, 7367, 7011, 1012, 3231, 1012, 22863, 23207, 1025, 1013, 1008, 1008, 1008, 1030, 3166, 14377, 1008, 1008, 1013, 2270, 2465, 2765, 1063, 2797, 5164, 3858, 1025, 2797, 5164, 3588, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-bus.h" #include "hashmap.h" enum bus_match_node_type { BUS_MATCH_ROOT, BUS_MATCH_VALUE, BUS_MATCH_LEAF, /* The following are all different kinds of compare nodes */ BUS_MATCH_SENDER, BUS_MATCH_MESSAGE_TYPE, BUS_MATCH_DESTINATION, BUS_MATCH_INTERFACE, BUS_MATCH_MEMBER, BUS_MATCH_PATH, BUS_MATCH_PATH_NAMESPACE, BUS_MATCH_ARG, BUS_MATCH_ARG_LAST = BUS_MATCH_ARG + 63, BUS_MATCH_ARG_PATH, BUS_MATCH_ARG_PATH_LAST = BUS_MATCH_ARG_PATH + 63, BUS_MATCH_ARG_NAMESPACE, BUS_MATCH_ARG_NAMESPACE_LAST = BUS_MATCH_ARG_NAMESPACE + 63, BUS_MATCH_ARG_HAS, BUS_MATCH_ARG_HAS_LAST = BUS_MATCH_ARG_HAS + 63, _BUS_MATCH_NODE_TYPE_MAX, _BUS_MATCH_NODE_TYPE_INVALID = -1 }; struct bus_match_node { enum bus_match_node_type type; struct bus_match_node *parent, *next, *prev, *child; union { struct { char *str; uint8_t u8; } value; struct { struct match_callback *callback; } leaf; struct { /* If this is set, then the child is NULL */ Hashmap *children; } compare; }; }; struct bus_match_component { enum bus_match_node_type type; uint8_t value_u8; char *value_str; }; enum bus_match_scope { BUS_MATCH_GENERIC, BUS_MATCH_LOCAL, BUS_MATCH_DRIVER, }; int bus_match_run(sd_bus *bus, struct bus_match_node *root, sd_bus_message *m); int bus_match_add(struct bus_match_node *root, struct bus_match_component *components, unsigned n_components, struct match_callback *callback); int bus_match_remove(struct bus_match_node *root, struct match_callback *callback); void bus_match_free(struct bus_match_node *node); void bus_match_dump(struct bus_match_node *node, unsigned level); const char* bus_match_node_type_to_string(enum bus_match_node_type t, char buf[], size_t l); enum bus_match_node_type bus_match_node_type_from_string(const char *k, size_t n); int bus_match_parse(const char *match, struct bus_match_component **_components, unsigned *_n_components); void bus_match_parse_free(struct bus_match_component *components, unsigned n_components); char *bus_match_to_string(struct bus_match_component *components, unsigned n_components); enum bus_match_scope bus_match_get_scope(const struct bus_match_component *components, unsigned n_components);
kraj/systemd
src/libsystemd/sd-bus/bus-match.h
C
gpl-2.0
2,682
[ 30522, 1013, 1008, 23772, 2595, 1011, 6105, 1011, 8909, 4765, 18095, 1024, 1048, 21600, 2140, 1011, 1016, 1012, 1015, 1011, 2030, 1011, 2101, 1008, 1013, 1001, 10975, 8490, 2863, 2320, 1001, 2421, 1000, 17371, 1011, 3902, 1012, 1044, 1000, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package tikv import ( "github.com/juju/errors" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/terror" ) var ( // ErrBodyMissing response body is missing error ErrBodyMissing = errors.New("response body is missing") ) // TiDB decides whether to retry transaction by checking if error message contains // string "try again later" literally. // In TiClient we use `errors.Annotate(err, txnRetryableMark)` to direct TiDB to // restart a transaction. // Note that it should be only used if i) the error occurs inside a transaction // and ii) the error is not totally unexpected and hopefully will recover soon. const txnRetryableMark = "[try again later]" // MySQL error instances. var ( ErrTiKVServerTimeout = terror.ClassTiKV.New(mysql.ErrTiKVServerTimeout, mysql.MySQLErrName[mysql.ErrTiKVServerTimeout]+txnRetryableMark) ErrResolveLockTimeout = terror.ClassTiKV.New(mysql.ErrResolveLockTimeout, mysql.MySQLErrName[mysql.ErrResolveLockTimeout]+txnRetryableMark) ErrPDServerTimeout = terror.ClassTiKV.New(mysql.ErrPDServerTimeout, mysql.MySQLErrName[mysql.ErrPDServerTimeout]+"%v") ErrRegionUnavailable = terror.ClassTiKV.New(mysql.ErrRegionUnavailable, mysql.MySQLErrName[mysql.ErrRegionUnavailable]+txnRetryableMark) ErrTiKVServerBusy = terror.ClassTiKV.New(mysql.ErrTiKVServerBusy, mysql.MySQLErrName[mysql.ErrTiKVServerBusy]+txnRetryableMark) ErrGCTooEarly = terror.ClassTiKV.New(mysql.ErrGCTooEarly, mysql.MySQLErrName[mysql.ErrGCTooEarly]) ) func init() { tikvMySQLErrCodes := map[terror.ErrCode]uint16{ mysql.ErrTiKVServerTimeout: mysql.ErrTiKVServerTimeout, mysql.ErrResolveLockTimeout: mysql.ErrResolveLockTimeout, mysql.ErrPDServerTimeout: mysql.ErrPDServerTimeout, mysql.ErrRegionUnavailable: mysql.ErrRegionUnavailable, mysql.ErrTiKVServerBusy: mysql.ErrTiKVServerBusy, mysql.ErrGCTooEarly: mysql.ErrGCTooEarly, } terror.ErrClassToMySQLCodes[terror.ClassTiKV] = tikvMySQLErrCodes }
spongedu/tidb
store/tikv/error.go
GO
apache-2.0
2,481
[ 30522, 1013, 1013, 9385, 2355, 17852, 17695, 1010, 4297, 1012, 1013, 1013, 1013, 1013, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1013, 1013, 2017, 2089, 2025, 2224, 2023, 5371, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Global Vars to set var musicas = new Array(11); musicas[0] = 0; // Wheel A musicas[1] = 0; // Whell B musicas[2] = "0;"; // A1 musicas[3] = "0;"; // A2 musicas[4] = "0;"; // A3 musicas[5] = "0;"; // A4 musicas[6] = "0;"; // B1 musicas[7] = "0;"; // B2 musicas[8] = "0;"; // B3 musicas[9] = "0;"; // B4 musicas[10] = 0; // Sings function ativa_facebook(){ alert('Aguarde...'); FB.api('/me', function(response) { // console.log(response); // NORMAL ACTION $.post('getUser.php', { facebookId: response.id}, function(data){ if(data.success){ //INSERE APENAS BATIDA $.post('salva_som.php?opc=1', { m1: musicas[0], m2: musicas[1], m3: musicas[2]+musicas[3]+musicas[4]+musicas[5]+musicas[6]+musicas[7]+musicas[8]+musicas[9], m4: musicas[10], usuario: data.usuario }, function(data){ if(data.success){ var image = Math.floor((Math.random()*3)+1); FB.api('/me/feed', 'post', { message: 'Sinta o sabor da minha batida no FLAVOR DJ: o gerador de som exclusivo do BH DANCE FESTIVAL. BH Dance Festival. A CIDADE NA PISTA.', link: 'https://apps.facebook.com/flavordj/?minhaBatida='+data.batida, picture: 'https://lit-castle-9930.herokuapp.com/img/share/flavor'+image+'.jpg' }, function(response) { if (!response || response.error) { alert('Error occured'); } else { alert('Sua batida foi compartilhada com sucesso!'); } }); } }, 'json'); }else{ //INSERE BATIDA E USUARIO $.post('salva_som.php?opc=2', { m1: musicas[0], m2: musicas[1], m3: musicas[2]+musicas[3]+musicas[4]+musicas[5]+musicas[6]+musicas[7]+musicas[8]+musicas[9], m4: musicas[10], facebookId: response.id, nome: response.name, email: response.email, sexo: response.gender, cidade: '' }, function(data){ if(data.success){ var image = Math.floor((Math.random()*3)+1); FB.api('/me/feed', 'post', { message: 'Sinta o sabor da minha batida no FLAVOR DJ: o gerador de som exclusivo do BH DANCE FESTIVAL. BH Dance Festival. A CIDADE NA PISTA.', link: 'https://apps.facebook.com/flavordj/?minhaBatida='+data.batida, picture: 'https://lit-castle-9930.herokuapp.com/img/share/flavor'+image+'.jpg' }, function(response) { if (!response || response.error) { alert('Error occured'); } else { alert('Sua batida foi compartilhada com sucesso!'); } }); } }, 'json'); } }, 'json'); }); } function computa_voto(batida){ FB.api('/me', function(response) { //console.log(response); // NORMAL ACTION $.post('getVoto.php', { facebookId: response.id}, function(data){ if(data.success){ alert('Você já votou em uma batida, obrigado por participar!'); }else{ //INSERE NO BD $.post('computa_voto.php', { facebookId: response.id, batida: batida }, function(data){ if(data.success){ } }, 'json'); } }, 'json'); }); } function login() { alert('Você ainda não tem o aplicativo do Flavor DJ. Instale-o primeiro para compartilhar sua batida.'); FB.login(function(response) { if (response.authResponse) { ativa_facebook(); } else { } }, {scope: 'email, publish_stream'}); } function desativaetp1(){ $('.audio1').jPlayer("stop"); $('.audio2').jPlayer("stop"); $('.audio3').jPlayer("stop"); $('.audio4').jPlayer("stop"); musicas[0] = "0;"; $('.etapa1, .guide .etapa1 div, .etapa1 li').removeClass('ativo'); $('.etapa1').css('z-index', 2); } function desativaetp2(){ $('.audio5').jPlayer("stop"); $('.audio6').jPlayer("stop"); $('.audio7').jPlayer("stop"); $('.audio8').jPlayer("stop"); musicas[1] = "0;"; $('.etapa2, .guide .etapa2 div, .etapa2 li').removeClass('ativo'); $('.etapa2').css('z-index', 2); } function desativaetpr(idPlayer, cod){ musicas[cod] = "0;"; $('.audio'+idPlayer).jPlayer("stop"); $('.etapa3').css('z-index', 2); } function desativaetp5(){ $('.audio17').jPlayer("stop"); $('.audio18').jPlayer("stop"); $('.audio19').jPlayer("stop"); $('.audio20').jPlayer("stop"); musicas[10] = "0;"; $('.etapa5, .guide .etapa5 div, .etapa5 li').removeClass('ativo'); $('.etapa5').css('z-index', 2); } function ativa_anima(){ $('.whel1 div.a').delay(300).animate({ height: '0px' }, 1000); $('.whel1 div.b').delay(300).animate({ height: '0px' }, 1000, function(){ $('.whel2 div.a').delay(300).animate({ width: '0px' }, 1000); $('.whel2 div.b').delay(300).animate({ width: '0px' }, 1000); }); } $(document).ready(function(){ //login_start(); $('.etapa1').click(function(){ if($(this).hasClass('ativo')){ desativaetp1(); }else{ desativaetp1(); $(this).addClass('ativo'); $(this).css('z-index', 1); var audioPlayer = $(this).attr('href'); musicas[0] = audioPlayer; $('.guide .etapa1 div.p'+audioPlayer).addClass('ativo'); $('.visor .etapa1 li.p'+audioPlayer).addClass('ativo'); $(".audio"+audioPlayer).jPlayer("play", 0); } return false; }) $('.etapa2').click(function(){ if($(this).hasClass('ativo')){ desativaetp2(); }else{ desativaetp2(); $(this).addClass('ativo'); $(this).css('z-index', 1); var audioPlayer = $(this).attr('href'); musicas[1] = audioPlayer; $('.guide .etapa2 div.p'+audioPlayer).addClass('ativo'); $('.visor .etapa2 li.p'+audioPlayer).addClass('ativo'); $(".audio"+audioPlayer).jPlayer("play", 0); } return false; }) $('.etapa3').click(function(){ var audioPlayer = $(this).attr('href'); var codigo = $(this).data('codigo'); if($(this).hasClass('ativo')){ desativaetpr(audioPlayer,codigo); $('.guide .etapa3 div.p'+audioPlayer).removeClass('ativo'); $('.visor .etapa3 li.p'+audioPlayer).removeClass('ativo'); $(this).removeClass('ativo'); }else{ $(this).addClass('ativo'); $('.guide .etapa3 div.p'+audioPlayer).addClass('ativo'); $('.visor .etapa3 li.p'+audioPlayer).addClass('ativo'); $(this).css('z-index', 1); musicas[codigo] = audioPlayer+";"; $(".audio"+audioPlayer).jPlayer("play", 0); } return false; }) $('.etapa4').click(function(){ var audioPlayer = $(this).attr('href'); var cod = $(this).data('codigo'); if($(this).hasClass('ativo')){ desativaetpr(audioPlayer, cod); $('.guide .etapa4 div.p'+audioPlayer).removeClass('ativo'); $('.visor .etapa4 li.p'+audioPlayer).removeClass('ativo'); $(this).removeClass('ativo'); }else{ $(this).addClass('ativo'); $('.guide .etapa4 div.p'+audioPlayer).addClass('ativo'); $('.visor .etapa4 li.p'+audioPlayer).addClass('ativo'); musicas[cod] = audioPlayer+";"; $(".audio"+audioPlayer).jPlayer("play", 0); } return false; }) $('.etapa5').click(function(){ if($(this).hasClass('ativo')){ desativaetp5(); }else{ desativaetp5(); $(this).addClass('ativo'); var audioPlayer = $(this).attr('href'); musicas[10] = audioPlayer; $('.guide .etapa5 div.p'+audioPlayer).addClass('ativo'); $('.visor .etapa5 li.p'+audioPlayer).addClass('ativo'); $(".audio"+audioPlayer).jPlayer("play", 0); } return false; }) $(".audio1").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/1.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio2").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/2.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio3").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/3.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio4").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/4.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio5").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/1.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio6").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/2.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio7").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/3.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio8").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/4.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio9").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/1.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio10").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/2.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio11").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/3.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio12").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/4.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio13").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/1.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio14").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/2.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio15").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/3.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio16").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/4.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio17").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/1.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio18").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/2.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio19").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/3.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $(".audio20").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/4.mp3" } )}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto' }); $('body').queryLoader2( { onLoadComplete: ativa_anima() } ); function login_start() { //alert('Você ainda não tem o aplicativo do Flavor DJ. Instale-o primeiro para compartilhar sua batida.'); FB.login(function(response) { if (response.authResponse) { // ativa_facebook(); } else { } }, {scope: 'email, publish_stream'}); } // Share var cont = 0 var i = 0; $('a.share').click(function(){ cont = 0; for(i = 0; i<11; i++){ if((musicas[i] == "0;") || (musicas[i] == 0)){ cont++; } } if(cont == 11){ alert('Você precisa selecionar pelo menos um ingrediente para sua batida.'); }else{ FB.getLoginStatus(function(response) { // console.log(response); if (response.status === 'connected') { // NORMAL ACTION ativa_facebook(); } else if (response.status === 'not_authorized') { login(); window.location.reload(); } else { login(); window.location.reload(); } }); } return false; }); $('.votarBatida').click(function(){ var batida = $(this).attr('href'); FB.getLoginStatus(function(response) { if (response.status === 'connected') { // NORMAL ACTION computa_voto(batida); } else if (response.status === 'not_authorized') { FB.login(function(response) { if (response.authResponse) { // NORMAL ACTION computa_voto(batida); } else { // console.log('Sua batida não foi compartilhada.'); } }, {scope: 'email, publish_stream'}); } else { FB.login(function(response) { if (response.authResponse) { // NORMAL ACTION computa_voto(batida); } else { //console.log('Sua batida não foi compartilhada.'); } }, {scope: 'email, publish_stream'}); } }); }); });
mateuslopesbh/flavordj
js/funcoes.js
JavaScript
cc0-1.0
16,201
[ 30522, 1013, 1013, 3795, 13075, 2015, 2000, 2275, 13075, 21137, 2015, 1027, 2047, 9140, 1006, 2340, 1007, 1025, 21137, 2015, 1031, 1014, 1033, 1027, 1014, 1025, 1013, 1013, 5217, 1037, 21137, 2015, 1031, 1015, 1033, 1027, 1014, 1025, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.slf4j; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; public class StringPrintStream extends PrintStream { public static final String LINE_SEP = System.getProperty("line.separator"); PrintStream other; List stringList = new ArrayList(); public StringPrintStream(PrintStream ps) { super(ps); other = ps; } public void print(String s) { other.print(s); stringList.add(s); } public void println(String s) { other.println(s); stringList.add(s); } public void println(Object o) { other.println(o); stringList.add(o); } }
virtix/mut4j
lib/slf4j-1.6.0/integration/src/test/java/org/slf4j/StringPrintStream.java
Java
mit
665
[ 30522, 7427, 8917, 1012, 22889, 2546, 2549, 3501, 1025, 12324, 9262, 1012, 22834, 1012, 11204, 25379, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 9140, 9863, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 2862, 1025, 2270, 2465, 5164, 16550, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* global requirejs, require */ /*jslint node: true */ 'use strict'; import Ember from 'ember'; import _keys from 'lodash/object/keys'; /* This function looks through all files that have been loaded by Ember CLI and finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports a hash containing the names of the files as keys and the data as values. */ export default function(prefix) { let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers']; let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`); let modulesMap = modules.reduce((memo, name) => { memo[name] = {}; return memo; }, {}); _keys(requirejs.entries).filter(function(key) { return mirageModuleRegExp.test(key); }).forEach(function(moduleName) { if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files return; } let moduleParts = moduleName.split('/'); let moduleType = moduleParts[moduleParts.length - 2]; let moduleKey = moduleParts[moduleParts.length - 1]; Ember.assert('Subdirectories under ' + moduleType + ' are not supported', moduleParts[moduleParts.length - 3] === 'mirage'); if (moduleType === 'scenario'){ Ember.assert('Only scenario/default.js is supported at this time.', moduleKey !== 'default'); } let module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); } let data = module['default']; modulesMap[moduleType][moduleKey] = data; }); return modulesMap; }
ballPointPenguin/ember-cli-mirage
addon/utils/read-modules.js
JavaScript
mit
1,627
[ 30522, 1013, 1008, 3795, 5478, 22578, 1010, 5478, 1008, 1013, 1013, 1008, 1046, 22908, 2102, 13045, 1024, 2995, 1008, 1013, 1005, 2224, 9384, 1005, 1025, 12324, 7861, 5677, 2013, 1005, 7861, 5677, 1005, 1025, 12324, 1035, 6309, 2013, 1005, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ErrorHandler\ErrorEnhancer; use Symfony\Component\ErrorHandler\Error\FatalError; use Symfony\Component\ErrorHandler\Error\UndefinedFunctionError; /** * @author Fabien Potencier <fabien@symfony.com> */ class UndefinedFunctionErrorEnhancer implements ErrorEnhancerInterface { /** * {@inheritdoc} */ public function enhance(\Throwable $error): ?\Throwable { if ($error instanceof FatalError) { return null; } $message = $error->getMessage(); $messageLen = \strlen($message); $notFoundSuffix = '()'; $notFoundSuffixLen = \strlen($notFoundSuffix); if ($notFoundSuffixLen > $messageLen) { return null; } if (0 !== substr_compare($message, $notFoundSuffix, -$notFoundSuffixLen)) { return null; } $prefix = 'Call to undefined function '; $prefixLen = \strlen($prefix); if (!str_starts_with($message, $prefix)) { return null; } $fullyQualifiedFunctionName = substr($message, $prefixLen, -$notFoundSuffixLen); if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedFunctionName, '\\')) { $functionName = substr($fullyQualifiedFunctionName, $namespaceSeparatorIndex + 1); $namespacePrefix = substr($fullyQualifiedFunctionName, 0, $namespaceSeparatorIndex); $message = sprintf('Attempted to call function "%s" from namespace "%s".', $functionName, $namespacePrefix); } else { $functionName = $fullyQualifiedFunctionName; $message = sprintf('Attempted to call function "%s" from the global namespace.', $functionName); } $candidates = []; foreach (get_defined_functions() as $type => $definedFunctionNames) { foreach ($definedFunctionNames as $definedFunctionName) { if (false !== $namespaceSeparatorIndex = strrpos($definedFunctionName, '\\')) { $definedFunctionNameBasename = substr($definedFunctionName, $namespaceSeparatorIndex + 1); } else { $definedFunctionNameBasename = $definedFunctionName; } if ($definedFunctionNameBasename === $functionName) { $candidates[] = '\\'.$definedFunctionName; } } } if ($candidates) { sort($candidates); $last = array_pop($candidates).'"?'; if ($candidates) { $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last; } else { $candidates = '"'.$last; } $message .= "\nDid you mean to call ".$candidates; } return new UndefinedFunctionError($message, $error); } }
Tobion/symfony
src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php
PHP
mit
3,081
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 1996, 25353, 2213, 14876, 4890, 7427, 1012, 1008, 1008, 1006, 1039, 1007, 6904, 11283, 2078, 8962, 2368, 19562, 1026, 6904, 11283, 2078, 1030, 25353, 2213, 14876, 489...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.joda.time.format; /* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.joda.time.DateTimeFieldType; import java.util.Collection; import java.util.HashSet; import java.util.Set; /* * Elasticsearch Note: This class has been copied almost identically from joda, where the * class is named ISODatetimeFormat * * However there has been done one huge modification in several methods, which forces the date * year to be exactly n digits, so that a year like "5" is invalid and must be "0005" * * All methods have been marked with an "// ES change" commentary * * In case you compare this with the original ISODateTimeFormat, make sure you use a diff * call, that ignores whitespaces/tabs/indentations like 'diff -b' */ /** * Factory that creates instances of DateTimeFormatter based on the ISO8601 standard. * <p> * Date-time formatting is performed by the {@link DateTimeFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link DateTimeFormat} and {@link DateTimeFormatterBuilder}. * <p> * ISO8601 is the international standard for data interchange. It defines a * framework, rather than an absolute standard. As a result this provider has a * number of methods that represent common uses of the framework. The most common * formats are {@link #date() date}, {@link #time() time}, and {@link #dateTime() dateTime}. * <p> * For example, to format a date time in ISO format: * <pre> * DateTime dt = new DateTime(); * DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); * String str = fmt.print(dt); * </pre> * <p> * Note that these formatters mostly follow the ISO8601 standard for printing. * For parsing, the formatters are more lenient and allow formats that are not * in strict compliance with the standard. * <p> * It is important to understand that these formatters are not linked to * the <code>ISOChronology</code>. These formatters may be used with any * chronology, however there may be certain side effects with more unusual * chronologies. For example, the ISO formatters rely on dayOfWeek being * single digit, dayOfMonth being two digit and dayOfYear being three digit. * A chronology with a ten day week would thus cause issues. However, in * general, it is safe to use these formatters with other chronologies. * <p> * ISODateTimeFormat is thread-safe and immutable, and the formatters it * returns are as well. * * @author Brian S O'Neill * @since 1.0 * @see DateTimeFormat * @see DateTimeFormatterBuilder */ public class StrictISODateTimeFormat { /** * Constructor. * * @since 1.1 (previously private) */ protected StrictISODateTimeFormat() { super(); } //----------------------------------------------------------------------- /** * Returns a formatter that outputs only those fields specified. * <p> * This method examines the fields provided and returns an ISO-style * formatter that best fits. This can be useful for outputting * less-common ISO styles, such as YearMonth (YYYY-MM) or MonthDay (--MM-DD). * <p> * The list provided may have overlapping fields, such as dayOfWeek and * dayOfMonth. In this case, the style is chosen based on the following * list, thus in the example, the calendar style is chosen as dayOfMonth * is higher in priority than dayOfWeek: * <ul> * <li>monthOfYear - calendar date style * <li>dayOfYear - ordinal date style * <li>weekOfWeekYear - week date style * <li>dayOfMonth - calendar date style * <li>dayOfWeek - week date style * <li>year * <li>weekyear * </ul> * The supported formats are: * <pre> * Extended Basic Fields * 2005-03-25 20050325 year/monthOfYear/dayOfMonth * 2005-03 2005-03 year/monthOfYear * 2005--25 2005--25 year/dayOfMonth * * 2005 2005 year * --03-25 --0325 monthOfYear/dayOfMonth * --03 --03 monthOfYear * ---03 ---03 dayOfMonth * 2005-084 2005084 year/dayOfYear * -084 -084 dayOfYear * 2005-W12-5 2005W125 weekyear/weekOfWeekyear/dayOfWeek * 2005-W-5 2005W-5 weekyear/dayOfWeek * * 2005-W12 2005W12 weekyear/weekOfWeekyear * -W12-5 -W125 weekOfWeekyear/dayOfWeek * -W12 -W12 weekOfWeekyear * -W-5 -W-5 dayOfWeek * 10:20:30.040 102030.040 hour/minute/second/milli * 10:20:30 102030 hour/minute/second * 10:20 1020 hour/minute * 10 10 hour * -20:30.040 -2030.040 minute/second/milli * -20:30 -2030 minute/second * -20 -20 minute * --30.040 --30.040 second/milli * --30 --30 second * ---.040 ---.040 milli * * 10-30.040 10-30.040 hour/second/milli * * 10:20-.040 1020-.040 hour/minute/milli * * 10-30 10-30 hour/second * * 10--.040 10--.040 hour/milli * * -20-.040 -20-.040 minute/milli * * plus datetime formats like {date}T{time} * </pre> * * indicates that this is not an official ISO format and can be excluded * by passing in <code>strictISO</code> as <code>true</code>. * <p> * This method can side effect the input collection of fields. * If the input collection is modifiable, then each field that was added to * the formatter will be removed from the collection, including any duplicates. * If the input collection is unmodifiable then no side effect occurs. * <p> * This side effect processing is useful if you need to know whether all * the fields were converted into the formatter or not. To achieve this, * pass in a modifiable list, and check that it is empty on exit. * * @param fields the fields to get a formatter for, not null, * updated by the method call unless unmodifiable, * removing those fields built in the formatter * @param extended true to use the extended format (with separators) * @param strictISO true to stick exactly to ISO8601, false to include additional formats * @return a suitable formatter * @throws IllegalArgumentException if there is no format for the fields * @since 1.1 */ public static DateTimeFormatter forFields( Collection<DateTimeFieldType> fields, boolean extended, boolean strictISO) { if (fields == null || fields.size() == 0) { throw new IllegalArgumentException("The fields must not be null or empty"); } Set<DateTimeFieldType> workingFields = new HashSet<>(fields); int inputSize = workingFields.size(); boolean reducedPrec = false; DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); // date if (workingFields.contains(DateTimeFieldType.monthOfYear())) { reducedPrec = dateByMonth(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfYear())) { reducedPrec = dateByOrdinal(bld, workingFields, extended); } else if (workingFields.contains(DateTimeFieldType.weekOfWeekyear())) { reducedPrec = dateByWeek(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfMonth())) { reducedPrec = dateByMonth(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfWeek())) { reducedPrec = dateByWeek(bld, workingFields, extended, strictISO); } else if (workingFields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); reducedPrec = true; } else if (workingFields.remove(DateTimeFieldType.weekyear())) { bld.append(Constants.we); reducedPrec = true; } boolean datePresent = (workingFields.size() < inputSize); // time time(bld, workingFields, extended, strictISO, reducedPrec, datePresent); // result if (bld.canBuildFormatter() == false) { throw new IllegalArgumentException("No valid format for fields: " + fields); } // side effect the input collection to indicate the processed fields // handling unmodifiable collections with no side effect try { fields.retainAll(workingFields); } catch (UnsupportedOperationException ex) { // ignore, so we can handle unmodifiable collections } return bld.toFormatter(); } //----------------------------------------------------------------------- /** * Creates a date using the calendar date format. * Specification reference: 5.2.1. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @param strictISO true to only allow ISO formats * @return true if reduced precision * @since 1.1 */ private static boolean dateByMonth( DateTimeFormatterBuilder bld, Collection<DateTimeFieldType> fields, boolean extended, boolean strictISO) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); if (fields.remove(DateTimeFieldType.monthOfYear())) { if (fields.remove(DateTimeFieldType.dayOfMonth())) { // YYYY-MM-DD/YYYYMMDD appendSeparator(bld, extended); bld.appendMonthOfYear(2); appendSeparator(bld, extended); bld.appendDayOfMonth(2); } else { // YYYY-MM/YYYY-MM bld.appendLiteral('-'); bld.appendMonthOfYear(2); reducedPrec = true; } } else { if (fields.remove(DateTimeFieldType.dayOfMonth())) { // YYYY--DD/YYYY--DD (non-iso) checkNotStrictISO(fields, strictISO); bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendDayOfMonth(2); } else { // YYYY/YYYY reducedPrec = true; } } } else if (fields.remove(DateTimeFieldType.monthOfYear())) { bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendMonthOfYear(2); if (fields.remove(DateTimeFieldType.dayOfMonth())) { // --MM-DD/--MMDD appendSeparator(bld, extended); bld.appendDayOfMonth(2); } else { // --MM/--MM reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfMonth())) { // ---DD/---DD bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendDayOfMonth(2); } return reducedPrec; } //----------------------------------------------------------------------- /** * Creates a date using the ordinal date format. * Specification reference: 5.2.2. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @since 1.1 */ private static boolean dateByOrdinal( DateTimeFormatterBuilder bld, Collection<DateTimeFieldType> fields, boolean extended) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); if (fields.remove(DateTimeFieldType.dayOfYear())) { // YYYY-DDD/YYYYDDD appendSeparator(bld, extended); bld.appendDayOfYear(3); } else { // YYYY/YYYY reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfYear())) { // -DDD/-DDD bld.appendLiteral('-'); bld.appendDayOfYear(3); } return reducedPrec; } //----------------------------------------------------------------------- /** * Creates a date using the calendar date format. * Specification reference: 5.2.3. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @param strictISO true to only allow ISO formats * @since 1.1 */ private static boolean dateByWeek( DateTimeFormatterBuilder bld, Collection<DateTimeFieldType> fields, boolean extended, boolean strictISO) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.weekyear())) { bld.append(Constants.we); if (fields.remove(DateTimeFieldType.weekOfWeekyear())) { appendSeparator(bld, extended); bld.appendLiteral('W'); bld.appendWeekOfWeekyear(2); if (fields.remove(DateTimeFieldType.dayOfWeek())) { // YYYY-WWW-D/YYYYWWWD appendSeparator(bld, extended); bld.appendDayOfWeek(1); } else { // YYYY-WWW/YYYY-WWW reducedPrec = true; } } else { if (fields.remove(DateTimeFieldType.dayOfWeek())) { // YYYY-W-D/YYYYW-D (non-iso) checkNotStrictISO(fields, strictISO); appendSeparator(bld, extended); bld.appendLiteral('W'); bld.appendLiteral('-'); bld.appendDayOfWeek(1); } else { // YYYY/YYYY reducedPrec = true; } } } else if (fields.remove(DateTimeFieldType.weekOfWeekyear())) { bld.appendLiteral('-'); bld.appendLiteral('W'); bld.appendWeekOfWeekyear(2); if (fields.remove(DateTimeFieldType.dayOfWeek())) { // -WWW-D/-WWWD appendSeparator(bld, extended); bld.appendDayOfWeek(1); } else { // -WWW/-WWW reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfWeek())) { // -W-D/-W-D bld.appendLiteral('-'); bld.appendLiteral('W'); bld.appendLiteral('-'); bld.appendDayOfWeek(1); } return reducedPrec; } //----------------------------------------------------------------------- /** * Adds the time fields to the builder. * Specification reference: 5.3.1. * * @param bld the builder * @param fields the fields * @param extended whether to use the extended format * @param strictISO whether to be strict * @param reducedPrec whether the date was reduced precision * @param datePresent whether there was a date * @since 1.1 */ private static void time( DateTimeFormatterBuilder bld, Collection<DateTimeFieldType> fields, boolean extended, boolean strictISO, boolean reducedPrec, boolean datePresent) { boolean hour = fields.remove(DateTimeFieldType.hourOfDay()); boolean minute = fields.remove(DateTimeFieldType.minuteOfHour()); boolean second = fields.remove(DateTimeFieldType.secondOfMinute()); boolean milli = fields.remove(DateTimeFieldType.millisOfSecond()); if (!hour && !minute && !second && !milli) { return; } if (hour || minute || second || milli) { if (strictISO && reducedPrec) { throw new IllegalArgumentException("No valid ISO8601 format for fields because Date was reduced precision: " + fields); } if (datePresent) { bld.appendLiteral('T'); } } if (hour && minute && second || (hour && !second && !milli)) { // OK - HMSm/HMS/HM/H - valid in combination with date } else { if (strictISO && datePresent) { throw new IllegalArgumentException("No valid ISO8601 format for fields because Time was truncated: " + fields); } if (!hour && (minute && second || (minute && !milli) || second)) { // OK - MSm/MS/M/Sm/S - valid ISO formats } else { if (strictISO) { throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields); } } } if (hour) { bld.appendHourOfDay(2); } else if (minute || second || milli) { bld.appendLiteral('-'); } if (extended && hour && minute) { bld.appendLiteral(':'); } if (minute) { bld.appendMinuteOfHour(2); } else if (second || milli) { bld.appendLiteral('-'); } if (extended && minute && second) { bld.appendLiteral(':'); } if (second) { bld.appendSecondOfMinute(2); } else if (milli) { bld.appendLiteral('-'); } if (milli) { bld.appendLiteral('.'); bld.appendMillisOfSecond(3); } } //----------------------------------------------------------------------- /** * Checks that the iso only flag is not set, throwing an exception if it is. * * @param fields the fields * @param strictISO true if only ISO formats allowed * @since 1.1 */ private static void checkNotStrictISO(Collection<DateTimeFieldType> fields, boolean strictISO) { if (strictISO) { throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields); } } /** * Appends the separator if necessary. * * @param bld the builder * @param extended whether to append the separator * @since 1.1 */ private static void appendSeparator(DateTimeFormatterBuilder bld, boolean extended) { if (extended) { bld.appendLiteral('-'); } } //----------------------------------------------------------------------- /** * Returns a generic ISO date parser for parsing dates with a possible zone. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * It accepts formats described by the following syntax: * <pre> * date = date-element ['T' offset] * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]]) * </pre> */ public static DateTimeFormatter dateParser() { return Constants.dp; } /** * Returns a generic ISO date parser for parsing local dates. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * This parser is initialised with the local (UTC) time zone. * <p> * It accepts formats described by the following syntax: * <pre> * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * </pre> * @since 1.3 */ public static DateTimeFormatter localDateParser() { return Constants.ldp; } /** * Returns a generic ISO date parser for parsing dates. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * It accepts formats described by the following syntax: * <pre> * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * </pre> */ public static DateTimeFormatter dateElementParser() { return Constants.dpe; } /** * Returns a generic ISO time parser for parsing times with a possible zone. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * time = ['T'] time-element [offset] * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]]) * </pre> */ public static DateTimeFormatter timeParser() { return Constants.tp; } /** * Returns a generic ISO time parser for parsing local times. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * This parser is initialised with the local (UTC) time zone. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * time = ['T'] time-element * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * </pre> * @since 1.3 */ public static DateTimeFormatter localTimeParser() { return Constants.ltp; } /** * Returns a generic ISO time parser. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * </pre> */ public static DateTimeFormatter timeElementParser() { return Constants.tpe; } /** * Returns a generic ISO datetime parser which parses either a date or a time or both. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * datetime = time | date-opt-time * time = 'T' time-element [offset] * date-opt-time = date-element ['T' [time-element] [offset]] * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]]) * </pre> */ public static DateTimeFormatter dateTimeParser() { return Constants.dtp; } /** * Returns a generic ISO datetime parser where the date is mandatory and the time is optional. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * This parser can parse zoned datetimes. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * date-opt-time = date-element ['T' [time-element] [offset]] * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * </pre> * @since 1.3 */ public static DateTimeFormatter dateOptionalTimeParser() { return Constants.dotp; } /** * Returns a generic ISO datetime parser where the date is mandatory and the time is optional. * <p> * The returned formatter can only be used for parsing, printing is unsupported. * <p> * This parser only parses local datetimes. * This parser is initialised with the local (UTC) time zone. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * It accepts formats described by the following syntax: * <pre> * datetime = date-element ['T' time-element] * date-element = std-date-element | ord-date-element | week-date-element * std-date-element = yyyy ['-' MM ['-' dd]] * ord-date-element = yyyy ['-' DDD] * week-date-element = xxxx '-W' ww ['-' e] * time-element = HH [minute-element] | [fraction] * minute-element = ':' mm [second-element] | [fraction] * second-element = ':' ss [fraction] * fraction = ('.' | ',') digit+ * </pre> * @since 1.3 */ public static DateTimeFormatter localDateOptionalTimeParser() { return Constants.ldotp; } //----------------------------------------------------------------------- /** * Returns a formatter for a full date as four digit year, two digit month * of year, and two digit day of month (yyyy-MM-dd). * <p> * The returned formatter prints and parses only this format. * See {@link #dateParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-MM-dd */ public static DateTimeFormatter date() { return yearMonthDay(); } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, three digit fraction of second, and * time zone offset (HH:mm:ss.SSSZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * See {@link #timeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for HH:mm:ss.SSSZZ */ public static DateTimeFormatter time() { return Constants.t; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and time zone offset (HH:mm:ssZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * See {@link #timeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for HH:mm:ssZZ */ public static DateTimeFormatter timeNoMillis() { return Constants.tx; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, three digit fraction of second, and * time zone offset prefixed by 'T' ('T'HH:mm:ss.SSSZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * See {@link #timeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for 'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter tTime() { return Constants.tt; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and time zone offset prefixed * by 'T' ('T'HH:mm:ssZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * See {@link #timeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for 'T'HH:mm:ssZZ */ public static DateTimeFormatter tTimeNoMillis() { return Constants.ttx; } /** * Returns a formatter that combines a full date and time, separated by a 'T' * (yyyy-MM-dd'T'HH:mm:ss.SSSZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter dateTime() { return Constants.dt; } /** * Returns a formatter that combines a full date and time without millis, * separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ssZZ */ public static DateTimeFormatter dateTimeNoMillis() { return Constants.dtx; } /** * Returns a formatter for a full ordinal date, using a four * digit year and three digit dayOfYear (yyyy-DDD). * <p> * The returned formatter prints and parses only this format. * See {@link #dateParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-DDD * @since 1.1 */ public static DateTimeFormatter ordinalDate() { return Constants.od; } /** * Returns a formatter for a full ordinal date and time, using a four * digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ss.SSSZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-DDD'T'HH:mm:ss.SSSZZ * @since 1.1 */ public static DateTimeFormatter ordinalDateTime() { return Constants.odt; } /** * Returns a formatter for a full ordinal date and time without millis, * using a four digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ssZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for yyyy-DDD'T'HH:mm:ssZZ * @since 1.1 */ public static DateTimeFormatter ordinalDateTimeNoMillis() { return Constants.odtx; } /** * Returns a formatter for a full date as four digit weekyear, two digit * week of weekyear, and one digit day of week (xxxx-'W'ww-e). * <p> * The returned formatter prints and parses only this format. * See {@link #dateParser()} for a more flexible parser that accepts different formats. * * @return a formatter for xxxx-'W'ww-e */ public static DateTimeFormatter weekDate() { return Constants.wwd; } /** * Returns a formatter that combines a full weekyear date and time, * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter weekDateTime() { return Constants.wdt; } /** * Returns a formatter that combines a full weekyear date and time without millis, * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ssZZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * See {@link #dateTimeParser()} for a more flexible parser that accepts different formats. * * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ssZZ */ public static DateTimeFormatter weekDateTimeNoMillis() { return Constants.wdtx; } //----------------------------------------------------------------------- /** * Returns a basic formatter for a full date as four digit year, two digit * month of year, and two digit day of month (yyyyMMdd). * <p> * The returned formatter prints and parses only this format. * * @return a formatter for yyyyMMdd */ public static DateTimeFormatter basicDate() { return Constants.bd; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, three digit millis, and time zone * offset (HHmmss.SSSZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * * @return a formatter for HHmmss.SSSZ */ public static DateTimeFormatter basicTime() { return Constants.bt; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, and time zone offset (HHmmssZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * * @return a formatter for HHmmssZ */ public static DateTimeFormatter basicTimeNoMillis() { return Constants.btx; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, three digit millis, and time zone * offset prefixed by 'T' ('T'HHmmss.SSSZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * * @return a formatter for 'T'HHmmss.SSSZ */ public static DateTimeFormatter basicTTime() { return Constants.btt; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, and time zone offset prefixed by 'T' * ('T'HHmmssZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * * @return a formatter for 'T'HHmmssZ */ public static DateTimeFormatter basicTTimeNoMillis() { return Constants.bttx; } /** * Returns a basic formatter that combines a basic date and time, separated * by a 'T' (yyyyMMdd'T'HHmmss.SSSZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * * @return a formatter for yyyyMMdd'T'HHmmss.SSSZ */ public static DateTimeFormatter basicDateTime() { return Constants.bdt; } /** * Returns a basic formatter that combines a basic date and time without millis, * separated by a 'T' (yyyyMMdd'T'HHmmssZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * * @return a formatter for yyyyMMdd'T'HHmmssZ */ public static DateTimeFormatter basicDateTimeNoMillis() { return Constants.bdtx; } /** * Returns a formatter for a full ordinal date, using a four * digit year and three digit dayOfYear (yyyyDDD). * <p> * The returned formatter prints and parses only this format. * * @return a formatter for yyyyDDD * @since 1.1 */ public static DateTimeFormatter basicOrdinalDate() { return Constants.bod; } /** * Returns a formatter for a full ordinal date and time, using a four * digit year and three digit dayOfYear (yyyyDDD'T'HHmmss.SSSZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * * @return a formatter for yyyyDDD'T'HHmmss.SSSZ * @since 1.1 */ public static DateTimeFormatter basicOrdinalDateTime() { return Constants.bodt; } /** * Returns a formatter for a full ordinal date and time without millis, * using a four digit year and three digit dayOfYear (yyyyDDD'T'HHmmssZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * * @return a formatter for yyyyDDD'T'HHmmssZ * @since 1.1 */ public static DateTimeFormatter basicOrdinalDateTimeNoMillis() { return Constants.bodtx; } /** * Returns a basic formatter for a full date as four digit weekyear, two * digit week of weekyear, and one digit day of week (xxxx'W'wwe). * <p> * The returned formatter prints and parses only this format. * * @return a formatter for xxxx'W'wwe */ public static DateTimeFormatter basicWeekDate() { return Constants.bwd; } /** * Returns a basic formatter that combines a basic weekyear date and time, * separated by a 'T' (xxxx'W'wwe'T'HHmmss.SSSZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which includes milliseconds. * * @return a formatter for xxxx'W'wwe'T'HHmmss.SSSZ */ public static DateTimeFormatter basicWeekDateTime() { return Constants.bwdt; } /** * Returns a basic formatter that combines a basic weekyear date and time * without millis, separated by a 'T' (xxxx'W'wwe'T'HHmmssZ). * <p> * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * <p> * The returned formatter prints and parses only this format, which excludes milliseconds. * * @return a formatter for xxxx'W'wwe'T'HHmmssZ */ public static DateTimeFormatter basicWeekDateTimeNoMillis() { return Constants.bwdtx; } //----------------------------------------------------------------------- /** * Returns a formatter for a four digit year. (yyyy) * * @return a formatter for yyyy */ public static DateTimeFormatter year() { return Constants.ye; } /** * Returns a formatter for a four digit year and two digit month of * year. (yyyy-MM) * * @return a formatter for yyyy-MM */ public static DateTimeFormatter yearMonth() { return Constants.ym; } /** * Returns a formatter for a four digit year, two digit month of year, and * two digit day of month. (yyyy-MM-dd) * * @return a formatter for yyyy-MM-dd */ public static DateTimeFormatter yearMonthDay() { return Constants.ymd; } /** * Returns a formatter for a four digit weekyear. (xxxx) * * @return a formatter for xxxx */ public static DateTimeFormatter weekyear() { return Constants.we; } /** * Returns a formatter for a four digit weekyear and two digit week of * weekyear. (xxxx-'W'ww) * * @return a formatter for xxxx-'W'ww */ public static DateTimeFormatter weekyearWeek() { return Constants.ww; } /** * Returns a formatter for a four digit weekyear, two digit week of * weekyear, and one digit day of week. (xxxx-'W'ww-e) * * @return a formatter for xxxx-'W'ww-e */ public static DateTimeFormatter weekyearWeekDay() { return Constants.wwd; } /** * Returns a formatter for a two digit hour of day. (HH) * * @return a formatter for HH */ public static DateTimeFormatter hour() { return Constants.hde; } /** * Returns a formatter for a two digit hour of day and two digit minute of * hour. (HH:mm) * * @return a formatter for HH:mm */ public static DateTimeFormatter hourMinute() { return Constants.hm; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, and two digit second of minute. (HH:mm:ss) * * @return a formatter for HH:mm:ss */ public static DateTimeFormatter hourMinuteSecond() { return Constants.hms; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and three digit fraction of * second (HH:mm:ss.SSS). Parsing will parse up to 3 fractional second * digits. * * @return a formatter for HH:mm:ss.SSS */ public static DateTimeFormatter hourMinuteSecondMillis() { return Constants.hmsl; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and three digit fraction of * second (HH:mm:ss.SSS). Parsing will parse up to 9 fractional second * digits, throwing away all except the first three. * * @return a formatter for HH:mm:ss.SSS */ public static DateTimeFormatter hourMinuteSecondFraction() { return Constants.hmsf; } /** * Returns a formatter that combines a full date and two digit hour of * day. (yyyy-MM-dd'T'HH) * * @return a formatter for yyyy-MM-dd'T'HH */ public static DateTimeFormatter dateHour() { return Constants.dh; } /** * Returns a formatter that combines a full date, two digit hour of day, * and two digit minute of hour. (yyyy-MM-dd'T'HH:mm) * * @return a formatter for yyyy-MM-dd'T'HH:mm */ public static DateTimeFormatter dateHourMinute() { return Constants.dhm; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, and two digit second of * minute. (yyyy-MM-dd'T'HH:mm:ss) * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss */ public static DateTimeFormatter dateHourMinuteSecond() { return Constants.dhms; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, two digit second of minute, and three digit * fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up * to 3 fractional second digits. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS */ public static DateTimeFormatter dateHourMinuteSecondMillis() { return Constants.dhmsl; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, two digit second of minute, and three digit * fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up * to 9 fractional second digits, throwing away all except the first three. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS */ public static DateTimeFormatter dateHourMinuteSecondFraction() { return Constants.dhmsf; } //----------------------------------------------------------------------- static final class Constants { private static final DateTimeFormatter ye = yearElement(), // year element (yyyy) mye = monthElement(), // monthOfYear element (-MM) dme = dayOfMonthElement(), // dayOfMonth element (-dd) we = weekyearElement(), // weekyear element (xxxx) wwe = weekElement(), // weekOfWeekyear element (-ww) dwe = dayOfWeekElement(), // dayOfWeek element (-ee) dye = dayOfYearElement(), // dayOfYear element (-DDD) hde = hourElement(), // hourOfDay element (HH) mhe = minuteElement(), // minuteOfHour element (:mm) sme = secondElement(), // secondOfMinute element (:ss) fse = fractionElement(), // fractionOfSecond element (.SSSSSSSSS) ze = offsetElement(), // zone offset element lte = literalTElement(), // literal 'T' element //y, // year (same as year element) ym = yearMonth(), // year month ymd = yearMonthDay(), // year month day //w, // weekyear (same as weekyear element) ww = weekyearWeek(), // weekyear week wwd = weekyearWeekDay(), // weekyear week day //h, // hour (same as hour element) hm = hourMinute(), // hour minute hms = hourMinuteSecond(), // hour minute second hmsl = hourMinuteSecondMillis(), // hour minute second millis hmsf = hourMinuteSecondFraction(), // hour minute second fraction dh = dateHour(), // date hour dhm = dateHourMinute(), // date hour minute dhms = dateHourMinuteSecond(), // date hour minute second dhmsl = dateHourMinuteSecondMillis(), // date hour minute second millis dhmsf = dateHourMinuteSecondFraction(), // date hour minute second fraction //d, // date (same as ymd) t = time(), // time tx = timeNoMillis(), // time no millis tt = tTime(), // Ttime ttx = tTimeNoMillis(), // Ttime no millis dt = dateTime(), // date time dtx = dateTimeNoMillis(), // date time no millis //wd, // week date (same as wwd) wdt = weekDateTime(), // week date time wdtx = weekDateTimeNoMillis(), // week date time no millis od = ordinalDate(), // ordinal date (same as yd) odt = ordinalDateTime(), // ordinal date time odtx = ordinalDateTimeNoMillis(), // ordinal date time no millis bd = basicDate(), // basic date bt = basicTime(), // basic time btx = basicTimeNoMillis(), // basic time no millis btt = basicTTime(), // basic Ttime bttx = basicTTimeNoMillis(), // basic Ttime no millis bdt = basicDateTime(), // basic date time bdtx = basicDateTimeNoMillis(), // basic date time no millis bod = basicOrdinalDate(), // basic ordinal date bodt = basicOrdinalDateTime(), // basic ordinal date time bodtx = basicOrdinalDateTimeNoMillis(), // basic ordinal date time no millis bwd = basicWeekDate(), // basic week date bwdt = basicWeekDateTime(), // basic week date time bwdtx = basicWeekDateTimeNoMillis(), // basic week date time no millis dpe = dateElementParser(), // date parser element tpe = timeElementParser(), // time parser element dp = dateParser(), // date parser ldp = localDateParser(), // local date parser tp = timeParser(), // time parser ltp = localTimeParser(), // local time parser dtp = dateTimeParser(), // date time parser dotp = dateOptionalTimeParser(), // date optional time parser ldotp = localDateOptionalTimeParser(); // local date optional time parser //----------------------------------------------------------------------- private static DateTimeFormatter dateParser() { if (dp == null) { DateTimeParser tOffset = new DateTimeFormatterBuilder() .appendLiteral('T') .append(offsetElement()).toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(tOffset) .toFormatter(); } return dp; } private static DateTimeFormatter localDateParser() { if (ldp == null) { return dateElementParser().withZoneUTC(); } return ldp; } private static DateTimeFormatter dateElementParser() { if (dpe == null) { return new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] { new DateTimeFormatterBuilder() .append(yearElement()) .appendOptional (new DateTimeFormatterBuilder() .append(monthElement()) .appendOptional(dayOfMonthElement().getParser()) .toParser()) .toParser(), new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .appendOptional(dayOfWeekElement().getParser()) .toParser(), new DateTimeFormatterBuilder() .append(yearElement()) .append(dayOfYearElement()) .toParser() }) .toFormatter(); } return dpe; } private static DateTimeFormatter timeParser() { if (tp == null) { return new DateTimeFormatterBuilder() .appendOptional(literalTElement().getParser()) .append(timeElementParser()) .appendOptional(offsetElement().getParser()) .toFormatter(); } return tp; } private static DateTimeFormatter localTimeParser() { if (ltp == null) { return new DateTimeFormatterBuilder() .appendOptional(literalTElement().getParser()) .append(timeElementParser()) .toFormatter().withZoneUTC(); } return ltp; } private static DateTimeFormatter timeElementParser() { if (tpe == null) { // Decimal point can be either '.' or ',' DateTimeParser decimalPoint = new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] { new DateTimeFormatterBuilder() .appendLiteral('.') .toParser(), new DateTimeFormatterBuilder() .appendLiteral(',') .toParser() }) .toParser(); return new DateTimeFormatterBuilder() // time-element .append(hourElement()) .append (null, new DateTimeParser[] { new DateTimeFormatterBuilder() // minute-element .append(minuteElement()) .append (null, new DateTimeParser[] { new DateTimeFormatterBuilder() // second-element .append(secondElement()) // second fraction .appendOptional(new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfSecond(1, 9) .toParser()) .toParser(), // minute fraction new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfMinute(1, 9) .toParser(), null }) .toParser(), // hour fraction new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfHour(1, 9) .toParser(), null }) .toFormatter(); } return tpe; } private static DateTimeFormatter dateTimeParser() { if (dtp == null) { // This is different from the general time parser in that the 'T' // is required. DateTimeParser time = new DateTimeFormatterBuilder() .appendLiteral('T') .append(timeElementParser()) .appendOptional(offsetElement().getParser()) .toParser(); return new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] {time, dateOptionalTimeParser().getParser()}) .toFormatter(); } return dtp; } private static DateTimeFormatter dateOptionalTimeParser() { if (dotp == null) { DateTimeParser timeOrOffset = new DateTimeFormatterBuilder() .appendLiteral('T') .appendOptional(timeElementParser().getParser()) .appendOptional(offsetElement().getParser()) .toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(timeOrOffset) .toFormatter(); } return dotp; } private static DateTimeFormatter localDateOptionalTimeParser() { if (ldotp == null) { DateTimeParser time = new DateTimeFormatterBuilder() .appendLiteral('T') .append(timeElementParser()) .toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(time) .toFormatter().withZoneUTC(); } return ldotp; } //----------------------------------------------------------------------- private static DateTimeFormatter time() { if (t == null) { return new DateTimeFormatterBuilder() .append(hourMinuteSecondFraction()) .append(offsetElement()) .toFormatter(); } return t; } private static DateTimeFormatter timeNoMillis() { if (tx == null) { return new DateTimeFormatterBuilder() .append(hourMinuteSecond()) .append(offsetElement()) .toFormatter(); } return tx; } private static DateTimeFormatter tTime() { if (tt == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(time()) .toFormatter(); } return tt; } private static DateTimeFormatter tTimeNoMillis() { if (ttx == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(timeNoMillis()) .toFormatter(); } return ttx; } private static DateTimeFormatter dateTime() { if (dt == null) { return new DateTimeFormatterBuilder() .append(date()) .append(tTime()) .toFormatter(); } return dt; } private static DateTimeFormatter dateTimeNoMillis() { if (dtx == null) { return new DateTimeFormatterBuilder() .append(date()) .append(tTimeNoMillis()) .toFormatter(); } return dtx; } private static DateTimeFormatter ordinalDate() { if (od == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(dayOfYearElement()) .toFormatter(); } return od; } private static DateTimeFormatter ordinalDateTime() { if (odt == null) { return new DateTimeFormatterBuilder() .append(ordinalDate()) .append(tTime()) .toFormatter(); } return odt; } private static DateTimeFormatter ordinalDateTimeNoMillis() { if (odtx == null) { return new DateTimeFormatterBuilder() .append(ordinalDate()) .append(tTimeNoMillis()) .toFormatter(); } return odtx; } private static DateTimeFormatter weekDateTime() { if (wdt == null) { return new DateTimeFormatterBuilder() .append(weekDate()) .append(tTime()) .toFormatter(); } return wdt; } private static DateTimeFormatter weekDateTimeNoMillis() { if (wdtx == null) { return new DateTimeFormatterBuilder() .append(weekDate()) .append(tTimeNoMillis()) .toFormatter(); } return wdtx; } //----------------------------------------------------------------------- private static DateTimeFormatter basicDate() { if (bd == null) { return new DateTimeFormatterBuilder() .appendYear(4, 4) .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2) .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2) .toFormatter(); } return bd; } private static DateTimeFormatter basicTime() { if (bt == null) { return new DateTimeFormatterBuilder() .appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2) .appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2) .appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2) .appendLiteral('.') .appendFractionOfSecond(3, 9) .appendTimeZoneOffset("Z", false, 2, 2) .toFormatter(); } return bt; } private static DateTimeFormatter basicTimeNoMillis() { if (btx == null) { return new DateTimeFormatterBuilder() .appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2) .appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2) .appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2) .appendTimeZoneOffset("Z", false, 2, 2) .toFormatter(); } return btx; } private static DateTimeFormatter basicTTime() { if (btt == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(basicTime()) .toFormatter(); } return btt; } private static DateTimeFormatter basicTTimeNoMillis() { if (bttx == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(basicTimeNoMillis()) .toFormatter(); } return bttx; } private static DateTimeFormatter basicDateTime() { if (bdt == null) { return new DateTimeFormatterBuilder() .append(basicDate()) .append(basicTTime()) .toFormatter(); } return bdt; } private static DateTimeFormatter basicDateTimeNoMillis() { if (bdtx == null) { return new DateTimeFormatterBuilder() .append(basicDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bdtx; } private static DateTimeFormatter basicOrdinalDate() { if (bod == null) { return new DateTimeFormatterBuilder() .appendYear(4, 4) .appendFixedDecimal(DateTimeFieldType.dayOfYear(), 3) .toFormatter(); } return bod; } private static DateTimeFormatter basicOrdinalDateTime() { if (bodt == null) { return new DateTimeFormatterBuilder() .append(basicOrdinalDate()) .append(basicTTime()) .toFormatter(); } return bodt; } private static DateTimeFormatter basicOrdinalDateTimeNoMillis() { if (bodtx == null) { return new DateTimeFormatterBuilder() .append(basicOrdinalDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bodtx; } private static DateTimeFormatter basicWeekDate() { if (bwd == null) { return new DateTimeFormatterBuilder() // ES change, was .appendWeekyear(4, 4) .appendFixedSignedDecimal(DateTimeFieldType.weekyear(), 4) .appendLiteral('W') .appendFixedDecimal(DateTimeFieldType.weekOfWeekyear(), 2) .appendFixedDecimal(DateTimeFieldType.dayOfWeek(), 1) .toFormatter(); } return bwd; } private static DateTimeFormatter basicWeekDateTime() { if (bwdt == null) { return new DateTimeFormatterBuilder() .append(basicWeekDate()) .append(basicTTime()) .toFormatter(); } return bwdt; } private static DateTimeFormatter basicWeekDateTimeNoMillis() { if (bwdtx == null) { return new DateTimeFormatterBuilder() .append(basicWeekDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bwdtx; } //----------------------------------------------------------------------- private static DateTimeFormatter yearMonth() { if (ym == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(monthElement()) .toFormatter(); } return ym; } private static DateTimeFormatter yearMonthDay() { if (ymd == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(monthElement()) .append(dayOfMonthElement()) .toFormatter(); } return ymd; } private static DateTimeFormatter weekyearWeek() { if (ww == null) { return new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .toFormatter(); } return ww; } private static DateTimeFormatter weekyearWeekDay() { if (wwd == null) { return new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .append(dayOfWeekElement()) .toFormatter(); } return wwd; } private static DateTimeFormatter hourMinute() { if (hm == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .toFormatter(); } return hm; } private static DateTimeFormatter hourMinuteSecond() { if (hms == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .toFormatter(); } return hms; } private static DateTimeFormatter hourMinuteSecondMillis() { if (hmsl == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .appendLiteral('.') .appendFractionOfSecond(3, 3) .toFormatter(); } return hmsl; } private static DateTimeFormatter hourMinuteSecondFraction() { if (hmsf == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .append(fractionElement()) .toFormatter(); } return hmsf; } private static DateTimeFormatter dateHour() { if (dh == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hour()) .toFormatter(); } return dh; } private static DateTimeFormatter dateHourMinute() { if (dhm == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinute()) .toFormatter(); } return dhm; } private static DateTimeFormatter dateHourMinuteSecond() { if (dhms == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecond()) .toFormatter(); } return dhms; } private static DateTimeFormatter dateHourMinuteSecondMillis() { if (dhmsl == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecondMillis()) .toFormatter(); } return dhmsl; } private static DateTimeFormatter dateHourMinuteSecondFraction() { if (dhmsf == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecondFraction()) .toFormatter(); } return dhmsf; } //----------------------------------------------------------------------- private static DateTimeFormatter yearElement() { if (ye == null) { return new DateTimeFormatterBuilder() // ES change, was .appendYear(4, 9) .appendFixedSignedDecimal(DateTimeFieldType.year(), 4) .toFormatter(); } return ye; } private static DateTimeFormatter monthElement() { if (mye == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') // ES change, was .appendMonthOfYear(2) .appendFixedSignedDecimal(DateTimeFieldType.monthOfYear(), 2) .toFormatter(); } return mye; } private static DateTimeFormatter dayOfMonthElement() { if (dme == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') // ES change, was .appendDayOfMonth(2) .appendFixedSignedDecimal(DateTimeFieldType.dayOfMonth(), 2) .toFormatter(); } return dme; } private static DateTimeFormatter weekyearElement() { if (we == null) { return new DateTimeFormatterBuilder() // ES change, was .appendWeekyear(4, 9) .appendFixedSignedDecimal(DateTimeFieldType.weekyear(), 4) .toFormatter(); } return we; } private static DateTimeFormatter weekElement() { if (wwe == null) { return new DateTimeFormatterBuilder() .appendLiteral("-W") // ES change, was .appendWeekOfWeekyear(2) .appendFixedSignedDecimal(DateTimeFieldType.weekOfWeekyear(), 2) .toFormatter(); } return wwe; } private static DateTimeFormatter dayOfWeekElement() { if (dwe == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') .appendDayOfWeek(1) .toFormatter(); } return dwe; } private static DateTimeFormatter dayOfYearElement() { if (dye == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') // ES change, was .appendDayOfYear(3) .appendFixedSignedDecimal(DateTimeFieldType.dayOfYear(), 3) .toFormatter(); } return dye; } private static DateTimeFormatter literalTElement() { if (lte == null) { return new DateTimeFormatterBuilder() .appendLiteral('T') .toFormatter(); } return lte; } private static DateTimeFormatter hourElement() { if (hde == null) { return new DateTimeFormatterBuilder() // ES change, was .appendHourOfDay(2) .appendFixedSignedDecimal(DateTimeFieldType.hourOfDay(), 2) .toFormatter(); } return hde; } private static DateTimeFormatter minuteElement() { if (mhe == null) { return new DateTimeFormatterBuilder() .appendLiteral(':') // ES change, was .appendMinuteOfHour(2) .appendFixedSignedDecimal(DateTimeFieldType.minuteOfHour(), 2) .toFormatter(); } return mhe; } private static DateTimeFormatter secondElement() { if (sme == null) { return new DateTimeFormatterBuilder() .appendLiteral(':') // ES change, was .appendSecondOfMinute(2) .appendFixedSignedDecimal(DateTimeFieldType.secondOfMinute(), 2) .toFormatter(); } return sme; } private static DateTimeFormatter fractionElement() { if (fse == null) { return new DateTimeFormatterBuilder() .appendLiteral('.') // Support parsing up to nanosecond precision even though // those extra digits will be dropped. .appendFractionOfSecond(3, 9) .toFormatter(); } return fse; } private static DateTimeFormatter offsetElement() { if (ze == null) { return new DateTimeFormatterBuilder() .appendTimeZoneOffset("Z", true, 2, 4) .toFormatter(); } return ze; } } }
HonzaKral/elasticsearch
server/src/main/java/org/joda/time/format/StrictISODateTimeFormat.java
Java
apache-2.0
79,822
[ 30522, 7427, 8917, 1012, 8183, 2850, 1012, 2051, 1012, 4289, 1025, 1013, 1008, 1008, 9385, 2541, 1011, 2268, 4459, 5624, 11634, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ | This file is part of the web2py Web Framework | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Provides: - List; like list but returns None instead of IndexOutOfBounds - Storage; like dictionary allowing also for `obj.foo` for `obj['foo']` """ try: import cPickle as pickle except: import pickle import copy_reg import gluon.portalocker as portalocker __all__ = ['List', 'Storage', 'Settings', 'Messages', 'StorageList', 'load_storage', 'save_storage'] DEFAULT = lambda:0 class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. Example:: >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o['a'] 2 >>> del o.a >>> print o.a None """ __slots__ = () __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ __getitem__ = dict.get __getattr__ = dict.get __getnewargs__ = lambda self: getattr(dict,self).__getnewargs__(self) __repr__ = lambda self: '<Storage %s>' % dict.__repr__(self) # http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi __getstate__ = lambda self: None __copy__ = lambda self: Storage(self) def getlist(self, key): """ Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlist('x') ['abc'] >>> request.vars.getlist('y') ['abc', 'def'] >>> request.vars.getlist('z') [] """ value = self.get(key, []) if value is None or isinstance(value, (list, tuple)): return value else: return [value] def getfirst(self, key, default=None): """ Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getfirst('x') 'abc' >>> request.vars.getfirst('y') 'abc' >>> request.vars.getfirst('z') """ values = self.getlist(key) return values[0] if values else default def getlast(self, key, default=None): """ Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlast('x') 'abc' >>> request.vars.getlast('y') 'def' >>> request.vars.getlast('z') """ values = self.getlist(key) return values[-1] if values else default def pickle_storage(s): return Storage, (dict(s),) copy_reg.pickle(Storage, pickle_storage) PICKABLE = (str, int, long, float, bool, list, dict, tuple, set) class StorageList(Storage): """ Behaves like Storage but missing elements defaults to [] instead of None """ def __getitem__(self, key): return self.__getattr__(key) def __getattr__(self, key): if key in self: return self.get(key) else: r = [] self[key] = r return r def load_storage(filename): fp = None try: fp = portalocker.LockedFile(filename, 'rb') storage = pickle.load(fp) finally: if fp: fp.close() return Storage(storage) def save_storage(storage, filename): fp = None try: fp = portalocker.LockedFile(filename, 'wb') pickle.dump(dict(storage), fp) finally: if fp: fp.close() class Settings(Storage): def __setattr__(self, key, value): if key != 'lock_keys' and self['lock_keys'] and key not in self: raise SyntaxError('setting key \'%s\' does not exist' % key) if key != 'lock_values' and self['lock_values']: raise SyntaxError('setting value cannot be changed: %s' % key) self[key] = value class Messages(Settings): def __init__(self, T): Storage.__init__(self, T=T) def __getattr__(self, key): value = self[key] if isinstance(value, str): return self.T(value) return value class FastStorage(dict): """ Eventually this should replace class Storage but causes memory leak because of http://bugs.python.org/issue1469629 >>> s = FastStorage() >>> s.a = 1 >>> s.a 1 >>> s['a'] 1 >>> s.b >>> s['b'] >>> s['b']=2 >>> s['b'] 2 >>> s.b 2 >>> isinstance(s,dict) True >>> dict(s) {'a': 1, 'b': 2} >>> dict(FastStorage(s)) {'a': 1, 'b': 2} >>> import pickle >>> s = pickle.loads(pickle.dumps(s)) >>> dict(s) {'a': 1, 'b': 2} >>> del s.b >>> del s.a >>> s.a >>> s.b >>> s['a'] >>> s['b'] """ def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self def __getattr__(self, key): return getattr(self, key) if key in self else None def __getitem__(self, key): return dict.get(self, key, None) def copy(self): self.__dict__ = {} s = FastStorage(self) self.__dict__ = self return s def __repr__(self): return '<Storage %s>' % dict.__repr__(self) def __getstate__(self): return dict(self) def __setstate__(self, sdict): dict.__init__(self, sdict) self.__dict__ = self def update(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self class List(list): """ Like a regular python list but a[i] if i is out of bounds returns None instead of `IndexOutOfBounds` """ def __call__(self, i, default=DEFAULT, cast=None, otherwise=None): """Allows to use a special syntax for fast-check of `request.args()` validity Args: i: index default: use this value if arg not found cast: type cast otherwise: can be: - None: results in a 404 - str: redirect to this address - callable: calls the function (nothing is passed) Example: You can use:: request.args(0,default=0,cast=int,otherwise='http://error_url') request.args(0,default=0,cast=int,otherwise=lambda:...) """ n = len(self) if 0 <= i < n or -n <= i < 0: value = self[i] elif default is DEFAULT: value = None else: value, cast = default, False if cast: try: value = cast(value) except (ValueError, TypeError): from http import HTTP, redirect if otherwise is None: raise HTTP(404) elif isinstance(otherwise, str): redirect(otherwise) elif callable(otherwise): return otherwise() else: raise RuntimeError("invalid otherwise") return value if __name__ == '__main__': import doctest doctest.testmod()
shashisp/blumix-webpy
app/gluon/storage.py
Python
mit
8,573
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1000, 1000, 1000, 1064, 2023, 5371, 2003, 2112, 1997, 1996, 4773, 2475, 7685, 4773, 7...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_07) on Tue Sep 01 20:56:59 UTC 2009 --> <TITLE> org.apache.hadoop.contrib.utils.join (Hadoop 0.20.1 API) </TITLE> <META NAME="date" CONTENT="2009-09-01"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.hadoop.contrib.utils.join (Hadoop 0.20.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/hadoop/contrib/index/mapred/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/hadoop/examples/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/contrib/utils/join/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.apache.hadoop.contrib.utils.join </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/ResetableIterator.html" title="interface in org.apache.hadoop.contrib.utils.join">ResetableIterator</A></B></TD> <TD>This defines an iterator interface that will help the reducer class re-group its input by source tags.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/ArrayListBackedIterator.html" title="class in org.apache.hadoop.contrib.utils.join">ArrayListBackedIterator</A></B></TD> <TD>This class provides an implementation of ResetableIterator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/DataJoinJob.html" title="class in org.apache.hadoop.contrib.utils.join">DataJoinJob</A></B></TD> <TD>This class implements the main function for creating a map/reduce job to join data of different sources.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/DataJoinMapperBase.html" title="class in org.apache.hadoop.contrib.utils.join">DataJoinMapperBase</A></B></TD> <TD>This abstract class serves as the base class for the mapper class of a data join job.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/DataJoinReducerBase.html" title="class in org.apache.hadoop.contrib.utils.join">DataJoinReducerBase</A></B></TD> <TD>This abstract class serves as the base class for the reducer class of a data join job.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/JobBase.html" title="class in org.apache.hadoop.contrib.utils.join">JobBase</A></B></TD> <TD>A common base implementing some statics collecting mechanisms that are commonly used in a typical map/reduce job.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/hadoop/contrib/utils/join/TaggedMapOutput.html" title="class in org.apache.hadoop.contrib.utils.join">TaggedMapOutput</A></B></TD> <TD>This abstract class serves as the base class for the values that flow from the mappers to the reducers in a data join job.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/hadoop/contrib/index/mapred/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/hadoop/examples/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/contrib/utils/join/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
koichi626/hadoop-gpu
hadoop-gpu-0.20.1/docs/api/org/apache/hadoop/contrib/utils/join/package-summary.html
HTML
apache-2.0
8,968
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...