code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Freeform - Control Panel * * The Control Panel master class that handles all of the CP requests and displaying. * * @package Solspace:Freeform * @author Solspace, Inc. * @copyright Copyright (c) 2008-2014, Solspace, Inc. * @link http://solspace.com/docs/freeform * @license http://www.solspace.com/license_agreement * @version 4.1.7 * @filesource freeform/mcp.freeform.php */ if ( ! class_exists('Module_builder_freeform')) { require_once 'addon_builder/module_builder.php'; } class Freeform_mcp extends Module_builder_freeform { private $migration_batch_limit = 100; private $pro_update = FALSE; // -------------------------------------------------------------------- /** * Constructor * * @access public * @param bool Enable calling of methods based on URI string * @return string */ public function __construct( $switch = TRUE ) { parent::__construct(); // Install or Uninstall Request if ((bool) $switch === FALSE) return; if ( ! function_exists('lang')) { ee()->load->helper('language'); } // -------------------------------------------- // Module Menu Items // -------------------------------------------- $menu = array( 'module_forms' => array( 'link' => $this->base, 'title' => lang('forms') ), 'module_fields' => array( 'link' => $this->base . AMP . 'method=fields', 'title' => lang('fields') ), 'module_fieldtypes' => array( 'link' => $this->base . AMP . 'method=fieldtypes', 'title' => lang('fieldtypes') ), 'module_notifications' => array( 'link' => $this->base . AMP . 'method=notifications', 'title' => lang('notifications') ), /*'module_export' => array( 'link' => $this->base . AMP . 'method=export', 'title' => lang('export') ),*/ 'module_utilities' => array( 'link' => $this->base . AMP . 'method=utilities', 'title' => lang('utilities') ), 'module_preferences' => array( 'link' => $this->base . AMP . 'method=preferences', 'title' => lang('preferences') ), 'module_documentation' => array( 'link' => FREEFORM_DOCS_URL, 'title' => lang('help'), 'new_window' => TRUE ), ); $this->cached_vars['lang_module_version'] = lang('freeform_module_version'); $this->cached_vars['module_version'] = FREEFORM_VERSION; $this->cached_vars['module_menu_highlight'] = 'module_forms'; $this->cached_vars['inner_nav_links'] = array(); // ------------------------------------- // css includes. WOOT! // ------------------------------------- $this->cached_vars['cp_stylesheet'] = array( 'chosen', 'standard_cp' ); $this->cached_vars['cp_javascript'] = array( 'standard_cp.min', 'chosen.jquery.min' ); // ------------------------------------- // custom CP? // ------------------------------------- $debug_normal = (ee()->input->get_post('debug_normal') !== FALSE); $is_crappy_ie_version = FALSE; $ua = strtolower($_SERVER['HTTP_USER_AGENT']); if (stristr($ua, 'msie 6') OR stristr($ua, 'msie 7') OR stristr($ua, 'msie 8')) { //technically this should be true for any IE version, but... $is_crappy_ie_version = TRUE; } if ( ! $debug_normal AND ! $is_crappy_ie_version AND ! $this->check_no($this->preference('use_solspace_mcp_style'))) { $this->cached_vars['cp_stylesheet'][] = 'custom_cp'; } //avoids AR collisions $this->data->get_module_preferences(); $this->data->get_global_module_preferences(); $this->data->show_all_sites(); // ------------------------------------- // run upgrade or downgrade scripts // ------------------------------------- if (FREEFORM_PRO AND $this->data->global_preference('ffp') === 'n' OR ! FREEFORM_PRO AND $this->data->global_preference('ffp') === 'y') { $_GET['method'] = 'freeform_module_update'; $this->pro_update = TRUE; } $this->cached_vars['module_menu'] = $menu; } // END Freeform_cp_base() //--------------------------------------------------------------------- // begin views //--------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Module's Main Homepage * * @access public * @param string * @return null */ public function index ($message='') { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } return $this->forms($message); } // END index() // -------------------------------------------------------------------- /** * My Forms * * @access public * @param string $message incoming message for flash data * @return string html output */ public function forms($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $new_form_link = $this->mod_link(array( 'method' => 'edit_form' )); $this->cached_vars['new_form_link'] = $new_form_link; $this->add_crumb( lang('forms') ); $this->freeform_add_right_link(lang('new_form'), $new_form_link); $this->set_highlight('module_forms'); //-------------------------------------- // start vars //-------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; // ------------------------------------- // pagination? // ------------------------------------- ee()->load->model('freeform_form_model'); if ( ! $this->data->show_all_sites()) { ee()->freeform_form_model->where( 'site_id', ee()->config->item('site_id') ); } $total_results = ee()->freeform_form_model->count(array(), FALSE); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'forms' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); ee()->freeform_form_model->limit( $row_limit, $pagination_data['pagination_page'] ); $paginate = $pagination_data['pagination_links']; } ee()->freeform_form_model->order_by('form_label'); $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // Did they upgrade from FF3? // ------------------------------------- $this->cached_vars['legacy'] = FALSE; $this->cached_vars['migrate_link'] = ''; ee()->load->library('freeform_migration'); if ( ee()->freeform_migration->legacy() === TRUE ) { $this->cached_vars['legacy'] = TRUE; $this->cached_vars['migrate_link'] = $this->mod_link(array('method' => 'utilities')); } // ------------------------------------- // data // ------------------------------------- $rows = ee()->freeform_form_model->get(); $form_data = array(); if ($rows !== FALSE) { // ------------------------------------- // check for composer for each form // ------------------------------------- $form_ids = array(); $potential_composer_ids = array(); foreach ($rows as $row) { $form_ids[] = $row['form_id']; if ($this->is_positive_intlike($row['composer_id'])) { $potential_composer_ids[$row['form_id']] = $row['composer_id']; } } $has_composer = array(); if ( ! empty($potential_composer_ids)) { ee()->load->model('freeform_composer_model'); $composer_ids = ee()->freeform_composer_model ->key('composer_id', 'composer_id') ->where('preview !=', 'y') ->where_in( 'composer_id', array_values($potential_composer_ids) ) ->get(); if ( ! empty($composer_ids)) { foreach ($potential_composer_ids as $form_id => $composer_id) { if (in_array($composer_id, $composer_ids)) { $has_composer[$form_id] = $composer_id; } } } } // ------------------------------------- // suppliment rows // ------------------------------------- foreach ($rows as $row) { $row['submissions_count'] = ( $this->data->get_form_submissions_count($row['form_id']) ); $row['moderate_count'] = ( $this->data->get_form_needs_moderation_count($row['form_id']) ); $row['has_composer'] = isset( $has_composer[$row['form_id']] ); // ------------------------------------- // piles o' links // ------------------------------------- $row['form_submissions_link'] = $this->mod_link(array( 'method' => 'entries', 'form_id' => $row['form_id'] )); $row['form_moderate_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $row['form_id'], 'search_status' => 'pending' )); $row['form_edit_composer_link'] = $this->mod_link(array( 'method' => 'form_composer', 'form_id' => $row['form_id'] )); $row['form_settings_link'] = $this->mod_link(array( 'method' => 'edit_form', 'form_id' => $row['form_id'] )); $row['form_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_form', 'duplicate_id' => $row['form_id'] )); $row['form_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_form', 'form_id' => $row['form_id'] )); $form_data[] = $row; } } $this->cached_vars['form_data'] = $form_data; $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'delete_confirm_form' )); // ---------------------------------------- // Load vars // ---------------------------------------- // ------------------------------------- // JS // ------------------------------------- ee()->cp->add_js_script( array('plugin' => array('tooltip', 'dataTables')) ); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'forms.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END forms // -------------------------------------------------------------------- /** * delete_confirm_form * * @access public * @return string */ public function delete_confirm_form () { $form_ids = ee()->input->get_post('form_id', TRUE); if ( ! is_array($form_ids) AND ! $this->is_positive_intlike($form_ids) ) { $this->actions()->full_stop(lang('no_form_ids_submitted')); } //already checked for numeric :p if ( ! is_array($form_ids)) { $form_ids = array($form_ids); } return $this->delete_confirm( 'delete_forms', array('form_ids' => $form_ids), 'delete_form_confirmation' ); } //END delete_confirm_form // -------------------------------------------------------------------- /** * delete_forms * * @access public * @return string */ public function delete_forms ($form_ids = array()) { $message = 'delete_form_success'; if ( empty($form_ids) ) { $form_ids = ee()->input->get_post('form_ids'); } if ( ! is_array($form_ids) AND $this->is_positive_intlike($form_ids)) { $form_ids = array($form_ids); } //if everything is all nice and array like, DELORT //but one last check on each item to make sure its a number if ( is_array($form_ids)) { ee()->load->library('freeform_forms'); foreach ($form_ids as $form_id) { if ($this->is_positive_intlike($form_id)) { ee()->freeform_forms->delete_form($form_id); } } } //the voyage home ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => $message ))); } //END delete_forms // -------------------------------------------------------------------- /** * Edit Form * * @access public * @return string html output */ public function edit_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = $this->cached_vars['update'] = ($form_id != 0); // ------------------------------------- // default data // ------------------------------------- $inputs = array( 'form_id' => '0', 'form_name' => '', 'form_label' => '', 'default_status' => $this->data->defaults['default_form_status'], 'notify_admin' => 'n', 'notify_user' => 'n', 'user_email_field' => '', 'user_notification_id' => '0', 'admin_notification_id' => '0', 'admin_notification_email' => ee()->config->item('webmaster_email'), 'form_description' => '', 'template_id' => '0', 'composer_id' => '0', 'field_ids' => '', 'field_order' => '', ); // ------------------------------------- // updating? // ------------------------------------- if ($update) { $form_data = $this->data->get_form_info($form_id); if ($form_data) { foreach ($form_data as $key => $value) { if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } $inputs[$key] = form_prep($value); } } else { $this->actions()->full_stop(lang('invalid_form_id')); } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $update ? lang('update_form') . ': ' . $form_data['form_label'] : lang('new_form') ); $this->set_highlight('module_forms'); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicate_id'] = $duplicate_id; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $form_data = $this->data->get_form_info($duplicate_id); if ($form_data) { foreach ($form_data as $key => $value) { if (in_array($key, array('form_id', 'form_label', 'form_name'))) { continue; } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $form_data['form_label']; } } if (isset($form_data['field_ids']) AND ! empty($form_data['field_ids']) AND isset($form_data['field_order']) AND ! empty($form_data['field_order'])) { $field_ids = $form_data['field_ids']; if ( ! is_array($field_ids)) { $field_ids = $this->actions()->pipe_split($field_ids); } $field_order = $form_data['field_order']; if ( ! is_array($field_order)) { $field_order = $this->actions()->pipe_split($field_order); } $missing_ids = array_diff($field_ids, $field_order); $inputs['field_order'] = implode('|', array_merge($field_order, $missing_ids)); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } // ------------------------------------- // select boxes // ------------------------------------- $this->cached_vars['statuses'] = $this->data->get_form_statuses(); ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); //fields $this->cached_vars['available_fields'] = $available_fields; //notifications $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); // ------------------------------------- // user email fields // ------------------------------------- $user_email_fields = array('' => lang('choose_user_email_field')); $f_rows = ee()->freeform_field_model ->select('field_id, field_label, settings') ->get(array('field_type' => 'text')); //we only want fields that are being validated as email if ($f_rows) { foreach ($f_rows as $row) { $row_settings = json_decode($row['settings'], TRUE); $row_settings = (is_array($row_settings)) ? $row_settings : array(); if (isset($row_settings['field_content_type']) AND $row_settings['field_content_type'] == 'email') { $user_email_fields[$row['field_id']] = $row['field_label']; } } } $this->cached_vars['user_email_fields'] = $user_email_fields; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_form' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; ee()->cp->add_js_script(array( 'ui' => array('draggable', 'droppable', 'sortable') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_form.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_form // -------------------------------------------------------------------- /** * form composer * * ajax form and field builder * * @access public * @param string message lang line * @return string html output */ public function form_composer ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // form_id // ------------------------------------- $form_id = ee()->input->get_post('form_id', TRUE); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $update = $form_data['composer_id'] != 0; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->base ); $this->add_crumb( lang('composer') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['form_data'] = $form_data; // ------------------------------------- // fields for composer // ------------------------------------- ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model ->where('composer_use', 'y') ->order_by('field_label') ->key('field_name') ->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); // ------------------------------------- // templates // ------------------------------------- ee()->load->model('freeform_template_model'); $available_templates = ee()->freeform_template_model ->where('enable_template', 'y') ->order_by('template_label') ->key('template_id', 'template_label') ->get(); $available_templates = ($available_templates !== FALSE) ? $available_templates : array(); // ------------------------------------- // get field output for composer // ------------------------------------- ee()->load->library('freeform_fields'); $field_composer_output = array(); $field_id_list = array(); foreach ($available_fields as $field_name => $field_data) { $field_id_list[$field_data['field_id']] = $field_name; //encode to keep JS from running //camel case because its exposed in JS $field_composer_output[$field_name] = $this->composer_field_data( $field_data['field_id'], $field_data, TRUE ); } $this->cached_vars['field_id_list'] = $this->json_encode($field_id_list); $this->cached_vars['field_composer_output_json'] = $this->json_encode($field_composer_output); $this->cached_vars['available_fields'] = $available_fields; $this->cached_vars['available_templates'] = $available_templates; $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); $this->cached_vars['disable_missing_submit_warning'] = $this->check_yes( $this->preference('disable_missing_submit_warning') ); // ------------------------------------- // previous composer data? // ------------------------------------- $composer_data = '{}'; if ($form_data['composer_id'] > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $form_data['composer_id']) ->get_row(); if ($composer !== FALSE) { $composer_data_test = $this->json_decode($composer['composer_data']); if ($composer_data_test) { $composer_data = $composer['composer_data']; } } } $this->cached_vars['composer_layout_data'] = $composer_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_allowed_html_tags'] = ( lang('allowed_html_tags') . "&lt;" . implode("&gt;, &lt;", $this->data->allowed_html_tags) . "&gt;" ); $this->cached_vars['captcha_dummy_url'] = $this->sc->addon_theme_url . 'images/captcha.png'; $this->cached_vars['new_field_url'] = $this->mod_link(array( 'method' => 'edit_field', //this builds a URL, so yes this is intentionally a string 'modal' => 'true' ), TRUE); $this->cached_vars['field_data_url'] = $this->mod_link(array( 'method' => 'composer_field_data' ), TRUE); $this->cached_vars['composer_preview_url'] = $this->mod_link(array( 'method' => 'composer_preview', 'form_id' => $form_id ), TRUE); $this->cached_vars['composer_ajax_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id ), TRUE); // $this->cached_vars['composer_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id )); $this->cached_vars['allowed_html_tags'] = "'" . implode("','", $this->data->allowed_html_tags) . "'"; // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); ee()->cp->add_js_script(array( 'ui' => array('sortable', 'draggable', 'droppable'), 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'composer_cp.min'; $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['cp_javascript'][] = 'security.min'; $this->cached_vars['current_page'] = $this->view( 'composer.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END form_composer // -------------------------------------------------------------------- /** * Composer preview * * @access public * @return mixed ajax return if detected or else html without cp */ public function composer_preview () { $form_id = $this->get_post_or_zero('form_id'); $template_id = $this->get_post_or_zero('template_id'); $composer_id = $this->get_post_or_zero('composer_id'); $preview_id = $this->get_post_or_zero('preview_id'); $subpreview = (ee()->input->get_post('subpreview') !== FALSE); $composer_page = $this->get_post_or_zero('composer_page'); if ( ! $this->data->is_valid_form_id($form_id)) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // is this a preview? // ------------------------------------- if ($preview_id > 0) { $preview_mode = TRUE; $composer_id = $preview_id; } $page_count = 1; // ------------------------------------- // main output or sub output? // ------------------------------------- if ( ! $subpreview) { // ------------------------------------- // get composer data and build page count // ------------------------------------- if ($composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer !== FALSE) { $composer_data = $this->json_decode( $composer['composer_data'], TRUE ); if ($composer_data AND isset($composer_data['rows']) AND ! empty($composer_data['rows'])) { foreach ($composer_data['rows'] as $row) { if ($row == 'page_break') { $page_count++; } } } } } $page_url = array(); for ($i = 1, $l = $page_count; $i <= $l; $i++) { $page_url[] = $this->mod_link(array( 'method' => __FUNCTION__, 'form_id' => $form_id, 'template_id' => $template_id, 'preview_id' => $preview_id, 'subpreview' => 'true', 'composer_page' => $i )); } $this->cached_vars['page_url'] = $page_url; $this->cached_vars['default_preview_css'] = $this->sc->addon_theme_url . 'css/default_composer.css'; $this->cached_vars['jquery_src'] = ee()->functions->fetch_site_index(0, 0) . QUERY_MARKER . 'ACT=jquery'; $html = $this->view('composer_preview.html', NULL, TRUE); } else { $subhtml = "{exp:freeform:composer form_id='$form_id'"; $subhtml .= ($composer_page > 1) ? " multipage_page='" . $composer_page . "'" : ''; $subhtml .= ($template_id > 0) ? " composer_template_id='" . $template_id . "'" : ''; $subhtml .= ($preview_id > 0) ? " preview_id='" . $preview_id . "'" : ''; $subhtml .= "}"; $html = $this->actions()->template()->process_string_as_template($subhtml); } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'html' => $html )); } else { exit($html); } } //end composer preview // -------------------------------------------------------------------- /** * entries * * @access public * @param string $message message lang line * @param bool $moderate are we moderating? * @param bool $export export? * @return string html output */ public function entries ( $message = '' , $moderate = FALSE, $export = FALSE) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // moderate // ------------------------------------- $search_status = ee()->input->get_post('search_status'); $moderate = ( $moderate AND ($search_status == 'pending' OR $search_status === FALSE ) ); //if moderate and search status was not submitted, fake into pending if ($moderate AND $search_status === FALSE) { $_POST['search_status'] = 'pending'; } $this->cached_vars['moderate'] = $moderate; $this->cached_vars['method'] = $method = ( $moderate ? 'moderate_entries' : 'entries' ); // ------------------------------------- // user using session id instead of cookies? // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); // ------------------------------------- // form data? legit? GTFO? // ------------------------------------- $form_id = ee()->input->get_post('form_id'); ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); //form data does all of the proper id validity checks for us $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { $this->actions()->full_stop(lang('invalid_form_id')); exit(); } $this->cached_vars['form_id'] = $form_id; $this->cached_vars['form_label'] = $form_data['form_label']; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $form_data['form_label'] . ': ' . lang($moderate ? 'moderate' : 'entries') ); $this->set_highlight('module_forms'); $this->freeform_add_right_link( lang('new_entry'), $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id )) ); // ------------------------------------- // status prefs // ------------------------------------- $form_statuses = $this->data->get_form_statuses(); $this->cached_vars['form_statuses'] = $form_statuses; // ------------------------------------- // rest of models // ------------------------------------- ee()->load->model('freeform_entry_model'); ee()->freeform_entry_model->id($form_id); // ------------------------------------- // custom field labels // ------------------------------------- $standard_columns = $this->get_standard_column_names(); //we want author instead of author id until we get data $possible_columns = $standard_columns; //key = value $all_columns = array_combine($standard_columns, $standard_columns); $column_labels = array(); $field_column_names = array(); //field prefix $f_prefix = ee()->freeform_form_model->form_field_prefix; //keyed labels for the front end foreach ($standard_columns as $column_name) { $column_labels[$column_name] = lang($column_name); } // ------------------------------------- // check for fields with custom views for entry tables // ------------------------------------- ee()->load->library('freeform_fields'); //fields in this form foreach ($form_data['fields'] as $field_id => $field_data) { //outputs form_field_1, form_field_2, etc for ->select() $field_id_name = $f_prefix . $field_id; $field_column_names[$field_id_name] = $field_data['field_name']; $all_columns[$field_id_name] = $field_data['field_name']; $column_labels[$field_data['field_name']] = $field_data['field_label']; $column_labels[$field_id_name] = $field_data['field_label']; $possible_columns[] = $field_id; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $field_data )); if ( ! empty($instance->entry_views)) { foreach ($instance->entry_views as $e_lang => $e_method) { $this->freeform_add_right_link( $e_lang, $this->mod_link(array( 'method' => 'field_method', 'field_id' => $field_id, 'field_method' => $e_method, 'form_id' => $form_id )) ); } } } // ------------------------------------- // visible columns // ------------------------------------- $visible_columns = $this->visible_columns($standard_columns, $possible_columns); $this->cached_vars['visible_columns'] = $visible_columns; $this->cached_vars['column_labels'] = $column_labels; $this->cached_vars['possible_columns'] = $possible_columns; $this->cached_vars['all_columns'] = $all_columns; // ------------------------------------- // prep unused from from possible // ------------------------------------- //so so used $un_used = array(); foreach ($possible_columns as $pcid) { $check = ($this->is_positive_intlike($pcid)) ? $f_prefix . $pcid : $pcid; if ( ! in_array($check, $visible_columns)) { $un_used[] = $check; } } $this->cached_vars['unused_columns'] = $un_used; // ------------------------------------- // build query // ------------------------------------- //base url for pagination $pag_url = array( 'method' => $method, 'form_id' => $form_id ); //cleans out blank keys from unset $find_columns = array_merge(array(), $visible_columns); $must_haves = array('entry_id'); // ------------------------------------- // search criteria // building query // ------------------------------------- $has_search = FALSE; $search_vars = array( 'search_keywords', 'search_status', 'search_date_range', 'search_date_range_start', 'search_date_range_end', 'search_on_field' ); foreach ($search_vars as $search_var) { $$search_var = ee()->input->get_post($search_var, TRUE); //set for output $this->cached_vars[$search_var] = ( ($$search_var) ? trim($$search_var) : '' ); } // ------------------------------------- // search keywords // ------------------------------------- if ($search_keywords AND trim($search_keywords) !== '' AND $search_on_field AND in_array($search_on_field, $visible_columns)) { ee()->freeform_entry_model->like( $search_on_field, $search_keywords ); //pagination $pag_url['search_keywords'] = $search_keywords; $pag_url['search_on_field'] = $search_on_field; $has_search = TRUE; } //no search on field? guess we had better search it all *gulp* else if ($search_keywords AND trim($search_keywords) !== '') { $first = TRUE; ee()->freeform_entry_model->group_like( $search_keywords, array_values($visible_columns) ); $pag_url['search_keywords'] = $search_keywords; $has_search = TRUE; } //status search? if ($moderate) { ee()->freeform_entry_model->where('status', 'pending'); } else if ($search_status AND in_array($search_status, array_flip( $form_statuses))) { ee()->freeform_entry_model->where('status', $search_status); //pagination $pag_url['search_status'] = $search_status; $has_search = TRUE; } // ------------------------------------- // date range? // ------------------------------------- //pagination if ($search_date_range == 'date_range') { //if its the same date, lets set the time to the end of the day if ($search_date_range_start == $search_date_range_end) { $search_date_range_end .= ' 23:59'; } if ($search_date_range_start !== FALSE) { $pag_url['search_date_range_start'] = $search_date_range_start; } if ($search_date_range_end !== FALSE) { $pag_url['search_date_range_end'] = $search_date_range_end; } //pagination if ($search_date_range_start OR $search_date_range_end) { $pag_url['search_date_range'] = 'date_range'; $has_search = TRUE; } } else if ($search_date_range !== FALSE) { $pag_url['search_date_range'] = $search_date_range; $has_search = TRUE; } ee()->freeform_entry_model->date_where( $search_date_range, $search_date_range_start, $search_date_range_end ); // ------------------------------------- // any searches? // ------------------------------------- $this->cached_vars['has_search'] = $has_search; // ------------------------------------- // data from all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_entry_model->where( 'site_id', ee()->config->item('site_id') ); } //we need the counts for exports and end results $total_entries = ee()->freeform_entry_model->count(array(), FALSE); // ------------------------------------- // orderby // ------------------------------------- $order_by = 'entry_date'; $p_order_by = ee()->input->get_post('order_by'); if ($p_order_by !== FALSE AND in_array($p_order_by, $all_columns)) { $order_by = $p_order_by; $pag_url['order_by'] = $order_by; } // ------------------------------------- // sort // ------------------------------------- $sort = ($order_by == 'entry_date') ? 'desc' : 'asc'; $p_sort = ee()->input->get_post('sort'); if ($p_sort !== FALSE AND in_array(strtolower($p_sort), array('asc', 'desc'))) { $sort = strtolower($p_sort); $pag_url['sort'] = $sort; } ee()->freeform_entry_model->order_by($order_by, $sort); $this->cached_vars['order_by'] = $order_by; $this->cached_vars['sort'] = $sort; // ------------------------------------- // export button // ------------------------------------- if ($total_entries > 0) { $this->freeform_add_right_link( lang('export_entries'), '#export_entries' ); } // ------------------------------------- // export url // ------------------------------------- $export_url = $pag_url; $export_url['moderate'] = $moderate ? 'true' : 'false'; $export_url['method'] = 'export_entries'; $this->cached_vars['export_url'] = $this->mod_link($export_url); // ------------------------------------- // export? // ------------------------------------- if ($export) { $export_fields = ee()->input->get_post('export_fields'); $export_labels = $column_labels; // ------------------------------------- // build possible select alls // ------------------------------------- $select = array(); //are we sending just the selected fields? if ($export_fields != 'all') { $select = array_unique(array_merge($must_haves, $find_columns)); foreach ($export_labels as $key => $value) { //clean export labels for json if ( ! in_array($key, $select)) { unset($export_labels[$key]); } } //get real names foreach ($select as $key => $value) { if (isset($field_column_names[$value])) { $select[$key] = $field_column_names[$value]; } } } //sending all fields means we need to still clean some labels else { foreach ($all_columns as $field_id_name => $field_name) { //clean export labels for json if ($field_id_name != $field_name) { unset($export_labels[$field_id_name]); } $select[] = $field_name; } } foreach ($export_labels as $key => $value) { //fix entities $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8'); $export_labels[$key] = $value; if (isset($field_column_names[$key])) { $export_labels[$field_column_names[$key]] = $value; } } ee()->freeform_entry_model->select(implode(', ', $select)); // ------------------------------------- // check for chunking, etc // ------------------------------------- ee()->load->library('freeform_export'); ee()->freeform_export->format_dates = (ee()->input->get_post('format_dates') == 'y'); ee()->freeform_export->export(array( 'method' => ee()->input->get_post('export_method'), 'form_id' => $form_id, 'form_name' => $form_data['form_name'], 'output' => 'download', 'model' => ee()->freeform_entry_model, 'remove_entry_id' => ($export_fields != 'all' AND ! in_array('entry_id', $visible_columns)), 'header_labels' => $export_labels, 'total_entries' => $total_entries )); } //END if ($export) // ------------------------------------- // selects // ------------------------------------- $needed_selects = array_unique(array_merge($must_haves, $find_columns)); ee()->freeform_entry_model->select(implode(', ', $needed_selects)); //-------------------------------------- // pagination start vars //-------------------------------------- $pag_url = $this->mod_link($pag_url); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; //moved above exports //$total_entries = ee()->freeform_entry_model->count(array(), FALSE); $current_page = 0; // ------------------------------------- // pagination? // ------------------------------------- // do we need pagination? if ($total_entries > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_entries, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $pag_url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; $current_page = $pagination_data['pagination_page']; ee()->freeform_entry_model->limit($row_limit, $current_page); } $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // get data // ------------------------------------- $result_array = ee()->freeform_entry_model->get(); $count = $row_count; $entries = array(); if ( ! $result_array) { $result_array = array(); } $entry_ids = array(); foreach ($result_array as $row) { $entry_ids[] = $row['entry_id']; } // ------------------------------------- // allow pre_process // ------------------------------------- ee()->freeform_fields->apply_field_method(array( 'method' => 'pre_process_entries', 'form_id' => $form_id, 'entry_id' => $entry_ids, 'form_data' => $form_data, 'field_data' => $form_data['fields'] )); foreach ( $result_array as $row) { //apply display_entry_cp to our field data $field_parse = ee()->freeform_fields->apply_field_method(array( 'method' => 'display_entry_cp', 'form_id' => $form_id, 'entry_id' => $row['entry_id'], 'form_data' => $form_data, 'field_data' => $form_data['fields'], 'field_input_data' => $row )); $row = array_merge($row, $field_parse['variables']); $entry = array(); $entry['view_entry_link'] = $this->mod_link(array( 'method' => 'view_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['edit_entry_link'] = $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['approve_link'] = $this->mod_link(array( 'method' => 'approve_entries', 'form_id' => $form_id, 'entry_ids' => $row['entry_id'] )); $entry['count'] = ++$count; $entry['id'] = $row['entry_id']; // ------------------------------------- // remove entry_id and author_id if we // arent showing them // ------------------------------------- if ( ! in_array('entry_id', $visible_columns)) { unset($row['entry_id']); } // ------------------------------------- // dates // ------------------------------------- if (in_array('entry_date', $visible_columns)) { $row['entry_date'] = $this->format_cp_date($row['entry_date']); } if (in_array('edit_date', $visible_columns)) { $row['edit_date'] = ($row['edit_date'] == 0) ? '' : $this->format_cp_date($row['edit_date']); } $entry['data'] = $row; $entries[] = $entry; } $this->cached_vars['entries'] = $entries; // ------------------------------------- // ajax request? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'entries' => $entries, 'paginate' => $paginate, 'visibleColumns' => $visible_columns, 'allColumns' => $all_columns, 'columnLabels' => $column_labels, 'success' => TRUE )); exit(); } // ------------------------------------- // moderation count? // ------------------------------------- //lets not waste the query if we are already moderating $moderation_count = ( ( ! $moderate) ? $this->data->get_form_needs_moderation_count($form_id) : 0 ); if ($moderation_count > 0) { $this->cached_vars['lang_num_items_awaiting_moderation'] = str_replace( array('%num%', '%form_label%'), array($moderation_count, $form_data['form_label']), lang('num_items_awaiting_moderation') ); } $this->cached_vars['moderation_count'] = $moderation_count; $this->cached_vars['moderation_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $form_id, 'search_status' => 'pending' )); // ------------------------------------- // is admin? // ------------------------------------- $this->cached_vars['is_admin'] = $is_admin = ( ee()->session->userdata('group_id') == 1 ); // ------------------------------------- // can save field layout? // ------------------------------------- //$this->cached_vars['can_edit_layout'] = $can_edit_layout = ( // $is_admin OR // $this->check_yes($this->preference('allow_user_field_layout')) //); //just in case $this->cached_vars['can_edit_layout'] = TRUE; $this->freeform_add_right_link( lang('edit_field_layout'), '#edit_field_layout' ); // ------------------------------------- // member groups // ------------------------------------- $member_groups = array(); if ($is_admin) { ee()->db->select('group_id, group_title'); $member_groups = $this->prepare_keyed_result( ee()->db->get('member_groups'), 'group_id', 'group_title' ); } $this->cached_vars['member_groups'] = $member_groups; // ------------------------------------- // lang items // ------------------------------------- // ------------------------------------- // no results lang // ------------------------------------- $this->cached_vars['lang_no_results_for_form'] = ( ($has_search) ? lang('no_results_for_search') : ( ($moderate) ? lang('no_entries_awaiting_approval') : lang('no_entries_for_form') ) ); // ------------------------------------- // moderation lang // ------------------------------------- $this->cached_vars['lang_viewing_moderation'] = str_replace( '%form_label%', $form_data['form_label'], lang('viewing_moderation') ); // ------------------------------------- // other vars // ------------------------------------- $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'entries_action', 'return_method' => (($moderate) ? 'moderate_' : '' ) . 'entries' )); $this->cached_vars['save_layout_url'] = $this->mod_link(array( 'method' => 'save_field_layout' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); //$this->load_datatables(); ee()->cp->add_js_script(array( 'ui' => array('datepicker', 'sortable'), 'file' => 'underscore' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'entries.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END entries // -------------------------------------------------------------------- /** * Fire a field method as a page view * * @access public * @param string $message lang line to load for a message * @return string html output */ public function field_method ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // goods // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $field_id = $this->get_post_or_zero('field_id'); $field_method = ee()->input->get_post('field_method'); $instance = FALSE; if ( $field_method == FALSE OR ! $this->data->is_valid_form_id($form_id) OR $field_id == 0) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } ee()->load->library('freeform_fields'); $instance =& ee()->freeform_fields->get_field_instance(array( 'form_id' => $form_id, 'field_id' => $field_id )); //legit? if ( ! is_object($instance) OR empty($instance->entry_views) OR //removed so you can post to this //! in_array($field_method, $instance->entry_views) OR ! is_callable(array($instance, $field_method))) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } $method_lang = lang('field_entry_view'); foreach ($instance->entry_views as $e_lang => $e_method) { if ($field_method == $e_method) { $method_lang = $e_lang; } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('entries'), $this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id )) ); $this->add_crumb($method_lang); $this->set_highlight('module_forms'); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $instance->$field_method(); // ------------------------------------- // loading these after the instance // incase the instance exits // ------------------------------------- $this->load_fancybox(); return $this->ee_cp_view('index.html'); } //END field_method // -------------------------------------------------------------------- /** * migrate collections * * @access public * @return string */ public function migrate_collections ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Library //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Variables //-------------------------------------- $migrate_empty_fields = 'n'; $migrate_attachments = 'n'; $this->cached_vars['total'] = 0; $this->cached_vars['collections'] = ''; $collections = ee()->input->post('collections'); if ( $collections !== FALSE ) { $this->cached_vars['total'] = ee()->freeform_migration ->get_migration_count( $collections ); $this->cached_vars['collections'] = implode('|', $collections); if ($this->check_yes( ee()->input->post('migrate_empty_fields') ) ) { $migrate_empty_fields = 'y'; } if ($this->check_yes( ee()->input->post('migrate_attachments') ) ) { $migrate_attachments = 'y'; } } //-------------------------------------- // Migration ajax url //-------------------------------------- $this->cached_vars['ajax_url'] = $this->base . '&method=migrate_collections_ajax' . '&migrate_empty_fields=' . $migrate_empty_fields . '&migrate_attachments=' . $migrate_attachments . '&collections=' . urlencode( $this->cached_vars['collections'] ) . '&total=' . $this->cached_vars['total'] . '&batch=0'; //-------------------------------------- // images //-------------------------------------- //Success image $this->cached_vars['success_png_url'] = $this->sc->addon_theme_url . 'images/success.png'; // Error image $this->cached_vars['error_png_url'] = $this->sc->addon_theme_url . 'images/exclamation.png'; //-------------------------------------- // Javascript //-------------------------------------- $this->cached_vars['cp_javascript'][] = 'migrate'; ee()->cp->add_js_script( array('ui' => array('core', 'progressbar')) ); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'migrate.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End migrate collections // -------------------------------------------------------------------- /** * migrate collections ajax * * @access public * @return string */ public function migrate_collections_ajax() { $upper_limit = 9999; //-------------------------------------- // Base output //-------------------------------------- $out = array( 'done' => FALSE, 'batch' => ee()->input->get('batch'), 'total' => ee()->input->get('total') ); //-------------------------------------- // Libraries //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Validate //-------------------------------------- $collections = ee()->input->get('collections'); if ( empty( $collections ) OR ee()->input->get('batch') === FALSE ) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Done? //-------------------------------------- if ( ee()->input->get('batch') !== FALSE AND ee()->input->get('total') !== FALSE AND ee()->input->get('batch') >= ee()->input->get('total') ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Anything? //-------------------------------------- $collections = $this->actions()->pipe_split( urldecode( ee()->input->get('collections') ) ); $counts = ee()->freeform_migration->get_collection_counts($collections); if (empty($counts)) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Do any of the submitted collections have unmigrated entries? //-------------------------------------- $migrate = FALSE; foreach ( $counts as $form_name => $val ) { if ( ! empty( $val['unmigrated'] ) ) { $migrate = TRUE; } } if ( empty( $migrate ) ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Master arrays //-------------------------------------- $forms = array(); $form_fields = array(); //-------------------------------------- // Loop and process //-------------------------------------- foreach ( $counts as $form_name => $val ) { //-------------------------------------- // For each collection, create a form //-------------------------------------- $form_data = ee()->freeform_migration->create_form($form_name); if ( $form_data !== FALSE ) { $forms[ $form_data['form_name'] ]['form_id'] = $form_data['form_id']; $forms[ $form_data['form_name'] ]['form_label'] = $form_data['form_label']; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, determine fields //-------------------------------------- $migrate_empty_fields = ( $this->check_yes(ee()->input->get('migrate_empty_fields')) ) ? 'y': 'n'; $fields = ee()->freeform_migration->get_fields_for_collection( $form_name, $migrate_empty_fields ); if ($fields !== FALSE) { $form_fields[ $form_name ]['fields'] = $fields; } else { $errors = ee()->freeform_migration->get_errors(); if ($errors !== FALSE) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, create necessary fields if they don't yet exist. //-------------------------------------- $created_field_ids = array(); if ( ! empty( $form_fields[$form_name]['fields'] ) ) { foreach ( $form_fields[$form_name]['fields'] as $name => $attr ) { $field_id = ee()->freeform_migration->create_field( $forms[$form_name]['form_id'], $name, $attr ); if ($field_id !== FALSE ) { $created_field_ids[] = $field_id; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } } //-------------------------------------- // For each collection, create upload fields if needed. //-------------------------------------- $attachment_profiles = ee()->freeform_migration->get_attachment_profiles( $form_name ); if ($this->check_yes( ee()->input->get('migrate_attachments') ) AND $attachment_profiles !== FALSE ) { foreach ( $attachment_profiles as $row ) { $field_id = ee()->freeform_migration->create_upload_field( $forms[ $form_name ]['form_id'], $row['name'], $row ); if ($field_id !== FALSE) { $created_field_ids[] = $field_id; $upload_pref_id_map[ $row['pref_id'] ] = array( 'field_id' => $field_id, 'field_name' => $row['name'] ); } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } if ( ! empty( $upload_pref_id_map ) ) { ee()->freeform_migration->set_property( 'upload_pref_id_map', $upload_pref_id_map ); } } //-------------------------------------- // Assign the fields to our form. //-------------------------------------- ee()->freeform_migration->assign_fields_to_form( $forms[ $form_data['form_name'] ]['form_id'], $created_field_ids ); //-------------------------------------- // Safeguard? //-------------------------------------- if ( ee()->input->get('batch') == $upper_limit ) { $this->send_ajax_response(array('done' => TRUE )); exit(); } //-------------------------------------- // Pass attachments pref //-------------------------------------- if ($this->check_yes( ee()->input->get('migrate_attachments') ) ) { ee()->freeform_migration->set_property('migrate_attachments', TRUE); } //-------------------------------------- // Grab entries //-------------------------------------- ee()->freeform_migration->set_property( 'batch_limit', $this->migration_batch_limit ); $entries = ee()->freeform_migration->get_legacy_entries($form_name); if ( $entries !== FALSE ) { foreach ( $entries as $entry ) { //-------------------------------------- // Insert //-------------------------------------- $entry_id = ee()->freeform_migration->set_legacy_entry( $forms[ $form_name ]['form_id'], $entry ); if ( $entry_id === FALSE ) { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } else { $out['batch'] = $out['batch'] + 1; } } } } //-------------------------------------- // Are we done? //-------------------------------------- $this->send_ajax_response($out); exit(); } // End migrate collections ajax // -------------------------------------------------------------------- /** * moderate entries * * almost the same as entries but with some small modifications * * @access public * @param string message lang line * @return string html output */ public function moderate_entries ( $message = '' ) { return $this->entries($message, TRUE); } //END moderate_entries // -------------------------------------------------------------------- /** * Action from submitted entries links * * @access public * @return string html output */ public function entries_action () { $action = ee()->input->get_post('submit_action'); if ($action == 'approve') { return $this->approve_entries(); } else if ($action == 'delete') { return $this->delete_confirm_entries(); } /* else if ($action == 'edit') { $this->edit_entries(); } */ } //END entries_action // -------------------------------------------------------------------- /** * [edit_entry description] * * @access public * @return string parsed html */ public function edit_entry ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $entry_data = array(); $edit = FALSE; if ($entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ($entry_data == FALSE) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $edit = TRUE; } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( lang($edit ? 'edit_entry' : 'new_entry') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // load the template library in case // people get upset or something // ------------------------------------- if ( ! isset(ee()->TMPL) OR ! is_object(ee()->TMPL)) { ee()->load->library('template'); $globals['TMPL'] =& ee()->template; ee()->TMPL =& ee()->template; } // ------------------------------------- // get fields // ------------------------------------- ee()->load->library('freeform_fields'); $field_output_data = array(); $field_loop_ids = array_keys($form_data['fields']); if ($form_data['field_order'] !== '') { $order_ids = $this->actions()->pipe_split($form_data['field_order']); if ( ! empty($order_ids)) { //this makes sure that any fields in 'fields' are in the //order set as well. Will add missing at the end like this $field_loop_ids = array_merge( $order_ids, array_diff($field_loop_ids, $order_ids) ); } } foreach ($field_loop_ids as $field_id) { if ( ! isset($form_data['fields'][$field_id])) { continue; } $f_data = $form_data['fields'][$field_id]; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $f_data, 'form_id' => $form_id, 'entry_id' => $entry_id, 'edit' => $edit, 'extra_settings' => array( 'entry_id' => $entry_id ) )); $column_name = ee()->freeform_entry_model->form_field_prefix . $field_id; $display_field_data = ''; if ($edit) { if (isset($entry_data[$column_name])) { $display_field_data = $entry_data[$column_name]; } else if (isset($entry_data[$f_data['field_name']])) { $display_field_data = $entry_data[$f_data['field_name']]; } } $field_output_data[$field_id] = array( 'field_display' => $instance->display_edit_cp($display_field_data), 'field_label' => $f_data['field_label'], 'field_description' => $f_data['field_description'] ); } $entry_data['screen_name'] = ''; $entry_data['group_title'] = ''; if (!empty($entry_data['author_id'])) { $member_data = ee()->db ->select('group_title, screen_name') ->from('members') ->join('member_groups', 'members.group_id = member_groups.group_id', 'left') ->where('member_id', $entry_data['author_id']) ->limit(1) ->get(); if ($member_data->num_rows() > 0) { $entry_data['screen_name'] = $member_data->row('screen_name'); $entry_data['group_title'] = $member_data->row('group_title'); } } if ($entry_data['screen_name'] == '') { $entry_data['screen_name'] = lang('guest'); $entry_data['group_title'] = lang('guest'); $guest_data = ee()->db ->select('group_title') ->from('member_groups') ->where('group_id', 3) ->limit(1) ->get(); if ($guest_data->num_rows() > 0) { $entry_data['group_title'] = $guest_data->row('group_title'); } } $entry_data['entry_date'] = ( ! empty( $entry_data['entry_date'] ) ) ? $entry_data['entry_date'] : ee()->localize->now; $entry_data['entry_date'] = $this->format_cp_date($entry_data['entry_date']); $entry_data['edit_date'] = (!empty($entry_data['edit_date'])) ? $this->format_cp_date($entry_data['edit_date']) : lang('n_a'); $this->cached_vars['entry_data'] = $entry_data; $this->cached_vars['field_output_data'] = $field_output_data; $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_entry' )); $this->cached_vars['form_id'] = $form_id; $this->cached_vars['entry_id'] = $entry_id; $this->cached_vars['statuses'] = $this->data->get_form_statuses(); // -------------------------------------------- // Load page // -------------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; $this->cached_vars['current_page'] = $this->view( 'edit_entry.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_entry // -------------------------------------------------------------------- /** * fields * * @access public * @param string message * @return string */ public function fields ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_field_link'] = $this->mod_link(array( 'method' => 'edit_field' )); $this->add_crumb( lang('fields') ); //optional $this->freeform_add_right_link(lang('new_field'), $this->cached_vars['new_field_link']); $this->set_highlight('module_fields'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $field_data = array(); $paginate_url = array('method' => 'fields'); ee()->load->model('freeform_field_model'); ee()->freeform_field_model->select( 'field_label, field_name, field_type, field_id, field_description' ); // ------------------------------------- // search? // ------------------------------------- $field_search = ''; $field_search_on = ''; $search = ee()->input->get_post('field_search', TRUE); if ($search) { $f_search_on = ee()->input->get_post('field_search_on'); if ($f_search_on == 'field_name') { ee()->freeform_field_model->like('field_name', $search); $field_search_on = 'field_name'; } else if ($f_search_on == 'field_label') { ee()->freeform_field_model->like('field_label', $search); $field_search_on = 'field_label'; } else if ($f_search_on == 'field_description') { ee()->freeform_field_model->like('field_description', $search); $field_search_on = 'field_description'; } else //if ($f_search_on == 'all') { ee()->freeform_field_model->like('field_name', $search); ee()->freeform_field_model->or_like('field_label', $search); ee()->freeform_field_model->or_like('field_description', $search); $field_search_on = 'all'; } $field_search = $search; $paginate_url['field_search'] = $search; $paginate_url['field_search_on'] = $field_search_on; } $this->cached_vars['field_search'] = $field_search; $this->cached_vars['field_search_on'] = $field_search_on; // ------------------------------------- // all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_field_model->where( 'site_id', ee()->config->item('site_id') ); } ee()->freeform_field_model->order_by('field_name', 'asc'); $total_results = ee()->freeform_field_model->count(array(), FALSE); $row_count = 0; // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $this->mod_link($paginate_url)), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->freeform_field_model->limit( $row_limit, $pagination_data['pagination_page'] ); } $query = ee()->freeform_field_model->get(); $count = $row_count; if ($query !== FALSE) { foreach ($query as $row) { $row['count'] = ++$count; $row['field_edit_link'] = $this->mod_link(array( 'method' => 'edit_field', 'field_id' => $row['field_id'] )); $row['field_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_field', 'duplicate_id' => $row['field_id'] )); $row['field_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_fields', 'field_id' => $row['field_id'] )); $field_data[] = $row; } } $this->cached_vars['field_data'] = $field_data; $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'field_data' => $field_data, 'paginate' => $paginate )); } // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_fields' )); // ------------------------------------- // js // ------------------------------------- ee()->cp->add_js_script(array( 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fields.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END fields // -------------------------------------------------------------------- /** * Edit Field * * @access public * @param bool $modal is this a modal version? * @return string */ public function edit_field ($modal = FALSE) { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); $modal = ( ! $modal AND $this->check_yes(ee()->input->get_post('modal'))) ? TRUE : $modal; $this->cached_vars['modal'] = $modal; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fields') , $this->base . AMP . 'method=fields'); $this->add_crumb( lang(($update ? 'update_field' : 'new_field')) ); //optional //$this->freeform_add_right_link(lang('home'), $this->base . AMP . 'method=some_method'); $this->set_highlight('module_fields'); // ------------------------------------- // default values // ------------------------------------- $inputs = array( 'field_id' => '0', 'field_name' => '', 'field_label' => '', 'field_order' => '0', 'field_type' => $this->data->defaults['field_type'], 'field_length' => $this->data->defaults['field_length'], 'field_description' => '', 'submissions_page' => 'y', 'moderation_page' => 'y', 'composer_use' => 'y', ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; $field_in_forms = array(); $incoming_settings = FALSE; if ($update) { $field_data = $this->data->get_field_info_by_id($field_id); if (empty($field_data)) { $this->actions()->full_stop(lang('invalid_field_id')); } foreach ($field_data as $key => $value) { $inputs[$key] = $value; } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_field_id($field_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $field_in_forms[] = $row['form_id']; $form_names[] = $row['form_label']; } $this->cached_vars['lang_field_edit_warning'] = lang('field_edit_warning'); $this->cached_vars['lang_field_edit_warning_desc'] = str_replace( '%form_names%', implode(', ', $form_names), lang('field_edit_warning_desc') ); } } $this->cached_vars['form_ids'] = implode('|', array_unique($field_in_forms)); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $duplicate = FALSE; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $field_data = $this->data->get_field_info_by_id($duplicate_id); if ($field_data) { $duplicate = TRUE; foreach ($field_data as $key => $value) { if (in_array($key, array('field_id', 'field_label', 'field_name'))) { continue; } $inputs[$key] = $value; } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $field_data['field_label']; } } // ------------------------------------- // get available field types // ------------------------------------- ee()->load->library('freeform_fields'); $this->cached_vars['fieldtypes'] = ee()->freeform_fields->get_available_fieldtypes(); // ------------------------------------- // get available forms to add this to // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } $this->cached_vars['available_forms'] = $this->prepare_keyed_result( ee()->db->get('freeform_forms'), 'form_id' ); // ------------------------------------- // add desc and lang for field types // ------------------------------------- foreach($this->cached_vars['fieldtypes'] as $fieldtype => $field_data) { //settings? $settings = ( ($update OR $duplicate ) AND $inputs['field_type'] == $fieldtype AND isset($inputs['settings']) ) ? json_decode($inputs['settings'], TRUE) : array(); //we are encoding this and decoding in JS because leaving the //fields intact while in storage in the html makes dupes of fields. //I could do some html moving around, but that would keep running //individual settings JS over and over again when it should //only be run on display. $this->cached_vars['fieldtypes'][$fieldtype]['settings_output'] = base64_encode( ee()->freeform_fields->fieldtype_display_settings_output( $fieldtype, $settings ) ); } if (isset($inputs['field_label'])) { $inputs['field_label'] = form_prep($inputs['field_label']); } if (isset($inputs['field_description'])) { $inputs['field_description'] = form_prep($inputs['field_description']); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_field' )); //---------------------------------------- // Load vars //---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_field' : 'create_field') ); $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['current_page'] = $this->view( 'edit_field.html', NULL, TRUE ); if ($modal) { exit($this->cached_vars['current_page']); } $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; return $this->ee_cp_view('index.html'); } //END edit_field // -------------------------------------------------------------------- /** * Field Types * * @access public * @param message * @return string */ public function fieldtypes ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fieldtypes') ); $this->set_highlight('module_fieldtypes'); //-------------------------------------- // start vars //-------------------------------------- $fieldtypes = array(); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); ee()->load->model('freeform_fieldtype_model'); if ( ( $installed_fieldtypes = ee()->freeform_fieldtype_model->installed_fieldtypes() ) === FALSE ) { $installed_fieldtypes = array(); } $fieldtypes = ee()->freeform_fields->get_installable_fieldtypes(); // ------------------------------------- // missing fieldtype folders? // ------------------------------------- $missing_fieldtypes = array(); foreach ($installed_fieldtypes as $name => $version) { if ( ! array_key_exists($name, $fieldtypes)) { $missing_fieldtypes[] = $name; } } // ------------------------------------- // add urls and crap // ------------------------------------- $action_url = $this->base . AMP . 'method=freeform_fieldtype_action'; foreach ($fieldtypes as $name => $data) { $fieldtypes[$name]['installed_lang'] = lang($data['installed'] ? 'installed' : 'not_installed'); $action = ($data['installed'] ? 'uninstall' : 'install'); $fieldtypes[$name]['action_lang'] = lang($action); $fieldtypes[$name]['action_url'] = $this->mod_link(array( 'method' => 'freeform_fieldtype_action', 'name' => $name, 'action' => $action, //some other time -gf //'folder' => base64_encode($data['folder']) )); } $this->cached_vars['fieldtypes'] = $fieldtypes; $this->cached_vars['freeform_ft_docs_url'] = $this->data->doc_links['custom_fields']; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fieldtypes.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END field_types // -------------------------------------------------------------------- /** * notifications * * @access public * @param string message to output * @return string outputted template */ public function notifications ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_notification_link'] = $this->mod_link(array( 'method' => 'edit_notification' )); $this->add_crumb( lang('notifications') ); $this->freeform_add_right_link( lang('new_notification'), $this->cached_vars['new_notification_link'] ); $this->set_highlight('module_notifications'); // ------------------------------------- // data // ------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $notification_data = array(); ee()->db->start_cache(); ee()->db->order_by('notification_name', 'asc'); if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } ee()->db->from('freeform_notification_templates'); ee()->db->stop_cache(); $total_results = ee()->db->count_all_results(); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'notifications' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->db->limit($row_limit, $pagination_data['pagination_page']); } $query = ee()->db->get(); ee()->db->flush_cache(); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { $row['notification_edit_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'notification_id' => $row['notification_id'], )); $row['notification_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'duplicate_id' => $row['notification_id'], )); $row['notification_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_notification', 'notification_id' => $row['notification_id'], )); $notification_data[] = $row; } } $this->cached_vars['notification_data'] = $notification_data; $this->cached_vars['paginate'] = $paginate; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_notification' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'notifications.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END notifications // -------------------------------------------------------------------- /** * edit_notification * * @access public * @return string */ public function edit_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb( lang('notifications'), $this->base . AMP . 'method=notifications' ); $this->add_crumb( lang(($update ? 'update_notification' : 'new_notification')) ); $this->set_highlight('module_notifications'); // ------------------------------------- // data items // ------------------------------------- $inputs = array( 'notification_id' => '0', 'notification_name' => '', 'notification_label' => '', 'notification_description' => '', 'wordwrap' => $this->data->defaults['wordwrap'], 'allow_html' => $this->data->defaults['allow_html'], 'from_name' => form_prep(ee()->config->item('webmaster_name')), 'from_email' => ee()->config->item('webmaster_email'), 'reply_to_email' => ee()->config->item('webmaster_email'), 'email_subject' => '', 'template_data' => '', 'include_attachments' => 'n' ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; if ($update) { $notification_data = $this->data->get_notification_info_by_id($notification_id); foreach ($notification_data as $key => $value) { $inputs[$key] = form_prep($value); } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_notification_id($notification_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $form_names[] = $row['form_label']; } $this->cached_vars['lang_notification_edit_warning'] = str_replace( '%form_names%', implode(', ', $form_names), lang('notification_edit_warning') ); } } // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $notification_data = $this->data->get_notification_info_by_id($duplicate_id); if ($notification_data) { foreach ($notification_data as $key => $value) { //TODO: remove other items that dont need to be duped? if (in_array($key, array( 'notification_id', 'notification_label', 'notification_name' ))) { continue; } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $notification_data['notification_label']; } } // ------------------------------------- // get available fields // ------------------------------------- ee()->load->model('freeform_field_model'); $this->cached_vars['available_fields'] = array(); if ( ( $fields = ee()->freeform_field_model->get() ) !== FALSE ) { $this->cached_vars['available_fields'] = $fields; } $this->cached_vars['standard_tags'] = $this->data->standard_notification_tags; // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->base . AMP . 'method=save_notification'; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_notification' : 'create_notification') ); $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_notification.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_notification // -------------------------------------------------------------------- /** * preferences * * @access public * @return string */ public function preferences ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('preferences')); $this->set_highlight('module_preferences'); // ------------------------------------- // global prefs // ------------------------------------- $this->cached_vars['msm_enabled'] = $msm_enabled = $this->data->msm_enabled; $is_admin = (ee()->session->userdata('group_id') == 1); $this->cached_vars['show_global_prefs'] = ($is_admin AND $msm_enabled); $global_pref_data = array(); $global_prefs = $this->data->get_global_module_preferences(); $default_global_prefs = array_keys($this->data->default_global_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $global_prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_global_prefs)) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_global_preferences[$key]['type']; $global_pref_data[] = $pref; } $this->cached_vars['global_pref_data'] = $global_pref_data; // ------------------------------------- // these two will only be used if MSM // is enabled, but setting them // anyway to avoid potential PHP errors // ------------------------------------- $prefs_all_sites = ! $this->check_no( $this->data->global_preference('prefs_all_sites') ); $this->cached_vars['lang_site_prefs_for_site'] = ( lang('site_prefs_for') . ' ' . ( ($prefs_all_sites) ? lang('all_sites') : ee()->config->item('site_label') ) ); //-------------------------------------- // per site prefs //-------------------------------------- $pref_data = array(); $prefs = $this->data->get_module_preferences(); $default_prefs = array_keys($this->data->default_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_prefs)) { continue; } //admin only pref? //MSM pref and no MSM? if ( (ee()->session->userdata('group_id') != 1 AND in_array($key, $this->data->admin_only_prefs)) OR ( ! $msm_enabled AND in_array($key, $this->data->msm_only_prefs)) ) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_preferences[$key]['type']; $pref_data[] = $pref; } $this->cached_vars['pref_data'] = $pref_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_preferences' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'preferences.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END preferences // -------------------------------------------------------------------- /** * delete confirm page abstractor * * @access private * @param string method you want to post data to after confirm * @param array all of the values you want to carry over to post * @param string the lang line of the warning message to display * @param string the lang line of the submit button for confirm * @param bool $message_use_lang use the lang wrapper for the message? * @return string */ private function delete_confirm ($method, $hidden_values, $message_line, $submit_line = 'delete', $message_use_lang = TRUE) { $this->cached_vars = array_merge($this->cached_vars, array( 'hidden_values' => $hidden_values, 'lang_message' => ($message_use_lang ? lang($message_line) : $message_line), 'lang_submit' => lang($submit_line), 'form_url' => $this->mod_link(array('method' => $method)) )); $this->cached_vars['current_page'] = $this->view( 'delete_confirm.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END delete_confirm //-------------------------------------------------------------------- // end views //-------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Clean up inputted paragraph html * * @access public * @param string $string string to clean * @return mixed string if html or json if not */ public function clean_paragraph_html ($string = '', $allow_ajax = TRUE) { if ( ! $string OR trim($string == '')) { $string = ee()->input->get_post('clean_string'); if ( $string === FALSE OR trim($string) === '') { $string = ''; } } $allowed_tags = '<' . implode('><', $this->data->allowed_html_tags) . '>'; $string = strip_tags($string, $allowed_tags); $string = ee()->security->xss_clean($string); return $string; } //END clean_paragraph_html // -------------------------------------------------------------------- /** * Fieldtype Actions * * this installs or uninstalles depending on the sent action * this will redirect no matter what * * @access public * @return null */ public function freeform_fieldtype_action () { $return_url = array('method' => 'fieldtypes'); $name = ee()->input->get_post('name', TRUE); $action = ee()->input->get_post('action'); if ($name AND $action) { ee()->load->library('freeform_fields'); if ($action === 'install') { if (ee()->freeform_fields->install_fieldtype($name)) { $return_url['msg'] = 'fieldtype_installed'; } else { return $this->actions()->full_stop(lang('fieldtype_install_error')); } } else if ($action === 'uninstall') { $uninstall = $this->uninstall_confirm_fieldtype($name); //if its not a boolean true, its a confirmation if ($uninstall !== TRUE) { return $uninstall; } else { $return_url['msg'] = 'fieldtype_uninstalled'; } } } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('fieldtype_uninstalled') )); } else { ee()->functions->redirect($this->mod_link($return_url)); } } //END freeform_fieldtype_action // -------------------------------------------------------------------- /** * save field layout * * ajax called method for saving field layout in the entries screen * * @access public * @return string */ public function save_field_layout () { ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); $save_for = ee()->input->get_post('save_for', TRUE); $shown_fields = ee()->input->get_post('shown_fields', TRUE); $form_id = $this->get_post_or_zero('form_id'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid // ------------------------------------- if ( ! $this->is_ajax_request() OR ! is_array($save_for) OR ! is_array($shown_fields) OR ! $form_data ) { return $this->send_ajax_response(array( 'success' => FALSE, 'message' => lang('invalid_input') )); } // ------------------------------------- // permissions? // ------------------------------------- //if (ee()->session->userdata('group_id') != 1 AND // ! $this->check_yes($this->preference('allow_user_field_layout')) //) //{ // return $this->send_ajax_response(array( // 'success' => FALSE, // 'message' => lang('invalid_permissions') // )); //} // ------------------------------------- // save // ------------------------------------- $field_layout_prefs = $this->preference('field_layout_prefs'); $original_prefs = ( is_array($field_layout_prefs) ? $field_layout_prefs : array() ); // ------------------------------------- // who is it for? // ------------------------------------- $for = array(); foreach ($save_for as $item) { //if this is for everyone, we can stop if (in_array($item, array('just_me', 'everyone'))) { $for = $item; break; } if ($this->is_positive_intlike($item)) { $for[] = $item; } } // ------------------------------------- // what do they want to see? // ------------------------------------- $standard_columns = $this->get_standard_column_names(); $possible_columns = $standard_columns; //build possible columns foreach ($form_data['fields'] as $field_id => $field_data) { $possible_columns[] = $field_id; } $data = array(); $prefix = ee()->freeform_form_model->form_field_prefix; //check for field validity, no funny business foreach ($shown_fields as $field_name) { $field_id = str_replace($prefix, '', $field_name); if (in_array($field_name, $standard_columns)) { $data[] = $field_name; unset( $possible_columns[ array_search( $field_name, $possible_columns ) ] ); } else if (in_array($field_id , array_keys($form_data['fields']))) { $data[] = $field_id; unset( $possible_columns[ array_search( $field_id, $possible_columns ) ] ); } } //removes holes sort($possible_columns); // ------------------------------------- // insert the data per group or all // ------------------------------------- $settings = array( 'visible' => $data, 'hidden' => $possible_columns ); if ($for == 'just_me') { $id = ee()->session->userdata('member_id'); $original_prefs['entry_layout_prefs']['member'][$id] = $settings; } else if ($for == 'everyone') { $original_prefs['entry_layout_prefs']['all']['visible'] = $settings; } else { foreach ($for as $who) { $original_prefs['entry_layout_prefs']['group'][$who]['visible'] = $settings; } } // ------------------------------------- // save // ------------------------------------- $this->data->set_module_preferences(array( 'field_layout_prefs' => json_encode($original_prefs) )); // ------------------------------------- // success! // ------------------------------------- //TODO test for ajax request or redirect back //don't want JS erorrs preventing this from //working $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('layout_saved'), 'update_fields' => array() )); //prevent EE CP default spit out exit(); } //END save_field_layout // -------------------------------------------------------------------- /** * save_form * * @access public * @return null */ public function save_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = ($form_id != 0); // ------------------------------------- // default status // ------------------------------------- $default_status = ee()->input->get_post('default_status', TRUE); $default_status = ($default_status AND trim($default_status) != '') ? $default_status : $this->data->defaults['default_form_status']; // ------------------------------------- // composer return? // ------------------------------------- $do_composer = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer'); $composer_save_finish = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer_save_finish'); if ($composer_save_finish) { $do_composer = TRUE; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $form_name = ee()->input->get_post('form_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $form_name OR ! trim($form_name)) { $errors['form_name'] = lang('form_name_required'); } else { $form_name = strtolower(trim($form_name)); if ( in_array($form_name, $this->data->prohibited_names ) ) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('reserved_form_name') ); } //if the form_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $form_name) OR is_numeric($form_name)) { $errors['form_name'] = lang('form_name_can_only_contain'); } ee()->load->model('freeform_form_model'); //get dupe from field names $dupe_data = ee()->freeform_form_model->get_row(array( 'form_name' => $form_name )); //if we are updating, we don't want to error on the same field id if ( ! empty($dupe_data) AND ! ($update AND $dupe_data['form_id'] == $form_id)) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('form_name_exists') ); } } // ------------------------------------- // form label // ------------------------------------- $form_label = ee()->input->get_post('form_label', TRUE); if ( ! $form_label OR ! trim($form_label) ) { $errors['form_label'] = lang('form_label_required'); } // ------------------------------------- // admin notification email // ------------------------------------- $admin_notification_email = ee()->input->get_post('admin_notification_email', TRUE); if ($admin_notification_email AND trim($admin_notification_email) != '') { ee()->load->helper('email'); $emails = preg_split( '/(\s+)?\,(\s+)?/', $admin_notification_email, -1, PREG_SPLIT_NO_EMPTY ); $errors['admin_notification_email'] = array(); foreach ($emails as $key => $email) { $emails[$key] = trim($email); if ( ! valid_email($email)) { $errors['admin_notification_email'][] = str_replace('%email%', $email, lang('non_valid_email')); } } if (empty($errors['admin_notification_email'])) { unset($errors['admin_notification_email']); } $admin_notification_email = implode('|', $emails); } else { $admin_notification_email = ''; } // ------------------------------------- // user email field // ------------------------------------- $user_email_field = ee()->input->get_post('user_email_field'); ee()->load->model('freeform_field_model'); $field_ids = ee()->freeform_field_model->key('field_id', 'field_id')->get(); if ($user_email_field AND $user_email_field !== '--' AND trim($user_email_field) !== '' AND ! in_array($user_email_field, $field_ids )) { $errors['user_email_field'] = lang('invalid_user_email_field'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // field ids // ------------------------------------- $field_ids = array_filter( $this->actions()->pipe_split( ee()->input->get_post('field_ids', TRUE) ), array($this, 'is_positive_intlike') ); $sorted_field_ids = $field_ids; sort($sorted_field_ids); // ------------------------------------- // insert data // ------------------------------------- $data = array( 'form_name' => strip_tags($form_name), 'form_label' => strip_tags($form_label), 'default_status' => $default_status, 'user_notification_id' => $this->get_post_or_zero('user_notification_id'), 'admin_notification_id' => $this->get_post_or_zero('admin_notification_id'), 'admin_notification_email' => $admin_notification_email, 'form_description' => strip_tags(ee()->input->get_post('form_description', TRUE)), 'author_id' => ee()->session->userdata('member_id'), 'field_ids' => implode('|', $sorted_field_ids), 'field_order' => implode('|', $field_ids), 'notify_admin' => ( (ee()->input->get_post('notify_admin') == 'y') ? 'y' : 'n' ), 'notify_user' => ( (ee()->input->get_post('notify_user') == 'y') ? 'y' : 'n' ), 'user_email_field' => $user_email_field, ); //load the forms model if its not been already ee()->load->library('freeform_forms'); if ($do_composer) { unset($data['field_ids']); unset($data['field_order']); } if ($update) { unset($data['author_id']); if ( ! $do_composer) { $data['composer_id'] = 0; } ee()->freeform_forms->update_form($form_id, $data); } else { //we don't want this running on update, will only happen for dupes $composer_id = $this->get_post_or_zero('composer_id'); //this is a dupe and they want composer to dupe too? if ($do_composer AND $composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer_data = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer_data !== FALSE) { $data['composer_id'] = ee()->freeform_composer_model->insert( array( 'composer_data' => $composer_data['composer_data'], 'site_id' => ee()->config->item('site_id') ) ); } } $form_id = ee()->freeform_forms->create_form($data); } // ------------------------------------- // return // ------------------------------------- if ( ! $composer_save_finish AND $do_composer) { ee()->functions->redirect($this->mod_link(array( 'method' => 'form_composer', 'form_id' => $form_id, 'msg' => 'edit_form_success' ))); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'forms', 'msg' => 'edit_form_success' ))); } } //END save_form // -------------------------------------------------------------------- /** * Save Entry * * @access public * @return null redirect */ public function save_entry () { // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); ee()->load->library('freeform_forms'); ee()->load->library('freeform_fields'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid form id // ------------------------------------- if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $previous_inputs = array(); if ( $entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ( ! $entry_data) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $previous_inputs = $entry_data; } // ------------------------------------- // form data // ------------------------------------- $field_labels = array(); $valid_fields = array(); foreach ( $form_data['fields'] as $row) { $field_labels[$row['field_name']] = $row['field_label']; $valid_fields[] = $row['field_name']; } // ------------------------------------- // is this an edit? entry_id // ------------------------------------- $edit = ($entry_id AND $entry_id != 0); // ------------------------------------- // for hooks // ------------------------------------- $this->edit = $edit; $this->multipage = FALSE; $this->last_page = TRUE; // ------------------------------------- // prevalidate hook // ------------------------------------- $errors = array(); //to assist backward compat $this->field_errors = array(); if (ee()->extensions->active_hook('freeform_module_validate_begin') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_begin', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } // ------------------------------------- // validate // ------------------------------------- $field_input_data = array(); $field_list = array(); // ------------------------------------- // status? // ------------------------------------- $available_statuses = $this->data->get_form_statuses(); $status = ee()->input->get_post('status'); if ( ! array_key_exists($status, $available_statuses)) { $field_input_data['status'] = $this->data->defaults['default_form_status']; } else { $field_input_data['status'] = $status; } foreach ($form_data['fields'] as $field_id => $field_data) { $field_list[$field_data['field_name']] = $field_data['field_label']; $field_post = ee()->input->get_post($field_data['field_name']); //if it's not even in $_POST or $_GET, lets skip input //unless its an uploaded file, then we'll send false anyway //because its fieldtype will handle the rest of that work if ($field_post !== FALSE OR isset($_FILES[$field_data['field_name']])) { $field_input_data[$field_data['field_name']] = $field_post; } } //form fields do thier own validation, //so lets just get results! (sexy results?) $this->field_errors = array_merge( $this->field_errors, ee()->freeform_fields->validate( $form_id, $field_input_data ) ); // ------------------------------------- // post validate hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_validate_end') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_end', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } $errors = array_merge($errors, $this->field_errors); // ------------------------------------- // halt on errors // ------------------------------------- if (count($errors) > 0) { $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_begin') === TRUE) { $backup_field_input_data = $field_input_data; $field_input_data = ee()->extensions->universal_call( 'freeform_module_insert_begin', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($field_input_data) AND $this->check_yes($this->preference('hook_data_protection'))) { $field_input_data = $backup_field_input_data; } } // ------------------------------------- // insert/update data into db // ------------------------------------- if ($edit) { ee()->freeform_forms->update_entry( $form_id, $entry_id, $field_input_data ); } else { $entry_id = ee()->freeform_forms->insert_new_entry( $form_id, $field_input_data ); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_end') === TRUE) { ee()->extensions->universal_call( 'freeform_module_insert_end', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; } // ------------------------------------- // return // ------------------------------------- $success_line = ($edit) ? 'edit_entry_success' : 'new_entry_success'; if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'form_id' => $form_id, 'entry_id' => $entry_id, 'message' => lang($success_line), 'success' => TRUE )); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id, 'msg' => $success_line ))); } } //END edit_entry // -------------------------------------------------------------------- /** * approve entries * * accepts ajax call to approve entries * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to approve * @return string */ public function approve_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } // ------------------------------------- // approve! // ------------------------------------- $updates = array(); foreach($entry_ids as $entry_id) { $updates[] = array( 'entry_id' => $entry_id, 'status' => 'open' ); } ee()->load->model('freeform_form_model'); ee()->db->update_batch( ee()->freeform_form_model->table_name($form_id), $updates, 'entry_id' ); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); exit(); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'moderate_entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_approved' ))); } } //END approve_entry // -------------------------------------------------------------------- /** * get/post form_id * * gets and validates the current form_id possibly passed * * @access private * @param bool validate form_id * @return mixed integer of passed in form_id or bool false */ private function get_post_form_id ($validate = TRUE) { $form_id = $this->get_post_or_zero('form_id'); if ($form_id == 0 OR ($validate AND ! $this->data->is_valid_form_id($form_id)) ) { return FALSE; } return $form_id; } //ENd get_post_form_id // -------------------------------------------------------------------- /** * get/post entry_ids * * gets and validates the current entry possibly passed * * @access private * @return mixed array of passed in entry_ids or bool false */ private function get_post_entry_ids () { $entry_ids = ee()->input->get_post('entry_ids'); if ( ! is_array($entry_ids) AND ! $this->is_positive_intlike($entry_ids)) { return FALSE; } if ( ! is_array($entry_ids)) { $entry_ids = array($entry_ids); } //clean and validate each as int $entry_ids = array_filter($entry_ids, array($this, 'is_positive_intlike')); if (empty($entry_ids)) { return FALSE; } return $entry_ids; } //END get_post_entry_ids // -------------------------------------------------------------------- /** * delete_confirm_entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_confirm_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_entries(); } // ------------------------------------- // form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->show_error(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->show_error(lang('invalid_entry_id')); } // ------------------------------------- // return method? // ------------------------------------- $return_method = ee()->input->get_post('return_method'); $return_method = ($return_method AND is_callable(array($this, $return_method))) ? $return_method : 'entries'; // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_entries', array( 'form_id' => $form_id, 'entry_ids' => $entry_ids, 'return_method' => $return_method ), 'confirm_delete_entries' ); } //END delete_confirm_entries // -------------------------------------------------------------------- /** * delete entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $this->is_positive_intlike($form_id)) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } ee()->load->library('freeform_forms'); $success = ee()->freeform_forms->delete_entries($form_id, $entry_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_deleted' ))); } } //END delete_entries // -------------------------------------------------------------------- /** * Confirm Delete Fields * * @access public * @return html */ public function delete_confirm_fields () { //the following fields will be deleted //the following forms will be affected //they contain the forms.. $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } $delete_field_confirmation = ''; $clean_field_ids = array(); foreach ($field_ids as $field_id) { if ($this->is_positive_intlike($field_id)) { $clean_field_ids[] = $field_id; } } if (empty($clean_field_ids)) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } // ------------------------------------- // build a list of forms affected by fields // ------------------------------------- ee()->db->where_in('field_id', $clean_field_ids); $all_field_data = ee()->db->get('freeform_fields'); $delete_field_confirmation = lang('delete_field_confirmation'); $extra_form_data = ''; foreach ($all_field_data->result_array() as $row) { //this doesn't get field data, so we had to above; $field_form_data = $this->data->get_form_info_by_field_id($row['field_id']); // ------------------------------------- // get each form affected by each field listed // and show the user what forms will be affected // ------------------------------------- if ( $field_form_data !== FALSE ) { $freeform_affected = array(); foreach ($field_form_data as $form_id => $form_data) { $freeform_affected[] = $form_data['form_label']; } $extra_form_data .= '<p>' . '<strong>' . $row['field_label'] . '</strong>: ' . implode(', ', $freeform_affected) . '</p>'; } } //if we have anything, add some extra warnings if ($extra_form_data != '') { $delete_field_confirmation .= '<p>' . lang('freeform_will_lose_data') . '</p>' . $extra_form_data; } return $this->delete_confirm( 'delete_fields', array('field_id' => $clean_field_ids), $delete_field_confirmation, 'delete', FALSE ); } //END delete_confirm_fields // -------------------------------------------------------------------- /** * utilities * * @access public * @return string */ public function utilities ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Counts //-------------------------------------- ee()->load->library('freeform_migration'); $this->cached_vars['counts'] = ee()->freeform_migration->get_collection_counts(); // $test = ee()->freeform_migration->create_upload_field( 1, 'goff', array( 'file_upload_location' => '1' ) ); // print_r( $test ); print_r( ee()->freeform_migration->get_errors() ); //-------------------------------------- // File upload field installed? //-------------------------------------- $this->cached_vars['file_upload_installed'] = ee()->freeform_migration->get_field_type_installed('file_upload'); $query = ee()->db->query( "SELECT * FROM exp_freeform_fields WHERE field_type = 'file_upload'" ); //-------------------------------------- // Load vars //-------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'migrate_collections' )); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'utilities.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End utilities // -------------------------------------------------------------------- /** * Confirm Uninstall Fieldtypes * * @access public * @return html */ public function uninstall_confirm_fieldtype ($name = '') { $name = trim($name); if ($name == '') { ee()->functions->redirect($this->base); } ee()->load->model('freeform_field_model'); $items = ee()->freeform_field_model ->key('field_label', 'field_label') ->get(array('field_type' => $name)); if ($items == FALSE) { return $this->uninstall_fieldtype($name); } else { $confirmation = '<p>' . lang('following_fields_converted') . ': <strong>'; $confirmation .= implode(', ', $items) . '</strong></p>'; return $this->delete_confirm( 'uninstall_fieldtype', array('fieldtype' => $name), $confirmation, 'uninstall', FALSE ); } } //END uninstall_confirm_fieldtype // -------------------------------------------------------------------- /** * Uninstalls fieldtypes * * @access public * @param string $name fieldtype name to remove * @return void */ public function uninstall_fieldtype ($name = '', $redirect = TRUE) { if ($name == '') { $name = ee()->input->get_post('fieldtype', TRUE); } if ( ! $name) { $this->actions()->full_stop(lang('no_fieldtypes_submitted')); } ee()->load->library('freeform_fields'); $success = ee()->freeform_fields->uninstall_fieldtype($name); if ( ! $redirect) { return $success; } if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success, 'message' => lang('fieldtype_uninstalled'), )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fieldtypes', 'msg' => 'fieldtype_uninstalled' ))); } } //END uninstall_fieldtype // -------------------------------------------------------------------- /** * Delete Fields * * @access public * @return void */ public function delete_fields () { // ------------------------------------- // safety goggles // ------------------------------------- // $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } // ------------------------------------- // delete fields // ------------------------------------- ee()->load->library('freeform_fields'); ee()->freeform_fields->delete_field($field_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'fields_deleted' ))); } } //END delete_fields // -------------------------------------------------------------------- /** * Confirm deletion of notifications * * accepts ajax call to delete notification * * @access public * @param int form id * @param mixed array or int of notification ids to delete * @return string */ public function delete_confirm_notification ($notification_id = 0) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_notification(); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_notification', array( 'notification_id' => $notification_id, 'return_method' => 'notifications' ), 'confirm_delete_notification' ); } //END delete_confirm_notification // -------------------------------------------------------------------- /** * Delete Notifications * * @access public * @param integer $notification_id notification * @return null */ public function delete_notification ($notification_id = 0) { // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } ee()->load->model('freeform_notification_model'); $success = ee()->freeform_notification_model ->where_in('notification_id', $notification_id) ->delete(); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'notifications'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'msg' => 'delete_notification_success' ))); } } //END delete_notification // -------------------------------------------------------------------- /** * save_field * * @access public * @return void (redirect) */ public function save_field () { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); // ------------------------------------- // yes or no items (all default yes) // ------------------------------------- $y_or_n = array('submissions_page', 'moderation_page', 'composer_use'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // field instance // ------------------------------------- $field_type = ee()->input->get_post('field_type', TRUE); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); $available_fieldtypes = ee()->freeform_fields->get_available_fieldtypes(); //get the update with previous settings if this is an edit if ($update) { $field = ee()->freeform_field_model ->where('field_id', $field_id) ->where('field_type', $field_type) ->count(); //make sure that we have the correct type just in case they //are changing type like hooligans if ($field) { $field_instance =& ee()->freeform_fields->get_field_instance($field_id); } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $field_name = ee()->input->get_post('field_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $field_name OR ! trim($field_name)) { $errors['field_name'] = lang('field_name_required'); } else { $field_name = strtolower(trim($field_name)); if ( in_array($field_name, $this->data->prohibited_names ) ) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('freeform_reserved_field_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $field_name) OR is_numeric($field_name)) { $errors['field_name'] = lang('field_name_can_only_contain'); } //get dupe from field names $f_query = ee()->db->select('field_name, field_id')->get_where( 'freeform_fields', array('field_name' => $field_name) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('field_id') == $field_id)) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('field_name_exists') ); } } // ------------------------------------- // field label // ------------------------------------- $field_label = ee()->input->get_post('field_label', TRUE); if ( ! $field_label OR ! trim($field_label) ) { $errors['field_label'] = lang('field_label_required'); } // ------------------------------------- // field type // ------------------------------------- if ( ! $field_type OR ! array_key_exists($field_type, $available_fieldtypes)) { $errors['field_type'] = lang('invalid_fieldtype'); } // ------------------------------------- // field settings errors? // ------------------------------------- $field_settings_validate = $field_instance->validate_settings(); if ( $field_settings_validate !== TRUE) { if (is_array($field_settings_validate)) { $errors['field_settings'] = $field_settings_validate; } else if (! empty($field_instance->errors)) { $errors['field_settings'] = $field_instance->errors; } else { $errors['field_settings'] = lang('field_settings_error'); } } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } if ($this->check_yes(ee()->input->get_post('validate_only')) AND $this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'field_name' => strip_tags($field_name), 'field_label' => strip_tags($field_label), 'field_type' => $field_type, 'edit_date' => '0', //overridden if update 'field_description' => strip_tags(ee()->input->get_post('field_description', TRUE)), 'submissions_page' => $submissions_page, 'moderation_page' => $moderation_page, 'composer_use' => $composer_use, 'settings' => json_encode($field_instance->save_settings()) ); if ($update) { ee()->freeform_field_model->update( array_merge( $data, array( 'edit_date' => ee()->localize->now ) ), array('field_id' => $field_id) ); } else { $field_id = ee()->freeform_field_model->insert( array_merge( $data, array( 'author_id' => ee()->session->userdata('member_id'), 'entry_date' => ee()->localize->now, 'site_id' => ee()->config->item('site_id') ) ) ); } $field_instance->field_id = $field_id; $field_instance->post_save_settings(); $field_in_forms = array(); if ($update) { $field_in_forms = $this->data->get_form_info_by_field_id($field_id); if ($field_in_forms) { $field_in_forms = array_keys($field_in_forms); } else { $field_in_forms = array(); } } $form_ids = ee()->input->get_post('form_ids'); if ($form_ids !== FALSE) { $form_ids = preg_split( '/\|/', $form_ids, -1, PREG_SPLIT_NO_EMPTY ); } else { $form_ids = array(); } if ( ! (empty($form_ids) AND empty($field_in_forms))) { $remove = array_unique(array_diff($field_in_forms, $form_ids)); $add = array_unique(array_diff($form_ids, $field_in_forms)); ee()->load->library('freeform_forms'); foreach ($add as $add_id) { ee()->freeform_forms->add_field_to_form($add_id, $field_id); } foreach ($remove as $remove_id) { ee()->freeform_forms->remove_field_from_form($remove_id, $field_id); } } // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $return = array( 'success' => TRUE, 'field_id' => $field_id, ); if ($this->check_yes(ee()->input->get_post('include_field_data'))) { $return['composerFieldData'] = $this->composer_field_data($field_id, NULL, TRUE); } $this->send_ajax_response($return); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'edit_field_success' ))); } } //END save_field // -------------------------------------------------------------------- /** * save_notification * * @access public * @return null (redirect) */ public function save_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); // ------------------------------------- // yes or no items (default yes) // ------------------------------------- $y_or_n = array('wordwrap'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // yes or no items (default no) // ------------------------------------- $n_or_y = array('allow_html', 'include_attachments'); foreach ($n_or_y as $item) { //set as local var $$item = $this->check_yes(ee()->input->get_post($item)) ? 'y' : 'n'; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // notification name // ------------------------------------- $notification_name = ee()->input->get_post('notification_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $notification_name OR ! trim($notification_name)) { $errors['notification_name'] = lang('notification_name_required'); } else { $notification_name = strtolower(trim($notification_name)); if ( in_array($notification_name, $this->data->prohibited_names ) ) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('reserved_notification_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $notification_name) OR is_numeric($notification_name)) { $errors['notification_name'] = lang('notification_name_can_only_contain'); } //get dupe from field names ee()->db->select('notification_name, notification_id'); $f_query = ee()->db->get_where( 'freeform_notification_templates', array( 'notification_name' => $notification_name ) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('notification_id') == $notification_id)) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('notification_name_exists') ); } } // ------------------------------------- // notification label // ------------------------------------- $notification_label = ee()->input->get_post('notification_label', TRUE); if ( ! $notification_label OR ! trim($notification_label) ) { $errors['notification_label'] = lang('notification_label_required'); } ee()->load->helper('email'); // ------------------------------------- // notification email // ------------------------------------- $from_email = ee()->input->get_post('from_email', TRUE); if ($from_email AND trim($from_email) != '') { $from_email = trim($from_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $from_email)) { if ( ! valid_email($from_email)) { $errors['from_email'] = str_replace( '%email%', $from_email, lang('non_valid_email') ); } } } // ------------------------------------- // from name // ------------------------------------- $from_name = ee()->input->get_post('from_name', TRUE); if ( ! $from_name OR ! trim($from_name) ) { //$errors['from_name'] = lang('from_name_required'); } // ------------------------------------- // reply to email // ------------------------------------- $reply_to_email = ee()->input->get_post('reply_to_email', TRUE); if ($reply_to_email AND trim($reply_to_email) != '') { $reply_to_email = trim($reply_to_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $reply_to_email)) { if ( ! valid_email($reply_to_email)) { $errors['reply_to_email'] = str_replace( '%email%', $reply_to_email, lang('non_valid_email') ); } } } else { $reply_to_email = ''; } // ------------------------------------- // email subject // ------------------------------------- $email_subject = ee()->input->get_post('email_subject', TRUE); if ( ! $email_subject OR ! trim($email_subject) ) { $errors['email_subject'] = lang('email_subject_required'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //ajax checking? else if ($this->check_yes(ee()->input->get_post('validate_only'))) { return $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'notification_name' => strip_tags($notification_name), 'notification_label' => strip_tags($notification_label), 'notification_description' => strip_tags(ee()->input->get_post('notification_description', TRUE)), 'wordwrap' => $wordwrap, 'allow_html' => $allow_html, 'from_name' => $from_name, 'from_email' => $from_email, 'reply_to_email' => $reply_to_email, 'email_subject' => strip_tags($email_subject), 'template_data' => ee()->input->get_post('template_data'), 'include_attachments' => $include_attachments ); ee()->load->model('freeform_notification_model'); if ($update) { ee()->freeform_notification_model->update( $data, array('notification_id' => $notification_id) ); } else { $notification_id = ee()->freeform_notification_model->insert( array_merge( $data, array( 'site_id' => ee()->config->item('site_id') ) ) ); } // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'notification_id' => $notification_id )); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'notifications', 'msg' => 'edit_notification_success' ))); } } //END save_notification // -------------------------------------------------------------------- /** * Sets the menu highlight and assists with permissions (Freeform Pro) * * @access protected * @param string $menu_item The menu item to highlight */ protected function set_highlight($menu_item = 'module_forms') { $this->cached_vars['module_menu_highlight'] = $menu_item; } //END set_highlight // -------------------------------------------------------------------- /** * save_preferences * * @access public * @return null (redirect) */ public function save_preferences() { //defaults are in data.freeform.php $prefs = array(); $all_prefs = array_merge( $this->data->default_preferences, $this->data->default_global_preferences ); //check post input for all existing prefs and default if not present foreach($all_prefs as $pref_name => $data) { $input = ee()->input->get_post($pref_name, TRUE); //default $output = $data['value']; //int if ($data['type'] == 'int' AND $this->is_positive_intlike($input, -1)) { $output = $input; } //yes or no elseif ($data['type'] == 'y_or_n' AND in_array(trim($input), array('y', 'n'), TRUE)) { $output = trim($input); } //list of items //this seems nutty, but this serializes the list of items elseif ($data['type'] == 'list') { //lotses? if (is_array($input)) { $temp_input = array(); foreach ($input as $key => $value) { if (trim($value) !== '') { $temp_input[] = trim($value); } } $output = json_encode($temp_input); } //just one :/ else if (trim($input) !== '') { $output = json_encode(array(trim($input))); } } //text areas elseif ($data['type'] == 'text' OR $data['type'] == 'textarea' ) { $output = trim($input); } $prefs[$pref_name] = $output; } //send all prefs to DB $this->data->set_module_preferences($prefs); // ---------------------------------- // Redirect to Homepage with Message // ---------------------------------- ee()->functions->redirect( $this->base . AMP . 'method=preferences' . AMP . 'msg=preferences_updated' ); } //END save_preferences // -------------------------------------------------------------------- /** * Export Entries * * Calls entries with proper flags to cue export * * @access public * @return mixed forces a download of the exported items or error */ public function export_entries () { $moderate = (ee()->input->get_post('moderate') == 'true'); return $this->entries(NULL, $moderate, TRUE); } //END export_entries // -------------------------------------------------------------------- /** * get_standard_column_names * * gets the standard column names and replaces author_id with author * * @access private * @return null */ private function get_standard_column_names() { $standard_columns = array_keys( ee()->freeform_form_model->default_form_table_columns ); array_splice( $standard_columns, array_search('author_id', $standard_columns), 1, 'author' ); return $standard_columns; } //END get_standard_column_names // -------------------------------------------------------------------- /** * mod_link * * makes $this->base . AMP . 'key=value' out of arrays * * @access public * @param array key value pair of get vars to add to base * @param bool $real_amp use a real ampersand? * @return string */ private function mod_link ($vars = array(), $real_amp = FALSE) { $link = $this->base; $amp = $real_amp ? '&' : AMP; if ($real_amp) { $link = str_replace(AMP, '&', $link); } else { //Swap all to regular amp first so we don't get false //positives. Could do this with negative lookups, but //those are spottier than this. $link = str_replace('&', AMP, str_replace(AMP, '&', $link)); } if ( ! empty($vars)) { foreach ($vars as $key => $value) { $link .= $amp . $key . '=' . $value; } } return $link; } //END mod_link // -------------------------------------------------------------------- /** * load_fancybox * * loads fancybox jquery UI plugin and its needed css * * @access private * @return null */ private function load_fancybox() { //so currently the fancybox setup inlucded in EE doesn't get built //automaticly and requires relying on the current CP theme. //Dislike. Inlcuding our own version instead. //Seems fancy box has also been removed from some later versions //of EE, so instinct here was correct. $css_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.css'; $js_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.pack.js'; ee()->cp->add_to_head('<link href="' . $css_link . '" type="text/css" rel="stylesheet" media="screen" />'); ee()->cp->add_to_foot('<script src="' . $js_link . '" type="text/javascript"></script>'); } //END load_fancybox // -------------------------------------------------------------------- /** * freeform_add_right_link * * abstractor for cp add_right_link so freeform can move it how it needs * when an alternate style is chosen * * @access private * @param string words of link to display * @param string link to display * @return null */ private function freeform_add_right_link ($lang, $link) { $this->cached_vars['inner_nav_links'][$lang] = $link; //return $this->add_right_link($lang, $link); } //END freeform_add_right_link // -------------------------------------------------------------------- /** * Module Upgrading * * This function is not required by the 1.x branch of ExpressionEngine by default. However, * as the install and deinstall ones are, we are just going to keep the habit and include it * anyhow. * - Originally, the $current variable was going to be passed via parameter, but as there might * be a further use for such a variable throughout the module at a later date we made it * a class variable. * * * @access public * @return bool */ public function freeform_module_update() { if ( ! isset($_POST['run_update']) OR $_POST['run_update'] != 'y') { $this->add_crumb(lang('update_freeform_module')); $this->build_crumbs(); $this->cached_vars['form_url'] = $this->base . '&msg=update_successful'; if ($this->pro_update) { $this->cached_vars['form_url'] .= "&update_pro=true"; } $this->cached_vars['current_page'] = $this->view( 'update_module.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } require_once $this->addon_path . 'upd.freeform.php'; $U = new Freeform_upd(); if ($U->update() !== TRUE) { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_failure') ))); } else { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_successful') ))); } } // END freeform_module_update() // -------------------------------------------------------------------- /** * Visible Columns * * @access protected * @param $possible_columns possible columns * @return array array of visible columns */ protected function visible_columns ($standard_columns = array(), $possible_columns = array()) { // ------------------------------------- // get column settings // ------------------------------------- $column_settings = array(); ee()->load->model('freeform_form_model'); $field_layout_prefs = $this->preference('field_layout_prefs'); $member_id = ee()->session->userdata('member_id'); $group_id = ee()->session->userdata('group_id'); $f_prefix = ee()->freeform_form_model->form_field_prefix; //¿existe? Member? Group? all? if ($field_layout_prefs) { //$field_layout_prefs = json_decode($field_layout_prefs, TRUE); $entry_layout_prefs = ( isset($field_layout_prefs['entry_layout_prefs']) ? $field_layout_prefs['entry_layout_prefs'] : FALSE ); if ($entry_layout_prefs) { if (isset($entry_layout_prefs['member'][$member_id])) { $column_settings = $entry_layout_prefs['member'][$member_id]; } else if (isset($entry_layout_prefs['all'])) { $column_settings = $entry_layout_prefs['all']; } else if (isset($entry_layout_prefs['group'][$group_id])) { $column_settings = $entry_layout_prefs['group'][$group_id]; } } } //if a column is missing, we don't want to error //and if its newer than the settings, show it by default //settings are also in order of appearence here. //we also store the field ids without the prefix //in case someone changed it. That would probably //hose everything, but who knows? ;) if ( ! empty($column_settings)) { $to_sort = array(); //we are going over possible instead of settings in case something //is new or an old column is missing foreach ($possible_columns as $cid) { //if these are new, put them at the end if (! in_array($cid, $column_settings['visible']) AND ! in_array($cid, $column_settings['hidden']) ) { $to_sort[$cid] = $cid; } } //now we want columns from the settings order to go first //this way stuff thats not been removed gets to keep settings foreach ($column_settings['visible'] as $ecid) { if (in_array($ecid, $possible_columns)) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($ecid, $standard_columns) ) { $ecid = $f_prefix . $ecid; } $visible_columns[] = $ecid; } } //and if we have anything left over (new fields probably) //its at the end if (! empty($to_sort)) { foreach ($to_sort as $tsid) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($tsid, $standard_columns) ) { $tsid = $f_prefix . $tsid; } $visible_columns[] = $tsid; } } } //if we don't have any settings, just toss it all in in order else { foreach ($possible_columns as $pcid) { if ( ! in_array($pcid, $standard_columns) ) { $pcid = $f_prefix . $pcid; } $visible_columns[] = $pcid; } //in theory it should always be there if prefs are empty ... $default_hide = array('site_id', 'entry_id', 'complete'); foreach ($default_hide as $hide_me_seymour) { if (in_array($hide_me_seymour, $visible_columns)) { unset( $visible_columns[ array_search( $hide_me_seymour, $visible_columns ) ] ); } } //fix keys, but preserve order $visible_columns = array_merge(array(), $visible_columns); } return $visible_columns; } //END visible_columns // -------------------------------------------------------------------- /** * Format CP date * * @access public * @param mixed $date unix time * @return string unit time formatted to cp date formatting pref */ public function format_cp_date($date) { return $this->actions()->format_cp_date($date); } //END format_cp_date // -------------------------------------------------------------------- /** * Send AJAX response * * Outputs and exit either an HTML string or a * JSON array with the Profile disabled and correct * headers sent. * * @access public * @param string|array String is sent as HTML, Array is sent as JSON * @param bool Is this an error message? * @param bool bust cache for JSON? * @return void */ public function send_ajax_response($msg, $error = FALSE, $cache_bust = TRUE) { $this->restore_xid(); parent::send_ajax_response($msg, $error, $cache_bust); } //END send_ajax_response // -------------------------------------------------------------------- /** * EE 2.7+ restore xid with version check * @access public * @return voic */ public function restore_xid() { //deprecated in 2.8. Weeee! if (version_compare($this->ee_version, '2.7', '>=') && version_compare($this->ee_version, '2.8', '<')) { ee()->security->restore_xid(); } } //END restore_xid } // END CLASS Freeform
cfox89/EE-Integration-to-API
system/expressionengine/third_party/freeform/mcp.freeform.php
PHP
mit
159,782
<!DOCTYPE html><html><head><meta charset=utf-8><meta itemprop=name content=ESS_在线考试系统><meta name=keywords content="在线考试, 随机试题"><meta name=description content="在线考试系统, 支持随机生成试题, 随机选项, 在线考试"><meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"><link rel=icon href=./logo.png><link href=/static/css/app.78dc4afeba3d5b1ec39077e72921911d.css rel=stylesheet></head><body><div id=app></div><script type=text/javascript src=/static/js/manifest.56aba6cf9a8f01b185dd.js></script><script type=text/javascript src=/static/js/vendor.e209ba326b65a769a57a.js></script><script type=text/javascript src=/static/js/app.534dfddb4177c561540f.js></script></body><script src=//at.alicdn.com/t/font_455702_omc7om53zyk138fr.js></script></html>
bedisdover/ESS
application/web/index.html
HTML
mit
835
/* exported Qualifications */ function Qualifications(skills, items) { var requirements = { 'soldier': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 3 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 3 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.flakArmor, level: 3 }, { skill: skills.engineer.nanoArmorKit, level: 4 }, { skill: skills.engineer.tankMine, level: 1 } ], equipment: [] }, 'Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 3 }, { skill: skills.medic.medicalApplicator, level: 4 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.advancedMobileStation, level: 1 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 0 } ], equipment: [] } } }, 'veteran': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 1 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.c4, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 2 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.nanoArmorKit, level: 6 }, { skill: skills.engineer.claymoreMine, level: 2 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.ammunitionPackage, level: 3 }, { skill: skills.engineer.stickyGrenade, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] }, 'Medic': { certifications: [ { skill: skills.medic.medicalApplicator, level: 6 }, { skill: skills.medic.nanoRegenDevice, level: 6 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.advancedEquipmentTerminalHacking, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.blockadeArmor, level: 3 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 2 } ], equipment: [] } } }, 'medic': { meta: { passPercentage: 100 }, classes: { 'Loadout: Offensive Medic': { certifications: [ { skill: skills.medic.grenadeBandolier, level: 2 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.nanoRegenDevice, level: 6 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] }, 'Loadout: Defensive Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 4 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.regenerationField, level: 5 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] } } }, 'engineer': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.claymoreMine, level: 2 } ], equipment: [ items.weapon.trac5s ] }, 'Loadout: Anti-Vehicle MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.avManaTurret, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] } } }, 'lightAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Bounty Hunter': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 4 }, { skill: skills.lightAssault.jumpJets, level: 6 }, { skill: skills.lightAssault.flashGrenade, level: 1 } ], equipment: [] }, 'Loadout: Death From Above': { certifications: [ { skill: skills.lightAssault.grenadeBandolier, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 5 }, { skill: skills.lightAssault.smokeGrenade, level: 1 } ], equipment: [] } } }, 'infiltrator': { meta: { passPercentage: 100 }, classes: { 'Loadout: Close Quarters': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 4 }, { skill: skills.infiltrator.grenadeBandolier, level: 2 }, { skill: skills.infiltrator.reconDetectDevice, level: 6 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.empGrenade, level: 1 } ], equipment: [ items.weapon.ns7pdw ] }, 'Loadout: Assassin': { certifications: [ { skill: skills.infiltrator.ammunitionBelt, level: 3 }, { skill: skills.infiltrator.motionSpotter, level: 5 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.decoyGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.rams ] } } }, 'heavyAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.heavyAssault.grenadeBandolier, level: 2 }, { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.concussionGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.decimator ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.c4, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 } ], equipment: [ items.weapon.skep, items.weapon.grounder ] } } }, 'maxUnit': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftMercy, items.max.rightMercy ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftPounder, items.max.rightPounder ] }, 'Loadout: Anti-Air': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftBurster, items.max.rightBurster ] } } }, 'basicTanks': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 1 } ], equipment: [ items.prowler.walker ] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] } } }, 'sunderer': { meta: { passPercentage: 100 }, classes: { 'Sunderer': { certifications: [ { skill: skills.sunderer.mineGuard, level: 4 }, { skill: skills.sunderer.blockadeArmor, level: 4 }, { skill: skills.sunderer.gateShieldDiffuser, level: 3 }, { skill: skills.sunderer.naniteProximityRepairSystem, level: 6 } ], equipment: [] } } }, 'prowler': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 4 }, { skill: skills.prowler.mineGuard, level: 4 } ], equipment: [ items.prowler.p2120ap, items.prowler.halberd ] } } }, 'lightning': { meta: { passPercentage: 100 }, classes: { 'Lightning': { certifications: [ { skill: skills.lightning.reinforcedTopArmor, level: 1 } ], equipment: [ items.lightning.skyguard ] } } }, 'harasser': { meta: { passPercentage: 100 }, classes: { 'Harasser': { certifications: [ { skill: skills.harasser.fireSuppressionSystem, level: 4 }, { skill: skills.harasser.compositeArmor, level: 4 }, { skill: skills.harasser.turbo, level: 5 } ], equipment: [ items.harasser.halberd ] } } }, 'commander': { meta: { passPercentage: 100 }, classes: { 'Squad Leader': { certifications: [ { skill: skills.squadLeader.commandCommChannel, level: 1 }, { skill: skills.squadLeader.requestReinforcements, level: 1 }, { skill: skills.squadLeader.rallyPointGreen, level: 1 }, { skill: skills.squadLeader.rallyPointOrange, level: 1 }, { skill: skills.squadLeader.rallyPointPurple, level: 1 }, { skill: skills.squadLeader.rallyPointYellow, level: 1 }, { skill: skills.squadLeader.priorityDeployment, level: 4 } ], equipment: [] } } } }, echoHavoc = qual('Echo Havoc', null, null, true), max = qual('MAX', echoHavoc, requirements.maxUnit), heavyAssault = qual('Heavy Assault', max, requirements.heavyAssault), echoCovertOps = qual('Echo Covert Ops', null, null, true), infiltrator = qual('Infiltrator', echoCovertOps, requirements.infiltrator), lightAssault = qual('Light Assault', infiltrator, requirements.lightAssault), echoSpecialist = qual('Echo Specialist', null, null, true), engineer = qual('Engineer', echoSpecialist, requirements.engineer), combatMedic = qual('Combat Medic', engineer, requirements.medic), commander = qual('Commander', null, requirements.commander, true), sunderer = qual('Sunderer', [ echoSpecialist, echoCovertOps, echoHavoc ], requirements.sunderer), harasser = qual('Harasser', null, requirements.harasser), lightning = qual('Lightning', harasser, requirements.lightning), prowler = qual('Prowler', lightning, requirements.prowler), basicTanks = qual('Basic Tanks', [ sunderer, prowler ], requirements.basicTanks), veteran = qual('Veteran', [ combatMedic, lightAssault, heavyAssault, commander ], requirements.veteran, true), soldier = qual('Soldier', [ veteran, basicTanks ], requirements.soldier, true); addParentRelationships(soldier); return soldier; function qual(name, child, certs, isRank) { var obj = {}; obj.name = name; if (child) { if ($.isArray(child)) { obj.child = child; } else { obj.child = [ child ]; } } if (certs) { obj.cert = certs; } if (isRank) { obj.isRank = true; } return obj; } function addParentRelationships(rank, parent) { if (parent) { if (rank.parent) { rank.parent.push(parent); } else { rank.parent = [ parent ]; } } if (rank.child) { $.each(rank.child, function() { addParentRelationships(this, rank); }); } } }
stevenbenner/ps2-equipment-check
js/qualifications.js
JavaScript
mit
12,343
package addonloader.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * Simple wrapper around {@link Properites}, * allowing to easily access objects. * @author Enginecrafter77 */ public class ObjectSettings extends Properties{ private static final long serialVersionUID = -8939834947658913650L; private final File path; public ObjectSettings(File path) throws FileNotFoundException, IOException { this.path = path; this.load(new FileReader(path)); } public ObjectSettings(String path) throws FileNotFoundException, IOException { this(new File(path)); } public boolean getBoolean(String key, boolean def) { return Boolean.parseBoolean(this.getProperty(key, String.valueOf(def))); } public int getInteger(String key, int def) { return Integer.parseInt(this.getProperty(key, String.valueOf(def))); } public float getFloat(String key, float def) { return Float.parseFloat(this.getProperty(key, String.valueOf(def))); } public void set(String key, Object val) { this.setProperty(key, val.toString()); } public void store(String comment) { try { this.store(new FileOutputStream(path), comment); } catch(IOException e) { e.printStackTrace(); } } }
Enginecrafter77/LMPluger
src/addonloader/util/ObjectSettings.java
Java
mit
1,423
print ARGF.read.gsub!(/\B[a-z]+\B/) {|x| x.split('').sort_by{rand}.join}
J-Y/RubyQuiz
ruby_quiz/quiz76_sols/solutions/Himadri Choudhury/scramble.rb
Ruby
mit
73
require 'minitest/autorun' require 'minitest/pride' require 'bundler/setup' Bundler.require(:default) require 'active_record' require File.dirname(__FILE__) + '/../lib/where_exists' ActiveRecord::Base.default_timezone = :utc ActiveRecord::Base.time_zone_aware_attributes = true ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => File.dirname(__FILE__) + "/db/test.db" )
EugZol/where_exists
test/test_helper.rb
Ruby
mit
402
/* * This file is part of the easy framework. * * (c) Julien Sergent <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'events' ) /** * @class Database */ class Database { /** * @constructor */ constructor( config ) { this._config = config this.stateEmitter = new EventsEmitter() this.name = config.config.name this.init() } /** * init - init attributes */ init() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = false this._connectionError = null } /** * load - load database config */ async start() { await this.connect() } /** * restart - restart database component */ async restart() { this.resetProperties() await this.start() } /** * connect - connect database to instance */ async connect() { const { instance, connected, error } = await this.config.connector() const oldConnected = this.connected this.instance = instance this.connected = connected this.connectionError = error if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } if ( error ) { throw new Error( error ) } } /** * Reset database connection and instance * * @memberOf Database */ disconnect() { const oldConnected = this.connected this.resetProperties() if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } } /** * verifyConnectionHandler - handler called by daemon which indicates if database still available or not * * @returns {Promise} * * @memberOf Database */ verifyConnectionHandler() { return this.config.verifyConnectionHandler() } /** * Branch handler on database state events * * @param {Function} handler * * @memberOf Database */ connectToStateEmitter( handler ) { this.stateEmitter.on( 'change', handler ) } /** * get - get database instance * * @returns {Object} */ get instance() { return this._instance } /** * set - set database instance * * @param {Object} instance * @returns {Object} */ set instance( instance ) { this._instance = instance return this._instance } /** * get - get database connection state * * @returns {Object} */ get connected() { return this._connected } /** * set - set database connection state * * @param {boolean} connected * @returns {Database} */ set connected( connected ) { this._connected = connected return this } /** * get - get database configurations * * @returns {Object} */ get config() { return this._config } /** * Get connection error * * @readonly * * @memberOf Database */ get connectionError() { return this._connectionError } /** * Set connection error * * @returns {Database} * * @memberOf Database */ set connectionError( error ) { this._connectionError = error return this } } module.exports = Database
MadDeveloper/easy.js
easy/database/Database.js
JavaScript
mit
3,837
import { useEffect, useRef, useState } from "react" import * as React from "react" import { RelayPaginationProp, RelayRefetchProp, createPaginationContainer, } from "react-relay" import { graphql } from "relay-runtime" import Waypoint from "react-waypoint" import { Box, Flex, Spacer, Spinner } from "@artsy/palette" import compact from "lodash/compact" import styled from "styled-components" import { extractNodes } from "v2/Utils/extractNodes" import { ItemFragmentContainer } from "./Item" import { Reply } from "./Reply" import { ConversationMessagesFragmentContainer as ConversationMessages } from "./ConversationMessages" import { ConversationHeader } from "./ConversationHeader" import { ConfirmArtworkModalQueryRenderer } from "./ConfirmArtworkModal" import { BuyerGuaranteeMessage } from "./BuyerGuaranteeMessage" import { returnOrderModalDetails } from "../Utils/returnOrderModalDetails" import { OrderModal } from "./OrderModal" import { UnreadMessagesToastQueryRenderer } from "./UnreadMessagesToast" import useOnScreen from "../Utils/useOnScreen" import { UpdateConversation } from "../Mutation/UpdateConversationMutation" import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql" import { useRouter } from "v2/System/Router/useRouter" export interface ConversationProps { conversation: Conversation_conversation showDetails: boolean setShowDetails: (showDetails: boolean) => void relay: RelayPaginationProp refetch: RelayRefetchProp["refetch"] } export const PAGE_SIZE: number = 15 const Loading: React.FC = () => ( <SpinnerContainer> <Spinner /> </SpinnerContainer> ) const Conversation: React.FC<ConversationProps> = props => { const { conversation, relay, showDetails, setShowDetails } = props const liveArtwork = conversation?.items?.[0]?.liveArtwork const artwork = liveArtwork?.__typename === "Artwork" ? liveArtwork : null const isOfferable = !!artwork && !!artwork?.isOfferableFromInquiry const [showConfirmArtworkModal, setShowConfirmArtworkModal] = useState< boolean >(false) const inquiryItemBox = compact(conversation.items).map((i, idx) => { const isValidType = i.item?.__typename === "Artwork" || i.item?.__typename === "Show" return ( <ItemFragmentContainer item={i.item!} key={isValidType ? i.item?.id : idx} /> ) }) // ORDERS const [showOrderModal, setShowOrderModal] = useState<boolean>(false) const activeOrder = extractNodes(conversation.orderConnection)[0] let orderID let kind if (activeOrder) { kind = activeOrder.buyerAction orderID = activeOrder.internalID } const { url, modalTitle } = returnOrderModalDetails({ kind: kind!, orderID: orderID, }) // SCROLLING AND FETCHING // States and Refs const bottomOfMessageContainer = useRef<HTMLElement>(null) const initialMount = useRef(true) const initialScroll = useRef(true) const scrollContainer = useRef<HTMLDivElement>(null) const [fetchingMore, setFetchingMore] = useState<boolean>(false) const [lastMessageID, setLastMessageID] = useState<string | null>() const [lastOrderUpdate, setLastOrderUpdate] = useState<string | null>() const isBottomVisible = useOnScreen(bottomOfMessageContainer) // Functions const loadMore = (): void => { if (relay.isLoading() || !relay.hasMore() || !initialMount.current) return setFetchingMore(true) const scrollCursor = scrollContainer.current ? scrollContainer.current?.scrollHeight - scrollContainer.current?.scrollTop : 0 relay.loadMore(PAGE_SIZE, error => { if (error) console.error(error) setFetchingMore(false) if (scrollContainer.current) { // Scrolling to former position scrollContainer.current?.scrollTo({ top: scrollContainer.current?.scrollHeight - scrollCursor, behavior: "smooth", }) } }) } const { match } = useRouter() const conversationID = match?.params?.conversationID // TODO: refactor useEffect(() => { initialScroll.current = false }, [conversationID]) useEffect(() => { initialScroll.current = !fetchingMore }, [fetchingMore]) useEffect(() => { if (!fetchingMore && !initialScroll.current) { scrollToBottom() } }) const scrollToBottom = () => { if (!!bottomOfMessageContainer?.current) { bottomOfMessageContainer.current?.scrollIntoView?.({ block: "end", inline: "nearest", behavior: initialMount.current ? "auto" : "smooth", }) if (isBottomVisible) initialMount.current = false setLastMessageID(conversation?.lastMessageID) setOrderKey() } } const refreshData = () => { props.refetch({ conversationID: conversation.internalID }, null, error => { if (error) console.error(error) scrollToBottom() }) } const setOrderKey = () => { setLastOrderUpdate(activeOrder?.updatedAt) } const [toastBottom, setToastBottom] = useState(0) // Behaviours // -Navigation useEffect(() => { setLastMessageID(conversation?.fromLastViewedMessageID) initialMount.current = true setOrderKey() }, [ conversation.internalID, conversation.fromLastViewedMessageID, setOrderKey, ]) // -Last message opened useEffect(() => { // Set on a timeout so the user sees the "new" flag setTimeout( () => { UpdateConversation(relay.environment, conversation) }, !!conversation.isLastMessageToUser ? 3000 : 0 ) }, [lastMessageID]) // -Workaround Reply render resizing race condition useEffect(() => { if (initialMount.current) scrollToBottom() const rect = scrollContainer.current?.getBoundingClientRect() setToastBottom(window.innerHeight - (rect?.bottom ?? 0) + 30) }, [scrollContainer?.current?.clientHeight]) // -On scroll down useEffect(() => { if (isBottomVisible) refreshData() }, [isBottomVisible]) return ( <Flex flexDirection="column" flexGrow={1}> <ConversationHeader partnerName={conversation.to.name} showDetails={showDetails} setShowDetails={setShowDetails} /> <NoScrollFlex flexDirection="column" width="100%"> <MessageContainer ref={scrollContainer as any}> <Box pb={[6, 6, 6, 0]} pr={1}> <Spacer mt={["75px", "75px", 2]} /> <Flex flexDirection="column" width="100%" px={1}> {isOfferable && <BuyerGuaranteeMessage />} {inquiryItemBox} <Waypoint onEnter={loadMore} /> {fetchingMore ? <Loading /> : null} <ConversationMessages messages={conversation.messagesConnection!} events={conversation.orderConnection} lastViewedMessageID={conversation?.fromLastViewedMessageID} setShowDetails={setShowDetails} /> <Box ref={bottomOfMessageContainer as any} /> </Flex> </Box> <UnreadMessagesToastQueryRenderer conversationID={conversation?.internalID!} lastOrderUpdate={lastOrderUpdate} bottom={toastBottom} hasScrolled={!isBottomVisible} onClick={scrollToBottom} refreshCallback={refreshData} /> </MessageContainer> <Reply onScroll={scrollToBottom} conversation={conversation} refetch={props.refetch} environment={relay.environment} openInquiryModal={() => setShowConfirmArtworkModal(true)} openOrderModal={() => setShowOrderModal(true)} /> </NoScrollFlex> {isOfferable && ( <ConfirmArtworkModalQueryRenderer artworkID={artwork?.internalID!} conversationID={conversation.internalID!} show={showConfirmArtworkModal} closeModal={() => setShowConfirmArtworkModal(false)} /> )} {isOfferable && ( <OrderModal path={url!} orderID={orderID} title={modalTitle!} show={showOrderModal} closeModal={() => { refreshData() setShowOrderModal(false) }} /> )} </Flex> ) } const MessageContainer = styled(Box)` flex-grow: 1; overflow-y: auto; ` const NoScrollFlex = styled(Flex)` overflow: hidden; flex-grow: 1; ` const SpinnerContainer = styled.div` width: 100%; height: 100px; position: relative; ` export const ConversationPaginationContainer = createPaginationContainer( Conversation, { conversation: graphql` fragment Conversation_conversation on Conversation @argumentDefinitions( count: { type: "Int", defaultValue: 30 } after: { type: "String" } ) { id internalID from { name email } to { name initials } initialMessage lastMessageID fromLastViewedMessageID isLastMessageToUser unread orderConnection( first: 10 states: [APPROVED, FULFILLED, SUBMITTED, REFUNDED, CANCELED] participantType: BUYER ) { edges { node { internalID updatedAt ... on CommerceOfferOrder { buyerAction } } } ...ConversationMessages_events } unread messagesConnection(first: $count, after: $after, sort: DESC) @connection(key: "Messages_messagesConnection", filters: []) { pageInfo { startCursor endCursor hasPreviousPage hasNextPage } edges { node { id } } totalCount ...ConversationMessages_messages } items { item { __typename ... on Artwork { id isOfferableFromInquiry internalID } ...Item_item } liveArtwork { ... on Artwork { isOfferableFromInquiry internalID __typename } } } ...ConversationCTA_conversation } `, }, { direction: "forward", getConnectionFromProps(props) { return props.conversation?.messagesConnection }, getFragmentVariables(prevVars, count) { return { ...prevVars, count, } }, getVariables(props, { cursor, count }) { return { count, cursor, after: cursor, conversationID: props.conversation.id, } }, query: graphql` query ConversationPaginationQuery( $count: Int $after: String $conversationID: ID! ) { node(id: $conversationID) { ...Conversation_conversation @arguments(count: $count, after: $after) } } `, } )
artsy/force
src/v2/Apps/Conversation/Components/Conversation.tsx
TypeScript
mit
11,098
--- layout: post title: Hybrid重构框架 color: blue width: 3 height: 1 category: hybrid --- #### Hybrid重构框架结构 !["框架结构"]({{"/assets/framework/1.png" | prepend: site.baseurl }}) 框架结构是基于业务模型定制的 分为 【公共模块】 和 【业务模块】 #### 公共模块(Common ) 组成 公共模块 由两部分组成 分别是 【Scss】 和 【Widget】 !["公共模块结构"]({{"/assets/framework/2.png" | prepend: site.baseurl }}) *** **Scss 放着框架公用代码** 【component】 * _button(按钮) * _list-item(列表 包括带箭头的) * _name-gender(性别样式 主要用在理财师业务模块中) * _notice-bar(小黄条) * _value(代表收益涨、跌的公共色值类) 【mixins】 * _border-line(兼容ios9 和 Android 关于1px显示的粗细问题 现已统一采用1px/*no*/) * _button(按钮 + 状态) * _clearfix(清除浮动) * _cus-font-height(自定义字号 高度 和button 合作用的) * _ellipse(省略号缩写) * _list-item(列表样式 供 component里的的list-item调用) * _value(涨跌样式 供 component里的的value调用) * _way-step-v(类似时间轴一样的 竖列步骤结构) 【themes】 定义了全站通用的颜色值 * 字体 * 基本色 橙色、白色、蓝色 * 蓝色、灰色的灰度级 * 线条色 * 文本色 * 按钮色 * 收益涨跌色值 【core】是以上通用 样式的集合出口 *** **Widget 存放框架组件样式代码** 暂时抽出的组件有 * animate(动画) * banner(广告banner) * baseloading(加载样式) * fundItem(基金模块) * indexCrowdfunding(理财首页的众筹模块) * newsItem(发现频道的 新闻模块) * prodfixItem (固收页的 产品模块 包括新手 和 加息类产品) * slick (轮播组件样式) * tab ( tab 导航) *** #### 业务模块(Pages) 组成 目前业务模块 有众筹、白拿、基金、理财、发现、积分商城、新手引导、邀请、理财师 后续会根据业务内容的增加而变化 !["业务模块"]({{"/assets/framework/3.png" | prepend: site.baseurl }})
Angelkuga/h5-standard-spec
_posts/2016-10-23-hybrid-refactor-framework.markdown
Markdown
mit
2,288
<?php class LinterTests extends PHPUnit_Framework_TestCase { /** * @param string $source * @param \Superbalist\Money\Linter\Tests\LinterTestInterface $test */ protected function assertLinterThrowsWarnings($source, \Superbalist\Money\Linter\Tests\LinterTestInterface $test) { $result = $test->analyse($source); $this->assertNotEmpty($result); } /** * */ public function testMatchesAbsFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo abs(-37);', new \Superbalist\Money\Linter\Tests\AbsFunctionCallTest() ); } /** * */ public function testMatchesArraySumFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $values = array(0, 1, 2, 3); $sum = array_sum($values);', new \Superbalist\Money\Linter\Tests\ArraySumFunctionCallTest() ); } /** * */ public function testMatchesCeilFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo ceil(3.3);', new \Superbalist\Money\Linter\Tests\CeilFunctionCallTest() ); } /** * */ public function testMatchesDivideOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 / 0.1;', new \Superbalist\Money\Linter\Tests\DivideOperatorTest() ); } /** * */ public function testMatchesFloatCastTest() { $this->assertLinterThrowsWarnings( '<?php $test = "3.3"; echo (float) $test;', new \Superbalist\Money\Linter\Tests\FloatCastTest() ); } /** * */ public function testMatchesFloatParamDocBlockTest() { $source = <<<'EOT' <?php /** * @param float $number this is a test * @return float test */ public function getFloatNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatParamDocBlockTest()); } /** * */ public function testMatchesFloatReturnDocBlockTest() { $source = <<<'EOT' <?php /** * @param float $number this is a test * @return float test */ public function getFloatNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatReturnDocBlockTest()); } /** * */ public function testMatchesFloatvalFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo floatval("3.3");', new \Superbalist\Money\Linter\Tests\FloatvalFunctionCallTest() ); } /** * */ public function testMatchesFloatVarDocBlockTest() { $source = <<<'EOT' <?php /** * @var float */ protected $number = 0.0; EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatVarDocBlockTest()); } /** * */ public function testMatchesFloorFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo floor(3.3);', new \Superbalist\Money\Linter\Tests\FloorFunctionCallTest() ); } /** * */ public function testMatchesGreaterThanOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 > 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\GreaterThanOperatorTest() ); } /** * */ public function testMatchesGreaterThanOrEqualsOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 >= 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\GreaterThanOrEqualsOperatorTest() ); } /** * */ public function testMatchesIntCastTest() { $this->assertLinterThrowsWarnings( '<?php $test = "3.3"; echo (int) $test;', new \Superbalist\Money\Linter\Tests\IntCastTest() ); } /** * */ public function testMatchesIntParamDocBlockTest() { $source = <<<'EOT' <?php /** * @param int $number this is a test * @return int test */ public function getIntNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntParamDocBlockTest()); } /** * */ public function testMatchesIntReturnDocBlockTest() { $source = <<<'EOT' <?php /** * @param int $number this is a test * @return int test */ public function getIntNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntReturnDocBlockTest()); } /** * */ public function testMatchesIntvalFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo intval("3.3");', new \Superbalist\Money\Linter\Tests\IntvalFunctionCallTest() ); } /** * */ public function testMatchesIntVarDocBlockTest() { $source = <<<'EOT' <?php /** * @var int */ protected $number = 0; EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntVarDocBlockTest()); } /** * */ public function testMatchesIsFloatFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3.3; var_dump(is_float($a));', new \Superbalist\Money\Linter\Tests\IsFloatFunctionCallTest() ); } /** * */ public function testMatchesIsIntegerFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_integer($a));', new \Superbalist\Money\Linter\Tests\IsIntegerFunctionCallTest() ); } /** * */ public function testMatchesIsIntFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_int($a));', new \Superbalist\Money\Linter\Tests\IsIntFunctionCallTest() ); } /** * */ public function testMatchesIsNumericFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_numeric($a));', new \Superbalist\Money\Linter\Tests\IsNumericFunctionCallTest() ); } /** * */ public function testMatchesMaxFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo max(0, 3.3);', new \Superbalist\Money\Linter\Tests\MaxFunctionCallTest() ); } /** * */ public function testMatchesMinFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo min(0, 3.3);', new \Superbalist\Money\Linter\Tests\MinFunctionCallTest() ); } /** * */ public function testMatchesMinusOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 - 0.1;', new \Superbalist\Money\Linter\Tests\MinusOperatorTest() ); } /** * */ public function testMatchesModOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 4 % 2;', new \Superbalist\Money\Linter\Tests\ModOperatorTest() ); } /** * */ public function testMatchesMoneyFormatCallTest() { $this->assertLinterThrowsWarnings( '<?php echo money_format("%.2n", 2.4562)', new \Superbalist\Money\Linter\Tests\MoneyFormatCallTest() ); } /** * */ public function testMatchesMultiplyOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 * 0.1;', new \Superbalist\Money\Linter\Tests\MultiplyOperatorTest() ); } /** * */ public function testMatchesNumberFloatTest() { $this->assertLinterThrowsWarnings( '<?php $test = 0.2 + 0.1;', new \Superbalist\Money\Linter\Tests\NumberFloatTest() ); } /** * */ public function testMatchesNumberFormatCallTest() { $this->assertLinterThrowsWarnings( '<?php echo number_format(1.3, 2)', new \Superbalist\Money\Linter\Tests\NumberFormatCallTest() ); } /** * */ public function testMatchesNumberIntTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 + 0.1;', new \Superbalist\Money\Linter\Tests\NumberIntTest() ); } /** * */ public function testMatchesPlusOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 + 0.1;', new \Superbalist\Money\Linter\Tests\PlusOperatorTest() ); } /** * */ public function testMatchesPowFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo pow(2, 8);', new \Superbalist\Money\Linter\Tests\PowFunctionCallTest() ); } /** * */ public function testMatchesRoundFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo round(9.93434, 2);', new \Superbalist\Money\Linter\Tests\RoundFunctionCallTest() ); } /** * */ public function testMatchesSmallerThanOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 < 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\SmallerThanOperatorTest() ); } /** * */ public function testMatchesSmallerThanOrEqualsOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 <= 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\SmallerThanOrEqualsOperatorTest() ); } /** * */ public function testMatchesSprintfFormatFloatTest() { $this->assertLinterThrowsWarnings( '<?php echo sprintf("%f", 4.55555);', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); $this->assertLinterThrowsWarnings( '<?php echo sprintf("%.2f %s", 4.55555, "test");', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); $this->assertLinterThrowsWarnings( '<?php echo sprintf("%.2f %s", 4.55555, sprintf("%s", "test")); $test = intval(1.1);', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); } /** * */ public function testMatchesVariableDecrementTest() { $this->assertLinterThrowsWarnings( '<?php $n = 3; $n--;', new \Superbalist\Money\Linter\Tests\VariableDecrementTest() ); } /** * */ public function testMatchesVariableDivideEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n /= 3;', new \Superbalist\Money\Linter\Tests\VariableDivideEqualsTest() ); } /** * */ public function testMatchesVariableIncrementTest() { $this->assertLinterThrowsWarnings( '<?php $n = 3; $n++;', new \Superbalist\Money\Linter\Tests\VariableIncrementTest() ); } /** * */ public function testMatchesVariableMinusEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n -= 2;', new \Superbalist\Money\Linter\Tests\VariableMinusEqualsTest() ); } /** * */ public function testMatchesVariableModEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 24; $n %= 2;', new \Superbalist\Money\Linter\Tests\VariableModEqualsTest() ); } /** * */ public function testMatchesVariablePlusEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n += 2;', new \Superbalist\Money\Linter\Tests\VariablePlusEqualsTest() ); } /** * */ public function testMatchesVariableTimesEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n *= 2;', new \Superbalist\Money\Linter\Tests\VariableTimesEqualsTest() ); } }
Superbalist/php-money
tests/LinterTests.php
PHP
mit
12,597
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>hammer: 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.8.1 / hammer - 1.3+8.12</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> hammer <small> 1.3+8.12 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-10 07:56:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-10 07:56:43 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 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/lukaszcz/coqhammer&quot; dev-repo: &quot;git+https://github.com/lukaszcz/coqhammer.git&quot; bug-reports: &quot;https://github.com/lukaszcz/coqhammer/issues&quot; license: &quot;LGPL-2.1-only&quot; synopsis: &quot;General-purpose automated reasoning hammer tool for Coq&quot; description: &quot;&quot;&quot; A general-purpose automated reasoning hammer tool for Coq that combines learning from previous proofs with the translation of problems to the logics of automated systems and the reconstruction of successfully found proofs. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; {ocaml:version &gt;= &quot;4.06&quot;} &quot;plugin&quot;] install: [ [make &quot;install-plugin&quot;] [make &quot;test-plugin&quot;] {with-test} ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.13~&quot;} (&quot;conf-g++&quot; {build} | &quot;conf-clang&quot; {build}) &quot;coq-hammer-tactics&quot; {= version} ] tags: [ &quot;category:Miscellaneous/Coq Extensions&quot; &quot;keyword:automation&quot; &quot;keyword:hammer&quot; &quot;logpath:Hammer.Plugin&quot; &quot;date:2020-07-28&quot; ] authors: [ &quot;Lukasz Czajka &lt;[email protected]&gt;&quot; &quot;Cezary Kaliszyk &lt;[email protected]&gt;&quot; ] url { src: &quot;https://github.com/lukaszcz/coqhammer/archive/v1.3-coq8.12.tar.gz&quot; checksum: &quot;sha512=666ea825c122319e398efb7287f429ebfb5d35611b4cabe4b88732ffb5c265ef348b53d5046c958831ac0b7a759b44ce1ca04220ca68b1915accfd23435b479c&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-hammer.1.3+8.12 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-hammer -&gt; coq &gt;= 8.12 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer.1.3+8.12</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.07.1-2.0.6/released/8.8.1/hammer/1.3+8.12.html
HTML
mit
7,338
package ch.bisi.koukan.job; import ch.bisi.koukan.provider.XMLExchangeRatesProvider; import ch.bisi.koukan.repository.DataAccessException; import ch.bisi.koukan.repository.ExchangeRatesRepository; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Executes scheduled tasks for updating the in memory exchange rates * by querying the European Central Bank endpoints. */ @Component public class ECBDataLoaderScheduler { private static final Logger logger = LoggerFactory.getLogger(ECBDataLoaderScheduler.class); private final XMLExchangeRatesProvider xmlExchangeRatesProvider; private final ExchangeRatesRepository exchangeRatesRepository; private final URL dailyEndpoint; private final URL pastDaysEndpoint; /** * Instantiates a new {@link ECBDataLoaderScheduler}. * * @param xmlExchangeRatesProvider the provider of exchange rates * @param exchangeRatesRepository the repository * @param dailyEndpoint the ECB daily endpoint {@link URL} * @param pastDaysEndpoint the ECB endpoint {@link URL} for retrieving past days data */ @Autowired public ECBDataLoaderScheduler( @Qualifier("ECBProvider") final XMLExchangeRatesProvider xmlExchangeRatesProvider, final ExchangeRatesRepository exchangeRatesRepository, @Qualifier("dailyEndpoint") final URL dailyEndpoint, @Qualifier("pastDaysEndpoint") final URL pastDaysEndpoint) { this.xmlExchangeRatesProvider = xmlExchangeRatesProvider; this.exchangeRatesRepository = exchangeRatesRepository; this.dailyEndpoint = dailyEndpoint; this.pastDaysEndpoint = pastDaysEndpoint; } /** * Retrieves the whole exchange rates daily data. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${daily.rates.update.rate}") public void loadDailyData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = dailyEndpoint.openStream()) { logger.info("Updating ECB daily exchange rates data"); loadData(inputStream); } } /** * Retrieves the whole exchange rates data for past days. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${past.days.rates.update.rate}") public void loadPastDaysData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = pastDaysEndpoint.openStream()) { logger.info("Updating ECB exchange rates data for the past 90 days"); loadData(inputStream); } } /** * Loads exchange rates data from the given {@link InputStream}. * * @param inputStream the {@link InputStream} * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ private void loadData(final InputStream inputStream) throws XMLStreamException, DataAccessException { final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); exchangeRatesRepository.save(xmlExchangeRatesProvider.retrieveAll(xmlStreamReader)); } }
bisignam/koukan
src/main/java/ch/bisi/koukan/job/ECBDataLoaderScheduler.java
Java
mit
3,982
<?php namespace JetMinds\Job\Updates; use Schema; use October\Rain\Database\Schema\Blueprint; use October\Rain\Database\Updates\Migration; class CreateResumesTable extends Migration { public function up() { Schema::create('jetminds_job_resumes', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->string('email')->nullable(); $table->string('phone')->nullable(); $table->string('position')->nullable(); $table->longText('location')->nullable(); $table->string('resume_category')->nullable(); $table->string('resume_education')->nullable(); $table->longText('education_note')->nullable(); $table->string('resume_experience')->nullable(); $table->longText('experience_note')->nullable(); $table->string('resume_language')->nullable(); $table->string('resume_skill')->nullable(); $table->longText('resume_note')->nullable(); $table->boolean('is_invite')->default(1); $table->timestamps(); }); } public function down() { Schema::dropIfExists('jetminds_job_resumes'); } }
jetmindsgroup/job-plugin
updates/create_resumes_table.php
PHP
mit
1,311
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace SpartaHack { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public static ObservableValue<string> Title { get; set; } public static ObservableValue<bool> LoggedIn { get; set; } public static ObservableValue<string> Time { get; set; } public static MainPage root; private DateTime DoneTime; public MainPage(Frame frame) { this.InitializeComponent(); Title = new ObservableValue<string>(); LoggedIn = new ObservableValue<bool>(); Time = new ObservableValue<string>(); this.MySplitView.Content = frame; DataContext = this; DoneTime = DateTime.Parse("1/22/2017 17:00:00 GMT"); DispatcherTimer dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromSeconds(1); dt.Tick += Dt_Tick; this.Loaded += (s,e) => { rdAnnouncements.IsChecked = true; dt.Start(); }; MySplitView.PaneClosed += (s, e) => { grdHideView.Visibility = Visibility.Collapsed; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); }; } private void Dt_Tick(object sender, object e) { TimeSpan dt = DoneTime.ToUniversalTime().Subtract(DateTime.Now.ToUniversalTime()); if (dt.TotalSeconds <= 0) Time.Value = "FINISHED"; else //txtCountDown.Text = dt.ToString(@"hh\:mm\:ss"); //Time.Value = $"{(int)dt.TotalHours}H {dt.Minutes}M {dt.Seconds}S"; Time.Value= string.Format("{0:##}h {1:##}m {2:##}s", ((int)dt.TotalHours), dt.Minutes.ToString(), dt.Seconds.ToString()); } private void OnAnnouncementsChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(AnnouncementsPage)); } catch { } } private void OnScheduleChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SchedulePage)); } catch { } } private void OnTicketChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(TicketPage)); } catch { } } private void OnMapChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(MapPage)); } catch { } } private void OnSponsorChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SponsorPage)); } catch { } } private void OnPrizeChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(PrizePage)); } catch { } } private void OnLoginChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(ProfilePage)); } catch { } } private void HambButton_Click(object sender, RoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } private void grdHideView_Tapped(object sender, TappedRoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } } }
SpartaHack/SpartaHack2016-Windows
2017/SpartaHack/SpartaHack/MainPage.xaml.cs
C#
mit
6,063
using System; using System.Diagnostics; namespace Oragon.Architecture.IO.Path { partial class PathHelpers { #region Private Classes private sealed class RelativeFilePath : RelativePathBase, IRelativeFilePath { #region Internal Constructors internal RelativeFilePath(string pathString) : base(pathString) { Debug.Assert(pathString != null); Debug.Assert(pathString.Length > 0); Debug.Assert(pathString.IsValidRelativeFilePath()); } #endregion Internal Constructors #region Public Properties public string FileExtension { get { return FileNameHelpers.GetFileNameExtension(m_PathString); } } // // File Name and File Name Extension // public string FileName { get { return FileNameHelpers.GetFileName(m_PathString); } } public string FileNameWithoutExtension { get { return FileNameHelpers.GetFileNameWithoutExtension(m_PathString); } } // // IsFilePath ; IsDirectoryPath // public override bool IsDirectoryPath { get { return false; } } public override bool IsFilePath { get { return true; } } #endregion Public Properties #region Public Methods public override IAbsolutePath GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { return (this as IRelativeFilePath).GetAbsolutePathFrom(path); } public IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract IDirectoryPath path = PathBrowsingHelpers.GetBrotherDirectoryWithName(this, directoryName); var pathTyped = path as IRelativeDirectoryPath; Debug.Assert(pathTyped != null); return pathTyped; } public IRelativeFilePath GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract IFilePath path = PathBrowsingHelpers.GetBrotherFileWithName(this, fileName); var pathTyped = path as IRelativeFilePath; Debug.Assert(pathTyped != null); return pathTyped; } public bool HasExtension(string extension) { // All these 3 assertions have been checked by contract! Debug.Assert(extension != null); Debug.Assert(extension.Length >= 2); Debug.Assert(extension[0] == '.'); return FileNameHelpers.HasExtension(m_PathString, extension); } IDirectoryPath IFilePath.GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract return this.GetBrotherDirectoryWithName(directoryName); } // Explicit Impl methods IFilePath IFilePath.GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract return this.GetBrotherFileWithName(fileName); } IFilePath IFilePath.UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); return this.UpdateExtension(newExtension); } // // Absolute/Relative pathString conversion // IAbsoluteFilePath IRelativeFilePath.GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { Debug.Assert(path != null); // Enforced by contracts! string pathAbsolute, failureReason; if (!AbsoluteRelativePathHelpers.TryGetAbsolutePathFrom(path, this, out pathAbsolute, out failureReason)) { throw new ArgumentException(failureReason); } Debug.Assert(pathAbsolute != null); Debug.Assert(pathAbsolute.Length > 0); return (pathAbsolute + MiscHelpers.DIR_SEPARATOR_CHAR + this.FileName).ToAbsoluteFilePath(); } // // Path Browsing facilities // public IRelativeFilePath UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); string pathString = PathBrowsingHelpers.UpdateExtension(this, newExtension); Debug.Assert(pathString.IsValidRelativeFilePath()); return new RelativeFilePath(pathString); } #endregion Public Methods } #endregion Private Classes } }
luizcarlosfaria/Oragon.Architecture
[source]/Oragon.Architecture/IO/Path/PathHelpers+RelativeFilePath.cs
C#
mit
4,445
--- layout: page title: Guardian Quality Technologies Award Ceremony date: 2016-05-24 author: Peter Simmons tags: weekly links, java status: published summary: Sed consequat quis sapien eget malesuada. Morbi semper tempor nunc. banner: images/banner/meeting-01.jpg booking: startDate: 12/25/2019 endDate: 12/28/2019 ctyhocn: MSLOHHX groupCode: GQTAC published: true --- Aliquam bibendum sit amet nibh et feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam feugiat dictum sapien, eget vestibulum mauris tincidunt ut. Quisque suscipit diam vel aliquet suscipit. Donec at sollicitudin orci. Integer est nulla, elementum quis viverra non, semper nec nibh. Mauris pellentesque ligula ac nisl mollis, sit amet semper sapien luctus. Aenean dignissim in lacus sed convallis. Quisque ac dignissim tellus, vel blandit diam. Maecenas consequat ligula ut purus semper, a condimentum tellus volutpat. Aliquam quis lorem ante. Quisque tempus pretium urna. Proin justo nisi, maximus et velit vitae, dictum pretium dui. Ut ut luctus magna. Phasellus lectus justo, varius sed ultrices nec, malesuada id massa. Mauris nulla justo, finibus commodo lobortis sed, pulvinar id ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla fermentum lobortis arcu, id elementum diam tempor vitae. Aliquam erat volutpat. Nulla lacinia metus sit amet cursus lacinia. * Suspendisse congue velit sed varius malesuada * Nulla et ante luctus, sollicitudin justo ullamcorper, aliquet nulla * Proin tincidunt sem quis venenatis cursus * Pellentesque a ipsum tincidunt nisi aliquet varius in sit amet metus * Vestibulum eu ante sit amet lectus vestibulum pretium ut et libero. Nullam molestie felis quis nunc tincidunt, at vestibulum enim tempus. Vivamus imperdiet nec est non tempor. Curabitur at scelerisque leo. Morbi tempor arcu at ex finibus pulvinar. Curabitur ullamcorper tincidunt hendrerit. Donec quam nibh, viverra non feugiat sit amet, dictum ac libero. Ut dignissim neque sit amet tortor lobortis efficitur. Curabitur id consectetur turpis, quis facilisis augue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas sit amet rhoncus erat, nec pulvinar metus.
KlishGroup/prose-pogs
pogs/M/MSLOHHX/GQTAC/index.md
Markdown
mit
2,265
--- layout: page title: Protector Purple Group Show date: 2016-05-24 author: Barbara Riddle tags: weekly links, java status: published summary: In lacinia libero vitae ullamcorper malesuada. banner: images/banner/wedding.jpg booking: startDate: 05/06/2019 endDate: 05/07/2019 ctyhocn: PTNHHHX groupCode: PPGS published: true --- Quisque fermentum nibh lorem, non feugiat nunc dignissim nec. Praesent sed neque sollicitudin, fermentum purus a, porttitor urna. Nullam placerat varius ipsum, quis porttitor sem gravida et. Pellentesque porta interdum luctus. Cras dolor tellus, tristique non efficitur id, ultrices vel nisi. Pellentesque viverra quam vitae est tincidunt, ac lobortis nulla dictum. Vestibulum ornare turpis erat, et porta magna imperdiet sed. Phasellus auctor dui sed ipsum venenatis, ornare porttitor magna varius. * Aliquam porttitor elit at ipsum feugiat, in vehicula elit hendrerit * Morbi quis ligula non nulla sollicitudin sollicitudin eu sed mi * Ut accumsan nisi nec nisl varius, at euismod mi sodales * Nulla tristique magna nec accumsan posuere. Cras ultricies tellus in elit congue pretium. Sed efficitur quam feugiat orci tincidunt finibus. Praesent consectetur sed purus ut condimentum. Suspendisse tincidunt condimentum viverra. In porta rhoncus arcu, a lacinia risus maximus non. Pellentesque et gravida velit. Suspendisse a aliquet mauris. Pellentesque tempor interdum elit sed aliquam. Praesent semper est a metus aliquet, nec ornare nunc sollicitudin. Aliquam non orci dictum, bibendum mi eu, pellentesque mi. Nulla risus odio, blandit in auctor vel, sagittis eu nisi. Curabitur porttitor purus nisi. In eget accumsan erat.
KlishGroup/prose-pogs
pogs/P/PTNHHHX/PPGS/index.md
Markdown
mit
1,665
--- layout: page title: Liberated Peace Electronics Party date: 2016-05-24 author: Charles Hunt tags: weekly links, java status: published summary: Sed sit amet facilisis elit. banner: images/banner/leisure-01.jpg booking: startDate: 11/07/2018 endDate: 11/12/2018 ctyhocn: NCLHXHX groupCode: LPEP published: true --- Ut consequat tortor non eros interdum consectetur. Vestibulum porta gravida nisi, ac laoreet sem imperdiet sit amet. Curabitur dictum elit nisl. Fusce sit amet nulla magna. Nulla risus erat, aliquam sit amet mattis in, placerat sed massa. In dolor ante, ornare at tristique non, rhoncus ac diam. In augue urna, ultrices sed commodo in, pellentesque ut dolor. Vestibulum cursus consectetur odio, lobortis malesuada lectus. Nullam dignissim gravida tristique. 1 Donec eleifend neque blandit enim auctor, ut pellentesque est pulvinar 1 In vitae erat efficitur, rhoncus sem ac, auctor leo 1 Nulla eget est non metus vestibulum convallis 1 Aenean eu purus malesuada, mollis enim nec, aliquet lectus 1 Phasellus nec nisi efficitur, accumsan neque ut, mollis dolor. Praesent tincidunt vulputate elit. Aliquam erat volutpat. Proin placerat nisi ut diam posuere, a laoreet enim luctus. Vestibulum luctus urna a nisi commodo congue. Donec sit amet sem et augue placerat sodales a eget nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum vel ullamcorper urna. Donec cursus imperdiet erat, at finibus velit egestas iaculis. Duis malesuada laoreet leo, in aliquam neque faucibus in. Praesent faucibus diam eget odio lobortis, iaculis laoreet ligula rhoncus. Aliquam erat volutpat. Curabitur hendrerit nibh in orci volutpat egestas. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In volutpat semper mattis. Sed euismod quam id mi consequat, nec consectetur turpis imperdiet. Nunc tristique ultricies enim, vel venenatis quam porta quis. Sed ligula tortor, fringilla ac ultrices vel, vulputate eu nunc. Duis laoreet suscipit turpis ac tempus. Pellentesque nunc nisi, interdum sed bibendum ac, rutrum eu magna. Praesent ac lacinia purus. Phasellus facilisis consequat finibus. Etiam semper dolor nec neque egestas, sed tincidunt odio interdum. Etiam ut ipsum pellentesque, rutrum urna non, pharetra mi. Sed in diam non mauris sodales iaculis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi quis aliquam arcu, eget euismod arcu. Aenean et efficitur nisi. Morbi eu magna ut ligula tempus maximus eu quis nulla.
KlishGroup/prose-pogs
pogs/N/NCLHXHX/LPEP/index.md
Markdown
mit
2,566
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.03 at 03:15:27 PM EDT // package API.amazon.mws.xml.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="value"> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="delete" type="{}BooleanType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "cdrh_classification") public class CdrhClassification { @XmlElement(required = true) protected CdrhClassification.Value value; @XmlAttribute(name = "delete") protected BooleanType delete; /** * Gets the value of the value property. * * @return * possible object is * {@link CdrhClassification.Value } * */ public CdrhClassification.Value getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link CdrhClassification.Value } * */ public void setValue(CdrhClassification.Value value) { this.value = value; } /** * Gets the value of the delete property. * * @return * possible object is * {@link BooleanType } * */ public BooleanType getDelete() { return delete; } /** * Sets the value of the delete property. * * @param value * allowed object is * {@link BooleanType } * */ public void setDelete(BooleanType value) { this.delete = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class Value { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } } }
VDuda/SyncRunner-Pub
src/API/amazon/mws/xml/JAXB/CdrhClassification.java
Java
mit
3,909
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> namespace Marius.Html.Hap { /// <summary> /// Represents a base class for fragments in a mixed code document. /// </summary> public abstract class MixedCodeDocumentFragment { #region Fields internal MixedCodeDocument Doc; private string _fragmentText; internal int Index; internal int Length; private int _line; internal int _lineposition; internal MixedCodeDocumentFragmentType _type; #endregion #region Constructors internal MixedCodeDocumentFragment(MixedCodeDocument doc, MixedCodeDocumentFragmentType type) { Doc = doc; _type = type; switch (type) { case MixedCodeDocumentFragmentType.Text: Doc._textfragments.Append(this); break; case MixedCodeDocumentFragmentType.Code: Doc._codefragments.Append(this); break; } Doc._fragments.Append(this); } #endregion #region Properties /// <summary> /// Gets the fragement text. /// </summary> public string FragmentText { get { if (_fragmentText == null) { _fragmentText = Doc._text.Substring(Index, Length); } return FragmentText; } internal set { _fragmentText = value; } } /// <summary> /// Gets the type of fragment. /// </summary> public MixedCodeDocumentFragmentType FragmentType { get { return _type; } } /// <summary> /// Gets the line number of the fragment. /// </summary> public int Line { get { return _line; } internal set { _line = value; } } /// <summary> /// Gets the line position (column) of the fragment. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the fragment position in the document's stream. /// </summary> public int StreamPosition { get { return Index; } } #endregion } }
marius-klimantavicius/marius-html
Marius.Html/Hap/MixedCodeDocumentFragment.cs
C#
mit
2,555
import React from 'react' import { User } from '../../lib/accounts/users' import styled from '../../lib/styled' import MdiIcon from '@mdi/react' import { mdiAccount } from '@mdi/js' import { SectionPrimaryButton } from './styled' import { useTranslation } from 'react-i18next' interface UserProps { user: User signout: (user: User) => void } const Container = styled.div` margin-bottom: 8px; ` export default ({ user, signout }: UserProps) => { const { t } = useTranslation() return ( <Container> <MdiIcon path={mdiAccount} size='80px' /> <p>{user.name}</p> <SectionPrimaryButton onClick={() => signout(user)}> {t('general.signOut')} </SectionPrimaryButton> </Container> ) }
Sarah-Seo/Inpad
src/components/PreferencesModal/UserInfo.tsx
TypeScript
mit
731
#include "TextItem.h" #include <QPainter> #include <QFont> #include <QDebug> //////////////////////////////////////////////////////////////// TextItem::TextItem(const QString& text, QGraphicsLayoutItem *parent) : BaseItem(parent) { _text = text; QFont font; font.setPointSize(11); font.setBold(false); setFont(font); } //////////////////////////////////////////////////////////////// TextItem::~TextItem() { } //////////////////////////////////////////////////////////////// void TextItem::setFont(const QFont &font) { _font = font; QFontMetrics fm(_font); } //////////////////////////////////////////////////////////////// QSizeF TextItem::measureSize() const { QFontMetrics fm(_font); const QSizeF& size = fm.size(Qt::TextExpandTabs, _text); // NOTE: flag Qt::TextSingleLine ignores newline characters. return size; } //////////////////////////////////////////////////////////////// void TextItem::draw(QPainter *painter, const QRectF& bounds) { painter->setFont(_font); // TODO: mozno bude treba specialne handlovat novy riadok painter->drawText(bounds, _text); }
AdUki/GraphicEditor
GraphicEditor/Ui/Items/TextItem.cpp
C++
mit
1,137
/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ #define _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ #include "../../StroikaPreComp.h" #include "../../Configuration/Common.h" #include "../../Configuration/Concepts.h" #include "../../Debug/AssertExternallySynchronizedMutex.h" #include "../Common.h" /** * \file * * Description: * This module genericly wraps STL containers (such as map, vector etc), and facilitates * using them as backends for Stroika containers. * * TODO: * * @todo Replace Contains() with Lookup () - as we did for LinkedList<T> * * @todo Redo Contains1 versus Contains using partial template specialization of STLContainerWrapper - easy * cuz such a trivial class. I can use THAT trick to handle the case of forward_list too. And size... * * @todo Add special subclass of ForwardIterator that tracks PREVPTR - and use to cleanup stuff * that uses forward_list code... * */ namespace Stroika::Foundation::Containers::DataStructures { namespace Private_ { template <typename T> using has_erase_t = decltype (declval<T&> ().erase (begin (declval<T&> ()), end (declval<T&> ()))); template <typename T> constexpr inline bool has_erase_v = Configuration::is_detected_v<has_erase_t, T>; } /** * Use this to wrap an underlying stl container (like std::vector or stl:list, etc) to adapt * it for Stroika containers. * * \note \em Thread-Safety <a href="Thread-Safety.md#C++-Standard-Thread-Safety">C++-Standard-Thread-Safety</a> * */ template <typename STL_CONTAINER_OF_T> class STLContainerWrapper : public STL_CONTAINER_OF_T, public Debug::AssertExternallySynchronizedMutex { private: using inherited = STL_CONTAINER_OF_T; public: using value_type = typename STL_CONTAINER_OF_T::value_type; using iterator = typename STL_CONTAINER_OF_T::iterator; using const_iterator = typename STL_CONTAINER_OF_T::const_iterator; public: /** * Basic (mostly internal) element used by ForwardIterator. Abstract name so can be referenced generically across 'DataStructure' objects */ using UnderlyingIteratorRep = const_iterator; public: /** * pass through CTOR args to underlying container */ template <typename... EXTRA_ARGS> STLContainerWrapper (EXTRA_ARGS&&... args); public: class ForwardIterator; public: /* * Take iteartor 'pi' which is originally a valid iterator from 'movedFrom' - and replace *pi with a valid * iterator from 'this' - which points at the same logical position. This requires that this container * was just 'copied' from 'movedFrom' - and is used to produce an eqivilennt iterator (since iterators are tied to * the container they were iterating over). */ nonvirtual void MoveIteratorHereAfterClone (ForwardIterator* pi, const STLContainerWrapper* movedFrom) const; public: nonvirtual bool Contains (ArgByValueType<value_type> item) const; public: /** * \note Complexity: * Always: O(N) */ template <typename FUNCTION> nonvirtual void Apply (FUNCTION doToElement) const; public: /** * \note Complexity: * Worst Case: O(N) * Typical: O(N), but can be less if systematically finding entries near start of container */ template <typename FUNCTION> nonvirtual iterator Find (FUNCTION doToElement); template <typename FUNCTION> nonvirtual const_iterator Find (FUNCTION doToElement) const; public: template <typename PREDICATE> nonvirtual bool FindIf (PREDICATE pred) const; public: nonvirtual void Invariant () const noexcept; public: nonvirtual iterator remove_constness (const_iterator it); }; /** * STLContainerWrapper::ForwardIterator is a private utility class designed * to promote source code sharing among the patched iterator implementations. * * \note ForwardIterator takes a const-pointer the the container as argument since this * iterator never MODIFIES the container. * * However, it does a const-cast to maintain a non-const pointer since that is needed to * option a non-const iterator pointer, which is needed by some classes that use this, and * there is no zero (or even low for forward_list) cost way to map from const to non const * iterators (needed to perform the update). * * @see https://stroika.atlassian.net/browse/STK-538 */ template <typename STL_CONTAINER_OF_T> class STLContainerWrapper<STL_CONTAINER_OF_T>::ForwardIterator { public: /** */ explicit ForwardIterator (const STLContainerWrapper* data); explicit ForwardIterator (const STLContainerWrapper* data, UnderlyingIteratorRep startAt); explicit ForwardIterator (const ForwardIterator& from) = default; public: nonvirtual bool Done () const noexcept; public: nonvirtual ForwardIterator& operator++ () noexcept; public: nonvirtual value_type Current () const; public: /** * Only legal to call if underlying iterator is random_access */ nonvirtual size_t CurrentIndex () const; public: nonvirtual UnderlyingIteratorRep GetUnderlyingIteratorRep () const; public: nonvirtual void SetUnderlyingIteratorRep (UnderlyingIteratorRep l); public: nonvirtual bool Equals (const ForwardIterator& rhs) const; public: nonvirtual const STLContainerWrapper* GetReferredToData () const; private: const STLContainerWrapper* fData_; const_iterator fStdIterator_; private: friend class STLContainerWrapper; }; } /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "STLContainerWrapper.inl" #endif /*_Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ */
SophistSolutions/Stroika
Library/Sources/Stroika/Foundation/Containers/DataStructures/STLContainerWrapper.h
C
mit
6,578
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>LCOV - coverage.infosrc/core</title> <link rel="stylesheet" type="text/css" href="../../gcov.css"> </head> <body> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="title">LCOV - code coverage report</td></tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr> <td width="100%"> <table cellpadding=1 border=0 width="100%"> <tr> <td width="10%" class="headerItem">Current view:</td> <td width="35%" class="headerValue"><a href="../../index.html">top level</a> - src/core</td> <td width="5%"></td> <td width="15%"></td> <td width="10%" class="headerCovTableHead">Hit</td> <td width="10%" class="headerCovTableHead">Total</td> <td width="15%" class="headerCovTableHead">Coverage</td> </tr> <tr> <td class="headerItem">Test:</td> <td class="headerValue">coverage.info</td> <td></td> <td class="headerItem">Lines:</td> <td class="headerCovTableEntry">193</td> <td class="headerCovTableEntry">220</td> <td class="headerCovTableEntryMed">87.7 %</td> </tr> <tr> <td class="headerItem">Date:</td> <td class="headerValue">2013-01-10</td> <td></td> <td class="headerItem">Functions:</td> <td class="headerCovTableEntry">23</td> <td class="headerCovTableEntry">26</td> <td class="headerCovTableEntryMed">88.5 %</td> </tr> <tr> <td></td> <td></td> <td></td> <td class="headerItem">Branches:</td> <td class="headerCovTableEntry">20</td> <td class="headerCovTableEntry">24</td> <td class="headerCovTableEntryMed">83.3 %</td> </tr> <tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> </td> </tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> <center> <table width="80%" cellpadding=1 cellspacing=1 border=0> <tr> <td width="44%"><br></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> </tr> <tr> <td class="tableHead">Filename <span class="tableHeadSort"><img src="../../glass.png" width=10 height=14 alt="Sort by name" title="Sort by name" border=0></span></td> <td class="tableHead" colspan=3>Line Coverage <span class="tableHeadSort"><a href="index-sort-l.html"><img src="../../updown.png" width=10 height=14 alt="Sort by line coverage" title="Sort by line coverage" border=0></a></span></td> <td class="tableHead" colspan=2>Functions <span class="tableHeadSort"><a href="index-sort-f.html"><img src="../../updown.png" width=10 height=14 alt="Sort by function coverage" title="Sort by function coverage" border=0></a></span></td> <td class="tableHead" colspan=2>Branches <span class="tableHeadSort"><a href="index-sort-b.html"><img src="../../updown.png" width=10 height=14 alt="Sort by branch coverage" title="Sort by branch coverage" border=0></a></span></td> </tr> <tr> <td class="coverFile"><a href="dvm.c.gcov.html">dvm.c</a></td> <td class="coverBar" align="center"> <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../emerald.png" width=91 height=10 alt="91.4%"><img src="../../snow.png" width=9 height=10 alt="91.4%"></td></tr></table> </td> <td class="coverPerHi">91.4&nbsp;%</td> <td class="coverNumHi">128 / 140</td> <td class="coverPerHi">92.3&nbsp;%</td> <td class="coverNumHi">12 / 13</td> <td class="coverPerMed">88.9&nbsp;%</td> <td class="coverNumMed">16 / 18</td> </tr> <tr> <td class="coverFile"><a href="vmbase.c.gcov.html">vmbase.c</a></td> <td class="coverBar" align="center"> <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../amber.png" width=81 height=10 alt="81.2%"><img src="../../snow.png" width=19 height=10 alt="81.2%"></td></tr></table> </td> <td class="coverPerMed">81.2&nbsp;%</td> <td class="coverNumMed">65 / 80</td> <td class="coverPerMed">84.6&nbsp;%</td> <td class="coverNumMed">11 / 13</td> <td class="coverPerLo">66.7&nbsp;%</td> <td class="coverNumLo">4 / 6</td> </tr> </table> </center> <br> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php">LCOV version 1.9</a></td></tr> </table> <br> </body> </html>
rumblesan/diddy-vm
cdiddy/coverage/src/core/index.html
HTML
mit
5,152
import {writeFile} from 'fs-promise'; import {get, has, merge, set} from 'lodash/fp'; import flatten from 'flat'; import fs from 'fs'; import path from 'path'; const data = new WeakMap(); const initial = new WeakMap(); export default class Config { constructor(d) { data.set(this, d); initial.set(this, Object.assign({}, d)); } clone() { return Object.assign({}, data.get(this)); } get(keypath) { return get(keypath, data.get(this)); } has(keypath) { return has(keypath, data.get(this)); } inspect() { return data.get(this); } merge(extra) { data.set(this, merge(data.get(this), extra)); } set(keypath, value) { return set(keypath, data.get(this), value); } async save() { const out = this.toString(); return await writeFile(`.boilerizerc`, out); } toJSON() { const keys = Object.keys(flatten(data.get(this), {safe: true})); const init = initial.get(this); let target; try { const filepath = path.join(process.cwd(), `.boilerizerc`); // Using sync here because toJSON can't have async functions in it // eslint-disable-next-line no-sync const raw = fs.readFileSync(filepath, `utf8`); target = JSON.parse(raw); } catch (e) { if (e.code !== `ENOENT`) { console.error(e); throw e; } target = {}; } return keys.reduce((acc, key) => { if (!has(key, init) || has(key, target)) { const val = this.get(key); acc = set(key, val, acc); } return acc; }, target); } toString() { return JSON.stringify(this, null, 2); } }
ianwremmel/boilerize
src/lib/config.js
JavaScript
mit
1,639
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.dfa.report; public class ClassNode extends AbstractReportNode { private String className; public ClassNode(String className) { this.className = className; } public String getClassName() { return className; } public boolean equalsNode(AbstractReportNode arg0) { if (!(arg0 instanceof ClassNode)) { return false; } return ((ClassNode) arg0).getClassName().equals(className); } }
byronka/xenos
utils/pmd-bin-5.2.2/src/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java
Java
mit
585
<?php namespace Helpers; /** *This class handles rendering of view files * *@author Geoffrey Oliver <[email protected]> *@copyright Copyright (c) 2015 - 2020 Geoffrey Oliver *@link http://libraries.gliver.io *@category Core *@package Core\Helpers\View */ use Drivers\Templates\Implementation; use Exceptions\BaseException; use Drivers\Cache\CacheBase; use Drivers\Registry; class View { /** *This is the constructor class. We make this private to avoid creating instances of *this object * *@param null *@return void */ private function __construct() {} /** *This method stops creation of a copy of this object by making it private * *@param null *@return void * */ private function __clone(){} /** *This method parses the input variables and loads the specified views * *@param string $filePath the string that specifies the view file to load *@param array $data an array with variables to be passed to the view file *@return void This method does not return anything, it directly loads the view file *@throws */ public static function render($filePath, array $data = null) { //this try block is excecuted to enable throwing and catching of errors as appropriate try { //get the variables passed and make them available to the view if ( $data != null) { //loop through the array setting the respective variables foreach ($data as $key => $value) { $$key = $value; } } //get the parsed contents of the template file $contents = self::getContents($filePath); //start the output buffer ob_start(); //evaluate the contents of this view file eval("?>" . $contents . "<?"); //get the evaluated contents $contents = ob_get_contents(); //clean the output buffer ob_end_clean(); //return the evaluated contents echo $contents; //stop further script execution exit(); } catch(BaseException $e) { //echo $e->getMessage(); $e->show(); } catch(Exception $e) { echo $e->getMessage(); } } /** *This method converts the code into valid php code * *@param string $file The name of the view whose contant is to be parsed *@return string $parsedContent The parsed content of the template file */ public static function getContents($filePath) { //compose the file full path $path = Path::view($filePath); //get an instance of the view template class $template = Registry::get('template'); //get the compiled file contents $contents = $template->compiled($path); //return the compiled template file contents return $contents; } }
ggiddy/documentation
system/Helpers/View.php
PHP
mit
3,113
package pl.mmorpg.prototype.server.objects.monsters.properties.builders; import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties; public class SnakePropertiesBuilder extends MonsterProperties.Builder { @Override public MonsterProperties build() { experienceGain(100) .hp(100) .strength(5) .level(1); return super.build(); } }
Pankiev/MMORPG_Prototype
Server/core/src/pl/mmorpg/prototype/server/objects/monsters/properties/builders/SnakePropertiesBuilder.java
Java
mit
384
using Microsoft.DataTransfer.AzureTable.Source; using System; using System.Globalization; namespace Microsoft.DataTransfer.AzureTable { /// <summary> /// Contains dynamic resources for data adapters configuration. /// </summary> public static class DynamicConfigurationResources { /// <summary> /// Gets the description for source internal fields configuration property. /// </summary> public static string Source_InternalFields { get { return Format(ConfigurationResources.Source_InternalFieldsFormat, Defaults.Current.SourceInternalFields, String.Join(", ", Enum.GetNames(typeof(AzureTableInternalFields)))); } } private static string Format(string format, params object[] args) { return String.Format(CultureInfo.InvariantCulture, format, args); } } }
innovimax/azure-documentdb-datamigrationtool
AzureTable/Microsoft.DataTransfer.AzureTable/DynamicConfigurationResources.cs
C#
mit
948
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'], plugins: [ 'karma-mocha', 'karma-chai', 'karma-sinon-chai', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-jquery', 'karma-chai-jquery', 'karma-mocha-reporter' ], // list of files / patterns to load in the browser files: [ 'bower/angular/angular.js', 'bower/angular-sanitize/angular-sanitize.js', 'bower/angular-mocks/angular-mocks.js', 'dist/ac-components.min.js', 'test/unit/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
avalanche-canada/ac-components
karma-dist-minified.conf.js
JavaScript
mit
2,019
#! python3 """ GUI for Ultrasonic Temperature Controller Copyright (c) 2015 by Stefan Lehmann """ import os import datetime import logging import json import serial from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \ QDockWidget, QLabel, QFileDialog, QApplication from qtpy.QtGui import QIcon from qtpy.QtCore import QSettings, QCoreApplication, Qt, QThread, \ Signal from serial.serialutil import SerialException from jsonwatch.jsonitem import JsonItem from jsonwatch.jsonnode import JsonNode from jsonwatchqt.logger import LoggingWidget from pyqtconfig.config import QSettingsManager from jsonwatchqt.plotsettings import PlotSettingsWidget from jsonwatchqt.objectexplorer import ObjectExplorer from jsonwatchqt.plotwidget import PlotWidget from jsonwatchqt.serialdialog import SerialDialog, PORT_SETTING, \ BAUDRATE_SETTING from jsonwatchqt.utilities import critical, pixmap from jsonwatchqt.recorder import RecordWidget from jsonwatchqt.csvsettings import CSVSettingsDialog, DECIMAL_SETTING, \ SEPARATOR_SETTING logger = logging.getLogger("jsonwatchqt.mainwindow") WINDOWSTATE_SETTING = "mainwindow/windowstate" GEOMETRY_SETTING = "mainwindow/geometry" FILENAME_SETTING = "mainwindow/filename" def strip(s): return s.strip() def utf8_to_bytearray(x): return bytearray(x, 'utf-8') def bytearray_to_utf8(x): return x.decode('utf-8') def set_default_settings(settings: QSettingsManager): settings.set_defaults({ DECIMAL_SETTING: ',', SEPARATOR_SETTING: ';' }) class SerialWorker(QThread): data_received = Signal(datetime.datetime, str) def __init__(self, ser: serial.Serial, parent=None): super().__init__(parent) self.serial = ser self._quit = False def run(self): while not self._quit: try: if self.serial.isOpen() and self.serial.inWaiting(): self.data_received.emit( datetime.datetime.now(), strip(bytearray_to_utf8(self.serial.readline())) ) except SerialException: pass def quit(self): self._quit = True class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.recording_enabled = False self.serial = serial.Serial() self.rootnode = JsonNode('') self._connected = False self._dirty = False self._filename = None # settings self.settings = QSettingsManager() set_default_settings(self.settings) # Controller Settings self.settingsDialog = None # object explorer self.objectexplorer = ObjectExplorer(self.rootnode, self) self.objectexplorer.nodevalue_changed.connect(self.send_serialdata) self.objectexplorer.nodeproperty_changed.connect(self.set_dirty) self.objectexplorerDockWidget = QDockWidget(self.tr("object explorer"), self) self.objectexplorerDockWidget.setObjectName( "objectexplorer_dockwidget") self.objectexplorerDockWidget.setWidget(self.objectexplorer) # plot widget self.plot = PlotWidget(self.rootnode, self.settings, self) # plot settings self.plotsettings = PlotSettingsWidget(self.settings, self.plot, self) self.plotsettingsDockWidget = QDockWidget(self.tr("plot settings"), self) self.plotsettingsDockWidget.setObjectName("plotsettings_dockwidget") self.plotsettingsDockWidget.setWidget(self.plotsettings) # log widget self.loggingWidget = LoggingWidget(self) self.loggingDockWidget = QDockWidget(self.tr("logger"), self) self.loggingDockWidget.setObjectName("logging_dockwidget") self.loggingDockWidget.setWidget(self.loggingWidget) # record widget self.recordWidget = RecordWidget(self.rootnode, self) self.recordDockWidget = QDockWidget(self.tr("data recording"), self) self.recordDockWidget.setObjectName("record_dockwidget") self.recordDockWidget.setWidget(self.recordWidget) # actions and menus self._init_actions() self._init_menus() # statusbar statusbar = self.statusBar() statusbar.setVisible(True) self.connectionstateLabel = QLabel(self.tr("Not connected")) statusbar.addPermanentWidget(self.connectionstateLabel) statusbar.showMessage(self.tr("Ready")) # layout self.setCentralWidget(self.plot) self.addDockWidget(Qt.LeftDockWidgetArea, self.objectexplorerDockWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.plotsettingsDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.loggingDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.recordDockWidget) self.load_settings() def _init_actions(self): # Serial Dialog self.serialdlgAction = QAction(self.tr("Serial Settings..."), self) self.serialdlgAction.setShortcut("F6") self.serialdlgAction.setIcon(QIcon(pixmap("configure.png"))) self.serialdlgAction.triggered.connect(self.show_serialdlg) # Connect self.connectAction = QAction(self.tr("Connect"), self) self.connectAction.setShortcut("F5") self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.connectAction.triggered.connect(self.toggle_connect) # Quit self.quitAction = QAction(self.tr("Quit"), self) self.quitAction.setShortcut("Alt+F4") self.quitAction.setIcon(QIcon(pixmap("window-close-3.png"))) self.quitAction.triggered.connect(self.close) # Save Config as self.saveasAction = QAction(self.tr("Save as..."), self) self.saveasAction.setShortcut("Ctrl+Shift+S") self.saveasAction.setIcon(QIcon(pixmap("document-save-as-5.png"))) self.saveasAction.triggered.connect(self.show_savecfg_dlg) # Save file self.saveAction = QAction(self.tr("Save"), self) self.saveAction.setShortcut("Ctrl+S") self.saveAction.setIcon(QIcon(pixmap("document-save-5.png"))) self.saveAction.triggered.connect(self.save_file) # Load file self.loadAction = QAction(self.tr("Open..."), self) self.loadAction.setShortcut("Ctrl+O") self.loadAction.setIcon(QIcon(pixmap("document-open-7.png"))) self.loadAction.triggered.connect(self.show_opencfg_dlg) # New self.newAction = QAction(self.tr("New"), self) self.newAction.setShortcut("Ctrl+N") self.newAction.setIcon(QIcon(pixmap("document-new-6.png"))) self.newAction.triggered.connect(self.new) # start recording self.startrecordingAction = QAction(self.tr("Start recording"), self) self.startrecordingAction.setShortcut("F9") self.startrecordingAction.setIcon(QIcon(pixmap("media-record-6.png"))) self.startrecordingAction.triggered.connect(self.start_recording) # stop recording self.stoprecordingAction = QAction(self.tr("Stop recording"), self) self.stoprecordingAction.setShortcut("F10") self.stoprecordingAction.setIcon(QIcon(pixmap("media-playback-stop-8.png"))) self.stoprecordingAction.setEnabled(False) self.stoprecordingAction.triggered.connect(self.stop_recording) # clear record self.clearrecordAction = QAction(self.tr("Clear"), self) self.clearrecordAction.setIcon(QIcon(pixmap("editclear.png"))) self.clearrecordAction.triggered.connect(self.clear_record) # export record self.exportcsvAction = QAction(self.tr("Export to csv..."), self) self.exportcsvAction.setIcon(QIcon(pixmap("text_csv.png"))) self.exportcsvAction.triggered.connect(self.export_csv) # show record settings self.recordsettingsAction = QAction(self.tr("Settings..."), self) self.recordsettingsAction.setIcon(QIcon(pixmap("configure.png"))) self.recordsettingsAction.triggered.connect(self.show_recordsettings) # Info self.infoAction = QAction(self.tr("Info"), self) self.infoAction.setShortcut("F1") self.infoAction.triggered.connect(self.show_info) def _init_menus(self): # file menu self.fileMenu = self.menuBar().addMenu(self.tr("File")) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.loadAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveasAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.connectAction) self.fileMenu.addAction(self.serialdlgAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) # view menu self.viewMenu = self.menuBar().addMenu(self.tr("View")) self.viewMenu.addAction( self.objectexplorerDockWidget.toggleViewAction()) self.viewMenu.addAction(self.plotsettingsDockWidget.toggleViewAction()) self.viewMenu.addAction(self.loggingDockWidget.toggleViewAction()) self.viewMenu.addAction(self.recordDockWidget.toggleViewAction()) # record menu self.recordMenu = self.menuBar().addMenu(self.tr("Record")) self.recordMenu.addAction(self.startrecordingAction) self.recordMenu.addAction(self.stoprecordingAction) self.recordMenu.addAction(self.exportcsvAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.clearrecordAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.recordsettingsAction) # info menu self.menuBar().addAction(self.infoAction) def show_info(self): QMessageBox.about( self, QApplication.applicationName(), "%s %s\n" "Copyright (c) by %s" % ( QCoreApplication.applicationName(), QCoreApplication.applicationVersion(), QCoreApplication.organizationName(), ) ) def load_file(self, filename): old_filename = self.filename if self.filename != filename else None self.filename = filename try: with open(filename, 'rb') as f: try: self.objectexplorer.model().beginResetModel() self.rootnode.load(bytearray_to_utf8(f.read())) self.objectexplorer.model().endResetModel() except ValueError as e: critical(self, "File '%s' is not a valid config file." % filename) logger.error(str(e)) if old_filename is not None: self.load_file(old_filename) else: self.filename = None except FileNotFoundError as e: logger.error(str(e)) self.filename = None self.objectexplorer.refresh() def load_settings(self): settings = QSettings() # window geometry try: self.restoreGeometry(settings.value(GEOMETRY_SETTING)) except: logger.debug("error restoring window geometry") # window state try: self.restoreState(settings.value(WINDOWSTATE_SETTING)) except: logger.debug("error restoring window state") # filename self.filename = settings.value(FILENAME_SETTING) if self.filename is not None: self.load_file(self.filename) def save_settings(self): settings = QSettings() settings.setValue(WINDOWSTATE_SETTING, self.saveState()) settings.setValue(GEOMETRY_SETTING, self.saveGeometry()) settings.setValue(FILENAME_SETTING, self.filename) def closeEvent(self, event): if self.dirty: res = QMessageBox.question( self, QCoreApplication.applicationName(), self.tr("Save changes to file '%s'?" % self.filename if self.filename is not None else "unknown"), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if res == QMessageBox.Cancel: event.ignore() return elif res == QMessageBox.Yes: self.save_file() self.save_settings() try: self.worker.quit() except AttributeError: pass try: self.serial.close() except (SerialException, AttributeError): pass def new(self): self.objectexplorer.model().beginResetModel() self.rootnode.clear() self.objectexplorer.model().endResetModel() def send_reset(self): jsonstring = json.dumps({"resetpid": 1}) self.serial.write(bytearray(jsonstring, 'utf-8')) def receive_serialdata(self, time, data): self.loggingWidget.log_input(data) try: self.rootnode.from_json(data) except ValueError as e: logger.error(str(e)) # refresh widgets self.objectexplorer.refresh() self.plot.refresh(time) if self.recording_enabled: self.recordWidget.add_data(time, self.rootnode) def send_serialdata(self, node): if isinstance(node, JsonItem): if self.serial.isOpen(): s = node.to_json() self.serial.write(utf8_to_bytearray(s + '\n')) self.loggingWidget.log_output(s.strip()) def show_serialdlg(self): dlg = SerialDialog(self.settings, self) dlg.exec_() def toggle_connect(self): if self.serial.isOpen(): self.disconnect() else: self.connect() def connect(self): # Load port setting port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # If no port has been selected before show serial settings dialog if port is None: if self.show_serialdlg() == QDialog.Rejected: return port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # Serial connection try: self.serial.port = port self.serial.baudrate = baudrate self.serial.open() except ValueError: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("Serial parameters e.g. baudrate, databits are out " "of range.") ) except SerialException: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("The device '%s' can not be found or can not be " "configured." % port) ) else: self.worker = SerialWorker(self.serial, self) self.worker.data_received.connect(self.receive_serialdata) self.worker.start() self.connectAction.setText(self.tr("Disconnect")) self.connectAction.setIcon(QIcon(pixmap("network-disconnect-3.png"))) self.serialdlgAction.setEnabled(False) self.connectionstateLabel.setText( self.tr("Connected to %s") % port) self._connected = True self.objectexplorer.refresh() def disconnect(self): self.worker.quit() self.serial.close() self.connectAction.setText(self.tr("Connect")) self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.serialdlgAction.setEnabled(True) self.connectionstateLabel.setText(self.tr("Not connected")) self._connected = False self.objectexplorer.refresh() def show_savecfg_dlg(self): filename, _ = QFileDialog.getSaveFileName( self, self.tr("Save configuration file..."), directory=os.path.expanduser("~"), filter="Json file (*.json)" ) if filename: self.filename = filename self.save_file() def save_file(self): if self.filename is not None: config_string = self.rootnode.dump() with open(self.filename, 'w') as f: f.write(config_string) self.dirty = False else: self.show_savecfg_dlg() def show_opencfg_dlg(self): # show file dialog filename, _ = QFileDialog.getOpenFileName( self, self.tr("Open configuration file..."), directory=os.path.expanduser("~"), filter=self.tr("Json file (*.json);;All files (*.*)") ) # load config file if filename: self.load_file(filename) def refresh_window_title(self): s = "%s %s" % (QCoreApplication.applicationName(), QCoreApplication.applicationVersion()) if self.filename is not None: s += " - " + self.filename if self.dirty: s += "*" self.setWindowTitle(s) def start_recording(self): self.recording_enabled = True self.startrecordingAction.setEnabled(False) self.stoprecordingAction.setEnabled(True) def stop_recording(self): self.recording_enabled = False self.startrecordingAction.setEnabled(True) self.stoprecordingAction.setEnabled(False) def export_csv(self): filename, _ = QFileDialog.getSaveFileName( self, QCoreApplication.applicationName(), filter="CSV files(*.csv);;All files (*.*)" ) if filename == "": return # get current dataframe and export to csv df = self.recordWidget.dataframe decimal = self.settings.get(DECIMAL_SETTING) df = df.applymap(lambda x: str(x).replace(".", decimal)) df.to_csv( filename, index_label="time", sep=self.settings.get(SEPARATOR_SETTING) ) def clear_record(self): self.recordWidget.clear() def show_recordsettings(self): dlg = CSVSettingsDialog(self) dlg.exec_() # filename property @property def filename(self): return self._filename @filename.setter def filename(self, value=""): self._filename = value self.refresh_window_title() # dirty property @property def dirty(self): return self._dirty @dirty.setter def dirty(self, value): self._dirty = value self.refresh_window_title() def set_dirty(self): self.dirty = True # connected property @property def connected(self): return self._connected
MrLeeh/jsonwatchqt
jsonwatchqt/mainwindow.py
Python
mit
19,071
This returns the resolution of the cone (rather than the cap)
workergnome/ofdocs_markdown
3d/ofConePrimitive.getResolution.md
Markdown
mit
62
using System.Threading; using CodeTiger; using Xunit; namespace UnitTests.CodeTiger { public class LazyTests { public class Create1 { [Fact] public void SetsIsValueCreatedToFalse() { var target = Lazy.Create<object>(); Assert.False(target.IsValueCreated); } [Fact] public void ReturnsDefaultValueOfObject() { var target = Lazy.Create<object>(); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Fact] public void ReturnsDefaultValueOfBoolean() { var target = Lazy.Create<bool>(); Assert.Equal(new bool(), target.Value); } [Fact] public void ReturnsDefaultValueOfDecimal() { var target = Lazy.Create<decimal>(); Assert.Equal(new decimal(), target.Value); } } public class Create1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfObject(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfBoolean(bool isThreadSafe) { var target = Lazy.Create<bool>(isThreadSafe); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfDecimal(bool isThreadSafe) { var target = Lazy.Create<decimal>(isThreadSafe); Assert.Equal(new decimal(), target.Value); } } public class Create1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfObject(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfBoolean(LazyThreadSafetyMode mode) { var target = Lazy.Create<bool>(mode); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfDecimal(LazyThreadSafetyMode mode) { var target = Lazy.Create<decimal>(mode); Assert.Equal(new decimal(), target.Value); } } public class Create1_FuncOfTaskOfT1 { [Fact] public void SetsIsValueCreatedToFalse() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.False(target.IsValueCreated); } [Fact] public void SetsValueToProvidedObject() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void SetsValueToProvidedTask(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsValueToProvidedTask(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.Same(expected, target.Value); } } } }
csdahlberg/CodeTigerLib
UnitTests/UnitTests.CodeTiger.Core/LazyTests.cs
C#
mit
6,719
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Function awe_webview_set_callback_change_target_url</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js">/**/</script> <script type="text/javascript" src="../../prettify/prettify.js">/**/</script> <script type="text/javascript" src="../../scripts/ddox.js">/**/</script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class=" module">animation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/component.html" class=" module">component</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class=" tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/awesomium.html" class="selected module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class=" module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/resources.html" class=" module">resources</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/tasks.html" class=" module">tasks</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); //]]> </script> </div> </nav> <div id="main-contents"> <h1>Function awe_webview_set_callback_change_target_url</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt--> <p> Assign a <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> function to be notified when the target URL has changed. This is usually the result of hovering over a link on the page. </p> <section> <p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#webview"><code class="prettyprint lang-d">webview</code></a> The WebView instance. </p> <p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> A function pointer to the <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a>. </p> </section> <section> <h2>Prototype</h2> <pre class="code prettyprint lang-d prototype"> void awe_webview_set_callback_change_target_url( &nbsp;&nbsp;<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>* webview, &nbsp;&nbsp;extern(C) void function(<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>*, const(<a href="../../utility/awesomium/awe_string.html">awe_string</a>)*) callback ) extern(C);</pre> </section> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt--> </section> <section> <h2>License</h2><!-- using block ddox.license in ddox.layout.dt--> </section> </div> </body> </html>
Circular-Studios/Dash-Docs
api/v0.9.0/utility/awesomium/awe_webview_set_callback_change_target_url.html
HTML
mit
8,881
all: g++ lpf.cpp -o lpf.o .PHONY: clean clean: rm *.o
jmeline/secret-meme
pe/Makefile
Makefile
mit
58
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { sc := bufio.NewScanner(os.Stdin) sc.Split(bufio.ScanWords) n := nextInt(sc) a := nextInt(sc) b := nextInt(sc) answer := 0 for i := 1; i <= n; i++ { sum := 0 for _, s := range fmt.Sprintf("%d", i) { x, _ := strconv.Atoi(string(s)) sum = sum + x } if a <= sum && sum <= b { answer = answer + i } } fmt.Println(answer) } // ---------- func nextString(sc *bufio.Scanner) string { sc.Scan() return sc.Text() } func nextNumber(sc *bufio.Scanner) float64 { sc.Scan() f, err := strconv.ParseFloat(sc.Text(), 32) if err != nil { panic(err) } return f } func nextInt(sc *bufio.Scanner) int { sc.Scan() n, err := strconv.Atoi(sc.Text()) if err != nil { panic(err) } return n } func printArray(xs []int) { fmt.Println(strings.Trim(fmt.Sprint(xs), "[]")) } func debugPrintf(format string, a ...interface{}) { fmt.Fprintf(os.Stderr, format, a...) }
bati11/study-algorithm
at_coder/abc/ABC083B_SomeSums/ABC083B.go
GO
mit
973
export default function _isString(obj) { return toString.call(obj) === '[object String]' }
jrpool/js-utility-underscore
src/objects/_isString.js
JavaScript
mit
93
# cortex-ls [![NPM version](https://badge.fury.io/js/cortex-ls.svg)](http://badge.fury.io/js/cortex-ls) [![Build Status](https://travis-ci.org/cortexjs/cortex-ls.svg?branch=master)](https://travis-ci.org/cortexjs/cortex-ls) [![Dependency Status](https://gemnasium.com/cortexjs/cortex-ls.svg)](https://gemnasium.com/cortexjs/cortex-ls) <!-- description --> ## Install ```bash $ npm install cortex-ls --save ``` ## Usage ```js var cortex_ls = require('cortex-ls); ``` ## Licence MIT <!-- do not want to make nodeinit to complicated, you can edit this whenever you want. -->
cortexjs/cortex-ls
README.md
Markdown
mit
579
import Vue from 'vue' import Router from 'vue-router' import index from '../components/index' import project from '../components/project/index' import proAdd from '../components/project/proAdd' import proList from '../components/project/proList' import apiList from '../components/project/apiList' import apiView from '../components/project/apiView' import apiEdit from '../components/project/apiEdit' import apiHistory from '../components/project/apiHistory' import test from '../components/test' import message from '../components/message' import member from '../components/member' import doc from '../components/doc' import set from '../components/set' import userSet from '../components/user/set' import login from '../components/user/login' Vue.use(Router) const router:any = new Router({ mode: 'history', routes: [ { path: '/', name: 'index', component: index }, { path: '/project', name: 'project', component: project, children: [ { path: 'list', name: 'proList', component: proList, meta: { requireLogin: true } }, { path: 'add', name: 'proAdd', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/edit', name: 'proEdit', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/api', name: 'proApiList', component: apiList, children: [ { path: 'add', name: 'apiAdd', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/detail', name: 'apiView', component: apiView, meta: { requireLogin: true }, }, { path: ':apiId/edit', name: 'apiEdit', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/history', name: 'apiHistory', component: apiHistory, meta: { requireLogin: true } } ] } ] }, { path: '/test', name: 'test', component: test, meta: { requireLogin: true } }, { path: '/message', name: 'message', component: message, meta: { requireLogin: true } }, { path: '/member', name: 'member', component: member, meta: { requireLogin: true } }, { path: '/doc', name: 'doc', component: doc }, { path: '/set', name: 'set', component: set, meta: { requireLogin: true } }, { path: '/user/set', name: 'userSet', component: userSet, meta: { requireLogin: true } }, { path: '/user/login', name: 'login', component: login } ] }) router.beforeEach((to:any, from:any, next:any) => { if (to.matched.some((res:any) => res.meta.requireLogin)) { if (localStorage.getItem('token')) { next() } else { next('/user/login') } } else { next() } }) export default router
studyweb2017/best-api
web/src/service/router.ts
TypeScript
mit
3,538
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ], [ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ], [ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ], [ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ], [ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ], [ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ] ];
bhargavipatel/808X_VO
docs/html/class_mock.js
JavaScript
mit
1,000
#include "StdAfx.h" #include ".\datawriter.h" using namespace std; DataWriter::DataWriter(const std::string &fileName) { this->fileName = fileName; fileStream = NULL; //Initialize the filestream fileStream = new fstream(fileName.c_str(), ios::out|ios::binary|ios::trunc); } void DataWriter::Write(int data, const size_t size) { if (fileStream) { if (fileStream->is_open()) { int sizeCount = 0; while (data > 0) { fileStream->put(char(data%256)); data /= 256; ++sizeCount; } while (sizeCount < size) //Fill the remaining characters { fileStream->put(char(0)); ++sizeCount; } } } } void DataWriter::Write(const char data) { if (fileStream) { if (fileStream->is_open()) { fileStream->put(data); } } } void DataWriter::Write(const char* data, const size_t size) { if (!data) { std::cout << "Warning: attempted to write null pointer\n"; return; } if (fileStream) { if (fileStream->is_open()) { if (strlen(data) > size) { cout << "Warning: Attempting to write data to area larger than specified size\n"; return; } fileStream->write(data,strlen(data)); if (strlen(data) < size) { for (unsigned int i = 0; i < size - strlen(data); ++i) { fileStream->put(char(0));//The files we're dealing with are little-endian, so fill after the placement of the data } } } } }
AngryLawyer/SiegeUnitConverterCpp
DataWriter.cpp
C++
mit
1,869
# Material-UI Versions <p class="description">You can come back to this page and switch the version of the docs you're reading at any time.</p> ## Stable versions The most recent version is recommended in production. {{"demo": "pages/versions/StableVersions.js", "hideHeader": true}} ## Последние версии Here you can find the latest unreleased documentation and code. You can use it to see what changes are coming and provide better feedback to Material-UI contributors. {{"demo": "pages/versions/LatestVersion.js", "hideHeader": true}} ## Versioning strategy We recognize that you need **stability** from the Material-UI library. Stability ensures that reusable components and libraries, tutorials, tools, and learned practices don't become obsolete unexpectedly. Stability is essential for the ecosystem around Material-UI to thrive. This document contains **the practices that we follow** to provide you with a leading-edge UI library, balanced with stability. We strive to ensure that future changes are always introduced in a predictable way. We want everyone who depends on Material-UI to know when and how new features are added, and to be well-prepared when obsolete ones are removed. Material-UI strictly follows [Semantic Versioning 2.0.0](https://semver.org/). Material-UI version numbers have three parts: `major.minor.patch`. The version number is incremented based on the level of change included in the release. - **Major releases** contain significant new features, some but minimal developer assistance is expected during the update. When updating to a new major release, you may need to run update scripts, refactor code, run additional tests, and learn new APIs. - **Minor releases** contain important new features. Minor releases are fully backward-compatible; no developer assistance is expected during update, but you can optionally modify your apps and libraries to begin using new APIs, features, and capabilities that were added in the release. - **Patch releases** are low risk, contain bug fixes and small new features. No developer assistance is expected during update. ## Release frequency We work toward a regular schedule of releases, so that you can plan and coordinate your updates with the continuing evolution of Material-UI. In general, you can expect the following release cycle: - A **major** release every 6 months. - 1-3 **minor** releases for each major release. - A **patch** release every week (anytime for urgent bugfix). ## Release schedule > Disclaimer: The dates are offered as general guidance and may be adjusted by us when necessary to ensure delivery of a high-quality code. | Date | Version | |:------------- |:-------------------------- | | May 2019 | `@material-ui/core` v4.0.0 | | December 2019 | `@material-ui/core` v5.0.0 | You can follow [our milestones](https://github.com/mui-org/material-ui/milestones) for a more detailed overview. ## Support policy We only support the latest version of Material-UI. We don't yet have the resources to offer [LTS](https://en.wikipedia.org/wiki/Long-term_support) releases. ## Deprecation practices Sometimes **"breaking changes"**, such as the removal of support for select APIs and features, are necessary. To make these transitions as easy as possible, we make two commitments to you: - We work hard to minimize the number of breaking changes and to provide migration tools when possible. - We follow the deprecation policy described here, so you have time to update your apps to the latest APIs and best practices. To help ensure that you have sufficient time and a clear path to update, this is our deprecation policy: - We announce deprecated features in the changelog, and when possible, with warnings at runtime. - When we announce a deprecation, we also announce a recommended update path. - We support existing use of a stable API during the deprecation period, so your code will keep working during that period. - We only make peer dependency updates (React) that require changes to your apps in a major release.
allanalexandre/material-ui
docs/src/pages/versions/versions-ru.md
Markdown
mit
4,094
namespace mazes.Core.Grids { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using mazes.Core.Cells; using mazes.Core.Grids.Cartesian; public class WeaveGrid : Grid { private readonly List<UnderCell> _underCells = new List<UnderCell>(); public WeaveGrid(int rows, int cols) : base(rows, cols) { PrepareGrid(); ConfigureCells(); } private void PrepareGrid() { var rows = new List<List<Cell>>(); for (var row = 0; row < Rows; row++) { var newRow = new List<Cell>(); for (var column = 0; column < Columns; column++) { newRow.Add(new OverCell(row, column, this)); } rows.Add(newRow); } _grid = rows; } private void ConfigureCells() { foreach (var cell in Cells.Cast<OverCell>()) { var row = cell.Row; var col = cell.Column; cell.North = (OverCell)this[row - 1, col]; cell.South = (OverCell)this[row + 1, col]; cell.West = (OverCell)this[row, col - 1]; cell.East = (OverCell)this[row, col + 1]; } } public void TunnelUnder(OverCell overCell) { var underCell = new UnderCell(overCell); _underCells.Add(underCell); } public override IEnumerable<Cell> Cells => base.Cells.Union(_underCells); public override Image ToImg(int cellSize = 50, float insetPrc = 0) { return base.ToImg(cellSize, insetPrc == 0 ? 0.1f : insetPrc); } protected override void ToImgWithInset(Graphics g, CartesianCell cell, DrawMode mode, int cellSize, int x, int y, int inset) { if (cell is UnderCell) { var (x1, x2, x3, x4, y1, y2, y3, y4) = CellCoordinatesWithInset(x, y, cellSize, inset); if (cell.VerticalPassage) { g.DrawLine(Pens.Black, x2, y1, x2, y2); g.DrawLine(Pens.Black, x3, y1, x3, y2); g.DrawLine(Pens.Black, x2, y3, x2, y4); g.DrawLine(Pens.Black, x3, y3, x3, y4); } else { g.DrawLine(Pens.Black, x1, y2, x2, y2); g.DrawLine(Pens.Black, x1, y3, x2, y3); g.DrawLine(Pens.Black, x3, y2, x4, y2); g.DrawLine(Pens.Black, x3, y3, x4, y3); } } else { base.ToImgWithInset(g, cell, mode, cellSize, x, y, inset); } } } }
ericrrichards/mazes
mazes/Core/Grids/WeaveGrid.cs
C#
mit
2,678
package stream.flarebot.flarebot.mod.modlog; public enum ModAction { BAN(true, ModlogEvent.USER_BANNED), SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), FORCE_BAN(true, ModlogEvent.USER_BANNED), TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), UNBAN(false, ModlogEvent.USER_UNBANNED), KICK(true, ModlogEvent.USER_KICKED), TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), MUTE(true, ModlogEvent.USER_MUTED), UNMUTE(false, ModlogEvent.USER_UNMUTED), WARN(true, ModlogEvent.USER_WARNED); private boolean infraction; private ModlogEvent event; ModAction(boolean infraction, ModlogEvent modlogEvent) { this.infraction = infraction; this.event = modlogEvent; } public boolean isInfraction() { return infraction; } @Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); } public String getLowercaseName() { return toString().toLowerCase(); } public ModlogEvent getEvent() { return event; } }
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java
Java
mit
1,090
<?php /** * @package Update * @category modules * @author Nazar Mokrynskyi <[email protected]> * @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs; use h; $Config = Config::instance(); $db = DB::instance(); $Index = Index::instance(); $module_object = $Config->module('Update'); if (!$module_object->version) { $module_object->version = 0; } if (isset($Config->route[0]) && $Config->route[0] == 'process') { $version = (int)$module_object->version; for ($i = 1; file_exists(MFOLDER."/sql/$i.sql") || file_exists(MFOLDER."/php/$i.php"); ++$i) { if ($version < $i) { if (file_exists(MFOLDER."/sql/$i.sql")) { foreach (explode(';', file_get_contents(MFOLDER."/sql/$i.sql")) as $s) { if ($s) { $db->{'0'}()->q($s); } } } if (file_exists(MFOLDER."/php/$i.php")) { include MFOLDER."/php/$i.php"; } $module_object->version = $i; } } $Index->save(true); } $Index->buttons = false; $Index->content( h::{'p.cs-center'}("Current revision: $module_object->version"). h::{'a.cs-button.cs-center'}( 'Update System structure', [ 'href' => 'admin/Update/process' ] ) );
nazar-pc/cherrytea.org-old
components/modules/Update/admin/index.php
PHP
mit
1,229
<!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 (version 1.6.0_18) on Thu Dec 18 17:18:41 PST 2014 --> <title>Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li> <li><a href="BasicFileChooserUI.UpdateAction.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction" class="title">Uses of Class<br>javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</h2> </div> <div class="classUseContainer">No usage of javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li> <li><a href="BasicFileChooserUI.UpdateAction.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
fbiville/annotation-processing-ftw
doc/java/jdk7/javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html
HTML
mit
5,212
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="/public/font-awesome/css/font-awesome.min.css"> <!-- Enable responsiveness on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title> 404: Page not found &middot; Home </title> <!-- CSS --> <link rel="stylesheet" href="/public/css/poole.css"> <link rel="stylesheet" href="/public/css/syntax.css"> <link rel="stylesheet" href="/public/css/hyde.css"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface"> <!-- Icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png"> <link rel="shortcut icon" href="/public/favicon.ico"> <!-- RSS --> <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml"> </head> <body> <div class="sidebar"> <div class="container sidebar-sticky"> <div class="sidebar-about"> <img src="/public/logo.png"> <p class="lead"></p> </div> <ul class="sidebar-nav"> <li class="sidebar-nav-item"> <a href="/"> Home</a> </li> <li class="sidebar-nav-item"> <a href="/about.html">About</a> </li> <li class="sidebar-nav-item"> <a href="/projects.html">Projects</a> </li> <li class="sidebar-nav-item"> <a href="/feedback.html">Feedback</a> </li> </ul> <p>&copy; 2014. All rights reserved.</p> </div> </div> <div class="content container"> <div class="page"> <h1 class="page-title">404: Page not found</h1> <p class="lead">Sorry, we've misplaced that URL or it's pointing to something that doesn't exist. <a href="/">Head back home</a> to try finding it again.</p> </div> </div> </body> </html>
b4z/b4z.github.io
_site/404/index.html
HTML
mit
2,396
#pragma once #include "dg/enums.h" #include "json/json.h" namespace eule{ /** * @brief Provide a mapping between input file and named parameters */ struct Parameters { unsigned n; //!< \# of polynomial coefficients in R and Z unsigned Nx; //!< \# of cells in x -direction unsigned Ny; //!< \# of cells in y -direction unsigned Nz; //!< \# of cells in z -direction double dt; //!< timestep unsigned n_out; //!< \# of polynomial coefficients in output file unsigned Nx_out; //!< \# of cells in x-direction in output file unsigned Ny_out; //!< \# of cells in y-direction in output file unsigned Nz_out; //!< \# of cells in z-direction in output file unsigned itstp; //!< \# of steps between outputs unsigned maxout; //!< \# of outputs excluding first double eps_pol; //!< accuracy of polarization double jfactor; //jump factor € [1,0.01] double eps_maxwell; //!< accuracy of induction equation double eps_gamma; //!< accuracy of gamma operator double eps_time;//!< accuracy of implicit timestep double eps_hat;//!< 1 double mu[2]; //!< mu[0] = mu_e, m[1] = mu_i double tau[2]; //!< tau[0] = -1, tau[1] = tau_i double beta; //!< plasma beta double nu_perp; //!< perpendicular diffusion double nu_parallel; //!< parallel diffusion double c; //!< parallel resistivity double amp; //!< blob amplitude double sigma; //!< perpendicular blob width double posX; //!< perpendicular position relative to box width double posY; //!< perpendicular position relative to box height double sigma_z; //!< parallel blob width in units of pi double k_psi; //!< mode number double omega_source; //!< source amplitude double nprofileamp; //!< amplitude of profile double bgprofamp; //!< background profile amplitude double boxscaleRp; //!< box can be larger double boxscaleRm;//!< box can be larger double boxscaleZp;//!< box can be larger double boxscaleZm;//!< box can be larger enum dg::bc bc; //!< global perpendicular boundary condition unsigned pollim; //!< 0= no poloidal limiter, 1 = poloidal limiter unsigned pardiss; //!< 0 = adjoint parallel dissipation, 1 = nonadjoint parallel dissipation unsigned mode; //!< 0 = blob simulations (several rounds fieldaligned), 1 = straight blob simulation( 1 round fieldaligned), 2 = turbulence simulations ( 1 round fieldaligned), unsigned initcond; //!< 0 = zero electric potential, 1 = ExB vorticity equals ion diamagnetic vorticity unsigned curvmode; //!< 0 = low beta, 1 = toroidal field line Parameters( const Json::Value& js) { n = js["n"].asUInt(); Nx = js["Nx"].asUInt(); Ny = js["Ny"].asUInt(); Nz = js["Nz"].asUInt(); dt = js["dt"].asDouble(); n_out = js["n_out"].asUInt(); Nx_out = js["Nx_out"].asUInt(); Ny_out = js["Ny_out"].asUInt(); Nz_out = js["Nz_out"].asUInt(); itstp = js["itstp"].asUInt(); maxout = js["maxout"].asUInt(); eps_pol = js["eps_pol"].asDouble(); jfactor = js["jumpfactor"].asDouble(); eps_maxwell = js["eps_maxwell"].asDouble(); eps_gamma = js["eps_gamma"].asDouble(); eps_time = js["eps_time"].asDouble(); eps_hat = 1.; mu[0] = js["mu"].asDouble(); mu[1] = +1.; tau[0] = -1.; tau[1] = js["tau"].asDouble(); beta = js["beta"].asDouble(); nu_perp = js["nu_perp"].asDouble(); nu_parallel = js["nu_parallel"].asDouble(); c = js["resistivity"].asDouble(); amp = js["amplitude"].asDouble(); sigma = js["sigma"].asDouble(); posX = js["posX"].asDouble(); posY = js["posY"].asDouble(); sigma_z = js["sigma_z"].asDouble(); k_psi = js["k_psi"].asDouble(); omega_source = js["source"].asDouble(); bc = dg::str2bc(js["bc"].asString()); nprofileamp = js["nprofileamp"].asDouble(); bgprofamp = js["bgprofamp"].asDouble(); boxscaleRp = js.get("boxscaleRp",1.05).asDouble(); boxscaleRm = js.get("boxscaleRm",1.05).asDouble(); boxscaleZp = js.get("boxscaleZp",1.05).asDouble(); boxscaleZm = js.get("boxscaleZm",1.05).asDouble(); pollim = js.get( "pollim", 0).asUInt(); pardiss = js.get( "pardiss", 0).asUInt(); mode = js.get( "mode", 0).asUInt(); initcond = js.get( "initial", 0).asUInt(); curvmode = js.get( "curvmode", 0).asUInt(); } /** * @brief Display parameters * * @param os Output stream */ void display( std::ostream& os = std::cout ) const { os << "Physical parameters are: \n" <<" mu_e = "<<mu[0]<<"\n" <<" mu_i = "<<mu[1]<<"\n" <<" beta = "<<beta<<"\n" <<" El.-temperature: = "<<tau[0]<<"\n" <<" Ion-temperature: = "<<tau[1]<<"\n" <<" perp. Viscosity: = "<<nu_perp<<"\n" <<" par. Resistivity: = "<<c<<"\n" <<" par. Viscosity: = "<<nu_parallel<<"\n"; os <<"Blob parameters are: \n" << " amplitude: "<<amp<<"\n" << " width: "<<sigma<<"\n" << " posX: "<<posX<<"\n" << " posY: "<<posY<<"\n" << " sigma_z: "<<sigma_z<<"\n"; os << "Profile parameters are: \n" <<" omega_source: "<<omega_source<<"\n" <<" density profile amplitude: "<<nprofileamp<<"\n" <<" background profile amplitude: "<<bgprofamp<<"\n" <<" boxscale R+: "<<boxscaleRp<<"\n" <<" boxscale R-: "<<boxscaleRm<<"\n" <<" boxscale Z+: "<<boxscaleZp<<"\n" <<" boxscale Z-: "<<boxscaleZm<<"\n"; os << "Algorithmic parameters are: \n" <<" n = "<<n<<"\n" <<" Nx = "<<Nx<<"\n" <<" Ny = "<<Ny<<"\n" <<" Nz = "<<Nz<<"\n" <<" dt = "<<dt<<"\n"; os << " Stopping for Polar CG: "<<eps_pol<<"\n" <<" Jump scale factor: "<<jfactor<<"\n" <<" Stopping for Maxwell CG: "<<eps_maxwell<<"\n" <<" Stopping for Gamma CG: "<<eps_gamma<<"\n" <<" Stopping for Time CG: "<<eps_time<<"\n"; os << "Output parameters are: \n" <<" n_out = "<<n_out<<"\n" <<" Nx_out = "<<Nx_out<<"\n" <<" Ny_out = "<<Ny_out<<"\n" <<" Nz_out = "<<Nz_out<<"\n" <<" Steps between output: "<<itstp<<"\n" <<" Number of outputs: "<<maxout<<"\n"; os << "Boundary condition is: \n" <<" global BC = "<<dg::bc2str(bc)<<"\n" <<" Poloidal limiter = "<<pollim<<"\n" <<" Parallel dissipation = "<<pardiss<<"\n" <<" Computation mode = "<<mode<<"\n" <<" init cond = "<<initcond<<"\n" <<" curvature mode = "<<curvmode<<"\n"; os << std::flush; } }; }//namespace eule
e3reiter/feltor
src/feltor/parameters.h
C
mit
7,654
import PartyBot from 'partybot-http-client'; import React, { PropTypes, Component } from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet/components/Heading'; import Box from 'grommet/components/Box'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import FormFields from 'grommet/components/FormFields'; import NumberInput from 'grommet/components/NumberInput'; import CloseIcon from 'grommet/components/icons/base/Close'; import Dropzone from 'react-dropzone'; import Layer from 'grommet/components/Layer'; import Header from 'grommet/components/Header'; import Section from 'grommet/components/Section'; import Paragraph from 'grommet/components/Paragraph'; import request from 'superagent'; import Select from 'react-select'; import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants'; import Immutable from 'immutable'; import _ from 'underscore'; class ManageTablesPage extends Component { constructor(props) { super(props); this.handleMobile = this.handleMobile.bind(this); this.closeSetup = this.closeSetup.bind(this); this.onDrop = this.onDrop.bind(this); this.addVariant = this.addVariant.bind(this); this.submitSave = this.submitSave.bind(this); this.submitDelete = this.submitDelete.bind(this); this.state = { isMobile: false, tableId: props.params.table_id || null, confirm: false, name: '', variants: [], organisationId: '5800471acb97300011c68cf7', venues: [], venueId: '', events: [], eventId: '', selectedEvents: [], tableTypes: [], tableTypeId: undefined, tags: 'table', image: null, prevImage: null, isNewImage: null, prices: [] }; } componentWillMount() { if (this.state.tableId) { this.setState({variants: []}); } } componentDidMount() { if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleMobile); } let options = { organisationId: this.state.organisationId }; this.getVenues(options); // IF TABLE ID EXISTS if(this.props.params.table_id) { let tOptions = { organisationId: this.state.organisationId, productId: this.props.params.table_id } this.getTable(tOptions); } } componentWillUnmount() { if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleMobile); } } handleMobile() { const isMobile = window.innerWidth <= 768; this.setState({ isMobile, }); }; getVenues = (options) => { PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({venueId: body[0]._id}); let ttOptions = { organisationId: this.state.organisationId, venue_id: this.state.venueId } // this.getEvents(ttOptions); this.getTableTypes(ttOptions); } this.setState({venues: body, events: []}); } }); } getEvents = (options) => { PartyBot.events.getEventsInOrganisation(options, (err, response, body) => { if(!err && response.statusCode == 200) { if(body.length > 0) { this.setState({eventId: body[0]._id}); } body.map((value, index) =>{ this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })}); }); } }); } getTableTypes = (options) => { PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({tableTypes: body}); let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: body[0]._id } PartyBot.tableTypes.getTableType(params, (aerr, aresponse, abody) => { let events = abody._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: body[0]._id, events: _.flatten(events) }); }); } } }); } getTable = (options) => { PartyBot.products.getProductsInOrganisation(options, (error, response, body) => { if(response.statusCode == 200) { this.setState({ name: body.name, image: { preview: body.image }, prevImage: { preview: body.image }, variants: body.prices.map((value, index) => { return { _event: value._event, price: value.price } }) }); } }); } onVenueChange = (event) => { let id = event.target.value; this.setState({ venueId: id, events: [], variants: []}); let options = { organisationId: this.state.organisationId, venue_id: id }; this.getTableTypes(options); // this.getEvents(options); } onEventChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: event.target.value, price: item.price}); this.setState( { variants: mutated.toArray() } ); } onPriceChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: item._event, price: event.target.value}); this.setState( { variants: mutated.toArray() } ); } closeSetup(){ this.setState({ confirm: false }); this.context.router.push('/tables'); } addVariant() { // will create then get? var newArray = this.state.variants.slice(); newArray.push({ _event_id: [], description: "", image: null, imageUrl: "" }); this.setState({variants:newArray}) } removeVariant(index, event){ // delete variant ID let variants = Immutable.List(this.state.variants); let mutated = variants.remove(index); // let selectedEvents = Immutable.List(this.state.selectedEvents); // let mutatedEvents = selectedEvents.remove(index); this.setState({ variants: mutated.toJS(), }); } onEventAdd = (index, selectedEvents) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('_event_id', selectedEvents); let newClone = cloned.set(index, anIndex); let selectedEventState = Immutable.List(this.state.selectedEvents); let newSelectedEventState = selectedEventState.set(index, selectedEvents); this.setState({selectedEvents: newSelectedEventState.toJS(), variants: newClone.toJS()}); } setDescrpiption = (index, event) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('description', event.target.value); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS()}); } onDrop = (index, file) => { this.setState({ isBusy: true }); let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file[0]); console.log('dragged'); upload.end((err, response) => { if (err) { } else { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('image', file[0]); anIndex = anIndex.set('imageUrl', response.body.secure_url); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS(), isBusy: false}); } }); } onTypeChange = (event) => { var id = event.target.value; let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: id } PartyBot.tableTypes.getTableType(params, (err, response, body) => { let events = body._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: id, variants: [], events: _.flatten(events) }); }); } setName = (event) => { this.setState({name: event.target.value}); } getTypeOptions = () => { return this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; }); } getTableVariants = () => { return this.state.variants.map((value, index) => { return ( <Box key={index} separator="all"> <FormField label="Event" htmlFor="events" /> <Select name="events" options={this.state.events.filter((x) => { let a = _.contains(_.uniq(_.flatten(this.state.selectedEvents)), x); return !a; })} value={value._event_id} onChange={this.onEventAdd.bind(this, index)} multi={true} /> <FormField label="Description" htmlFor="tableTypedescription"> <input id="tableTypedescription" type="text" onChange={this.setDescrpiption.bind(this, index)} value={value.description}/> </FormField> <FormField label="Image"> {value.image ? <Box size={{ width: 'large' }} align="center" justify="center"> <div> <img src={value.image.preview} width="200" /> </div> <Box size={{ width: 'large' }}> <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/> </Box> </Box> : <Box align="center" justify="center" size={{ width: 'large' }}> <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop.bind(this, index)} accept='image/*'> Drop image here or click to select image to upload. </Dropzone> </Box> } <Button label="Remove" onClick={this.removeVariant.bind(this, index)} primary={true} float="right"/> </FormField> </Box>) }); // return this.state.variants.map( (item, index) => { // return <div key={index}> // <FormField label="Event" htmlFor="tableName"> // <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event||this.state.events[0]._event}> // { // this.state.events.map( (value, index) => { // return (<option key={index} value={value._event}>{value.name}</option>) // }) // } // </select> // </FormField> // <FormField label="Price(Php)" htmlFor="tablePrice"> // <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/> // </FormField> // <Footer pad={{"vertical": "small"}}> // <Heading align="center"> // <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} /> // <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} /> // </Heading> // </Footer> // </div>; // }); } onDrop(file) { this.setState({ image: file[0], isNewImage: true }); } onRemoveImage = () => { this.setState({ image: null, isNewImage: false }); } handleImageUpload(file, callback) { if(this.state.isNewImage) { let options = { url: CLOUDINARY_UPLOAD_URL, formData: { file: file } }; let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file); upload.end((err, response) => { if (err) { console.error(err); } if (response.body.secure_url !== '') { callback(null, response.body.secure_url) } else { callback(err, ''); } }); } else { callback(null, null); } } submitDelete (event) { event.preventDefault(); let delParams = { organisationId: this.state.organisationId, productId: this.state.tableId }; PartyBot.products.deleteProduct(delParams, (error, response, body) => { if(!error && response.statusCode == 200) { this.setState({ confirm: true }); } else { } }); } submitSave() { event.preventDefault(); this.handleImageUpload(this.state.image, (err, imageLink) => { if(err) { console.log(err); } else { let updateParams = { name: this.state.name, organisationId: this.state.organisationId, productId: this.state.tableId, venueId: this.state.venueId, table_type: this.state.tableTypeId, image: imageLink || this.state.prevImage.preview, prices: this.state.variants }; PartyBot.products.update(updateParams, (errors, response, body) => { if(response.statusCode == 200) { this.setState({ confirm: true }); } }); } }); } submitCreate = () => { event.preventDefault(); console.log(this.state); let params = {}; // this.handleImageUpload(this.state.image, (err, imageLink) => { // if(err) { // console.log(err); // } else { // let createParams = { // name: this.state.name, // organisationId: this.state.organisationId, // venueId: this.state.venueId, // tags: this.state.tags, // table_type: this.state.tableTypeId, // image: imageLink, // prices: this.state.variants // }; // PartyBot.products.create(createParams, (errors, response, body) => { // if(response.statusCode == 200) { // this.setState({ // confirm: true // }); // } // }); // } // }); } render() { const { router, } = this.context; const { isMobile, } = this.state; const { files, variants, } = this.state; return ( <div className={styles.container}> <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css"/> {this.state.confirm !== false ? <Layer align="center"> <Header> Table successfully created. </Header> <Section> <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/> </Section> </Layer> : null } <Box> {this.state.tableId !== null ? <Heading align="center"> Edit Table </Heading> : <Heading align="center"> Add Table </Heading> } </Box> <Box size={{ width: 'large' }} direction="row" justify="center" align="center" wrap={true} margin="small"> <Form> <FormFields> <fieldset> <FormField label="Venue" htmlFor="tableVenue"> <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}> {this.state.venues.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label="Table Type" htmlFor="tableType"> <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}> {this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label=" Name" htmlFor="tableName"> <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/> </FormField> { //Dynamic Price/Event Component this.getTableVariants() } <Button label="Add Event" primary={true} onClick={this.addVariant} /> </fieldset> </FormFields> <Footer pad={{"vertical": "medium"}}> { this.state.tableId !== null ? <Heading align="center"> <Button label="Save Changes" primary={true} onClick={this.submitSave} /> <Button label="Delete" primary={true} onClick={this.submitDelete} /> </Heading> : <Heading align="center"> <Button label="Create Table" primary={true} onClick={this.submitCreate} /> </Heading> } </Footer> </Form> </Box> </div> ); } } ManageTablesPage.contextTypes = { router: PropTypes.object.isRequired, }; export default cssModules(ManageTablesPage, styles);
JaySmartwave/palace-bot-sw
app/src/pages/ManageTablesPage/index.js
JavaScript
mit
17,890
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. I2db::Application.config.secret_token = 'f30c2c606ad3fe5dee77ef556c72975365eecdaf0d7487c8944e755182923e1b29d57c90c64b4015705a25c000d989975ff1dd08abb608ebebde302bc4991582'
panjunction/i2db
config/initializers/secret_token.rb
Ruby
mit
495
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Interfaces { public static class IApplicationCommandConstants { /// <summary> /// This application name represents default commands - when there is no /// command for specific application /// </summary> public const string DEFAULT_APPLICATION = "DEFAULT"; } /// <summary> /// Represents simple association that connects application, remote command and feedback to this command. /// If ApplicationName is null - this is a default behaviour. /// </summary> public interface IApplicationCommand { /// <summary> /// Name of the application /// </summary> string ApplicationName { get; } /// <summary> /// Remote command /// </summary> RemoteCommand RemoteCommand { get; } /// <summary> /// Command to be executed /// </summary> ICommand Command { get; } /// <summary> /// Executes associated command /// </summary> void Do(); } }
StanislavUshakov/ArduinoWindowsRemoteControl
Core/Interfaces/IApplicationCommand.cs
C#
mit
1,174
module HealthSeven::V2_3 class QryQ02 < ::HealthSeven::Message attribute :msh, Msh, position: "MSH", require: true attribute :qrd, Qrd, position: "QRD", require: true attribute :qrf, Qrf, position: "QRF" attribute :dsc, Dsc, position: "DSC" end end
niquola/health_seven
lib/health_seven/2.3/messages/qry_q02.rb
Ruby
mit
256
<?php namespace seregazhuk\tests\Bot\Providers; use seregazhuk\PinterestBot\Api\Providers\User; use seregazhuk\PinterestBot\Helpers\UrlBuilder; /** * Class ProfileSettingsTest * @method User getProvider() */ class ProfileSettingsTest extends ProviderBaseTest { /** @test */ public function it_retrieves_current_user_sessions_history() { $provider = $this->getProvider(); $provider->sessionsHistory(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_SESSIONS_HISTORY); } /** @test */ public function it_returns_list_of_available_locales() { $provider = $this->getProvider(); $provider->getLocales(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_LOCALES); } /** @test */ public function it_returns_list_of_available_countries() { $provider = $this->getProvider(); $provider->getCountries(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_COUNTRIES); } /** @test */ public function it_returns_list_of_available_account_types() { $provider = $this->getProvider(); $provider->getAccountTypes(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_ACCOUNT_TYPES); } protected function getProviderClass() { return User::class; } }
seregazhuk/php-pinterest-bot
tests/Bot/Providers/ProfileSettingsTest.php
PHP
mit
1,348
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Runtime.Internal.Transform { public static class CustomMarshallTransformations { public static long ConvertDateTimeToEpochMilliseconds(DateTime dateTime) { TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - Amazon.Util.AWSSDKUtils.EPOCH_START.Ticks); return (long)ts.TotalMilliseconds; } } }
Shogan/Unity3D.CharacterCreator
Assets/AWSSDK/src/Core/Amazon.Runtime/Internal/Transform/CustomMarshallTransformations.cs
C#
mit
1,054
<wicket:extend> <div class="row"> <div class="col-md-12"> <h3>Ergebnisse</h3> <br/> </div> </div> <div class="row"> <div class="col-md-12 result-border"> <div class="row"> <div class="col-md-12"> <h4> Erkannte Version: <wicket:container wicket:id="schemaVersion"/> </h4> </div> </div> <div wicket:id="schemvalidationOK"> <div class="row"> <div class="col-md-12"> <br/> <h4>Schemavalidierung</h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-success"> <p>Die gew&auml;hlte ebInterface Instanz entspricht den Vorgaben des ebInterface Schemas.</p> </div> </div> </div> <div wicket:id="schemvalidationNOK"> <div class="row"> <div class="col-md-12"> <br/> <h4>Schemavalidierung</h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-danger"> <p>Die gew&auml;hlte ebInterface Instanz entspricht nicht den Vorgaben des ebInterface Schemas.</p> <p> <strong>Fehlerdetails: </strong> <wicket:container wicket:id="schemaValidationError"/> </p> </div> </div> </div> <div wicket:id="signatureResultContainer"> <div class="row"> <div class="col-md-12"> <br/> <h4>Validierung der XML Signatur</h4> </div> </div> <div class="row"> <div class="col-md-12"> <h5>Signatur</h5> <div wicket:id="signatureDetails"/> <h5>Zertifikat:</h5> <div wicket:id="certificateDetails"/> <h5>Manifest:</h5> <div wicket:id="manifestDetails"/> </div> </div> </div> <div wicket:id="schematronOK"> <div class="row"> <div class="col-md-12"> <br/> <h4> Schematronvalidierung <wicket:container wicket:id="selectedSchematron"/> </h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-success"> <p>Die gew&auml;hlte ebInterface Instanz verletzt keine der Schematronregeln</p> </div> </div> </div> <div wicket:id="schematronNOK"> <div class="row"> <div class="col-md-12"> <br/> <h4> Schematronvalidierung <wicket:container wicket:id="selectedSchematron"/> </h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-danger"> <p>Die gew&auml;hlte ebInterface Instanz verletzt Schematron Regeln:</p> <div wicket:id="errorDetailsPanel"></div> </div> </div> </div> <div wicket:id="zugferdMappingLog"> <div class="row"> <div class="col-md-12"> <br/> <h4> ZUGFeRD-Konvertierung </h4> </div> </div> <div class="row"> <div wicket:id="zugferdMappingLogSuccess"> <div class="col-md-12 alert alert-success"> <div wicket:id="zugferdLogSuccessPanel"></div> </div> </div> <div wicket:id="zugferdMappingLogError"> <div class="col-md-12 alert alert-danger"> <div wicket:id="zugferdLogErrorPanel"></div> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <br/> <br/> <a class="btn btn-ghost btn-ghost--red" type="submit" wicket:id="linkZugferdXMLDownload">Download ZUGFeRD XML</a> <a class="btn btn-ghost btn-ghost--red" type="submit" wicket:id="linkZugferdPDFDownload">Download ZUGFeRD PDF</a> </div> <div class="col-md-12"> <br/> <br/> <a class="btn btn-ghost btn-ghost--red" wicket:id="returnLink">Neue Anfrage starten</a> <br/> <br/> <br/> <br/> </div> </div> </wicket:extend>
austriapro/ebinterface-web
ebinterface-web/src/main/java/at/ebinterface/validation/web/pages/resultpages/ResultPageZugferd.html
HTML
mit
5,589
package edu.isep.sixcolors.view.listener; import edu.isep.sixcolors.model.Config; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A popup window asking if the player want's to exit Six Colors */ public class Exit implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( null, Config.EXIT_MESSAGE, Config.EXIT_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE ); if (option == JOptionPane.YES_OPTION){ System.exit(0); } } }
ohhopi/six-couleurs
6Colors/src/edu/isep/sixcolors/view/listener/Exit.java
Java
mit
702
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.IO; using gView.Framework.Data; using gView.Framework.UI; namespace gView.Framework.UI.Dialogs { public partial class FormMetadata : Form { private Metadata _metadata; private object _metadataObject; public FormMetadata(XmlStream xmlStream, object metadataObject) { InitializeComponent(); _metadata = new Metadata(); _metadata.ReadMetadata(xmlStream); _metadataObject = metadataObject; } private void FormMetadata_Load(object sender, EventArgs e) { if (_metadata.Providers == null) return; foreach (IMetadataProvider provider in _metadata.Providers) { if (provider == null) continue; TabPage page = new TabPage(provider.Name); if (provider is IPropertyPage) { Control ctrl = ((IPropertyPage)provider).PropertyPage(null) as Control; if (ctrl != null) { page.Controls.Add(ctrl); ctrl.Dock = DockStyle.Fill; } if (ctrl is IMetadataObjectParameter) ((IMetadataObjectParameter)ctrl).MetadataObject = _metadataObject; } tabControl1.TabPages.Add(page); } } public XmlStream Stream { get { XmlStream stream = new XmlStream("Metadata"); if (_metadata != null) _metadata.WriteMetadata(stream); return stream; } } } }
jugstalt/gViewGisOS
gView.Explorer.UI/Framework/UI/Dialogs/FormMetadata.cs
C#
mit
1,880
eslint-plugin-extjs ============ [![npm](https://img.shields.io/npm/v/eslint-plugin-extjs.svg)](https://npmjs.org/package/eslint-plugin-extjs) [![Travis](https://img.shields.io/travis/burnnat/eslint-plugin-extjs.svg)](https://travis-ci.org/burnnat/eslint-plugin-extjs) [![Gemnasium](https://img.shields.io/gemnasium/burnnat/eslint-plugin-extjs.svg)](https://gemnasium.com/burnnat/eslint-plugin-extjs) ESLint rules for projects using the ExtJS framework. These rules are targeted for use with ExtJS 4.x. Pull requests for compatibility with 5.x are welcome! ## Rule Details ### ext-array-foreach The two main array iterator functions provided by ExtJS, [`Ext.Array.forEach`][ext-array-foreach] and [`Ext.Array.each`][ext-array-each], differ in that `each` provides extra functionality for early termination and reverse iteration. The `forEach` method, however, will delegate to the browser's native [`Array.forEach`][array-foreach] implementation where available, for performance. So, in situations where the extra features of `each` are not needed, `forEach` should be preferred. As the `forEach` documentation says: > [Ext.Array.forEach] will simply delegate to the native Array.prototype.forEach > method if supported. It doesn't support stopping the iteration by returning > false in the callback function like each. However, performance could be much > better in modern browsers comparing with each. The following patterns are considered warnings: Ext.Array.each( ['a', 'b'], function() { // do something } ); Ext.Array.each( ['a', 'b'], function() { // do something }, this, false ); The following patterns are not considered warnings: Ext.Array.forEach( ['a', 'b'], function() { // do something } ); Ext.Array.each( ['a', 'b'], function(item) { if (item === 'a') { return false; } } ); Ext.Array.each( ['a', 'b'], function() { // do something }, this, true ); ### ext-deps One problem with larger ExtJS projects is keeping the [`uses`][ext-uses] and [`requires`][ext-requires] configs for a class synchronized as its body changes over time and dependencies are added and removed. This rule checks that all external references within a particular class have a corresponding entry in the `uses` or `requires` config, and that there are no extraneous dependencies listed in the class configuration that are not referenced in the class body. The following patterns are considered warnings: Ext.define('App', { requires: ['Ext.panel.Panel'] }); Ext.define('App', { constructor: function() { this.panel = new Ext.panel.Panel(); } }); The following patterns are not considered warnings: Ext.define('App', { requires: ['Ext.panel.Panel'], constructor: function() { this.panel = new Ext.panel.Panel(); } }); Ext.define('App', { extend: 'Ext.panel.Panel' }); ### no-ext-create While using [`Ext.create`][ext-create] for instantiation has some benefits during development, mainly synchronous loading of missing classes, it remains slower than the `new` operator due to its extra overhead. For projects with properly configured [`uses`][ext-uses] and [`requires`][ext-requires] blocks, the extra features of `Ext.create` are not needed, so the `new` keyword should be preferred in cases where the class name is static. This is confirmed by Sencha employees, one of whom has [said][ext-create-forum]: > 'Ext.create' is slower than 'new'. Its chief benefit is for situations where > the class name is a dynamic value and 'new' is not an option. As long as the > 'requires' declarations are correct, the overhead of 'Ext.create' is simply > not needed. The following patterns are considered warnings: var panel = Ext.create('Ext.util.Something', { someConfig: true }); The following patterns are not considered warnings: var panel = new Ext.util.Something({ someConfig: true }); var panel = Ext.create(getDynamicClassName(), { config: true }); ### no-ext-multi-def Best practices for ExtJS 4 [dictate][ext-class-system] that each class definition be placed in its own file, and that the filename should correspond to the class being defined therein. This rule checks that there is no more than one top-level class definition included per file. The following patterns are considered warnings: // all in one file Ext.define('App.First', { // ... }); Ext.define('App.Second', { // ... }); The following patterns are not considered warnings: // file a Ext.define('App', { // class definition }); // file b Ext.define('App', { dynamicDefine: function() { Ext.define('Dynamic' + Ext.id(), { // class definition }); } }); [array-foreach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach [ext-array-foreach]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Array-method-forEach [ext-array-each]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Array-method-each [ext-class-system]: http://docs.sencha.com/extjs/4.2.1/#!/guide/class_system-section-2%29-source-files [ext-create]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext-method-create [ext-create-forum]: http://www.sencha.com/forum/showthread.php?166536-Ext.draw-Ext.create-usage-dropped-why&p=700522&viewfull=1#post700522 [ext-requires]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Class-cfg-requires [ext-uses]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Class-cfg-uses
burnnat/eslint-plugin-extjs
README.md
Markdown
mit
5,895
This is an example from `pst-solides3d` documentation. Compiled example ---------------- ![Example](sphere-cylinder.png)
MartinThoma/LaTeX-examples
pstricks/sphere-cylinder/README.md
Markdown
mit
122
namespace EgaViewer_v2 { partial class CustomPictureBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
ChainedLupine/BSAVEViewer
EgaViewer_v2/CustomPictureBox.Designer.cs
C#
mit
1,033
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2019 Marco Antognini ([email protected]), // Laurent Gomila ([email protected]) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #import <Cocoa/Cocoa.h> #import <SFML/Graphics.hpp> /* * NB: We need pointers for C++ objects fields in Obj-C interface ! * The recommended way is to use PIMPL idiom. * * It's elegant. Moreover, we do no constrain * other file including this one to be Obj-C++. */ struct SFMLmainWindow; @interface CocoaAppDelegate : NSObject <NSApplicationDelegate> { @private NSWindow* m_window; NSView* m_sfmlView; NSTextField* m_textField; SFMLmainWindow* m_mainWindow; NSTimer* m_renderTimer; BOOL m_visible; BOOL m_initialized; } @property (retain) IBOutlet NSWindow* window; @property (assign) IBOutlet NSView* sfmlView; @property (assign) IBOutlet NSTextField* textField; -(IBAction)colorChanged:(NSPopUpButton*)sender; -(IBAction)rotationChanged:(NSSlider*)sender; -(IBAction)visibleChanged:(NSButton*)sender; -(IBAction)textChanged:(NSTextField*)sender; -(IBAction)updateText:(NSButton*)sender; @end /* * This interface is used to prevent the system alert produced when the SFML view * has the focus and the user press a key. */ @interface SilentWindow : NSWindow -(void)keyDown:(NSEvent*)theEvent; @end
Senryoku/NESen
ext/SFML/examples/cocoa/CocoaAppDelegate.h
C
mit
2,396
namespace StudentClass { public class Course { public Course(string name) : this() { this.Name = name; } public Course() { } public string Name { get; private set; } public override string ToString() { return this.Name; } } }
TomaNikolov/TelerikAcademy
OOP/06.CommonTypeSystem/StudentClass/Course.cs
C#
mit
361
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "CDStructures.h" @interface IDEEditorDocumentValidatedUserInterfaceItem : NSObject <NSValidatedUserInterfaceItem> { SEL _action; long long _tag; } @property long long tag; // @synthesize tag=_tag; @property SEL action; // @synthesize action=_action; @end
kolinkrewinkel/Multiplex
Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEEditorDocumentValidatedUserInterfaceItem.h
C
mit
415
<!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 Thu Mar 02 16:51:04 PST 2017 --> <title>ResourceTableFactory</title> <meta name="date" content="2017-03-02"> <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="ResourceTableFactory"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </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/res/ResourceTable.Visitor.html" title="interface in org.robolectric.res"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/res/ResourceValueConverter.html" title="interface in org.robolectric.res"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/res/ResourceTableFactory.html" target="_top">Frames</a></li> <li><a href="ResourceTableFactory.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>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></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.res</div> <h2 title="Class ResourceTableFactory" class="title">Class ResourceTableFactory</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.robolectric.res.ResourceTableFactory</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">ResourceTableFactory</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#ResourceTableFactory--">ResourceTableFactory</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static <a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#newFrameworkResourceTable-org.robolectric.res.ResourcePath-">newFrameworkResourceTable</a></span>(<a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>&nbsp;resourcePath)</code> <div class="block">Builds an Android framework resource table in the "android" package space.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static <a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#newResourceTable-java.lang.String-org.robolectric.res.ResourcePath...-">newResourceTable</a></span>(java.lang.String&nbsp;packageName, <a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>...&nbsp;resourcePaths)</code> <div class="block">Creates an application resource table which can be constructed with multiple resources paths representing overlayed resource libraries.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ResourceTableFactory--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ResourceTableFactory</h4> <pre>public&nbsp;ResourceTableFactory()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="newFrameworkResourceTable-org.robolectric.res.ResourcePath-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>newFrameworkResourceTable</h4> <pre>public static&nbsp;<a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a>&nbsp;newFrameworkResourceTable(<a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>&nbsp;resourcePath)</pre> <div class="block">Builds an Android framework resource table in the "android" package space.</div> </li> </ul> <a name="newResourceTable-java.lang.String-org.robolectric.res.ResourcePath...-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>newResourceTable</h4> <pre>public static&nbsp;<a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a>&nbsp;newResourceTable(java.lang.String&nbsp;packageName, <a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>...&nbsp;resourcePaths)</pre> <div class="block">Creates an application resource table which can be constructed with multiple resources paths representing overlayed resource libraries.</div> </li> </ul> </li> </ul> </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> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/res/ResourceTable.Visitor.html" title="interface in org.robolectric.res"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/res/ResourceValueConverter.html" title="interface in org.robolectric.res"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/res/ResourceTableFactory.html" target="_top">Frames</a></li> <li><a href="ResourceTableFactory.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>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
robolectric/robolectric.github.io
javadoc/3.3/org/robolectric/res/ResourceTableFactory.html
HTML
mit
11,438
//Generated by the Argon Build System /*********************************************************************** Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "opus/silk/float/main_FLP.h" /* Autocorrelations for a warped frequency axis */ void silk_warped_autocorrelation_FLP( silk_float *corr, /* O Result [order + 1] */ const silk_float *input, /* I Input data to correlate */ const silk_float warping, /* I Warping coefficient */ const opus_int length, /* I Length of input */ const opus_int order /* I Correlation order (even) */ ) { opus_int n, i; double tmp1, tmp2; double state[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; double C[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; /* Order must be even */ silk_assert( ( order & 1 ) == 0 ); /* Loop over samples */ for( n = 0; n < length; n++ ) { tmp1 = input[ n ]; /* Loop over allpass sections */ for( i = 0; i < order; i += 2 ) { /* Output of allpass section */ tmp2 = state[ i ] + warping * ( state[ i + 1 ] - tmp1 ); state[ i ] = tmp1; C[ i ] += state[ 0 ] * tmp1; /* Output of allpass section */ tmp1 = state[ i + 1 ] + warping * ( state[ i + 2 ] - tmp2 ); state[ i + 1 ] = tmp2; C[ i + 1 ] += state[ 0 ] * tmp2; } state[ order ] = tmp1; C[ order ] += state[ 0 ] * tmp1; } /* Copy correlations in silk_float output format */ for( i = 0; i < order + 1; i++ ) { corr[ i ] = ( silk_float )C[ i ]; } }
skylersaleh/ArgonEngine
common/opus/silk/float/warped_autocorrelation_FLP.c
C
mit
3,596
export const ic_restaurant_menu_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm12.05-3.19c1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47c1.53.71 3.68.21 5.27-1.38z"},"children":[]}]};
wmira/react-icons-kit
src/md/ic_restaurant_menu_twotone.js
JavaScript
mit
464
# encoding: UTF-8 module DocuBot::LinkTree; end class DocuBot::LinkTree::Node attr_accessor :title, :link, :page, :parent def initialize( title=nil, link=nil, page=nil ) @title,@link,@page = title,link,page @children = [] end def anchor @link[/#(.+)/,1] end def file @link.sub(/#.+/,'') end def leaf? [email protected]?{ |node| node.page != @page } end # Add a new link underneath a link to its logical parent def add_to_link_hierarchy( title, link, page=nil ) node = DocuBot::LinkTree::Node.new( title, link, page ) parent_link = if node.anchor node.file elsif File.basename(link)=='index.html' File.dirname(File.dirname(link))/'index.html' else (File.dirname(link) / 'index.html') end #puts "Adding #{title.inspect} (#{link}) to hierarchy under #{parent_link}" parent = descendants.find{ |n| n.link==parent_link } || self parent << node end def <<( node ) node.parent = self @children << node end def []( child_index ) @children[child_index] end def children( parent_link=nil, &block ) if parent_link root = find( parent_link ) root ? root.children( &block ) : [] else @children end end def descendants ( @children + @children.map{ |child| child.descendants } ).flatten end def find( link ) # TODO: this is eminently cachable descendants.find{ |node| node.link==link } end def depth # Cached assuming no one is going to shuffle the nodes after placement @depth ||= ancestors.length end def ancestors # Cached assuming no one is going to shuffle the nodes after placement return @ancestors if @ancestors @ancestors = [] node = self @ancestors << node while node = node.parent @ancestors.reverse! end def to_s "#{@title} (#{@link}) - #{@page && @page.title}" end def to_txt( depth=0 ) indent = " "*depth [ indent+to_s, children.map{|kid|kid.to_txt(depth+1)} ].flatten.join("\n") end end class DocuBot::LinkTree::Root < DocuBot::LinkTree::Node undef_method :title undef_method :link undef_method :page attr_reader :bundle def initialize( bundle ) @bundle = bundle @children = [] end def <<( node ) node.parent = nil @children << node end def to_s "(Table of Contents)" end end
Phrogz/docubot
lib/docubot/link_tree.rb
Ruby
mit
2,249
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })
hudochenkov/stylelint
lib/rules/value-list-comma-space-before/__tests__/index.js
JavaScript
mit
5,084
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/favicon.ico"/> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/iosicon.png"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/images/photon/[email protected]" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="jquery.autotab-1.1b.js.html#">Sign Up &#187;</a> <a href="jquery.autotab-1.1b.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="jquery.autotab-1.1b.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
user-tony/photon-rails
lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/jquery.autotab-1.1b.js.html
HTML
mit
15,506
/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+bash+css-extras+git+php+php-extras+jsx+scss+twig+yaml&plugins=line-highlight+line-numbers */ /** * prism.js default theme for JavaScript, CSS and HTML * Based on dabblet (http://dabblet.com) * @author Lea Verou */ code[class*="language-"], pre[class*="language-"] { color: black; text-shadow: 0 1px white; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; line-height: 1.5; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; } pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { text-shadow: none; background: #b3d4fc; } pre[class*="language-"]::selection, pre[class*="language-"] ::selection, code[class*="language-"]::selection, code[class*="language-"] ::selection { text-shadow: none; background: #b3d4fc; } @media print { code[class*="language-"], pre[class*="language-"] { text-shadow: none; } } /* Code blocks */ pre[class*="language-"] { padding: 1em; margin: .5em 0; overflow: auto; } :not(pre) > code[class*="language-"], pre[class*="language-"] { background: #f5f2f0; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; } .token.comment, .token.prolog, .token.doctype, .token.cdata { color: slategray; } .token.punctuation { color: #999; } .namespace { opacity: .7; } .token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: #905; } .token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color: #690; } .token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color: #a67f59; background: hsla(0, 0%, 100%, .5); } .token.atrule, .token.attr-value, .token.keyword { color: #07a; } .token.function { color: #DD4A68; } .token.regex, .token.important, .token.variable { color: #e90; } .token.important, .token.bold { font-weight: bold; } .token.italic { font-style: italic; } .token.entity { cursor: help; } pre[data-line] { position: relative; padding: 1em 0 1em 3em; } .line-highlight { position: absolute; left: 0; right: 0; padding: inherit 0; margin-top: 1em; /* Same as .prism’s padding-top */ background: hsla(24, 20%, 50%,.08); background: -moz-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: -webkit-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: -o-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); pointer-events: none; line-height: inherit; white-space: pre; } .line-highlight:before, .line-highlight[data-end]:after { content: attr(data-start); position: absolute; top: .4em; left: .6em; min-width: 1em; padding: 0 .5em; background-color: hsla(24, 20%, 50%,.4); color: hsl(24, 20%, 95%); font: bold 65%/1.5 sans-serif; text-align: center; vertical-align: .3em; border-radius: 999px; text-shadow: none; box-shadow: 0 1px white; } .line-highlight[data-end]:after { content: attr(data-end); top: auto; bottom: .4em; } pre.line-numbers { position: relative; padding-left: 3.8em; counter-reset: linenumber; } pre.line-numbers > code { position: relative; } .line-numbers .line-numbers-rows { position: absolute; pointer-events: none; top: 0; font-size: 100%; left: -3.8em; width: 3em; /* works for line-numbers below 1000 lines */ letter-spacing: -1px; border-right: 1px solid #999; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .line-numbers-rows > span { pointer-events: none; display: block; counter-increment: linenumber; } .line-numbers-rows > span:before { content: counter(linenumber); color: #999; display: block; padding-right: 0.8em; text-align: right; }
wesruv/reveal.js
plugin/prism/prism.css
CSS
mit
4,266
# -*- coding: utf-8 -*- """ """ from datetime import datetime, timedelta import os from flask import request from flask import Flask import pytz import db from utils import get_remote_addr, get_location_data app = Flask(__name__) @app.route('/yo-water/', methods=['POST', 'GET']) def yowater(): payload = request.args if request.args else request.get_json(force=True) username = payload.get('username') reminder = db.reminders.find_one({'username': username}) reply_object = payload.get('reply') if reply_object is None: if db.reminders.find_one({'username': username}) is None: address = get_remote_addr(request) data = get_location_data(address) if not data: return 'Timezone needed' user_data = {'created': datetime.now(pytz.utc), 'username': username} if data.get('time_zone'): user_data.update({'timezone': data.get('time_zone')}) db.reminders.insert(user_data) return 'OK' else: reply_text = reply_object.get('text') if reply_text == u'Can\'t right now 😖': reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15) else: reminder['step'] += 1 reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60) reminder['last_reply_date'] = datetime.now(pytz.utc) db.reminders.update({'username': username}, reminder) db.replies.insert({'username': username, 'created': datetime.now(pytz.utc), 'reply': reply_text}) return 'OK' if __name__ == "__main__": app.debug = True app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
YoApp/yo-water-tracker
server.py
Python
mit
1,851
<html> <head> <title>Terry George's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Terry George's panel show appearances</h1> <p>Terry George has appeared in <span class="total">1</span> episodes between 2009-2009. <a href="http://www.imdb.com/name/nm313623">Terry George on IMDB</a>. <a href="https://en.wikipedia.org/wiki/Terry_George">Terry George on Wikipedia</a>.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2009</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2009-06-26</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> </ol> </div> </body> </html>
slowe/panelshows
people/ne3kzguz.html
HTML
mit
1,049
{% extends "base.html" %} {% block title %} new statement {% endblock title %} {% load crispy_forms_tags %} {% block content %} <h1>Create a new {{ model_name_lower }}!</h1> {% if request.user.is_anonymous %} Only signed-in users can create {{ model_name_lower }}s! {% else %} {% crispy form form.helper %} {% endif %} {% endblock content %} {% block javascript %} {{ block.super }} {{ form.media }} {% endblock javascript %}
amstart/demo
demoslogic/templates/blockobjects/new.html
HTML
mit
428
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() import views urlpatterns = patterns('', url(r'^pis', views.pis), url(r'^words', views.words, { 'titles': False }), url(r'^projects', views.projects), url(r'^posters', views.posters), url(r'^posterpresenters', views.posterpresenters), url(r'^pigraph', views.pigraph), url(r'^institutions', views.institutions), url(r'^institution/(?P<institutionid>\d+)', views.institution), url(r'^profile/$', views.profile), url(r'^schedule/(?P<email>\S+)', views.schedule), url(r'^ratemeeting/(?P<rmid>\d+)/(?P<email>\S+)', views.ratemeeting), url(r'^submitrating/(?P<rmid>\d+)/(?P<email>\S+)', views.submitrating), url(r'^feedback/(?P<email>\S+)', views.after), url(r'^breakouts', views.breakouts), url(r'^breakout/(?P<bid>\d+)', views.breakout), url(r'^about', views.about), url(r'^buginfo', views.buginfo), url(r'^allrms', views.allrms), url(r'^allratings', views.allratings), url(r'^login', views.login), url(r'^logout', views.logout), url(r'^edit_home_page', views.edit_home_page), url(r'^pi/(?P<userid>\d+)', views.pi), # , name = 'pi'), url(r'^pi/(?P<email>\S+)', views.piEmail), # , name = 'pi'), url(r'^project/(?P<abstractid>\S+)', views.project, name = 'project'), url(r'^scope=(?P<scope>\w+)/(?P<url>.+)$', views.set_scope), url(r'^active=(?P<active>\d)/(?P<url>.+)$', views.set_active), url(r'^admin/', include(admin.site.urls)), (r'', include('django_browserid.urls')), url(r'^$', views.index, name = 'index'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
ctames/conference-host
webApp/urls.py
Python
mit
1,850
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; t.throws(function() { interval.fields[field].push(-1); }, /Cannot add property .*?, object is not extensible/, field + ' is frozen'); delete interval.fields[field]; }); interval.fields.dummy = []; t.same(interval.fields.dummy, undefined, 'Fields is frozen'); t.same(interval.fields.second, [0], 'Second matches'); t.same(interval.fields.minute, [1], 'Minute matches'); t.same(interval.fields.hour, [2], 'Hour matches'); t.same(interval.fields.dayOfMonth, [3], 'Day of month matches'); t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches'); t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches'); } catch (err) { t.error(err, 'Interval parse error'); } t.end(); });
harrisiirak/cron-parser
test/fields.js
JavaScript
mit
1,093
<!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/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>Boost::context future: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Boost::context future </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="class_future.html">Future</a></li><li class="navelem"><a class="el" href="struct_future_1_1_already_fulfilled.html">AlreadyFulfilled</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>what</b>() const noexcept (defined in <a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a>)</td><td class="entry"><a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Jul 7 2015 13:05:59 for Boost::context future by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
disnesquick/coopfuture
doc/struct_future_1_1_already_fulfilled-members.html
HTML
mit
4,799
<?php use Illuminate\Database\Seeder; // composer require laracasts/testdummy use Laracasts\TestDummy\Factory as TestDummy; class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => 'system', 'email' => '[email protected]', 'password' => bcrypt('system'), ]); } }
Ranthalion/LevelUp
database/seeds/UsersTableSeeder.php
PHP
mit
378
package br.eti.qisolucoes.contactcloud.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").authenticated() .antMatchers("/theme/**", "/plugins/**", "/page/**", "/", "/usuario/form", "/usuario/salvar").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/login").loginPage("/login").permitAll().defaultSuccessUrl("/agenda/abrir", true) .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); auth.userDetailsService(userDetailsService); } }
nosered/contact-cloud
src/main/java/br/eti/qisolucoes/contactcloud/config/SecurityConfig.java
Java
mit
1,557
package de.chandre.admintool.security.dbuser.repo; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import de.chandre.admintool.security.dbuser.domain.ATRole; /** * * @author André * @since 1.1.7 */ @Repository public interface RoleRepository extends JpaRepository<ATRole, String> { ATRole findByName(String name); @Query("SELECT r.name FROM ATRole r") List<String> findAllRoleNames(); List<ATRole> findByNameIn(Set<String> ids); List<ATRole> findByIdIn(Set<String> ids); void deleteByName(String name); }
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/repo/RoleRepository.java
Java
mit
724
#! /bin/bash defaults write com.apple.finder AppleShowAllFiles FALSE killall Finder
worp1900/niftySnippets
console/bash/mac/hideHiddenFilesInFinder.sh
Shell
mit
84
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, fillIn } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | inputs/text-input', function (hooks) { setupRenderingTest(hooks); hooks.beforeEach(async function () { this.config = { value: '123 hello', name: 'myInput', disabled: false, autocomplete: 'name', texts: { placeholder: 'Your name', }, }; await render(hbs`<Inputs::TextInput @config={{config}} />`); }); test('it renders', async function (assert) { assert.dom('textarea').hasAttribute('name', 'myInput'); assert.dom('textarea').hasAttribute('autocomplete', 'name'); assert.dom('textarea').hasAttribute('placeholder', 'Your name'); }); test('it updates value', async function (assert) { assert.dom('textarea').hasValue('123 hello'); this.set('config.value', 'hello?'); assert.dom('textarea').hasValue('hello?'); await fillIn('textarea', 'bye!'); assert.equal(this.config.value, 'bye!'); }); test('it can be disabled', async function (assert) { assert.dom('textarea').isNotDisabled(); this.set('config.disabled', true); assert.dom('textarea').isDisabled(); }); test('it supports presence validations', async function (assert) { assert.dom('textarea').doesNotHaveAttribute('required'); this.set('config.validations', { required: true }); assert.dom('textarea').hasAttribute('required'); }); });
nibynic/ember-form-builder
tests/integration/components/inputs/text-input-test.js
JavaScript
mit
1,560
#!/usr/bin/env node var listCommand = []; require('./listCommand')(listCommand) var logDetail = (str) => { console.log(' > '+str); } var printHelp = () => { var txtHelp = ""; var h = ' '; var t = ' '; txtHelp += "\n"+h+"Usage : rider [command] \n"; txtHelp += "\n"+h+"Command List : \n"; var maxText = 0; if(listCommand == undefined){ logDetail("not found help detail"); return; } Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; if(maxText < item.name.length+item.params.length) maxText = item.name.length+item.params.length+4; }); var maxT = Math.ceil(maxText/4); Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; var x = (item.name.length+item.params.length+4)/4; x = Math.ceil(x); var space = '\t'; for (var i = 0; i < maxT-x-1; i++) { space += '\t'; } var txt = ""; if(item.params.length > 0){ space += '\t'; txt = '\t'+item.name +" [" +item.params+"] " + space +item.desc+"\n"; }else{ txt = '\t'+item.name + space +item.desc+"\n"; } txtHelp +=txt; txtHelp +"\n"; }); console.log(txtHelp); process.exit(0); } var parseParams = (params, cb) => { if(params.length < 3){ return cb(true); } cb(false); } var checkCommand = (cmd) => { var foundCmd = false; Object.keys(listCommand).forEach((keyName) => { if(keyName == cmd){ foundCmd = true; return; } }); return !foundCmd; } var runCommand = (params, cb) => { var opt = params[2]; var objRun = listCommand[opt]; if(objRun != undefined && objRun != null){ objRun.runCommand(params, cb); } } var main = () => { console.log(">> Rider ... "); var params = process.argv; parseParams(params, (err) => { if(err){ printHelp(); return; } var opt = params[2]; if(opt == "-h" || opt == "--help"){ printHelp(); return; } if(checkCommand(opt)){ printHelp(); return; } runCommand(params, () => { process.exit(0); }); }); } // -- call main function -- main();
khajer/rider.js
cli.js
JavaScript
mit
2,029
<?php /* * Arabian language */ $lang = [ 'albums' => 'Альбомы' ];
Speennaker/tanyaprykhodko
application/language/arabian/main_lang.php
PHP
mit
78
// // RSAEncryptor.h // iOSProject // // Created by Alpha on 2017/6/12. // Copyright © 2017年 STT. All rights reserved. // #import <Foundation/Foundation.h> @interface RSAEncryptor : NSObject /** * 加密方法 * * @param str 需要加密的字符串 * @param path '.der'格式的公钥文件路径 */ + (NSString *)encryptString:(NSString *)str publicKeyWithContentsOfFile:(NSString *)path; /** * 解密方法 * * @param str 需要解密的字符串 * @param path '.p12'格式的私钥文件路径 * @param password 私钥文件密码 */ + (NSString *)decryptString:(NSString *)str privateKeyWithContentsOfFile:(NSString *)path password:(NSString *)password; /** * 加密方法 * * @param str 需要加密的字符串 * @param pubKey 公钥字符串 */ + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey; /** * 解密方法 * * @param str 需要解密的字符串 * @param privKey 私钥字符串 */ + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey; @end
STT-Ocean/iOSProject
iOSProject/iOSProject/iOSProject/Others/Cers/RSAEncryptor.h
C
mit
1,075
# Digital ecosystem dashboard This dashboard was technically and graphically made by [Sebcreation](http://www.sebcreation.com) ## Requirements This application requires [Node JS](http://nodejs.org/), the streaming build system [gulp.js](http://gulpjs.com/) and the [compass](http://compass-style.org/) ruby gem. After installing Node JS, gulp.js can easily be installed via Terminal : ``` $ npm install -g gulp ``` Compass can easily be installed via Terminal : ``` $ gem update --system $ gem install compass ``` Please refer the [user guide](http://compass-style.org/install/)
sebcreation/digital-ecosystem
README.md
Markdown
mit
590
<?php namespace Hal\Controller; /* * File: /app/code/core/system/base_controller.php * Purpose: Base class from which all controllers extend */ class Base_Controller { protected $action; public $cache; public $config; private $controller; private $controller_class; private $controller_filename; protected $core; protected $cron; protected $data; protected $db; protected $dispatcher; public $load; public $log; protected $model; protected $param; protected $route; public $session; public $template; public $toolbox; public $view; public function __construct($app) { $this->config = $app['config']; $this->core = $app; $this->cron = $app['cron']; $this->db = $app['database']; $this->dispatcher = $app['dispatcher']; $this->event = $app['event']; $this->load = $app['load']; $this->log = $app['log']; $this->model = $app['system_model']; $this->orm = $app['orm']; $this->route = $app['router']; $this->session = $app['session']; $this->template = $app['template']; $this->toolbox = $app['toolbox']; } public final function parse() { # Define child controller extending this class $this->controller = $this->route->controller; # The class name contained inside child controller $this->controller_class = $this->controller.'_Controller'; # File name of child controller $this->controller_filename = ucwords($this->controller_class).'.php'; # Action being requested from child controller $this->action = $this->route->action; $action = trim(strtolower($this->route->action)); # URL parameters $this->param = $this->route->param; # Pass controller information to view files; used for debugger $this->template->assign('controller', $this->controller); $this->template->assign('controller_class', $this->controller_class); $this->template->assign('controller_filename', $this->controller_filename); $this->template->assign('action', $action); # Admin, Public and Override classes $_admin_class = $this->controller_class; $_web_class = "\Web\Controller\\".$this->controller_class; $_override_class = "\Hal\ControllerOverride\\".$this->controller_class; # Check if the admin controller is being requested if ($this->controller == $this->config->setting('admin_controller') && is_readable(CORE_PATH.'controllers/'.$this->controller_filename) && $this->controller_filename) { # File was found and has proper file permissions require_once CORE_PATH.'controllers/'.$this->controller_filename; if (class_exists($_admin_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $this->controller_class($this->core); if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action $this->template->assign('controller_path', CORE_PATH.'controllers/'.$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } else { # Controller file exists, but class name # is not formatted / spelled properly $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } # First search for requested controller file in override directory elseif (is_readable(PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename) && class_exists($_web_class)) { # File was found and has proper file permissions require_once PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename; if (class_exists($_override_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $_override_class($this->core); // if (!is_subclass_of($__instantiate_class, $_web_class)) // { // echo $_override_class . ' DOES NOT EXTEND ' . $_web_class; // } if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action $this->template->assign('controller_path', PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } else { # Controller file exists, but class name # is not formatted / spelled properly $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } else { if (!is_readable($this->config->setting('controllers_path').$this->controller_filename)) { # Controller file does not exist, or # does not have read permissions if ($this->config->setting('debug_mode') === 'OFF' { return $this->redirect('error/_404'); } else { $controller = new \Web\Controller\Error_Controller($this->core); $controller->controller(); } } # Search for requested controller file in public directory if (is_readable($this->config->setting('controllers_path').$this->controller_filename) && $this->controller_filename) { # File was found and has proper file permissions require_once $this->config->setting('controllers_path').$this->controller_filename; if (class_exists($_web_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $_web_class($this->core); if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('controller_path', $this->config->setting('controllers_path').$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } } else { # Controller file exists, but class name is not formatted / spelled properly if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } } else { # Controller file does not exist, or # does not have read permissions if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('content', 'error/controller.tpl'); } } } } public function model($model) { return $this->load->model("$model"); } public function redirect($url) { if ($url === 'http_referer') { return header('Location: '.$_SERVER['HTTP_REFERER']); exit; } return header('Location: '.BASE_URL.$url); } public function session() { return $this->toolbox('session'); } public function toolbox($helper) { # Load a Toolbox helper return $this->toolbox["$helper"]; } }
arout/diamondphp
app/code/core/system/controllers/Base_Controller.php
PHP
mit
6,878
--- title: While We're At It category: The Guts of FP order: 1 --- You won't get very far in most imperative languages without the humble `while` loop or one of it's variants such as `for`. Even though for loops are more commonly used, they are just syntactic sugar on while, so let's start there: {% highlight javascript %} let i = 0; while (i < someEndValue) { // do something interesting here i++; } {% endhighlight %} While it's possible for `someEndValue` to be anything it's extremely common for it to be the length of a collection. {% highlight javascript %} let i = 0; while (i < someCollection.length) { // do something with someCollection[i] here i++; } {% endhighlight %} This immediately brings up a problem, if we want to avoid mutating state, what useful thing could we do in the body of the while loop? While is not an expression, so we can't be returning a value. While demands that we mutate something inside the body, even if we are creating a new value each loop we're still rebinding the variable to a new value. This is as close to no-mutation as we can accomplish with while, but we're still clobbering that outer variable each time. {% highlight javascript %} let numbers = []; let i = 0; while (i < 5) { numbers.push(i); i++; } {% endhighlight %} Furthermore, since `while` is not an expression, there is no way to really combine it with anything else. This is a concept known as composition and we'll return to it later. Fortunately there's another construct that can be used to accomplish a looping structure but allows you to return a value at the end and doesn't need to mutate anything or reassign variables. This means you can use `const someValue = doTheThing(...)` or even `const someValue = doTheThing(...).andThen(...)`. You may have never thought about `recursion` this way, but it's true! > Recursion is the ability of a function to be applied to an argument inside itself. If done wrong this leads to an infinite chain of application in much the same way that forgetting the `i++` at the end of a `while` is an infinite loop. {% highlight javascript %} const populateArray = (numbers, i, endValue) => i < endValue ? populateArray([...numbers, i], i + 1, endValue) : numbers; const result = populateArray([], 0, 5); {% endhighlight %} The process of running this function would look like this. {% highlight javascript %} numbers i | | v v populateArray([], 0, 5) numbers i | | v v populateArray([0], 1, 5) numbers i | | v v populateArray([0, 1], 2, 5) numbers i | | v v populateArray([0, 1, 2], 3, 5) numbers i | | v v populateArray([0, 1, 2, 3], 4, 5) numbers i | | v v populateArray([0, 1, 2, 3, 4], 5, 5) {% endhighlight %} When we run `populateArray`, 0 is less than 5, so we recursively call `populateArray` again, but this time with `[0]` and `1` for the `numbers` and `i` arguments. This continues down until `i` is 5 at which point we return the current value of numbers which is `[0, 1, 2, 3, 4]`. This value is in turn returned by each prior `populateArray` and the final result is thus `[0, 1, 2, 3, 4]`. This may look more complex than the `while` example if you're not used to thinking recursively and using it in this manner. Hopefully though you see much of the operations we're performing are the same. - `i < 5` is the same as `i < endValue` - `numbers.push(i)` and `[...numbers, i]` are both adding an element to the array - `i++` and `i + 1` both move the counter up one Everything we could express in a while loop we can do via recursion and not need to mutate an outer variable along the way. With that said though, you probably don't write many while loops given there are constructs that more directly do what you want such as for. Let's look at a few common cases. #### Filter: reject unwanted values {% highlight javascript %} const itemsToKeep = []; for (var i = 0; i < collection.length; i++) { if (someCriteria(collection[i])) { itemsToKeep.push(collection[i]); } } {% endhighlight %} #### Map: transform values {% highlight javascript %} const newCollection = []; for (var i = 0; i < collection.length; i++) { newCollection.push( someOperation(collection[i]) ); } {% endhighlight %} If your language supports a `foreach` style iteration (`for x of y` in ES6) where the value itself is bound to a local variable instead of using an index, these could both be re-written using that. Both these cases have a striking amount of similarity. Hopefully you've noticed this at some point as well. In fact, almost every line of each of these two cases are the same - `const itemsToKeep = []` is `const newCollection = []` - `for (var i = 0; i < collection.length; i++) {` is identical for both - `itemsToKeep.push` is `newCollection.push` The only difference is that in the first case the item is conditionally added, and in the second, the item is processed before being added. This is the fundamental difference between the two operations, one filters out elements, the other maps one value to another. **_If the "when and what to insert" decision could be parameterized, then the rest of the code could be written once and not every time we need this construct._** ### Higher Order Functions To accomplish this feat we would need a function that could be parameterized by another function. {% highlight javascript %} const doThing = (someFunction, someValue) => someFunction(someValue); {% endhighlight %} What are `someFunction` and `someValue`? No idea! Here's a function that receives _another_ function as an argument and can use it to produce a return value. We can go in the opposite direction as well. {% highlight javascript %} const makeFunction = () => (someNumber) => someNumber + 1; const newFunction = makeFunction(); newFunction(5); // 6 {% endhighlight %} This is not particularly interesting, in fact a function written like this could be converted back to a constant like you're used to. {% highlight javascript %} const newFunction = (someNumber) => someNumber + 1; {% endhighlight %} The interesting part is simply that functions are just values and can be returned like any other value, although this is not particularly common in JavaScript. The first function does not need to have zero arguments, in fact it's often useful for it to have arguments since the function that is returned can see and reference those variables. {% highlight javascript %} const makeGreeting = (message) => (name) => message + " " + name; const jolly = makeGreeting("Hello there"); const grouchy = makeGreeting("Get off my lawn!"); jolly("Tina"); // "Hello there Tina" grouchy("Max"); // "Get off my lawn! Max" // we don't need to create an intermediate function makeGreeting("Look ma, no funtion, right")("Sam"); // "Look ma, no funtion, right Sam" {% endhighlight %} The inner returned functions can also be written on a single line {% highlight javascript %} const makeGreeting = (message) => (name) => message + " " + name; {% endhighlight %} > A function that receives another function as an argument, or returns a new function as a return value is known as a **higher order function**. This may not seem very useful at first, but let's apply the idea to the problem from before and see how this both helps eliminates the need for mutation of a variable, and solves a broad class of problems, all at once. ### Fold and Friends For any while loop of the shape with the form: - Initialize a new collection - Iterate over existing collection - Insert values into new collection there is a generalized solution known commonly as `fold`, `reduce`, or `aggregate`. general shape of: {% highlight javascript %} const newValue = fold(thingToDoWithEachNewElement, initialNewValue, collectionToIterateOver); {% endhighlight %} The `thingToDoWithEachNewElement` is a function that takes the working `initialNewValue` and combines it with an element from `collectionToIterateOver`. This might be done by doing a if check in the case of a filter type operation, or by running the element through a function first as in the case of the map type operation. Or it might be something unrelated to collections in the case of a sum type operation. #### Filter type operation {% highlight javascript %} const filterFn = (element, collection) => someCondition(element) ? [...collection, element] : collection; const someCondition = (x) => x > 5; filterFn(7, [4, 5]) // [4, 5, 7] filterFn(4, [4, 5]) // [4, 5] {% endhighlight %} #### Map type operation {% highlight javascript %} const mapFn = (element, collection) => [...collection, someOperation(element)]; const someOperation = (str) => str + "!"; mapFn("hi", []) // ["hi!"] mapFn("excited", ["I", "am"]) // ["I", "am", "excited!"] {% endhighlight %} And we could use these functions with `fold` in a more concrete setting: {% highlight javascript %} const filteredValues = fold(filterFn, [], [3, 4, 5, 6]); const transformedValues = fold(mapFn, [], ["programming", "is", "fun"]); {% endhighlight %} > This is generally the point where people's eyes glaze over as we begin to get a bit more abstract. From here on out, we will be working with concepts you likely have never encountered. This is genuinely hard to get at first, but the "different paradigm" type of understanding is on the other side, so hang in there! ### Exercise Ready for a challenge? Open `exercises/fold.js` in your editor and implement the `fold` function that can operate on arrays. Do this either using a for loop or using recursion (or try both). It matters much less how something like `fold` is implemented "under the hood" as long as the interface is pure. To test your changes, run `npm run -s fold` from the `exercises` directory. > Ask questions! ## [Next](/3-guts-of-fp/type-it-out)
wayfinderio/intro-to-fp
_docs/3-guts-of-fp/while-we-are-at-it.md
Markdown
mit
10,427
import { BaseController } from "./BaseController"; import { Route } from "./BaseController"; import * as loadHtml from "./HtmlLoader"; export class MainController extends BaseController { main = (): void => { loadHtml.load(this.requestData, '/views/index.html', {}); } routes: Route[] = [ new Route("/", this.main) ]; }
Kasperki/NodeBlog
blog/MainController.ts
TypeScript
mit
357
import React from "react"; import $ from "jquery"; import "bootstrap/dist/js/bootstrap.min"; import "jquery-ui/ui/widgets/datepicker"; import { postFulltimeEmployer, postParttimeEmployer, putFullTimeEmployer, putParttimeEmployer } from "../actions/PostData"; import DropDownBtn from "../components/DropDownBtn"; import {parseBirthdayForServer} from "../utils/Utils"; import {connect} from "react-redux"; class ModalEmployer extends React.Component { componentWillReceiveProps = (nextProps) => { if (nextProps.data) { this.setState(nextProps.data); if (nextProps.data.day_salary) { this.setState({ type: 'congNhat' }) } else { this.setState({ type: 'bienChe' }) } } if (nextProps.data == null) { this.setState(this.emptyObject) } } emptyObject = { "salary_level": "", "name": "", "month_salary": "", "phone": "", "birthday": "", "allowance": "", "department_id": this.props.departments.length > 0 ? this.props.departments[0].id : "", day_salary: "", } onClickSave = () => { let data = { "name": this.state.name, "phone": this.state.phone, "birthday": parseBirthdayForServer(this.state.birthday), "department_id": this.state.department_id, } if (this.state.type === "bienChe") { data.salary_level = this.state.salary_level; data.month_salary = this.state.month_salary; data.allowance = this.state.allowance; if (this.props.data) { putFullTimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postFulltimeEmployer(data, this.props.fetchEmployers); } } if (this.state.type === "congNhat") { data.day_salary = this.state.day_salary; if (this.props.data) { putParttimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postParttimeEmployer(data, this.props.fetchEmployers) } } $('#create').modal('toggle'); } constructor(props) { super(props); this.state = Object.assign(this.emptyObject, {type: null}) } onChangeText = (event) => { this.setState({ [event.target.name]: event.target.value }) } clickType = (type) => { this.setState({ type }) } componentDidMount = () => { $('#datepicker').datepicker({ uiLibrary: 'bootstrap4', iconsLibrary: 'fontawesome', onSelect: (dateText) => { this.setState({ birthday: dateText }) }, dateFormat: 'dd/mm/yy' }); } renderExtraForm = () => { if (this.state.type) { switch (this.state.type) { case "bienChe": return <div> <label htmlFor="id">Lương tháng</label> <div className="input-group"> <input onChange={this.onChangeText} name="month_salary" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.month_salary}/> </div> <label htmlFor="id">Bậc lương</label> <div className="input-group"> <input onChange={this.onChangeText} name="salary_level" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.salary_level}/> </div> <label htmlFor="id">Phụ cấp</label> <div className="input-group"> <input onChange={this.onChangeText} name="allowance" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.allowance}/> </div> </div> break; case "congNhat": return <div> <label htmlFor="id">Lương ngày</label> <div className="input-group"> <input name="day_salary" value={this.state.day_salary} onChange={this.onChangeText} type="text" className="form-control" id="id" aria-describedby="basic-addon3"/> </div> </div> break; } } } onSelectDepartment = (item) => { this.setState({ department_id: item.id }) } renderDropDownBtn = () => { if (this.props.departments.length > 0) { return ( <DropDownBtn onChange={this.onSelectDepartment} default data={this.props.departments}></DropDownBtn> ) } } render() { return ( <div className="modal fade" id="create" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Thêm nhân viên</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <label htmlFor="name">Tên nhân viên</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.name} name="name" type="text" className="form-control" id="name" aria-describedby="basic-addon3"/> </div> <label htmlFor="datepicker">Ngày tháng năm sinh</label> <div className="input-group date" data-provide="datepicker"> <input onClick={this.onChangeText} onChange={this.onChangeText} value={this.state.birthday} name="birthday" type="text" className="form-control" id="datepicker"/> </div> <label htmlFor="phone">Số điện thoại</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.phone} name="phone" type="text" className="form-control" id="phone" aria-describedby="basic-addon3"/> </div> <div className="btn-group"> <label htmlFor="name" className="margin-R10">Chọn phòng ban</label> {this.renderDropDownBtn()} </div> <div className="btn-group btn-middle align-middle"> { (() => { if (this.props.data) { if (this.props.data.day_salary === null) { return (<button className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>) } else { return ( <button className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button> ) } } else { let arr = []; arr.push(<button onClick={this.clickType.bind(this, "bienChe")} className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>); arr.push(<button onClick={this.clickType.bind(this, "congNhat")} className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button>); return arr; } })() } </div> { this.renderExtraForm() } </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal">Hủy</button> <button onClick={this.onClickSave} type="button" className="btn btn-primary">Lưu</button> </div> </div> </div> </div> ) } } const mapStateToProps = state => { return { departments: state.app.departments } } export default connect(mapStateToProps)(ModalEmployer)
liemnt/quanlynv
quanlynhanvien/src/components/ModalEmployer.js
JavaScript
mit
10,454
require 'spec_helper' describe Character do before do @character = Character.new(name: "Walder Frey", page: 'index.html') end subject { @character} it { should respond_to(:name)} it { should respond_to(:icon)} it { should respond_to(:page)} it { should respond_to(:degrees)} it { should respond_to(:all_relationships)} it { should respond_to(:children)} it { should respond_to(:parents)} it { should respond_to(:relationships)} it { should respond_to(:reverse_relationships)} it { should be_valid} describe "when name is not present" do before {@character.name = nil} it {should_not be_valid} end describe "when page is not present" do before {@character.page = nil} it {should_not be_valid} end describe "character with page already exists" do before do character_with_same_page = @character.dup character_with_same_page.page.upcase! character_with_same_page.save end it { should_not be_valid} end describe "character relationships" do before{ @character.save} let!(:child_character) do FactoryGirl.create(:character) end let!(:relationship) { @character.relationships.build(:child_id => child_character.id)} it "should display for both" do expect(@character.all_relationships.to_a).to eq child_character.all_relationships.to_a end it "should destroy relationships" do relationships = @character.relationships.to_a @character.destroy expect(relationships).not_to be_empty relationships.each do |relationship| expect(Relationship.where(:id => relationship.id)).to be_empty end end end end
thatguyandy27/DegreesOfWalderFrey
degrees_of_frey/spec/models/character_spec.rb
Ruby
mit
1,683
package net.sf.jabref.gui.util; import javafx.concurrent.Task; /** * An object that executes submitted {@link Task}s. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, thread pooling, etc. */ public interface TaskExecutor { /** * Runs the given task. * * @param task the task to run * @param <V> type of return value of the task */ <V> void execute(BackgroundTask<V> task); }
Mr-DLib/jabref
src/main/java/net/sf/jabref/gui/util/TaskExecutor.java
Java
mit
528
require 'test_helper' class Test45sHelperTest < ActionView::TestCase end
thejhubbs/permissionary
test/dummy/test/helpers/test45s_helper_test.rb
Ruby
mit
74
--- author: generalchoa comments: true date: 2014-01-31 23:22:32+00:00 layout: post slug: week13-day35b-beefmode title: Week13 - Day35B - Beefmode wordpress_id: 1429 categories: - B - StrongLifts tags: - agile 8 - deadlift - dips - incline db press - plank - preacher curls - push-up - seated db curls - shoulder shocker - squat - standing bb curls --- **Weight: **185 lbs ?? **Duration**:  11:45am - 1:02pm ~ 1hr. 17min. Time recorded is from when I started the pre-workout stretches until I started my post-workout stretches.  The Shoulder Shocker felt hugely improved, weights felt light for the first 2 sets.  Usually, I'm dying at the end of the second set.  Weight on the scale was at 187 this morning!  Getting into freshly washed and dried jeans was pretty tough, haha.  Legs are getting too beefy from all this squatting. **Squats:  **3x5xBar + 5x115 + 3x145 + 2x165 + 1x185 + 3x5x205 Went down pretty slow to control the bar and prevent tweaking the back.  This makes it quite a bit harder since I'm increasing time under the bar.  These are getting pretty heavy.  Getting close to the magical 225, 2-plate squat.  I think I may incorporate some back off sets, very similar to Madcow's heavy day scheme or Wendler's Boring But Big accessory. **Seated Plate Raises:  **3x10x25 **Seated Lateral Raise: **3x10x12 **Seated DB Shrug + Clean + Half Press:  **3x10x12 Able to get to the end of the second set without feeling dead.  Felt a huge improvement here.  Doing the cleaning movement, I'm using a more explosive pull to clean the dumbbells up instead just using all shoulders.  It is a clean after all. **Deadlift:  **5x135 + 3x165 + 2x185 + 1x215 + 1x240 + 5x265 Supinated left, regular right.  Pretty heavy, kept the bar glued to my shins.  Not sure if I was rounding, but my low back wasn't killing me afterwards. **Accessories: **Preacher BB Curls:  **14x50** Incline DB Press:  **10x50** Standing EZ Bar Curls:  10x40 Dips:  **12**/4/4 Seated DB Curls:  **10x30** Pushups:  10/10/8 Cranked out some extra reps on the 50lb preacher.  I think once I get to 18+ reps on the 50, I'm going to jump up.  Went up to 50lbs on the incline db press.  These were pretty difficult, so definitely sticking to 50s for a while.  Dips are still improving, both in strength and endurance.  Pushups felt improved today as well.  Going to for 3 sets of 10 reps across next time. **Core: **Elbow Planks: **1min.** Burn, baby, burn.
mbchoa/discipline
_posts/2014-01-31-week13-day35b-beefmode.markdown
Markdown
mit
2,473
package com.mgireesh; public class Solution extends VersionControl { public int firstBadVersion(int n) { int badVersion = 0; int start = 1; int end = n; while (start < end) { int mid = start + (end - start) / 2; if (isBadVersion(mid)) { end = mid; } else { start = mid + 1; } } return start; } }
mgireesh05/leetcode
first-bad-version/src/com/mgireesh/Solution.java
Java
mit
331
<?php namespace Aurex\Framework\Module\Modules\FormDoctrineModule; use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension, Silex\Provider\TranslationServiceProvider, Aurex\Framework\Module\ModuleInterface, Silex\Provider\SessionServiceProvider, Silex\Provider\FormServiceProvider, Aurex\Framework\Aurex; /** * Class FormDoctrineModule * * @package Aurex\Framework\Module\Modules\FormDoctrineModule */ class FormDoctrineModule implements ModuleInterface { /** * {@inheritDoc} */ public function integrate(Aurex $aurex) { $aurex->register(new FormServiceProvider); $aurex->register(new SessionServiceProvider); $aurex->register(new TranslationServiceProvider, [ 'locale' => 'en' ]); $aurex['form.extensions'] = $aurex->extend('form.extensions', function ($extensions, $app) { $managerRegistry = new FormManagerRegistry(null, [], ['default'], null, null, '\Doctrine\ORM\Proxy\Proxy'); $managerRegistry->setContainer($app); unset($extensions); return [(new DoctrineOrmExtension($managerRegistry))]; }); $aurex->getInjector()->share($aurex['form.factory']); } /** * {@inheritDoc} */ public function usesConfigurationKey() { return null; } }
J7mbo/Aurex
lib/Framework/Module/Modules/FormDoctrineModule/FormDoctrineModule.php
PHP
mit
1,340
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - matrix_expressions_ex.cpp</title></head><body bgcolor='white'><pre> <font color='#009900'>// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt </font> <font color='#009900'>/* This example contains a detailed discussion of the template expression technique used to implement the matrix tools in the dlib C++ library. It also gives examples showing how a user can create their own custom matrix expressions. Note that you should be familiar with the dlib::matrix before reading this example. So if you haven't done so already you should read the matrix_ex.cpp example program. */</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>iostream<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>dlib<font color='#5555FF'>/</font>matrix.h<font color='#5555FF'>&gt;</font> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> dlib; <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='custom_matrix_expressions_example'></a>custom_matrix_expressions_example</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>int</u></font> <b><a name='main'></a>main</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// Declare some variables used below </font> matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font>,<font color='#979000'>3</font>,<font color='#979000'>1</font><font color='#5555FF'>&gt;</font> y; matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font>,<font color='#979000'>3</font>,<font color='#979000'>3</font><font color='#5555FF'>&gt;</font> M; matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>&gt;</font> x; <font color='#009900'>// set all elements to 1 </font> y <font color='#5555FF'>=</font> <font color='#979000'>1</font>; M <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#009900'>// ------------------------- Template Expressions ----------------------------- </font> <font color='#009900'>// Now I will discuss the "template expressions" technique and how it is </font> <font color='#009900'>// used in the matrix object. First consider the following expression: </font> x <font color='#5555FF'>=</font> y <font color='#5555FF'>+</font> y; <font color='#009900'>/* Normally this expression results in machine code that looks, at a high level, like the following: temp = y + y; x = temp Temp is a temporary matrix returned by the overloaded + operator. temp then contains the result of adding y to itself. The assignment operator copies the value of temp into x and temp is then destroyed while the blissful C++ user never sees any of this. This is, however, totally inefficient. In the process described above you have to pay for the cost of constructing a temporary matrix object and allocating its memory. Then you pay the additional cost of copying it over to x. It also gets worse when you have more complex expressions such as x = round(y + y + y + M*y) which would involve the creation and copying of 5 temporary matrices. All these inefficiencies are removed by using the template expressions technique. The basic idea is as follows, instead of having operators and functions return temporary matrix objects you return a special object that represents the expression you wish to perform. So consider the expression x = y + y again. With dlib::matrix what happens is the expression y+y returns a matrix_exp object instead of a temporary matrix. The construction of a matrix_exp does not allocate any memory or perform any computations. The matrix_exp however has an interface that looks just like a dlib::matrix object and when you ask it for the value of one of its elements it computes that value on the spot. Only in the assignment operator does someone ask the matrix_exp for these values so this avoids the use of any temporary matrices. Thus the statement x = y + y is equivalent to the following code: // loop over all elements in y matrix for (long r = 0; r &lt; y.nr(); ++r) for (long c = 0; c &lt; y.nc(); ++c) x(r,c) = y(r,c) + y(r,c); This technique works for expressions of arbitrary complexity. So if you typed x = round(y + y + y + M*y) it would involve no temporary matrices being created at all. Each operator takes and returns only matrix_exp objects. Thus, no computations are performed until the assignment operator requests the values from the matrix_exp it receives as input. There is, however, a slight complication in all of this. It is for statements that involve the multiplication of a complex matrix_exp such as the following: */</font> x <font color='#5555FF'>=</font> M<font color='#5555FF'>*</font><font face='Lucida Console'>(</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font face='Lucida Console'>)</font>; <font color='#009900'>/* According to the discussion above, this statement would compute the value of M*(M+M+M+M+M+M+M) totally without any temporary matrix objects. This sounds good but we should take a closer look. Consider that the + operator is invoked 6 times. This means we have something like this: x = M * (matrix_exp representing M+M+M+M+M+M+M); M is being multiplied with a quite complex matrix_exp. Now recall that when you ask a matrix_exp what the value of any of its elements are it computes their values *right then*. If you think on what is involved in performing a matrix multiply you will realize that each element of a matrix is accessed M.nr() times. In the case of our above expression the cost of accessing an element of the matrix_exp on the right hand side is the cost of doing 6 addition operations. Thus, it would be faster to assign M+M+M+M+M+M+M to a temporary matrix and then multiply that by M. This is exactly what the dlib::matrix does under the covers. This is because it is able to spot expressions where the introduction of a temporary is needed to speed up the computation and it will automatically do this for you. Another complication that is dealt with automatically is aliasing. All matrix expressions are said to "alias" their contents. For example, consider the following expressions: M + M M * M We say that the expressions (M + M) and (M * M) alias M. Additionally, we say that the expression (M * M) destructively aliases M. To understand why we say (M * M) destructively aliases M consider what would happen if we attempted to evaluate it without first assigning (M * M) to a temporary matrix. That is, if we attempted to perform the following: for (long r = 0; r &lt; M.nr(); ++r) for (long c = 0; c &lt; M.nc(); ++c) M(r,c) = rowm(M,r)*colm(M,c); It is clear that the result would be corrupted and M wouldn't end up with the right values in it. So in this case we must perform the following: temp = M*M; M = temp; This sort of interaction is what defines destructive aliasing. Whenever we are assigning a matrix expression to a destination that is destructively aliased by the expression we need to introduce a temporary. The dlib::matrix is capable of recognizing the two forms of aliasing and introduces temporary matrices only when necessary. */</font> <font color='#009900'>// Next we discuss how to create custom matrix expressions. In what follows we </font> <font color='#009900'>// will define three different matrix expressions and show their use. </font> <font color='#BB00BB'>custom_matrix_expressions_example</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> M<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_trans'></a>example_op_trans</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that represents a transposed matrix. As discussed above, constructing this object doesn't compute anything. It just holds a reference to a matrix and presents an interface which defines matrix transposition. !*/</font> <font color='#009900'>// Here we simply hold a reference to the matrix we are supposed to be the transpose of. </font> <b><a name='example_op_trans'></a>example_op_trans</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m_<font face='Lucida Console'>)</font> : m<font face='Lucida Console'>(</font>m_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m; <font color='#009900'>// The cost field is used by matrix multiplication code to decide if a temporary needs to </font> <font color='#009900'>// be introduced. It represents the computational cost of evaluating an element of the </font> <font color='#009900'>// matrix expression. In this case we say that the cost of obtaining an element of the </font> <font color='#009900'>// transposed matrix is the same as obtaining an element of the original matrix (since </font> <font color='#009900'>// transpose doesn't really compute anything). </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> M::cost; <font color='#009900'>// Here we define the matrix expression's compile-time known dimensions. Since this </font> <font color='#009900'>// is a transpose we define them to be the reverse of M's dimensions. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> M::NC; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> M::NR; <font color='#009900'>// Define the type of element in this matrix expression. Also define the </font> <font color='#009900'>// memory manager type used and the layout. Usually we use the same types as the </font> <font color='#009900'>// input matrix. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::layout_type layout_type; <font color='#009900'>// This is where the action is. This function is what defines the value of an element of </font> <font color='#009900'>// this matrix expression. Here we are saying that m(c,r) == trans(m)(r,c) which is just </font> <font color='#009900'>// the definition of transposition. Note also that we must define the return type from this </font> <font color='#009900'>// function as a typedef. This typedef lets us either return our argument by value or by </font> <font color='#009900'>// reference. In this case we use the same type as the underlying m matrix. Later in this </font> <font color='#009900'>// example program you will see two other options. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::const_ret_type const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#BB00BB'>m</font><font face='Lucida Console'>(</font>c,r<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Define the run-time defined dimensions of this matrix. </font> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nc</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Recall the discussion of aliasing. Each matrix expression needs to define what </font> <font color='#009900'>// kind of aliasing it introduces so that we know when to introduce temporaries. The </font> <font color='#009900'>// aliases() function indicates that the matrix transpose expression aliases item if </font> <font color='#009900'>// and only if the m matrix aliases item. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// This next function indicates that the matrix transpose expression also destructively </font> <font color='#009900'>// aliases anything m aliases. I.e. transpose has destructive aliasing. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b>; <font color='#009900'>// Here we define a simple function that creates and returns transpose expressions. Note that the </font><font color='#009900'>// matrix_op&lt;&gt; template is a matrix_exp object and exists solely to reduce the amount of boilerplate </font><font color='#009900'>// you have to write to create a matrix expression. </font><font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> M <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_trans<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='example_trans'></a>example_trans</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_trans<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font> op; <font color='#009900'>// m.ref() returns a reference to the object of type M contained in the matrix expression m. </font> <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>m.<font color='#BB00BB'>ref</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_vector_to_matrix'></a>example_op_vector_to_matrix</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that holds a reference to a std::vector&lt;T&gt; and makes it look like a column vector. Thus it enables you to use a std::vector as if it was a dlib::matrix. !*/</font> <b><a name='example_op_vector_to_matrix'></a>example_op_vector_to_matrix</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vect_<font face='Lucida Console'>)</font> : vect<font face='Lucida Console'>(</font>vect_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vect; <font color='#009900'>// This expression wraps direct memory accesses so we use the lowest possible cost. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> <font color='#979000'>0</font>; <font color='#009900'>// We don't know the length of the vector until runtime. So we put 0 here. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#009900'>// We do know that it only has one column (since it's a vector) </font> <font color='#0000FF'>typedef</font> T type; <font color='#009900'>// Since the std::vector doesn't use a dlib memory manager we list the default one here. </font> <font color='#0000FF'>typedef</font> default_memory_manager mem_manager_type; <font color='#009900'>// The layout type also doesn't really matter in this case. So we list row_major_layout </font> <font color='#009900'>// since it is a good default. </font> <font color='#0000FF'>typedef</font> row_major_layout layout_type; <font color='#009900'>// Note that we define const_ret_type to be a reference type. This way we can </font> <font color='#009900'>// return the contents of the std::vector by reference. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> vect[r]; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> vect.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>1</font>; <b>}</b> <font color='#009900'>// This expression never aliases anything since it doesn't contain any matrix expression (it </font> <font color='#009900'>// contains only a std::vector which doesn't count since you can't assign a matrix expression </font> <font color='#009900'>// to a std::vector object). </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <b>}</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <b>}</b> <b>}</b>; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_vector_to_matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='example_vector_to_matrix'></a>example_vector_to_matrix</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vector <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_vector_to_matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font> op; <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>vector<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> M, <font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_add_scalar'></a>example_op_add_scalar</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that represents a matrix with a single scalar value added to all its elements. !*/</font> <b><a name='example_op_add_scalar'></a>example_op_add_scalar</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m_, <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> val_<font face='Lucida Console'>)</font> : m<font face='Lucida Console'>(</font>m_<font face='Lucida Console'>)</font>, val<font face='Lucida Console'>(</font>val_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#009900'>// A reference to the matrix </font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m; <font color='#009900'>// A copy of the scalar value that should be added to each element of m </font> <font color='#0000FF'>const</font> T val; <font color='#009900'>// This time we add 1 to the cost since evaluating an element of this </font> <font color='#009900'>// expression means performing 1 addition operation. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> M::cost <font color='#5555FF'>+</font> <font color='#979000'>1</font>; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> M::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> M::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::layout_type layout_type; <font color='#009900'>// Note that we declare const_ret_type to be a non-reference type. This is important </font> <font color='#009900'>// since apply() computes a new temporary value and thus we can't return a reference </font> <font color='#009900'>// to it. </font> <font color='#0000FF'>typedef</font> type const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#BB00BB'>m</font><font face='Lucida Console'>(</font>r,c<font face='Lucida Console'>)</font> <font color='#5555FF'>+</font> val; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nc</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// This expression aliases anything m aliases. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Unlike the transpose expression. This expression only destructively aliases something if m does. </font> <font color='#009900'>// So this expression has the regular non-destructive kind of aliasing. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>destructively_aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b>; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> M, <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_add_scalar<font color='#5555FF'>&lt;</font>M,T<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='add_scalar'></a>add_scalar</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> m, T val <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_add_scalar<font color='#5555FF'>&lt;</font>M,T<font color='#5555FF'>&gt;</font> op; <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>m.<font color='#BB00BB'>ref</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>, val<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='custom_matrix_expressions_example'></a>custom_matrix_expressions_example</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <b>{</b> matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>&gt;</font> <font color='#BB00BB'>x</font><font face='Lucida Console'>(</font><font color='#979000'>2</font>,<font color='#979000'>3</font><font face='Lucida Console'>)</font>; x <font color='#5555FF'>=</font> <font color='#979000'>1</font>, <font color='#979000'>1</font>, <font color='#979000'>1</font>, <font color='#979000'>2</font>, <font color='#979000'>2</font>, <font color='#979000'>2</font>; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> x <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// Finally, lets use the matrix expressions we defined above. </font> <font color='#009900'>// prints the transpose of x </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font>x<font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// prints this: </font> <font color='#009900'>// 11 11 11 </font> <font color='#009900'>// 12 12 12 </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// matrix expressions can be nested, even the user defined ones. </font> <font color='#009900'>// the following statement prints this: </font> <font color='#009900'>// 11 12 </font> <font color='#009900'>// 11 12 </font> <font color='#009900'>// 11 12 </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font><font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// Since we setup the alias detection correctly we can even do this: </font> x <font color='#5555FF'>=</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font><font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>new x:\n</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> x <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>Do some testing with the example_vector_to_matrix() function: </font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; std::vector<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>float</u></font><font color='#5555FF'>&gt;</font> vect; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>3</font><font face='Lucida Console'>)</font>; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>5</font><font face='Lucida Console'>)</font>; <font color='#009900'>// Now lets treat our std::vector like a matrix and print some things. </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_vector_to_matrix</font><font face='Lucida Console'>(</font>vect<font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font><font color='#BB00BB'>example_vector_to_matrix</font><font face='Lucida Console'>(</font>vect<font face='Lucida Console'>)</font>, <font color='#979000'>10</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>/* As an aside, note that dlib contains functions equivalent to the ones we defined above. They are: - dlib::trans() - dlib::mat() (converts things into matrices) - operator+ (e.g. you can say my_mat + 1) Also, if you are going to be creating your own matrix expression you should also look through the matrix code in the dlib/matrix folder. There you will find many other examples of matrix expressions. */</font> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> </pre></body></html>
kaathleen/LeapGesture-library
DynamicGestures/dlib-18.5/docs/matrix_expressions_ex.cpp.html
HTML
mit
37,000
define('exports@*', [], function(require, exports, module){ exports.a = 1; });
kaelzhang/neuron
test/mod/exports/*/exports.js
JavaScript
mit
84
package types // ApiVersion custom ENUM for SDK forward compatibility type ApiVersion int const ( ApiV1 ApiVersion = iota ) // EnvironmentType // https://docs.coinapi.io/#endpoints-2 type EnvironmentType int const ( ProdEncrypted EnvironmentType = iota ProdInsecure TestEncrypted TestInsecure ) // MessageType replicates the official incoming message types as (kinda) string enum. // https://docs.coinapi.io/#messages type MessageType string const ( TRADE MessageType = "trade" QUOTE MessageType = "quote" BOOK_L2_FULL MessageType = "book" // Orderbook L2 (Full) BOOK_L2_TOP_5 MessageType = "book5" // Orderbook L2 (5 best Bid / Ask) BOOK_L2_TOP_20 MessageType = "book20" // Orderbook L2 (20 best Bid / Ask) BOOK_L2_TOP_50 MessageType = "book50" // Orderbook L2 (50 best Bid / Ask) BOOK_L3_FULL MessageType = "book_l3" // Orderbook L3 (Full) https://docs.coinapi.io/#orderbook-l3-full-in OHLCV MessageType = "ohlcv" VOLUME MessageType = "volume" HEARTBEAT MessageType = "hearbeat" // DO NOT FIX! it's a typo in the official msg spec! ERROR MessageType = "error" // Otherwise processMessage(.) fails to handle heartbeat messages! EXCHANGERATE MessageType = "exrate" RECONNECT MessageType = "reconnect" ) // ReconnectType defines the reconnect behavior upon receiving a reconnect message // https://docs.coinapi.io/#reconnect-in type ReconnectType int const ( OnConnectionClose ReconnectType = iota OnReconnectMessage )
coinapi/coinapi-sdk
data-api/go-ws/api/types/enums.go
GO
mit
1,517
require 'rubygems' require 'bundler' Bundler.require require 'sinatra' set :public_folder, 'static' get '/' do File.read(File.join('index.html')) end get '/api/' do #content_type :js content_type("application/javascript") response["Content-Type"] = "application/javascript" #require 'config/initializers/beamly.rb' root = ::File.dirname(__FILE__) require ::File.join( root, 'config', 'initializers', 'beamly' ) #require 'config/initializers/beamly' z = Beamly::Epg.new region_id = z.regions.first.id provider_id = z.providers.first.id result = z.catalogues(region_id, provider_id) services = z.epg(result.first.epg_id) today = Date.today.strftime("%Y/%m/%d") schedule = z.schedule(services[8].service_id, today) today_formatted = Date.today.strftime("%Y-%m-%d") headers "Content-Type" => "application/json" json = '[' schedule.each do |item| time_formatted = Time.at(item.start).getlocal.strftime("%Y-%m-%d %H:%M") json += ' { "date": "'+time_formatted+'", "episodes": [ { "show": { "title": "'+item.title+'", "year": 2013, "genres": ["Comedy"], }, "episode":{"images": {"screen": "http://img-a.zeebox.com/940x505/'+item.img+'"}} } ] }, ' end json += ']' formatted_callback = "#{params['callback']}("+json+')' content_type("application/javascript") response["Content-Type"] = "application/javascript" formatted_callback end
TigerWolf/beamly_demo
main.rb
Ruby
mit
1,529
using System.Threading.Tasks; using FluentAssertions; using Histrio.Testing; using Xunit; namespace Histrio.Tests.Cell { public class When_getting_a_value_from_a_cell : GivenWhenThen { [Theory, InlineData(true), InlineData(333), InlineData(new[] {true, true}), InlineData("foo")] public void Then_value_the_cell_is_holding_on_to_is_returned<T>(T expectedValue) { var theater = new Theater(); var taskCompletionSource = new TaskCompletionSource<Reply<T>>(); ; Address customer = null; Address cell = null; Given(() => { cell = theater.CreateActor(new CellBehavior<T>()); var set = new Set<T>(expectedValue); theater.Dispatch(set, cell); customer = theater.CreateActor(new AssertionBehavior<Reply<T>>(taskCompletionSource, 1)); }); When(() => { var get = new Get(customer); theater.Dispatch(get, cell); }); Then(async () => { var actualValue = await taskCompletionSource.Task; actualValue.Content.ShouldBeEquivalentTo(expectedValue); }); } } }
MCGPPeters/Histrio
old/src/Histrio.Tests/Cell/When_getting_a_value_from_a_cell.cs
C#
mit
1,321