text stringlengths 2 1.04M | meta dict |
|---|---|
import logging
from django.core import management
from django.core.management.base import NoArgsCommand
from desktop.models import Directory, Document, Document2, Document2Permission, SAMPLE_USER_OWNERS
from useradmin.models import get_default_user_group, install_sample_user
LOG = logging.getLogger(__name__)
class Command(NoArgsCommand):
def handle_noargs(self, **options):
if not Document2.objects.filter(type='search-dashboard', owner__username__in=SAMPLE_USER_OWNERS).exists():
sample_user = install_sample_user()
management.call_command('loaddata', 'initial_search_examples.json', verbosity=2)
Document.objects.sync()
# Get or create sample user directories
home_dir = Directory.objects.get_home_directory(sample_user)
examples_dir, created = Directory.objects.get_or_create(
parent_directory=home_dir,
owner=sample_user,
name=Document2.EXAMPLES_DIR
)
Document2.objects.filter(type='search-dashboard', owner__username__in=SAMPLE_USER_OWNERS).update(parent_directory=examples_dir)
# Share with default group
examples_dir.share(sample_user, Document2Permission.READ_PERM, groups=[get_default_user_group()])
LOG.info('Successfully installed sample search dashboard')
| {
"content_hash": "beaeb08531ed2d2b1309c1ffd11dad80",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 133,
"avg_line_length": 37.55882352941177,
"alnum_prop": 0.7368833202819107,
"repo_name": "fangxingli/hue",
"id": "807a62d5233d368b46ff9de7f24da2e84096d2c6",
"size": "2069",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "apps/search/src/search/management/commands/search_setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "13685"
},
{
"name": "C",
"bytes": "2397157"
},
{
"name": "C++",
"bytes": "177090"
},
{
"name": "CSS",
"bytes": "1031718"
},
{
"name": "Emacs Lisp",
"bytes": "12145"
},
{
"name": "Genshi",
"bytes": "946"
},
{
"name": "Groff",
"bytes": "14877"
},
{
"name": "HTML",
"bytes": "24116446"
},
{
"name": "Java",
"bytes": "575404"
},
{
"name": "JavaScript",
"bytes": "9113771"
},
{
"name": "KiCad",
"bytes": "475"
},
{
"name": "M4",
"bytes": "1377"
},
{
"name": "Makefile",
"bytes": "116696"
},
{
"name": "Mako",
"bytes": "2550491"
},
{
"name": "Myghty",
"bytes": "936"
},
{
"name": "PLSQL",
"bytes": "13774"
},
{
"name": "Perl",
"bytes": "138710"
},
{
"name": "PigLatin",
"bytes": "328"
},
{
"name": "PowerShell",
"bytes": "630"
},
{
"name": "Python",
"bytes": "38448329"
},
{
"name": "Scala",
"bytes": "215057"
},
{
"name": "Shell",
"bytes": "54850"
},
{
"name": "Smarty",
"bytes": "130"
},
{
"name": "TeX",
"bytes": "126420"
},
{
"name": "Thrift",
"bytes": "259222"
},
{
"name": "XSLT",
"bytes": "516845"
}
],
"symlink_target": ""
} |
<?php
if ( !defined ( 'ABSPATH' ) ) {
exit;
}
class Redux_Welcome {
/**
* @var string The capability users should have to view the page
*/
public $minimum_capability = 'manage_options';
/**
* Get things started
*
* @since 1.4
*/
public function __construct () {
add_action ( 'admin_menu', array( $this, 'admin_menus' ) );
add_action ( 'admin_head', array( $this, 'admin_head' ) );
add_action ( 'admin_init', array( $this, 'welcome' ) );
update_option( 'redux_version_upgraded_from', ReduxFramework::$_version );
set_transient( '_redux_activation_redirect', true, 30 );
}
/**
* Register the Dashboard Pages which are later hidden but these pages
* are used to render the Welcome and Credits pages.
*
* @access public
* @since 1.4
* @return void
*/
public function admin_menus () {
// About Page
add_dashboard_page (
__ ( 'Welcome to Redux Framework', 'redux-framework' ), __ ( 'Welcome to Redux Framework', 'redux-framework' ), $this->minimum_capability, 'redux-about', array( $this, 'about_screen' )
);
// Changelog Page
add_dashboard_page (
__ ( 'Redux Framework Changelog', 'redux-framework' ), __ ( 'Redux Framework Changelog', 'redux-framework' ), $this->minimum_capability, 'redux-changelog', array( $this, 'changelog_screen' )
);
// Getting Started Page
add_dashboard_page (
__ ( 'Getting started with Redux Framework', 'redux-framework' ), __ ( 'Getting started with Redux Framework', 'redux-framework' ), $this->minimum_capability, 'redux-getting-started', array( $this, 'getting_started_screen' )
);
// Credits Page
add_dashboard_page (
__ ( 'The people that develop Redux Framework', 'redux-framework' ), __ ( 'The people that develop Redux Framework', 'redux-framework' ), $this->minimum_capability, 'redux-credits', array( $this, 'credits_screen' )
);
}
/**
* Hide Individual Dashboard Pages
*
* @access public
* @since 1.4
* @return void
*/
public function admin_head () {
remove_submenu_page ( 'index.php', 'redux-about' );
remove_submenu_page ( 'index.php', 'redux-changelog' );
remove_submenu_page ( 'index.php', 'redux-getting-started' );
remove_submenu_page ( 'index.php', 'redux-credits' );
// Badge for welcome page
$badge_url = ReduxFramework::$_url . 'assets/images/redux-badge.png';
?>
<style type="text/css" media="screen">
/*<![CDATA[*/
.redux-badge {
padding-top: 150px;
height: 52px;
width: 185px;
color: #666;
font-weight: bold;
font-size: 14px;
text-align: center;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.8);
margin: 0 -5px;
background: url('<?php echo $badge_url; ?>') no-repeat;
}
.about-wrap .redux-badge {
position: absolute;
top: 0;
right: 0;
}
.redux-welcome-screenshots {
float: right;
margin-left: 10px!important;
}
.about-wrap .feature-section {
margin-top: 20px;
}
/*]]>*/
</style>
<?php
}
/**
* Navigation tabs
*
* @access public
* @since 1.9
* @return void
*/
public function tabs () {
$selected = isset ( $_GET[ 'page' ] ) ? $_GET[ 'page' ] : 'redux-about';
?>
<h2 class="nav-tab-wrapper">
<a class="nav-tab <?php echo $selected == 'redux-about' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'page' => 'redux-about' ), 'index.php' ) ) ); ?>">
<?php _e ( "What's New", 'redux-framework' ); ?>
</a>
<a class="nav-tab <?php echo $selected == 'redux-getting-started' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'page' => 'redux-getting-started' ), 'index.php' ) ) ); ?>">
<?php _e ( 'Getting Started', 'redux-framework' ); ?>
</a>
<a class="nav-tab <?php echo $selected == 'redux-changelog' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'page' => 'redux-changelog' ), 'index.php' ) ) ); ?>">
<?php _e ( 'Changelog', 'redux-framework' ); ?>
</a>
<a class="nav-tab <?php echo $selected == 'redux-credits' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'page' => 'redux-credits' ), 'index.php' ) ) ); ?>">
<?php _e ( 'Credits', 'redux-framework' ); ?>
</a>
</h2>
<?php
}
/**
* Render About Screen
*
* @access public
* @since 1.4
* @return void
*/
public function about_screen () {
list( $display_version ) = explode ( '-', ReduxFramework::$_version );
?>
<div class="wrap about-wrap">
<h1><?php printf ( __ ( 'Welcome to Redux Framework %s', 'redux-framework' ), $display_version ); ?></h1>
<div class="about-text"><?php printf ( __ ( 'Thank you for updating to the latest version! Redux Framework %s is ready to <add description>', 'redux-framework' ), $display_version ); ?></div>
<div class="redux-badge"><?php printf ( __ ( 'Version %s', 'redux-framework' ), $display_version ); ?></div>
<?php $this->tabs (); ?>
<div class="changelog">
<h3><?php _e ( 'Some Feature', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Some feature', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p></p>
<p></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'More Features', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p><?php _e ( 'description', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p><?php _e ( 'description', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Feature', 'redux-framework' ); ?></h4>
<p><?php _e ( 'description', 'redux-framework' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Additional Updates', 'redux-framework' ); ?></h3>
<div class="feature-section col three-col">
<div>
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
</div>
<div>
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
</div>
<div class="last-feature">
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Cool thing', 'redux-framework' ); ?></h4>
<p><?php _e ( 'cool thing description.', 'redux-framework' ); ?></p>
</div>
</div>
</div>
<div class="return-to-dashboard">
<a href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'post_type' => 'download', 'page' => 'redux-settings' ), 'edit.php' ) ) ); ?>"><?php _e ( 'Go to Redux Framework', 'redux-framework' ); ?></a> ·
<a href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'page' => 'redux-changelog' ), 'index.php' ) ) ); ?>"><?php _e ( 'View the Full Changelog', 'redux' ); ?></a>
</div>
</div>
<?php
}
/**
* Render Changelog Screen
*
* @access public
* @since 2.0.3
* @return void
*/
public function changelog_screen () {
list( $display_version ) = explode ( '-', ReduxFramework::$_version );
?>
<div class="wrap about-wrap">
<h1><?php _e ( 'Redux Framework Changelog', 'redux-framework' ); ?></h1>
<div class="about-text"><?php printf ( __ ( 'Thank you for updating to the latest version! Redux Framework %s is ready to make your <description>', 'redux-framework' ), $display_version ); ?></div>
<div class="redux-badge"><?php printf ( __ ( 'Version %s', 'redux-framework' ), $display_version ); ?></div>
<?php $this->tabs (); ?>
<div class="changelog">
<h3><?php _e ( 'Full Changelog', 'redux-framework' ); ?></h3>
<div class="feature-section">
<?php echo $this->parse_readme (); ?>
</div>
</div>
<div class="return-to-dashboard">
<a href="<?php echo esc_url ( admin_url ( add_query_arg ( array( 'post_type' => 'download', 'page' => 'redux-settings' ), 'edit.php' ) ) ); ?>"><?php _e ( 'Go to Redux Framework', 'redux-framework' ); ?></a>
</div>
</div>
<?php
}
/**
* Render Getting Started Screen
*
* @access public
* @since 1.9
* @return void
*/
public function getting_started_screen () {
list( $display_version ) = explode ( '-', ReduxFramework::$_version );
?>
<div class="wrap about-wrap">
<h1><?php printf ( __ ( 'Welcome to Redux Framework %s', 'redux-framework' ), $display_version ); ?></h1>
<div class="about-text"><?php printf ( __ ( 'Thank you for updating to the latest version! Redux Framework %s is ready to make your <description>', 'redux-framework' ), $display_version ); ?></div>
<div class="redux-badge"><?php printf ( __ ( 'Version %s', 'redux-framework' ), $display_version ); ?></div>
<?php $this->tabs (); ?>
<p class="about-description"><?php _e ( 'Use the tips below to get started using Redux Framework. You\'ll be up and running in no time!', 'redux-framework' ); ?></p>
<div class="changelog">
<h3><?php _e ( 'Creating Your First Panel', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php printf ( __ ( '<a href="%s">%s → Add New</a>', 'redux' ), admin_url ( 'post-new.php?post_type=download' ), redux_get_label_plural () ); ?></h4>
<p><?php printf ( __ ( 'The %s menu is your access point for all aspects of your Easy Digital Downloads product creation and setup. To create your first product, simply click Add New and then fill out the product details.', 'redux' ), redux_get_label_plural () ); ?></p>
<h4><?php _e ( 'Product Price', 'redux' ); ?></h4>
<p><?php _e ( 'Products can have simple prices or variable prices if you wish to have more than one price point for a product. For a single price, simply enter the price. For multiple price points, click <em>Enable variable pricing</em> and enter the options.', 'redux' ); ?></p>
<h4><?php _e ( 'Download Files', 'redux' ); ?></h4>
<p><?php _e ( 'Uploading the downloadable files is simple. Click <em>Upload File</em> in the Download Files section and choose your download file. To add more than one file, simply click the <em>Add New</em> button.', 'redux' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Display a Product Grid', 'redux-framework' ); ?></h3>
<div class="feature-section">
<img src="<?php echo Redux_PLUGIN_URL . 'assets/images/screenshots/grid.png'; ?>" class="redux-welcome-screenshots"/>
<h4><?php _e ( 'Flexible Product Grids', 'redux-framework' ); ?></h4>
<p><?php _e ( 'The [downloads] shortcode will display a product grid that works with any theme, no matter the size. It is even responsive!', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Change the Number of Columns', 'redux-framework' ); ?></h4>
<p><?php _e ( 'You can easily change the number of columns by adding the columns="x" parameter:', 'redux-framework' ); ?></p>
<p><pre>[downloads columns="4"]</pre></p>
<h4><?php _e ( 'Additional Display Options', 'redux-framework' ); ?></h4>
<p><?php printf ( __ ( 'The product grids can be customized in any way you wish and there is <a href="%s">extensive documentation</a> to assist you.', 'redux-framework' ), 'http://easydigitaldownloads.com/documentation' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Purchase Buttons Anywhere', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'The <em>[purchase_link]</em> Shortcode', 'redux-framework' ); ?></h4>
<p><?php _e ( 'With easily accessible shortcodes to display purchase buttons, you can add a Buy Now or Add to Cart button for any product anywhere on your site in seconds.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Buy Now Buttons', 'redux-framework' ); ?></h4>
<p><?php _e ( 'Purchase buttons can behave as either Add to Cart or Buy Now buttons. With Buy Now buttons customers are taken straight to PayPal, giving them the most frictionless purchasing experience possible.', 'redux-framework' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Need Help?', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Phenomenal Support', 'redux-framework' ); ?></h4>
<p><?php _e ( 'We do our best to provide the best support we can. If you encounter a problem or have a question, post a question in the <a href="https://easydigitaldownloads.com/support">support forums</a>.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Need Even Faster Support?', 'redux' ); ?></h4>
<p><?php _e ( 'Our <a href="https://easydigitaldownloads.com/support/pricing/">Priority Support forums</a> are there for customers that need faster and/or more in-depth assistance.', 'redux-framework' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Stay Up to Date', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Get Notified of Extension Releases', 'v' ); ?></h4>
<p><?php _e ( 'New extensions that make Easy Digital Downloads even more powerful are released nearly every single week. Subscribe to the newsletter to stay up to date with our latest releases. <a href="http://eepurl.com/kaerz" target="_blank">Signup now</a> to ensure you do not miss a release!', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Get Alerted About New Tutorials', 'redux-framework' ); ?></h4>
<p><?php _e ( '<a href="http://eepurl.com/kaerz" target="_blank">Signup now</a> to hear about the latest tutorial releases that explain how to take Easy Digital Downloads further.', 'redux-framework' ); ?></p>
</div>
</div>
<div class="changelog">
<h3><?php _e ( 'Extensions for Everything', 'redux-framework' ); ?></h3>
<div class="feature-section">
<h4><?php _e ( 'Over 250 Extensions', 'redux-framework' ); ?></h4>
<p><?php _e ( 'Add-on plugins are available that greatly extend the default functionality of Easy Digital Downloads. There are extensions for payment processors, such as Stripe and PayPal, extensions for newsletter integrations, and many, many more.', 'redux-framework' ); ?></p>
<h4><?php _e ( 'Visit the Extension Store', 'redux-framework' ); ?></h4>
<p><?php _e ( '<a href="https://easydigitaldownloads.com/extensions" target="_blank">The Extensions store</a> has a list of all available extensions, including convenient category filters so you can find exactly what you are looking for.', 'redux-framework' ); ?></p>
</div>
</div>
</div>
<?php
}
/**
* Render Credits Screen
*
* @access public
* @since 1.4
* @return void
*/
public function credits_screen () {
list( $display_version ) = explode ( '-', ReduxFramework::$_version );
?>
<div class="wrap about-wrap">
<h1><?php printf ( __ ( 'Welcome to Redux Framework %s', 'redux-framework' ), $display_version ); ?></h1>
<div class="about-text"><?php printf ( __ ( 'Thank you for updating to the latest version! Redux Framework %s is ready to make your <description>', 'redux-framework' ), $display_version ); ?></div>
<div class="redux-badge"><?php printf ( __ ( 'Version %s', 'redux-framework' ), $display_version ); ?></div>
<?php $this->tabs (); ?>
<p class="about-description"><?php _e ( 'Redux Framework is created by a worldwide team of developers who <something witty here>', 'redux-framework' ); ?></p>
<?php echo $this->contributors (); ?>
</div>
<?php
}
/**
* Parse the Redux readme.txt file
*
* @since 2.0.3
* @return string $readme HTML formatted readme file
*/
public function parse_readme () {
$url = ReduxFramework::$_dir;
$url = str_replace('ReduxCore', '', $url);
$file = file_exists ( $url . 'README.txt' ) ? $url . 'README.txt' : null;
if ( !$file ) {
$readme = '<p>' . __ ( 'No valid changlog was found.', 'redux' ) . '</p>';
} else {
$readme = file_get_contents ( $file );
$readme = nl2br ( esc_html ( $readme ) );
$readme = explode ( '== Changelog ==', $readme );
$readme = end ( $readme );
$remove = explode( '== Attribution ==', $readme );
$readme = str_replace( '== Attribution ==' . end( $remove ), '', $readme );
$readme = preg_replace ( '/`(.*?)`/', '<code>\\1</code>', $readme );
$readme = preg_replace ( '/[\040]\*\*(.*?)\*\*/', ' <strong>\\1</strong>', $readme );
$readme = preg_replace ( '/[\040]\*(.*?)\*/', ' <em>\\1</em>', $readme );
$readme = preg_replace ( '/= (.*?) =/', '<h4>\\1</h4>', $readme );
$readme = preg_replace ( '/\[(.*?)\]\((.*?)\)/', '<a href="\\2">\\1</a>', $readme );
}
return $readme;
}
/**
* Render Contributors List
*
* @since 1.4
* @uses Redux_Welcome::get_contributors()
* @return string $contributor_list HTML formatted list of all the contributors for Redux
*/
public function contributors () {
$contributors = $this->get_contributors ();
if ( empty ( $contributors ) )
return '';
$contributor_list = '<ul class="wp-people-group">';
foreach ( $contributors as $contributor ) {
$contributor_list .= '<li class="wp-person">';
$contributor_list .= sprintf ( '<a href="%s" title="%s">', esc_url ( 'https://github.com/' . $contributor->login ), esc_html ( sprintf ( __ ( 'View %s', 'redux-framework' ), $contributor->login ) )
);
$contributor_list .= sprintf ( '<img src="%s" width="64" height="64" class="gravatar" alt="%s" />', esc_url ( $contributor->avatar_url ), esc_html ( $contributor->login ) );
$contributor_list .= '</a>';
$contributor_list .= sprintf ( '<a class="web" href="%s">%s</a>', esc_url ( 'https://github.com/' . $contributor->login ), esc_html ( $contributor->login ) );
$contributor_list .= '</a>';
$contributor_list .= '</li>';
}
$contributor_list .= '</ul>';
return $contributor_list;
}
/**
* Retreive list of contributors from GitHub.
*
* @access public
* @since 1.4
* @return array $contributors List of contributors
*/
public function get_contributors () {
$contributors = get_transient ( 'redux_contributors' );
if ( false !== $contributors )
return $contributors;
$response = wp_remote_get ( 'https://api.github.com/repos/ReduxFramework/redux-framework/contributors', array( 'sslverify' => false ) );
if ( is_wp_error ( $response ) || 200 != wp_remote_retrieve_response_code ( $response ) )
return array();
$contributors = json_decode ( wp_remote_retrieve_body ( $response ) );
if ( !is_array ( $contributors ) )
return array();
set_transient ( 'redux_contributors', $contributors, 3600 );
return $contributors;
}
/**
* Sends user to the Welcome page on first activation of Redux as well as each
* time Redux is upgraded to a new version
*
* @access public
* @since 1.4
* @global $redux_options Array of all the Redux Options
* @return void
*/
public function welcome () {
logconsole('welcome.php');
//return;
// Bail if no activation redirect
if ( !get_transient ( '_redux_activation_redirect' ) )
return;
// Delete the redirect transient
delete_transient ( '_redux_activation_redirect' );
// Bail if activating from network, or bulk
if ( is_network_admin () || isset ( $_GET[ 'activate-multi' ] ) )
return;
$upgrade = get_option ( 'redux_version_upgraded_from' );
//
// if ( !$upgrade ) { // First time install
// wp_safe_redirect ( admin_url ( 'index.php?page=redux-getting-started' ) );
// exit;
// } else { // Update
// wp_safe_redirect ( admin_url ( 'index.php?page=redux-about' ) );
// exit;
// }
}
}
new Redux_Welcome();
| {
"content_hash": "b3109c8bb01560b78b84788ee0166349",
"timestamp": "",
"source": "github",
"line_count": 551,
"max_line_length": 345,
"avg_line_length": 43.36116152450091,
"alnum_prop": 0.5110915787711368,
"repo_name": "thegrowthland/growth",
"id": "f75d94dcf1b694488c0d5f40c81e8886149352db",
"size": "23892",
"binary": false,
"copies": "19",
"ref": "refs/heads/Redux-Builder",
"path": "admin/redux-framework/ReduxCore/inc/welcome.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "989610"
},
{
"name": "JavaScript",
"bytes": "209284"
},
{
"name": "PHP",
"bytes": "1145382"
},
{
"name": "Perl",
"bytes": "259"
}
],
"symlink_target": ""
} |
package org.cloudfoundry.client.v2.applications;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;
@JsonDeserialize
@Value.Immutable
abstract class _InstanceStatistics {
/**
* The isolation segment
*/
@JsonProperty("isolation_segment")
@Nullable
abstract String getIsolationSegment();
/**
* The instance state
*/
@JsonProperty("state")
@Nullable
abstract String getState();
/**
* The instance statistics
*/
@JsonProperty("stats")
@Nullable
abstract Statistics getStatistics();
}
| {
"content_hash": "34e94eb5f9eb012e984e3c91b0f59744",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 65,
"avg_line_length": 20.114285714285714,
"alnum_prop": 0.7002840909090909,
"repo_name": "cloudfoundry/cf-java-client",
"id": "fc207d119f5fdd518d20e942fc02b55def0bd053",
"size": "1324",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/applications/_InstanceStatistics.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "460"
},
{
"name": "HTML",
"bytes": "818"
},
{
"name": "Java",
"bytes": "7530131"
},
{
"name": "Shell",
"bytes": "6507"
}
],
"symlink_target": ""
} |
@interface HCAppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *urlTextField;
@property (weak) IBOutlet NSButton *getButton;
@property (weak) IBOutlet NSButton *postButton;
@property (weak) IBOutlet NSTableView *requestHeadersTableView;
@property (weak) IBOutlet NSTableView *parametersTableView;
@property (unsafe_unretained) IBOutlet NSTextView *responseTextView;
@property (unsafe_unretained) IBOutlet NSTextView *responseHeadersTextView;
@end
| {
"content_hash": "4290492a891f017d51e1503bc4c0325f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 75,
"avg_line_length": 44.166666666666664,
"alnum_prop": 0.8207547169811321,
"repo_name": "frank4565/HTTPCake",
"id": "c3d3f7f19a819df6d72556d49e0231fffb764a77",
"size": "691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HTTPCake/HCAppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "6904"
}
],
"symlink_target": ""
} |
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb')
describe Ohai::System, "hostname plugin" do
before(:each) do
@plugin = get_plugin("hostname")
end
it "should set the domain to everything after the first dot of the fqdn" do
@plugin[:fqdn] = "katie.bethell"
@plugin.run
@plugin[:domain].should == "bethell"
end
it "should not set a domain if fqdn is not set" do
@plugin.run
@plugin[:domain].should == nil
end
end
| {
"content_hash": "77d2d282b45388e571bcbc9987d0520b",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 77,
"avg_line_length": 25.31578947368421,
"alnum_prop": 0.6465696465696466,
"repo_name": "broadinstitute/ohai",
"id": "5891811ae282cf0bdbff13a1a8bdafcc914e7cd7",
"size": "1165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/unit/plugins/hostname_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "3892918"
},
{
"name": "Shell",
"bytes": "946"
}
],
"symlink_target": ""
} |
<?php
namespace OwlyCode\ReactBoard;
use OwlyCode\ReactBoard\Adapter\RachetApp;
use OwlyCode\ReactBoard\Application\ApplicationInterface;
use OwlyCode\ReactBoard\Asset\AssetInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\EventDispatcher\Event;
class Kernel
{
private $container;
private $hostname;
private $port;
private $rootDir;
public function __construct($hostname = 'localhost', $port = 8080)
{
$this->hostname = $hostname;
$this->port = $port;
$this->container = new ContainerBuilder();
$loader = new XmlFileLoader($this->container, new FileLocator(__DIR__));
$loader->load('Resources/services.xml');
$this->container->setParameter('kernel.root_dir', $this->getRootDir());
}
public function configureContainer(callable $callback)
{
call_user_func($callback, $this->container);
}
public function register(ApplicationInterface $application)
{
$application->setContainer($this->container);
$this->container->get('application_repository')->register($application);
}
public function link(AssetInterface $asset)
{
$this->container->get('assets_repository')->add($asset);
}
public function run()
{
$this->container->get('application_repository')->init();
$app = new RachetApp($this->hostname, $this->port, '0.0.0.0');
$app->route('/ws', $this->container->get('server.web_socket'));
$app->route('/{application}/{module}', $this->container->get('server.application'));
$app->route('/public/{asset}', $this->container->get('server.assets'), array('asset' => '.*'));
$this->container->get('event_dispatcher')->dispatch('reactboard.start', new Event());
$app->run();
}
/**
* From Symfony2's Kernel implementation
*/
public function getRootDir()
{
if (null === $this->rootDir) {
$r = new \ReflectionObject($this);
$this->rootDir = str_replace('\\', '/', dirname($r->getFileName()));
}
return $this->rootDir;
}
}
| {
"content_hash": "6aff149d483b23579832b286735c4276",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 103,
"avg_line_length": 30.7027027027027,
"alnum_prop": 0.6324823943661971,
"repo_name": "OwlyCode/reactboard",
"id": "c841c6d5c2a22874eb4c2b8abadee570ab64a994",
"size": "2272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/OwlyCode/ReactBoard/Kernel.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1666"
},
{
"name": "JavaScript",
"bytes": "6011"
},
{
"name": "PHP",
"bytes": "31847"
}
],
"symlink_target": ""
} |
/**
* Author: Ruo
* Create: 2018-07-28
* Description: 列表项目
*/
import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import styled, {ThemeProvider} from 'styled-components';
import {Button} from 'Components';
/**
* props: twoLine
*/
const ListItemView = styled.div.attrs({
className: 'list-item',
})`
//margin-top: 3px;
background-color: #fff;
border-top: ${props => props.noBorder ? 'none' : '1px solid #f2f3f5'};
&:nth-of-type(1) {
border-top: none;
margin-top: 0;
}
`;
const TitleView = styled.div.attrs({
className: 'title-view',
})`
min-height: ${props => props.theme.twoLine ? '65px' : '49px'};
padding: 0 0 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
font-size: 13px;
cursor: ${({onClick}) => onClick ? 'pointer' : 'default'};
opacity: ${({theme = {toggle: true}}) => theme.toggle ? 1 : 0.5};
//.icon {
// margin: 0 12px 0 -6px;
//}
`;
const TwoLineContainerView = styled.div.attrs({
className: 'two-line-container',
})`
display: flex;
flex-direction: column;
flex: auto;
h3 {
margin: 0;
height: 20px;
font-size: 13px;
}
`;
const First = styled.h3`
margin: 0;
height: 20px;
font-size: 13px;
font-weight: 400;
`;
const Secondary = styled.div`
margin-top: 2px;
height:20px;
font-size: 12px;
font-weight: 400;
color: #757575;
`;
const Start = styled.div.attrs({
className: 'list-item-start',
})`
.icon + & {
-webkit-padding-start: 16px;
}
display: flex;
flex-direction: row;
align-items: center;
flex: auto;
margin: 15px 0;
h1, h2, h3, h4, h5, h6, p {
margin: 0;
height: 20px;
font-size: 13px;
}
`;
/*
const Middle = styled.div.attrs({
className: 'list-item-middle',
})`
display: flex;
align-items: center;
.separator + & {
//margin: -12px;
}
`;
*/
const End = styled.div.attrs({
className: 'list-item-end',
})`
display: flex;
align-items: center;
margin: 0 20px 0 0;
.separator + & {
margin: 0 13px 0 -13px;
}
`;
const SubList = styled.div.attrs({
className: props => props.hide ? 'sub-list hide' : 'sub-list',
})`
display: flex;
flex-direction: column;
position: relative;
max-height: 0;
border-radius: 4px;
background-color: white;
transition: all 0.3s;
overflow: hidden;
opacity: 1;
.list-item {
margin-left: 60px;
.list-item-start {
margin: 0;
}
&:last-of-type {
padding-bottom: 16px;
}
}
`;
/**
* 分割线
* 根据twoLine属性设定自适应高度
*/
const Separator = styled.div.attrs({
className: 'separator',
})`
height: calc(${props => props.theme.twoLine ? '65px' : '49px'} - 2 * 9px);
-webkit-border-start: 1px solid rgba(0, 0, 0, 0.02);
flex-shrink: 0;
-webkit-margin-end:20px;
-webkit-margin-start:20px;
`;
export class ListItem extends React.Component {
propTypes = {
subList: PropTypes.object,
operation: PropTypes.any,
children: PropTypes.any,
icon: PropTypes.any,
separator: PropTypes.bool,
twoLine: PropTypes.bool,
noBorder: PropTypes.bool,
extend: PropTypes.bool,
toggle: PropTypes.bool,
first: PropTypes.any,
second: PropTypes.any,
middle: PropTypes.any,
onClick: PropTypes.func,
};
constructor(props) {
super();
const {subList} = props;
this.state = {
maxHeight: 0,
hideSubList: subList && subList.hide !== undefined ? subList.hide : false,
};
}
componentDidMount() {
if (this.subListRef) {
const sumHeight = _.sumBy(this.subListRef.querySelectorAll('.list-item, *'),
(e) => e.getBoundingClientRect().height);
this.setState({maxHeight: sumHeight});
}
}
render() {
let {
operation = null, // 右侧操作DOM,可能是按钮,单选按钮或者面板折叠按钮
icon, // 显示在最左侧的ICON
children,
separator = false, // 右侧操作DOM是否要添加分割线
twoLine = false, // 是否两行高度
first, // 标题,需要twoLine = true
second, // 副标题,需要twoLine = true
middle = null, // 中间内容
subList = null,
noBorder = false,
extend = false, // subList是否为可折叠,如果没有设定operation就会自动将operation设定为折叠按钮
onClick,
toggle = true, // 是否可以切换,即operation是否可点击
...rest
} = this.props;
const {maxHeight, hideSubList} = this.state;
if (!operation && subList && subList.children && extend) {
operation = <Button
icon={hideSubList === true ? 'arrowDown' : 'arrowUp'}
onClick={() => this.setState({hideSubList: !hideSubList})}
/>;
onClick = () => this.setState({hideSubList: !hideSubList});
}
return (
<ThemeProvider theme={{twoLine, toggle}}>
<ListItemView noBorder={noBorder} {...rest}>
<TitleView onClick={toggle ? onClick : extend ? onClick : null}>
{icon && icon}
{twoLine && <TwoLineContainerView>
{first && <First>{first}</First>}
{second && <Secondary>{second}</Secondary>}
</TwoLineContainerView>}
{!twoLine && <Start>{children}{middle}</Start>}
{separator && <Separator/>}
{operation && <End>{operation}</End>}
</TitleView>
{/* 折叠子列表 */}
{subList && subList.children && <ThemeProvider theme={{twoLine, ...subList.theme}}>
<SubList
style={{
maxHeight: (!extend && subList.hide) || (extend && hideSubList === true) ? '0' : maxHeight || '',
transitionDuration: `${Math.min(Math.sqrt(subList.children.length) / 10 + (hideSubList ? 0.1 : 0.5), 1.2)}s`,
}}
ref={i => this.subListRef = i}
>{subList.children}</SubList>
</ThemeProvider>}
</ListItemView>
</ThemeProvider>
);
}
}
| {
"content_hash": "9566a67639a6c636797f3b3b9b1dc32d",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 141,
"avg_line_length": 26.923076923076923,
"alnum_prop": 0.5366666666666666,
"repo_name": "zacyu/bilibili-helper",
"id": "f1b173c761dbcc497b5f296e303f1837932f72cc",
"size": "6548",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/components/configPage/List/ListItem.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37762"
},
{
"name": "HTML",
"bytes": "1523"
},
{
"name": "JavaScript",
"bytes": "342787"
}
],
"symlink_target": ""
} |
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
<predicate lemma="gouge">
<roleset framnet="" id="gouge.01" name="put deep grooves or scratches into a surface" vncls="21.2">
<roles>
<role descr="causer of gouges" f="" n="0">
<vnrole vncls="21.2-1" vntheta="agent"/>
</role>
<role descr="surface" f="" n="1">
<vnrole vncls="21.2-1" vntheta="patient"/>
</role>
<note/>
</roles>
<example name="adessive" src="" type="">
<inflection aspect="progressive" form="participle" person="ns" tense="ns" voice="active"/>
<text>What had he thought of, to go to John, grovel and beg
understanding? To confess with a canvas chair as a prie-dieu, [*-2]
gouging at his heart until a rough and stupid hand bade him rise and
go?
</text>
<arg f="" n="0">[*-2]</arg>
<rel f="">gouging</rel>
<arg f="" n="1">at his heart</arg>
<arg f="tmp" n="m">until a rough and stupid hand bade him rise and go</arg>
<note/>
</example>
<example name="more commonly transitive" src="" type="">
<inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
<text>Quickly but carefully lowering my duffel bag over the low
side-rack, I stepped on the running board; it flopped down, sprang
back up and gouged my shin.
</text>
<arg f="" n="0">it</arg>
<rel f="">gouged</rel>
<arg f="" n="1">my shin</arg>
<note/>
</example>
<note/>
</roleset>
<roleset framnet="" id="gouge.02" name="extort money, swindle" vncls="-">
<roles>
<role descr="petty crook" f="" n="0"/>
<role descr="money" f="" n="1"/>
<role descr="source" f="" n="2"/>
<note/>
</roles>
<example name="the one example" src="" type="">
<inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
<text>There I was, a retired wobbly and structural iron worker who
[*T*-1] 'd never gouged a cent off a fellow worker in my thirty years
in the movement.
</text>
<arg f="" n="0">[*T*-1]</arg>
<arg f="rcl" n="m">who -> a retired wobbly and structural iron worker</arg>
<rel f="">gouged</rel>
<arg f="" n="1">a cent</arg>
<arg f="" n="2">off a fellow worker</arg>
<arg f="tmp" n="m">in my thirty years in the movement</arg>
<note/>
</example>
<note/>
</roleset>
<note>Frames file for 'gouge' based on sentences in brown.</note>
</predicate>
<note/>
</frameset>
| {
"content_hash": "5d6ba046ebcb18dd8aefd80a5ba0bfd8",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 107,
"avg_line_length": 42.05128205128205,
"alnum_prop": 0.4472560975609756,
"repo_name": "TeamSPoon/logicmoo_workspace",
"id": "c3865a5d1efb4284c3446fdc4b55e3b9ebe6e08a",
"size": "3280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packs_sys/logicmoo_nlu/ext/pldata/propbank-frames-2.1.5/frames/gouge-v.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "342"
},
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "126627"
},
{
"name": "HTML",
"bytes": "839172"
},
{
"name": "Java",
"bytes": "11116"
},
{
"name": "JavaScript",
"bytes": "238700"
},
{
"name": "PHP",
"bytes": "42253"
},
{
"name": "Perl 6",
"bytes": "23"
},
{
"name": "Prolog",
"bytes": "440882"
},
{
"name": "PureBasic",
"bytes": "1334"
},
{
"name": "Rich Text Format",
"bytes": "3436542"
},
{
"name": "Roff",
"bytes": "42"
},
{
"name": "Shell",
"bytes": "61603"
},
{
"name": "TeX",
"bytes": "99504"
}
],
"symlink_target": ""
} |
package gomez
import (
"bufio"
_ "fmt"
"io"
"log"
"os"
"sync"
"golang.org/x/crypto/ssh"
)
type runner struct {
host *Host
clientConfig *ClientConfig
client *ssh.Client
session *ssh.Session
stdin io.WriteCloser
stdout io.Reader
waitGroup *sync.WaitGroup
cmdOptions CmdOptions
}
// run a command on the remote hosts
func (config *ClientConfig) Run(cmd string) CmdResult {
return config.run(cmd, CmdOptions{})
}
func (config *ClientConfig) RunWithOpts(cmd string, options CmdOptions) CmdResult {
return config.run(cmd, options)
}
func (config *ClientConfig) run(cmd string, options CmdOptions) CmdResult {
cmdResult := CmdResult{}
// create a wait group the waits for command execution on all hosts
var sessionWaitGroup sync.WaitGroup
sessionWaitGroup.Add(len(config.Hosts))
// need to create a session for each host
for _, host := range config.Hosts {
client, session, err := CreateSession(host)
if err != nil {
log.Fatalln(err)
break
}
runner := runner{
clientConfig: config,
client: client,
session: session,
host: host,
waitGroup: &sessionWaitGroup,
cmdOptions: options,
}
go runner.run(cmd)
}
sessionWaitGroup.Wait()
return cmdResult
}
func (runner *runner) run(cmd string) {
defer runner.waitGroup.Done()
defer runner.client.Close()
defer runner.session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
if err := runner.session.RequestPty("xterm", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
// switch the current working directory
cdCmd := ""
if runner.cmdOptions.WorkingDirectory != "" {
cdCmd = "cd " + runner.cmdOptions.WorkingDirectory + " && "
}
cmdStr := cdCmd + cmd
cmdDisplay := cmdStr
sudoChannel := make(chan bool)
if runner.cmdOptions.UseSudo {
cmdStr = WrapSudoCommand(cmdStr)
sudoRunner := sudoRunner{}
sudoRunner.handlePrompt(runner, sudoChannel)
}
OutputRemote(runner.host, cmdDisplay)
// conditionally create the stdOut reader. If using sudo, the sudo handler will
// handle displaying output.
if !runner.cmdOptions.UseSudo {
stdOutReader, err := runner.session.StdoutPipe()
runner.waitGroup.Add(1)
if err != nil {
log.Fatalln(err)
}
stdOutScanner := bufio.NewScanner(stdOutReader)
go func() {
for stdOutScanner.Scan() {
OutputRemote(runner.host, stdOutScanner.Text())
}
defer runner.waitGroup.Done()
}()
}
stdErrReader, err := runner.session.StderrPipe()
runner.waitGroup.Add(1)
if err != nil {
log.Fatalln(err)
}
stdErrScanner := bufio.NewScanner(stdErrReader)
go func() {
for stdErrScanner.Scan() {
OutputRemote(runner.host, stdErrScanner.Text())
}
defer runner.waitGroup.Done()
}()
if err := runner.session.Run(cmdStr); err != nil {
close(sudoChannel)
os.Exit(1)
}
close(sudoChannel)
}
| {
"content_hash": "b4c3735b64e4c2ad5e023eb17aca5ed4",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 83,
"avg_line_length": 21.447552447552447,
"alnum_prop": 0.6817737202477991,
"repo_name": "cgutierrez/gomez",
"id": "f5d9dbccff65e30c7fa407d38b4d4059aac61b12",
"size": "3067",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "remote.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "14111"
}
],
"symlink_target": ""
} |
package org.onepf.opfiab.opfiab_uitest.manager;
import android.support.annotation.NonNull;
import org.onepf.opfiab.listener.BillingListener;
import org.onepf.opfiab.model.event.SetupResponse;
import org.onepf.opfiab.model.event.SetupStartedEvent;
import org.onepf.opfiab.model.event.billing.BillingRequest;
import org.onepf.opfiab.model.event.billing.BillingResponse;
import org.onepf.opfiab.model.event.billing.ConsumeResponse;
import org.onepf.opfiab.model.event.billing.InventoryResponse;
import org.onepf.opfiab.model.event.billing.PurchaseResponse;
import org.onepf.opfiab.model.event.billing.SkuDetailsResponse;
/**
* @author antonpp
* @since 29.05.15
*/
public class BillingManagerAdapter extends TestManagerAdapter implements BillingListener {
public BillingManagerAdapter(final TestManager testManager) {
super(testManager);
}
public BillingManagerAdapter() {
super();
}
@Override
public void onRequest(@NonNull BillingRequest billingRequest) {
validateEvent(billingRequest);
}
@Override
public void onResponse(@NonNull BillingResponse billingResponse) {
// already handled
}
@Override
public void onConsume(@NonNull ConsumeResponse consumeResponse) {
validateEvent(consumeResponse);
}
@Override
public void onInventory(@NonNull InventoryResponse inventoryResponse) {
validateEvent(inventoryResponse);
}
@Override
public void onPurchase(@NonNull PurchaseResponse purchaseResponse) {
validateEvent(purchaseResponse);
}
@Override
public void onSetupStarted(@NonNull SetupStartedEvent setupStartedEvent) {
validateEvent(setupStartedEvent);
}
@Override
public void onSetupResponse(@NonNull SetupResponse setupResponse) {
validateEvent(setupResponse);
}
@Override
public void onSkuDetails(@NonNull SkuDetailsResponse skuDetailsResponse) {
validateEvent(skuDetailsResponse);
}
}
| {
"content_hash": "7d9a16d0c62569835436a088cfd41101",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 90,
"avg_line_length": 28.457142857142856,
"alnum_prop": 0.7479919678714859,
"repo_name": "onepf/OPFIab",
"id": "ec943401ea04b20892c0b886c239ecb1dffc268a",
"size": "2603",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/opfiab-uitest/src/androidTest/java/org/onepf/opfiab/opfiab_uitest/manager/BillingManagerAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "592999"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="13_-_Classes_and_Objects" default="default" basedir=".">
<description>Builds, tests, and runs the project 13 - Classes and Objects.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="13_-_Classes_and_Objects-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>
| {
"content_hash": "cc85662ad991260f9a37363d962b3ea6",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 92,
"avg_line_length": 49.0958904109589,
"alnum_prop": 0.6540178571428571,
"repo_name": "arcyfelix/Courses",
"id": "2ebf18da57a7331d1d7e910e97a3c5da0920c578",
"size": "3584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "17-10-21-Java Tutorial For Complete Beginners/13 - Classes and Objects/build.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "30658"
},
{
"name": "CSS",
"bytes": "68601"
},
{
"name": "Dockerfile",
"bytes": "2012"
},
{
"name": "Elixir",
"bytes": "60760"
},
{
"name": "Groovy",
"bytes": "3605"
},
{
"name": "HTML",
"bytes": "3083919"
},
{
"name": "Java",
"bytes": "561657"
},
{
"name": "JavaScript",
"bytes": "161601"
},
{
"name": "Jupyter Notebook",
"bytes": "95735180"
},
{
"name": "PHP",
"bytes": "82"
},
{
"name": "Python",
"bytes": "185224"
},
{
"name": "Scala",
"bytes": "84149"
},
{
"name": "Shell",
"bytes": "47283"
},
{
"name": "Vue",
"bytes": "90691"
},
{
"name": "XSLT",
"bytes": "88587"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Integrated Taxonomic Information System
#### Published in
Bol. Acad. Nac. Ci. Republ. Argent. 16:249. 1900 (Bol. Acad. Nac. Ci. Republ. Argent. 15:518. 1897, nom. nud. )
#### Original name
null
### Remarks
null | {
"content_hash": "0d1520974e81a3d835d3be14e0cdca6c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 111,
"avg_line_length": 18.46153846153846,
"alnum_prop": 0.6833333333333333,
"repo_name": "mdoering/backbone",
"id": "b396bdb2fffe06fc48da868458e7fdb040c24e69",
"size": "288",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Atriplex/Atriplex lampa/ Syn. Atriplex cachiyuyu/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!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_25) on Thu Jun 18 10:33:36 CDT 2015 -->
<title>org.qoders.exception.handler</title>
<meta name="date" content="2015-06-18">
<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="org.qoders.exception.handler";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/qoders/exception/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/qoders/exception/handler/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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">
<h1 title="Package" class="title">Package org.qoders.exception.handler</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/qoders/exception/handler/RestExceptionControllerAdvise.html" title="class in org.qoders.exception.handler">RestExceptionControllerAdvise</a></td>
<td class="colLast">
<div class="block">Handle all RESTFUL services Exception</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/qoders/exception/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/qoders/exception/handler/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 ======= -->
</body>
</html>
| {
"content_hash": "46cee8d6c6d60df154aba6a6f1747aaf",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 191,
"avg_line_length": 34.673611111111114,
"alnum_prop": 0.6070498698177449,
"repo_name": "qoders/easywallet",
"id": "c66d8be764299f29860f7cb668c677502f795de3",
"size": "4993",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/org/qoders/exception/handler/package-summary.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "143230"
},
{
"name": "HTML",
"bytes": "21322"
},
{
"name": "Java",
"bytes": "142935"
},
{
"name": "JavaScript",
"bytes": "28569"
}
],
"symlink_target": ""
} |
namespace cycamore {
/// SepMaterial returns a material object that represents the composition and
/// quantity resulting from the separation of material from mat using the given
/// mass-based efficiencies. Each key in effs represents a nuclide or element
/// (canonical PyNE form), and each value is the corresponding mass-based
/// separations efficiency for that nuclide or element. Note that this returns
/// an untracked material that should only be used for its composition and qty
/// - not in any real inventories, etc.
cyclus::Material::Ptr SepMaterial(std::map<int, double> effs,
cyclus::Material::Ptr mat);
/// Separations processes feed material into one or more streams containing
/// specific elements and/or nuclides. It uses mass-based efficiencies.
///
/// User defined separations streams are specified as groups of
/// component-efficiency pairs where 'component' means either a particular
/// element or a particular nuclide. Each component's paired efficiency
/// represents the mass fraction of that component in the feed that is
/// separated into that stream. The efficiencies of a particular component
/// across all streams must sum up to less than or equal to one. If less than
/// one, the remainining material is sent to a waste inventory and
/// (potentially) traded away from there.
///
/// The facility receives material into a feed inventory that it processes with
/// a specified throughput each time step. Each output stream has a
/// corresponding output inventory size/limit. If the facility is unable to
/// reduce its stocks by trading and hits this limit for any of its output
/// streams, further processing/separations of feed material will halt until
/// room is again available in the output streams.
class Separations : public cyclus::Facility {
#pragma cyclus note { \
"niche": "separations", \
"doc": \
"Separations processes feed material into one or more streams containing" \
" specific elements and/or nuclides. It uses mass-based efficiencies." \
"\n\n" \
"User defined separations streams are specified as groups of" \
" component-efficiency pairs where 'component' means either a particular" \
" element or a particular nuclide. Each component's paired efficiency" \
" represents the mass fraction of that component in the feed that is" \
" separated into that stream. The efficiencies of a particular component" \
" across all streams must sum up to less than or equal to one. If less than" \
" one, the remainining material is sent to a waste inventory and" \
" (potentially) traded away from there." \
"\n\n" \
"The facility receives material into a feed inventory that it processes with" \
" a specified throughput each time step. Each output stream has a" \
" corresponding output inventory size/limit. If the facility is unable to" \
" reduce its stocks by trading and hits this limit for any of its output" \
" streams, further processing/separations of feed material will halt until" \
" room is again available in the output streams." \
"", \
}
public:
Separations(cyclus::Context* ctx);
virtual ~Separations(){};
virtual std::string version() { return CYCAMORE_VERSION; }
virtual void Tick();
virtual void Tock();
virtual void EnterNotify();
virtual void AcceptMatlTrades(const std::vector<std::pair<
cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses);
virtual std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
GetMatlRequests();
virtual std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> GetMatlBids(
cyclus::CommodMap<cyclus::Material>::type& commod_requests);
virtual void GetMatlTrades(
const std::vector<cyclus::Trade<cyclus::Material> >& trades,
std::vector<std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >& responses);
virtual bool CheckDecommissionCondition();
#pragma cyclus clone
#pragma cyclus initfromcopy
#pragma cyclus infiletodb
#pragma cyclus initfromdb
#pragma cyclus schema
#pragma cyclus annotations
#pragma cyclus snapshot
// the following pragmas are ommitted and the functions are written
// manually in order to handle the vector of resource buffers:
//
// #pragma cyclus snapshotinv
// #pragma cyclus initinv
virtual cyclus::Inventories SnapshotInv();
virtual void InitInv(cyclus::Inventories& inv);
private:
#pragma cyclus var { \
"doc": "Ordered list of commodities on which to request feed material to " \
"separate. Order only matters for matching up with feed commodity " \
"preferences if specified.", \
"uilabel": "Feed Commodity List", \
"uitype": ["oneormore", "incommodity"], \
}
std::vector<std::string> feed_commods;
#pragma cyclus var { \
"default": [], \
"uilabel": "Feed Commodity Preference List", \
"doc": "Feed commodity request preferences for each of the given feed " \
"commodities (same order)." \
" If unspecified, default is to use 1.0 for all "\
"preferences.", \
}
std::vector<double> feed_commod_prefs;
#pragma cyclus var { \
"doc": "Name for recipe to be used in feed requests." \
" Empty string results in use of a dummy recipe.", \
"uilabel": "Feed Commodity Recipe List", \
"uitype": "recipe", \
"default": "", \
}
std::string feed_recipe;
#pragma cyclus var { \
"doc" : "Maximum amount of feed material to keep on hand.", \
"uilabel": "Maximum Feed Inventory", \
"units" : "kg", \
}
double feedbuf_size;
#pragma cyclus var { \
"capacity" : "feedbuf_size", \
}
cyclus::toolkit::ResBuf<cyclus::Material> feed;
#pragma cyclus var { \
"doc" : "Maximum quantity of feed material that can be processed per time "\
"step.", \
"uilabel": "Maximum Separations Throughput", \
"default": 1e299, \
"uitype": "range", \
"range": [0.0, 1e299], \
"units": "kg/(time step)", \
}
double throughput;
#pragma cyclus var { \
"doc": "Commodity on which to trade the leftover separated material " \
"stream. This MUST NOT be the same as any commodity used to define "\
"the other separations streams.", \
"uitype": "outcommodity", \
"uilabel": "Leftover Commodity", \
"default": "default-waste-stream", \
}
std::string leftover_commod;
#pragma cyclus var { \
"doc" : "Maximum amount of leftover separated material (not included in" \
" any other stream) that can be stored." \
" If full, the facility halts operation until space becomes " \
"available.", \
"uilabel": "Maximum Leftover Inventory", \
"default": 1e299, \
"uitype": "range", \
"range": [0.0, 1e299], \
"units": "kg", \
}
double leftoverbuf_size;
#pragma cyclus var { \
"capacity" : "leftoverbuf_size", \
}
cyclus::toolkit::ResBuf<cyclus::Material> leftover;
#pragma cyclus var { \
"alias": ["streams", "commod", ["info", "buf_size", ["efficiencies", "comp", "eff"]]], \
"uitype": ["oneormore", "outcommodity", ["pair", "double", ["oneormore", "nuclide", "double"]]], \
"uilabel": "Separations Streams and Efficiencies", \
"doc": "Output streams for separations." \
" Each stream must have a unique name identifying the commodity on "\
" which its material is traded," \
" a max buffer capacity in kg (neg values indicate infinite size)," \
" and a set of component efficiencies." \
" 'comp' is a component to be separated into the stream" \
" (e.g. U, Pu, etc.) and 'eff' is the mass fraction of the" \
" component that is separated from the feed into this output" \
" stream. If any stream buffer is full, the facility halts" \
" operation until space becomes available." \
" The sum total of all component efficiencies across streams must" \
" be less than or equal to 1" \
" (e.g. sum of U efficiencies for all streams must be <= 1).", \
}
std::map<std::string, std::pair<double, std::map<int, double> > > streams_;
// custom SnapshotInv and InitInv and EnterNotify are used to persist this
// state var.
std::map<std::string, cyclus::toolkit::ResBuf<cyclus::Material> > streambufs;
};
} // namespace cycamore
#endif // CYCAMORE_SRC_SEPARATIONS_H_
| {
"content_hash": "5401f8589dd05959c7f5281c1a43fc87",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 102,
"avg_line_length": 42.03921568627451,
"alnum_prop": 0.6613805970149254,
"repo_name": "gonuke/cycamore",
"id": "b226dc9c8240469cd41f14e3790a1386ce145c04",
"size": "8700",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/separations.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "540"
},
{
"name": "C++",
"bytes": "266271"
},
{
"name": "CMake",
"bytes": "25343"
},
{
"name": "Python",
"bytes": "37286"
},
{
"name": "Shell",
"bytes": "1617"
}
],
"symlink_target": ""
} |
// The MIT License (MIT) - http://opensource.org/licenses/MIT
//
// Copyright (c) 2014 slowfei
//
// Create on 2014-08-16
// Update on 2015-06-12
// Email slowfei#foxmail.com
// Home http://www.slowfei.com
//
package gosfdoc
import (
"bytes"
"encoding/json"
"errors"
"github.com/slowfei/gosfcore/utils/filemanager"
"io/ioutil"
"path"
"path/filepath"
"strings"
)
const (
DEFAULT_CONFIG_FILE_NAME = "gosfdoc.json"
DEFAULT_OUTPATH = "doc"
)
var (
_gosfdocConfigJson = `{
"ScanPath" : %#v,
"CodeLang" : [%v],
"Outpath" : "doc",
"OutAppendPath" : %#v,
"CopyCode" : true,
"CodeLinkRoot" : false,
"HtmlTitle" : "Document",
"DocTitle" : "<b>Document:</b>",
"MenuTitle" : "<center><b>package</b></center>",
"Languages" : [
{"default" : "Default"}
],
"FilterPaths" : []
}`
)
/**
* main config info
* output `gosfdoc.json` use
*/
type MainConfig struct {
path string `json:"-"` // private handle path, save console command path.
currentVersion string `json:"-"` // current output version, private record.
DocUrl string // custom link url to document http. e.g.: http://slowfei.github.io/gosfdoc/index.html
ScanPath string // scan document info file path, relative or absolute path, is "/" scan current console path.
CodeLang []string // code languages
Outpath string // output document path, relative or absolute path.
OutAppendPath string // append output source code and markdown relative path(scan path join). defalut ""
CopyCode bool // copy source code to document directory. default false
CodeLinkRoot bool // source code link to root directory, 'CopyCode' is true was invalid, default true
HtmlTitle string // document html show title
DocTitle string // html top tabbar show title
MenuTitle string // html left menu show title
Languages []map[string]string // document support the language. key is directory name, value is show text.
FilterPaths []string // filter path, relative or absolute path
}
/**
* set absolute path
*/
func (mc *MainConfig) setAbspath() {
mc.path = SFFileManager.GetCmdDir()
if 0 == len(mc.ScanPath) || "/" == mc.ScanPath {
mc.ScanPath = mc.path
} else if !filepath.IsAbs(mc.ScanPath) {
mc.ScanPath = filepath.Join(mc.path, mc.ScanPath)
}
if 0 == len(mc.Outpath) {
mc.Outpath = filepath.Join(mc.ScanPath, DEFAULT_OUTPATH)
} else if !filepath.IsAbs(mc.Outpath) {
mc.Outpath = filepath.Join(mc.ScanPath, mc.Outpath)
}
for i := 0; i < len(mc.FilterPaths); i++ {
p := mc.FilterPaths[i]
if !filepath.IsAbs(p) {
mc.FilterPaths[i] = filepath.Join(mc.ScanPath, p)
}
}
}
/**
* check config param value
* error value will update default.
*
* @return error
* @return bool fatal error is false, pass is true. (pass does not mean that there are no errors)
*/
func (mc *MainConfig) Check() (error, bool) {
errBuf := bytes.NewBufferString("")
pass := true
mc.path = SFFileManager.GetCmdDir()
if 0 == len(mc.ScanPath) {
errBuf.WriteString("ScanPath: please set document scan path.\n")
pass = false
}
if 0 == len(mc.CodeLang) {
errBuf.WriteString("CodeLang: specify code language type nil.\n")
pass = false
} else {
count := len(mc.CodeLang)
for i := 0; i < count; i++ {
lang := mc.CodeLang[i]
if _, ok := _mapParser[lang]; !ok {
errBuf.WriteString("CodeLang: not " + lang + " Parser.\n")
}
}
}
if 0 != len(mc.OutAppendPath) && filepath.IsAbs(mc.OutAppendPath) {
errBuf.WriteString("OutAppendPath: please use relative path.\n")
// 这里主要怕效验不通过后强制执行,所以强行修改默认的OutAppendPath
tempPath := filepath.Base(mc.path)
if "src" == tempPath {
tempPath = ""
}
mc.OutAppendPath = tempPath
pass = false
}
if 0 == len(mc.Outpath) {
errBuf.WriteString("Outpath: output directory is nil, will use 'doc' default directory.\n")
mc.Outpath = DEFAULT_OUTPATH
}
if 0 == len(mc.HtmlTitle) {
mc.HtmlTitle = "Document"
errBuf.WriteString("HtmlTitle: to set the html title.\n")
}
if 0 == len(mc.DocTitle) {
mc.DocTitle = "<b>Document:</b>"
errBuf.WriteString("DocTitle: to set the doc title.\n")
}
if 0 == len(mc.MenuTitle) {
mc.MenuTitle = "<center><b>package</b></center>"
errBuf.WriteString("MenuTitle: to set the menu title.\n")
}
if 0 == len(mc.Languages) {
mc.Languages = []map[string]string{map[string]string{"Default": "default"}}
errBuf.WriteString("Languages: to set the default html text language.\n")
} else {
for _, mapv := range mc.Languages {
if _, ok := mapv["default"]; !ok {
mapv["default"] = "Default"
errBuf.WriteString("Languages: to set the default html text language.\n")
}
}
}
var err error = nil
if 0 != errBuf.Len() {
err = errors.New(errBuf.String())
}
return err, pass
}
/**
* to github.com link path
* use on a tag href
*
* append path relative path
* e.g.: https://.../project/doc/v1_0_0/md/default/(github.com/slowfei)/(temp/gosfdoc.md)
* to: https://.../project/doc/v1_0_0/src/github.com/slowfei/gosfdoc.go (to source code path)
* to: https://.../project/doc/v1_0_0/md/default/github.com/test/test.md (to markdown path)
*
* @param `relMDPath` relative markdown out project path.
* relative path: $GOPATH/[github.com/slowfei]/projectname/( .../markdown.md )
* @param `isToMarkdown` to markdown link? false is source code access path
* @return use github.com to relative link. "../../../" or "../../src/[projectname]"
*/
func (m MainConfig) GithubLink(relMDPath string, isToMarkdown bool) string {
resultPath := ""
backRel := ""
appendPath := m.OutAppendPath
appendPath = strings.TrimSuffix(appendPath, "/")
appendPath = strings.TrimPrefix(appendPath, "/")
pathSplit := strings.Split(appendPath, "/")
for _, p := range pathSplit {
if 0 != len(p) {
backRel += "../"
}
}
relMDPath = path.Dir(relMDPath)
relMDPath = strings.TrimPrefix(relMDPath, "/")
relMDPath = strings.TrimSuffix(relMDPath, "/")
// // 可能出现的问题,Dir("") == "."
// // 所以需要判断"."的处理
// if 0 != len(relMDPath) && "." != relMDPath {
// pathSplit = strings.Split(relMDPath, "/")
// for _, p := range pathSplit {
// if 0 != len(p) {
// backRel += "../"
// }
// }
// }
if isToMarkdown {
// https://.../project/doc/v1_0_0/md/default/
resultPath = backRel
} else if m.CodeLinkRoot {
// https://.../project/blob/master/doc/v1_0_0/src/packagepath/file.go
// to
resultPath = path.Join("../../../../", backRel, relMDPath)
// resultPath = "../../../../" + backRel
} else {
// https://.../project/blob/master/doc/v1_0_0/src/packagepath/file.go
// resultPath = "../../" + backRel + "src" + relMDPath
resultPath = path.Join("../../", backRel, "src", path.Join(appendPath, relMDPath))
}
return resultPath
}
/**
* html menu show helper struct
* index.html Markdown struct
*/
type MenuMarkdown struct {
MenuName string
Version string
List []PackageInfo
}
/**
* html menu show helper struct
* src.html File list struct
*/
type MenuFile struct {
MenuName string
Version string
List []FileLink
}
/**
* document directory html javascript use config
*
* output `config.json`
*/
type DocConfig struct {
ContentJson string // content json file
IntroMd string // intro markdown file
AboutMd string // about markdown file
Languages []map[string]string // key is directory name, value is show text
LinkRoot bool // is link root directory
AppendPath string // append output source code and markdown relative path(scan path join)
Versions []string // output document versions
Markdowns []MenuMarkdown // markdown info list
Files []MenuFile // source code file links
}
/**
* read document config `config.json`
*
* @param `path`
* @return
*/
func readDocConifg(path string) DocConfig {
result := DocConfig{}
isExists, isDir, _ := SFFileManager.Exists(path)
if isExists && !isDir {
jsonData, _ := ioutil.ReadFile(path)
if nil != jsonData && 0 != len(jsonData) {
json.Unmarshal(jsonData, &result)
}
}
return result
}
/**
* conifg load
*
* @param jsonData
* @return load error info
*/
func configLoadByJson(jsonData []byte, c *MainConfig) error {
e2 := json.Unmarshal(jsonData, c)
if nil != e2 {
return e2
}
return nil
}
/**
* conifg load
*
* @param configPath
* @return error info
*/
func configLoadByFilepath(configPath string, c *MainConfig) error {
var path string
if filepath.IsAbs(configPath) { /*temp
ll
*/
path = configPath
} else {
path = filepath.Join(SFFileManager.GetExecDir(), configPath)
}
isExists, isDir, _ := SFFileManager.Exists(path)
if !isExists || isDir {
return errors.New("failed to load configuration file:" + configPath)
}
jsonData, e1 := ioutil.ReadFile(path)
if nil != e1 {
return e1
}
return configLoadByJson(jsonData, c)
}
| {
"content_hash": "46ce7074a941f9137097190bb60a74b0",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 129,
"avg_line_length": 27.650887573964496,
"alnum_prop": 0.6158784506740852,
"repo_name": "slowfei/gosfdoc",
"id": "95e0eabb97ad3966d4168650bf9e60549751ae3c",
"size": "9430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test-template/doc/v1_0_1/src/gosfdoc.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "367980"
},
{
"name": "Go",
"bytes": "778457"
},
{
"name": "HTML",
"bytes": "6614"
},
{
"name": "JavaScript",
"bytes": "478262"
}
],
"symlink_target": ""
} |
package org.hl7.fhir.instance.model;
// Generated on Tue, Oct 21, 2014 07:07+1100 for FHIR v0.3.0
import java.util.*;
/**
* Records an unexpected reaction suspected to be related to the exposure of the reaction subject to a substance.
*/
public class AdverseReaction extends Resource {
public enum ReactionSeverity {
SEVERE, // Severe complications arose due to the reaction.
SERIOUS, // Serious inconvenience to the subject.
MODERATE, // Moderate inconvenience to the subject.
MINOR, // Minor inconvenience to the subject.
NULL; // added to help the parsers
public static ReactionSeverity fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("severe".equals(codeString))
return SEVERE;
if ("serious".equals(codeString))
return SERIOUS;
if ("moderate".equals(codeString))
return MODERATE;
if ("minor".equals(codeString))
return MINOR;
throw new Exception("Unknown ReactionSeverity code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case SEVERE: return "severe";
case SERIOUS: return "serious";
case MODERATE: return "moderate";
case MINOR: return "minor";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case SEVERE: return "Severe complications arose due to the reaction.";
case SERIOUS: return "Serious inconvenience to the subject.";
case MODERATE: return "Moderate inconvenience to the subject.";
case MINOR: return "Minor inconvenience to the subject.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case SEVERE: return "";
case SERIOUS: return "";
case MODERATE: return "";
case MINOR: return "";
default: return "?";
}
}
}
public static class ReactionSeverityEnumFactory implements EnumFactory {
public Enum<?> fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("severe".equals(codeString))
return ReactionSeverity.SEVERE;
if ("serious".equals(codeString))
return ReactionSeverity.SERIOUS;
if ("moderate".equals(codeString))
return ReactionSeverity.MODERATE;
if ("minor".equals(codeString))
return ReactionSeverity.MINOR;
throw new Exception("Unknown ReactionSeverity code '"+codeString+"'");
}
public String toCode(Enum<?> code) throws Exception {
if (code == ReactionSeverity.SEVERE)
return "severe";
if (code == ReactionSeverity.SERIOUS)
return "serious";
if (code == ReactionSeverity.MODERATE)
return "moderate";
if (code == ReactionSeverity.MINOR)
return "minor";
return "?";
}
}
public enum ExposureType {
DRUGADMIN, // Drug Administration.
IMMUNIZ, // Immunization.
COINCIDENTAL, // In the same area as the substance.
NULL; // added to help the parsers
public static ExposureType fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("drugadmin".equals(codeString))
return DRUGADMIN;
if ("immuniz".equals(codeString))
return IMMUNIZ;
if ("coincidental".equals(codeString))
return COINCIDENTAL;
throw new Exception("Unknown ExposureType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case DRUGADMIN: return "drugadmin";
case IMMUNIZ: return "immuniz";
case COINCIDENTAL: return "coincidental";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case DRUGADMIN: return "Drug Administration.";
case IMMUNIZ: return "Immunization.";
case COINCIDENTAL: return "In the same area as the substance.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case DRUGADMIN: return "";
case IMMUNIZ: return "";
case COINCIDENTAL: return "";
default: return "?";
}
}
}
public static class ExposureTypeEnumFactory implements EnumFactory {
public Enum<?> fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("drugadmin".equals(codeString))
return ExposureType.DRUGADMIN;
if ("immuniz".equals(codeString))
return ExposureType.IMMUNIZ;
if ("coincidental".equals(codeString))
return ExposureType.COINCIDENTAL;
throw new Exception("Unknown ExposureType code '"+codeString+"'");
}
public String toCode(Enum<?> code) throws Exception {
if (code == ExposureType.DRUGADMIN)
return "drugadmin";
if (code == ExposureType.IMMUNIZ)
return "immuniz";
if (code == ExposureType.COINCIDENTAL)
return "coincidental";
return "?";
}
}
public enum CausalityExpectation {
LIKELY, // Likely that this specific exposure caused the reaction.
UNLIKELY, // Unlikely that this specific exposure caused the reaction - the exposure is being linked to for information purposes.
CONFIRMED, // It has been confirmed that this exposure was one of the causes of the reaction.
UNKNOWN, // It is unknown whether this exposure had anything to do with the reaction.
NULL; // added to help the parsers
public static CausalityExpectation fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("likely".equals(codeString))
return LIKELY;
if ("unlikely".equals(codeString))
return UNLIKELY;
if ("confirmed".equals(codeString))
return CONFIRMED;
if ("unknown".equals(codeString))
return UNKNOWN;
throw new Exception("Unknown CausalityExpectation code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case LIKELY: return "likely";
case UNLIKELY: return "unlikely";
case CONFIRMED: return "confirmed";
case UNKNOWN: return "unknown";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case LIKELY: return "Likely that this specific exposure caused the reaction.";
case UNLIKELY: return "Unlikely that this specific exposure caused the reaction - the exposure is being linked to for information purposes.";
case CONFIRMED: return "It has been confirmed that this exposure was one of the causes of the reaction.";
case UNKNOWN: return "It is unknown whether this exposure had anything to do with the reaction.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case LIKELY: return "";
case UNLIKELY: return "";
case CONFIRMED: return "";
case UNKNOWN: return "";
default: return "?";
}
}
}
public static class CausalityExpectationEnumFactory implements EnumFactory {
public Enum<?> fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("likely".equals(codeString))
return CausalityExpectation.LIKELY;
if ("unlikely".equals(codeString))
return CausalityExpectation.UNLIKELY;
if ("confirmed".equals(codeString))
return CausalityExpectation.CONFIRMED;
if ("unknown".equals(codeString))
return CausalityExpectation.UNKNOWN;
throw new Exception("Unknown CausalityExpectation code '"+codeString+"'");
}
public String toCode(Enum<?> code) throws Exception {
if (code == CausalityExpectation.LIKELY)
return "likely";
if (code == CausalityExpectation.UNLIKELY)
return "unlikely";
if (code == CausalityExpectation.CONFIRMED)
return "confirmed";
if (code == CausalityExpectation.UNKNOWN)
return "unknown";
return "?";
}
}
public static class AdverseReactionSymptomComponent extends BackboneElement {
/**
* Indicates the specific sign or symptom that was observed.
*/
protected CodeableConcept code;
/**
* The severity of the sign or symptom.
*/
protected Enumeration<ReactionSeverity> severity;
private static final long serialVersionUID = -1856198542L;
public AdverseReactionSymptomComponent() {
super();
}
public AdverseReactionSymptomComponent(CodeableConcept code) {
super();
this.code = code;
}
/**
* @return {@link #code} (Indicates the specific sign or symptom that was observed.)
*/
public CodeableConcept getCode() {
return this.code;
}
/**
* @param value {@link #code} (Indicates the specific sign or symptom that was observed.)
*/
public AdverseReactionSymptomComponent setCode(CodeableConcept value) {
this.code = value;
return this;
}
/**
* @return {@link #severity} (The severity of the sign or symptom.). This is the underlying object with id, value and extensions. The accessor "getSeverity" gives direct access to the value
*/
public Enumeration<ReactionSeverity> getSeverityElement() {
return this.severity;
}
/**
* @param value {@link #severity} (The severity of the sign or symptom.). This is the underlying object with id, value and extensions. The accessor "getSeverity" gives direct access to the value
*/
public AdverseReactionSymptomComponent setSeverityElement(Enumeration<ReactionSeverity> value) {
this.severity = value;
return this;
}
/**
* @return The severity of the sign or symptom.
*/
public ReactionSeverity getSeverity() {
return this.severity == null ? null : this.severity.getValue();
}
/**
* @param value The severity of the sign or symptom.
*/
public AdverseReactionSymptomComponent setSeverity(ReactionSeverity value) {
if (value == null)
this.severity = null;
else {
if (this.severity == null)
this.severity = new Enumeration<ReactionSeverity>();
this.severity.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("code", "CodeableConcept", "Indicates the specific sign or symptom that was observed.", 0, java.lang.Integer.MAX_VALUE, code));
childrenList.add(new Property("severity", "code", "The severity of the sign or symptom.", 0, java.lang.Integer.MAX_VALUE, severity));
}
public AdverseReactionSymptomComponent copy() {
AdverseReactionSymptomComponent dst = new AdverseReactionSymptomComponent();
dst.code = code == null ? null : code.copy();
dst.severity = severity == null ? null : severity.copy();
return dst;
}
}
public static class AdverseReactionExposureComponent extends BackboneElement {
/**
* Identifies the initial date of the exposure that is suspected to be related to the reaction.
*/
protected DateTimeType date;
/**
* The type of exposure: Drug Administration, Immunization, Coincidental.
*/
protected Enumeration<ExposureType> type;
/**
* A statement of how confident that the recorder was that this exposure caused the reaction.
*/
protected Enumeration<CausalityExpectation> causalityExpectation;
/**
* Substance that is presumed to have caused the adverse reaction.
*/
protected Reference substance;
/**
* The actual object that is the target of the reference (Substance that is presumed to have caused the adverse reaction.)
*/
protected Substance substanceTarget;
private static final long serialVersionUID = 1654286186L;
public AdverseReactionExposureComponent() {
super();
}
/**
* @return {@link #date} (Identifies the initial date of the exposure that is suspected to be related to the reaction.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value
*/
public DateTimeType getDateElement() {
return this.date;
}
/**
* @param value {@link #date} (Identifies the initial date of the exposure that is suspected to be related to the reaction.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value
*/
public AdverseReactionExposureComponent setDateElement(DateTimeType value) {
this.date = value;
return this;
}
/**
* @return Identifies the initial date of the exposure that is suspected to be related to the reaction.
*/
public DateAndTime getDate() {
return this.date == null ? null : this.date.getValue();
}
/**
* @param value Identifies the initial date of the exposure that is suspected to be related to the reaction.
*/
public AdverseReactionExposureComponent setDate(DateAndTime value) {
if (value == null)
this.date = null;
else {
if (this.date == null)
this.date = new DateTimeType();
this.date.setValue(value);
}
return this;
}
/**
* @return {@link #type} (The type of exposure: Drug Administration, Immunization, Coincidental.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Enumeration<ExposureType> getTypeElement() {
return this.type;
}
/**
* @param value {@link #type} (The type of exposure: Drug Administration, Immunization, Coincidental.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public AdverseReactionExposureComponent setTypeElement(Enumeration<ExposureType> value) {
this.type = value;
return this;
}
/**
* @return The type of exposure: Drug Administration, Immunization, Coincidental.
*/
public ExposureType getType() {
return this.type == null ? null : this.type.getValue();
}
/**
* @param value The type of exposure: Drug Administration, Immunization, Coincidental.
*/
public AdverseReactionExposureComponent setType(ExposureType value) {
if (value == null)
this.type = null;
else {
if (this.type == null)
this.type = new Enumeration<ExposureType>();
this.type.setValue(value);
}
return this;
}
/**
* @return {@link #causalityExpectation} (A statement of how confident that the recorder was that this exposure caused the reaction.). This is the underlying object with id, value and extensions. The accessor "getCausalityExpectation" gives direct access to the value
*/
public Enumeration<CausalityExpectation> getCausalityExpectationElement() {
return this.causalityExpectation;
}
/**
* @param value {@link #causalityExpectation} (A statement of how confident that the recorder was that this exposure caused the reaction.). This is the underlying object with id, value and extensions. The accessor "getCausalityExpectation" gives direct access to the value
*/
public AdverseReactionExposureComponent setCausalityExpectationElement(Enumeration<CausalityExpectation> value) {
this.causalityExpectation = value;
return this;
}
/**
* @return A statement of how confident that the recorder was that this exposure caused the reaction.
*/
public CausalityExpectation getCausalityExpectation() {
return this.causalityExpectation == null ? null : this.causalityExpectation.getValue();
}
/**
* @param value A statement of how confident that the recorder was that this exposure caused the reaction.
*/
public AdverseReactionExposureComponent setCausalityExpectation(CausalityExpectation value) {
if (value == null)
this.causalityExpectation = null;
else {
if (this.causalityExpectation == null)
this.causalityExpectation = new Enumeration<CausalityExpectation>();
this.causalityExpectation.setValue(value);
}
return this;
}
/**
* @return {@link #substance} (Substance that is presumed to have caused the adverse reaction.)
*/
public Reference getSubstance() {
return this.substance;
}
/**
* @param value {@link #substance} (Substance that is presumed to have caused the adverse reaction.)
*/
public AdverseReactionExposureComponent setSubstance(Reference value) {
this.substance = value;
return this;
}
/**
* @return {@link #substance} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Substance that is presumed to have caused the adverse reaction.)
*/
public Substance getSubstanceTarget() {
return this.substanceTarget;
}
/**
* @param value {@link #substance} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Substance that is presumed to have caused the adverse reaction.)
*/
public AdverseReactionExposureComponent setSubstanceTarget(Substance value) {
this.substanceTarget = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("date", "dateTime", "Identifies the initial date of the exposure that is suspected to be related to the reaction.", 0, java.lang.Integer.MAX_VALUE, date));
childrenList.add(new Property("type", "code", "The type of exposure: Drug Administration, Immunization, Coincidental.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("causalityExpectation", "code", "A statement of how confident that the recorder was that this exposure caused the reaction.", 0, java.lang.Integer.MAX_VALUE, causalityExpectation));
childrenList.add(new Property("substance", "Reference(Substance)", "Substance that is presumed to have caused the adverse reaction.", 0, java.lang.Integer.MAX_VALUE, substance));
}
public AdverseReactionExposureComponent copy() {
AdverseReactionExposureComponent dst = new AdverseReactionExposureComponent();
dst.date = date == null ? null : date.copy();
dst.type = type == null ? null : type.copy();
dst.causalityExpectation = causalityExpectation == null ? null : causalityExpectation.copy();
dst.substance = substance == null ? null : substance.copy();
return dst;
}
}
/**
* This records identifiers associated with this reaction that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).
*/
protected List<Identifier> identifier = new ArrayList<Identifier>();
/**
* The date (and possibly time) when the reaction began.
*/
protected DateTimeType date;
/**
* The subject of the adverse reaction.
*/
protected Reference subject;
/**
* The actual object that is the target of the reference (The subject of the adverse reaction.)
*/
protected Patient subjectTarget;
/**
* If true, indicates that no reaction occurred.
*/
protected BooleanType didNotOccurFlag;
/**
* Identifies the individual responsible for the information in the reaction record.
*/
protected Reference recorder;
/**
* The actual object that is the target of the reference (Identifies the individual responsible for the information in the reaction record.)
*/
protected Resource recorderTarget;
/**
* The signs and symptoms that were observed as part of the reaction.
*/
protected List<AdverseReactionSymptomComponent> symptom = new ArrayList<AdverseReactionSymptomComponent>();
/**
* An exposure to a substance that preceded a reaction occurrence.
*/
protected List<AdverseReactionExposureComponent> exposure = new ArrayList<AdverseReactionExposureComponent>();
private static final long serialVersionUID = 264165454L;
public AdverseReaction() {
super();
}
public AdverseReaction(Reference subject, BooleanType didNotOccurFlag) {
super();
this.subject = subject;
this.didNotOccurFlag = didNotOccurFlag;
}
/**
* @return {@link #identifier} (This records identifiers associated with this reaction that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).)
*/
public List<Identifier> getIdentifier() {
return this.identifier;
}
// syntactic sugar
/**
* @return {@link #identifier} (This records identifiers associated with this reaction that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).)
*/
public Identifier addIdentifier() {
Identifier t = new Identifier();
this.identifier.add(t);
return t;
}
/**
* @return {@link #date} (The date (and possibly time) when the reaction began.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value
*/
public DateTimeType getDateElement() {
return this.date;
}
/**
* @param value {@link #date} (The date (and possibly time) when the reaction began.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value
*/
public AdverseReaction setDateElement(DateTimeType value) {
this.date = value;
return this;
}
/**
* @return The date (and possibly time) when the reaction began.
*/
public DateAndTime getDate() {
return this.date == null ? null : this.date.getValue();
}
/**
* @param value The date (and possibly time) when the reaction began.
*/
public AdverseReaction setDate(DateAndTime value) {
if (value == null)
this.date = null;
else {
if (this.date == null)
this.date = new DateTimeType();
this.date.setValue(value);
}
return this;
}
/**
* @return {@link #subject} (The subject of the adverse reaction.)
*/
public Reference getSubject() {
return this.subject;
}
/**
* @param value {@link #subject} (The subject of the adverse reaction.)
*/
public AdverseReaction setSubject(Reference value) {
this.subject = value;
return this;
}
/**
* @return {@link #subject} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The subject of the adverse reaction.)
*/
public Patient getSubjectTarget() {
return this.subjectTarget;
}
/**
* @param value {@link #subject} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The subject of the adverse reaction.)
*/
public AdverseReaction setSubjectTarget(Patient value) {
this.subjectTarget = value;
return this;
}
/**
* @return {@link #didNotOccurFlag} (If true, indicates that no reaction occurred.). This is the underlying object with id, value and extensions. The accessor "getDidNotOccurFlag" gives direct access to the value
*/
public BooleanType getDidNotOccurFlagElement() {
return this.didNotOccurFlag;
}
/**
* @param value {@link #didNotOccurFlag} (If true, indicates that no reaction occurred.). This is the underlying object with id, value and extensions. The accessor "getDidNotOccurFlag" gives direct access to the value
*/
public AdverseReaction setDidNotOccurFlagElement(BooleanType value) {
this.didNotOccurFlag = value;
return this;
}
/**
* @return If true, indicates that no reaction occurred.
*/
public boolean getDidNotOccurFlag() {
return this.didNotOccurFlag == null ? false : this.didNotOccurFlag.getValue();
}
/**
* @param value If true, indicates that no reaction occurred.
*/
public AdverseReaction setDidNotOccurFlag(boolean value) {
if (this.didNotOccurFlag == null)
this.didNotOccurFlag = new BooleanType();
this.didNotOccurFlag.setValue(value);
return this;
}
/**
* @return {@link #recorder} (Identifies the individual responsible for the information in the reaction record.)
*/
public Reference getRecorder() {
return this.recorder;
}
/**
* @param value {@link #recorder} (Identifies the individual responsible for the information in the reaction record.)
*/
public AdverseReaction setRecorder(Reference value) {
this.recorder = value;
return this;
}
/**
* @return {@link #recorder} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies the individual responsible for the information in the reaction record.)
*/
public Resource getRecorderTarget() {
return this.recorderTarget;
}
/**
* @param value {@link #recorder} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies the individual responsible for the information in the reaction record.)
*/
public AdverseReaction setRecorderTarget(Resource value) {
this.recorderTarget = value;
return this;
}
/**
* @return {@link #symptom} (The signs and symptoms that were observed as part of the reaction.)
*/
public List<AdverseReactionSymptomComponent> getSymptom() {
return this.symptom;
}
// syntactic sugar
/**
* @return {@link #symptom} (The signs and symptoms that were observed as part of the reaction.)
*/
public AdverseReactionSymptomComponent addSymptom() {
AdverseReactionSymptomComponent t = new AdverseReactionSymptomComponent();
this.symptom.add(t);
return t;
}
/**
* @return {@link #exposure} (An exposure to a substance that preceded a reaction occurrence.)
*/
public List<AdverseReactionExposureComponent> getExposure() {
return this.exposure;
}
// syntactic sugar
/**
* @return {@link #exposure} (An exposure to a substance that preceded a reaction occurrence.)
*/
public AdverseReactionExposureComponent addExposure() {
AdverseReactionExposureComponent t = new AdverseReactionExposureComponent();
this.exposure.add(t);
return t;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "This records identifiers associated with this reaction that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("date", "dateTime", "The date (and possibly time) when the reaction began.", 0, java.lang.Integer.MAX_VALUE, date));
childrenList.add(new Property("subject", "Reference(Patient)", "The subject of the adverse reaction.", 0, java.lang.Integer.MAX_VALUE, subject));
childrenList.add(new Property("didNotOccurFlag", "boolean", "If true, indicates that no reaction occurred.", 0, java.lang.Integer.MAX_VALUE, didNotOccurFlag));
childrenList.add(new Property("recorder", "Reference(Practitioner|Patient)", "Identifies the individual responsible for the information in the reaction record.", 0, java.lang.Integer.MAX_VALUE, recorder));
childrenList.add(new Property("symptom", "", "The signs and symptoms that were observed as part of the reaction.", 0, java.lang.Integer.MAX_VALUE, symptom));
childrenList.add(new Property("exposure", "", "An exposure to a substance that preceded a reaction occurrence.", 0, java.lang.Integer.MAX_VALUE, exposure));
}
public AdverseReaction copy() {
AdverseReaction dst = new AdverseReaction();
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
dst.date = date == null ? null : date.copy();
dst.subject = subject == null ? null : subject.copy();
dst.didNotOccurFlag = didNotOccurFlag == null ? null : didNotOccurFlag.copy();
dst.recorder = recorder == null ? null : recorder.copy();
dst.symptom = new ArrayList<AdverseReactionSymptomComponent>();
for (AdverseReactionSymptomComponent i : symptom)
dst.symptom.add(i.copy());
dst.exposure = new ArrayList<AdverseReactionExposureComponent>();
for (AdverseReactionExposureComponent i : exposure)
dst.exposure.add(i.copy());
return dst;
}
protected AdverseReaction typedCopy() {
return copy();
}
@Override
public ResourceType getResourceType() {
return ResourceType.AdverseReaction;
}
}
| {
"content_hash": "f8f5fee454d2f0a245213063948735b8",
"timestamp": "",
"source": "github",
"line_count": 785,
"max_line_length": 370,
"avg_line_length": 41.49554140127388,
"alnum_prop": 0.6212623564806288,
"repo_name": "cqframework/ProfileGenerator",
"id": "32c0da818c7b3b7a64888ba42145bd46c364bbb1",
"size": "34151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FhirReferenceImpl/src/main/java/org/hl7/fhir/instance/model/AdverseReaction.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3168"
},
{
"name": "Groovy",
"bytes": "16567"
},
{
"name": "Java",
"bytes": "5303309"
},
{
"name": "Shell",
"bytes": "257"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Tabebuia coralibe Standl.
### Remarks
null | {
"content_hash": "b71625e090d0ca2e468d606033f4e988",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 11.307692307692308,
"alnum_prop": 0.7278911564625851,
"repo_name": "mdoering/backbone",
"id": "03ca4cd19e9fc5dd7f1cab0147efc3a3f54b83b9",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Bignoniaceae/Handroanthus/Handroanthus coralibe/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
title: About Me
header-img: "img/bg.png"
description: "This is what I do."
layout: page
---
[<img src="/wp-content/uploads/2014/12/gjermund_round-300x300.png" width="300" height="300" style="margin-left: auto; margin-right: auto"/>](/wp-content/uploads/2014/12/gjermund_round.png)
My name is Gjermund Bjaanes. I am 27 years old, born and raised in Norway. I am a developer, geek, enthusiast and innovator. I’m passionate about software engineering and all things new and fancy in tech.
Currently I focus mostly on innovation and new technology. It's what I do while working, and it's mostly what I do when not working - because I am truly passionate. It's what I live for.
I am a software engineer and innovator by trade and **by passion**.
I have always had a very enthusiastic interest for computers, dated to when I was little. It became an obsession for programming, IT, gadgets and new technology.
I worked as a pure developer for a few years, before diving into a more innovative position where I can explore and tinker with technology in a much more interesting way. I love to learn, and I love to create.
Other than that; In my spare time I like to code, read, cook, hang out with friends and to work out.
* * *
I am employed at Flatirons as a Technical Leader of Innovation. That means that my job is find new innovative use cases we can work with - while getting to play with (err, learn about) a lot of cool new tech!
* * * | {
"content_hash": "6fdddf2cb8dcee6c44ae399dedd13b68",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 211,
"avg_line_length": 63.08695652173913,
"alnum_prop": 0.7553411440385941,
"repo_name": "bjaanes/bjaanes.github.io",
"id": "dab38339386552798510b96141de7de21e2b10c0",
"size": "1456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "about-me.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22260"
},
{
"name": "HTML",
"bytes": "18202"
},
{
"name": "JavaScript",
"bytes": "56133"
},
{
"name": "PHP",
"bytes": "1242"
},
{
"name": "Ruby",
"bytes": "200"
}
],
"symlink_target": ""
} |
package com.mcleodmoores.config;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.id.VersionCorrection;
import com.opengamma.util.ArgumentChecker;
/**
* Wrapper for a configuration validator that gets a {@link ConfigSource} from a compilation context.
* @param <U> the type of the configuration to be validated
* @param <V> the type of the configurations that have been validated
*/
public final class CompilationContextConfigurationValidator<U, V> {
/** The underlying validator */
private final ConfigurationValidator<U, V> _validator;
/**
* Gets a validator.
* @param validator the underlying validator, not null
* @return the validator
* @param <U> the type of the configuration to be validated
* @param <V> the type of the configurations that have been validated
*/
public static <U, V> CompilationContextConfigurationValidator<U, V> of(final ConfigurationValidator<U, V> validator) {
ArgumentChecker.notNull(validator, "validator");
return new CompilationContextConfigurationValidator<>(validator);
}
/**
* Restricted constructor.
* @param validator the underlying validator
*/
private CompilationContextConfigurationValidator(final ConfigurationValidator<U, V> validator) {
_validator = validator;
}
/**
* Validates the latest version of a configuration.
* @param configuration the configuration, not null
* @param compilationContext the compilation context, not null
* @return the validation information
*/
public ConfigurationValidationInfo<V> validate(final U configuration, final FunctionCompilationContext compilationContext) {
return validate(configuration, VersionCorrection.LATEST, compilationContext);
}
/**
* Validates a configuration.
* @param configuration the configuration, not null
* @param versionCorrection the configuration version, not null
* @param compilationContext the compilation context, not null
* @return the validation information
*/
public ConfigurationValidationInfo<V> validate(final U configuration, final VersionCorrection versionCorrection,
final FunctionCompilationContext compilationContext) {
ArgumentChecker.notNull(configuration, "configuration");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
ArgumentChecker.notNull(compilationContext, "compilationContext");
final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(compilationContext);
if (configSource == null) {
throw new IllegalStateException("ConfigSource not set in function compilation context");
}
return _validator.validate(configuration, versionCorrection, configSource);
}
}
| {
"content_hash": "a582efb18cd7201c9139caab224001b0",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 126,
"avg_line_length": 41.73529411764706,
"alnum_prop": 0.7677942212825933,
"repo_name": "McLeodMoores/starling",
"id": "06821ad46ee4f73eadaffbdc4ed9b19c00b4bac9",
"size": "2929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/validation/src/main/java/com/mcleodmoores/config/CompilationContextConfigurationValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2505"
},
{
"name": "CSS",
"bytes": "213501"
},
{
"name": "FreeMarker",
"bytes": "310184"
},
{
"name": "GAP",
"bytes": "1490"
},
{
"name": "Groovy",
"bytes": "11518"
},
{
"name": "HTML",
"bytes": "318295"
},
{
"name": "Java",
"bytes": "79541905"
},
{
"name": "JavaScript",
"bytes": "1511230"
},
{
"name": "PLSQL",
"bytes": "398"
},
{
"name": "PLpgSQL",
"bytes": "26901"
},
{
"name": "Shell",
"bytes": "11481"
},
{
"name": "TSQL",
"bytes": "604117"
}
],
"symlink_target": ""
} |
* Added support for TypeScript 4.9.
## 0.3.3
No user-facing changes.
## 0.3.2
No user-facing changes.
## 0.3.1
### Minor Analysis Improvements
- Several of the SQL and NoSQL library models have improved, leading to more results for the `js/sql-injection` query,
and in some cases the `js/missing-rate-limiting` query.
## 0.3.0
### Breaking Changes
* Many library models have been rewritten to use dataflow nodes instead of the AST.
The types of some classes have been changed, and these changes may break existing code.
Other classes and predicates have been renamed, in these cases the old name is still available as a deprecated feature.
* The basetype of the following list of classes has changed from an expression to a dataflow node, and thus code using these classes might break.
The fix to these breakages is usually to use `asExpr()` to get an expression from a dataflow node, or to use `.flow()` to get a dataflow node from an expression.
- DOM.qll#WebStorageWrite
- CryptoLibraries.qll#CryptographicOperation
- Express.qll#Express::RequestBodyAccess
- HTTP.qll#HTTP::ResponseBody
- HTTP.qll#HTTP::CookieDefinition
- HTTP.qll#HTTP::ServerDefinition
- HTTP.qll#HTTP::RouteSetup
- NoSQL.qll#NoSql::Query
- SQL.qll#SQL::SqlString
- SQL.qll#SQL::SqlSanitizer
- HTTP.qll#ResponseBody
- HTTP.qll#CookieDefinition
- HTTP.qll#ServerDefinition
- HTTP.qll#RouteSetup
- HTTP.qll#HTTP::RedirectInvocation
- HTTP.qll#RedirectInvocation
- Express.qll#Express::RouterDefinition
- AngularJSCore.qll#LinkFunction
- Connect.qll#Connect::StandardRouteHandler
- CryptoLibraries.qll#CryptographicKeyCredentialsExpr
- AWS.qll#AWS::Credentials
- Azure.qll#Azure::Credentials
- Connect.qll#Connect::Credentials
- DigitalOcean.qll#DigitalOcean::Credentials
- Express.qll#Express::Credentials
- NodeJSLib.qll#NodeJSLib::Credentials
- PkgCloud.qll#PkgCloud::Credentials
- Request.qll#Request::Credentials
- ServiceDefinitions.qll#InjectableFunctionServiceRequest
- SensitiveActions.qll#SensitiveVariableAccess
- SensitiveActions.qll#CleartextPasswordExpr
- Connect.qll#Connect::ServerDefinition
- Restify.qll#Restify::ServerDefinition
- Connect.qll#Connect::RouteSetup
- Express.qll#Express::RouteSetup
- Fastify.qll#Fastify::RouteSetup
- Hapi.qll#Hapi::RouteSetup
- Koa.qll#Koa::RouteSetup
- Restify.qll#Restify::RouteSetup
- NodeJSLib.qll#NodeJSLib::RouteSetup
- Express.qll#Express::StandardRouteHandler
- Express.qll#Express::SetCookie
- Hapi.qll#Hapi::RouteHandler
- HTTP.qll#HTTP::Servers::StandardHeaderDefinition
- HTTP.qll#Servers::StandardHeaderDefinition
- Hapi.qll#Hapi::ServerDefinition
- Koa.qll#Koa::AppDefinition
- SensitiveActions.qll#SensitiveCall
### Deprecated APIs
* Some classes/modules with upper-case acronyms in their name have been renamed to follow our style-guide.
The old name still exists as a deprecated alias.
### Major Analysis Improvements
* Added support for TypeScript 4.8.
### Minor Analysis Improvements
* A model for the `mermaid` library has been added. XSS queries can now detect flow through the `render` method of the `mermaid` library.
## 0.2.5
## 0.2.4
### Deprecated APIs
* Many classes/predicates/modules with upper-case acronyms in their name have been renamed to follow our style-guide.
The old name still exists as a deprecated alias.
* The utility files previously in the `semmle.javascript.security.performance` package have been moved to the `semmle.javascript.security.regexp` package.
The previous files still exist as deprecated aliases.
### Minor Analysis Improvements
* Most deprecated predicates/classes/modules that have been deprecated for over a year have been deleted.
### Bug Fixes
* Fixed that top-level `for await` statements would produce a syntax error. These statements are now parsed correctly.
## 0.2.3
## 0.2.2
## 0.2.1
### Minor Analysis Improvements
* The `chownr` library is now modeled as a sink for the `js/path-injection` query.
* Improved modeling of sensitive data sources, so common words like `certain` and `secretary` are no longer considered a certificate and a secret (respectively).
* The `gray-matter` library is now modeled as a sink for the `js/code-injection` query.
## 0.2.0
### Major Analysis Improvements
* Added support for TypeScript 4.7.
### Minor Analysis Improvements
* All new ECMAScript 2022 features are now supported.
## 0.1.4
## 0.1.3
### Minor Analysis Improvements
* The `isLibaryFile` predicate from `ClassifyFiles.qll` has been renamed to `isLibraryFile` to fix a typo.
## 0.1.2
### Deprecated APIs
* The `ReflectedXss`, `StoredXss`, `XssThroughDom`, and `ExceptionXss` modules from `Xss.qll` have been deprecated.
Use the `Customizations.qll` file belonging to the query instead.
### Minor Analysis Improvements
* The [cash](https://github.com/fabiospampinato/cash) library is now modelled as an alias for JQuery.
Sinks and sources from cash should now be handled by all XSS queries.
* Added the `Selection` api as a DOM text source in the `js/xss-through-dom` query.
* The security queries now recognize drag and drop data as a source, enabling the queries to flag additional alerts.
* The security queries now recognize ClipboardEvent function parameters as a source, enabling the queries to flag additional alerts.
## 0.1.1
## 0.1.0
### Bug Fixes
* The following predicates on `API::Node` have been changed so as not to include the receiver. The receiver should now only be accessed via `getReceiver()`.
- `getParameter(int i)` previously included the receiver when `i = -1`
- `getAParameter()` previously included the receiver
- `getLastParameter()` previously included the receiver for calls with no arguments
## 0.0.14
## 0.0.13
### Deprecated APIs
* Some predicates from `DefUse.qll`, `DataFlow.qll`, `TaintTracking.qll`, `DOM.qll`, `Definitions.qll` that weren't used by any query have been deprecated.
The documentation for each predicate points to an alternative.
* Many classes/predicates/modules that had upper-case acronyms have been renamed to follow our style-guide.
The old name still exists as a deprecated alias.
* Some modules that started with a lowercase letter have been renamed to follow our style-guide.
The old name still exists as a deprecated alias.
### Minor Analysis Improvements
* All deprecated predicates/classes/modules that have been deprecated for over a year have been deleted.
## 0.0.12
### Major Analysis Improvements
* Added support for TypeScript 4.6.
### Minor Analysis Improvements
* Added sources from the [`jszip`](https://www.npmjs.com/package/jszip) library to the `js/zipslip` query.
## 0.0.11
## 0.0.10
## 0.0.9
### Deprecated APIs
* The `codeql/javascript-upgrades` CodeQL pack has been removed. All upgrades scripts have been merged into the `codeql/javascript-all` CodeQL pack.
## 0.0.8
## 0.0.7
## 0.0.6
### New Features
* TypeScript 4.5 is now supported.
## 0.0.5
| {
"content_hash": "9447e537565b33791bf38aec6a4eb9d2",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 165,
"avg_line_length": 33.339622641509436,
"alnum_prop": 0.7470288624787776,
"repo_name": "github/codeql",
"id": "7bf9f7f1db04de083a4b7fed42d6368998de230e",
"size": "7111",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "javascript/ql/lib/CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "3739"
},
{
"name": "Batchfile",
"bytes": "3534"
},
{
"name": "C",
"bytes": "410440"
},
{
"name": "C#",
"bytes": "21146000"
},
{
"name": "C++",
"bytes": "1352639"
},
{
"name": "CMake",
"bytes": "1809"
},
{
"name": "CodeQL",
"bytes": "32583145"
},
{
"name": "Dockerfile",
"bytes": "496"
},
{
"name": "EJS",
"bytes": "1478"
},
{
"name": "Emacs Lisp",
"bytes": "3445"
},
{
"name": "Go",
"bytes": "697562"
},
{
"name": "HTML",
"bytes": "58008"
},
{
"name": "Handlebars",
"bytes": "1000"
},
{
"name": "Java",
"bytes": "5417683"
},
{
"name": "JavaScript",
"bytes": "2432320"
},
{
"name": "Kotlin",
"bytes": "12163740"
},
{
"name": "Lua",
"bytes": "13113"
},
{
"name": "Makefile",
"bytes": "8631"
},
{
"name": "Mustache",
"bytes": "17025"
},
{
"name": "Nunjucks",
"bytes": "923"
},
{
"name": "Perl",
"bytes": "1941"
},
{
"name": "PowerShell",
"bytes": "1295"
},
{
"name": "Python",
"bytes": "1649035"
},
{
"name": "RAML",
"bytes": "2825"
},
{
"name": "Ruby",
"bytes": "299268"
},
{
"name": "Rust",
"bytes": "234024"
},
{
"name": "Shell",
"bytes": "23973"
},
{
"name": "Smalltalk",
"bytes": "23"
},
{
"name": "Starlark",
"bytes": "27062"
},
{
"name": "Swift",
"bytes": "204309"
},
{
"name": "Thrift",
"bytes": "3020"
},
{
"name": "TypeScript",
"bytes": "219623"
},
{
"name": "Vim Script",
"bytes": "1949"
},
{
"name": "Vue",
"bytes": "2881"
}
],
"symlink_target": ""
} |
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:tab="urn:import:stroom.widget.tab.client.view">
<g:FlowPanel styleName="max dock-container-vertical">
<g:FlowPanel styleName="dock-min dataRetentionViewImpl-tabBarOuter">
<tab:LinkTabBar ui:field="tabBar" addStyleNames="max dataRetentionViewImpl-tabBarInner"/>
</g:FlowPanel>
<tab:LayerContainerImpl ui:field="layerContainer" styleName="dock-max"/>
</g:FlowPanel>
</ui:UiBinder>
| {
"content_hash": "a321b93dd54518261e1a23826627db0a",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 101,
"avg_line_length": 57.45454545454545,
"alnum_prop": 0.6930379746835443,
"repo_name": "gchq/stroom",
"id": "c55f2f2ff5ee202620590634b1f96c85e3f5b5aa",
"size": "632",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stroom-core-client/src/main/resources/stroom/receive/rules/client/view/DataRetentionViewImpl.ui.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "272243"
},
{
"name": "Dockerfile",
"bytes": "21009"
},
{
"name": "HTML",
"bytes": "14114"
},
{
"name": "Java",
"bytes": "22782925"
},
{
"name": "JavaScript",
"bytes": "14516557"
},
{
"name": "Makefile",
"bytes": "661"
},
{
"name": "Python",
"bytes": "3176"
},
{
"name": "SCSS",
"bytes": "158667"
},
{
"name": "Shell",
"bytes": "166531"
},
{
"name": "TypeScript",
"bytes": "2009517"
},
{
"name": "XSLT",
"bytes": "174226"
}
],
"symlink_target": ""
} |
<TS language="kk_KZ" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Double-click to edit address or label</source>
<translation>Адресті немесе белгіні өзгерту үшін екі рет шертіңіз</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Жаңа адрес енгізу</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Таңдаған адресті тізімнен жою</translation>
</message>
<message>
<source>&Delete</source>
<translation>Жою</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Үтірмен бөлінген текст (*.csv)</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>таңба</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>(no label)</source>
<translation>(таңбасыз)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Құпия сөзді енгізу</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Жаңа құпия сөзі</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Жаңа құпия сөзді қайта енгізу</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Әмиянді шифрлау</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Бұл операциясы бойынша сіздің әмиянізді қоршаудан шығару үшін әмиянның құпия сөзі керек</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Әмиянізді қоршаудан шығару</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Бұл операциясы бойынша сіздің әмиянізді шифрлап тастау үшін әмиянның құпия сөзі керек</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Әмиянізді шифрлап тастау</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Құпия сөзді өзгерту</translation>
</message>
</context>
<context>
<name>DiamondGUI</name>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>(no label)</source>
<translation>(таңбасыз)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
</context>
<context>
<name>OverviewPage</name>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context>
<context>
<name>ReceiveCoinsDialog</name>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>Label</source>
<translation>таңба</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Label</source>
<translation>таңба</translation>
</message>
<message>
<source>(no label)</source>
<translation>(таңбасыз)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>(no label)</source>
<translation>(таңбасыз)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Үтірмен бөлінген файл (*.csv)</translation>
</message>
<message>
<source>Label</source>
<translation>таңба</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>diamond-core</name>
<message>
<source>Transaction amount too small</source>
<translation>Транзакция өте кішкентай</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Транзакция өте үлкен</translation>
</message>
</context>
</TS> | {
"content_hash": "80722ec58b4ee7cb58b2e7cd3dc7443e",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 122,
"avg_line_length": 26.213043478260868,
"alnum_prop": 0.6331066511859347,
"repo_name": "TGDiamond/Diamond",
"id": "f824a2c423787c570f9f57275a62bac186a98b79",
"size": "6555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/diamond_kk_KZ.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "231278"
},
{
"name": "C++",
"bytes": "3245987"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C",
"bytes": "1984"
},
{
"name": "Objective-C++",
"bytes": "6310"
},
{
"name": "Python",
"bytes": "164078"
},
{
"name": "Shell",
"bytes": "46474"
},
{
"name": "TypeScript",
"bytes": "5440561"
}
],
"symlink_target": ""
} |
<?php
namespace Predis\PubSub;
use Predis\ClientException;
use Predis\ClientInterface;
use Predis\Command\Command;
use Predis\Connection\AggregateConnectionInterface;
use Predis\NotSupportedException;
/**
* PUB/SUB consumer abstraction.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class Consumer extends AbstractConsumer
{
private $client;
private $options;
/**
* @param ClientInterface $client Client instance used by the consumer.
* @param array $options Options for the consumer initialization.
*/
public function __construct(ClientInterface $client, array $options = null)
{
$this->checkCapabilities($client);
$this->options = $options ?: array();
$this->client = $client;
$this->genericSubscribeInit('subscribe');
$this->genericSubscribeInit('psubscribe');
}
/**
* Returns the underlying client instance used by the pub/sub iterator.
*
* @return ClientInterface
*/
public function getClient()
{
return $this->client;
}
/**
* Checks if the client instance satisfies the required conditions needed to
* initialize a PUB/SUB consumer.
*
* @param ClientInterface $client Client instance used by the consumer.
*
* @throws NotSupportedException
*/
private function checkCapabilities(ClientInterface $client)
{
if ($client->getConnection() instanceof AggregateConnectionInterface) {
throw new NotSupportedException(
'Cannot initialize a PUB/SUB consumer over aggregate connections.'
);
}
$commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
if ($client->getProfile()->supportsCommands($commands) === false) {
throw new NotSupportedException(
'The current profile does not support PUB/SUB related commands.'
);
}
}
/**
* This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE.
*
* @param string $subscribeAction Type of subscription.
*/
private function genericSubscribeInit($subscribeAction)
{
if (isset($this->options[$subscribeAction])) {
$this->$subscribeAction($this->options[$subscribeAction]);
}
}
/**
* {@inheritdoc}
*/
protected function writeRequest($method, $arguments)
{
$this->client->getConnection()->writeRequest(
$this->client->createCommand($method,
Command::normalizeArguments($arguments)
)
);
}
/**
* {@inheritdoc}
*/
protected function disconnect()
{
$this->client->disconnect();
}
/**
* {@inheritdoc}
*/
protected function getValue()
{
$response = $this->client->getConnection()->read();
switch ($response[0]) {
case self::SUBSCRIBE:
case self::UNSUBSCRIBE:
case self::PSUBSCRIBE:
case self::PUNSUBSCRIBE:
if ($response[2] === 0) {
$this->invalidate();
}
// The missing break here is intentional as we must process
// subscriptions and unsubscriptions as standard messages.
// no break
case self::MESSAGE:
return (object) array(
'kind' => $response[0],
'channel' => $response[1],
'payload' => $response[2],
);
case self::PMESSAGE:
return (object) array(
'kind' => $response[0],
'pattern' => $response[1],
'channel' => $response[2],
'payload' => $response[3],
);
case self::PONG:
return (object) array(
'kind' => $response[0],
'payload' => $response[1],
);
default:
throw new ClientException(
"Unknown message type '{$response[0]}' received in the PUB/SUB context."
);
}
}
}
| {
"content_hash": "aa8a554064ea598bfbfb1ffe2b9eae19",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 95,
"avg_line_length": 29.066225165562916,
"alnum_prop": 0.5279106858054227,
"repo_name": "janritter/KVBApi",
"id": "ecdb4ecebeda88fc6809daf72b6191bf0321b5eb",
"size": "4628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "predis/src/PubSub/Consumer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "297"
},
{
"name": "HTML",
"bytes": "7601"
},
{
"name": "PHP",
"bytes": "2827841"
},
{
"name": "Roff",
"bytes": "376867"
},
{
"name": "Shell",
"bytes": "755"
}
],
"symlink_target": ""
} |
from commands import Command
import re
import utility
class TVCommand(Command):
def extract_channel_info(self, contents, channel_name):
m = re.search('(<div class="kanalRubrik">' + channel_name + '.*?<\/div><\/div>)', contents)
if m:
contents = m.group(1)
m = re.search('<div class="kanalRubrik">' + channel_name + '<\/div>.*?<img src="img\/.*?_orange.gif" alt="" title="(.*?)"\/><\/div> (.*?) <a href="#" class="prgm_orange"', contents)
if m:
show_name = m.group(1)
show_start = m.group(2)
show_end = ''
show_movie = ''
m = re.search('<div class="kanalRubrik">' + channel_name + '<\/div>.*?<img src="img\/(.*?)_orange.gif" alt="" title=".*?"\/>.*?<img src="img\/.*?_yellow.gif" alt="" title=".*?"\/><\/div> (.*?) <a href="#" class="prgm_yellow"', contents)
if m:
#show_movie = ' MOVIE' if m.group(1) == 'mov'
show_end = m.group(2)
show_name = show_name.replace('å', 'å').replace('ä', 'ä').replace('ö', 'ö')
show_name = show_name.replace('Å', 'Å').replace('Ä', 'Ä').replace('Ö', 'Ö')
show_name = show_name.replace('&', '&')
show_start = show_start.replace(':', '')
show_end = show_end.replace(':', '')
s = "%s-%s %s%s" % (show_start, show_end, show_name, show_movie)
return s
return None
def trig_tv(self, bot, source, target, trigger, argument):
response = utility.read_url("http://www.tv.nu/")
data = response["data"]
if len(argument):
channel = argument
s = self.extract_channel_info(data, channel)
if s:
return "Currently on %s: %s." % (channel, s)
else:
return "Could not find that channel. Try http://tvguide.swedb.se/tv?=NU"
else:
channels = ['SVT 1', 'SVT 2', 'TV3', 'TV4', 'TV4+', 'Kanal 5', 'TV6', 'Discovery Mix', 'MTV']
descriptions = []
for channel in channels:
s = self.extract_channel_info(data, channel)
if s:
descriptions.append(channel + ': ' + s)
descriptions.append('http://tvguide.swedb.se/tv?=NU')
return " | ".join(descriptions)
| {
"content_hash": "8408fc7ceb673d98339419f4f8c4d3ec",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 240,
"avg_line_length": 35.224137931034484,
"alnum_prop": 0.5795398923152227,
"repo_name": "serpis/pynik",
"id": "f9cf0044e87cbeb25217535b779671d052bee52a",
"size": "2060",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/tv.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "195137"
}
],
"symlink_target": ""
} |
unless ENV['CI']
require 'simplecov'
SimpleCov.start
end
require 'nhk_program'
require 'rspec'
require 'webmock/rspec'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
end
def stub_get(path, endpoint = NHKProgram.endpoint)
stub_request(:get, endpoint + '/' + path)
end
| {
"content_hash": "ab8943904acfde1eedeca88266154873",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 77,
"avg_line_length": 26.875,
"alnum_prop": 0.7271317829457364,
"repo_name": "mitukiii/nhk_program-for-ruby",
"id": "945dc919be0d82e862d118bc1ae6b58223dcad17",
"size": "976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "26835"
}
],
"symlink_target": ""
} |
require 'ndr_support/safe_file'
module NdrImport
module File
# This mixin adds table enumeration functionality to importers.
module Registry
class <<self
attr_accessor :handlers
def register(klass, *formats)
@handlers ||= {}
formats.each do |format|
@handlers[format] = klass
end
end
def unregister(*formats)
formats.each do |format|
@handlers.delete(format)
end
end
def files(filename, options = {}, &block)
return enum_for(:files, filename, options) unless block
klass_factory(filename, nil, options).files(&block)
end
def tables(filename, format = nil, options = {}, &block)
return enum_for(:tables, filename, format, options) unless block
klass_factory(filename, format, options).tables(&block)
end
private
def klass_factory(filename, format, options)
format ||= SafeFile.extname(filename).delete('.').downcase
klass = Registry.handlers[format]
if klass
klass.new(filename, format, options)
else
UnregisteredFiletype.new(filename, format, options)
end
end
end
end
end
end
require_relative 'all'
| {
"content_hash": "64f7e162170d95da6504136e50075033",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 74,
"avg_line_length": 25.423076923076923,
"alnum_prop": 0.5824508320726173,
"repo_name": "PublicHealthEngland/ndr_import",
"id": "479a9323e0c71972d4b1b753db5277d72320b03f",
"size": "1322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ndr_import/file/registry.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "250605"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
<!--
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
-->
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Fab Academy 2017;</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Fab Academy Page by Inês" />
<meta name="keywords" content="fab lab, fab academy, assignments" />
<meta name="author" content="Inês Carmo" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<!-- Place favicon2.ico and apple-touch-icon.jpg in the root directory -->
<link rel="shortcut icon" href="favicon2.ico">
<!-- Google Webfont -->
<link href='https://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>
<!-- Themify Icons -->
<link rel="stylesheet" href="css/themify-icons.css">
<!-- Icomoon Icons -->
<link rel="stylesheet" href="css/icomoon-icons.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Easy Responsive Tabs -->
<link rel="stylesheet" href="css/easy-responsive-tabs.css">
<!-- Theme Style -->
<link rel="stylesheet" href="css/style.css">
<!-- FOR IE9 below -->
<!--[if lte IE 9]>
<script src="js/modernizr-2.6.2.min.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body onLoad="Load()">
<!-- Header -->
<header id="fh5co-header" role="banner">
<div class="container">
<!-- Logo -->
<div id="fh5co-logo">
<a href="index.html">
<img src="images/logo2.png" alt="" width="150" height="151"> </a> </div>
<!-- Logo -->
<!-- Mobile Toggle Menu Button -->
<a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle"><i></i></a>
<!-- Main Nav -->
<div id="fh5co-main-nav">
<nav id="fh5co-nav" role="navigation">
<ul>
<li class="fh5co-active">
<a href="index.html">Assignments</a><a href="index.html"></a> </li>
<li>
<a href="finalproject.html">Final Project </a> </li>
<li>
<a href="aboutme.html">About me </a> </li>
</ul>
</nav>
</div>
<!-- Main Nav -->
</div>
</header>
<!-- Header -->
<main role="main">
<!-- Start Intro -->
<div id="fh5co-intro">
<div class="container">
<h1>Week no. 16 </h1>
<div class="row">
<div class="col-md-6 col-md-push-6 fh5co-intro-sub">
<p>Interface and Application Programing : </p>
<ul>
<li>write an application that interfaces with an input &/or output device that you made,<br>
comparing as many tool options as possible</li>
</ul>
</div>
</div>
</div>
</div>
<!-- End Intro -->
<div id="fh5co-tab-feature-center" class="fh5co-tab text-center">
<div>
<div class="row">
<div class="col-md-12">
<h2 class="h3">Interface</h2>
</div>
<div class="col-md-12">
<p>For this assignment, I thought about using a board that I had already made and that is working well, <br>
so I chose the hello button of week 4. For the interface part I thought about <br>
using processing, because I had already used it a few years ago and so I can remember it. </p>
</div>
<p align="center" class="style38">Before start doing anything I need to:<br>
1. Install <a href="https://processing.org/download/">processing</a>:<br>
2. Read some examples and tutorials.
<p align="center" class="style38">After doing this i choose one tutorial to follow: <a href="http://jeknowledge.github.io/academy-articles/interface-led-com-arduino-e-processing">http://jeknowledge.github.io/academy-articles/interface-led-com-arduino-e-processing
</a>
<p align="center" class="style38">And after doing this example i tryed to adapt it an make it my own. So i started designing my interface.
<p align="center" class="style38"><img src="images/week16/1.PNG" width="700" height="557">
<img src="images/week16/2.PNG" width="700" height="550">
<p align="center" class="style38">So, the goal is when you push on the red button on the screen, the LED on the board ligths up.
<p align="center" class="style38">
<p align="center" class="style38"><div align="center">
<video width="719" controls="controls">
<source src="images/week16/interface.mp4" type="video/mp4" />
Your browser does not support the video tag. </div>
</video>
</div>
<p align="center" class="style38">
<p align="center" class="style38">
<p><br>
</p>
</div>
</div>
<div class="col-md-6"></div>
</div>
</div>
<div>
<div class="row">
<div class="col-md-12">
<h2 align="center" class="h3">Programing </h2>
</div>
<div class="col-md-12">
<p align="center">For the programing part I'll try to do my code in arduino following the same tutorial example.</p>
<p align="center"><img src="images/week16/arduino1.PNG" width="582" height="660"> </p>
<p align="center"> </p>
<p align="center"> </p>
<p align="center"><br>
</div>
<div>
<div class="row">
<div class="col-md-12">
<h2 align="center" class="h3"> ... </h2>
</div>
<div class="col-md-12">
<p align="center">......</p>
</div>
<div align="left">
<p align="center"><FONT SIZE=1><BR>
</FONT>...</p>
<p align="center"> </p>
</div>
</BODY>
| {
"content_hash": "0edf3ef26c9f9c607047ed6fba77e8f6",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 292,
"avg_line_length": 40.32786885245902,
"alnum_prop": 0.503929539295393,
"repo_name": "FabAcademyPortugal2017/FabAcademyPortugal2017.github.io",
"id": "e5834fd18d65b93adf508675e5684565c4d7dfb7",
"size": "7382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ines/week16.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1084366"
},
{
"name": "Eagle",
"bytes": "1542237"
},
{
"name": "HTML",
"bytes": "1500154"
},
{
"name": "JavaScript",
"bytes": "1067852"
},
{
"name": "PHP",
"bytes": "479685"
},
{
"name": "Shell",
"bytes": "4440"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<title>iPad Popover: Top/Bottom</title>
<link rel="stylesheet" href="../chui/chui.ios.css">
<style type="text/css">
toolbar {
background-color: rgba(125,130,140,.85);
}
uibutton > label {
-webkit-font-smoothing: subpixel-antialiased;
}
/* popover background */
popover#popover2 {
background-color: red;
}
popover#popover2 > header {
background-image:
-webkit-linear-gradient(top, yellow, orange 50%, red 50%);
}
popover#popover2:after {
/* Matches the first color of the header above. */
background-color: yellow !important;
}
#popover2[ui-pointer-position*=bottom]:after {
/* For a popover attached to the bottom. This color needs to match the background color of the popover */
background-color: red;
}
</style>
<script src="../libs/zepto.js"></script>
<script src="../chui/iscroll.js"></script>
<script src="../chui/chui.ios.js"></script>
<script type="text/javascript">
$(function(){
var popover1 = {
triggerElement : "#showPopover1",
popoverOrientation: "top",
pointerOrientation: "left",
id: "popover1",
title: "Popover One"
};
$.UIPopover(popover1);
$("#popover1 scrollpanel").append('<tableview ui-kind="grouped">\
<tablecell><celltitle>item one</celltitle></tablecell>\
<tablecell><celltitle>item two</celltitle></tablecell>\
<tablecell><celltitle>item three</celltitle></tablecell>\
<tablecell><celltitle>item four</celltitle></tablecell>\
</ul>');
$("#showPopover1").on("click", function() {
$.UIPopover.show($("#popover1"));
});
var popover2 = {
triggerElement: "#showPopover2",
popoverOrientation: "top",
pointerOrientation: "center",
id: "popover2",
title: "Popover Two"
};
$.UIPopover(popover2);
$("#popover2 scrollpanel").append('<tableview><tablecell><celltitle>item one</celltitle></tablecell><tablecell><celltitle>item two</celltitle></tablecell><tablecell><celltitle>item three</celltitle></tablecell></tableview>');
$("#showPopover2").on("click", function() {
$.UIPopover.show($("#popover2"));
});
var popover3 = {
triggerElement: "#showPopover3",
popoverOrientation: "top",
pointerOrientation: "right",
id: "popover3",
title: "Popover Three"
};
$.UIPopover(popover3);
$("#popover3 scrollpanel").append('<actionsheet>\
<uibutton ui-kind="action">\
<label>Set Value</label>\
</uibutton>\
<uibutton ui-kind="action" ui-implements="cancel">\
<label>Cancel</label>\
</uibutton>\
</actionsheet>');
$("#showPopover3").on("click", function() {
$.UIPopover.show($("#popover3"));
});
var popover4 = {
triggerElement: "#showPopover4",
popoverOrientation: "bottom",
pointerOrientation: "left",
id: "popover4",
title: "Popover Four"
};
$.UIPopover(popover4);
$("#popover4 scrollpanel").append('<tableheader>Nothing here yet</tableheader>');
$("#showPopover4").on("click", function() {
$.UIPopover.show($("#popover4"));
});
var popover5 = {
triggerElement: "#showPopover5",
popoverOrientation: "bottom",
pointerOrientation: "center",
id: "popover5",
title: "Popover Five"
};
$.UIPopover(popover5);
$("#popover5 scrollpanel").append('<actionsheet>\
<uibutton ui-kind="action">\
<label>Set Value</label>\
</uibutton>\
<uibutton ui-kind="action" ui-implements="cancel">\
<label>Cancel</label>\
</uibutton>\
<uibutton ui-kind="action" ui-implements="delete">\
<label>Delete</label>\
</uibutton>\
</actionsheet>');
$("#showPopover5").on("click", function() {
$.UIPopover.show($("#popover5"));
});
var popover6 = {
triggerElement: "#showPopover6",
popoverOrientation: "bottom",
pointerOrientation: "right",
id: "popover6",
title: "Popover Six"
};
$.UIPopover(popover6);
$("#popover6 scrollpanel").append('<tableview><tablecell><celltitle>item one</celltitle></tablecell><tablecell><celltitle>item two</celltitle></tablecell><tablecell><celltitle>item three</celltitle></tablecell><tableview>');
$("#showPopover6").on("click", function() {
$.UIPopover.show($("#popover6"));
});
});
</script>
</head>
<body>
<app>
<view id="main" ui-background-style="slanted-left-equal" style="background-color: #bbbac4" ui-navigation-status="current">
<toolbar class="ui-custom-tint">
<uibutton id="showPopover1" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover 1</label>
</uibutton>
<uibutton id="showPopover2" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover is a long button 2</label>
</uibutton>
<uibutton id="showPopover3" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover 3</label>
</uibutton>
</toolbar>
<subview ui-associations="withNavBar withBottomToolBar">
<scrollpanel>
</scrollpanel>
</subview>
<toolbar ui-placement="bottom" class="ui-custom-tint">
<uibutton id="showPopover4" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover 4</label>
</uibutton>
<uibutton id="showPopover5" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover is a very long button you know 5</label>
</uibutton>
<uibutton id="showPopover6" class="ui-custom-tint" style="background-color: #000">
<label>Show Popover 6</label>
</uibutton>
</toolbar>
</view>
</app>
</body>
</html>
| {
"content_hash": "03c4ce44efabcee6b6b06e47ce0e7a6e",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 229,
"avg_line_length": 37.54545454545455,
"alnum_prop": 0.5597760290556901,
"repo_name": "SoumitraAgarwal/chocolatechip-ui",
"id": "5496dbdab323c0208571d85fd26394b71f6d1187",
"size": "6608",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples-ios-zepto/popovers.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1110733"
},
{
"name": "HTML",
"bytes": "2266569"
},
{
"name": "JavaScript",
"bytes": "1707298"
},
{
"name": "Python",
"bytes": "8714"
}
],
"symlink_target": ""
} |
package list
import (
"testing"
adapter_integration "istio.io/istio/mixer/pkg/adapter/test"
)
const (
h1OverrideSrc1Src2 = `
apiVersion: "config.istio.io/v1alpha2"
kind: listchecker
metadata:
name: staticversion
namespace: istio-system
spec:
overrides: ["src1", "src2"]
blacklist: false
`
i1ValSrcNameAttr = `
apiVersion: "config.istio.io/v1alpha2"
kind: listentry
metadata:
name: appversion
namespace: istio-system
spec:
value: source.name | ""
`
r1H1I1 = `
apiVersion: "config.istio.io/v1alpha2"
kind: rule
metadata:
name: checkwl
namespace: istio-system
spec:
actions:
- handler: staticversion.listchecker
instances:
- appversion.listentry
`
)
func TestReport(t *testing.T) {
adapter_integration.RunTest(
t,
GetInfo,
adapter_integration.Scenario{
ParallelCalls: []adapter_integration.Call{
{
CallKind: adapter_integration.CHECK,
Attrs: map[string]interface{}{"source.name": "src1"},
},
{
CallKind: adapter_integration.CHECK,
},
},
Configs: []string{
h1OverrideSrc1Src2,
r1H1I1,
i1ValSrcNameAttr,
},
Want: `{
"AdapterState": null,
"Returns": [
{
"Check": {
"Status": {},
"ValidDuration": 300000000000,
"ValidUseCount": 10000
}
},
{
"Check": {
"Status": {
"code": 5,
"message": "staticversion.listchecker.istio-system: is not whitelisted"
},
"ValidDuration": 300000000000,
"ValidUseCount": 10000
}
}
]
}`,
},
)
}
| {
"content_hash": "50da2a75947a37b237e3a45a918794ff",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 87,
"avg_line_length": 20,
"alnum_prop": 0.5604651162790698,
"repo_name": "frankbu/istio",
"id": "a8a73e75d7568a78db753a376b9b0fa636b93aa0",
"size": "2311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mixer/adapter/list/list_integration_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20388"
},
{
"name": "Go",
"bytes": "6385883"
},
{
"name": "HTML",
"bytes": "228865"
},
{
"name": "JavaScript",
"bytes": "35715"
},
{
"name": "Makefile",
"bytes": "52245"
},
{
"name": "Python",
"bytes": "60086"
},
{
"name": "Ruby",
"bytes": "4820"
},
{
"name": "Shell",
"bytes": "266236"
},
{
"name": "Smarty",
"bytes": "10973"
}
],
"symlink_target": ""
} |
package org.apache.shardingsphere.elasticjob.error.handler;
import org.apache.shardingsphere.elasticjob.infra.spi.SPIPostProcessor;
import org.apache.shardingsphere.elasticjob.infra.spi.TypedSPI;
/**
* Job error handler.
*/
public interface JobErrorHandler extends TypedSPI, SPIPostProcessor {
/**
* Handle exception.
*
* @param jobName job name
* @param cause failure cause
*/
void handleException(String jobName, Throwable cause);
}
| {
"content_hash": "d572c778d6c43dc94a72ad2ac2624d3b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 71,
"avg_line_length": 24,
"alnum_prop": 0.725,
"repo_name": "dangdangdotcom/elastic-job",
"id": "fe87a196d9cd4b7dfa83f64ef5cf051071540715",
"size": "1283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "elasticjob-ecosystem/elasticjob-error-handler/elasticjob-error-handler-spi/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/JobErrorHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace metaforce {
CFrontEndUITouchBar::~CFrontEndUITouchBar() = default;
void CFrontEndUITouchBar::SetPhase(EPhase ph) { m_phase = ph; }
CFrontEndUITouchBar::EPhase CFrontEndUITouchBar::GetPhase() { return m_phase; }
void CFrontEndUITouchBar::SetFileSelectPhase(const SFileSelectDetail details[3], bool eraseGame, bool galleryActive) {
m_phase = EPhase::FileSelect;
}
void CFrontEndUITouchBar::SetNoCardSelectPhase(bool galleryActive) { m_phase = EPhase::NoCardSelect; }
void CFrontEndUITouchBar::SetFusionBonusPhase(bool fusionSuitActive) { m_phase = EPhase::FusionBonus; }
void CFrontEndUITouchBar::SetStartOptionsPhase(bool normalBeat) { m_phase = EPhase::StartOptions; }
CFrontEndUITouchBar::EAction CFrontEndUITouchBar::PopAction() { return EAction::None; }
#ifndef __APPLE__
std::unique_ptr<CFrontEndUITouchBar> NewFrontEndUITouchBar() { return std::make_unique<CFrontEndUITouchBar>(); }
#endif
} // namespace metaforce
| {
"content_hash": "989caf4cb556f7980932fd4d39724594",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 118,
"avg_line_length": 51.94444444444444,
"alnum_prop": 0.7935828877005348,
"repo_name": "AxioDL/PathShagged",
"id": "b37d5f96d9dbf3bfbe9f143f3cb5eedf6eb58f9a",
"size": "983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Runtime/MP1/CFrontEndUITouchBar.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "30964"
},
{
"name": "C++",
"bytes": "1853098"
},
{
"name": "CMake",
"bytes": "25640"
},
{
"name": "Python",
"bytes": "29052"
}
],
"symlink_target": ""
} |
#pragma once
#include <string>
#include <vector>
#include <osquery/status.h>
// clang-format off
#ifndef STR
#define STR_OF(x) #x
#define STR(x) STR_OF(x)
#endif
#define STR_EX(x) x
#define CONCAT(x, y) STR(STR_EX(x)STR_EX(y))
#ifndef FRIEND_TEST
#define FRIEND_TEST(test_case_name, test_name) \
friend class test_case_name##_##test_name##_Test
#endif
// clang-format on
#ifndef __constructor__
#define __registry_constructor__ __attribute__((constructor(101)))
#define __plugin_constructor__ __attribute__((constructor(102)))
#else
#define __registry_constructor__ __attribute__((__constructor__(101)))
#define __plugin_constructor__ __attribute__((__constructor__(102)))
#endif
/// A configuration error is catastrophic and should exit the watcher.
#define EXIT_CATASTROPHIC 78
namespace osquery {
/**
* @brief The version of osquery
*/
extern const std::string kVersion;
extern const std::string kSDKVersion;
extern const std::string kSDKPlatform;
/// Use a macro for the sdk/platform literal, symbols available in lib.cpp.
#define OSQUERY_SDK_VERSION STR(OSQUERY_BUILD_SDK_VERSION)
#define OSQUERY_PLATFORM STR(OSQUERY_BUILD_PLATFORM)
/**
* @brief A helpful tool type to report when logging, print help, or debugging.
*/
enum ToolType {
OSQUERY_TOOL_UNKNOWN = 0,
OSQUERY_TOOL_SHELL,
OSQUERY_TOOL_DAEMON,
OSQUERY_TOOL_TEST,
OSQUERY_EXTENSION,
};
/// The osquery tool type for runtime decisions.
extern ToolType kToolType;
class Initializer {
public:
/**
* @brief Sets up various aspects of osquery execution state.
*
* osquery needs a few things to happen as soon as the process begins
* executing. Initializer takes care of setting up the relevant parameters.
* Initializer should be called in an executable's `main()` function.
*
* @param argc the number of elements in argv
* @param argv the command-line arguments passed to `main()`
* @param tool the type of osquery main (daemon, shell, test, extension).
*/
Initializer(int& argc, char**& argv, ToolType tool = OSQUERY_TOOL_TEST);
/**
* @brief Sets up the process as an osquery daemon.
*
* A daemon has additional constraints, it can use a process mutex, check
* for sane/non-default configurations, etc.
*/
void initDaemon();
/**
* @brief Daemon tools may want to continually spawn worker processes
* and monitor their utilization.
*
* A daemon may call initWorkerWatcher to begin watching child daemon
* processes until it-itself is unscheduled. The basic guarantee is that only
* workers will return from the function.
*
* The worker-watcher will implement performance bounds on CPU utilization
* and memory, as well as check for zombie/defunct workers and respawn them
* if appropriate. The appropriateness is determined from heuristics around
* how the worker exited. Various exit states and velocities may cause the
* watcher to resign.
*
* @param name The name of the worker process.
*/
void initWorkerWatcher(const std::string& name);
/// Assume initialization finished, start work.
void start();
/// Turns off various aspects of osquery such as event loops.
void shutdown();
/**
* @brief Check if a process is an osquery worker.
*
* By default an osqueryd process will fork/exec then set an environment
* variable: `OSQUERY_WORKER` while continually monitoring child I/O.
* The environment variable causes subsequent child processes to skip several
* initialization steps and jump into extension handling, registry setup,
* config/logger discovery and then the event publisher and scheduler.
*/
static bool isWorker();
private:
/// Initialize this process as an osquery daemon worker.
void initWorker(const std::string& name);
/// Initialize the osquery watcher, optionally spawn a worker.
void initWatcher();
/// Set and wait for an active plugin optionally broadcasted.
void initActivePlugin(const std::string& type, const std::string& name);
private:
int* argc_;
char*** argv_;
int tool_;
std::string binary_;
};
/**
* @brief Split a given string based on an optional delimiter.
*
* If no delimiter is supplied, the string will be split based on whitespace.
*
* @param s the string that you'd like to split
* @param delim the delimiter which you'd like to split the string by
*
* @return a vector of strings split by delim.
*/
std::vector<std::string> split(const std::string& s,
const std::string& delim = "\t ");
/**
* @brief Split a given string based on an delimiter.
*
* @param s the string that you'd like to split.
* @param delim the delimiter which you'd like to split the string by.
* @param occurrences the number of times to split by delim.
*
* @return a vector of strings split by delim for occurrences.
*/
std::vector<std::string> split(const std::string& s,
const std::string& delim,
size_t occurences);
/**
* @brief In-line replace all instances of from with to.
*
* @param str The input/output mutable string.
* @param from Search string
* @param to Replace string
*/
inline void replaceAll(std::string& str,
const std::string& from,
const std::string& to) {
if (from.empty()) {
return;
}
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
/**
* @brief Join a vector of strings using a tokenizer.
*
* @param s the string that you'd like to split.
* @param tok a token glue.
*
* @return a joined string.
*/
std::string join(const std::vector<std::string>& s, const std::string& tok);
/**
* @brief Getter for a host's current hostname
*
* @return a string representing the host's current hostname
*/
std::string getHostname();
/**
* @brief generate a uuid to uniquely identify this machine
*
* @return uuid string to identify this machine
*/
std::string generateHostUuid();
/**
* @brief Get a configured UUID/name that uniquely identify this machine
*
* @return string to identify this machine
*/
std::string getHostIdentifier();
/**
* @brief Getter for the current time, in a human-readable format.
*
* @return the current date/time in the format: "Wed Sep 21 10:27:52 2011"
*/
std::string getAsciiTime();
/**
* @brief Getter for the current UNIX time.
*
* @return an int representing the amount of seconds since the UNIX epoch
*/
int getUnixTime();
/**
* @brief In-line helper function for use with utf8StringSize
*/
template <typename _Iterator1, typename _Iterator2>
inline size_t incUtf8StringIterator(_Iterator1& it, const _Iterator2& last) {
if (it == last) {
return 0;
}
size_t res = 1;
for (++it; last != it; ++it, ++res) {
unsigned char c = *it;
if (!(c & 0x80) || ((c & 0xC0) == 0xC0)) {
break;
}
}
return res;
}
/**
* @brief Get the length of a UTF-8 string
*
* @param str The UTF-8 string
*
* @return the length of the string
*/
inline size_t utf8StringSize(const std::string& str) {
size_t res = 0;
std::string::const_iterator it = str.begin();
for (; it != str.end(); incUtf8StringIterator(it, str.end())) {
res++;
}
return res;
}
/**
* @brief Create a pid file
*
* @return A status object indicating the success or failure of the operation
*/
Status createPidFile();
}
| {
"content_hash": "31ff0a3b5250c793a628362c24604bc4",
"timestamp": "",
"source": "github",
"line_count": 269,
"max_line_length": 79,
"avg_line_length": 27.762081784386616,
"alnum_prop": 0.6807712908409213,
"repo_name": "alonashu/osquery",
"id": "40f8abb4e8ff76e6e67ebb5a2372a9a842e51a18",
"size": "7775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/osquery/core.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "38331"
},
{
"name": "C++",
"bytes": "1258142"
},
{
"name": "CMake",
"bytes": "69725"
},
{
"name": "Makefile",
"bytes": "3400"
},
{
"name": "Objective-C++",
"bytes": "32703"
},
{
"name": "Shell",
"bytes": "2030"
},
{
"name": "Thrift",
"bytes": "2879"
}
],
"symlink_target": ""
} |
package ch.ethz.scu.obit.microscopy.readers;
import java.io.File;
import java.io.IOException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.ChannelSeparator;
import loci.formats.FormatException;
import loci.formats.ImageReader;
import loci.formats.meta.IMetadata;
import loci.formats.services.OMEXMLService;
import loci.plugins.util.ImageProcessorReader;
import loci.plugins.util.LociPrefs;
import ome.units.quantity.Length;
import ome.xml.model.primitives.Color;
import ome.xml.model.primitives.Timestamp;
public class BioFormatsWrapper {
/* Private instance variables */
private File filename;
private ImageProcessorReader reader = null;
private ServiceFactory factory;
private OMEXMLService service;
private IMetadata omexmlMeta;
private String errorMessage = "";
private List<String> referencedFiles;
private int numberOfSeries = 0;
private final static double[][] defaultChannelColors = {
{ 255.0, 0.0, 0.0, 255.0 }, { 0.0, 255.0, 0.0, 255.0 },
{ 0.0, 0.0, 255.0, 255.0 }, { 255.0, 255.0, 0.0, 255.0 },
{ 255.0, 0.0, 255.0, 255.0 }, { 0.0, 255.0, 255.0, 255.0 },
{ 255.0, 255.0, 255.0, 255.0 }, };
private boolean isFileScanned = false;
/**
* Metadata attributes
*/
private final Map<String, HashMap<String, String>> attr = new HashMap<String, HashMap<String, String>>();
/**
* Constructor
*
* @param filename Full path to the file to process.
*/
public BioFormatsWrapper(File filename) {
// Store the filename
this.filename = filename;
// Initialize the list of referenced files
this.referencedFiles = new ArrayList<String>();
// Initialize
init(false);
}
/**
* Alternate constructor
*
* @param filename Full path to the file to process.
* @param groupFiles Toggles the file grouping behavior of the reader.
*/
public BioFormatsWrapper(File filename, Boolean groupFiles) {
// Store the filename
this.filename = filename;
// Initialize the list of referenced files
this.referencedFiles = new ArrayList<String>();
// Initialize
if (!init(groupFiles)) {
throw new RuntimeException(
"Could not initialize the BioFormats Library for file "
+ filename);
}
}
/**
* Initialize the reader and sets up the OMEXML metadata store
*
* @param groupFiles Toggles the file grouping behavior of the reader.
* @return bool True if the initialization was successful, false otherwise.
*/
private boolean init(Boolean groupFiles) {
// Create the reader
ImageReader imageReader = LociPrefs.makeImageReader();
imageReader.setGroupFiles(groupFiles);
reader = new ImageProcessorReader(new ChannelSeparator(imageReader));
// Set OME-XML metadata
factory = null;
service = null;
omexmlMeta = null;
try {
factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
} catch (DependencyException e) {
this.errorMessage = "Could not initialize bio-formats library. "
+ "Error was: " + e.getMessage();
return false;
}
try {
omexmlMeta = service.createOMEXMLMetadata();
} catch (ServiceException e) {
this.errorMessage = "Could not initialize bio-formats library. "
+ "Error was: " + e.getMessage();
return false;
}
reader.setMetadataStore(omexmlMeta);
// Try to open the image file
try {
reader.setId(filename.getCanonicalPath());
} catch (FormatException e) {
this.errorMessage = "Could not open file. Error was: "
+ e.getMessage();
return false;
} catch (IOException e) {
this.errorMessage = "Could not open file. Error was: "
+ e.getMessage();
return false;
}
this.errorMessage = "";
return true;
}
/**
* Close file. The client is responsible to call close to release the file
* handle!
*
* @return true if the file could be closed, false otherwise.
*/
public boolean close() {
// If the file is closed already, we return true
if (reader == null) {
return true;
}
// Try closing it
try {
reader.close();
} catch (IOException e) {
// Return failure
return false;
}
// Set the reader to null
reader = null;
// Return success
return true;
}
/**
* Implement finalize() to make sure that all file handles are released.
*/
@Override
public void finalize() throws Throwable {
// Call close
close();
// Call the parent finalize()
super.finalize();
}
/**
* Return the version of the bio-formats library used.
*
* @return String with the bio-formats library version.
*/
public String bioformatsVersion() {
return loci.formats.FormatTools.VERSION;
}
/**
* Return the error message
*
* @return The error message.
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* Return true if the file was scanned already, false otherwise.
*
* @return true if the file was scanned already, false otherwise.
*/
public boolean isScanned() {
return isFileScanned;
}
/**
* Scan the file for metadata information and stores it as a String-String
* map of key-value attributes.
*
* @return true if parsing was successful, false otherwise.
*/
public boolean parse() {
return parse(0);
}
/**
* Scan the file for metadata information and stores it as a String-String
* map of key-value attributes.
*
* @param firstSeriesIndex Index of the first series in the keys of the
* attributes property. Useful if one needs to
* concatenate the attributes over consecutive calls
* of parse on different files.
* @return true if parsing was successful, false otherwise.
*/
public boolean parse(int firstSeriesIndex) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// If we have already scanned the file we just return true
if (attr.size() > 0) {
return true;
}
// Initialize file scanned to false
isFileScanned = false;
// Now process the file
try {
// We cache the number of series
numberOfSeries = reader.getSeriesCount();
// Get and store all series
for (int i = 0; i < numberOfSeries; i++) {
// Set the series
reader.setSeries(i);
// Create a hashmap for the attributes of current series
HashMap<String, String> seriesAttr = new HashMap<String, String>();
// Series number
seriesAttr.put("numSeries",
Integer.toString(i + firstSeriesIndex));
// Image name
seriesAttr.put("name", omexmlMeta.getImageName(i));
if (seriesAttr.get("name").equals("")) {
// If the name is empty, fall back to series_{numSeries}
seriesAttr.put("name",
"series_" + seriesAttr.get("numSeries"));
}
// Image size X
seriesAttr.put("sizeX", Integer.toString(reader.getSizeX()));
// Image size Y
seriesAttr.put("sizeY", Integer.toString(reader.getSizeY()));
// Image size Z
seriesAttr.put("sizeZ", Integer.toString(reader.getSizeZ()));
// Image size C
seriesAttr.put("sizeC", Integer.toString(reader.getSizeC()));
// Image size T
seriesAttr.put("sizeT", Integer.toString(reader.getSizeT()));
// Data type
seriesAttr.put("datatype", getDataType());
// Is Signed
seriesAttr.put("isSigned",
Boolean.toString(loci.formats.FormatTools
.isSigned(reader.getPixelType())));
// Is Little Endian
seriesAttr.put("isLittleEndian",
Boolean.toString(reader.isLittleEndian()));
// Acquisition date
seriesAttr.put("acquisitionDate", getAcquisitionDate(i));
// Voxel sizes
double[] voxels = getVoxelSizes(i);
seriesAttr.put("voxelX", Double.toString(voxels[0]));
seriesAttr.put("voxelY", Double.toString(voxels[1]));
seriesAttr.put("voxelZ", Double.toString(voxels[2]));
// Channel names
String[] channelNames = getChannelNames(i);
for (int c = 0; c < reader.getSizeC(); c++) {
seriesAttr.put("channelName" + c, Normalizer
.normalize(channelNames[c], Normalizer.Form.NFD));
}
// Emission wavelengths
double[] emWavelengths = getEmissionWavelengths(i);
for (int c = 0; c < reader.getSizeC(); c++) {
seriesAttr.put("emWavelength" + c,
Double.toString(emWavelengths[c]));
}
// Excitation wavelengths
double[] exWavelengths = getExcitationWavelengths(i);
for (int c = 0; c < reader.getSizeC(); c++) {
seriesAttr.put("exWavelength" + c,
Double.toString(exWavelengths[c]));
}
// Stage position
double[] stagePosition = getStagePosition();
seriesAttr.put("positionX", Double.toString(stagePosition[0]));
seriesAttr.put("positionY", Double.toString(stagePosition[1]));
// Channel colors
double[][] colors = getChannelColors(i);
for (int c = 0; c < reader.getSizeC(); c++) {
seriesAttr.put("channelColor" + c,
"" + colors[c][0] + ", " + colors[c][1] + ", "
+ colors[c][2] + ", " + colors[c][3]);
}
// NAs
double[] NAs = getNAs();
if (NAs.length == 0) {
seriesAttr.put("NA", Double.toString(Double.NaN));
} else if (NAs.length == 1) {
seriesAttr.put("NA", Double.toString(NAs[0]));
} else {
// In some cases, the bioformats library returns an NA per
// series
// in others just one for all.
String strNAs = "";
try {
strNAs = Double.toString(NAs[i]);
} catch (Exception e) {
for (int c = 0; c < NAs.length - 1; c++) {
strNAs += Double.toString(NAs[c]) + ", ";
}
strNAs += Double.toString(NAs[NAs.length - 1]);
}
seriesAttr.put("NA", strNAs);
}
// Is the series a thumbnail?
seriesAttr.put("isThumbnail",
String.valueOf(reader.isThumbnailSeries()));
// Key prefix
String seriesKey = "series_" + (firstSeriesIndex + i);
// Now add the metadata for current series
attr.put(seriesKey, seriesAttr);
}
} catch (Exception e) {
// Reset the attribute map
attr.clear();
// Make sure the isFileScanned flag is set to false
isFileScanned = false;
// Return failure
return false;
}
// Now we can set the isFileScanned flag to true
isFileScanned = true;
// And return success
return true;
}
/**
* Return the parsed metadata attributes.
*
* @return map of series attributes.
*/
public Map<String, HashMap<String, String>> getAttributes() {
return attr;
}
/**
* Return the number of series in the file/dataset.
*
* @return the number of series.
*/
public int getNumberOfSeries() {
// This value is cached after parsing.
return numberOfSeries;
}
/**
* Return all referenced files for all series in the dataset as a list of
* Strings
*
* @return List of file names as Strings
*/
public List<String> getReferencedFiles() {
return referencedFiles;
}
/**
* Return the data type
*
* @return string datatype, one of "uint8", "uint16", "float",
* "unsupported".
*/
public String getDataType() {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Get and store the dataset type
String datatype;
switch (loci.formats.FormatTools
.getBytesPerPixel(reader.getPixelType())) {
case 1:
datatype = "uint8";
break;
case 2:
datatype = "uint16";
break;
case 4:
datatype = "float";
break;
default:
datatype = "unsupported";
break;
}
return datatype;
}
/**
* Return the channel excitation wavelengths
*
* @param seriesNum index of the series to query
* @return array of excitation wavelengths. Values that could not be
* retrieved will be replaced by Double.NaN.
*/
private double[] getExcitationWavelengths(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Allocate space to store the channel names
int nChannels = reader.getSizeC();
double[] exWavelengths = new double[nChannels];
for (int i = 0; i < nChannels; i++) {
Length pEx;
try {
pEx = omexmlMeta.getChannelExcitationWavelength(seriesNum, i);
} catch (IndexOutOfBoundsException e) {
pEx = null;
}
double ex;
if (pEx != null) {
ex = (double) pEx.value();
} else {
ex = Double.NaN;
}
exWavelengths[i] = ex;
}
return exWavelengths;
}
/**
* Return the channel emission wavelengths
*
* @param seriesNum index of the series to query
* @return array of emission wavelengths. Values that could not be retrieved
* will be replaced by Double.NaN.
*/
private double[] getEmissionWavelengths(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Allocate space to store the channel names
int nChannels = reader.getSizeC();
double[] emWavelengths = new double[nChannels];
for (int i = 0; i < nChannels; i++) {
Length pEm;
try {
pEm = omexmlMeta.getChannelEmissionWavelength(seriesNum, i);
} catch (IndexOutOfBoundsException e) {
pEm = null;
}
double em;
if (pEm != null) {
em = (double) pEm.value();
} else {
em = Double.NaN;
}
emWavelengths[i] = em;
}
return emWavelengths;
}
/**
* Return the objective numerical aperture(s) for a given series
*
* @return array of numerical apertures for the series. Values that could
* not be retrieved will be replaced by Double.NaN.
*/
private double[] getNAs() {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Number of instruments (usually one per series)
int nInstr = omexmlMeta.getInstrumentCount();
// Count objectives for this series (expected: 1)
int nTotObj = 0;
for (int i = 0; i < nInstr; i++) {
for (int j = 0; j < omexmlMeta.getObjectiveCount(i); j++) {
nTotObj++;
}
}
// Allocate space to store the numerical apertures
double[] numericalApertures = new double[nTotObj];
// Get all NAs (expected: 1)
int c = 0;
for (int i = 0; i < nInstr; i++) {
for (int j = 0; j < omexmlMeta.getObjectiveCount(i); j++) {
Double NA = omexmlMeta.getObjectiveLensNA(i, j);
if (NA == null) {
NA = Double.NaN;
}
numericalApertures[c++] = NA;
}
}
return numericalApertures;
}
/**
* Return the channel stage position for current series.
*
* The series must have set in advance with reader.setSeries(num).
*
* @return array of [X Y] stage position. Values that could not be retrieved
* will be replaced by Double.NaN.
*/
private double[] getStagePosition() {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Allocate memory to store the stage position
double[] stagePosition = new double[2];
// The series has been set earlier
double x, y;
// Does the stage position information exist?
Hashtable<String, Object> metadata = reader.getSeriesMetadata();
Set<String> keys = metadata.keySet();
if (keys.contains("X position")) {
Object m = metadata.get("X position");
x = (double) ((Length) m).value(); // Java 6 compatibility
} else {
x = Double.NaN;
}
if (keys.contains("Y position")) {
Object m = metadata.get("Y position");
y = (double) ((Length) m).value(); // Java 6 compatibility
} else {
y = Double.NaN;
}
// Now store the retrieved stage positions
stagePosition[0] = x;
stagePosition[1] = y;
// And return them
return stagePosition;
}
/**
* Return the channel colors [R, G, B, A]n for current series
*
* @param seriesNum index of the series to query
* @return array of arrays of [R, G, B, A]n, with n = 1 .. nChannels Values
* that could not be retrieved will be replaced by Double.NaN.
*/
private double[][] getChannelColors(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Allocate space to store the channel names
int nChannels = reader.getSizeC();
double[][] colors = new double[nChannels][4];
for (int i = 0; i < nChannels; i++) {
Color color;
try {
color = omexmlMeta.getChannelColor(seriesNum, i);
} catch (IndexOutOfBoundsException e) {
color = null;
}
if (color == null) {
if (nChannels == 1) {
// If one channel only, make it gray
colors[i][0] = 255.0;
colors[i][1] = 255.0;
colors[i][2] = 255.0;
colors[i][3] = 255.0;
} else {
// Recycle after we have run out of default colors
int n = i % defaultChannelColors.length;
colors[i] = defaultChannelColors[n];
}
} else {
colors[i][0] = color.getRed();
colors[i][1] = color.getGreen();
colors[i][2] = color.getBlue();
colors[i][3] = color.getAlpha();
}
}
// Return the colors
return colors;
}
/**
* Return the acquisition date for the specified series
*
* @param seriesNum index of series to query
* @return string acquisition date Values that could not be retrieved will
* be replaced by Double.NaN.
*/
private String getAcquisitionDate(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
Timestamp timestamp = omexmlMeta.getImageAcquisitionDate(seriesNum);
String acqDate;
if (timestamp == null) {
acqDate = "";
} else {
acqDate = timestamp.getValue();
}
return acqDate;
}
/**
* Return the voxel sizes for given series
*
* @param seriesNum index of series to query
* @return array of doubles [voxelX, voxelY, voxelZ] Values that could not
* be retrieved will be replaced by Double.NaN.
*/
private double[] getVoxelSizes(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
Length pVoxelX;
Length pVoxelY;
Length pVoxelZ;
double voxelX, voxelY, voxelZ;
// Voxel size X
pVoxelX = omexmlMeta.getPixelsPhysicalSizeX(seriesNum);
if (pVoxelX == null) {
voxelX = Double.NaN;
} else {
voxelX = (double) pVoxelX.value();
}
// Voxel size Y
pVoxelY = omexmlMeta.getPixelsPhysicalSizeY(seriesNum);
if (pVoxelY == null) {
if (pVoxelX == null) {
voxelY = Double.NaN;
} else {
// Some formats store just one size for X and Y,
// if they are equal.
voxelY = voxelX;
}
} else {
voxelY = (double) pVoxelY.value();
}
// Voxel size Z
pVoxelZ = omexmlMeta.getPixelsPhysicalSizeZ(seriesNum);
if (pVoxelZ == null) {
voxelZ = Double.NaN;
} else {
voxelZ = (double) pVoxelZ.value();
}
// Return
return new double[] { voxelX, voxelY, voxelZ };
}
/**
* Return the channel names
*
* @param seriesNum index of the series to query
* @return array of channel names
*/
private String[] getChannelNames(int seriesNum) {
// Make sure the reader is open
if (reader == null) {
throw new RuntimeException("File not opened yet!.");
}
// Allocate space to store the channel names
int nChannels = reader.getSizeC();
String[] channelNames = new String[nChannels];
for (int i = 0; i < nChannels; i++) {
String channelName;
try {
channelName = omexmlMeta.getChannelName(seriesNum, i);
} catch (IndexOutOfBoundsException e) {
channelName = null;
}
if (channelName == null) {
channelName = "CHANNEL_" + i;
}
// Make sure to remove "\0" end of the name
// (as found for instance in LSM files)
if (channelName.endsWith("\0")) {
channelName = channelName.substring(0,
channelName.length() - 1);
}
channelNames[i] = channelName;
}
return channelNames;
}
/**
* Return the list of series indices extracted from the file names
*
* @return List of series indices
*/
public List<Integer> getSeriesIndices() {
List<Integer> indices = new ArrayList<Integer>();
for (String key : attr.keySet()) {
// Get the index from the series_{n} key
indices.add(Integer.parseInt(key.substring(7)));
}
Collections.sort(indices);
return indices;
}
public byte[] ReadBytes() throws FormatException, IOException {
return this.reader.openBytes(0);
}
static public double[] getDefaultChannelColor(int channelIndex) {
return defaultChannelColors[channelIndex % 6];
}
}
| {
"content_hash": "6f5f63609e498f03665bfbd6babac872",
"timestamp": "",
"source": "github",
"line_count": 817,
"max_line_length": 109,
"avg_line_length": 31.085679314565482,
"alnum_prop": 0.5301413552781825,
"repo_name": "aarpon/obit_annotation_tool",
"id": "30529fd58e866b19c36bd5962e0d635f8cda3115",
"size": "25397",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "AnnotationToolMicroscopy/ch/ethz/scu/obit/microscopy/readers/BioFormatsWrapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "914670"
},
{
"name": "XSLT",
"bytes": "64106"
}
],
"symlink_target": ""
} |
<?php
namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
class Mysql extends Sql
{
/**
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table Table name
* @return array
*/
public function columns(string $table): array
{
$databaseBinding = $this->bindingName('database');
$tableBinding = $this->bindingName('table');
$query = 'SELECT COLUMN_NAME AS name FROM INFORMATION_SCHEMA.COLUMNS ';
$query .= 'WHERE TABLE_SCHEMA = ' . $databaseBinding . ' AND TABLE_NAME = ' . $tableBinding;
return [
'query' => $query,
'bindings' => [
$databaseBinding => $this->database->name(),
$tableBinding => $table,
]
];
}
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*
* @return array
*/
public function tables(): array
{
$binding = $this->bindingName('database');
return [
'query' => 'SELECT TABLE_NAME AS name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ' . $binding,
'bindings' => [
$binding => $this->database->name()
]
];
}
}
| {
"content_hash": "f4ec7c09d71909abed4c4c6459fdcbed",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 109,
"avg_line_length": 23.137254901960784,
"alnum_prop": 0.635593220338983,
"repo_name": "mmewen/mewen.fr",
"id": "f8fc9d3f87deed7452a82cdcf5b604006f491788",
"size": "1412",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kirby/src/Database/Sql/Mysql.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17090"
},
{
"name": "Hack",
"bytes": "842"
},
{
"name": "JavaScript",
"bytes": "198"
},
{
"name": "PHP",
"bytes": "1868855"
},
{
"name": "Python",
"bytes": "2225"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace phpDocumentor\Parser;
use League\Flysystem\Filesystem;
use phpDocumentor\Dsn;
/**
* Interface for FileSystem factories.
*/
interface FileSystemFactory
{
/**
* Returns a Filesystem instance based on the scheme of the provided Dsn.
*/
public function create(Dsn $dsn) : Filesystem;
}
| {
"content_hash": "da19961e216d068c280abd989844cc53",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 77,
"avg_line_length": 16.61904761904762,
"alnum_prop": 0.7106017191977078,
"repo_name": "phpDocumentor/phpDocumentor2",
"id": "591b228f0a3998c3e483522472249df495a2a2d2",
"size": "556",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/composer/symfony/flex-1.12.1",
"path": "src/phpDocumentor/Parser/FileSystemFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "284"
},
{
"name": "CSS",
"bytes": "14643"
},
{
"name": "Dockerfile",
"bytes": "1112"
},
{
"name": "Gherkin",
"bytes": "34587"
},
{
"name": "HTML",
"bytes": "120143"
},
{
"name": "JavaScript",
"bytes": "58657"
},
{
"name": "Makefile",
"bytes": "286"
},
{
"name": "PHP",
"bytes": "1274162"
},
{
"name": "Shell",
"bytes": "629"
}
],
"symlink_target": ""
} |
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXXX-X', 'auto');
ga('send', 'pageview');
</script>
</head>
| {
"content_hash": "5218d51a1ac526408673d6755e59576f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 84,
"avg_line_length": 35.333333333333336,
"alnum_prop": 0.6352201257861635,
"repo_name": "luism-s/mySage",
"id": "29d5c11930a93b37c868620374400664fcadaedf",
"size": "636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/head.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8950"
},
{
"name": "HTML",
"bytes": "362"
},
{
"name": "JavaScript",
"bytes": "10160"
},
{
"name": "PHP",
"bytes": "23359"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
angular
.module('xpacswebApp')
.controller('CapModelDetailController', CapModelDetailController);
CapModelDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'DataUtils', 'entity', 'CapModel', 'PatientInfo'];
function CapModelDetailController($scope, $rootScope, $stateParams, previousState, DataUtils, entity, CapModel, PatientInfo) {
var vm = this;
vm.capModel = entity;
vm.previousState = previousState.name;
vm.byteSize = DataUtils.byteSize;
vm.openFile = DataUtils.openFile;
var unsubscribe = $rootScope.$on('xpacswebApp:capModelUpdate', function(event, result) {
vm.capModel = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
| {
"content_hash": "4f742b0c6f330be77cef3d40ef65272b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 147,
"avg_line_length": 35.56521739130435,
"alnum_prop": 0.6430317848410758,
"repo_name": "CardiacAtlasProject/CAPServer2.0",
"id": "4b2635625334443ec8660f813eec1d29f03572cf",
"size": "818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xpacs/src/main/webapp/app/entities/cap-model/cap-model-detail.controller.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5036"
},
{
"name": "CSS",
"bytes": "10248"
},
{
"name": "Gherkin",
"bytes": "179"
},
{
"name": "HTML",
"bytes": "182082"
},
{
"name": "Java",
"bytes": "446416"
},
{
"name": "JavaScript",
"bytes": "271433"
},
{
"name": "Python",
"bytes": "13917"
},
{
"name": "Scala",
"bytes": "20977"
},
{
"name": "Shell",
"bytes": "9179"
}
],
"symlink_target": ""
} |
package com.cognifide.qa.bb.aem.core.component.dialog.dialogfields.text;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.cognifide.qa.bb.javascriptexecutor.JsScripts;
import com.cognifide.qa.bb.qualifier.CurrentScope;
import com.cognifide.qa.bb.qualifier.PageObject;
import com.google.inject.Inject;
/**
* Implementation of {@link ControlToolbar} for AEM 6.4
*/
@PageObject(css = ".coral3-ButtonGroup.rte-toolbar.is-active")
public class ControlToolbarImpl implements ControlToolbar {
static final String TOOLBAR_ITEM_SELECTOR = ".rte-toolbar-item";
@Inject
@CurrentScope
private WebElement scope;
@FindBy(css = TOOLBAR_ITEM_SELECTOR + "[data-action='format#bold']")
private WebElement toggleBoldButton;
@FindBy(css = TOOLBAR_ITEM_SELECTOR + "[data-action='format#italic']")
private WebElement toggleItalicButton;
@FindBy(css = TOOLBAR_ITEM_SELECTOR + "[data-action='format#underline']")
private WebElement toggleUnderlineButton;
@FindBy(css = TOOLBAR_ITEM_SELECTOR + "[data-action='#justify']")
private WebElement toggleJustifyButton;
@FindBy(css = TOOLBAR_ITEM_SELECTOR + "[data-action='#lists']")
private WebElement toggleListButton;
@Inject
private JavascriptExecutor javascriptExecutor;
@Override
public void selectText() {
javascriptExecutor.executeScript(JsScripts.SELECT_ALL);
}
@Override
public WebElement getScope() {
return scope;
}
@Override
public WebElement getToggleBoldButton() {
return toggleBoldButton;
}
@Override
public WebElement getToggleItalicButton() {
return toggleItalicButton;
}
@Override
public WebElement getToggleUnderlineButton() {
return toggleUnderlineButton;
}
@Override
public WebElement getToggleJustifyButton() {
return toggleJustifyButton;
}
@Override
public WebElement getToggleListButton() {
return toggleListButton;
}
}
| {
"content_hash": "88ff648a2c88a4357a76621c42d18374",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 75,
"avg_line_length": 25.346153846153847,
"alnum_prop": 0.7546788062721295,
"repo_name": "Cognifide/bobcat",
"id": "0a4b0d50a3473e1cf53de76a2a5284481d380c83",
"size": "2576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bb-aem-64/src/main/java/com/cognifide/qa/bb/aem/core/component/dialog/dialogfields/text/ControlToolbarImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "908281"
},
{
"name": "Shell",
"bytes": "1044"
}
],
"symlink_target": ""
} |
use super::get_tag;
#[cfg(target_arch = "x86_64")]
use arch::vga_buffer;
use memory::{Address, VirtualAddress};
/// Represents the framebuffer information tag.
#[repr(C)]
pub struct FramebufferInfo {
// type = 8
tag_type: u32,
size: u32,
pub framebuffer_addr: u64,
framebuffer_pitch: u32,
pub framebuffer_width: u32,
pub framebuffer_height: u32,
framebuffer_bpp: u8,
framebuffer_type: u8,
reserved: u8,
color_info: u32 // This is just a placeholder, this depends on the framebuffer_type.
}
/// Returns the VGA buffer information requested.
#[cfg(target_arch = "x86_64")]
pub fn get_vga_info() -> vga_buffer::Info {
let framebuffer_tag = get_tag(8);
match framebuffer_tag {
Some(framebuffer_tag_address) => {
let framebuffer_tag = unsafe { &*(framebuffer_tag_address as *const FramebufferInfo) };
vga_buffer::Info {
height: framebuffer_tag.framebuffer_height as usize,
width: framebuffer_tag.framebuffer_width as usize,
address: VirtualAddress::from_usize(to_virtual!(framebuffer_tag.framebuffer_addr))
}
},
None => vga_buffer::Info {
height: 25,
width: 80,
address: VirtualAddress::from_usize(to_virtual!(0xb8000))
}
}
}
| {
"content_hash": "1b14172acb6c92211ee0a62486fa803c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 99,
"avg_line_length": 32.46341463414634,
"alnum_prop": 0.6190833959429001,
"repo_name": "aticu/VeOS",
"id": "3178b5816a430e5cad8e4b760305908bbc408e8a",
"size": "1377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kernel/src/boot/multiboot2/framebuffer_info.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7509"
},
{
"name": "Makefile",
"bytes": "4542"
},
{
"name": "Rust",
"bytes": "276083"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RandomSchoolAsync.Extenders;
using RandomSchoolAsync.Repositories;
using RandomSchoolAsync.FieldTemplates;
using System.Threading.Tasks;
using ScaffoldFilter;
namespace RandomSchoolAsync.Maintain.vParent
{
public partial class Edit : System.Web.UI.Page
{
private ParentRepositoryAsync<RandomSchoolAsync.Models.Parent, int?> _repository = new ParentRepositoryAsync<RandomSchoolAsync.Models.Parent, int?>();
protected void Page_Init()
{
fvParent.SetDataMethodsObject(_repository);
fvParent.RedirectToRouteOnItemCommand("~/Maintain/vParent/Default");
fvParent.RedirectToRouteOnItemUpdated("~/Maintain/vParent/Default");
}
protected void Page_Load(object sender, EventArgs e)
{
}
public async Task ForeignKeyEventHandler_LoadForeignKey(ForeignModelEventArgs e)
{
e.returnResults = await _repository.GetForeignListAsync(e.foreignKeyModel, e.keyType);
}
protected void dcForeignKey_Load(object sender, EventArgs e)
{
System.Web.DynamicData.DynamicControl dc = (System.Web.DynamicData.DynamicControl)sender;
ForeignKey_EditField fkef = (ForeignKey_EditField)dc.FieldTemplate;
if (fkef != null)
{
fkef.ForeignKey += new AsyncForeignKeyEventHandler(ForeignKeyEventHandler_LoadForeignKey);
}
}
}
}
| {
"content_hash": "6287bca2585608009a969afe22d17011",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 152,
"avg_line_length": 33.17391304347826,
"alnum_prop": 0.7195281782437746,
"repo_name": "jbwilliamson/MaximiseWFScaffolding",
"id": "87ebd14dcfd743453d6834d63d109ad74e7017cd",
"size": "1528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RandomSchoolAsync/RandomSchoolAsync/Maintain/vParent/Edit.aspx.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "300977"
},
{
"name": "C#",
"bytes": "616243"
},
{
"name": "CSS",
"bytes": "3383"
},
{
"name": "JavaScript",
"bytes": "358408"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Register Requirements for AMD64 XX
XX XX
XX This encapsulates all the logic for setting register requirements for XX
XX the AMD64 architecture. XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator
#ifdef _TARGET_XARCH_
#include "jit.h"
#include "sideeffects.h"
#include "lower.h"
//------------------------------------------------------------------------
// TreeNodeInfoInitStoreLoc: Set register requirements for a store of a lclVar
//
// Arguments:
// storeLoc - the local store (GT_STORE_LCL_FLD or GT_STORE_LCL_VAR)
//
// Notes:
// This involves:
// - Setting the appropriate candidates for a store of a multi-reg call return value.
// - Requesting an internal register for SIMD12 stores.
// - Handling of contained immediates.
// - Widening operations of unsigneds. (TODO: Move to 1st phase of Lowering)
void Lowering::TreeNodeInfoInitStoreLoc(GenTreeLclVarCommon* storeLoc)
{
TreeNodeInfo* info = &(storeLoc->gtLsraInfo);
// Is this the case of var = call where call is returning
// a value in multiple return registers?
GenTree* op1 = storeLoc->gtGetOp1();
if (op1->IsMultiRegCall())
{
// backend expects to see this case only for store lclvar.
assert(storeLoc->OperGet() == GT_STORE_LCL_VAR);
// srcCount = number of registers in which the value is returned by call
GenTreeCall* call = op1->AsCall();
ReturnTypeDesc* retTypeDesc = call->GetReturnTypeDesc();
info->srcCount = retTypeDesc->GetReturnRegCount();
// Call node srcCandidates = Bitwise-OR(allregs(GetReturnRegType(i))) for all i=0..RetRegCount-1
regMaskTP srcCandidates = m_lsra->allMultiRegCallNodeRegs(call);
op1->gtLsraInfo.setSrcCandidates(m_lsra, srcCandidates);
return;
}
#ifdef FEATURE_SIMD
if (varTypeIsSIMD(storeLoc))
{
if (op1->IsCnsIntOrI())
{
// InitBlk
MakeSrcContained(storeLoc, op1);
}
else if (storeLoc->TypeGet() == TYP_SIMD12)
{
// Need an additional register to extract upper 4 bytes of Vector3.
info->internalFloatCount = 1;
info->setInternalCandidates(m_lsra, m_lsra->allSIMDRegs());
// In this case don't mark the operand as contained as we want it to
// be evaluated into an xmm register
}
return;
}
#endif // FEATURE_SIMD
// If the source is a containable immediate, make it contained, unless it is
// an int-size or larger store of zero to memory, because we can generate smaller code
// by zeroing a register and then storing it.
if (IsContainableImmed(storeLoc, op1) && (!op1->IsIntegralConst(0) || varTypeIsSmall(storeLoc)))
{
MakeSrcContained(storeLoc, op1);
}
// TODO: This should be moved to Lowering, but it widens the types, which changes the behavior
// of the above condition.
LowerStoreLoc(storeLoc);
}
//------------------------------------------------------------------------
// TreeNodeInfoInit: Set register requirements for a node
//
// Arguments:
// treeNode - the node of interest
//
// Notes:
// Preconditions:
// LSRA Has been initialized and there is a TreeNodeInfo node
// already allocated and initialized for every tree in the IR.
// Postconditions:
// Every TreeNodeInfo instance has the right annotations on register
// requirements needed by LSRA to build the Interval Table (source,
// destination and internal [temp] register counts).
//
void Lowering::TreeNodeInfoInit(GenTree* tree)
{
LinearScan* l = m_lsra;
Compiler* compiler = comp;
TreeNodeInfo* info = &(tree->gtLsraInfo);
#ifdef DEBUG
if (comp->verbose)
{
printf("TreeNodeInfoInit:\n");
comp->gtDispTreeRange(BlockRange(), tree);
}
#endif
// floating type generates AVX instruction (vmovss etc.), set the flag
SetContainsAVXFlags(varTypeIsFloating(tree->TypeGet()));
switch (tree->OperGet())
{
GenTree* op1;
GenTree* op2;
default:
TreeNodeInfoInitSimple(tree);
break;
case GT_LCL_FLD:
case GT_LCL_VAR:
info->srcCount = 0;
info->dstCount = 1;
#ifdef FEATURE_SIMD
// Need an additional register to read upper 4 bytes of Vector3.
if (tree->TypeGet() == TYP_SIMD12)
{
// We need an internal register different from targetReg in which 'tree' produces its result
// because both targetReg and internal reg will be in use at the same time.
info->internalFloatCount = 1;
info->isInternalRegDelayFree = true;
info->setInternalCandidates(m_lsra, m_lsra->allSIMDRegs());
}
#endif
break;
case GT_STORE_LCL_FLD:
case GT_STORE_LCL_VAR:
#ifdef _TARGET_X86_
if (tree->gtGetOp1()->OperGet() == GT_LONG)
{
tree->gtGetOp1()->SetContained();
info->srcCount = 2;
}
else
#endif // _TARGET_X86_
{
info->srcCount = 1;
}
info->dstCount = 0;
TreeNodeInfoInitStoreLoc(tree->AsLclVarCommon());
break;
case GT_PHYSREGDST:
info->srcCount = 1;
info->dstCount = 0;
break;
case GT_LIST:
case GT_FIELD_LIST:
case GT_ARGPLACE:
case GT_NO_OP:
case GT_START_NONGC:
case GT_PROF_HOOK:
info->srcCount = 0;
info->dstCount = 0;
break;
case GT_CNS_DBL:
info->srcCount = 0;
info->dstCount = 1;
break;
#if !defined(_TARGET_64BIT_)
case GT_LONG:
if ((tree->gtLIRFlags & LIR::Flags::IsUnusedValue) != 0)
{
// An unused GT_LONG node needs to consume its sources.
info->srcCount = 2;
}
else
{
// Passthrough
info->srcCount = 0;
}
info->dstCount = 0;
break;
#endif // !defined(_TARGET_64BIT_)
case GT_BOX:
case GT_COMMA:
case GT_QMARK:
case GT_COLON:
info->srcCount = 0;
info->dstCount = 0;
unreached();
break;
case GT_RETURN:
TreeNodeInfoInitReturn(tree);
break;
case GT_RETFILT:
if (tree->TypeGet() == TYP_VOID)
{
info->srcCount = 0;
info->dstCount = 0;
}
else
{
assert(tree->TypeGet() == TYP_INT);
info->srcCount = 1;
info->dstCount = 0;
info->setSrcCandidates(l, RBM_INTRET);
tree->gtOp.gtOp1->gtLsraInfo.setSrcCandidates(l, RBM_INTRET);
}
break;
// A GT_NOP is either a passthrough (if it is void, or if it has
// a child), but must be considered to produce a dummy value if it
// has a type but no child
case GT_NOP:
info->srcCount = 0;
if (tree->TypeGet() != TYP_VOID && tree->gtOp.gtOp1 == nullptr)
{
info->dstCount = 1;
}
else
{
info->dstCount = 0;
}
break;
case GT_JTRUE:
{
info->srcCount = 0;
info->dstCount = 0;
GenTree* cmp = tree->gtGetOp1();
l->clearDstCount(cmp);
#ifdef FEATURE_SIMD
// Say we have the following IR
// simdCompareResult = GT_SIMD((In)Equality, v1, v2)
// integerCompareResult = GT_EQ/NE(simdCompareResult, true/false)
// GT_JTRUE(integerCompareResult)
//
// In this case we don't need to generate code for GT_EQ_/NE, since SIMD (In)Equality
// intrinsic will set or clear the Zero flag.
genTreeOps cmpOper = cmp->OperGet();
if (cmpOper == GT_EQ || cmpOper == GT_NE)
{
GenTree* cmpOp1 = cmp->gtGetOp1();
GenTree* cmpOp2 = cmp->gtGetOp2();
if (cmpOp1->IsSIMDEqualityOrInequality() && (cmpOp2->IsIntegralConst(0) || cmpOp2->IsIntegralConst(1)))
{
// We always generate code for a SIMD equality comparison, but the compare itself produces no value.
// Neither the SIMD node nor the immediate need to be evaluated into a register.
l->clearOperandCounts(cmp);
l->clearDstCount(cmpOp1);
l->clearOperandCounts(cmpOp2);
cmpOp2->SetContained();
// Codegen of SIMD (in)Equality uses target integer reg only for setting flags.
// A target reg is not needed on AVX when comparing against Vector Zero.
// In all other cases we need to reserve an int type internal register, since we
// have cleared dstCount.
if (!compiler->canUseAVX() || !cmpOp1->gtGetOp2()->IsIntegralConstVector(0))
{
++(cmpOp1->gtLsraInfo.internalIntCount);
regMaskTP internalCandidates = cmpOp1->gtLsraInfo.getInternalCandidates(l);
internalCandidates |= l->allRegs(TYP_INT);
cmpOp1->gtLsraInfo.setInternalCandidates(l, internalCandidates);
}
// We have to reverse compare oper in the following cases:
// 1) SIMD Equality: Sets Zero flag on equal otherwise clears it.
// Therefore, if compare oper is == or != against false(0), we will
// be checking opposite of what is required.
//
// 2) SIMD inEquality: Clears Zero flag on true otherwise sets it.
// Therefore, if compare oper is == or != against true(1), we will
// be checking opposite of what is required.
GenTreeSIMD* simdNode = cmpOp1->AsSIMD();
if (simdNode->gtSIMDIntrinsicID == SIMDIntrinsicOpEquality)
{
if (cmpOp2->IsIntegralConst(0))
{
cmp->SetOper(GenTree::ReverseRelop(cmpOper));
}
}
else
{
assert(simdNode->gtSIMDIntrinsicID == SIMDIntrinsicOpInEquality);
if (cmpOp2->IsIntegralConst(1))
{
cmp->SetOper(GenTree::ReverseRelop(cmpOper));
}
}
}
}
#endif // FEATURE_SIMD
}
break;
case GT_JCC:
info->srcCount = 0;
info->dstCount = 0;
break;
case GT_SETCC:
info->srcCount = 0;
info->dstCount = 1;
#ifdef _TARGET_X86_
info->setDstCandidates(m_lsra, RBM_BYTE_REGS);
#endif // _TARGET_X86_
break;
case GT_JMP:
info->srcCount = 0;
info->dstCount = 0;
break;
case GT_SWITCH:
// This should never occur since switch nodes must not be visible at this
// point in the JIT.
info->srcCount = 0;
info->dstCount = 0; // To avoid getting uninit errors.
noway_assert(!"Switch must be lowered at this point");
break;
case GT_JMPTABLE:
info->srcCount = 0;
info->dstCount = 1;
break;
case GT_SWITCH_TABLE:
info->srcCount = 2;
info->internalIntCount = 1;
info->dstCount = 0;
break;
case GT_ASG:
case GT_ASG_ADD:
case GT_ASG_SUB:
noway_assert(!"We should never hit any assignment operator in lowering");
info->srcCount = 0;
info->dstCount = 0;
break;
#if !defined(_TARGET_64BIT_)
case GT_ADD_LO:
case GT_ADD_HI:
case GT_SUB_LO:
case GT_SUB_HI:
#endif
case GT_ADD:
case GT_SUB:
// SSE2 arithmetic instructions doesn't support the form "op mem, xmm".
// Rather they only support "op xmm, mem/xmm" form.
if (varTypeIsFloating(tree->TypeGet()))
{
// overflow operations aren't supported on float/double types.
assert(!tree->gtOverflow());
op1 = tree->gtGetOp1();
op2 = tree->gtGetOp2();
// No implicit conversions at this stage as the expectation is that
// everything is made explicit by adding casts.
assert(op1->TypeGet() == op2->TypeGet());
info->srcCount = 2;
info->dstCount = 1;
if (IsContainableMemoryOp(op2, true) || op2->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, op2);
}
else if (tree->OperIsCommutative() &&
(op1->IsCnsNonZeroFltOrDbl() ||
(IsContainableMemoryOp(op1, true) && IsSafeToContainMem(tree, op1))))
{
// Though we have GT_ADD(op1=memOp, op2=non-memOp, we try to reorder the operands
// as long as it is safe so that the following efficient code sequence is generated:
// addss/sd targetReg, memOp (if op1Reg == targetReg) OR
// movaps targetReg, op2Reg; addss/sd targetReg, [memOp]
//
// Instead of
// movss op1Reg, [memOp]; addss/sd targetReg, Op2Reg (if op1Reg == targetReg) OR
// movss op1Reg, [memOp]; movaps targetReg, op1Reg, addss/sd targetReg, Op2Reg
MakeSrcContained(tree, op1);
}
else
{
// If there are no containable operands, we can make an operand reg optional.
SetRegOptionalForBinOp(tree);
}
break;
}
__fallthrough;
case GT_AND:
case GT_OR:
case GT_XOR:
TreeNodeInfoInitLogicalOp(tree);
break;
case GT_RETURNTRAP:
// This just turns into a compare of its child with an int + a conditional call
info->srcCount = 1;
info->dstCount = 0;
if (tree->gtOp.gtOp1->isIndir())
{
MakeSrcContained(tree, tree->gtOp.gtOp1);
}
info->internalIntCount = 1;
info->setInternalCandidates(l, l->allRegs(TYP_INT));
break;
case GT_MOD:
case GT_DIV:
case GT_UMOD:
case GT_UDIV:
TreeNodeInfoInitModDiv(tree);
break;
case GT_MUL:
case GT_MULHI:
#if defined(_TARGET_X86_) && !defined(LEGACY_BACKEND)
case GT_MUL_LONG:
#endif
TreeNodeInfoInitMul(tree);
break;
case GT_INTRINSIC:
TreeNodeInfoInitIntrinsic(tree);
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
TreeNodeInfoInitSIMD(tree);
break;
#endif // FEATURE_SIMD
case GT_CAST:
TreeNodeInfoInitCast(tree);
break;
case GT_NEG:
info->srcCount = 1;
info->dstCount = 1;
// TODO-XArch-CQ:
// SSE instruction set doesn't have an instruction to negate a number.
// The recommended way is to xor the float/double number with a bitmask.
// The only way to xor is using xorps or xorpd both of which operate on
// 128-bit operands. To hold the bit-mask we would need another xmm
// register or a 16-byte aligned 128-bit data constant. Right now emitter
// lacks the support for emitting such constants or instruction with mem
// addressing mode referring to a 128-bit operand. For now we use an
// internal xmm register to load 32/64-bit bitmask from data section.
// Note that by trading additional data section memory (128-bit) we can
// save on the need for an internal register and also a memory-to-reg
// move.
//
// Note: another option to avoid internal register requirement is by
// lowering as GT_SUB(0, src). This will generate code different from
// Jit64 and could possibly result in compat issues (?).
if (varTypeIsFloating(tree))
{
info->internalFloatCount = 1;
info->setInternalCandidates(l, l->internalFloatRegCandidates());
}
else
{
// Codegen of this tree node sets ZF and SF flags.
tree->gtFlags |= GTF_ZSF_SET;
}
break;
case GT_NOT:
info->srcCount = 1;
info->dstCount = 1;
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
case GT_ROL:
case GT_ROR:
#ifdef _TARGET_X86_
case GT_LSH_HI:
case GT_RSH_LO:
#endif
TreeNodeInfoInitShiftRotate(tree);
break;
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
case GT_TEST_EQ:
case GT_TEST_NE:
case GT_CMP:
TreeNodeInfoInitCmp(tree);
break;
case GT_CKFINITE:
info->srcCount = 1;
info->dstCount = 1;
info->internalIntCount = 1;
break;
case GT_CMPXCHG:
info->srcCount = 3;
info->dstCount = 1;
// comparand is preferenced to RAX.
// Remaining two operands can be in any reg other than RAX.
tree->gtCmpXchg.gtOpComparand->gtLsraInfo.setSrcCandidates(l, RBM_RAX);
tree->gtCmpXchg.gtOpLocation->gtLsraInfo.setSrcCandidates(l, l->allRegs(TYP_INT) & ~RBM_RAX);
tree->gtCmpXchg.gtOpValue->gtLsraInfo.setSrcCandidates(l, l->allRegs(TYP_INT) & ~RBM_RAX);
tree->gtLsraInfo.setDstCandidates(l, RBM_RAX);
break;
case GT_LOCKADD:
info->srcCount = 2;
info->dstCount = (tree->TypeGet() == TYP_VOID) ? 0 : 1;
CheckImmedAndMakeContained(tree, tree->gtOp.gtOp2);
break;
case GT_CALL:
TreeNodeInfoInitCall(tree->AsCall());
break;
case GT_ADDR:
{
// For a GT_ADDR, the child node should not be evaluated into a register
GenTreePtr child = tree->gtOp.gtOp1;
assert(!l->isCandidateLocalRef(child));
l->clearDstCount(child);
info->srcCount = 0;
info->dstCount = 1;
}
break;
#if !defined(FEATURE_PUT_STRUCT_ARG_STK)
case GT_OBJ:
#endif
case GT_BLK:
case GT_DYN_BLK:
// These should all be eliminated prior to Lowering.
assert(!"Non-store block node in Lowering");
info->srcCount = 0;
info->dstCount = 0;
break;
#ifdef FEATURE_PUT_STRUCT_ARG_STK
case GT_PUTARG_STK:
LowerPutArgStk(tree->AsPutArgStk());
TreeNodeInfoInitPutArgStk(tree->AsPutArgStk());
break;
#endif // FEATURE_PUT_STRUCT_ARG_STK
case GT_STORE_BLK:
case GT_STORE_OBJ:
case GT_STORE_DYN_BLK:
LowerBlockStore(tree->AsBlk());
TreeNodeInfoInitBlockStore(tree->AsBlk());
break;
case GT_INIT_VAL:
// Always a passthrough of its child's value.
info->srcCount = 0;
info->dstCount = 0;
break;
case GT_LCLHEAP:
TreeNodeInfoInitLclHeap(tree);
break;
case GT_ARR_BOUNDS_CHECK:
#ifdef FEATURE_SIMD
case GT_SIMD_CHK:
#endif // FEATURE_SIMD
{
GenTreeBoundsChk* node = tree->AsBoundsChk();
// Consumes arrLen & index - has no result
info->srcCount = 2;
info->dstCount = 0;
GenTreePtr other;
if (CheckImmedAndMakeContained(tree, node->gtIndex))
{
other = node->gtArrLen;
}
else if (CheckImmedAndMakeContained(tree, node->gtArrLen))
{
other = node->gtIndex;
}
else if (IsContainableMemoryOp(node->gtIndex, true))
{
other = node->gtIndex;
}
else
{
other = node->gtArrLen;
}
if (node->gtIndex->TypeGet() == node->gtArrLen->TypeGet())
{
if (IsContainableMemoryOp(other, true))
{
MakeSrcContained(tree, other);
}
else
{
// We can mark 'other' as reg optional, since it is not contained.
SetRegOptional(other);
}
}
}
break;
case GT_ARR_ELEM:
// These must have been lowered to GT_ARR_INDEX
noway_assert(!"We should never see a GT_ARR_ELEM in lowering");
info->srcCount = 0;
info->dstCount = 0;
break;
case GT_ARR_INDEX:
info->srcCount = 2;
info->dstCount = 1;
// For GT_ARR_INDEX, the lifetime of the arrObj must be extended because it is actually used multiple
// times while the result is being computed.
tree->AsArrIndex()->ArrObj()->gtLsraInfo.isDelayFree = true;
info->hasDelayFreeSrc = true;
break;
case GT_ARR_OFFSET:
// This consumes the offset, if any, the arrObj and the effective index,
// and produces the flattened offset for this dimension.
info->srcCount = 3;
info->dstCount = 1;
// we don't want to generate code for this
if (tree->gtArrOffs.gtOffset->IsIntegralConst(0))
{
MakeSrcContained(tree, tree->gtArrOffs.gtOffset);
}
else
{
// Here we simply need an internal register, which must be different
// from any of the operand's registers, but may be the same as targetReg.
info->internalIntCount = 1;
}
break;
case GT_LEA:
// The LEA usually passes its operands through to the GT_IND, in which case we'll
// clear the info->srcCount and info->dstCount later, but we may be instantiating an address,
// so we set them here.
info->srcCount = 0;
if (tree->AsAddrMode()->HasBase())
{
info->srcCount++;
}
if (tree->AsAddrMode()->HasIndex())
{
info->srcCount++;
}
info->dstCount = 1;
break;
case GT_STOREIND:
{
info->srcCount = 2;
info->dstCount = 0;
GenTree* src = tree->gtOp.gtOp2;
if (compiler->codeGen->gcInfo.gcIsWriteBarrierAsgNode(tree))
{
TreeNodeInfoInitGCWriteBarrier(tree);
break;
}
// If the source is a containable immediate, make it contained, unless it is
// an int-size or larger store of zero to memory, because we can generate smaller code
// by zeroing a register and then storing it.
if (IsContainableImmed(tree, src) &&
(!src->IsIntegralConst(0) || varTypeIsSmall(tree) || tree->gtGetOp1()->OperGet() == GT_CLS_VAR_ADDR))
{
MakeSrcContained(tree, src);
}
else if (!varTypeIsFloating(tree))
{
// Perform recognition of trees with the following structure:
// StoreInd(addr, BinOp(expr, GT_IND(addr)))
// to be able to fold this into an instruction of the form
// BINOP [addr], register
// where register is the actual place where 'expr' is computed.
//
// SSE2 doesn't support RMW form of instructions.
if (TreeNodeInfoInitIfRMWMemOp(tree))
{
break;
}
}
TreeNodeInfoInitIndir(tree);
}
break;
case GT_NULLCHECK:
info->dstCount = 0;
info->srcCount = 1;
info->isLocalDefUse = true;
break;
case GT_IND:
info->dstCount = 1;
info->srcCount = 1;
TreeNodeInfoInitIndir(tree);
break;
case GT_CATCH_ARG:
info->srcCount = 0;
info->dstCount = 1;
info->setDstCandidates(l, RBM_EXCEPTION_OBJECT);
break;
#if !FEATURE_EH_FUNCLETS
case GT_END_LFIN:
info->srcCount = 0;
info->dstCount = 0;
break;
#endif
case GT_CLS_VAR:
// These nodes are eliminated by rationalizer.
JITDUMP("Unexpected node %s in Lower.\n", GenTree::OpName(tree->OperGet()));
unreached();
break;
} // end switch (tree->OperGet())
// If op2 of a binary-op gets marked as contained, then binary-op srcCount will be 1.
// Even then we would like to set isTgtPref on Op1.
if (tree->OperIsBinary() && info->srcCount >= 1)
{
if (isRMWRegOper(tree))
{
GenTree* op1 = tree->gtOp.gtOp1;
GenTree* op2 = tree->gtOp.gtOp2;
// Commutative opers like add/mul/and/or/xor could reverse the order of
// operands if it is safe to do so. In such a case we would like op2 to be
// target preferenced instead of op1.
if (tree->OperIsCommutative() && op1->gtLsraInfo.dstCount == 0 && op2 != nullptr)
{
op1 = op2;
op2 = tree->gtOp.gtOp1;
}
// If we have a read-modify-write operation, we want to preference op1 to the target.
// If op1 is contained, we don't want to preference it, but it won't
// show up as a source in that case, so it will be ignored.
op1->gtLsraInfo.isTgtPref = true;
// Is this a non-commutative operator, or is op2 a contained memory op?
// (Note that we can't call IsContained() at this point because it uses exactly the
// same information we're currently computing.)
// In either case, we need to make op2 remain live until the op is complete, by marking
// the source(s) associated with op2 as "delayFree".
// Note that if op2 of a binary RMW operator is a memory op, even if the operator
// is commutative, codegen cannot reverse them.
// TODO-XArch-CQ: This is not actually the case for all RMW binary operators, but there's
// more work to be done to correctly reverse the operands if they involve memory
// operands. Also, we may need to handle more cases than GT_IND, especially once
// we've modified the register allocator to not require all nodes to be assigned
// a register (e.g. a spilled lclVar can often be referenced directly from memory).
// Note that we may have a null op2, even with 2 sources, if op1 is a base/index memory op.
GenTree* delayUseSrc = nullptr;
// TODO-XArch-Cleanup: We should make the indirection explicit on these nodes so that we don't have
// to special case them.
if (tree->OperGet() == GT_XADD || tree->OperGet() == GT_XCHG || tree->OperGet() == GT_LOCKADD)
{
// These tree nodes will have their op1 marked as isDelayFree=true.
// Hence these tree nodes should have a Def position so that op1's reg
// gets freed at DefLoc+1.
if (tree->TypeGet() == TYP_VOID)
{
// Right now a GT_XADD node could be morphed into a
// GT_LOCKADD of TYP_VOID. See gtExtractSideEffList().
// Note that it is advantageous to use GT_LOCKADD
// instead of of GT_XADD as the former uses lock.add,
// which allows its second operand to be a contained
// immediate wheres xadd instruction requires its
// second operand to be in a register.
assert(tree->gtLsraInfo.dstCount == 0);
// Give it an artificial type and mark it isLocalDefUse = true.
// This would result in a Def position created but not considered
// consumed by its parent node.
tree->gtType = TYP_INT;
tree->gtLsraInfo.isLocalDefUse = true;
}
else
{
assert(tree->gtLsraInfo.dstCount != 0);
}
delayUseSrc = op1;
}
else if ((op2 != nullptr) && (!tree->OperIsCommutative() ||
(IsContainableMemoryOp(op2, true) && (op2->gtLsraInfo.srcCount == 0))))
{
delayUseSrc = op2;
}
if (delayUseSrc != nullptr)
{
SetDelayFree(delayUseSrc);
info->hasDelayFreeSrc = true;
}
}
}
TreeNodeInfoInitCheckByteable(tree);
// We need to be sure that we've set info->srcCount and info->dstCount appropriately
assert((info->dstCount < 2) || (tree->IsMultiRegCall() && info->dstCount == MAX_RET_REG_COUNT));
}
void Lowering::SetDelayFree(GenTree* delayUseSrc)
{
// If delayUseSrc is an indirection and it doesn't produce a result, then we need to set "delayFree'
// on the base & index, if any.
// Otherwise, we set it on delayUseSrc itself.
if (delayUseSrc->isIndir() && (delayUseSrc->gtLsraInfo.dstCount == 0))
{
GenTree* base = delayUseSrc->AsIndir()->Base();
GenTree* index = delayUseSrc->AsIndir()->Index();
if (base != nullptr)
{
base->gtLsraInfo.isDelayFree = true;
}
if (index != nullptr)
{
index->gtLsraInfo.isDelayFree = true;
}
}
else
{
delayUseSrc->gtLsraInfo.isDelayFree = true;
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitCheckByteable: Check the tree to see if "byte-able" registers are
// required, and set the tree node info accordingly.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitCheckByteable(GenTree* tree)
{
#ifdef _TARGET_X86_
LinearScan* l = m_lsra;
TreeNodeInfo* info = &(tree->gtLsraInfo);
// Exclude RBM_NON_BYTE_REGS from dst candidates of tree node and src candidates of operands
// if the tree node is a byte type.
//
// Though this looks conservative in theory, in practice we could not think of a case where
// the below logic leads to conservative register specification. In future when or if we find
// one such case, this logic needs to be fine tuned for that case(s).
if (ExcludeNonByteableRegisters(tree))
{
regMaskTP regMask;
if (info->dstCount > 0)
{
regMask = info->getDstCandidates(l);
assert(regMask != RBM_NONE);
info->setDstCandidates(l, regMask & ~RBM_NON_BYTE_REGS);
}
if (tree->OperIsSimple() && (info->srcCount > 0))
{
// No need to set src candidates on a contained child operand.
GenTree* op = tree->gtOp.gtOp1;
assert(op != nullptr);
bool containedNode = (op->gtLsraInfo.srcCount == 0) && (op->gtLsraInfo.dstCount == 0);
if (!containedNode)
{
regMask = op->gtLsraInfo.getSrcCandidates(l);
assert(regMask != RBM_NONE);
op->gtLsraInfo.setSrcCandidates(l, regMask & ~RBM_NON_BYTE_REGS);
}
if (tree->OperIsBinary() && (tree->gtOp.gtOp2 != nullptr))
{
op = tree->gtOp.gtOp2;
containedNode = (op->gtLsraInfo.srcCount == 0) && (op->gtLsraInfo.dstCount == 0);
if (!containedNode)
{
regMask = op->gtLsraInfo.getSrcCandidates(l);
assert(regMask != RBM_NONE);
op->gtLsraInfo.setSrcCandidates(l, regMask & ~RBM_NON_BYTE_REGS);
}
}
}
}
#endif //_TARGET_X86_
}
//------------------------------------------------------------------------
// TreeNodeInfoInitSimple: Sets the srcCount and dstCount for all the trees
// without special handling based on the tree node type.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitSimple(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
unsigned kind = tree->OperKind();
info->dstCount = tree->IsValue() ? 1 : 0;
if (kind & (GTK_CONST | GTK_LEAF))
{
info->srcCount = 0;
}
else if (kind & (GTK_SMPOP))
{
if (tree->gtGetOp2IfPresent() != nullptr)
{
info->srcCount = 2;
}
else
{
info->srcCount = 1;
}
}
else
{
unreached();
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitReturn: Set the NodeInfo for a GT_RETURN.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitReturn(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* l = m_lsra;
Compiler* compiler = comp;
#if !defined(_TARGET_64BIT_)
if (tree->TypeGet() == TYP_LONG)
{
GenTree* op1 = tree->gtGetOp1();
noway_assert(op1->OperGet() == GT_LONG);
op1->SetContained();
GenTree* loVal = op1->gtGetOp1();
GenTree* hiVal = op1->gtGetOp2();
info->srcCount = 2;
loVal->gtLsraInfo.setSrcCandidates(l, RBM_LNGRET_LO);
hiVal->gtLsraInfo.setSrcCandidates(l, RBM_LNGRET_HI);
info->dstCount = 0;
}
else
#endif // !defined(_TARGET_64BIT_)
{
GenTree* op1 = tree->gtGetOp1();
regMaskTP useCandidates = RBM_NONE;
info->srcCount = (tree->TypeGet() == TYP_VOID) ? 0 : 1;
info->dstCount = 0;
#ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
if (varTypeIsStruct(tree))
{
// op1 has to be either an lclvar or a multi-reg returning call
if (op1->OperGet() == GT_LCL_VAR)
{
GenTreeLclVarCommon* lclVarCommon = op1->AsLclVarCommon();
LclVarDsc* varDsc = &(compiler->lvaTable[lclVarCommon->gtLclNum]);
assert(varDsc->lvIsMultiRegRet);
// Mark var as contained if not enregistrable.
if (!varTypeIsEnregisterableStruct(op1))
{
MakeSrcContained(tree, op1);
}
}
else
{
noway_assert(op1->IsMultiRegCall());
ReturnTypeDesc* retTypeDesc = op1->AsCall()->GetReturnTypeDesc();
info->srcCount = retTypeDesc->GetReturnRegCount();
useCandidates = retTypeDesc->GetABIReturnRegs();
}
}
else
#endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
{
// Non-struct type return - determine useCandidates
switch (tree->TypeGet())
{
case TYP_VOID:
useCandidates = RBM_NONE;
break;
case TYP_FLOAT:
useCandidates = RBM_FLOATRET;
break;
case TYP_DOUBLE:
useCandidates = RBM_DOUBLERET;
break;
#if defined(_TARGET_64BIT_)
case TYP_LONG:
useCandidates = RBM_LNGRET;
break;
#endif // defined(_TARGET_64BIT_)
default:
useCandidates = RBM_INTRET;
break;
}
}
if (useCandidates != RBM_NONE)
{
op1->gtLsraInfo.setSrcCandidates(l, useCandidates);
}
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitShiftRotate: Set the NodeInfo for a shift or rotate.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitShiftRotate(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* l = m_lsra;
info->srcCount = 2;
info->dstCount = 1;
// For shift operations, we need that the number
// of bits moved gets stored in CL in case
// the number of bits to shift is not a constant.
GenTreePtr shiftBy = tree->gtOp.gtOp2;
GenTreePtr source = tree->gtOp.gtOp1;
#ifdef _TARGET_X86_
// The first operand of a GT_LSH_HI and GT_RSH_LO oper is a GT_LONG so that
// we can have a three operand form. Increment the srcCount.
if (tree->OperGet() == GT_LSH_HI || tree->OperGet() == GT_RSH_LO)
{
assert(source->OperGet() == GT_LONG);
source->SetContained();
info->srcCount++;
if (tree->OperGet() == GT_LSH_HI)
{
GenTreePtr sourceLo = source->gtOp.gtOp1;
sourceLo->gtLsraInfo.isDelayFree = true;
}
else
{
GenTreePtr sourceHi = source->gtOp.gtOp2;
sourceHi->gtLsraInfo.isDelayFree = true;
}
source->gtLsraInfo.hasDelayFreeSrc = true;
info->hasDelayFreeSrc = true;
}
#endif
// x64 can encode 8 bits of shift and it will use 5 or 6. (the others are masked off)
// We will allow whatever can be encoded - hope you know what you are doing.
if (!IsContainableImmed(tree, shiftBy) || (shiftBy->gtIntConCommon.IconValue() > 255) ||
(shiftBy->gtIntConCommon.IconValue() < 0))
{
source->gtLsraInfo.setSrcCandidates(l, l->allRegs(TYP_INT) & ~RBM_RCX);
shiftBy->gtLsraInfo.setSrcCandidates(l, RBM_RCX);
info->setDstCandidates(l, l->allRegs(TYP_INT) & ~RBM_RCX);
}
else
{
MakeSrcContained(tree, shiftBy);
// Note that Rotate Left/Right instructions don't set ZF and SF flags.
//
// If the operand being shifted is 32-bits then upper three bits are masked
// by hardware to get actual shift count. Similarly for 64-bit operands
// shift count is narrowed to [0..63]. If the resulting shift count is zero,
// then shift operation won't modify flags.
//
// TODO-CQ-XARCH: We can optimize generating 'test' instruction for GT_EQ/NE(shift, 0)
// if the shift count is known to be non-zero and in the range depending on the
// operand size.
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitPutArgReg: Set the NodeInfo for a PUTARG_REG.
//
// Arguments:
// node - The PUTARG_REG node.
// argReg - The register in which to pass the argument.
// info - The info for the node's using call.
// isVarArgs - True if the call uses a varargs calling convention.
// callHasFloatRegArgs - Set to true if this PUTARG_REG uses an FP register.
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitPutArgReg(
GenTreeUnOp* node, regNumber argReg, TreeNodeInfo& info, bool isVarArgs, bool* callHasFloatRegArgs)
{
assert(node != nullptr);
assert(node->OperIsPutArgReg());
assert(argReg != REG_NA);
// Each register argument corresponds to one source.
info.srcCount++;
// Set the register requirements for the node.
const regMaskTP argMask = genRegMask(argReg);
node->gtLsraInfo.setDstCandidates(m_lsra, argMask);
node->gtLsraInfo.setSrcCandidates(m_lsra, argMask);
// To avoid redundant moves, have the argument operand computed in the
// register in which the argument is passed to the call.
node->gtOp.gtOp1->gtLsraInfo.setSrcCandidates(m_lsra, m_lsra->getUseCandidates(node));
#if FEATURE_VARARG
*callHasFloatRegArgs |= varTypeIsFloating(node->TypeGet());
// In the case of a varargs call, the ABI dictates that if we have floating point args,
// we must pass the enregistered arguments in both the integer and floating point registers.
// Since the integer register is not associated with this arg node, we will reserve it as
// an internal register so that it is not used during the evaluation of the call node
// (e.g. for the target).
if (isVarArgs && varTypeIsFloating(node))
{
regNumber targetReg = comp->getCallArgIntRegister(argReg);
info.setInternalIntCount(info.internalIntCount + 1);
info.addInternalCandidates(m_lsra, genRegMask(targetReg));
}
#endif // FEATURE_VARARG
}
//------------------------------------------------------------------------
// TreeNodeInfoInitCall: Set the NodeInfo for a call.
//
// Arguments:
// call - The call node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitCall(GenTreeCall* call)
{
TreeNodeInfo* info = &(call->gtLsraInfo);
LinearScan* l = m_lsra;
Compiler* compiler = comp;
bool hasMultiRegRetVal = false;
ReturnTypeDesc* retTypeDesc = nullptr;
info->srcCount = 0;
if (call->TypeGet() != TYP_VOID)
{
hasMultiRegRetVal = call->HasMultiRegRetVal();
if (hasMultiRegRetVal)
{
// dst count = number of registers in which the value is returned by call
retTypeDesc = call->GetReturnTypeDesc();
info->dstCount = retTypeDesc->GetReturnRegCount();
}
else
{
info->dstCount = 1;
}
}
else
{
info->dstCount = 0;
}
GenTree* ctrlExpr = call->gtControlExpr;
if (call->gtCallType == CT_INDIRECT)
{
// either gtControlExpr != null or gtCallAddr != null.
// Both cannot be non-null at the same time.
assert(ctrlExpr == nullptr);
assert(call->gtCallAddr != nullptr);
ctrlExpr = call->gtCallAddr;
#ifdef _TARGET_X86_
// Fast tail calls aren't currently supported on x86, but if they ever are, the code
// below that handles indirect VSD calls will need to be fixed.
assert(!call->IsFastTailCall() || !call->IsVirtualStub());
#endif // _TARGET_X86_
}
// set reg requirements on call target represented as control sequence.
if (ctrlExpr != nullptr)
{
// we should never see a gtControlExpr whose type is void.
assert(ctrlExpr->TypeGet() != TYP_VOID);
// call can take a Rm op on x64
info->srcCount++;
// In case of fast tail implemented as jmp, make sure that gtControlExpr is
// computed into a register.
if (!call->IsFastTailCall())
{
#ifdef _TARGET_X86_
// On x86, we need to generate a very specific pattern for indirect VSD calls:
//
// 3-byte nop
// call dword ptr [eax]
//
// Where EAX is also used as an argument to the stub dispatch helper. Make
// sure that the call target address is computed into EAX in this case.
if (call->IsVirtualStub() && (call->gtCallType == CT_INDIRECT))
{
assert(ctrlExpr->isIndir());
ctrlExpr->gtGetOp1()->gtLsraInfo.setSrcCandidates(l, RBM_VIRTUAL_STUB_TARGET);
MakeSrcContained(call, ctrlExpr);
}
else
#endif // _TARGET_X86_
if (ctrlExpr->isIndir())
{
MakeSrcContained(call, ctrlExpr);
}
}
else
{
// Fast tail call - make sure that call target is always computed in RAX
// so that epilog sequence can generate "jmp rax" to achieve fast tail call.
ctrlExpr->gtLsraInfo.setSrcCandidates(l, RBM_RAX);
}
}
// If this is a varargs call, we will clear the internal candidates in case we need
// to reserve some integer registers for copying float args.
// We have to do this because otherwise the default candidates are allRegs, and adding
// the individual specific registers will have no effect.
if (call->IsVarargs())
{
info->setInternalCandidates(l, RBM_NONE);
}
RegisterType registerType = call->TypeGet();
// Set destination candidates for return value of the call.
CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef _TARGET_X86_
if (call->IsHelperCall(compiler, CORINFO_HELP_INIT_PINVOKE_FRAME))
{
// The x86 CORINFO_HELP_INIT_PINVOKE_FRAME helper uses a custom calling convention that returns with
// TCB in REG_PINVOKE_TCB. AMD64/ARM64 use the standard calling convention. fgMorphCall() sets the
// correct argument registers.
info->setDstCandidates(l, RBM_PINVOKE_TCB);
}
else
#endif // _TARGET_X86_
if (hasMultiRegRetVal)
{
assert(retTypeDesc != nullptr);
info->setDstCandidates(l, retTypeDesc->GetABIReturnRegs());
}
else if (varTypeIsFloating(registerType))
{
#ifdef _TARGET_X86_
// The return value will be on the X87 stack, and we will need to move it.
info->setDstCandidates(l, l->allRegs(registerType));
#else // !_TARGET_X86_
info->setDstCandidates(l, RBM_FLOATRET);
#endif // !_TARGET_X86_
}
else if (registerType == TYP_LONG)
{
info->setDstCandidates(l, RBM_LNGRET);
}
else
{
info->setDstCandidates(l, RBM_INTRET);
}
// number of args to a call =
// callRegArgs + (callargs - placeholders, setup, etc)
// there is an explicit thisPtr but it is redundant
// If there is an explicit this pointer, we don't want that node to produce anything
// as it is redundant
if (call->gtCallObjp != nullptr)
{
GenTreePtr thisPtrNode = call->gtCallObjp;
if (thisPtrNode->gtOper == GT_PUTARG_REG)
{
l->clearOperandCounts(thisPtrNode);
thisPtrNode->SetContained();
l->clearDstCount(thisPtrNode->gtOp.gtOp1);
}
else
{
l->clearDstCount(thisPtrNode);
}
}
bool callHasFloatRegArgs = false;
bool isVarArgs = call->IsVarargs();
// First, count reg args
for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext())
{
assert(list->OperIsList());
// By this point, lowering has ensured that all call arguments are one of the following:
// - an arg setup store
// - an arg placeholder
// - a nop
// - a copy blk
// - a field list
// - a put arg
//
// Note that this property is statically checked by Lowering::CheckBlock.
GenTreePtr argNode = list->Current();
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(call, argNode);
assert(curArgTabEntry);
if (curArgTabEntry->regNum == REG_STK)
{
// late arg that is not passed in a register
DISPNODE(argNode);
assert(argNode->gtOper == GT_PUTARG_STK);
argNode->gtLsraInfo.srcCount = 1;
argNode->gtLsraInfo.dstCount = 0;
#ifdef FEATURE_PUT_STRUCT_ARG_STK
// If the node is TYP_STRUCT and it is put on stack with
// putarg_stk operation, we consume and produce no registers.
// In this case the embedded Obj node should not produce
// registers too since it is contained.
// Note that if it is a SIMD type the argument will be in a register.
if (argNode->TypeGet() == TYP_STRUCT)
{
assert(argNode->gtOp.gtOp1 != nullptr && argNode->gtOp.gtOp1->OperGet() == GT_OBJ);
argNode->gtOp.gtOp1->gtLsraInfo.dstCount = 0;
argNode->gtLsraInfo.srcCount = 0;
}
#endif // FEATURE_PUT_STRUCT_ARG_STK
continue;
}
#ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
if (argNode->OperGet() == GT_FIELD_LIST)
{
argNode->SetContained();
assert(varTypeIsStruct(argNode) || curArgTabEntry->isStruct);
unsigned eightbyte = 0;
for (GenTreeFieldList* entry = argNode->AsFieldList(); entry != nullptr; entry = entry->Rest())
{
const regNumber argReg = eightbyte == 0 ? curArgTabEntry->regNum : curArgTabEntry->otherRegNum;
TreeNodeInfoInitPutArgReg(entry->Current()->AsUnOp(), argReg, *info, isVarArgs, &callHasFloatRegArgs);
eightbyte++;
}
}
else
#endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
{
TreeNodeInfoInitPutArgReg(argNode->AsUnOp(), curArgTabEntry->regNum, *info, isVarArgs,
&callHasFloatRegArgs);
}
}
// Now, count stack args
// Note that these need to be computed into a register, but then
// they're just stored to the stack - so the reg doesn't
// need to remain live until the call. In fact, it must not
// because the code generator doesn't actually consider it live,
// so it can't be spilled.
GenTreePtr args = call->gtCallArgs;
while (args)
{
GenTreePtr arg = args->gtOp.gtOp1;
if (!(args->gtFlags & GTF_LATE_ARG))
{
TreeNodeInfo* argInfo = &(arg->gtLsraInfo);
if (argInfo->dstCount != 0)
{
argInfo->isLocalDefUse = true;
}
// If the child of GT_PUTARG_STK is a constant, we don't need a register to
// move it to memory (stack location).
//
// On AMD64, we don't want to make 0 contained, because we can generate smaller code
// by zeroing a register and then storing it. E.g.:
// xor rdx, rdx
// mov gword ptr [rsp+28H], rdx
// is 2 bytes smaller than:
// mov gword ptr [rsp+28H], 0
//
// On x86, we push stack arguments; we don't use 'mov'. So:
// push 0
// is 1 byte smaller than:
// xor rdx, rdx
// push rdx
argInfo->dstCount = 0;
if (arg->gtOper == GT_PUTARG_STK)
{
GenTree* op1 = arg->gtOp.gtOp1;
if (IsContainableImmed(arg, op1)
#if defined(_TARGET_AMD64_)
&& !op1->IsIntegralConst(0)
#endif // _TARGET_AMD64_
)
{
MakeSrcContained(arg, op1);
}
}
}
args = args->gtOp.gtOp2;
}
#if FEATURE_VARARG
// If it is a fast tail call, it is already preferenced to use RAX.
// Therefore, no need set src candidates on call tgt again.
if (call->IsVarargs() && callHasFloatRegArgs && !call->IsFastTailCall() && (ctrlExpr != nullptr))
{
// Don't assign the call target to any of the argument registers because
// we will use them to also pass floating point arguments as required
// by Amd64 ABI.
ctrlExpr->gtLsraInfo.setSrcCandidates(l, l->allRegs(TYP_INT) & ~(RBM_ARG_REGS));
}
#endif // !FEATURE_VARARG
}
//------------------------------------------------------------------------
// TreeNodeInfoInitBlockStore: Set the NodeInfo for a block store.
//
// Arguments:
// blkNode - The block store node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitBlockStore(GenTreeBlk* blkNode)
{
GenTree* dstAddr = blkNode->Addr();
unsigned size = blkNode->gtBlkSize;
GenTree* source = blkNode->Data();
LinearScan* l = m_lsra;
Compiler* compiler = comp;
// Sources are dest address, initVal or source.
// We may require an additional source or temp register for the size.
blkNode->gtLsraInfo.srcCount = 2;
blkNode->gtLsraInfo.dstCount = 0;
blkNode->gtLsraInfo.setInternalCandidates(l, RBM_NONE);
GenTreePtr srcAddrOrFill = nullptr;
bool isInitBlk = blkNode->OperIsInitBlkOp();
regMaskTP dstAddrRegMask = RBM_NONE;
regMaskTP sourceRegMask = RBM_NONE;
regMaskTP blkSizeRegMask = RBM_NONE;
if (isInitBlk)
{
GenTree* initVal = source;
if (initVal->OperIsInitVal())
{
initVal->SetContained();
initVal = initVal->gtGetOp1();
}
srcAddrOrFill = initVal;
switch (blkNode->gtBlkOpKind)
{
case GenTreeBlk::BlkOpKindUnroll:
assert(initVal->IsCnsIntOrI());
if (size >= XMM_REGSIZE_BYTES)
{
// Reserve an XMM register to fill it with
// a pack of 16 init value constants.
ssize_t fill = initVal->gtIntCon.gtIconVal & 0xFF;
blkNode->gtLsraInfo.internalFloatCount = 1;
blkNode->gtLsraInfo.setInternalCandidates(l, l->internalFloatRegCandidates());
if ((fill == 0) && ((size & 0xf) == 0))
{
MakeSrcContained(blkNode, source);
}
// use XMM register to fill with constants, it's AVX instruction and set the flag
SetContainsAVXFlags();
}
#ifdef _TARGET_X86_
if ((size & 1) != 0)
{
// On x86, you can't address the lower byte of ESI, EDI, ESP, or EBP when doing
// a "mov byte ptr [dest], val". If the fill size is odd, we will try to do this
// when unrolling, so only allow byteable registers as the source value. (We could
// consider just using BlkOpKindRepInstr instead.)
sourceRegMask = RBM_BYTE_REGS;
}
#endif // _TARGET_X86_
break;
case GenTreeBlk::BlkOpKindRepInstr:
// rep stos has the following register requirements:
// a) The memory address to be in RDI.
// b) The fill value has to be in RAX.
// c) The buffer size will go in RCX.
dstAddrRegMask = RBM_RDI;
srcAddrOrFill = initVal;
sourceRegMask = RBM_RAX;
blkSizeRegMask = RBM_RCX;
break;
case GenTreeBlk::BlkOpKindHelper:
#ifdef _TARGET_AMD64_
// The helper follows the regular AMD64 ABI.
dstAddrRegMask = RBM_ARG_0;
sourceRegMask = RBM_ARG_1;
blkSizeRegMask = RBM_ARG_2;
#else // !_TARGET_AMD64_
dstAddrRegMask = RBM_RDI;
sourceRegMask = RBM_RAX;
blkSizeRegMask = RBM_RCX;
#endif // !_TARGET_AMD64_
break;
default:
unreached();
}
}
else
{
// CopyObj or CopyBlk
if (source->gtOper == GT_IND)
{
srcAddrOrFill = blkNode->Data()->gtGetOp1();
// We're effectively setting source as contained, but can't call MakeSrcContained, because the
// "inheritance" of the srcCount is to a child not a parent - it would "just work" but could be misleading.
// If srcAddr is already non-contained, we don't need to change it.
if (srcAddrOrFill->gtLsraInfo.getDstCount() == 0)
{
srcAddrOrFill->gtLsraInfo.setDstCount(1);
srcAddrOrFill->gtLsraInfo.setSrcCount(source->gtLsraInfo.srcCount);
}
m_lsra->clearOperandCounts(source);
source->SetContained();
source->AsIndir()->Addr()->ClearContained();
}
else if (!source->IsMultiRegCall() && !source->OperIsSIMD())
{
assert(source->IsLocal());
MakeSrcContained(blkNode, source);
}
if (blkNode->OperGet() == GT_STORE_OBJ)
{
if (blkNode->gtBlkOpKind == GenTreeBlk::BlkOpKindRepInstr)
{
// We need the size of the contiguous Non-GC-region to be in RCX to call rep movsq.
blkSizeRegMask = RBM_RCX;
}
// The srcAddr must be in a register. If it was under a GT_IND, we need to subsume all of its
// sources.
sourceRegMask = RBM_RSI;
dstAddrRegMask = RBM_RDI;
}
else
{
switch (blkNode->gtBlkOpKind)
{
case GenTreeBlk::BlkOpKindUnroll:
// If we have a remainder smaller than XMM_REGSIZE_BYTES, we need an integer temp reg.
//
// x86 specific note: if the size is odd, the last copy operation would be of size 1 byte.
// But on x86 only RBM_BYTE_REGS could be used as byte registers. Therefore, exclude
// RBM_NON_BYTE_REGS from internal candidates.
if ((size & (XMM_REGSIZE_BYTES - 1)) != 0)
{
blkNode->gtLsraInfo.internalIntCount++;
regMaskTP regMask = l->allRegs(TYP_INT);
#ifdef _TARGET_X86_
if ((size & 1) != 0)
{
regMask &= ~RBM_NON_BYTE_REGS;
}
#endif
blkNode->gtLsraInfo.setInternalCandidates(l, regMask);
}
if (size >= XMM_REGSIZE_BYTES)
{
// If we have a buffer larger than XMM_REGSIZE_BYTES,
// reserve an XMM register to use it for a
// series of 16-byte loads and stores.
blkNode->gtLsraInfo.internalFloatCount = 1;
blkNode->gtLsraInfo.addInternalCandidates(l, l->internalFloatRegCandidates());
// Uses XMM reg for load and store and hence check to see whether AVX instructions
// are used for codegen, set ContainsAVX flag
SetContainsAVXFlags();
}
// If src or dst are on stack, we don't have to generate the address
// into a register because it's just some constant+SP.
if ((srcAddrOrFill != nullptr) && srcAddrOrFill->OperIsLocalAddr())
{
MakeSrcContained(blkNode, srcAddrOrFill);
}
if (dstAddr->OperIsLocalAddr())
{
MakeSrcContained(blkNode, dstAddr);
}
break;
case GenTreeBlk::BlkOpKindRepInstr:
// rep stos has the following register requirements:
// a) The dest address has to be in RDI.
// b) The src address has to be in RSI.
// c) The buffer size will go in RCX.
dstAddrRegMask = RBM_RDI;
sourceRegMask = RBM_RSI;
blkSizeRegMask = RBM_RCX;
break;
case GenTreeBlk::BlkOpKindHelper:
#ifdef _TARGET_AMD64_
// The helper follows the regular AMD64 ABI.
dstAddrRegMask = RBM_ARG_0;
sourceRegMask = RBM_ARG_1;
blkSizeRegMask = RBM_ARG_2;
#else // !_TARGET_AMD64_
dstAddrRegMask = RBM_RDI;
sourceRegMask = RBM_RAX;
blkSizeRegMask = RBM_RCX;
#endif // !_TARGET_AMD64_
break;
default:
unreached();
}
}
}
if (dstAddrRegMask != RBM_NONE)
{
dstAddr->gtLsraInfo.setSrcCandidates(l, dstAddrRegMask);
}
if (sourceRegMask != RBM_NONE)
{
if (srcAddrOrFill != nullptr)
{
srcAddrOrFill->gtLsraInfo.setSrcCandidates(l, sourceRegMask);
}
else
{
// This is a local source; we'll use a temp register for its address.
blkNode->gtLsraInfo.addInternalCandidates(l, sourceRegMask);
blkNode->gtLsraInfo.internalIntCount++;
}
}
if (blkSizeRegMask != RBM_NONE)
{
if (size != 0)
{
// Reserve a temp register for the block size argument.
blkNode->gtLsraInfo.addInternalCandidates(l, blkSizeRegMask);
blkNode->gtLsraInfo.internalIntCount++;
}
else
{
// The block size argument is a third argument to GT_STORE_DYN_BLK
noway_assert(blkNode->gtOper == GT_STORE_DYN_BLK);
blkNode->gtLsraInfo.setSrcCount(3);
GenTree* blockSize = blkNode->AsDynBlk()->gtDynamicSize;
blockSize->gtLsraInfo.setSrcCandidates(l, blkSizeRegMask);
}
}
}
#ifdef FEATURE_PUT_STRUCT_ARG_STK
//------------------------------------------------------------------------
// TreeNodeInfoInitPutArgStk: Set the NodeInfo for a GT_PUTARG_STK.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitPutArgStk(GenTreePutArgStk* putArgStk)
{
TreeNodeInfo* info = &(putArgStk->gtLsraInfo);
LinearScan* l = m_lsra;
info->srcCount = 0;
#ifdef _TARGET_X86_
if (putArgStk->gtOp1->gtOper == GT_FIELD_LIST)
{
unsigned fieldCount = 0;
bool needsByteTemp = false;
bool needsSimdTemp = false;
unsigned prevOffset = putArgStk->getArgSize();
for (GenTreeFieldList* current = putArgStk->gtOp1->AsFieldList(); current != nullptr; current = current->Rest())
{
GenTree* const fieldNode = current->Current();
const var_types fieldType = fieldNode->TypeGet();
const unsigned fieldOffset = current->gtFieldOffset;
assert(fieldType != TYP_LONG);
info->srcCount++;
// For x86 we must mark all integral fields as contained or reg-optional, and handle them
// accordingly in code generation, since we may have up to 8 fields, which cannot all be in
// registers to be consumed atomically by the call.
if (varTypeIsIntegralOrI(fieldNode))
{
if (fieldNode->OperGet() == GT_LCL_VAR)
{
LclVarDsc* varDsc = &(comp->lvaTable[fieldNode->AsLclVarCommon()->gtLclNum]);
if (varDsc->lvTracked && !varDsc->lvDoNotEnregister)
{
SetRegOptional(fieldNode);
}
else
{
MakeSrcContained(putArgStk, fieldNode);
}
}
else if (fieldNode->IsIntCnsFitsInI32())
{
MakeSrcContained(putArgStk, fieldNode);
}
else
{
// For the case where we cannot directly push the value, if we run out of registers,
// it would be better to defer computation until we are pushing the arguments rather
// than spilling, but this situation is not all that common, as most cases of promoted
// structs do not have a large number of fields, and of those most are lclVars or
// copy-propagated constants.
SetRegOptional(fieldNode);
}
}
#if defined(FEATURE_SIMD)
// Note that we need to check the GT_FIELD_LIST type, not the fieldType. This is because the
// GT_FIELD_LIST will be TYP_SIMD12 whereas the fieldType might be TYP_SIMD16 for lclVar, where
// we "round up" to 16.
else if (current->gtFieldType == TYP_SIMD12)
{
needsSimdTemp = true;
}
#endif // defined(FEATURE_SIMD)
else
{
assert(varTypeIsFloating(fieldNode) || varTypeIsSIMD(fieldNode));
}
// We can treat as a slot any field that is stored at a slot boundary, where the previous
// field is not in the same slot. (Note that we store the fields in reverse order.)
const bool fieldIsSlot = ((fieldOffset % 4) == 0) && ((prevOffset - fieldOffset) >= 4);
if (!fieldIsSlot)
{
if (varTypeIsByte(fieldType))
{
// If this field is a slot--i.e. it is an integer field that is 4-byte aligned and takes up 4 bytes
// (including padding)--we can store the whole value rather than just the byte. Otherwise, we will
// need a byte-addressable register for the store. We will enforce this requirement on an internal
// register, which we can use to copy multiple byte values.
needsByteTemp = true;
}
}
if (varTypeIsGC(fieldType))
{
putArgStk->gtNumberReferenceSlots++;
}
prevOffset = fieldOffset;
fieldCount++;
}
info->dstCount = 0;
if (putArgStk->gtPutArgStkKind == GenTreePutArgStk::Kind::Push)
{
// If any of the fields cannot be stored with an actual push, we may need a temporary
// register to load the value before storing it to the stack location.
info->internalIntCount = 1;
regMaskTP regMask = l->allRegs(TYP_INT);
if (needsByteTemp)
{
regMask &= ~RBM_NON_BYTE_REGS;
}
info->setInternalCandidates(l, regMask);
}
#if defined(FEATURE_SIMD)
// For PutArgStk of a TYP_SIMD12, we need a SIMD temp register.
if (needsSimdTemp)
{
info->internalFloatCount += 1;
info->addInternalCandidates(l, l->allSIMDRegs());
}
#endif // defined(FEATURE_SIMD)
return;
}
#endif // _TARGET_X86_
#if defined(FEATURE_SIMD) && defined(_TARGET_X86_)
// For PutArgStk of a TYP_SIMD12, we need an extra register.
if (putArgStk->TypeGet() == TYP_SIMD12)
{
info->srcCount = putArgStk->gtOp1->gtLsraInfo.dstCount;
info->dstCount = 0;
info->internalFloatCount = 1;
info->setInternalCandidates(l, l->allSIMDRegs());
return;
}
#endif // defined(FEATURE_SIMD) && defined(_TARGET_X86_)
if (putArgStk->TypeGet() != TYP_STRUCT)
{
TreeNodeInfoInitSimple(putArgStk);
return;
}
GenTreePtr dst = putArgStk;
GenTreePtr src = putArgStk->gtOp1;
GenTreePtr srcAddr = nullptr;
bool haveLocalAddr = false;
if ((src->OperGet() == GT_OBJ) || (src->OperGet() == GT_IND))
{
srcAddr = src->gtOp.gtOp1;
assert(srcAddr != nullptr);
haveLocalAddr = srcAddr->OperIsLocalAddr();
}
else
{
assert(varTypeIsSIMD(putArgStk));
}
info->srcCount = src->gtLsraInfo.dstCount;
info->dstCount = 0;
// If we have a buffer between XMM_REGSIZE_BYTES and CPBLK_UNROLL_LIMIT bytes, we'll use SSE2.
// Structs and buffer with sizes <= CPBLK_UNROLL_LIMIT bytes are occurring in more than 95% of
// our framework assemblies, so this is the main code generation scheme we'll use.
ssize_t size = putArgStk->gtNumSlots * TARGET_POINTER_SIZE;
switch (putArgStk->gtPutArgStkKind)
{
case GenTreePutArgStk::Kind::Push:
case GenTreePutArgStk::Kind::PushAllSlots:
case GenTreePutArgStk::Kind::Unroll:
// If we have a remainder smaller than XMM_REGSIZE_BYTES, we need an integer temp reg.
//
// x86 specific note: if the size is odd, the last copy operation would be of size 1 byte.
// But on x86 only RBM_BYTE_REGS could be used as byte registers. Therefore, exclude
// RBM_NON_BYTE_REGS from internal candidates.
if ((putArgStk->gtNumberReferenceSlots == 0) && (size & (XMM_REGSIZE_BYTES - 1)) != 0)
{
info->internalIntCount++;
regMaskTP regMask = l->allRegs(TYP_INT);
#ifdef _TARGET_X86_
if ((size % 2) != 0)
{
regMask &= ~RBM_NON_BYTE_REGS;
}
#endif
info->setInternalCandidates(l, regMask);
}
#ifdef _TARGET_X86_
if (size >= 8)
#else // !_TARGET_X86_
if (size >= XMM_REGSIZE_BYTES)
#endif // !_TARGET_X86_
{
// If we have a buffer larger than or equal to XMM_REGSIZE_BYTES on x64/ux,
// or larger than or equal to 8 bytes on x86, reserve an XMM register to use it for a
// series of 16-byte loads and stores.
info->internalFloatCount = 1;
info->addInternalCandidates(l, l->internalFloatRegCandidates());
SetContainsAVXFlags();
}
break;
case GenTreePutArgStk::Kind::RepInstr:
info->internalIntCount += 3;
info->setInternalCandidates(l, (RBM_RDI | RBM_RCX | RBM_RSI));
break;
default:
unreached();
}
// Always mark the OBJ and ADDR as contained trees by the putarg_stk. The codegen will deal with this tree.
MakeSrcContained(putArgStk, src);
if (haveLocalAddr)
{
// If the source address is the address of a lclVar, make the source address contained to avoid unnecessary
// copies.
//
// To avoid an assertion in MakeSrcContained, increment the parent's source count beforehand and decrement it
// afterwards.
info->srcCount++;
MakeSrcContained(putArgStk, srcAddr);
info->srcCount--;
}
}
#endif // FEATURE_PUT_STRUCT_ARG_STK
//------------------------------------------------------------------------
// TreeNodeInfoInitLclHeap: Set the NodeInfo for a GT_LCLHEAP.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitLclHeap(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* l = m_lsra;
Compiler* compiler = comp;
info->srcCount = 1;
info->dstCount = 1;
// Need a variable number of temp regs (see genLclHeap() in codegenamd64.cpp):
// Here '-' means don't care.
//
// Size? Init Memory? # temp regs
// 0 - 0 (returns 0)
// const and <=6 reg words - 0 (pushes '0')
// const and >6 reg words Yes 0 (pushes '0')
// const and <PageSize No 0 (amd64) 1 (x86)
// (x86:tmpReg for sutracting from esp)
// const and >=PageSize No 2 (regCnt and tmpReg for subtracing from sp)
// Non-const Yes 0 (regCnt=targetReg and pushes '0')
// Non-const No 2 (regCnt and tmpReg for subtracting from sp)
//
// Note: Here we don't need internal register to be different from targetReg.
// Rather, require it to be different from operand's reg.
GenTreePtr size = tree->gtOp.gtOp1;
if (size->IsCnsIntOrI())
{
MakeSrcContained(tree, size);
size_t sizeVal = size->gtIntCon.gtIconVal;
if (sizeVal == 0)
{
info->internalIntCount = 0;
}
else
{
// Compute the amount of memory to properly STACK_ALIGN.
// Note: The Gentree node is not updated here as it is cheap to recompute stack aligned size.
// This should also help in debugging as we can examine the original size specified with localloc.
sizeVal = AlignUp(sizeVal, STACK_ALIGN);
// For small allocations up to 6 pointer sized words (i.e. 48 bytes of localloc)
// we will generate 'push 0'.
assert((sizeVal % REGSIZE_BYTES) == 0);
size_t cntRegSizedWords = sizeVal / REGSIZE_BYTES;
if (cntRegSizedWords <= 6)
{
info->internalIntCount = 0;
}
else if (!compiler->info.compInitMem)
{
// No need to initialize allocated stack space.
if (sizeVal < compiler->eeGetPageSize())
{
#ifdef _TARGET_X86_
info->internalIntCount = 1; // x86 needs a register here to avoid generating "sub" on ESP.
#else // !_TARGET_X86_
info->internalIntCount = 0;
#endif // !_TARGET_X86_
}
else
{
// We need two registers: regCnt and RegTmp
info->internalIntCount = 2;
}
}
else
{
// >6 and need to zero initialize allocated stack space.
info->internalIntCount = 0;
}
}
}
else
{
if (!compiler->info.compInitMem)
{
info->internalIntCount = 2;
}
else
{
info->internalIntCount = 0;
}
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitLogicalOp: Set the NodeInfo for GT_AND/GT_OR/GT_XOR,
// as well as GT_ADD/GT_SUB.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitLogicalOp(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
// We're not marking a constant hanging on the left of the add
// as containable so we assign it to a register having CQ impact.
// TODO-XArch-CQ: Detect this case and support both generating a single instruction
// for GT_ADD(Constant, SomeTree)
info->srcCount = 2;
info->dstCount = 1;
GenTree* op1 = tree->gtGetOp1();
GenTree* op2 = tree->gtGetOp2();
// We can directly encode the second operand if it is either a containable constant or a memory-op.
// In case of memory-op, we can encode it directly provided its type matches with 'tree' type.
// This is because during codegen, type of 'tree' is used to determine emit Type size. If the types
// do not match, they get normalized (i.e. sign/zero extended) on load into a register.
bool directlyEncodable = false;
bool binOpInRMW = false;
GenTreePtr operand = nullptr;
if (IsContainableImmed(tree, op2))
{
directlyEncodable = true;
operand = op2;
}
else
{
binOpInRMW = IsBinOpInRMWStoreInd(tree);
if (!binOpInRMW)
{
const unsigned operatorSize = genTypeSize(tree->TypeGet());
if (IsContainableMemoryOp(op2, true) && (genTypeSize(op2->TypeGet()) == operatorSize))
{
directlyEncodable = true;
operand = op2;
}
else if (tree->OperIsCommutative())
{
if (IsContainableImmed(tree, op1) ||
(IsContainableMemoryOp(op1, true) && (genTypeSize(op1->TypeGet()) == operatorSize) &&
IsSafeToContainMem(tree, op1)))
{
// If it is safe, we can reverse the order of operands of commutative operations for efficient
// codegen
directlyEncodable = true;
operand = op1;
}
}
}
}
if (directlyEncodable)
{
assert(operand != nullptr);
MakeSrcContained(tree, operand);
}
else if (!binOpInRMW)
{
// If this binary op neither has contained operands, nor is a
// Read-Modify-Write (RMW) operation, we can mark its operands
// as reg optional.
SetRegOptionalForBinOp(tree);
}
// Codegen of this tree node sets ZF and SF flags.
tree->gtFlags |= GTF_ZSF_SET;
}
//------------------------------------------------------------------------
// TreeNodeInfoInitModDiv: Set the NodeInfo for GT_MOD/GT_DIV/GT_UMOD/GT_UDIV.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitModDiv(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* l = m_lsra;
GenTree* op1 = tree->gtGetOp1();
GenTree* op2 = tree->gtGetOp2();
info->srcCount = 2;
info->dstCount = 1;
switch (tree->OperGet())
{
case GT_MOD:
case GT_DIV:
if (varTypeIsFloating(tree->TypeGet()))
{
// No implicit conversions at this stage as the expectation is that
// everything is made explicit by adding casts.
assert(op1->TypeGet() == op2->TypeGet());
if (IsContainableMemoryOp(op2, true) || op2->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, op2);
}
else
{
// If there are no containable operands, we can make an operand reg optional.
// SSE2 allows only op2 to be a memory-op.
SetRegOptional(op2);
}
return;
}
break;
default:
break;
}
// Amd64 Div/Idiv instruction:
// Dividend in RAX:RDX and computes
// Quotient in RAX, Remainder in RDX
if (tree->OperGet() == GT_MOD || tree->OperGet() == GT_UMOD)
{
// We are interested in just the remainder.
// RAX is used as a trashable register during computation of remainder.
info->setDstCandidates(l, RBM_RDX);
}
else
{
// We are interested in just the quotient.
// RDX gets used as trashable register during computation of quotient
info->setDstCandidates(l, RBM_RAX);
}
bool op2CanBeRegOptional = true;
#ifdef _TARGET_X86_
if (op1->OperGet() == GT_LONG)
{
op1->SetContained();
// To avoid reg move would like to have op1's low part in RAX and high part in RDX.
GenTree* loVal = op1->gtGetOp1();
GenTree* hiVal = op1->gtGetOp2();
// Src count is actually 3, so increment.
assert(op2->IsCnsIntOrI());
assert(tree->OperGet() == GT_UMOD);
info->srcCount++;
op2CanBeRegOptional = false;
// This situation also requires an internal register.
info->internalIntCount = 1;
info->setInternalCandidates(l, l->allRegs(TYP_INT));
loVal->gtLsraInfo.setSrcCandidates(l, RBM_EAX);
hiVal->gtLsraInfo.setSrcCandidates(l, RBM_EDX);
}
else
#endif
{
// If possible would like to have op1 in RAX to avoid a register move
op1->gtLsraInfo.setSrcCandidates(l, RBM_RAX);
}
// divisor can be an r/m, but the memory indirection must be of the same size as the divide
if (IsContainableMemoryOp(op2, true) && (op2->TypeGet() == tree->TypeGet()))
{
MakeSrcContained(tree, op2);
}
else if (op2CanBeRegOptional)
{
op2->gtLsraInfo.setSrcCandidates(l, l->allRegs(TYP_INT) & ~(RBM_RAX | RBM_RDX));
// If there are no containable operands, we can make an operand reg optional.
// Div instruction allows only op2 to be a memory op.
SetRegOptional(op2);
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitIntrinsic: Set the NodeInfo for a GT_INTRINSIC.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitIntrinsic(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* l = m_lsra;
// Both operand and its result must be of floating point type.
GenTree* op1 = tree->gtGetOp1();
assert(varTypeIsFloating(op1));
assert(op1->TypeGet() == tree->TypeGet());
info->srcCount = 1;
info->dstCount = 1;
switch (tree->gtIntrinsic.gtIntrinsicId)
{
case CORINFO_INTRINSIC_Sqrt:
if (IsContainableMemoryOp(op1, true) || op1->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, op1);
}
else
{
// Mark the operand as reg optional since codegen can still
// generate code if op1 is on stack.
SetRegOptional(op1);
}
break;
case CORINFO_INTRINSIC_Abs:
// Abs(float x) = x & 0x7fffffff
// Abs(double x) = x & 0x7ffffff ffffffff
// In case of Abs we need an internal register to hold mask.
// TODO-XArch-CQ: avoid using an internal register for the mask.
// Andps or andpd both will operate on 128-bit operands.
// The data section constant to hold the mask is a 64-bit size.
// Therefore, we need both the operand and mask to be in
// xmm register. When we add support in emitter to emit 128-bit
// data constants and instructions that operate on 128-bit
// memory operands we can avoid the need for an internal register.
if (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Abs)
{
info->internalFloatCount = 1;
info->setInternalCandidates(l, l->internalFloatRegCandidates());
}
break;
#ifdef _TARGET_X86_
case CORINFO_INTRINSIC_Cos:
case CORINFO_INTRINSIC_Sin:
case CORINFO_INTRINSIC_Round:
NYI_X86("Math intrinsics Cos, Sin and Round");
break;
#endif // _TARGET_X86_
default:
// Right now only Sqrt/Abs are treated as math intrinsics
noway_assert(!"Unsupported math intrinsic");
unreached();
break;
}
}
#ifdef FEATURE_SIMD
//------------------------------------------------------------------------
// TreeNodeInfoInitSIMD: Set the NodeInfo for a GT_SIMD tree.
//
// Arguments:
// tree - The GT_SIMD node of interest
//
// Return Value:
// None.
void Lowering::TreeNodeInfoInitSIMD(GenTree* tree)
{
GenTreeSIMD* simdTree = tree->AsSIMD();
TreeNodeInfo* info = &(tree->gtLsraInfo);
LinearScan* lsra = m_lsra;
info->dstCount = 1;
SetContainsAVXFlags(true, simdTree->gtSIMDSize);
switch (simdTree->gtSIMDIntrinsicID)
{
GenTree* op1;
GenTree* op2;
case SIMDIntrinsicInit:
{
op1 = tree->gtOp.gtOp1;
#if !defined(_TARGET_64BIT_)
if (op1->OperGet() == GT_LONG)
{
info->srcCount = 2;
op1->SetContained();
}
else
#endif // !defined(_TARGET_64BIT_)
{
info->srcCount = 1;
}
// This sets all fields of a SIMD struct to the given value.
// Mark op1 as contained if it is either zero or int constant of all 1's,
// or a float constant with 16 or 32 byte simdType (AVX case)
//
// Should never see small int base type vectors except for zero initialization.
assert(!varTypeIsSmallInt(simdTree->gtSIMDBaseType) || op1->IsIntegralConst(0));
#if !defined(_TARGET_64BIT_)
if (op1->OperGet() == GT_LONG)
{
op1->SetContained();
GenTree* op1lo = op1->gtGetOp1();
GenTree* op1hi = op1->gtGetOp2();
if ((op1lo->IsIntegralConst(0) && op1hi->IsIntegralConst(0)) ||
(op1lo->IsIntegralConst(-1) && op1hi->IsIntegralConst(-1)))
{
assert(op1->gtLsraInfo.srcCount == 0);
assert(op1->gtLsraInfo.dstCount == 0);
assert(op1lo->gtLsraInfo.srcCount == 0);
assert(op1lo->gtLsraInfo.dstCount == 1);
assert(op1hi->gtLsraInfo.srcCount == 0);
assert(op1hi->gtLsraInfo.dstCount == 1);
op1lo->gtLsraInfo.dstCount = 0;
op1lo->SetContained();
op1hi->gtLsraInfo.dstCount = 0;
op1hi->SetContained();
info->srcCount = 0;
}
else
{
// need a temp
info->internalFloatCount = 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
info->isInternalRegDelayFree = true;
}
}
else
#endif // !defined(_TARGET_64BIT_)
if (op1->IsFPZero() || op1->IsIntegralConst(0) ||
(varTypeIsIntegral(simdTree->gtSIMDBaseType) && op1->IsIntegralConst(-1)))
{
MakeSrcContained(tree, op1);
info->srcCount = 0;
}
else if ((comp->getSIMDInstructionSet() == InstructionSet_AVX) &&
((simdTree->gtSIMDSize == 16) || (simdTree->gtSIMDSize == 32)))
{
// Either op1 is a float or dbl constant or an addr
if (op1->IsCnsFltOrDbl() || op1->OperIsLocalAddr())
{
MakeSrcContained(tree, op1);
info->srcCount = 0;
}
}
}
break;
case SIMDIntrinsicInitN:
{
info->srcCount = (short)(simdTree->gtSIMDSize / genTypeSize(simdTree->gtSIMDBaseType));
// Need an internal register to stitch together all the values into a single vector in a SIMD reg.
info->internalFloatCount = 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
break;
case SIMDIntrinsicInitArray:
// We have an array and an index, which may be contained.
info->srcCount = 2;
CheckImmedAndMakeContained(tree, tree->gtGetOp2());
break;
case SIMDIntrinsicDiv:
// SSE2 has no instruction support for division on integer vectors
noway_assert(varTypeIsFloating(simdTree->gtSIMDBaseType));
info->srcCount = 2;
break;
case SIMDIntrinsicAbs:
// float/double vectors: This gets implemented as bitwise-And operation
// with a mask and hence should never see here.
//
// Must be a Vector<int> or Vector<short> Vector<sbyte>
assert(simdTree->gtSIMDBaseType == TYP_INT || simdTree->gtSIMDBaseType == TYP_SHORT ||
simdTree->gtSIMDBaseType == TYP_BYTE);
assert(comp->getSIMDInstructionSet() >= InstructionSet_SSE3_4);
info->srcCount = 1;
break;
case SIMDIntrinsicSqrt:
// SSE2 has no instruction support for sqrt on integer vectors.
noway_assert(varTypeIsFloating(simdTree->gtSIMDBaseType));
info->srcCount = 1;
break;
case SIMDIntrinsicAdd:
case SIMDIntrinsicSub:
case SIMDIntrinsicMul:
case SIMDIntrinsicBitwiseAnd:
case SIMDIntrinsicBitwiseAndNot:
case SIMDIntrinsicBitwiseOr:
case SIMDIntrinsicBitwiseXor:
case SIMDIntrinsicMin:
case SIMDIntrinsicMax:
info->srcCount = 2;
// SSE2 32-bit integer multiplication requires two temp regs
if (simdTree->gtSIMDIntrinsicID == SIMDIntrinsicMul && simdTree->gtSIMDBaseType == TYP_INT &&
comp->getSIMDInstructionSet() == InstructionSet_SSE2)
{
info->internalFloatCount = 2;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
break;
case SIMDIntrinsicEqual:
info->srcCount = 2;
break;
// SSE2 doesn't support < and <= directly on int vectors.
// Instead we need to use > and >= with swapped operands.
case SIMDIntrinsicLessThan:
case SIMDIntrinsicLessThanOrEqual:
info->srcCount = 2;
noway_assert(!varTypeIsIntegral(simdTree->gtSIMDBaseType));
break;
// SIMDIntrinsicEqual is supported only on non-floating point base type vectors.
// SSE2 cmpps/pd doesn't support > and >= directly on float/double vectors.
// Instead we need to use < and <= with swapped operands.
case SIMDIntrinsicGreaterThan:
noway_assert(!varTypeIsFloating(simdTree->gtSIMDBaseType));
info->srcCount = 2;
break;
case SIMDIntrinsicOpEquality:
case SIMDIntrinsicOpInEquality:
info->srcCount = 2;
// On SSE4/AVX, we can generate optimal code for (in)equality
// against zero using ptest. We can safely do this optimization
// for integral vectors but not for floating-point for the reason
// that we have +0.0 and -0.0 and +0.0 == -0.0
op2 = tree->gtGetOp2();
if ((comp->getSIMDInstructionSet() >= InstructionSet_SSE3_4) && op2->IsIntegralConstVector(0))
{
MakeSrcContained(tree, op2);
}
else
{
// Need one SIMD register as scratch.
// See genSIMDIntrinsicRelOp() for details on code sequence generated and
// the need for one scratch register.
//
// Note these intrinsics produce a BOOL result, hence internal float
// registers reserved are guaranteed to be different from target
// integer register without explicitly specifying.
info->internalFloatCount = 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
break;
case SIMDIntrinsicDotProduct:
// Float/Double vectors:
// For SSE, or AVX with 32-byte vectors, we also need an internal register
// as scratch. Further we need the targetReg and internal reg to be distinct
// registers. Note that if this is a TYP_SIMD16 or smaller on AVX, then we
// don't need a tmpReg.
//
// 32-byte integer vector on SSE4/AVX:
// will take advantage of phaddd, which operates only on 128-bit xmm reg.
// This will need 1 (in case of SSE4) or 2 (in case of AVX) internal
// registers since targetReg is an int type register.
//
// See genSIMDIntrinsicDotProduct() for details on code sequence generated
// and the need for scratch registers.
if (varTypeIsFloating(simdTree->gtSIMDBaseType))
{
if ((comp->getSIMDInstructionSet() == InstructionSet_SSE2) ||
(simdTree->gtOp.gtOp1->TypeGet() == TYP_SIMD32))
{
info->internalFloatCount = 1;
info->isInternalRegDelayFree = true;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
// else don't need scratch reg(s).
}
else
{
assert(simdTree->gtSIMDBaseType == TYP_INT && comp->getSIMDInstructionSet() >= InstructionSet_SSE3_4);
// No need to set isInternalRegDelayFree since targetReg is a
// an int type reg and guaranteed to be different from xmm/ymm
// regs.
info->internalFloatCount = comp->canUseAVX() ? 2 : 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
info->srcCount = 2;
break;
case SIMDIntrinsicGetItem:
{
// This implements get_Item method. The sources are:
// - the source SIMD struct
// - index (which element to get)
// The result is baseType of SIMD struct.
info->srcCount = 2;
op1 = tree->gtOp.gtOp1;
op2 = tree->gtOp.gtOp2;
// If the index is a constant, mark it as contained.
if (CheckImmedAndMakeContained(tree, op2))
{
info->srcCount = 1;
}
if (IsContainableMemoryOp(op1, true))
{
MakeSrcContained(tree, op1);
if (op1->OperGet() == GT_IND)
{
op1->AsIndir()->Addr()->ClearContained();
}
// Although GT_IND of TYP_SIMD12 reserves an internal float
// register for reading 4 and 8 bytes from memory and
// assembling them into target XMM reg, it is not required
// in this case.
op1->gtLsraInfo.internalIntCount = 0;
op1->gtLsraInfo.internalFloatCount = 0;
}
else
{
// If the index is not a constant, we will use the SIMD temp location to store the vector.
// Otherwise, if the baseType is floating point, the targetReg will be a xmm reg and we
// can use that in the process of extracting the element.
//
// If the index is a constant and base type is a small int we can use pextrw, but on AVX
// we will need a temp if are indexing into the upper half of the AVX register.
// In all other cases with constant index, we need a temp xmm register to extract the
// element if index is other than zero.
if (!op2->IsCnsIntOrI())
{
(void)comp->getSIMDInitTempVarNum();
}
else if (!varTypeIsFloating(simdTree->gtSIMDBaseType))
{
bool needFloatTemp;
if (varTypeIsSmallInt(simdTree->gtSIMDBaseType) &&
(comp->getSIMDInstructionSet() == InstructionSet_AVX))
{
int byteShiftCnt = (int)op2->AsIntCon()->gtIconVal * genTypeSize(simdTree->gtSIMDBaseType);
needFloatTemp = (byteShiftCnt >= 16);
}
else
{
needFloatTemp = !op2->IsIntegralConst(0);
}
if (needFloatTemp)
{
info->internalFloatCount = 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
}
}
}
break;
case SIMDIntrinsicSetX:
case SIMDIntrinsicSetY:
case SIMDIntrinsicSetZ:
case SIMDIntrinsicSetW:
info->srcCount = 2;
// We need an internal integer register for SSE2 codegen
if (comp->getSIMDInstructionSet() == InstructionSet_SSE2)
{
info->internalIntCount = 1;
info->setInternalCandidates(lsra, lsra->allRegs(TYP_INT));
}
break;
case SIMDIntrinsicCast:
info->srcCount = 1;
break;
case SIMDIntrinsicConvertToSingle:
info->srcCount = 1;
if (simdTree->gtSIMDBaseType == TYP_UINT)
{
// We need an internal register different from targetReg.
info->isInternalRegDelayFree = true;
info->internalIntCount = 1;
info->internalFloatCount = 2;
info->setInternalCandidates(lsra, lsra->allSIMDRegs() | lsra->allRegs(TYP_INT));
}
break;
case SIMDIntrinsicConvertToUInt32:
case SIMDIntrinsicConvertToInt32:
info->srcCount = 1;
break;
case SIMDIntrinsicWidenLo:
case SIMDIntrinsicWidenHi:
info->srcCount = 1;
if (varTypeIsIntegral(simdTree->gtSIMDBaseType))
{
// We need an internal register different from targetReg.
info->isInternalRegDelayFree = true;
info->internalFloatCount = 1;
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
}
break;
case SIMDIntrinsicConvertToInt64:
case SIMDIntrinsicConvertToUInt64:
// We need an internal register different from targetReg.
info->isInternalRegDelayFree = true;
info->srcCount = 1;
info->internalIntCount = 1;
if (comp->getSIMDInstructionSet() == InstructionSet_AVX)
{
info->internalFloatCount = 2;
}
else
{
info->internalFloatCount = 1;
}
info->setInternalCandidates(lsra, lsra->allSIMDRegs() | lsra->allRegs(TYP_INT));
break;
case SIMDIntrinsicConvertToDouble:
// We need an internal register different from targetReg.
info->isInternalRegDelayFree = true;
info->srcCount = 1;
info->internalIntCount = 1;
#ifdef _TARGET_X86_
if (simdTree->gtSIMDBaseType == TYP_LONG)
{
info->internalFloatCount = 3;
}
else
#endif
if ((comp->getSIMDInstructionSet() == InstructionSet_AVX) || (simdTree->gtSIMDBaseType == TYP_ULONG))
{
info->internalFloatCount = 2;
}
else
{
info->internalFloatCount = 1;
}
info->setInternalCandidates(lsra, lsra->allSIMDRegs() | lsra->allRegs(TYP_INT));
break;
case SIMDIntrinsicNarrow:
// We need an internal register different from targetReg.
info->isInternalRegDelayFree = true;
info->srcCount = 2;
if ((comp->getSIMDInstructionSet() == InstructionSet_AVX) && (simdTree->gtSIMDBaseType != TYP_DOUBLE))
{
info->internalFloatCount = 2;
}
else
{
info->internalFloatCount = 1;
}
info->setInternalCandidates(lsra, lsra->allSIMDRegs());
break;
case SIMDIntrinsicShuffleSSE2:
info->srcCount = 2;
// Second operand is an integer constant and marked as contained.
op2 = tree->gtOp.gtOp2;
noway_assert(op2->IsCnsIntOrI());
MakeSrcContained(tree, op2);
break;
case SIMDIntrinsicGetX:
case SIMDIntrinsicGetY:
case SIMDIntrinsicGetZ:
case SIMDIntrinsicGetW:
case SIMDIntrinsicGetOne:
case SIMDIntrinsicGetZero:
case SIMDIntrinsicGetCount:
case SIMDIntrinsicGetAllOnes:
assert(!"Get intrinsics should not be seen during Lowering.");
unreached();
default:
noway_assert(!"Unimplemented SIMD node type.");
unreached();
}
}
#endif // FEATURE_SIMD
//------------------------------------------------------------------------
// TreeNodeInfoInitCast: Set the NodeInfo for a GT_CAST.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitCast(GenTree* tree)
{
TreeNodeInfo* info = &(tree->gtLsraInfo);
// TODO-XArch-CQ: Int-To-Int conversions - castOp cannot be a memory op and must have an assigned register.
// see CodeGen::genIntToIntCast()
info->srcCount = 1;
info->dstCount = 1;
// Non-overflow casts to/from float/double are done using SSE2 instructions
// and that allow the source operand to be either a reg or memop. Given the
// fact that casts from small int to float/double are done as two-level casts,
// the source operand is always guaranteed to be of size 4 or 8 bytes.
var_types castToType = tree->CastToType();
GenTreePtr castOp = tree->gtCast.CastOp();
var_types castOpType = castOp->TypeGet();
if (tree->gtFlags & GTF_UNSIGNED)
{
castOpType = genUnsignedType(castOpType);
}
if (!tree->gtOverflow() && (varTypeIsFloating(castToType) || varTypeIsFloating(castOpType)))
{
#ifdef DEBUG
// If converting to float/double, the operand must be 4 or 8 byte in size.
if (varTypeIsFloating(castToType))
{
unsigned opSize = genTypeSize(castOpType);
assert(opSize == 4 || opSize == 8);
}
#endif // DEBUG
// U8 -> R8 conversion requires that the operand be in a register.
if (castOpType != TYP_ULONG)
{
if (IsContainableMemoryOp(castOp, true) || castOp->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, castOp);
}
else
{
// Mark castOp as reg optional to indicate codegen
// can still generate code if it is on stack.
SetRegOptional(castOp);
}
}
}
#if !defined(_TARGET_64BIT_)
if (varTypeIsLong(castOpType))
{
noway_assert(castOp->OperGet() == GT_LONG);
castOp->SetContained();
info->srcCount = 2;
}
#endif // !defined(_TARGET_64BIT_)
// some overflow checks need a temp reg:
// - GT_CAST from INT64/UINT64 to UINT32
if (tree->gtOverflow() && (castToType == TYP_UINT))
{
if (genTypeSize(castOpType) == 8)
{
// Here we don't need internal register to be different from targetReg,
// rather require it to be different from operand's reg.
info->internalIntCount = 1;
}
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitGCWriteBarrier: Set the NodeInfo for a GT_STOREIND requiring a write barrier.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitGCWriteBarrier(GenTree* tree)
{
assert(tree->OperGet() == GT_STOREIND);
GenTreeStoreInd* dst = tree->AsStoreInd();
GenTreePtr addr = dst->Addr();
GenTreePtr src = dst->Data();
if (addr->OperGet() == GT_LEA)
{
// In the case where we are doing a helper assignment, if the dst
// is an indir through an lea, we need to actually instantiate the
// lea in a register
GenTreeAddrMode* lea = addr->AsAddrMode();
int leaSrcCount = 0;
if (lea->HasBase())
{
leaSrcCount++;
}
if (lea->HasIndex())
{
leaSrcCount++;
}
lea->gtLsraInfo.srcCount = leaSrcCount;
lea->gtLsraInfo.dstCount = 1;
}
bool useOptimizedWriteBarrierHelper = false; // By default, assume no optimized write barriers.
#if NOGC_WRITE_BARRIERS
#if defined(_TARGET_X86_)
useOptimizedWriteBarrierHelper = true; // On x86, use the optimized write barriers by default.
#ifdef DEBUG
GCInfo::WriteBarrierForm wbf = comp->codeGen->gcInfo.gcIsWriteBarrierCandidate(tree, src);
if (wbf == GCInfo::WBF_NoBarrier_CheckNotHeapInDebug) // This one is always a call to a C++ method.
{
useOptimizedWriteBarrierHelper = false;
}
#endif
if (useOptimizedWriteBarrierHelper)
{
// Special write barrier:
// op1 (addr) goes into REG_WRITE_BARRIER (rdx) and
// op2 (src) goes into any int register.
addr->gtLsraInfo.setSrcCandidates(m_lsra, RBM_WRITE_BARRIER);
src->gtLsraInfo.setSrcCandidates(m_lsra, RBM_WRITE_BARRIER_SRC);
}
#else // !defined(_TARGET_X86_)
#error "NOGC_WRITE_BARRIERS is not supported"
#endif // !defined(_TARGET_X86_)
#endif // NOGC_WRITE_BARRIERS
if (!useOptimizedWriteBarrierHelper)
{
// For the standard JIT Helper calls:
// op1 (addr) goes into REG_ARG_0 and
// op2 (src) goes into REG_ARG_1
addr->gtLsraInfo.setSrcCandidates(m_lsra, RBM_ARG_0);
src->gtLsraInfo.setSrcCandidates(m_lsra, RBM_ARG_1);
}
// Both src and dst must reside in a register, which they should since we haven't set
// either of them as contained.
assert(addr->gtLsraInfo.dstCount == 1);
assert(src->gtLsraInfo.dstCount == 1);
}
//-----------------------------------------------------------------------------------------
// TreeNodeInfoInitIndir: Specify register requirements for address expression of an indirection operation.
//
// Arguments:
// indirTree - GT_IND or GT_STOREIND gentree node
//
void Lowering::TreeNodeInfoInitIndir(GenTreePtr indirTree)
{
assert(indirTree->isIndir());
// If this is the rhs of a block copy (i.e. non-enregisterable struct),
// it has no register requirements.
if (indirTree->TypeGet() == TYP_STRUCT)
{
return;
}
GenTreePtr addr = indirTree->gtGetOp1();
TreeNodeInfo* info = &(indirTree->gtLsraInfo);
GenTreePtr base = nullptr;
GenTreePtr index = nullptr;
unsigned mul, cns;
bool rev;
#ifdef FEATURE_SIMD
// If indirTree is of TYP_SIMD12, don't mark addr as contained
// so that it always get computed to a register. This would
// mean codegen side logic doesn't need to handle all possible
// addr expressions that could be contained.
//
// TODO-XArch-CQ: handle other addr mode expressions that could be marked
// as contained.
if (indirTree->TypeGet() == TYP_SIMD12)
{
// Vector3 is read/written as two reads/writes: 8 byte and 4 byte.
// To assemble the vector properly we would need an additional
// XMM register.
info->internalFloatCount = 1;
// In case of GT_IND we need an internal register different from targetReg and
// both of the registers are used at the same time.
if (indirTree->OperGet() == GT_IND)
{
info->isInternalRegDelayFree = true;
}
info->setInternalCandidates(m_lsra, m_lsra->allSIMDRegs());
return;
}
#endif // FEATURE_SIMD
if ((indirTree->gtFlags & GTF_IND_REQ_ADDR_IN_REG) != 0)
{
// The address of an indirection that requires its address in a reg.
// Skip any further processing that might otherwise make it contained.
}
else if ((addr->OperGet() == GT_CLS_VAR_ADDR) || (addr->OperGet() == GT_LCL_VAR_ADDR))
{
// These nodes go into an addr mode:
// - GT_CLS_VAR_ADDR turns into a constant.
// - GT_LCL_VAR_ADDR is a stack addr mode.
// make this contained, it turns into a constant that goes into an addr mode
MakeSrcContained(indirTree, addr);
}
else if (addr->IsCnsIntOrI() && addr->AsIntConCommon()->FitsInAddrBase(comp))
{
// Amd64:
// We can mark any pc-relative 32-bit addr as containable, except for a direct VSD call address.
// (i.e. those VSD calls for which stub addr is known during JIT compilation time). In this case,
// VM requires us to pass stub addr in VirtualStubParam.reg - see LowerVirtualStubCall(). For
// that reason we cannot mark such an addr as contained. Note that this is not an issue for
// indirect VSD calls since morphArgs() is explicitly materializing hidden param as a non-standard
// argument.
//
// Workaround:
// Note that LowerVirtualStubCall() sets addr->gtRegNum to VirtualStubParam.reg and Lowering::doPhase()
// sets destination candidates on such nodes and resets addr->gtRegNum to REG_NA before calling
// TreeNodeInfoInit(). Ideally we should set a flag on addr nodes that shouldn't be marked as contained
// (in LowerVirtualStubCall()), but we don't have any GTF_* flags left for that purpose. As a workaround
// an explicit check is made here.
//
// On x86, direct VSD is done via a relative branch, and in fact it MUST be contained.
MakeSrcContained(indirTree, addr);
}
else if ((addr->OperGet() == GT_LEA) && IsSafeToContainMem(indirTree, addr))
{
MakeSrcContained(indirTree, addr);
}
else if (addr->gtOper == GT_ARR_ELEM)
{
// The GT_ARR_ELEM consumes all the indices and produces the offset.
// The array object lives until the mem access.
// We also consume the target register to which the address is
// computed
info->srcCount++;
assert(addr->gtLsraInfo.srcCount >= 2);
addr->gtLsraInfo.srcCount -= 1;
}
}
//------------------------------------------------------------------------
// TreeNodeInfoInitCmp: Set the register requirements for a compare.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitCmp(GenTreePtr tree)
{
assert(tree->OperIsCompare() || tree->OperIs(GT_CMP));
TreeNodeInfo* info = &(tree->gtLsraInfo);
info->srcCount = 2;
info->dstCount = tree->OperIs(GT_CMP) ? 0 : 1;
#ifdef _TARGET_X86_
// If the compare is used by a jump, we just need to set the condition codes. If not, then we need
// to store the result into the low byte of a register, which requires the dst be a byteable register.
// We always set the dst candidates, though, because if this is compare is consumed by a jump, they
// won't be used. We might be able to use GTF_RELOP_JMP_USED to determine this case, but it's not clear
// that flag is maintained until this location (especially for decomposed long compares).
info->setDstCandidates(m_lsra, RBM_BYTE_REGS);
#endif // _TARGET_X86_
GenTreePtr op1 = tree->gtOp.gtOp1;
GenTreePtr op2 = tree->gtOp.gtOp2;
var_types op1Type = op1->TypeGet();
var_types op2Type = op2->TypeGet();
// If either of op1 or op2 is floating point values, then we need to use
// ucomiss or ucomisd to compare, both of which support the following form:
// ucomis[s|d] xmm, xmm/mem
// That is only the second operand can be a memory op.
//
// Second operand is a memory Op: Note that depending on comparison operator,
// the operands of ucomis[s|d] need to be reversed. Therefore, either op1 or
// op2 can be a memory op depending on the comparison operator.
if (varTypeIsFloating(op1Type))
{
// The type of the operands has to be the same and no implicit conversions at this stage.
assert(op1Type == op2Type);
bool reverseOps;
if ((tree->gtFlags & GTF_RELOP_NAN_UN) != 0)
{
// Unordered comparison case
reverseOps = tree->OperIs(GT_GT, GT_GE);
}
else
{
reverseOps = tree->OperIs(GT_LT, GT_LE);
}
GenTreePtr otherOp;
if (reverseOps)
{
otherOp = op1;
}
else
{
otherOp = op2;
}
assert(otherOp != nullptr);
if (otherOp->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, otherOp);
}
else if (IsContainableMemoryOp(otherOp, true) && ((otherOp == op2) || IsSafeToContainMem(tree, otherOp)))
{
MakeSrcContained(tree, otherOp);
}
else
{
// SSE2 allows only otherOp to be a memory-op. Since otherOp is not
// contained, we can mark it reg-optional.
SetRegOptional(otherOp);
}
return;
}
// TODO-XArch-CQ: factor out cmp optimization in 'genCondSetFlags' to be used here
// or in other backend.
if (CheckImmedAndMakeContained(tree, op2))
{
// If the types are the same, or if the constant is of the correct size,
// we can treat the MemoryOp as contained.
if (op1Type == op2Type)
{
if (IsContainableMemoryOp(op1, true))
{
MakeSrcContained(tree, op1);
}
// If op1 codegen sets ZF and SF flags and ==/!= against
// zero, we don't need to generate test instruction,
// provided we don't have another GenTree node between op1
// and tree that could potentially modify flags.
//
// TODO-CQ: right now the below peep is inexpensive and
// gets the benefit in most of cases because in majority
// of cases op1, op2 and tree would be in that order in
// execution. In general we should be able to check that all
// the nodes that come after op1 in execution order do not
// modify the flags so that it is safe to avoid generating a
// test instruction. Such a check requires that on each
// GenTree node we need to set the info whether its codegen
// will modify flags.
//
// TODO-CQ: We can optimize compare against zero in the
// following cases by generating the branch as indicated
// against each case.
// 1) unsigned compare
// < 0 - always FALSE
// <= 0 - ZF=1 and jne
// > 0 - ZF=0 and je
// >= 0 - always TRUE
//
// 2) signed compare
// < 0 - SF=1 and js
// >= 0 - SF=0 and jns
else if (tree->OperIs(GT_EQ, GT_NE) && op1->gtSetZSFlags() && op2->IsIntegralConst(0) &&
(op1->gtNext == op2) && (op2->gtNext == tree))
{
// Require codegen of op1 to set the flags.
assert(!op1->gtSetFlags());
op1->gtFlags |= GTF_SET_FLAGS;
}
else
{
SetRegOptional(op1);
}
}
}
else if (op1Type == op2Type)
{
// Note that TEST does not have a r,rm encoding like CMP has but we can still
// contain the second operand because the emitter maps both r,rm and rm,r to
// the same instruction code. This avoids the need to special case TEST here.
if (IsContainableMemoryOp(op2, true))
{
MakeSrcContained(tree, op2);
}
else if (IsContainableMemoryOp(op1, true) && IsSafeToContainMem(tree, op1))
{
MakeSrcContained(tree, op1);
}
else if (op1->IsCnsIntOrI())
{
// TODO-CQ: We should be able to support swapping op1 and op2 to generate cmp reg, imm,
// but there is currently an assert in CodeGen::genCompareInt().
// https://github.com/dotnet/coreclr/issues/7270
SetRegOptional(op2);
}
else
{
// One of op1 or op2 could be marked as reg optional
// to indicate that codegen can still generate code
// if one of them is on stack.
SetRegOptional(PreferredRegOptionalOperand(tree));
}
}
}
//--------------------------------------------------------------------------------------------
// TreeNodeInfoInitIfRMWMemOp: Checks to see if there is a RMW memory operation rooted at
// GT_STOREIND node and if so will mark register requirements for nodes under storeInd so
// that CodeGen will generate a single instruction of the form:
//
// binOp [addressing mode], reg
//
// Parameters
// storeInd - GT_STOREIND node
//
// Return value
// True, if RMW memory op tree pattern is recognized and op counts are set.
// False otherwise.
//
bool Lowering::TreeNodeInfoInitIfRMWMemOp(GenTreePtr storeInd)
{
assert(storeInd->OperGet() == GT_STOREIND);
// SSE2 doesn't support RMW on float values
assert(!varTypeIsFloating(storeInd));
// Terminology:
// indirDst = memory write of an addr mode (i.e. storeind destination)
// indirSrc = value being written to memory (i.e. storeind source which could a binary/unary op)
// indirCandidate = memory read i.e. a gtInd of an addr mode
// indirOpSource = source operand used in binary/unary op (i.e. source operand of indirSrc node)
GenTreePtr indirCandidate = nullptr;
GenTreePtr indirOpSource = nullptr;
if (!IsRMWMemOpRootedAtStoreInd(storeInd, &indirCandidate, &indirOpSource))
{
JITDUMP("Lower of StoreInd didn't mark the node as self contained for reason: %d\n",
storeInd->AsStoreInd()->GetRMWStatus());
DISPTREERANGE(BlockRange(), storeInd);
return false;
}
GenTreePtr indirDst = storeInd->gtGetOp1();
GenTreePtr indirSrc = storeInd->gtGetOp2();
genTreeOps oper = indirSrc->OperGet();
// At this point we have successfully detected a RMW memory op of one of the following forms
// storeInd(indirDst, indirSrc(indirCandidate, indirOpSource)) OR
// storeInd(indirDst, indirSrc(indirOpSource, indirCandidate) in case of commutative operations OR
// storeInd(indirDst, indirSrc(indirCandidate) in case of unary operations
//
// Here indirSrc = one of the supported binary or unary operation for RMW of memory
// indirCandidate = a GT_IND node
// indirCandidateChild = operand of GT_IND indirCandidate
//
// The logic below essentially does the following
// Make indirOpSource contained.
// Make indirSrc contained.
// Make indirCandidate contained.
// Make indirCandidateChild contained.
// Make indirDst contained except when it is a GT_LCL_VAR or GT_CNS_INT that doesn't fit within addr
// base.
// Note that due to the way containment is supported, we accomplish some of the above by clearing operand counts
// and directly propagating them upward.
//
TreeNodeInfo* info = &(storeInd->gtLsraInfo);
info->dstCount = 0;
if (GenTree::OperIsBinary(oper))
{
// On Xarch RMW operations require that the non-rmw operand be an immediate or in a register.
// Therefore, if we have previously marked the indirOpSource as a contained memory op while lowering
// the binary node, we need to reset that now.
if (IsContainableMemoryOp(indirOpSource, true))
{
indirOpSource->ClearContained();
}
assert(!indirOpSource->isContained() || indirOpSource->OperIsConst());
JITDUMP("Lower succesfully detected an assignment of the form: *addrMode BinOp= source\n");
info->srcCount = indirOpSource->gtLsraInfo.dstCount;
}
else
{
assert(GenTree::OperIsUnary(oper));
JITDUMP("Lower succesfully detected an assignment of the form: *addrMode = UnaryOp(*addrMode)\n");
info->srcCount = 0;
}
DISPTREERANGE(BlockRange(), storeInd);
m_lsra->clearOperandCounts(indirSrc);
indirSrc->SetContained();
m_lsra->clearOperandCounts(indirCandidate);
indirCandidate->SetContained();
GenTreePtr indirCandidateChild = indirCandidate->gtGetOp1();
if (indirCandidateChild->OperGet() == GT_LEA)
{
GenTreeAddrMode* addrMode = indirCandidateChild->AsAddrMode();
if (addrMode->HasBase())
{
assert(addrMode->Base()->OperIsLeaf());
m_lsra->clearOperandCounts(addrMode->Base());
addrMode->Base()->SetContained();
info->srcCount++;
}
if (addrMode->HasIndex())
{
assert(addrMode->Index()->OperIsLeaf());
m_lsra->clearOperandCounts(addrMode->Index());
addrMode->Index()->SetContained();
info->srcCount++;
}
m_lsra->clearOperandCounts(indirDst);
indirDst->SetContained();
}
else
{
assert(indirCandidateChild->OperGet() == GT_LCL_VAR || indirCandidateChild->OperGet() == GT_LCL_VAR_ADDR ||
indirCandidateChild->OperGet() == GT_CLS_VAR_ADDR || indirCandidateChild->OperGet() == GT_CNS_INT);
// If it is a GT_LCL_VAR, it still needs the reg to hold the address.
// We would still need a reg for GT_CNS_INT if it doesn't fit within addressing mode base.
// For GT_CLS_VAR_ADDR, we don't need a reg to hold the address, because field address value is known at jit
// time. Also, we don't need a reg for GT_CLS_VAR_ADDR.
if (indirCandidateChild->OperGet() == GT_LCL_VAR_ADDR || indirCandidateChild->OperGet() == GT_CLS_VAR_ADDR)
{
m_lsra->clearOperandCounts(indirDst);
indirDst->SetContained();
}
else if (indirCandidateChild->IsCnsIntOrI() && indirCandidateChild->AsIntConCommon()->FitsInAddrBase(comp))
{
m_lsra->clearOperandCounts(indirDst);
indirDst->SetContained();
}
else
{
// Need a reg and hence increment src count of storeind
info->srcCount += indirCandidateChild->gtLsraInfo.dstCount;
}
}
m_lsra->clearOperandCounts(indirCandidateChild);
indirCandidateChild->SetContained();
#ifdef _TARGET_X86_
if (varTypeIsByte(storeInd))
{
// If storeInd is of TYP_BYTE, set indirOpSources to byteable registers.
bool containedNode = indirOpSource->gtLsraInfo.dstCount == 0;
if (!containedNode)
{
regMaskTP regMask = indirOpSource->gtLsraInfo.getSrcCandidates(m_lsra);
assert(regMask != RBM_NONE);
indirOpSource->gtLsraInfo.setSrcCandidates(m_lsra, regMask & ~RBM_NON_BYTE_REGS);
}
}
#endif
return true;
}
//------------------------------------------------------------------------
// TreeNodeInfoInitMul: Set the NodeInfo for a multiply.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// None.
//
void Lowering::TreeNodeInfoInitMul(GenTreePtr tree)
{
#if defined(_TARGET_X86_)
assert(tree->OperGet() == GT_MUL || tree->OperGet() == GT_MULHI || tree->OperGet() == GT_MUL_LONG);
#else
assert(tree->OperGet() == GT_MUL || tree->OperGet() == GT_MULHI);
#endif
TreeNodeInfo* info = &(tree->gtLsraInfo);
info->srcCount = 2;
info->dstCount = 1;
GenTreePtr op1 = tree->gtOp.gtOp1;
GenTreePtr op2 = tree->gtOp.gtOp2;
// Case of float/double mul.
if (varTypeIsFloating(tree->TypeGet()))
{
assert(tree->OperGet() == GT_MUL);
if (IsContainableMemoryOp(op2, true) || op2->IsCnsNonZeroFltOrDbl())
{
MakeSrcContained(tree, op2);
}
else if (op1->IsCnsNonZeroFltOrDbl() || (IsContainableMemoryOp(op1, true) && IsSafeToContainMem(tree, op1)))
{
// Since GT_MUL is commutative, we will try to re-order operands if it is safe to
// generate more efficient code sequence for the case of GT_MUL(op1=memOp, op2=non-memOp)
MakeSrcContained(tree, op1);
}
else
{
// If there are no containable operands, we can make an operand reg optional.
SetRegOptionalForBinOp(tree);
}
return;
}
bool isUnsignedMultiply = ((tree->gtFlags & GTF_UNSIGNED) != 0);
bool requiresOverflowCheck = tree->gtOverflowEx();
bool useLeaEncoding = false;
GenTreePtr memOp = nullptr;
bool hasImpliedFirstOperand = false;
GenTreeIntConCommon* imm = nullptr;
GenTreePtr other = nullptr;
// There are three forms of x86 multiply:
// one-op form: RDX:RAX = RAX * r/m
// two-op form: reg *= r/m
// three-op form: reg = r/m * imm
// This special widening 32x32->64 MUL is not used on x64
CLANG_FORMAT_COMMENT_ANCHOR;
#if defined(_TARGET_X86_)
if (tree->OperGet() != GT_MUL_LONG)
#endif
{
assert((tree->gtFlags & GTF_MUL_64RSLT) == 0);
}
// Multiply should never be using small types
assert(!varTypeIsSmall(tree->TypeGet()));
// We do use the widening multiply to implement
// the overflow checking for unsigned multiply
//
if (isUnsignedMultiply && requiresOverflowCheck)
{
// The only encoding provided is RDX:RAX = RAX * rm
//
// Here we set RAX as the only destination candidate
// In LSRA we set the kill set for this operation to RBM_RAX|RBM_RDX
//
info->setDstCandidates(m_lsra, RBM_RAX);
hasImpliedFirstOperand = true;
}
else if (tree->OperGet() == GT_MULHI)
{
// Have to use the encoding:RDX:RAX = RAX * rm. Since we only care about the
// upper 32 bits of the result set the destination candidate to REG_RDX.
info->setDstCandidates(m_lsra, RBM_RDX);
hasImpliedFirstOperand = true;
}
#if defined(_TARGET_X86_)
else if (tree->OperGet() == GT_MUL_LONG)
{
// have to use the encoding:RDX:RAX = RAX * rm
info->setDstCandidates(m_lsra, RBM_RAX);
hasImpliedFirstOperand = true;
}
#endif
else if (IsContainableImmed(tree, op2) || IsContainableImmed(tree, op1))
{
if (IsContainableImmed(tree, op2))
{
imm = op2->AsIntConCommon();
other = op1;
}
else
{
imm = op1->AsIntConCommon();
other = op2;
}
// CQ: We want to rewrite this into a LEA
ssize_t immVal = imm->AsIntConCommon()->IconValue();
if (!requiresOverflowCheck && (immVal == 3 || immVal == 5 || immVal == 9))
{
useLeaEncoding = true;
}
MakeSrcContained(tree, imm); // The imm is always contained
if (IsContainableMemoryOp(other, true))
{
memOp = other; // memOp may be contained below
}
}
// We allow one operand to be a contained memory operand.
// The memory op type must match with the 'tree' type.
// This is because during codegen we use 'tree' type to derive EmitTypeSize.
// E.g op1 type = byte, op2 type = byte but GT_MUL tree type is int.
//
if (memOp == nullptr)
{
if (IsContainableMemoryOp(op2, true) && (op2->TypeGet() == tree->TypeGet()) && IsSafeToContainMem(tree, op2))
{
memOp = op2;
}
else if (IsContainableMemoryOp(op1, true) && (op1->TypeGet() == tree->TypeGet()) &&
IsSafeToContainMem(tree, op1))
{
memOp = op1;
}
}
else
{
if ((memOp->TypeGet() != tree->TypeGet()) || !IsSafeToContainMem(tree, memOp))
{
memOp = nullptr;
}
}
// To generate an LEA we need to force memOp into a register
// so don't allow memOp to be 'contained'
//
if (!useLeaEncoding)
{
if (memOp != nullptr)
{
MakeSrcContained(tree, memOp);
// The memOp will be the second source. It must be different from the targetReg.
SetDelayFree(memOp);
info->hasDelayFreeSrc = true;
}
else if (imm != nullptr)
{
// Has a contained immediate operand.
// Only 'other' operand can be marked as reg optional.
assert(other != nullptr);
SetRegOptional(other);
}
else if (hasImpliedFirstOperand)
{
// Only op2 can be marke as reg optional.
SetRegOptional(op2);
}
else
{
// If there are no containable operands, we can make either of op1 or op2
// as reg optional.
SetRegOptionalForBinOp(tree);
}
}
}
//------------------------------------------------------------------------------
// SetContainsAVXFlags: Set ContainsAVX flag when it is floating type, set
// Contains256bitAVX flag when SIMD vector size is 32 bytes
//
// Arguments:
// isFloatingPointType - true if it is floating point type
// sizeOfSIMDVector - SIMD Vector size
//
void Lowering::SetContainsAVXFlags(bool isFloatingPointType /* = true */, unsigned sizeOfSIMDVector /* = 0*/)
{
#ifdef FEATURE_AVX_SUPPORT
if (isFloatingPointType)
{
if (comp->getFloatingPointInstructionSet() == InstructionSet_AVX)
{
comp->getEmitter()->SetContainsAVX(true);
}
if (sizeOfSIMDVector == 32 && comp->getSIMDInstructionSet() == InstructionSet_AVX)
{
comp->getEmitter()->SetContains256bitAVX(true);
}
}
#endif
}
#ifdef _TARGET_X86_
//------------------------------------------------------------------------
// ExcludeNonByteableRegisters: Determines if we need to exclude non-byteable registers for
// various reasons
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// If we need to exclude non-byteable registers
//
bool Lowering::ExcludeNonByteableRegisters(GenTree* tree)
{
// Example1: GT_STOREIND(byte, addr, op2) - storeind of byte sized value from op2 into mem 'addr'
// Storeind itself will not produce any value and hence dstCount=0. But op2 could be TYP_INT
// value. In this case we need to exclude esi/edi from the src candidates of op2.
if (varTypeIsByte(tree))
{
return true;
}
// Example2: GT_CAST(int <- bool <- int) - here type of GT_CAST node is int and castToType is bool.
else if ((tree->OperGet() == GT_CAST) && varTypeIsByte(tree->CastToType()))
{
return true;
}
else if (tree->OperIsCompare() || tree->OperIs(GT_CMP))
{
GenTree* op1 = tree->gtGetOp1();
GenTree* op2 = tree->gtGetOp2();
// Example3: GT_EQ(int, op1 of type ubyte, op2 of type ubyte) - in this case codegen uses
// ubyte as the result of comparison and if the result needs to be materialized into a reg
// simply zero extend it to TYP_INT size. Here is an example of generated code:
// cmp dl, byte ptr[addr mode]
// movzx edx, dl
if (varTypeIsByte(op1) && varTypeIsByte(op2))
{
return true;
}
// Example4: GT_EQ(int, op1 of type ubyte, op2 is GT_CNS_INT) - in this case codegen uses
// ubyte as the result of the comparison and if the result needs to be materialized into a reg
// simply zero extend it to TYP_INT size.
else if (varTypeIsByte(op1) && op2->IsCnsIntOrI())
{
return true;
}
// Example4: GT_EQ(int, op1 is GT_CNS_INT, op2 of type ubyte) - in this case codegen uses
// ubyte as the result of the comparison and if the result needs to be materialized into a reg
// simply zero extend it to TYP_INT size.
else if (op1->IsCnsIntOrI() && varTypeIsByte(op2))
{
return true;
}
else
{
return false;
}
}
#ifdef FEATURE_SIMD
else if (tree->OperGet() == GT_SIMD)
{
GenTreeSIMD* simdNode = tree->AsSIMD();
switch (simdNode->gtSIMDIntrinsicID)
{
case SIMDIntrinsicOpEquality:
case SIMDIntrinsicOpInEquality:
// We manifest it into a byte register, so the target must be byteable.
return true;
case SIMDIntrinsicGetItem:
{
// This logic is duplicated from genSIMDIntrinsicGetItem().
// When we generate code for a SIMDIntrinsicGetItem, under certain circumstances we need to
// generate a movzx/movsx. On x86, these require byteable registers. So figure out which
// cases will require this, so the non-byteable registers can be excluded.
GenTree* op1 = simdNode->gtGetOp1();
GenTree* op2 = simdNode->gtGetOp2();
var_types baseType = simdNode->gtSIMDBaseType;
if (!IsContainableMemoryOp(op1, true) && op2->IsCnsIntOrI() && varTypeIsSmallInt(baseType))
{
bool ZeroOrSignExtnReqd = true;
unsigned baseSize = genTypeSize(baseType);
if (baseSize == 1)
{
if ((op2->gtIntCon.gtIconVal % 2) == 1)
{
ZeroOrSignExtnReqd = (baseType == TYP_BYTE);
}
}
else
{
assert(baseSize == 2);
ZeroOrSignExtnReqd = (baseType == TYP_SHORT);
}
return ZeroOrSignExtnReqd;
}
break;
}
default:
break;
}
return false;
}
#endif // FEATURE_SIMD
else
{
return false;
}
}
#endif // _TARGET_X86_
#endif // _TARGET_XARCH_
#endif // !LEGACY_BACKEND
| {
"content_hash": "2dc61939fe867fec7f3563b51c4348f4",
"timestamp": "",
"source": "github",
"line_count": 3708,
"max_line_length": 120,
"avg_line_length": 36.67017259978425,
"alnum_prop": 0.5468659219109676,
"repo_name": "pgavlin/coreclr",
"id": "76a0a96099aab43604c92832c79fe0832f4186b1",
"size": "135973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/jit/lsraxarch.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1018888"
},
{
"name": "Awk",
"bytes": "5861"
},
{
"name": "Batchfile",
"bytes": "137794"
},
{
"name": "C",
"bytes": "2870576"
},
{
"name": "C#",
"bytes": "134065840"
},
{
"name": "C++",
"bytes": "68757573"
},
{
"name": "CMake",
"bytes": "654585"
},
{
"name": "Groovy",
"bytes": "172836"
},
{
"name": "Makefile",
"bytes": "2736"
},
{
"name": "Objective-C",
"bytes": "656865"
},
{
"name": "PAWN",
"bytes": "903"
},
{
"name": "Perl",
"bytes": "23640"
},
{
"name": "PowerShell",
"bytes": "9319"
},
{
"name": "Python",
"bytes": "233606"
},
{
"name": "Roff",
"bytes": "529523"
},
{
"name": "Shell",
"bytes": "217596"
},
{
"name": "Smalltalk",
"bytes": "1218746"
},
{
"name": "SuperCollider",
"bytes": "4752"
},
{
"name": "Yacc",
"bytes": "157348"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Tue Feb 14 08:16:38 UTC 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.examples.terasort.TeraGen.SortGenMapper (Hadoop 1.0.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-02-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.examples.terasort.TeraGen.SortGenMapper (Hadoop 1.0.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/examples/terasort/TeraGen.SortGenMapper.html" title="class in org.apache.hadoop.examples.terasort"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/examples/terasort//class-useTeraGen.SortGenMapper.html" target="_top"><B>FRAMES</B></A>
<A HREF="TeraGen.SortGenMapper.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.examples.terasort.TeraGen.SortGenMapper</B></H2>
</CENTER>
No usage of org.apache.hadoop.examples.terasort.TeraGen.SortGenMapper
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/examples/terasort/TeraGen.SortGenMapper.html" title="class in org.apache.hadoop.examples.terasort"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/examples/terasort//class-useTeraGen.SortGenMapper.html" target="_top"><B>FRAMES</B></A>
<A HREF="TeraGen.SortGenMapper.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| {
"content_hash": "abdac43fefebed831d659b10f5c9b09a",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 252,
"avg_line_length": 43.298611111111114,
"alnum_prop": 0.619887730553328,
"repo_name": "hoppinghippo/HadoopMapReduce",
"id": "88be9a227275a6ba7add675a5ad5484ceb826846",
"size": "6235",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/api/org/apache/hadoop/examples/terasort/class-use/TeraGen.SortGenMapper.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "64797"
},
{
"name": "C",
"bytes": "332613"
},
{
"name": "C++",
"bytes": "460930"
},
{
"name": "CSS",
"bytes": "34759"
},
{
"name": "HTML",
"bytes": "932320"
},
{
"name": "Java",
"bytes": "16215137"
},
{
"name": "JavaScript",
"bytes": "59122"
},
{
"name": "Makefile",
"bytes": "7960"
},
{
"name": "Objective-C",
"bytes": "118273"
},
{
"name": "PHP",
"bytes": "152555"
},
{
"name": "Perl",
"bytes": "149888"
},
{
"name": "Python",
"bytes": "1066410"
},
{
"name": "Ruby",
"bytes": "28485"
},
{
"name": "Shell",
"bytes": "1667689"
},
{
"name": "Smalltalk",
"bytes": "56562"
},
{
"name": "TeX",
"bytes": "26547"
},
{
"name": "Thrift",
"bytes": "3965"
},
{
"name": "XSLT",
"bytes": "27004"
}
],
"symlink_target": ""
} |
/* fips_dsa_sign.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2007.
*/
/* ====================================================================
* Copyright (c) 2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <string.h>
#include <openssl/evp.h>
#include <openssl/dsa.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/bn.h>
#ifdef OPENSSL_FIPS
/*
* FIPS versions of DSA_sign() and DSA_verify(). These include a tiny ASN1
* encoder/decoder to handle the specific case of a DSA signature.
*/
# if 0
int FIPS_dsa_size(DSA *r)
{
int ilen;
ilen = BN_num_bytes(r->q);
if (ilen > 20)
return -1;
/* If MSB set need padding byte */
ilen++;
/*
* Also need 2 bytes INTEGER header for r and s plus 2 bytes SEQUENCE
* header making 6 in total.
*/
return ilen * 2 + 6;
}
# endif
/*
* Tiny ASN1 encoder for DSA_SIG structure. We can assume r, s smaller than
* 0x80 octets as by the DSA standards they will be less than 2^160
*/
int FIPS_dsa_sig_encode(unsigned char *out, DSA_SIG *sig)
{
int rlen, slen, rpad, spad, seqlen;
rlen = BN_num_bytes(sig->r);
if (rlen > 20)
return -1;
if (BN_num_bits(sig->r) & 0x7)
rpad = 0;
else
rpad = 1;
slen = BN_num_bytes(sig->s);
if (slen > 20)
return -1;
if (BN_num_bits(sig->s) & 0x7)
spad = 0;
else
spad = 1;
/* Length of SEQUENCE, (1 tag + 1 len octet) * 2 + content octets */
seqlen = rlen + rpad + slen + spad + 4;
/* Actual encoded length: include SEQUENCE header */
if (!out)
return seqlen + 2;
/* Output SEQUENCE header */
*out++ = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
*out++ = (unsigned char)seqlen;
/* Output r */
*out++ = V_ASN1_INTEGER;
*out++ = (unsigned char)(rlen + rpad);
if (rpad)
*out++ = 0;
BN_bn2bin(sig->r, out);
out += rlen;
/* Output s */
*out++ = V_ASN1_INTEGER;
*out++ = (unsigned char)(slen + spad);
if (spad)
*out++ = 0;
BN_bn2bin(sig->s, out);
return seqlen + 2;
}
/* Companion DSA_SIG decoder */
int FIPS_dsa_sig_decode(DSA_SIG *sig, const unsigned char *in, int inlen)
{
int seqlen, rlen, slen;
const unsigned char *rbin;
/* Sanity check */
/* Need SEQUENCE tag */
if (*in++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED))
return 0;
/* Get length octet */
seqlen = *in++;
/* Check sensible length value */
if (seqlen < 4 || seqlen > 0x7F)
return 0;
/* Check INTEGER tag */
if (*in++ != V_ASN1_INTEGER)
return 0;
rlen = *in++;
seqlen -= 2 + rlen;
/* Check sensible seqlen value */
if (seqlen < 2)
return 0;
rbin = in;
in += rlen;
/* Check INTEGER tag */
if (*in++ != V_ASN1_INTEGER)
return 0;
slen = *in++;
/*
* Remaining bytes of SEQUENCE should exactly match encoding of s
*/
if (seqlen != (slen + 2))
return 0;
if (!sig->r && !(sig->r = BN_new()))
return 0;
if (!sig->s && !(sig->s = BN_new()))
return 0;
if (!BN_bin2bn(rbin, rlen, sig->r))
return 0;
if (!BN_bin2bn(in, slen, sig->s))
return 0;
return 1;
}
static int fips_dsa_sign(int type, const unsigned char *x, int y,
unsigned char *sig, unsigned int *siglen,
EVP_MD_SVCTX * sv)
{
DSA *dsa = sv->key;
unsigned char dig[EVP_MAX_MD_SIZE];
unsigned int dlen;
DSA_SIG *s;
EVP_DigestFinal_ex(sv->mctx, dig, &dlen);
s = dsa->meth->dsa_do_sign(dig, dlen, dsa);
OPENSSL_cleanse(dig, dlen);
if (s == NULL) {
*siglen = 0;
return 0;
}
*siglen = FIPS_dsa_sig_encode(sig, s);
DSA_SIG_free(s);
if (*siglen < 0)
return 0;
return 1;
}
static int fips_dsa_verify(int type, const unsigned char *x, int y,
const unsigned char *sigbuf, unsigned int siglen,
EVP_MD_SVCTX * sv)
{
DSA *dsa = sv->key;
DSA_SIG *s;
int ret = -1;
unsigned char dig[EVP_MAX_MD_SIZE];
unsigned int dlen;
s = DSA_SIG_new();
if (s == NULL)
return ret;
if (!FIPS_dsa_sig_decode(s, sigbuf, siglen))
goto err;
EVP_DigestFinal_ex(sv->mctx, dig, &dlen);
ret = dsa->meth->dsa_do_verify(dig, dlen, s, dsa);
OPENSSL_cleanse(dig, dlen);
err:
DSA_SIG_free(s);
return ret;
}
static int init(EVP_MD_CTX *ctx)
{
return SHA1_Init(ctx->md_data);
}
static int update(EVP_MD_CTX *ctx, const void *data, size_t count)
{
return SHA1_Update(ctx->md_data, data, count);
}
static int final(EVP_MD_CTX *ctx, unsigned char *md)
{
return SHA1_Final(md, ctx->md_data);
}
static const EVP_MD dss1_md = {
NID_dsa,
NID_dsaWithSHA1,
SHA_DIGEST_LENGTH,
EVP_MD_FLAG_FIPS | EVP_MD_FLAG_SVCTX,
init,
update,
final,
NULL,
NULL,
(evp_sign_method *) fips_dsa_sign,
(evp_verify_method *) fips_dsa_verify,
{EVP_PKEY_DSA, EVP_PKEY_DSA2, EVP_PKEY_DSA3, EVP_PKEY_DSA4, 0},
SHA_CBLOCK,
sizeof(EVP_MD *) + sizeof(SHA_CTX),
};
const EVP_MD *EVP_dss1(void)
{
return (&dss1_md);
}
#endif
| {
"content_hash": "4aea7b66c11cc7f87f3586d417a72ae6",
"timestamp": "",
"source": "github",
"line_count": 267,
"max_line_length": 77,
"avg_line_length": 28.9812734082397,
"alnum_prop": 0.6073920909795812,
"repo_name": "samdmarshall/SDMMobileDevice",
"id": "007fc471effc022128a72b94267229f55f18c3b3",
"size": "7738",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "openssl-0.9.8zg/fips/dsa/fips_dsa_sign.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "294020"
},
{
"name": "Batchfile",
"bytes": "77645"
},
{
"name": "C",
"bytes": "12582293"
},
{
"name": "C++",
"bytes": "444732"
},
{
"name": "DIGITAL Command Language",
"bytes": "273728"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "HTML",
"bytes": "239"
},
{
"name": "Logos",
"bytes": "108920"
},
{
"name": "M4",
"bytes": "48972"
},
{
"name": "Makefile",
"bytes": "721266"
},
{
"name": "Objective-C",
"bytes": "92185"
},
{
"name": "Perl",
"bytes": "730815"
},
{
"name": "Perl6",
"bytes": "27602"
},
{
"name": "Prolog",
"bytes": "29177"
},
{
"name": "Rebol",
"bytes": "106436"
},
{
"name": "Roff",
"bytes": "3125"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Shell",
"bytes": "170659"
},
{
"name": "XS",
"bytes": "4319"
},
{
"name": "eC",
"bytes": "4839"
}
],
"symlink_target": ""
} |
NS_ASSUME_NONNULL_BEGIN
@interface ConCommandB : AbsCommand
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "3356b3744ea31349d572943bfdd376b7",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 35,
"avg_line_length": 12.857142857142858,
"alnum_prop": 0.7888888888888889,
"repo_name": "LayZhangGitHub/LayZhangDemo",
"id": "d1101ff961a9f8993064564c5d85f7b5843a4aa7",
"size": "244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LayZhangDemo/LayZhangDemo/class/MainDemo/Design/DCommand/Imp/ConCommandB.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4268"
},
{
"name": "Objective-C",
"bytes": "2326575"
},
{
"name": "Ruby",
"bytes": "1096"
},
{
"name": "Shell",
"bytes": "11689"
},
{
"name": "Swift",
"bytes": "5136"
}
],
"symlink_target": ""
} |
<div class="overlay-container">
<span class="close"><a href="#"><img class="close-img" src="img/close.png" alt=""></a></span>
<div class="overlay-title">
<h3>Rouler serein</h3>
</div>
<div class="overlay-content-box overflow">
<div class="overlay-content">
<p>[HS Client]
Application rouler serein .jpg
Vidéo appli s/ yt
[/HS Client]
</p>
<p>Proposer à votre client de télécharger l’application « Rouler serein » gratuitement</p>
<p>Elle est disponible sur l’<a href="https://itunes.apple.com/fr/app/rouler-serein/id547607719?mt=8"> App Store</a> et <a href="https://play.google.com/store/apps/details?id=com.cronos.natixis&hl=fr">Google Play</a></p>
<p>Cette application n’est pas exclusivement réservée aux personnes assurées à la Banque Populaire des Alpes. De nombreux services sont accessibles pour tous !</p>
</div>
</div>
</div> | {
"content_hash": "53f955b55323a395aad05c04b959a083",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 232,
"avg_line_length": 49.25,
"alnum_prop": 0.6152284263959391,
"repo_name": "oXg3n/test",
"id": "432786171dd0d04cecce60dc9c96a787e8e441af",
"size": "1001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "overlay-10.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39693"
},
{
"name": "CSS",
"bytes": "49825"
},
{
"name": "HTML",
"bytes": "68691"
},
{
"name": "JavaScript",
"bytes": "8930"
},
{
"name": "PHP",
"bytes": "184"
},
{
"name": "Ruby",
"bytes": "900"
}
],
"symlink_target": ""
} |
$(python ../compute_engine_cfg.py)
if [ $? != "0" ]; then
echo "Failed to read compute_engine_cfg.py!"
exit 1
fi
# The base names of the VM instances. Actual names are VM_NAME_BASE-name
VM_NAME_BASE=${VM_NAME_BASE:="skia"}
# The name of instance where skia docs is running on.
INSTANCE_NAME=${VM_NAME_BASE}-docs
MACHINE_TYPE=n1-standard-4
DOCS_IP_ADDRESS=104.154.112.101
| {
"content_hash": "ef5a10dfadcef4bff6ebcdc28065c9fc",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 72,
"avg_line_length": 25.266666666666666,
"alnum_prop": 0.7018469656992085,
"repo_name": "Tiger66639/skia-buildbot",
"id": "7b00893c705f6ea1a2b89d6feeff7e2ac873174c",
"size": "631",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "compute_engine_scripts/docs/vm_config.sh",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "517"
},
{
"name": "C",
"bytes": "3114"
},
{
"name": "C++",
"bytes": "16606"
},
{
"name": "CSS",
"bytes": "20589"
},
{
"name": "Go",
"bytes": "1707602"
},
{
"name": "HTML",
"bytes": "911324"
},
{
"name": "JavaScript",
"bytes": "92257"
},
{
"name": "Makefile",
"bytes": "24280"
},
{
"name": "PowerShell",
"bytes": "7789"
},
{
"name": "Python",
"bytes": "318392"
},
{
"name": "Shell",
"bytes": "166456"
}
],
"symlink_target": ""
} |
/**
`JXHTTPOperationQueueDelegate` is a protocol that allows any object to receive synchronous
callbacks about the progress of a `JXHTTPOperationQueue`.
These methods may be called from different threads.
*/
@class JXHTTPOperationQueue;
@protocol JXHTTPOperationQueueDelegate <NSObject>
@optional
/**
Called when the queue adds an operation from an empty state.
@param queue The queue.
*/
- (void)httpOperationQueueWillStart:(JXHTTPOperationQueue *)queue;
/**
Called when the queue has completed all operations.
@param queue The queue.
*/
- (void)httpOperationQueueWillFinish:(JXHTTPOperationQueue *)queue;
/**
Called just after the first operation is added to the queue.
@param queue The queue.
*/
- (void)httpOperationQueueDidStart:(JXHTTPOperationQueue *)queue;
/**
Called periodically as operations in the queue upload data.
@param queue The queue.
*/
- (void)httpOperationQueueDidUpload:(JXHTTPOperationQueue *)queue;
/**
Called periodically as operations in the queue download data.
@param queue The queue.
*/
- (void)httpOperationQueueDidDownload:(JXHTTPOperationQueue *)queue;
/**
Called periodically as operations in the queue download or upload data.
@param queue The queue.
*/
- (void)httpOperationQueueDidMakeProgress:(JXHTTPOperationQueue *)queue;
/**
Called when the last operation in the queue finishes.
@param queue The queue.
*/
- (void)httpOperationQueueDidFinish:(JXHTTPOperationQueue *)queue;
@end
| {
"content_hash": "8eac9ddb3824985ad8f0bb1170793b67",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 91,
"avg_line_length": 23.983606557377048,
"alnum_prop": 0.7669172932330827,
"repo_name": "Suninus/JXHTTP",
"id": "6e7bea1ebd80c6e74319eeae22b0df44b6db4a89",
"size": "1463",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "JXHTTP/JXHTTPOperationQueueDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "775"
},
{
"name": "HTML",
"bytes": "1009"
},
{
"name": "Objective-C",
"bytes": "109579"
},
{
"name": "Ruby",
"bytes": "722"
}
],
"symlink_target": ""
} |
package org.joda.beans.sample;
import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.TypedMetaBean;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.light.LightMetaBean;
/**
* Mock light bean, used for testing.
*
* @author Stephen Colebourne
*/
@BeanDefinition(style = "light", constructorScope = "package")
public final class LightImmutableSimple implements ImmutableBean, Serializable {
/**
* The number.
*/
@PropertyDefinition
private final int number;
/**
* The text.
*/
@PropertyDefinition
private final String text;
//------------------------- AUTOGENERATED START -------------------------
/**
* The meta-bean for {@code LightImmutableSimple}.
*/
private static final TypedMetaBean<LightImmutableSimple> META_BEAN =
LightMetaBean.of(
LightImmutableSimple.class,
MethodHandles.lookup(),
new String[] {
"number",
"text"},
new Object[0]);
/**
* The meta-bean for {@code LightImmutableSimple}.
* @return the meta-bean, not null
*/
public static TypedMetaBean<LightImmutableSimple> meta() {
return META_BEAN;
}
static {
MetaBean.register(META_BEAN);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Creates an instance.
* @param number the value of the property
* @param text the value of the property
*/
LightImmutableSimple(
int number,
String text) {
this.number = number;
this.text = text;
}
@Override
public TypedMetaBean<LightImmutableSimple> metaBean() {
return META_BEAN;
}
//-----------------------------------------------------------------------
/**
* Gets the number.
* @return the value of the property
*/
public int getNumber() {
return number;
}
//-----------------------------------------------------------------------
/**
* Gets the text.
* @return the value of the property
*/
public String getText() {
return text;
}
//-----------------------------------------------------------------------
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
LightImmutableSimple other = (LightImmutableSimple) obj;
return (number == other.number) &&
JodaBeanUtils.equal(text, other.text);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(number);
hash = hash * 31 + JodaBeanUtils.hashCode(text);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("LightImmutableSimple{");
buf.append("number").append('=').append(JodaBeanUtils.toString(number)).append(',').append(' ');
buf.append("text").append('=').append(JodaBeanUtils.toString(text));
buf.append('}');
return buf.toString();
}
//-------------------------- AUTOGENERATED END --------------------------
}
| {
"content_hash": "4d61d2a920268724391252791e30236a",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 104,
"avg_line_length": 27.507575757575758,
"alnum_prop": 0.5320848251170477,
"repo_name": "JodaOrg/joda-beans",
"id": "25e6ceb38d77e30bccd113578a8cddde8a417c36",
"size": "4250",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/test/java/org/joda/beans/sample/LightImmutableSimple.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1682"
},
{
"name": "HTML",
"bytes": "153"
},
{
"name": "Java",
"bytes": "3070386"
}
],
"symlink_target": ""
} |
#include BOSS_WEBRTC_U_rtc_base__asyncinvoker_h //original-code:"rtc_base/asyncinvoker.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
namespace rtc {
AsyncInvoker::AsyncInvoker()
: pending_invocations_(0),
invocation_complete_(new RefCountedObject<Event>(false, false)),
destroying_(false) {}
AsyncInvoker::~AsyncInvoker() {
destroying_.store(true, std::memory_order_relaxed);
// Messages for this need to be cleared *before* our destructor is complete.
MessageQueueManager::Clear(this);
// And we need to wait for any invocations that are still in progress on
// other threads. Using memory_order_acquire for synchronization with
// AsyncClosure destructors.
while (pending_invocations_.load(std::memory_order_acquire) > 0) {
// If the destructor was called while AsyncInvoke was being called by
// another thread, WITHIN an AsyncInvoked functor, it may do another
// Thread::Post even after we called MessageQueueManager::Clear(this). So
// we need to keep calling Clear to discard these posts.
Thread::Current()->Clear(this);
invocation_complete_->Wait(Event::kForever);
}
}
void AsyncInvoker::OnMessage(Message* msg) {
// Get the AsyncClosure shared ptr from this message's data.
ScopedMessageData<AsyncClosure>* data =
static_cast<ScopedMessageData<AsyncClosure>*>(msg->pdata);
// Execute the closure and trigger the return message if needed.
data->inner_data().Execute();
delete data;
}
void AsyncInvoker::Flush(Thread* thread, uint32_t id /*= MQID_ANY*/) {
// If the destructor is waiting for invocations to finish, don't start
// running even more tasks.
if (destroying_.load(std::memory_order_relaxed))
return;
// Run this on |thread| to reduce the number of context switches.
if (Thread::Current() != thread) {
thread->Invoke<void>(RTC_FROM_HERE,
Bind(&AsyncInvoker::Flush, this, thread, id));
return;
}
MessageList removed;
thread->Clear(this, id, &removed);
for (MessageList::iterator it = removed.begin(); it != removed.end(); ++it) {
// This message was pending on this thread, so run it now.
thread->Send(it->posted_from, it->phandler, it->message_id, it->pdata);
}
}
void AsyncInvoker::Clear() {
MessageQueueManager::Clear(this);
}
void AsyncInvoker::DoInvoke(const Location& posted_from,
Thread* thread,
std::unique_ptr<AsyncClosure> closure,
uint32_t id) {
if (destroying_.load(std::memory_order_relaxed)) {
// Note that this may be expected, if the application is AsyncInvoking
// tasks that AsyncInvoke other tasks. But otherwise it indicates a race
// between a thread destroying the AsyncInvoker and a thread still trying
// to use it.
RTC_LOG(LS_WARNING) << "Tried to invoke while destroying the invoker.";
return;
}
thread->Post(posted_from, this, id,
new ScopedMessageData<AsyncClosure>(std::move(closure)));
}
void AsyncInvoker::DoInvokeDelayed(const Location& posted_from,
Thread* thread,
std::unique_ptr<AsyncClosure> closure,
uint32_t delay_ms,
uint32_t id) {
if (destroying_.load(std::memory_order_relaxed)) {
// See above comment.
RTC_LOG(LS_WARNING) << "Tried to invoke while destroying the invoker.";
return;
}
thread->PostDelayed(posted_from, delay_ms, this, id,
new ScopedMessageData<AsyncClosure>(std::move(closure)));
}
GuardedAsyncInvoker::GuardedAsyncInvoker() : thread_(Thread::Current()) {
thread_->SignalQueueDestroyed.connect(this,
&GuardedAsyncInvoker::ThreadDestroyed);
}
GuardedAsyncInvoker::~GuardedAsyncInvoker() {}
bool GuardedAsyncInvoker::Flush(uint32_t id) {
CritScope cs(&crit_);
if (thread_ == nullptr)
return false;
invoker_.Flush(thread_, id);
return true;
}
void GuardedAsyncInvoker::ThreadDestroyed() {
CritScope cs(&crit_);
// We should never get more than one notification about the thread dying.
RTC_DCHECK(thread_ != nullptr);
thread_ = nullptr;
}
AsyncClosure::AsyncClosure(AsyncInvoker* invoker)
: invoker_(invoker), invocation_complete_(invoker_->invocation_complete_) {
invoker_->pending_invocations_.fetch_add(1, std::memory_order_relaxed);
}
AsyncClosure::~AsyncClosure() {
// Using memory_order_release for synchronization with the AsyncInvoker
// destructor.
invoker_->pending_invocations_.fetch_sub(1, std::memory_order_release);
// After |pending_invocations_| is decremented, we may need to signal
// |invocation_complete_| in case the AsyncInvoker is being destroyed and
// waiting for pending tasks to complete.
//
// It's also possible that the destructor finishes before "Set()" is called,
// which is safe because the event is reference counted (and in a thread-safe
// way).
invocation_complete_->Set();
}
} // namespace rtc
| {
"content_hash": "0318db4c0f9d6b1f0f79a9811659d457",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 89,
"avg_line_length": 37.52173913043478,
"alnum_prop": 0.671687910390112,
"repo_name": "koobonil/Boss2D",
"id": "dcbc5b5b5327c9987613e1fd809b1675b5fcbb3d",
"size": "5586",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/asyncinvoker.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "4820445"
},
{
"name": "Awk",
"bytes": "4272"
},
{
"name": "Batchfile",
"bytes": "89930"
},
{
"name": "C",
"bytes": "119747922"
},
{
"name": "C#",
"bytes": "87505"
},
{
"name": "C++",
"bytes": "272329620"
},
{
"name": "CMake",
"bytes": "1199656"
},
{
"name": "CSS",
"bytes": "42679"
},
{
"name": "Clojure",
"bytes": "1487"
},
{
"name": "Cuda",
"bytes": "1651996"
},
{
"name": "DIGITAL Command Language",
"bytes": "239527"
},
{
"name": "Dockerfile",
"bytes": "9638"
},
{
"name": "Emacs Lisp",
"bytes": "15570"
},
{
"name": "Go",
"bytes": "858185"
},
{
"name": "HLSL",
"bytes": "3314"
},
{
"name": "HTML",
"bytes": "2958385"
},
{
"name": "Java",
"bytes": "2921052"
},
{
"name": "JavaScript",
"bytes": "178190"
},
{
"name": "Jupyter Notebook",
"bytes": "1833654"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "M4",
"bytes": "775724"
},
{
"name": "MATLAB",
"bytes": "74606"
},
{
"name": "Makefile",
"bytes": "3941551"
},
{
"name": "Meson",
"bytes": "2847"
},
{
"name": "Module Management System",
"bytes": "2626"
},
{
"name": "NSIS",
"bytes": "4505"
},
{
"name": "Objective-C",
"bytes": "4090702"
},
{
"name": "Objective-C++",
"bytes": "1702390"
},
{
"name": "PHP",
"bytes": "3530"
},
{
"name": "Perl",
"bytes": "11096338"
},
{
"name": "Perl 6",
"bytes": "11802"
},
{
"name": "PowerShell",
"bytes": "38571"
},
{
"name": "Python",
"bytes": "24123805"
},
{
"name": "QMake",
"bytes": "18188"
},
{
"name": "Roff",
"bytes": "1261269"
},
{
"name": "Ruby",
"bytes": "5890"
},
{
"name": "Scala",
"bytes": "5683"
},
{
"name": "Shell",
"bytes": "2879948"
},
{
"name": "TeX",
"bytes": "243507"
},
{
"name": "TypeScript",
"bytes": "1593696"
},
{
"name": "Verilog",
"bytes": "1215"
},
{
"name": "Vim Script",
"bytes": "3759"
},
{
"name": "Visual Basic",
"bytes": "16186"
},
{
"name": "eC",
"bytes": "9705"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "0edf70263bfb9cad2a2979f9d38adb82",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "b9862c191f195aa9929d08d1339978df464a74a3",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus gracilipes/ Syn. Phyllanthus hullettii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* 作者:黄鑫
* 日期:2013-04-01
* 描述:左侧组织机构树
*/
define(["dojo/_base/declare",
"capec/EnhancedTree",
"dijit/tree/ForestStoreModel",
"dojo/_base/lang",
"dojo/_base/connect",
"capec/utils/ajax",
"capec/utils/toTreeObj",
"dojo/data/ItemFileWriteStore",
"dijit/layout/ContentPane"], function($declare, $Tree, $ForestStoreModel, $lang, $connect, $ajax, $toTreeObj, $ItemFileWriteStore, $ContentPane) {
return $declare($ContentPane, {
vpath: "",
_gridStore: null,
_store: null,
_searchForm: null,
style: { "background-color": "red" },
bindStore: function($store){
this._store = $store;
this._store.bindTree(this);
},
bindGridStore: function($gridStore){
this._gridStore = $gridStore;
this._gridStore.bindTree(this);
},
bindSearchForm: function($searchForm){
this._searchForm = $searchForm;
},
constructor: function(){
this.inherited(arguments);
if(arguments.vpath) this.vpath = arguments.vpath;
},
postCreate : function() {
this.inherited(arguments);
console.log(8888);
this._loadData();
},
_loadData: function(){
$ajax({
async : false,
url : "../../testData/org.json",
callback : $lang.hitch(this, "_onDataLoaded")
});
},
_onDataLoaded: function($data){
var __items = $toTreeObj($data,0,{
identifier: "id",
fidentifier: "p_id",
label: "orgname"
}).children;
this._store = new $ItemFileWriteStore({
data: {
identifier: "id",
label: "orgname",
items: __items == undefined ? [] : __items
}
});
this.setStore(this._store);
},
startup:function(){
this.inherited(arguments);
},
_addEvents: function(){
this._connect1 = $connect.connect(this._tree, "onSelected", this, "_onSelectedItem");
},
_onSelectedItem: function($item){
// this._gridStore.loadData($item.id);
// this._searchForm.reset();
},
_addTree: function($store){
this._tree = new $Tree({
showRoot: true,
openOnDblClick: true,
keepSelection: true,
defaultOpen: true,
rowSelector: true,
style: { height: "100%", margin: 0, padding: 0 },
model: new $ForestStoreModel({
store: $store,
query: { type: "org" },
rootId: "0",
rootLabel: "郑州新开普电子股份有限公司",
childrenAttrs: [ "children" ]
})
},document.createElement("div"));
this.domNode.appendChild(this._tree.domNode);
},
setStore: function($store){
if($store != null) {
this._addTree($store);
this._addEvents();
this._tree.set("path", ["0"]);
}
},
getSelectedItem: function(){
return this._tree.selectedItem;
},
_removeHandles: function(){
this._connect1.remove();
},
destroy: function(){
this._removeHandles();
this.destroyDescendants();
this.inherited(arguments);
}
});
}); | {
"content_hash": "464f01f35914b31566c6c6e89ac8e347",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 147,
"avg_line_length": 24.589285714285715,
"alnum_prop": 0.620551924473493,
"repo_name": "3203317/2013",
"id": "7cdaf8225159f7455e1a5564f5db134de3de2b83",
"size": "2816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dojo-cppt/widgets/tree/OrgTree.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "298893"
},
{
"name": "CSS",
"bytes": "2478429"
},
{
"name": "ColdFusion",
"bytes": "864115"
},
{
"name": "Java",
"bytes": "2182264"
},
{
"name": "JavaScript",
"bytes": "26272909"
},
{
"name": "Lasso",
"bytes": "122535"
},
{
"name": "PHP",
"bytes": "471940"
},
{
"name": "Perl",
"bytes": "282121"
},
{
"name": "Python",
"bytes": "266343"
},
{
"name": "Shell",
"bytes": "154"
}
],
"symlink_target": ""
} |
nova-manage instance_type create m1.xsmall 1024 1 10 0 0 0
# Show instance types
nova-manage instance_type list | {
"content_hash": "205cc9b7008edfd0839336b9d12f8915",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 58,
"avg_line_length": 28,
"alnum_prop": 0.7946428571428571,
"repo_name": "alrokayan/hadoop-openstack-centos",
"id": "69f6937d68f3adbf60a40a57ae511510d4a2f467",
"size": "730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01-centos-openstack/04-add-instance-type.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4413"
},
{
"name": "Shell",
"bytes": "39013"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<config>
<luceneMatchVersion>7.0.0</luceneMatchVersion>
<directoryFactory name="DirectoryFactory" class="solr.RAMDirectoryFactory" />
<dataDir>${solr.core0.data.dir:}</dataDir>
<schemaFactory class="ClassicIndexSchemaFactory" />
<indexConfig>
<!-- Needed for RAMDirectoryFactory -->
<lockType>single</lockType>
</indexConfig>
<updateHandler class="solr.DirectUpdateHandler2" />
<requestDispatcher handleSelect="false">
<requestParsers enableRemoteStreaming="false"
multipartUploadLimitInKB="2048" formdataUploadLimitInKB="2048" />
</requestDispatcher>
<requestHandler name="/select" class="solr.SearchHandler">
<lst name="defaults">
<str name="echoParams">all</str>
<int name="rows">10</int>
<str name="df">id</str>
</lst>
<arr name="last-components">
<str>spellcheck</str>
</arr>
</requestHandler>
<requestHandler name="/analysis/field" startup="lazy"
class="solr.FieldAnalysisRequestHandler" />
<searchComponent name="query" class="querqy.solr.QuerqyQueryComponent"/>
<searchComponent name="spellcheck" class="solr.SpellCheckComponent">
<str name="queryAnalyzerFieldType">text</str>
<lst name="spellchecker">
<str name="name">default</str>
<str name="field">f1</str>
<str name="classname">solr.DirectSolrSpellChecker</str>
<str name="distanceMeasure">internal</str>
<float name="accuracy">0.5</float>
<int name="minPrefix">1</int>
</lst>
</searchComponent>
<requestHandler name="/querqy/rewriter" class="querqy.solr.QuerqyRewriterRequestHandler" />
<queryParser name="querqy" class="querqy.solr.QuerqyDismaxQParserPlugin">
<lst name="parser">
<str name="factory">querqy.solr.SimpleQuerqyQParserFactory</str>
<str name="class">querqy.parser.WhiteSpaceQuerqyParser</str>
</lst>
</queryParser>
<admin>
<defaultQuery>solr</defaultQuery>
</admin>
</config>
| {
"content_hash": "46807db5f1a05f69ec93845d7cd52762",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 92,
"avg_line_length": 28.5,
"alnum_prop": 0.7084623323013416,
"repo_name": "shopping24/querqy",
"id": "5dc7b132fb55169a0e7ed14fb05c642d491abbb3",
"size": "1938",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "querqy-for-lucene/querqy-solr/src/test/resources/solr/collection1/conf/solrconfig.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1367"
},
{
"name": "Java",
"bytes": "271356"
}
],
"symlink_target": ""
} |
import State from "../utils/state";
export default State.extend({
enter(manager) {
this.focusIn(manager);
},
focusIn(manager) {
manager.get("input").selectPeriod();
},
left(manager) {
manager.transitionTo("minutes");
},
up(manager) {
manager.get("input").togglePeriod();
},
down(manager) {
manager.get("input").togglePeriod();
},
// TODO - intl
key(manager, code) {
switch (code) {
case 'A'.charCodeAt(0):
manager.get("input").changePeriod("am");
break;
case 'P'.charCodeAt(0):
manager.get("input").changePeriod("pm");
break;
}
}
});
| {
"content_hash": "3dcb550b1e2ffd71f122b11eacf2c237",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 48,
"avg_line_length": 17.75,
"alnum_prop": 0.568075117370892,
"repo_name": "minutebase/ember-time-field",
"id": "a4e2389647e066a089a5617f9d368ab9f0589f20",
"size": "639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/states/period-focused.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34"
},
{
"name": "HTML",
"bytes": "2044"
},
{
"name": "JavaScript",
"bytes": "23309"
}
],
"symlink_target": ""
} |
namespace blink {
enum class WebOriginTrialTokenStatus;
// This interface abstracts the task of validating a token for an experimental
// feature. Experimental features can be turned on and off at runtime for a
// specific renderer, depending on the presence of a valid token provided by
// the origin.
//
// For more information, see https://github.com/jpchase/OriginTrials.
class WebTrialTokenValidator {
public:
virtual ~WebTrialTokenValidator() {}
// Returns true if the given token is valid for the specified origin and
// feature name.
virtual WebOriginTrialTokenStatus validateToken(const WebString& token, const WebSecurityOrigin&, const WebString& featureName) = 0;
};
} // namespace blink
#endif // WebTrialTokenValidator_h
| {
"content_hash": "d9c9d6a666d22c298f7e6360fea9a27b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 136,
"avg_line_length": 32.869565217391305,
"alnum_prop": 0.7658730158730159,
"repo_name": "axinging/chromium-crosswalk",
"id": "9b7860c4ea5877e309d32c42fed988aa936c8506",
"size": "1118",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "third_party/WebKit/public/platform/WebTrialTokenValidator.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "8242"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "23945"
},
{
"name": "C",
"bytes": "4103204"
},
{
"name": "C++",
"bytes": "225022948"
},
{
"name": "CSS",
"bytes": "949808"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Go",
"bytes": "18155"
},
{
"name": "HTML",
"bytes": "28206993"
},
{
"name": "Java",
"bytes": "7651204"
},
{
"name": "JavaScript",
"bytes": "18831169"
},
{
"name": "Makefile",
"bytes": "96270"
},
{
"name": "Objective-C",
"bytes": "1228122"
},
{
"name": "Objective-C++",
"bytes": "7563676"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "418221"
},
{
"name": "Python",
"bytes": "7855597"
},
{
"name": "Shell",
"bytes": "472586"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
} |
from django.conf.urls import url, patterns
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from server.views import (SubscribeViewWithFormValidation, SubscribeViewWithModelForm,
SubscribeViewWithModelFormAndValidation, Ng3WayDataBindingView, NgFormDataValidView)
urlpatterns = patterns('',
url(r'^form_validation/$', SubscribeViewWithFormValidation.as_view(),
name='djng_form_validation'),
url(r'^model_form/$', SubscribeViewWithModelForm.as_view(),
name='djng_model_form'),
url(r'^model_form_validation/$', SubscribeViewWithModelFormAndValidation.as_view(),
name='djng_model_form_validation'),
url(r'^threeway_databinding/$', Ng3WayDataBindingView.as_view(),
name='djng_3way_databinding'),
url(r'^form_data_valid', NgFormDataValidView.as_view(), name='form_data_valid'),
url(r'^$', RedirectView.as_view(url=reverse_lazy('djng_form_validation'))),
)
| {
"content_hash": "2d7e31a469286ec84a25502139827294",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 92,
"avg_line_length": 50.73684210526316,
"alnum_prop": 0.7406639004149378,
"repo_name": "jinankjain/django-angular",
"id": "76b96fe8d572fa0a82bd75da081ebcab8e5564ec",
"size": "988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/server/urls.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.docksidestage.compatible10x.dbflute.cbean.cq.bs;
import java.util.Map;
import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.docksidestage.compatible10x.dbflute.cbean.cq.ciq.*;
import org.docksidestage.compatible10x.dbflute.cbean.*;
import org.docksidestage.compatible10x.dbflute.cbean.cq.*;
/**
* The base condition-query of REGION.
* @author DBFlute(AutoGenerator)
*/
public class BsRegionCQ extends AbstractBsRegionCQ {
// ===================================================================================
// Attribute
// =========
protected RegionCIQ _inlineQuery;
// ===================================================================================
// Constructor
// ===========
public BsRegionCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(referrerQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// InlineView/OrClause
// ===================
/**
* Prepare InlineView query. <br>
* {select ... from ... left outer join (select * from REGION) where FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">inline()</span>.setFoo...;
* </pre>
* @return The condition-query for InlineView query. (NotNull)
*/
public RegionCIQ inline() {
if (_inlineQuery == null) { _inlineQuery = xcreateCIQ(); }
_inlineQuery.xsetOnClause(false); return _inlineQuery;
}
protected RegionCIQ xcreateCIQ() {
RegionCIQ ciq = xnewCIQ();
ciq.xsetBaseCB(_baseCB);
return ciq;
}
protected RegionCIQ xnewCIQ() {
return new RegionCIQ(xgetReferrerQuery(), xgetSqlClause(), xgetAliasName(), xgetNestLevel(), this);
}
/**
* Prepare OnClause query. <br>
* {select ... from ... left outer join REGION on ... and FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">on()</span>.setFoo...;
* </pre>
* @return The condition-query for OnClause query. (NotNull)
* @throws IllegalConditionBeanOperationException When this condition-query is base query.
*/
public RegionCIQ on() {
if (isBaseQuery()) { throw new IllegalConditionBeanOperationException("OnClause for local table is unavailable!"); }
RegionCIQ inlineQuery = inline(); inlineQuery.xsetOnClause(true); return inlineQuery;
}
// ===================================================================================
// Query
// =====
protected ConditionValue _regionId;
public ConditionValue xdfgetRegionId()
{ if (_regionId == null) { _regionId = nCV(); }
return _regionId; }
protected ConditionValue xgetCValueRegionId() { return xdfgetRegionId(); }
public Map<String, MemberAddressCQ> xdfgetRegionId_ExistsReferrer_MemberAddressList() { return xgetSQueMap("regionId_ExistsReferrer_MemberAddressList"); }
public String keepRegionId_ExistsReferrer_MemberAddressList(MemberAddressCQ sq) { return xkeepSQue("regionId_ExistsReferrer_MemberAddressList", sq); }
public Map<String, MemberAddressCQ> xdfgetRegionId_NotExistsReferrer_MemberAddressList() { return xgetSQueMap("regionId_NotExistsReferrer_MemberAddressList"); }
public String keepRegionId_NotExistsReferrer_MemberAddressList(MemberAddressCQ sq) { return xkeepSQue("regionId_NotExistsReferrer_MemberAddressList", sq); }
public Map<String, MemberAddressCQ> xdfgetRegionId_SpecifyDerivedReferrer_MemberAddressList() { return xgetSQueMap("regionId_SpecifyDerivedReferrer_MemberAddressList"); }
public String keepRegionId_SpecifyDerivedReferrer_MemberAddressList(MemberAddressCQ sq) { return xkeepSQue("regionId_SpecifyDerivedReferrer_MemberAddressList", sq); }
public Map<String, MemberAddressCQ> xdfgetRegionId_QueryDerivedReferrer_MemberAddressList() { return xgetSQueMap("regionId_QueryDerivedReferrer_MemberAddressList"); }
public String keepRegionId_QueryDerivedReferrer_MemberAddressList(MemberAddressCQ sq) { return xkeepSQue("regionId_QueryDerivedReferrer_MemberAddressList", sq); }
public Map<String, Object> xdfgetRegionId_QueryDerivedReferrer_MemberAddressListParameter() { return xgetSQuePmMap("regionId_QueryDerivedReferrer_MemberAddressList"); }
public String keepRegionId_QueryDerivedReferrer_MemberAddressListParameter(Object pm) { return xkeepSQuePm("regionId_QueryDerivedReferrer_MemberAddressList", pm); }
/**
* Add order-by as ascend. <br>
* (地域ID)REGION_ID: {PK, NotNull, INTEGER(10), classification=Region}
* @return this. (NotNull)
*/
public BsRegionCQ addOrderBy_RegionId_Asc() { regOBA("REGION_ID"); return this; }
/**
* Add order-by as descend. <br>
* (地域ID)REGION_ID: {PK, NotNull, INTEGER(10), classification=Region}
* @return this. (NotNull)
*/
public BsRegionCQ addOrderBy_RegionId_Desc() { regOBD("REGION_ID"); return this; }
protected ConditionValue _regionName;
public ConditionValue xdfgetRegionName()
{ if (_regionName == null) { _regionName = nCV(); }
return _regionName; }
protected ConditionValue xgetCValueRegionName() { return xdfgetRegionName(); }
/**
* Add order-by as ascend. <br>
* (地域名称)REGION_NAME: {NotNull, VARCHAR(50)}
* @return this. (NotNull)
*/
public BsRegionCQ addOrderBy_RegionName_Asc() { regOBA("REGION_NAME"); return this; }
/**
* Add order-by as descend. <br>
* (地域名称)REGION_NAME: {NotNull, VARCHAR(50)}
* @return this. (NotNull)
*/
public BsRegionCQ addOrderBy_RegionName_Desc() { regOBD("REGION_NAME"); return this; }
// ===================================================================================
// SpecifiedDerivedOrderBy
// =======================
/**
* Add order-by for specified derived column as ascend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] asc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Asc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsRegionCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }
/**
* Add order-by for specified derived column as descend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] desc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Desc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsRegionCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }
// ===================================================================================
// Union Query
// ===========
public void reflectRelationOnUnionQuery(ConditionQuery bqs, ConditionQuery uqs) {
}
// ===================================================================================
// Foreign Query
// =============
protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String property) {
return null;
}
// ===================================================================================
// ScalarCondition
// ===============
public Map<String, RegionCQ> xdfgetScalarCondition() { return xgetSQueMap("scalarCondition"); }
public String keepScalarCondition(RegionCQ sq) { return xkeepSQue("scalarCondition", sq); }
// ===================================================================================
// MyselfDerived
// =============
public Map<String, RegionCQ> xdfgetSpecifyMyselfDerived() { return xgetSQueMap("specifyMyselfDerived"); }
public String keepSpecifyMyselfDerived(RegionCQ sq) { return xkeepSQue("specifyMyselfDerived", sq); }
public Map<String, RegionCQ> xdfgetQueryMyselfDerived() { return xgetSQueMap("queryMyselfDerived"); }
public String keepQueryMyselfDerived(RegionCQ sq) { return xkeepSQue("queryMyselfDerived", sq); }
public Map<String, Object> xdfgetQueryMyselfDerivedParameter() { return xgetSQuePmMap("queryMyselfDerived"); }
public String keepQueryMyselfDerivedParameter(Object pm) { return xkeepSQuePm("queryMyselfDerived", pm); }
// ===================================================================================
// MyselfExists
// ============
protected Map<String, RegionCQ> _myselfExistsMap;
public Map<String, RegionCQ> xdfgetMyselfExists() { return xgetSQueMap("myselfExists"); }
public String keepMyselfExists(RegionCQ sq) { return xkeepSQue("myselfExists", sq); }
// ===================================================================================
// MyselfInScope
// =============
public Map<String, RegionCQ> xdfgetMyselfInScope() { return xgetSQueMap("myselfInScope"); }
public String keepMyselfInScope(RegionCQ sq) { return xkeepSQue("myselfInScope", sq); }
// ===================================================================================
// Very Internal
// =============
// very internal (for suppressing warn about 'Not Use Import')
protected String xCB() { return RegionCB.class.getName(); }
protected String xCQ() { return RegionCQ.class.getName(); }
protected String xCHp() { return HpQDRFunction.class.getName(); }
protected String xCOp() { return ConditionOption.class.getName(); }
protected String xMap() { return Map.class.getName(); }
}
| {
"content_hash": "7e8bcdf4664e102e25aff480697ea89f",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 174,
"avg_line_length": 56.11926605504587,
"alnum_prop": 0.5335131600457741,
"repo_name": "dbflute-test/dbflute-test-option-compatible10x",
"id": "759cb0885b9b2eada47ec1841207b8d5f98c85a6",
"size": "12877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/docksidestage/compatible10x/dbflute/cbean/cq/bs/BsRegionCQ.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "42349"
},
{
"name": "HTML",
"bytes": "42250"
},
{
"name": "Java",
"bytes": "8310649"
},
{
"name": "PLpgSQL",
"bytes": "848"
},
{
"name": "Perl",
"bytes": "9821"
},
{
"name": "Python",
"bytes": "3285"
},
{
"name": "Roff",
"bytes": "105"
},
{
"name": "Shell",
"bytes": "28618"
},
{
"name": "XSLT",
"bytes": "218435"
}
],
"symlink_target": ""
} |
package leap.web.api.meta.model;
import leap.core.security.SimpleSecurity;
import leap.lang.Arrays2;
import leap.lang.Builders;
import leap.lang.http.HTTP;
import leap.web.api.spec.swagger.SwaggerConstants;
import leap.web.route.Route;
import java.util.*;
public class MApiOperationBuilder extends MApiNamedWithDescBuilder<MApiOperation> {
protected String id;
protected Route route;
protected HTTP.Method method;
protected Set<String> tags = new LinkedHashSet<>();
protected List<MApiParameterBuilder> parameters = new ArrayList<>();
protected List<MApiResponseBuilder> responses = new ArrayList<>();
protected Set<String> consumes = new LinkedHashSet<>();
protected Set<String> produces = new LinkedHashSet<>();
protected Map<String, MApiSecurityReq> security = new HashMap<>();
protected MApiExtension extension;
protected boolean allowAnonymous;
protected boolean allowClientOnly;
protected String[] permissions;
protected SimpleSecurity[] securities;
protected boolean deprecated;
protected Boolean CorsEnabled;
public MApiOperationBuilder() {
}
public MApiOperationBuilder(Route route) {
this.route = route;
MApiSecurityReq[] securities = route.getExtension(MApiSecurityReq[].class);
if(null != securities) {
for(MApiSecurityReq security : securities) {
this.security.put(security.getName(), security);
}
}else {
if(!security.containsKey(SwaggerConstants.OAUTH2)){
MApiSecurityReq sec = new MApiSecurityReq(SwaggerConstants.OAUTH2);
security.put(sec.getName(), sec);
}
if(route.getPermissions() != null){
security.get(SwaggerConstants.OAUTH2).addScopes(route.getPermissions());
}
}
if(null != route.getAllowAnonymous()) {
this.allowAnonymous = route.getAllowAnonymous();
}
if(null != route.getAllowClientOnly()){
this.allowClientOnly = route.getAllowClientOnly();
}
this.extension = route.getExtension(MApiExtension.class);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public HTTP.Method getMethod() {
return method;
}
public MApiOperationBuilder setMethod(HTTP.Method method) {
this.method = method;
return this;
}
public Set<String> getTags() {
return tags;
}
public void addTag(String tag){
tags.add(tag);
}
public List<MApiParameterBuilder> getParameters() {
return parameters;
}
public MApiParameterBuilder getParameter(String name) {
for(MApiParameterBuilder p : parameters) {
if(p.getName().equals(name)) {
return p;
}
}
return null;
}
public void addParameter(MApiParameterBuilder p) {
parameters.add(p);
}
public List<MApiResponseBuilder> getResponses() {
return responses;
}
public MApiResponseBuilder getResponse(String name) {
for(MApiResponseBuilder r : responses) {
if(r.getName().equals(name)) {
return r;
}
}
return null;
}
public void addResponse(MApiResponseBuilder r) {
responses.add(r);
}
public Set<String> getConsumes() {
return consumes;
}
public void addConsume(String mimeType){
consumes.add(mimeType);
}
public Set<String> getProduces() {
return produces;
}
public void addProduce(String mimeType) {
produces.add(mimeType);
}
public Map<String, MApiSecurityReq> getSecurity() {
return security;
}
public void setSecurity(Map<String, MApiSecurityReq> security) {
this.security = security;
}
public void addSecurityRequirement(MApiSecurityReq req) {
this.security.put(req.getName(), req);
}
public boolean isDeprecated() {
return deprecated;
}
public void setDeprecated(boolean deprecated) {
this.deprecated = deprecated;
}
public boolean isAllowAnonymous() {
return allowAnonymous;
}
public void setAllowAnonymous(boolean allowAnonymous) {
this.allowAnonymous = allowAnonymous;
}
public boolean isAllowClientOnly() {
return allowClientOnly;
}
public void setAllowClientOnly(boolean allowClientOnly) {
this.allowClientOnly = allowClientOnly;
}
public String[] getPermissions() {
return permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public SimpleSecurity[] getSecurities() {
return securities;
}
public void setSecurities(SimpleSecurity[] securities) {
this.securities = securities;
}
public Boolean getCorsEnabled() {
return CorsEnabled;
}
public void setCorsEnabled(Boolean corsEnabled) {
this.CorsEnabled = corsEnabled;
}
public MApiExtension getExtension() {
return extension;
}
public void setExtension(MApiExtension extension) {
this.extension = extension;
}
@Override
public MApiOperation build() {
return new MApiOperation(id, name, title, summary, description, method,route,
tags.toArray(Arrays2.EMPTY_STRING_ARRAY),
Builders.buildList(parameters),
Builders.buildList(responses),
consumes.toArray(Arrays2.EMPTY_STRING_ARRAY),
produces.toArray(Arrays2.EMPTY_STRING_ARRAY),
security.values().toArray(new MApiSecurityReq[security.size()]),
allowAnonymous,
allowClientOnly,
deprecated, CorsEnabled, attrs, extension);
}
}
| {
"content_hash": "5869cadb1db691bc9536fe8f7e4f5ee3",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 96,
"avg_line_length": 26.484848484848484,
"alnum_prop": 0.6234063419418111,
"repo_name": "leapframework/framework",
"id": "fcbd464825df95f92f935f1cc9cca67b16dadf87",
"size": "6734",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "web/api/src/main/java/leap/web/api/meta/model/MApiOperationBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "355"
},
{
"name": "HTML",
"bytes": "645766"
},
{
"name": "Java",
"bytes": "13020209"
},
{
"name": "JavaScript",
"bytes": "167"
},
{
"name": "PLSQL",
"bytes": "30834"
},
{
"name": "Shell",
"bytes": "66"
}
],
"symlink_target": ""
} |
package php.runtime.invoke;
import php.runtime.Memory;
import php.runtime.common.Messages;
import php.runtime.env.Environment;
import php.runtime.env.TraceInfo;
import php.runtime.lang.IObject;
import php.runtime.memory.ObjectMemory;
import php.runtime.reflection.ClassEntity;
import php.runtime.reflection.MethodEntity;
import php.runtime.reflection.ParameterEntity;
public class DynamicMethodInvoker extends Invoker {
protected final IObject object;
protected final MethodEntity method;
public DynamicMethodInvoker(Environment env, TraceInfo trace, IObject object, MethodEntity method) {
super(env, trace);
this.object = object;
this.method = method;
}
@Override
public ParameterEntity[] getParameters() {
return method.getParameters();
}
@Override
public String getName() {
return object.getReflection().getName() + "::" + method.getName();
}
public IObject getObject() {
return object;
}
public MethodEntity getMethod() {
return method;
}
@Override
public int getArgumentCount() {
return method.getParameters() == null ? 0 : method.getParameters().length;
}
@Override
public void pushCall(TraceInfo trace, Memory[] args) {
env.pushCall(trace, object, args,
method.getName(),
method.getClazz().getName(),
object.getReflection().getName()
);
}
@Override
protected Memory invoke(Memory... args) throws Throwable {
return ObjectInvokeHelper.invokeMethod(
object, method, env, trace == null ? TraceInfo.UNKNOWN : trace, args, false
);
}
@Override
public int canAccess(Environment env) {
return method.canAccess(env);
}
public static DynamicMethodInvoker valueOf(Environment env, TraceInfo trace, IObject object, String methodName){
String methodNameL = methodName.toLowerCase();
int pos;
MethodEntity methodEntity;
if ((pos = methodName.indexOf("::")) > -1){
String className = methodNameL.substring(0, pos);
methodNameL = methodNameL.substring(pos + 2);
ClassEntity classEntity = object.getReflection();
ClassEntity clazz = env.fetchClass(methodName.substring(0, pos), className, false);
if (!classEntity.isInstanceOf(clazz)){
return null;
}
methodEntity = clazz.findMethod(methodNameL);
} else
methodEntity = object.getReflection().findMethod(methodNameL);
if (methodEntity == null){
if (object.getReflection().methodMagicCall != null) {
return new MagicDynamicMethodInvoker(
env, trace, object, object.getReflection().methodMagicCall, methodName
);
}
if (trace == null) {
return null;
}
env.error(trace, Messages.ERR_CALL_TO_UNDEFINED_METHOD.fetch(object.getReflection().getName() + "::" + methodName));
}
return new DynamicMethodInvoker(env, trace, object, methodEntity);
}
public static DynamicMethodInvoker valueOf(Environment env, TraceInfo trace, Memory object, String methodName){
return valueOf(env, trace, ((ObjectMemory)object).value, methodName);
}
public static DynamicMethodInvoker valueOf(Environment env, TraceInfo trace, IObject object){
MethodEntity methodEntity = object.getReflection().methodMagicInvoke;
if (methodEntity == null){
if (trace == null)
return null;
env.error(trace, Messages.ERR_CALL_TO_UNDEFINED_METHOD.fetch(object.getReflection().getName() + "::__invoke"));
}
return new DynamicMethodInvoker(env, null, object, methodEntity);
}
public static DynamicMethodInvoker valueOf(Environment env, TraceInfo trace, Memory object){
return valueOf(env, trace, ((ObjectMemory)object).value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DynamicMethodInvoker)) return false;
DynamicMethodInvoker that = (DynamicMethodInvoker) o;
return method.equals(that.method) && object.getPointer() == that.object.getPointer();
}
@Override
public int hashCode() {
int result = object.hashCode();
result = 31 * result + method.hashCode();
return result;
}
}
| {
"content_hash": "dfcbf604f20a9c0f0c03995ed685cef5",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 128,
"avg_line_length": 33.48148148148148,
"alnum_prop": 0.6373893805309735,
"repo_name": "livingvirus/jphp",
"id": "1b9b44cc5f22804b8f0f8876ae54cf8edc3a6e8f",
"size": "4520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jphp-runtime/src/php/runtime/invoke/DynamicMethodInvoker.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "112"
},
{
"name": "C++",
"bytes": "510"
},
{
"name": "Groovy",
"bytes": "14969"
},
{
"name": "HTML",
"bytes": "4169"
},
{
"name": "Java",
"bytes": "3522396"
},
{
"name": "PHP",
"bytes": "1129715"
},
{
"name": "Shell",
"bytes": "441"
},
{
"name": "SourcePawn",
"bytes": "90"
}
],
"symlink_target": ""
} |
namespace http = process::http;
namespace slave = mesos::internal::slave;
using std::list;
using std::string;
using std::vector;
using google::protobuf::Map;
using mesos::csi::state::VolumeState;
using process::Break;
using process::Continue;
using process::ControlFlow;
using process::Failure;
using process::Future;
using process::Owned;
using process::ProcessBase;
using process::grpc::StatusError;
using process::grpc::client::Runtime;
namespace mesos{
namespace csi {
namespace v1 {
VolumeManagerProcess::VolumeManagerProcess(
const string& _rootDir,
const CSIPluginInfo& _info,
const hashset<Service> _services,
const Runtime& _runtime,
ServiceManager* _serviceManager,
Metrics* _metrics)
: ProcessBase(process::ID::generate("csi-v1-volume-manager")),
rootDir(_rootDir),
info(_info),
services(_services),
runtime(_runtime),
serviceManager(_serviceManager),
metrics(_metrics)
{
// This should have been validated in `VolumeManager::create`.
CHECK(!services.empty())
<< "Must specify at least one service for CSI plugin type '" << info.type()
<< "' and name '" << info.name() << "'";
}
Future<Nothing> VolumeManagerProcess::recover()
{
Try<string> bootId_ = os::bootId();
if (bootId_.isError()) {
return Failure("Failed to get boot ID: " + bootId_.error());
}
bootId = bootId_.get();
return prepareServices()
.then(process::defer(self(), [this]() -> Future<Nothing> {
// Recover the states of CSI volumes.
Try<list<string>> volumePaths =
paths::getVolumePaths(rootDir, info.type(), info.name());
if (volumePaths.isError()) {
return Failure(
"Failed to find volumes for CSI plugin type '" + info.type() +
"' and name '" + info.name() + "': " + volumePaths.error());
}
vector<Future<Nothing>> futures;
foreach (const string& path, volumePaths.get()) {
Try<paths::VolumePath> volumePath =
paths::parseVolumePath(rootDir, path);
if (volumePath.isError()) {
return Failure(
"Failed to parse volume path '" + path +
"': " + volumePath.error());
}
CHECK_EQ(info.type(), volumePath->type);
CHECK_EQ(info.name(), volumePath->name);
const string& volumeId = volumePath->volumeId;
const string statePath = paths::getVolumeStatePath(
rootDir, info.type(), info.name(), volumeId);
if (!os::exists(statePath)) {
continue;
}
Result<VolumeState> volumeState =
slave::state::read<VolumeState>(statePath);
if (volumeState.isError()) {
return Failure(
"Failed to read volume state from '" + statePath +
"': " + volumeState.error());
}
if (volumeState.isNone()) {
continue;
}
volumes.put(volumeId, std::move(volumeState.get()));
VolumeData& volume = volumes.at(volumeId);
if (!VolumeState::State_IsValid(volume.state.state())) {
return Failure("Volume '" + volumeId + "' is in INVALID state");
}
// First, if there is a node reboot after the volume is made
// publishable, it should be reset to `NODE_READY`.
switch (volume.state.state()) {
case VolumeState::CREATED:
case VolumeState::NODE_READY:
case VolumeState::CONTROLLER_PUBLISH:
case VolumeState::CONTROLLER_UNPUBLISH:
case VolumeState::NODE_STAGE: {
break;
}
case VolumeState::VOL_READY:
case VolumeState::PUBLISHED:
case VolumeState::NODE_UNSTAGE:
case VolumeState::NODE_PUBLISH:
case VolumeState::NODE_UNPUBLISH: {
if (bootId != volume.state.boot_id()) {
// Since this is a no-op, no need to checkpoint here.
volume.state.set_state(VolumeState::NODE_READY);
volume.state.clear_boot_id();
}
break;
}
case VolumeState::UNKNOWN: {
return Failure("Volume '" + volumeId + "' is in UNKNOWN state");
}
// NOTE: We avoid using a default clause for the following values in
// proto3's open enum to enable the compiler to detect missing enum
// cases for us. See: https://github.com/google/protobuf/issues/3917
case google::protobuf::kint32min:
case google::protobuf::kint32max: {
UNREACHABLE();
}
}
// Second, if the volume has been used by a container before recovery,
// we have to bring the volume back to `PUBLISHED` so data can be
// cleaned up synchronously when needed.
if (volume.state.node_publish_required()) {
futures.push_back(publishVolume(volumeId));
}
}
// Garbage collect leftover mount paths that were failed to remove before.
const string mountRootDir =
paths::getMountRootDir(rootDir, info.type(), info.name());
Try<list<string>> mountPaths = paths::getMountPaths(mountRootDir);
if (mountPaths.isError()) {
// TODO(chhsiao): This could indicate that something is seriously wrong.
// To help debugging the problem, we should surface the error via
// MESOS-8745.
return Failure(
"Failed to find mount paths for CSI plugin type '" + info.type() +
"' and name '" + info.name() + "': " + mountPaths.error());
}
foreach (const string& path, mountPaths.get()) {
Try<string> volumeId = paths::parseMountPath(mountRootDir, path);
if (volumeId.isError()) {
return Failure(
"Failed to parse mount path '" + path + "': " + volumeId.error());
}
if (!volumes.contains(volumeId.get())) {
garbageCollectMountPath(volumeId.get());
}
}
return process::collect(futures).then([] { return Nothing(); });
}));
}
Future<vector<VolumeInfo>> VolumeManagerProcess::listVolumes()
{
if (!controllerCapabilities->listVolumes) {
return vector<VolumeInfo>();
}
// TODO(chhsiao): Set the max entries and use a loop to do multiple
// `ListVolumes` calls.
return call(CONTROLLER_SERVICE, &Client::listVolumes, ListVolumesRequest())
.then(process::defer(self(), [](const ListVolumesResponse& response) {
vector<VolumeInfo> result;
foreach (const auto& entry, response.entries()) {
result.push_back(VolumeInfo{Bytes(entry.volume().capacity_bytes()),
entry.volume().volume_id(),
entry.volume().volume_context()});
}
return result;
}));
}
Future<Bytes> VolumeManagerProcess::getCapacity(
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
if (!controllerCapabilities->getCapacity) {
return Bytes(0);
}
GetCapacityRequest request;
*request.add_volume_capabilities() = evolve(capability);
*request.mutable_parameters() = parameters;
return call(CONTROLLER_SERVICE, &Client::getCapacity, std::move(request))
.then([](const GetCapacityResponse& response) {
return Bytes(response.available_capacity());
});
}
Future<VolumeInfo> VolumeManagerProcess::createVolume(
const string& name,
const Bytes& capacity,
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
if (!controllerCapabilities->createDeleteVolume) {
return Failure(
"CREATE_DELETE_VOLUME controller capability is not supported for CSI "
"plugin type '" + info.type() + "' and name '" + info.name());
}
LOG(INFO) << "Creating volume with name '" << name << "'";
CreateVolumeRequest request;
request.set_name(name);
request.mutable_capacity_range()->set_required_bytes(capacity.bytes());
request.mutable_capacity_range()->set_limit_bytes(capacity.bytes());
*request.add_volume_capabilities() = evolve(capability);
*request.mutable_parameters() = parameters;
// We retry the `CreateVolume` call for MESOS-9517.
return call(
CONTROLLER_SERVICE, &Client::createVolume, std::move(request), true)
.then(process::defer(self(), [=](
const CreateVolumeResponse& response) -> Future<VolumeInfo> {
const string& volumeId = response.volume().volume_id();
// NOTE: If the volume is already tracked, there might already be
// operations running in its sequence. Since this continuation runs
// outside the sequence, we fail the call here to avoid any race issue.
// This also means that this call is not idempotent.
if (volumes.contains(volumeId)) {
return Failure("Volume with name '" + name + "' already exists");
}
VolumeState volumeState;
volumeState.set_state(VolumeState::CREATED);
*volumeState.mutable_volume_capability() = capability;
*volumeState.mutable_parameters() = parameters;
*volumeState.mutable_volume_context() =
response.volume().volume_context();
volumes.put(volumeId, std::move(volumeState));
checkpointVolumeState(volumeId);
return VolumeInfo{capacity, volumeId, response.volume().volume_context()};
}));
}
Future<Option<Error>> VolumeManagerProcess::validateVolume(
const VolumeInfo& volumeInfo,
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
// If the volume has been checkpointed, the validation succeeds only if the
// capability and parameters of the specified profile are the same as those in
// the checkpoint.
if (volumes.contains(volumeInfo.id)) {
const VolumeState& volumeState = volumes.at(volumeInfo.id).state;
if (volumeState.volume_capability() != capability) {
return Some(Error(
"Unsupported volume capability for volume '" + volumeInfo.id + "'"));
}
if (volumeState.parameters() != parameters) {
return Some(Error(
"Mismatched parameters for volume '" + volumeInfo.id + "'"));
}
return None();
}
LOG(INFO) << "Validating volume '" << volumeInfo.id << "'";
ValidateVolumeCapabilitiesRequest request;
request.set_volume_id(volumeInfo.id);
*request.add_volume_capabilities() = evolve(capability);
*request.mutable_volume_context() = volumeInfo.context;
*request.mutable_parameters() = parameters;
return call(
CONTROLLER_SERVICE,
&Client::validateVolumeCapabilities,
std::move(request))
.then(process::defer(self(), [=](
const ValidateVolumeCapabilitiesResponse& response)
-> Future<Option<Error>> {
if (!response.has_confirmed()) {
return Error(
"Validation failed for volume '" + volumeInfo.id + "': " +
response.message());
}
if (response.confirmed().volume_context() != volumeInfo.context) {
return Error(
"Validation failed for volume '" + volumeInfo.id +
"': Mismatched volume context");
}
if (std::none_of(
response.confirmed().volume_capabilities().begin(),
response.confirmed().volume_capabilities().end(),
[&](const csi::v1::VolumeCapability& _capability) {
return csi::v1::devolve(_capability) == capability;
})) {
return Error(
"Validation failed for volume '" + volumeInfo.id +
"': Unsupported volume capability");
}
if (response.confirmed().parameters() != parameters) {
return Error(
"Validation failed for volume '" + volumeInfo.id +
"': Mismatched parameters");
}
// NOTE: If the volume is already tracked, there might already be
// operations running in its sequence. Since this continuation runs
// outside the sequence, we fail the call here to avoid any race issue.
// This also means that this call is not idempotent.
if (volumes.contains(volumeInfo.id)) {
return Failure("Volume '" + volumeInfo.id + "' already validated");
}
VolumeState volumeState;
volumeState.set_state(VolumeState::CREATED);
*volumeState.mutable_volume_capability() = capability;
*volumeState.mutable_parameters() = parameters;
*volumeState.mutable_volume_context() = volumeInfo.context;
volumes.put(volumeInfo.id, std::move(volumeState));
checkpointVolumeState(volumeInfo.id);
return None();
}));
}
Future<bool> VolumeManagerProcess::deleteVolume(const string& volumeId)
{
if (!volumes.contains(volumeId)) {
return __deleteVolume(volumeId);
}
VolumeData& volume = volumes.at(volumeId);
LOG(INFO) << "Deleting volume '" << volumeId << "' in "
<< volume.state.state() << " state";
// Volume deletion is sequentialized with other operations on the same volume
// to avoid races.
return volume.sequence->add(std::function<Future<bool>()>(
process::defer(self(), &Self::_deleteVolume, volumeId)));
}
Future<Nothing> VolumeManagerProcess::attachVolume(const string& volumeId)
{
if (!volumes.contains(volumeId)) {
return Failure("Cannot attach unknown volume '" + volumeId + "'");
}
VolumeData& volume = volumes.at(volumeId);
LOG(INFO) << "Attaching volume '" << volumeId << "' in "
<< volume.state.state() << " state";
// Volume attaching is serialized with other operations on the same volume to
// avoid races.
return volume.sequence->add(std::function<Future<Nothing>()>(
process::defer(self(), &Self::_attachVolume, volumeId)));
}
Future<Nothing> VolumeManagerProcess::detachVolume(const string& volumeId)
{
if (!volumes.contains(volumeId)) {
return Failure("Cannot detach unknown volume '" + volumeId + "'");
}
VolumeData& volume = volumes.at(volumeId);
LOG(INFO) << "Detaching volume '" << volumeId << "' in "
<< volume.state.state() << " state";
// Volume detaching is serialized with other operations on the same volume to
// avoid races.
return volume.sequence->add(std::function<Future<Nothing>()>(
process::defer(self(), &Self::_detachVolume, volumeId)));
}
Future<Nothing> VolumeManagerProcess::publishVolume(const string& volumeId)
{
if (!volumes.contains(volumeId)) {
return Failure("Cannot publish unknown volume '" + volumeId + "'");
}
VolumeData& volume = volumes.at(volumeId);
LOG(INFO) << "Publishing volume '" << volumeId << "' in "
<< volume.state.state() << " state";
// Volume publishing is serialized with other operations on the same volume to
// avoid races.
return volume.sequence->add(std::function<Future<Nothing>()>(
process::defer(self(), &Self::_publishVolume, volumeId)));
}
Future<Nothing> VolumeManagerProcess::unpublishVolume(const string& volumeId)
{
if (!volumes.contains(volumeId)) {
return Failure("Cannot unpublish unknown volume '" + volumeId + "'");
}
VolumeData& volume = volumes.at(volumeId);
LOG(INFO) << "Unpublishing volume '" << volumeId << "' in "
<< volume.state.state() << " state";
// Volume unpublishing is serialized with other operations on the same volume
// to avoid races.
return volume.sequence->add(std::function<Future<Nothing>()>(
process::defer(self(), &Self::_unpublishVolume, volumeId)));
}
template <typename Request, typename Response>
Future<Response> VolumeManagerProcess::call(
const Service& service,
Future<RPCResult<Response>> (Client::*rpc)(Request),
const Request& request,
const bool retry) // Made immutable in the following mutable lambda.
{
Duration maxBackoff = DEFAULT_CSI_RETRY_BACKOFF_FACTOR;
return process::loop(
self(),
[=] {
// Make the call to the latest service endpoint.
return serviceManager->getServiceEndpoint(service)
.then(process::defer(
self(),
&VolumeManagerProcess::_call<Request, Response>,
lambda::_1,
rpc,
request));
},
[=](const RPCResult<Response>& result) mutable
-> Future<ControlFlow<Response>> {
Option<Duration> backoff = retry
? maxBackoff * (static_cast<double>(os::random()) / RAND_MAX)
: Option<Duration>::none();
maxBackoff = std::min(maxBackoff * 2, DEFAULT_CSI_RETRY_INTERVAL_MAX);
// We dispatch `__call` for testing purpose.
return process::dispatch(
self(), &VolumeManagerProcess::__call<Response>, result, backoff);
});
}
template <typename Request, typename Response>
Future<RPCResult<Response>> VolumeManagerProcess::_call(
const string& endpoint,
Future<RPCResult<Response>> (Client::*rpc)(Request),
const Request& request)
{
++metrics->csi_plugin_rpcs_pending;
return (Client(endpoint, runtime).*rpc)(request).onAny(
process::defer(self(), [=](const Future<RPCResult<Response>>& future) {
--metrics->csi_plugin_rpcs_pending;
if (future.isReady() && future->isSome()) {
++metrics->csi_plugin_rpcs_finished;
} else if (future.isDiscarded()) {
++metrics->csi_plugin_rpcs_cancelled;
} else {
++metrics->csi_plugin_rpcs_failed;
}
}));
}
template <typename Response>
Future<ControlFlow<Response>> VolumeManagerProcess::__call(
const RPCResult<Response>& result, const Option<Duration>& backoff)
{
if (result.isSome()) {
return Break(result.get());
}
if (backoff.isNone()) {
return Failure(result.error());
}
// See the link below for retryable status codes:
// https://grpc.io/grpc/cpp/namespacegrpc.html#aff1730578c90160528f6a8d67ef5c43b // NOLINT
switch (result.error().status.error_code()) {
case grpc::DEADLINE_EXCEEDED:
case grpc::UNAVAILABLE: {
LOG(ERROR) << "Received '" << result.error() << "' while expecting "
<< Response::descriptor()->name() << ". Retrying in "
<< backoff.get();
return process::after(backoff.get())
.then([]() -> Future<ControlFlow<Response>> { return Continue(); });
}
case grpc::CANCELLED:
case grpc::UNKNOWN:
case grpc::INVALID_ARGUMENT:
case grpc::NOT_FOUND:
case grpc::ALREADY_EXISTS:
case grpc::PERMISSION_DENIED:
case grpc::UNAUTHENTICATED:
case grpc::RESOURCE_EXHAUSTED:
case grpc::FAILED_PRECONDITION:
case grpc::ABORTED:
case grpc::OUT_OF_RANGE:
case grpc::UNIMPLEMENTED:
case grpc::INTERNAL:
case grpc::DATA_LOSS: {
return Failure(result.error());
}
case grpc::OK:
case grpc::DO_NOT_USE: {
UNREACHABLE();
}
}
UNREACHABLE();
}
Future<Nothing> VolumeManagerProcess::prepareServices()
{
CHECK(!services.empty());
// Get the plugin capabilities.
return call(
*services.begin(),
&Client::getPluginCapabilities,
GetPluginCapabilitiesRequest())
.then(process::defer(self(), [=](
const GetPluginCapabilitiesResponse& response) -> Future<Nothing> {
pluginCapabilities = response.capabilities();
if (services.contains(CONTROLLER_SERVICE) &&
!pluginCapabilities->controllerService) {
return Failure(
"CONTROLLER_SERVICE plugin capability is not supported for CSI "
"plugin type '" + info.type() + "' and name '" + info.name() + "'");
}
return Nothing();
}))
// Check if all services have consistent plugin infos.
.then(process::defer(self(), [this] {
vector<Future<GetPluginInfoResponse>> futures;
foreach (const Service& service, services) {
futures.push_back(call(
CONTROLLER_SERVICE, &Client::getPluginInfo, GetPluginInfoRequest())
.onReady([service](const GetPluginInfoResponse& response) {
LOG(INFO) << service << " loaded: " << stringify(response);
}));
}
return process::collect(futures)
.then([](const vector<GetPluginInfoResponse>& pluginInfos) {
for (size_t i = 1; i < pluginInfos.size(); ++i) {
if (pluginInfos[i].name() != pluginInfos[0].name() ||
pluginInfos[i].vendor_version() !=
pluginInfos[0].vendor_version()) {
LOG(WARNING) << "Inconsistent plugin services. Please check with "
"the plugin vendor to ensure compatibility.";
}
}
return Nothing();
});
}))
// Get the controller capabilities.
.then(process::defer(self(), [this]() -> Future<Nothing> {
if (!services.contains(CONTROLLER_SERVICE)) {
controllerCapabilities = ControllerCapabilities();
return Nothing();
}
return call(
CONTROLLER_SERVICE,
&Client::controllerGetCapabilities,
ControllerGetCapabilitiesRequest())
.then(process::defer(self(), [this](
const ControllerGetCapabilitiesResponse& response) {
controllerCapabilities = response.capabilities();
return Nothing();
}));
}))
// Get the node capabilities and ID.
.then(process::defer(self(), [this]() -> Future<Nothing> {
if (!services.contains(NODE_SERVICE)) {
nodeCapabilities = NodeCapabilities();
return Nothing();
}
return call(
NODE_SERVICE,
&Client::nodeGetCapabilities,
NodeGetCapabilitiesRequest())
.then(process::defer(self(), [this](
const NodeGetCapabilitiesResponse& response) -> Future<Nothing> {
nodeCapabilities = response.capabilities();
if (controllerCapabilities->publishUnpublishVolume) {
return call(
NODE_SERVICE, &Client::nodeGetInfo, NodeGetInfoRequest())
.then(process::defer(self(), [this](
const NodeGetInfoResponse& response) {
nodeId = response.node_id();
return Nothing();
}));
}
return Nothing();
}));
}));
}
Future<bool> VolumeManagerProcess::_deleteVolume(const std::string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.node_publish_required()) {
CHECK_EQ(VolumeState::PUBLISHED, volumeState.state());
const string targetPath = paths::getMountTargetPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
// NOTE: Normally the volume should have been cleaned up. However this may
// not be true for preprovisioned volumes (e.g., leftover from a previous
// resource provider instance). To prevent data leakage in such cases, we
// clean up the data (but not the target path) here.
Try<Nothing> rmdir = os::rmdir(targetPath, true, false);
if (rmdir.isError()) {
return Failure(
"Failed to clean up volume '" + volumeId + "': " + rmdir.error());
}
volumeState.set_node_publish_required(false);
checkpointVolumeState(volumeId);
}
if (volumeState.state() != VolumeState::CREATED) {
// Retry after transitioning the volume to `CREATED` state.
return _detachVolume(volumeId)
.then(process::defer(self(), &Self::_deleteVolume, volumeId));
}
// NOTE: The last asynchronous continuation, which is supposed to be run in
// the volume's sequence, would cause the sequence to be destructed, which
// would in turn discard the returned future. However, since the continuation
// would have already been run, the returned future will become ready, making
// the future returned by the sequence ready as well.
return __deleteVolume(volumeId)
.then(process::defer(self(), [this, volumeId](bool deleted) {
volumes.erase(volumeId);
const string volumePath =
paths::getVolumePath(rootDir, info.type(), info.name(), volumeId);
Try<Nothing> rmdir = os::rmdir(volumePath);
CHECK_SOME(rmdir) << "Failed to remove checkpointed volume state at '"
<< volumePath << "': " << rmdir.error();
garbageCollectMountPath(volumeId);
return deleted;
}));
}
Future<bool> VolumeManagerProcess::__deleteVolume(
const string& volumeId)
{
if (!controllerCapabilities->createDeleteVolume) {
return false;
}
LOG(INFO) << "Calling '/csi.v1.Controller/DeleteVolume' for volume '"
<< volumeId << "'";
DeleteVolumeRequest request;
request.set_volume_id(volumeId);
// We retry the `DeleteVolume` call for MESOS-9517.
return call(
CONTROLLER_SERVICE, &Client::deleteVolume, std::move(request), true)
.then([] { return true; });
}
Future<Nothing> VolumeManagerProcess::_attachVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::NODE_READY) {
return Nothing();
}
if (volumeState.state() != VolumeState::CREATED &&
volumeState.state() != VolumeState::CONTROLLER_PUBLISH &&
volumeState.state() != VolumeState::CONTROLLER_UNPUBLISH) {
return Failure(
"Cannot attach volume '" + volumeId + "' in " +
stringify(volumeState.state()) + " state");
}
if (!controllerCapabilities->publishUnpublishVolume) {
// Since this is a no-op, no need to checkpoint here.
volumeState.set_state(VolumeState::NODE_READY);
return Nothing();
}
// A previously failed `ControllerUnpublishVolume` call can be recovered
// through an extra `ControllerUnpublishVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#controllerunpublishvolume // NOLINT
if (volumeState.state() == VolumeState::CONTROLLER_UNPUBLISH) {
// Retry after recovering the volume to `CREATED` state.
return _detachVolume(volumeId)
.then(process::defer(self(), &Self::_attachVolume, volumeId));
}
if (volumeState.state() == VolumeState::CREATED) {
volumeState.set_state(VolumeState::CONTROLLER_PUBLISH);
checkpointVolumeState(volumeId);
}
LOG(INFO)
<< "Calling '/csi.v1.Controller/ControllerPublishVolume' for volume '"
<< volumeId << "'";
ControllerPublishVolumeRequest request;
request.set_volume_id(volumeId);
request.set_node_id(CHECK_NOTNONE(nodeId));
*request.mutable_volume_capability() =
evolve(volumeState.volume_capability());
request.set_readonly(false);
*request.mutable_volume_context() = volumeState.volume_context();
return call(
CONTROLLER_SERVICE, &Client::controllerPublishVolume, std::move(request))
.then(process::defer(self(), [this, volumeId](
const ControllerPublishVolumeResponse& response) {
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::NODE_READY);
*volumeState.mutable_publish_context() = response.publish_context();
checkpointVolumeState(volumeId);
return Nothing();
}));
}
Future<Nothing> VolumeManagerProcess::_detachVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::CREATED) {
return Nothing();
}
if (volumeState.state() != VolumeState::NODE_READY &&
volumeState.state() != VolumeState::CONTROLLER_PUBLISH &&
volumeState.state() != VolumeState::CONTROLLER_UNPUBLISH) {
// Retry after transitioning the volume to `CREATED` state.
return _unpublishVolume(volumeId)
.then(process::defer(self(), &Self::_detachVolume, volumeId));
}
if (!controllerCapabilities->publishUnpublishVolume) {
// Since this is a no-op, no need to checkpoint here.
volumeState.set_state(VolumeState::CREATED);
return Nothing();
}
// A previously failed `ControllerPublishVolume` call can be recovered through
// the current `ControllerUnpublishVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#controllerpublishvolume // NOLINT
if (volumeState.state() == VolumeState::NODE_READY ||
volumeState.state() == VolumeState::CONTROLLER_PUBLISH) {
volumeState.set_state(VolumeState::CONTROLLER_UNPUBLISH);
checkpointVolumeState(volumeId);
}
LOG(INFO)
<< "Calling '/csi.v1.Controller/ControllerUnpublishVolume' for volume '"
<< volumeId << "'";
ControllerUnpublishVolumeRequest request;
request.set_volume_id(volumeId);
request.set_node_id(CHECK_NOTNONE(nodeId));
return call(
CONTROLLER_SERVICE,
&Client::controllerUnpublishVolume,
std::move(request))
.then(process::defer(self(), [this, volumeId] {
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::CREATED);
volumeState.mutable_publish_context()->clear();
checkpointVolumeState(volumeId);
return Nothing();
}));
}
Future<Nothing> VolumeManagerProcess::_publishVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::PUBLISHED) {
CHECK(volumeState.node_publish_required());
return Nothing();
}
if (volumeState.state() != VolumeState::VOL_READY &&
volumeState.state() != VolumeState::NODE_PUBLISH &&
volumeState.state() != VolumeState::NODE_UNPUBLISH) {
// Retry after transitioning the volume to `VOL_READY` state.
return __publishVolume(volumeId)
.then(process::defer(self(), &Self::_publishVolume, volumeId));
}
// A previously failed `NodeUnpublishVolume` call can be recovered through an
// extra `NodeUnpublishVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#nodeunpublishvolume // NOLINT
if (volumeState.state() == VolumeState::NODE_UNPUBLISH) {
// Retry after recovering the volume to `VOL_READY` state.
return __unpublishVolume(volumeId)
.then(process::defer(self(), &Self::_publishVolume, volumeId));
}
const string targetPath = paths::getMountTargetPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
// Ensure the parent directory of the target path exists. The target path
// itself will be created by the plugin.
//
// NOTE: The target path will be removed by the plugin as well, and The parent
// directory of the target path will be cleaned up during volume removal.
Try<Nothing> mkdir = os::mkdir(Path(targetPath).dirname());
if (mkdir.isError()) {
return Failure(
"Failed to create parent directory of target path '" + targetPath +
"': " + mkdir.error());
}
if (volumeState.state() == VolumeState::VOL_READY) {
volumeState.set_state(VolumeState::NODE_PUBLISH);
checkpointVolumeState(volumeId);
}
LOG(INFO) << "Calling '/csi.v1.Node/NodePublishVolume' for volume '"
<< volumeId << "'";
NodePublishVolumeRequest request;
request.set_volume_id(volumeId);
*request.mutable_publish_context() = volumeState.publish_context();
request.set_target_path(targetPath);
*request.mutable_volume_capability() =
evolve(volumeState.volume_capability());
request.set_readonly(false);
*request.mutable_volume_context() = volumeState.volume_context();
if (nodeCapabilities->stageUnstageVolume) {
const string stagingPath = paths::getMountStagingPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
CHECK(os::exists(stagingPath));
request.set_staging_target_path(stagingPath);
}
return call(NODE_SERVICE, &Client::nodePublishVolume, std::move(request))
.then(process::defer(self(), [this, volumeId, targetPath]()
-> Future<Nothing> {
if (!os::exists(targetPath)) {
return Failure("Target path '" + targetPath + "' not created");
}
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::PUBLISHED);
// NOTE: This is the first time a container is going to consume the
// persistent volume, so the `node_publish_required` field is set to
// indicate that this volume must remain published so it can be
// synchronously cleaned up when the persistent volume is destroyed.
volumeState.set_node_publish_required(true);
checkpointVolumeState(volumeId);
return Nothing();
}));
}
Future<Nothing> VolumeManagerProcess::__publishVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::VOL_READY) {
CHECK(!volumeState.boot_id().empty());
return Nothing();
}
if (volumeState.state() != VolumeState::NODE_READY &&
volumeState.state() != VolumeState::NODE_STAGE &&
volumeState.state() != VolumeState::NODE_UNSTAGE) {
// Retry after transitioning the volume to `NODE_READY` state.
return _attachVolume(volumeId)
.then(process::defer(self(), &Self::__publishVolume, volumeId));
}
if (!nodeCapabilities->stageUnstageVolume) {
// Since this is a no-op, no need to checkpoint here.
volumeState.set_state(VolumeState::VOL_READY);
volumeState.set_boot_id(CHECK_NOTNONE(bootId));
return Nothing();
}
// A previously failed `NodeUnstageVolume` call can be recovered through an
// extra `NodeUnstageVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#nodeunstagevolume // NOLINT
if (volumeState.state() == VolumeState::NODE_UNSTAGE) {
// Retry after recovering the volume to `NODE_READY` state.
return _unpublishVolume(volumeId)
.then(process::defer(self(), &Self::__publishVolume, volumeId));
}
const string stagingPath = paths::getMountStagingPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
// NOTE: The staging path will be cleaned up in during volume removal.
Try<Nothing> mkdir = os::mkdir(stagingPath);
if (mkdir.isError()) {
return Failure(
"Failed to create mount staging path '" + stagingPath +
"': " + mkdir.error());
}
if (volumeState.state() == VolumeState::NODE_READY) {
volumeState.set_state(VolumeState::NODE_STAGE);
checkpointVolumeState(volumeId);
}
LOG(INFO) << "Calling '/csi.v1.Node/NodeStageVolume' for volume '" << volumeId
<< "'";
NodeStageVolumeRequest request;
request.set_volume_id(volumeId);
*request.mutable_publish_context() = volumeState.publish_context();
request.set_staging_target_path(stagingPath);
*request.mutable_volume_capability() =
evolve(volumeState.volume_capability());
*request.mutable_volume_context() = volumeState.volume_context();
return call(NODE_SERVICE, &Client::nodeStageVolume, std::move(request))
.then(process::defer(self(), [this, volumeId] {
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::VOL_READY);
volumeState.set_boot_id(CHECK_NOTNONE(bootId));
checkpointVolumeState(volumeId);
return Nothing();
}));
}
Future<Nothing> VolumeManagerProcess::_unpublishVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::NODE_READY) {
CHECK(volumeState.boot_id().empty());
return Nothing();
}
if (volumeState.state() != VolumeState::VOL_READY &&
volumeState.state() != VolumeState::NODE_STAGE &&
volumeState.state() != VolumeState::NODE_UNSTAGE) {
// Retry after transitioning the volume to `VOL_READY` state.
return __unpublishVolume(volumeId)
.then(process::defer(self(), &Self::_unpublishVolume, volumeId));
}
if (!nodeCapabilities->stageUnstageVolume) {
// Since this is a no-op, no need to checkpoint here.
volumeState.set_state(VolumeState::NODE_READY);
volumeState.clear_boot_id();
return Nothing();
}
// A previously failed `NodeStageVolume` call can be recovered through the
// current `NodeUnstageVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#nodestagevolume // NOLINT
if (volumeState.state() == VolumeState::VOL_READY ||
volumeState.state() == VolumeState::NODE_STAGE) {
volumeState.set_state(VolumeState::NODE_UNSTAGE);
checkpointVolumeState(volumeId);
}
const string stagingPath = paths::getMountStagingPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
CHECK(os::exists(stagingPath));
LOG(INFO) << "Calling '/csi.v1.Node/NodeUnstageVolume' for volume '"
<< volumeId << "'";
NodeUnstageVolumeRequest request;
request.set_volume_id(volumeId);
request.set_staging_target_path(stagingPath);
return call(NODE_SERVICE, &Client::nodeUnstageVolume, std::move(request))
.then(process::defer(self(), [this, volumeId] {
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::NODE_READY);
volumeState.clear_boot_id();
checkpointVolumeState(volumeId);
return Nothing();
}));
}
Future<Nothing> VolumeManagerProcess::__unpublishVolume(const string& volumeId)
{
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
if (volumeState.state() == VolumeState::VOL_READY) {
return Nothing();
}
if (volumeState.state() != VolumeState::PUBLISHED &&
volumeState.state() != VolumeState::NODE_PUBLISH &&
volumeState.state() != VolumeState::NODE_UNPUBLISH) {
return Failure(
"Cannot unpublish volume '" + volumeId + "' in " +
stringify(volumeState.state()) + "state");
}
// A previously failed `NodePublishVolume` call can be recovered through the
// current `NodeUnpublishVolume` call. See:
// https://github.com/container-storage-interface/spec/blob/v1.1.0/spec.md#nodepublishvolume // NOLINT
if (volumeState.state() == VolumeState::PUBLISHED ||
volumeState.state() == VolumeState::NODE_PUBLISH) {
volumeState.set_state(VolumeState::NODE_UNPUBLISH);
checkpointVolumeState(volumeId);
}
const string targetPath = paths::getMountTargetPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
LOG(INFO) << "Calling '/csi.v1.Node/NodeUnpublishVolume' for volume '"
<< volumeId << "'";
NodeUnpublishVolumeRequest request;
request.set_volume_id(volumeId);
request.set_target_path(targetPath);
return call(NODE_SERVICE, &Client::nodeUnpublishVolume, std::move(request))
.then(process::defer(self(), [this, volumeId, targetPath]()
-> Future<Nothing> {
if (os::exists(targetPath)) {
return Failure("Target path '" + targetPath + "' not removed");
}
CHECK(volumes.contains(volumeId));
VolumeState& volumeState = volumes.at(volumeId).state;
volumeState.set_state(VolumeState::VOL_READY);
checkpointVolumeState(volumeId);
return Nothing();
}));
}
void VolumeManagerProcess::checkpointVolumeState(const string& volumeId)
{
const string statePath =
paths::getVolumeStatePath(rootDir, info.type(), info.name(), volumeId);
// NOTE: We ensure the checkpoint is synced to the filesystem to avoid
// resulting in a stale or empty checkpoint when a system crash happens.
Try<Nothing> checkpoint =
slave::state::checkpoint(statePath, volumes.at(volumeId).state, true);
CHECK_SOME(checkpoint)
<< "Failed to checkpoint volume state to '" << statePath << "':"
<< checkpoint.error();
}
void VolumeManagerProcess::garbageCollectMountPath(const string& volumeId)
{
CHECK(!volumes.contains(volumeId));
const string path = paths::getMountPath(
paths::getMountRootDir(rootDir, info.type(), info.name()), volumeId);
if (os::exists(path)) {
Try<Nothing> rmdir = os::rmdir(path);
if (rmdir.isError()) {
LOG(ERROR) << "Failed to remove directory '" << path
<< "': " << rmdir.error();
}
}
}
VolumeManager::VolumeManager(
const string& rootDir,
const CSIPluginInfo& info,
const hashset<Service>& services,
const Runtime& runtime,
ServiceManager* serviceManager,
Metrics* metrics)
: process(new VolumeManagerProcess(
rootDir,
info,
services,
runtime,
serviceManager,
metrics))
{
process::spawn(CHECK_NOTNULL(process.get()));
recovered = process::dispatch(process.get(), &VolumeManagerProcess::recover);
}
VolumeManager::~VolumeManager()
{
process::terminate(process.get());
process::wait(process.get());
}
Future<Nothing> VolumeManager::recover()
{
return recovered;
}
Future<vector<VolumeInfo>> VolumeManager::listVolumes()
{
return recovered
.then(process::defer(process.get(), &VolumeManagerProcess::listVolumes));
}
Future<Bytes> VolumeManager::getCapacity(
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
return recovered
.then(process::defer(
process.get(),
&VolumeManagerProcess::getCapacity,
capability,
parameters));
}
Future<VolumeInfo> VolumeManager::createVolume(
const string& name,
const Bytes& capacity,
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
return recovered
.then(process::defer(
process.get(),
&VolumeManagerProcess::createVolume,
name,
capacity,
capability,
parameters));
}
Future<Option<Error>> VolumeManager::validateVolume(
const VolumeInfo& volumeInfo,
const types::VolumeCapability& capability,
const Map<string, string>& parameters)
{
return recovered
.then(process::defer(
process.get(),
&VolumeManagerProcess::validateVolume,
volumeInfo,
capability,
parameters));
}
Future<bool> VolumeManager::deleteVolume(const string& volumeId)
{
return recovered
.then(process::defer(
process.get(), &VolumeManagerProcess::deleteVolume, volumeId));
}
Future<Nothing> VolumeManager::attachVolume(const string& volumeId)
{
return recovered
.then(process::defer(
process.get(), &VolumeManagerProcess::attachVolume, volumeId));
}
Future<Nothing> VolumeManager::detachVolume(const string& volumeId)
{
return recovered
.then(process::defer(
process.get(), &VolumeManagerProcess::detachVolume, volumeId));
}
Future<Nothing> VolumeManager::publishVolume(const string& volumeId)
{
return recovered
.then(process::defer(
process.get(), &VolumeManagerProcess::publishVolume, volumeId));
}
Future<Nothing> VolumeManager::unpublishVolume(const string& volumeId)
{
return recovered
.then(process::defer(
process.get(), &VolumeManagerProcess::unpublishVolume, volumeId));
}
} // namespace v1 {
} // namespace csi {
} // namespace mesos {
| {
"content_hash": "727b4d2d2c5306e12382ead79757fcdb",
"timestamp": "",
"source": "github",
"line_count": 1300,
"max_line_length": 112,
"avg_line_length": 33.16076923076923,
"alnum_prop": 0.655269201326869,
"repo_name": "gsantovena/mesos",
"id": "e7e032988bce576ef8d6a0c3457f26f1aad9bb58",
"size": "44695",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/csi/v1_volume_manager.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7957"
},
{
"name": "C++",
"bytes": "14472425"
},
{
"name": "CMake",
"bytes": "101973"
},
{
"name": "CSS",
"bytes": "8085"
},
{
"name": "Dockerfile",
"bytes": "16822"
},
{
"name": "Groovy",
"bytes": "3895"
},
{
"name": "HTML",
"bytes": "94185"
},
{
"name": "Java",
"bytes": "143825"
},
{
"name": "JavaScript",
"bytes": "93108"
},
{
"name": "M4",
"bytes": "200726"
},
{
"name": "Makefile",
"bytes": "116815"
},
{
"name": "PowerShell",
"bytes": "2547"
},
{
"name": "Python",
"bytes": "380663"
},
{
"name": "Ruby",
"bytes": "10047"
},
{
"name": "Shell",
"bytes": "155887"
}
],
"symlink_target": ""
} |
<?php
namespace app\modules\usertalk\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\usertalk\models\Usertalk;
/**
* UsertalkSearch represents the model behind the search form about `app\modules\usertalk\models\Usertalk`.
*/
class UsertalkSearch extends Usertalk
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['usertalk_id', 'usertalk_status', 'usertalk_created_ip'], 'integer'],
[['usertalk_fio', 'usertalk_email', 'usertalk_text', 'usertalk_created'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Usertalk::find();
// add conditions that should always apply here
// $dataProvider = new ActiveDataProvider([
// 'query' => $query,
// ]);
$aDataConf = [
'query' => $query,
'sort'=> [
'defaultOrder' => isset($params['sort']) ? $params['sort'] : ['usertalk_created' => SORT_DESC, ]
]
];
if( isset($params['pagesize']) ) {
$aDataConf['pagination'] = [
'pageSize' => $params['pagesize'],
];
}
$dataProvider = new ActiveDataProvider($aDataConf);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'usertalk_id' => $this->usertalk_id,
'usertalk_status' => empty($this->usertalk_status) ? [self::USER_TALK_STATUS_ACTIVE, self::USER_TALK_STATUS_VISIBLE,] : $this->usertalk_status,
'usertalk_created_ip' => $this->usertalk_created_ip,
'usertalk_created' => $this->usertalk_created,
]);
$query->andFilterWhere(['like', 'usertalk_fio', $this->usertalk_fio])
->andFilterWhere(['like', 'usertalk_email', $this->usertalk_email])
->andFilterWhere(['like', 'usertalk_text', $this->usertalk_text]);
return $dataProvider;
}
/**
* @param int $nCount
* @return array
*/
public function getRundomMessages($nCount = 3) {
$aResult = [];
$aId = Usertalk::find()
->select('usertalk_id')
->andFilterWhere([
'usertalk_status' => self::USER_TALK_STATUS_VISIBLE,
])
->orderBy(['usertalk_created' => SORT_DESC])
->limit(150)
->column();
$i = mt_rand(4, 9);
while($i-- > 0) {
shuffle($aId);
}
if( count($aId) > $nCount ) {
$aId = array_splice($aId, 0, $nCount);
}
if( count($aId) > 0 ) {
$aResult = Usertalk::findAll(['usertalk_id' => $aId]);
}
return $aResult;
}
}
| {
"content_hash": "bd99b5ad2bf16dea4092bf262ff9fbb9",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 155,
"avg_line_length": 28.448275862068964,
"alnum_prop": 0.5266666666666666,
"repo_name": "mosedu/profmechta",
"id": "2310c3079c11c1cede328c7c39e6bb0275883d1a",
"size": "3300",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/usertalk/models/UsertalkSearch.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "1324"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "11274"
},
{
"name": "PHP",
"bytes": "416103"
}
],
"symlink_target": ""
} |
package okhttp3.internal;
import okhttp3.HttpUrl;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import okio.Buffer;
import okio.ByteString;
import okio.Source;
/** Junk drawer of utility methods. */
public final class Util {
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/** A cheap and type-safe constant for the UTF-8 Charset. */
public static final Charset UTF_8 = Charset.forName("UTF-8");
private Util() {
}
public static void checkOffsetAndCount(long arrayLength, long offset, long count) {
if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
throw new ArrayIndexOutOfBoundsException();
}
}
/** Returns true if two possibly-null objects are equal. */
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Closes {@code closeable}, ignoring any checked exceptions. Does nothing
* if {@code closeable} is null.
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* Closes {@code socket}, ignoring any checked exceptions. Does nothing if
* {@code socket} is null.
*/
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (AssertionError e) {
if (!isAndroidGetsocknameError(e)) throw e;
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* Closes {@code serverSocket}, ignoring any checked exceptions. Does nothing if
* {@code serverSocket} is null.
*/
public static void closeQuietly(ServerSocket serverSocket) {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* Closes {@code a} and {@code b}. If either close fails, this completes
* the other close and rethrows the first encountered exception.
*/
public static void closeAll(Closeable a, Closeable b) throws IOException {
Throwable thrown = null;
try {
a.close();
} catch (Throwable e) {
thrown = e;
}
try {
b.close();
} catch (Throwable e) {
if (thrown == null) thrown = e;
}
if (thrown == null) return;
if (thrown instanceof IOException) throw (IOException) thrown;
if (thrown instanceof RuntimeException) throw (RuntimeException) thrown;
if (thrown instanceof Error) throw (Error) thrown;
throw new AssertionError(thrown);
}
/**
* Attempts to exhaust {@code source}, returning true if successful. This is useful when reading
* a complete source is helpful, such as when doing so completes a cache body or frees a socket
* connection for reuse.
*/
public static boolean discard(Source source, int timeout, TimeUnit timeUnit) {
try {
return skipAll(source, timeout, timeUnit);
} catch (IOException e) {
return false;
}
}
/**
* Reads until {@code in} is exhausted or the deadline has been reached. This is careful to not
* extend the deadline if one exists already.
*/
public static boolean skipAll(Source source, int duration, TimeUnit timeUnit) throws IOException {
long now = System.nanoTime();
long originalDuration = source.timeout().hasDeadline()
? source.timeout().deadlineNanoTime() - now
: Long.MAX_VALUE;
source.timeout().deadlineNanoTime(now + Math.min(originalDuration, timeUnit.toNanos(duration)));
try {
Buffer skipBuffer = new Buffer();
while (source.read(skipBuffer, 2048) != -1) {
skipBuffer.clear();
}
return true; // Success! The source has been exhausted.
} catch (InterruptedIOException e) {
return false; // We ran out of time before exhausting the source.
} finally {
if (originalDuration == Long.MAX_VALUE) {
source.timeout().clearDeadline();
} else {
source.timeout().deadlineNanoTime(now + originalDuration);
}
}
}
/** Returns a 32 character string containing an MD5 hash of {@code s}. */
public static String md5Hex(String s) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5bytes = messageDigest.digest(s.getBytes("UTF-8"));
return ByteString.of(md5bytes).hex();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
/** Returns a Base 64-encoded string containing a SHA-1 hash of {@code s}. */
public static String shaBase64(String s) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] sha1Bytes = messageDigest.digest(s.getBytes("UTF-8"));
return ByteString.of(sha1Bytes).base64();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
/** Returns a SHA-1 hash of {@code s}. */
public static ByteString sha1(ByteString s) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] sha1Bytes = messageDigest.digest(s.toByteArray());
return ByteString.of(sha1Bytes);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
/** Returns an immutable copy of {@code list}. */
public static <T> List<T> immutableList(List<T> list) {
return Collections.unmodifiableList(new ArrayList<>(list));
}
/** Returns an immutable list containing {@code elements}. */
public static <T> List<T> immutableList(T... elements) {
return Collections.unmodifiableList(Arrays.asList(elements.clone()));
}
/** Returns an immutable copy of {@code map}. */
public static <K, V> Map<K, V> immutableMap(Map<K, V> map) {
return Collections.unmodifiableMap(new LinkedHashMap<>(map));
}
public static ThreadFactory threadFactory(final String name, final boolean daemon) {
return new ThreadFactory() {
@Override public Thread newThread(Runnable runnable) {
Thread result = new Thread(runnable, name);
result.setDaemon(daemon);
return result;
}
};
}
/**
* Returns an array containing containing only elements found in {@code first} and also in
* {@code second}. The returned elements are in the same order as in {@code first}.
*/
@SuppressWarnings("unchecked")
public static <T> T[] intersect(Class<T> arrayType, T[] first, T[] second) {
List<T> result = intersect(first, second);
return result.toArray((T[]) Array.newInstance(arrayType, result.size()));
}
/**
* Returns a list containing containing only elements found in {@code first} and also in
* {@code second}. The returned elements are in the same order as in {@code first}.
*/
private static <T> List<T> intersect(T[] first, T[] second) {
List<T> result = new ArrayList<>();
for (T a : first) {
for (T b : second) {
if (a.equals(b)) {
result.add(b);
break;
}
}
}
return result;
}
public static String hostHeader(HttpUrl url) {
// TODO: square braces for IPv6 ?
return url.port() != HttpUrl.defaultPort(url.scheme())
? url.host() + ":" + url.port()
: url.host();
}
/** Returns {@code s} with control characters and non-ASCII characters replaced with '?'. */
public static String toHumanReadableAscii(String s) {
for (int i = 0, length = s.length(), c; i < length; i += Character.charCount(c)) {
c = s.codePointAt(i);
if (c > '\u001f' && c < '\u007f') continue;
Buffer buffer = new Buffer();
buffer.writeUtf8(s, 0, i);
for (int j = i; j < length; j += Character.charCount(c)) {
c = s.codePointAt(j);
buffer.writeUtf8CodePoint(c > '\u001f' && c < '\u007f' ? c : '?');
}
return buffer.readUtf8();
}
return s;
}
/**
* Returns true if {@code e} is due to a firmware bug fixed after Android 4.2.2.
* https://code.google.com/p/android/issues/detail?id=54072
*/
public static boolean isAndroidGetsocknameError(AssertionError e) {
return e.getCause() != null && e.getMessage() != null
&& e.getMessage().contains("getsockname failed");
}
public static boolean contains(String[] array, String value) {
return Arrays.asList(array).contains(value);
}
public static String[] concat(String[] array, String value) {
String[] result = new String[array.length + 1];
System.arraycopy(array, 0, result, 0, array.length);
result[result.length - 1] = value;
return result;
}
}
| {
"content_hash": "547912a40c63f25a30fed0eba272c065",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 100,
"avg_line_length": 32.635416666666664,
"alnum_prop": 0.652516225130333,
"repo_name": "teffy/okhttp",
"id": "338fe7174c6e92947647e8d2ce681b4c6c36bd78",
"size": "10018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "okhttp/src/main/java/okhttp3/internal/Util.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3695"
},
{
"name": "HTML",
"bytes": "10222"
},
{
"name": "Java",
"bytes": "2245059"
},
{
"name": "Shell",
"bytes": "2641"
}
],
"symlink_target": ""
} |
/* eslint-env node */
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: '<%= engineModulePrefix %>',
environment
};
return ENV;
};
| {
"content_hash": "d5227b8cda4556b0614595709143729e",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 46,
"avg_line_length": 16.181818181818183,
"alnum_prop": 0.6179775280898876,
"repo_name": "ember-engines/engine-blueprint",
"id": "df7e26b415ca945519bb935f19d79a8753165d95",
"size": "178",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "files/routable-files/addon-config/environment.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10"
},
{
"name": "JavaScript",
"bytes": "7529"
}
],
"symlink_target": ""
} |
layout: post
title: "OWASP BWA WebGoat Challenge: Cross Site Scripting"
subtitle: "Cross Site Tracing Attack"
date: 2017-01-27 13:00:00 -0500
author: "coastal"
header-img: "images/site-resources/webgoat-header.jpg"
---
# Cross Site Tracing (XST) Attack
Instructions:
- Tomcat is configured to support the HTTP TRACE command. Your goal is to perform a Cross Site Tracing (XST) attack.
Alright, so what does the TRACE command do? Apparently, it invokes a remote, application-layer loop-back of the request message. The client can see what is being received at the other end of the request chain and use that data for diagnostic information. [w3 Trace Protocol][w3-trace]
Hmm..request loop-back. So we can view the original full request including headers? Well if we could get a user to run a ```TRACE``` command that would mean we could steal session cookies (as long as we can view the ```TRACE``` response). Let's craft a little XSS payload to perform a trace.
```
<script>
function callHTTPTrace() {
xmlHTTP = new XMLHttpRequest();
xmlHTTP.open("TRACE", "attack?Screen=75&menu=900", false);
xmlHTTP.onreadystatechange = function () {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
alert(xmlHTTP.response)
}
}
xmlHTTP.send();
}
callHTTPTrace();
</script>
```
This code makes an asynchronous ```TRACE``` call to the page we are on using an ```XMLHttpRequest``` object. By reading the response, we should be able to steal cookies from the user who runs this script. When we try to run this XSS though, the browser actually fails this script with the console log:
```
SecurityError: The operation is insecure.
```
However, we pass the lesson (nice?). If we check the challenge source, we can see the code that decides the outcome of our attempt.
```
if (param1.toLowerCase().indexOf("script") != -1 && param1.toLowerCase().indexOf("trace") != -1)
{
makeSuccess(s);
}
```
Aha, so we passed the lesson by including the word 'trace' in our input even though our script itself was blocked by the browser. Not the most comprehensive functional check. Although this attack doesn't seem to be too effective, at least when implemented so bluntly (like here) as our browser itself blocks the calls.
So on an insecure/outdated browser, this attack could likely still be used. Additionally, only if the ```TRACE``` command is enabled by the server (which many servers don't allow). I'm not sure entirely how useful this attack is, but it could be used to bypass the ```HTTPOnly``` cookie attribute, which disallows reading of cookies that have this flag set.
### Resources
[1. Trace HTTP Command][w3-trace]
[2. HTTPOnly Cookie Attribute][http-only]
[w3-trace]:https://www.w3.org/Protocols/rfc2616-sec9.html
[http-only]:https://www.owasp.org/index.php/HTTPOnly#Browsers_Supporting_HTTPOnly | {
"content_hash": "eae07ea4e74dda48e3c5a760b9879843",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 357,
"avg_line_length": 47.71186440677966,
"alnum_prop": 0.7463587921847247,
"repo_name": "spencerdodd/spencerdodd.github.io",
"id": "cb76fec10461247cb784f80cf5717411022c96bf",
"size": "2819",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/webgoat/2017-01-27-webgoat_part_9_final.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20088"
},
{
"name": "HTML",
"bytes": "33551"
},
{
"name": "JavaScript",
"bytes": "53780"
},
{
"name": "Ruby",
"bytes": "1221"
}
],
"symlink_target": ""
} |
using Hangfire;
using Hangfire.Console;
using Hangfire.Dashboard;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(AbpHangfireConsoleApp.Startup))]
namespace AbpHangfireConsoleApp
{
/// <summary>
/// Class to manage access to the hangfire dashboard.
/// </summary>
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
/// <summary>
/// Determines whether a user may access the hangfire dashboard.
/// </summary>
/// <param name="aContext">Context we are accessing the dashboard in.</param>
/// <returns>Returns TRUE should the user be allowed to access the dashboard.</returns>
public bool Authorize(DashboardContext aContext)
{
// In case you need an OWIN context, use the next line, `OwinContext` class
// is the part of the `Microsoft.Owin` package.
OwinContext owinContext = new OwinContext(aContext.GetOwinEnvironment());
return true;
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration
.UseSqlServerStorage("default")
.UseConsole(new ConsoleOptions
{
BackgroundColor = "#0d3163",
TextColor = "#ffffff",
TimestampColor = "#00aad7"
});
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
AppPath = "/",
Authorization = new[]
{
new HangfireAuthorizationFilter()
}
});
BackgroundJobServerOptions serverOptions = new BackgroundJobServerOptions
{
};
app.UseHangfireServer(serverOptions); }
}
} | {
"content_hash": "f35143e5e857d3afc17e6cf1fc136ee0",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 95,
"avg_line_length": 31.93220338983051,
"alnum_prop": 0.5737791932059448,
"repo_name": "aspnetboilerplate/aspnetboilerplate-samples",
"id": "bd4c2487cf6d5a593d7b56a710d799afc89f267a",
"size": "1886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AbpHangfireConsoleApp/AbpHangfireConsole.Program/StartUp.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "810"
},
{
"name": "Batchfile",
"bytes": "238"
},
{
"name": "C#",
"bytes": "5155046"
},
{
"name": "CSS",
"bytes": "2951271"
},
{
"name": "CoffeeScript",
"bytes": "585417"
},
{
"name": "Dockerfile",
"bytes": "2615"
},
{
"name": "HTML",
"bytes": "7236415"
},
{
"name": "JavaScript",
"bytes": "73730233"
},
{
"name": "Less",
"bytes": "195106"
},
{
"name": "Makefile",
"bytes": "9583"
},
{
"name": "PowerShell",
"bytes": "86362"
},
{
"name": "Ruby",
"bytes": "5150"
},
{
"name": "SCSS",
"bytes": "1430882"
},
{
"name": "Sass",
"bytes": "23989"
},
{
"name": "Shell",
"bytes": "7868"
},
{
"name": "Stylus",
"bytes": "23527"
},
{
"name": "TypeScript",
"bytes": "140579"
}
],
"symlink_target": ""
} |
namespace Passanger.Core.Domain
{
public class Vehicle
{
public string Brand { get; protected set; }
public string Name { get; protected set; }
public int Seats { get; protected set; }
}
} | {
"content_hash": "f00faa5df739afccb4f6388288b9a7fd",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 51,
"avg_line_length": 22.6,
"alnum_prop": 0.6106194690265486,
"repo_name": "rabZ1/Tutorial-API",
"id": "75e946d99975a56880aa7962189d390651f1b162",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Passanger/Passanger.Core/Domain/Vehicle.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "26624"
},
{
"name": "CSS",
"bytes": "687"
},
{
"name": "JavaScript",
"bytes": "33"
},
{
"name": "Smalltalk",
"bytes": "616"
}
],
"symlink_target": ""
} |
package info.novatec.testit.webtester.eventsystem.events.pageobject;
import static java.lang.String.format;
import info.novatec.testit.webtester.api.events.Event;
import info.novatec.testit.webtester.pageobjects.Form;
import info.novatec.testit.webtester.pageobjects.PageObject;
/**
* This {@link Event event} occurs whenever a form is submitted.
*
* @see Event
* @see Form
* @since 1.2
*/
@SuppressWarnings("serial")
public class FormSubmittedEvent extends AbstractPageObjectEvent{
private static final String MESSAGE_FORMAT = "Submitted form: %s.";
public FormSubmittedEvent(PageObject pageObject) {
super(pageObject);
}
@Override
public String getEventMessage() {
return format(MESSAGE_FORMAT, getSubjectName());
}
}
| {
"content_hash": "d24ed2ca31b98a74b3c89053ba8dfa84",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 71,
"avg_line_length": 24.21875,
"alnum_prop": 0.7393548387096774,
"repo_name": "nicopaul/webtester-core",
"id": "e78033d5821fad8b41fbac41c096685ebf9bf1cc",
"size": "775",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "webtester-core/src/main/java/info/novatec/testit/webtester/eventsystem/events/pageobject/FormSubmittedEvent.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "42487"
},
{
"name": "Java",
"bytes": "999090"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/spencerwi/Connect4)
A simple web app to play Connect 4 vs a simple AI
## How to build it
### Step One: build the backend
1. Ensure that you have Ruby 2.x installed, along with Ruby's `gem` package manager and [Bundler](http://bundler.io)
2. Run `bundle install`
### Step Two: build the frontend
1. Ensure that you have Nodejs installed, along with its `npm` package manager.
2. In the `public/` directory, run `npm start`.
## How to run it
1. Build it (see "How to build it")
2. In the root of the repo, run `./bin/rackup`.
| {
"content_hash": "87de1e9dc73f9a0a169067b9fa4e8df9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 119,
"avg_line_length": 31.6,
"alnum_prop": 0.7104430379746836,
"repo_name": "spencerwi/Connect4",
"id": "3b2e5780dd18488357a42b8f565a69bfcf6f3788",
"size": "644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1024"
},
{
"name": "HTML",
"bytes": "373"
},
{
"name": "JavaScript",
"bytes": "588"
},
{
"name": "Ruby",
"bytes": "40509"
},
{
"name": "TypeScript",
"bytes": "6856"
}
],
"symlink_target": ""
} |
layout: post
disqus: true
title: "Iniciando en ruby"
date: 2018-04-11 16:56:50 -0300
categories: ruby
---
Hablando con un amigo que quiere iniciarse en el mundo de ruby, me pregunto que es lo primero que debería hacer para iniciar en ruby, la respuesta `instalar RVM`
> Pero ¿Que es RVM? "RVM es una herramienta de línea de comandos que le permite instalar, administrar y trabajar fácilmente con múltiples entornos ruby, desde intérpretes hasta conjuntos de gemas." by [RVM](https://rvm.io/)
En otras palabras si estas trabajando con muchos proyectos en ruby, cada proyecto usa una version diferente o igual de ruby, cada proyecto tiene sus propias gemas o comparten gemas pero estas gemas son versiones diferentes....mas o menos se van dando cuenta del problema de tener que administrar todos los ambientes?? Solución RVM, versiones de ruby separadas con sus propios conjunto de gems(gemsets)
No voy a hacer una guía para [instalar RVM](https://rvm.io/rvm/install), ya hay muchas guia de eso, pero si les voy a mostrar algunas características que pueden usar en sus proyectos.
- Instalar cualquier version de ruby `rvm install [version de ruby]`
- Ver version de ruby instaladas `rvm list`
- Cambiar de version de ruby `rvm use [version de ruby]`
- Crear un set de gems para un version de ruby `rvm gemset create [nombre del gemset]`
- Ver lista de gemsets para la version de ruby actual `rvm gemset list`
- Cambiar de gemset `rvm gemset use [nombre del gemset]`
- Copiar un gemset `rvm gemset copy [version de ruby de origen]@[nombre del gemset de origen] [version de ruby de destino]@[nombre del gemset de destino]`
- Si quieren linkear una version de ruby con un gemset especifico `rvm use --ruby-version [version de ruby]@[nombre del gemset]`, esto de linkear sirve para que cuando entres a una carpeta especifica se cambia automáticamente la version de rubi y el gemset

| {
"content_hash": "ced3706ae9a550966cfde6ee9b181cf0",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 401,
"avg_line_length": 78.88,
"alnum_prop": 0.7728194726166329,
"repo_name": "14tinchov/after_create",
"id": "f0e07328dc2f5dcf17073bcc390852677a19d135",
"size": "1986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_i18n/es/_posts/2018-04-11-iniciando-en-ruby.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40740"
},
{
"name": "HTML",
"bytes": "26992"
},
{
"name": "JavaScript",
"bytes": "5773"
},
{
"name": "Ruby",
"bytes": "1636"
}
],
"symlink_target": ""
} |
package uk.ac.manchester.cs.jfact.elf;
import conformance.PortedFrom;
// Rule for C [= \Er.D case; CR3
/** the rule for C [= \ER.D case */
@PortedFrom(file = "ELFReasoner.h", name = "RAddRule")
public class RAddRule extends TELFRule {
/** role to add the pair */
@PortedFrom(file = "ELFReasoner.h", name = "R")
TELFRole R;
/** filler (D) of the existential */
@PortedFrom(file = "ELFReasoner.h", name = "Filler")
TELFConcept Filler;
/** init c'tor: remember D */
RAddRule(ELFReasoner ER, TELFRole r, TELFConcept C) {
super(ER);
R = r;
Filler = C;
}
/** apply a method with a given source S(C) */
@Override
@PortedFrom(file = "ELFReasoner.h", name = "apply")
void apply(TELFConcept Source) {
ER.addAction(new ELFAction(R, Source, Filler));
}
}
| {
"content_hash": "349f891c499194db2a149712dd16fae7",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 57,
"avg_line_length": 28.79310344827586,
"alnum_prop": 0.6083832335329341,
"repo_name": "edlectrico/android-jfact",
"id": "6b3496952ec666feb789eee4362bd548e44499dd",
"size": "835",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/uk/ac/manchester/cs/jfact/elf/RAddRule.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1570914"
}
],
"symlink_target": ""
} |
(function (angular, jcs) {
'use strict';
/**
* @ngdoc service
* @name jcs-core.eventbus
* @requires $rootScope
*
* @description
* Provides a eventing mechanism when a user cna broadcast and subscribe to application wide events.
*/
angular.module(jcs.modules.core.name).factory(jcs.modules.core.services.eventbus, [
'$rootScope',
function ($rootScope) {
/**
* @ngdoc function
* @name subscribe
* @methodOf jcs-core.eventbus
*
* @description
* Subscribes a callback to the given application wide event
*
* @param {String} eventName The name of the event to subscribe to.
* @param {Function} callback A callback which is fire when the event is raised.
* @return {Function} A function tht can be called to unsubscrive to the event.
*/
var subscribe = function (eventName, callback) {
return $rootScope.$on(eventName, callback);
},
/**
* @ngdoc function
* @name broadcast
* @methodOf jcs-core.eventbus
*
* @description
* Broadcasts the given event and data.
*
* @param {String} eventName The name of the event to broadcast.
* @param {object} data A data object that will be passed along with the event.
*/
broadcast = function (eventName, data) {
$rootScope.$emit(eventName, data);
};
return {
subscribe: subscribe,
broadcast: broadcast
};
}
]);
}(angular, jcs)); | {
"content_hash": "034ea0e79d16eb9e2e2057000d27920f",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 104,
"avg_line_length": 35.25,
"alnum_prop": 0.5008183306055647,
"repo_name": "Zaknafeyn/expense-manager",
"id": "1708b1f320553816ad862edbc6339b8b36dca237",
"size": "1833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/modules/core/services/eventbus.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2783"
},
{
"name": "HTML",
"bytes": "16765"
},
{
"name": "JavaScript",
"bytes": "55926"
}
],
"symlink_target": ""
} |
/* ========================================================================== */
/* === CHOLMOD/MATLAB/cholmod mexFunction =================================== */
/* ========================================================================== */
/* -----------------------------------------------------------------------------
* CHOLMOD/MATLAB Module. Copyright (C) 2005-2006, Timothy A. Davis
* http://www.suitesparse.com
* MATLAB(tm) is a Trademark of The MathWorks, Inc.
* -------------------------------------------------------------------------- */
/* Supernodal sparse Cholesky backslash, x = A\b. Factorizes PAP' in LL' then
* solves a sparse linear system. Uses the diagonal and upper triangular part
* of A only. A must be sparse. b can be sparse or dense.
*
* Usage:
*
* x = cholmod2 (A, b)
* [x stats] = cholmod2 (A, b, ordering) % a scalar: 0,-1,-2, or -3
* [x stats] = cholmod2 (A, b, p) % a permutation vector
*
* The 3rd argument select the ordering method to use. If not present or -1,
* the default ordering strategy is used (AMD, and then try METIS if AMD finds
* an ordering with high fill-in, and use the best method tried).
*
* Other options for the ordering parameter:
*
* 0 natural (no etree postordering)
* -1 use CHOLMOD's default ordering strategy (AMD, then try METIS)
* -2 AMD, and then try NESDIS (not METIS) if AMD has high fill-in
* -3 use AMD only
* -4 use METIS only
* -5 use NESDIS only
* -6 natural, but with etree postordering
* p user permutation (vector of size n, with a permutation of 1:n)
*
* stats(1) estimate of the reciprocal of the condition number
* stats(2) ordering used:
* 0: natural, 1: given, 2:amd, 3:metis, 4:nesdis, 5:colamd,
* 6: natural but postordered.
* stats(3) nnz(L)
* stats(4) flop count in Cholesky factorization. Excludes solution
* of upper/lower triangular systems, which can be easily
* computed from stats(3) (roughly 4*nnz(L)*size(b,2)).
* stats(5) memory usage in MB.
*/
#include "cholmod_matlab.h"
void mexFunction
(
int nargout,
mxArray *pargout [ ],
int nargin,
const mxArray *pargin [ ]
)
{
double dummy = 0, rcond, *p ;
cholmod_sparse Amatrix, Bspmatrix, *A, *Bs, *Xs ;
cholmod_dense Bmatrix, *X, *B ;
cholmod_factor *L ;
cholmod_common Common, *cm ;
Long n, B_is_sparse, ordering, k, *Perm ;
/* ---------------------------------------------------------------------- */
/* start CHOLMOD and set parameters */
/* ---------------------------------------------------------------------- */
cm = &Common ;
cholmod_l_start (cm) ;
sputil_config (SPUMONI, cm) ;
/* There is no supernodal LDL'. If cm->final_ll = FALSE (the default), then
* this mexFunction will use a simplicial LDL' when flops/lnz < 40, and a
* supernodal LL' otherwise. This may give suprising results to the MATLAB
* user, so always perform an LL' factorization by setting cm->final_ll
* to TRUE. */
cm->final_ll = TRUE ;
cm->quick_return_if_not_posdef = TRUE ;
/* ---------------------------------------------------------------------- */
/* get inputs */
/* ---------------------------------------------------------------------- */
if (nargout > 2 || nargin < 2 || nargin > 3)
{
mexErrMsgTxt ("usage: [x,rcond] = cholmod2 (A,b,ordering)") ;
}
n = mxGetM (pargin [0]) ;
if (!mxIsSparse (pargin [0]) || (n != mxGetN (pargin [0])))
{
mexErrMsgTxt ("A must be square and sparse") ;
}
if (n != mxGetM (pargin [1]))
{
mexErrMsgTxt ("# of rows of A and B must match") ;
}
/* get sparse matrix A. Use triu(A) only. */
A = sputil_get_sparse (pargin [0], &Amatrix, &dummy, 1) ;
/* get sparse or dense matrix B */
B = NULL ;
Bs = NULL ;
B_is_sparse = mxIsSparse (pargin [1]) ;
if (B_is_sparse)
{
/* get sparse matrix B (unsymmetric) */
Bs = sputil_get_sparse (pargin [1], &Bspmatrix, &dummy, 0) ;
}
else
{
/* get dense matrix B */
B = sputil_get_dense (pargin [1], &Bmatrix, &dummy) ;
}
/* get the ordering option */
if (nargin < 3)
{
/* use default ordering */
ordering = -1 ;
}
else
{
/* use a non-default option */
ordering = mxGetScalar (pargin [2]) ;
}
p = NULL ;
Perm = NULL ;
if (ordering == 0)
{
/* natural ordering */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_NATURAL ;
cm->postorder = FALSE ;
}
else if (ordering == -1)
{
/* default strategy ... nothing to change */
}
else if (ordering == -2)
{
/* default strategy, but with NESDIS in place of METIS */
cm->default_nesdis = TRUE ;
}
else if (ordering == -3)
{
/* use AMD only */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_AMD ;
cm->postorder = TRUE ;
}
else if (ordering == -4)
{
/* use METIS only */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_METIS ;
cm->postorder = TRUE ;
}
else if (ordering == -5)
{
/* use NESDIS only */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_NESDIS ;
cm->postorder = TRUE ;
}
else if (ordering == -6)
{
/* natural ordering, but with etree postordering */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_NATURAL ;
cm->postorder = TRUE ;
}
else if (ordering == -7)
{
/* always try both AMD and METIS, and pick the best */
cm->nmethods = 2 ;
cm->method [0].ordering = CHOLMOD_AMD ;
cm->method [1].ordering = CHOLMOD_METIS ;
cm->postorder = TRUE ;
}
else if (ordering >= 1)
{
/* assume the 3rd argument is a user-provided permutation of 1:n */
if (mxGetNumberOfElements (pargin [2]) != n)
{
mexErrMsgTxt ("invalid input permutation") ;
}
/* copy from double to integer, and convert to 0-based */
p = mxGetPr (pargin [2]) ;
Perm = cholmod_l_malloc (n, sizeof (Long), cm) ;
for (k = 0 ; k < n ; k++)
{
Perm [k] = p [k] - 1 ;
}
/* check the permutation */
if (!cholmod_l_check_perm (Perm, n, n, cm))
{
mexErrMsgTxt ("invalid input permutation") ;
}
/* use only the given permutation */
cm->nmethods = 1 ;
cm->method [0].ordering = CHOLMOD_GIVEN ;
cm->postorder = FALSE ;
}
else
{
mexErrMsgTxt ("invalid ordering option") ;
}
/* ---------------------------------------------------------------------- */
/* analyze and factorize */
/* ---------------------------------------------------------------------- */
L = cholmod_l_analyze_p (A, Perm, NULL, 0, cm) ;
cholmod_l_free (n, sizeof (Long), Perm, cm) ;
cholmod_l_factorize (A, L, cm) ;
rcond = cholmod_l_rcond (L, cm) ;
if (rcond == 0)
{
mexWarnMsgTxt ("Matrix is indefinite or singular to working precision");
}
else if (rcond < DBL_EPSILON)
{
mexWarnMsgTxt ("Matrix is close to singular or badly scaled.") ;
mexPrintf (" Results may be inaccurate. RCOND = %g.\n", rcond) ;
}
/* ---------------------------------------------------------------------- */
/* solve and return solution to MATLAB */
/* ---------------------------------------------------------------------- */
if (B_is_sparse)
{
/* solve AX=B with sparse X and B; return sparse X to MATLAB */
Xs = cholmod_l_spsolve (CHOLMOD_A, L, Bs, cm) ;
pargout [0] = sputil_put_sparse (&Xs, cm) ;
}
else
{
/* solve AX=B with dense X and B; return dense X to MATLAB */
X = cholmod_l_solve (CHOLMOD_A, L, B, cm) ;
pargout [0] = sputil_put_dense (&X, cm) ;
}
/* return statistics, if requested */
if (nargout > 1)
{
pargout [1] = mxCreateDoubleMatrix (1, 5, mxREAL) ;
p = mxGetPr (pargout [1]) ;
p [0] = rcond ;
p [1] = L->ordering ;
p [2] = cm->lnz ;
p [3] = cm->fl ;
p [4] = cm->memory_usage / 1048576. ;
}
cholmod_l_free_factor (&L, cm) ;
cholmod_l_finish (cm) ;
cholmod_l_print_common (" ", cm) ;
/*
if (cm->malloc_count !=
(mxIsComplex (pargout [0]) + (mxIsSparse (pargout[0]) ? 3:1)))
mexErrMsgTxt ("memory leak!") ;
*/
}
| {
"content_hash": "074f535b9c8b9b61d00ca4da3e827882",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 80,
"avg_line_length": 29.874074074074073,
"alnum_prop": 0.5208281676171584,
"repo_name": "jlblancoc/suitesparse-metis-for-windows",
"id": "05af912ef0d25ae0fc49d8a8c76c215e3638683c",
"size": "8066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SuiteSparse/CHOLMOD/MATLAB/cholmod2.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Awk",
"bytes": "1372"
},
{
"name": "Batchfile",
"bytes": "156"
},
{
"name": "C",
"bytes": "18917607"
},
{
"name": "C++",
"bytes": "1381288"
},
{
"name": "CMake",
"bytes": "97889"
},
{
"name": "Cuda",
"bytes": "82351"
},
{
"name": "D",
"bytes": "740"
},
{
"name": "Fortran",
"bytes": "172674"
},
{
"name": "HTML",
"bytes": "100278"
},
{
"name": "Java",
"bytes": "269430"
},
{
"name": "M",
"bytes": "4328"
},
{
"name": "M4",
"bytes": "20897"
},
{
"name": "MATLAB",
"bytes": "3001034"
},
{
"name": "Makefile",
"bytes": "359086"
},
{
"name": "NASL",
"bytes": "107"
},
{
"name": "Perl",
"bytes": "9412"
},
{
"name": "Python",
"bytes": "14188"
},
{
"name": "Roff",
"bytes": "9481"
},
{
"name": "Ruby",
"bytes": "51657"
},
{
"name": "Shell",
"bytes": "122066"
},
{
"name": "TeX",
"bytes": "972029"
},
{
"name": "sed",
"bytes": "1660"
}
],
"symlink_target": ""
} |
InvalidArgumentException = function(args) {
this.message = 'Invalid Argument Received';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(InvalidArgumentException, Thrift.TException);
InvalidArgumentException.prototype.name = 'InvalidArgumentException';
InvalidArgumentException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
InvalidArgumentException.prototype.write = function(output) {
output.writeStructBegin('InvalidArgumentException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
InvalidCredentialsException = function(args) {
this.message = 'Failed to Verify and Authenticate Credentials';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(InvalidCredentialsException, Thrift.TException);
InvalidCredentialsException.prototype.name = 'InvalidCredentialsException';
InvalidCredentialsException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
InvalidCredentialsException.prototype.write = function(output) {
output.writeStructBegin('InvalidCredentialsException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
InvalidTokenException = function(args) {
this.message = 'The specified token is invalid';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(InvalidTokenException, Thrift.TException);
InvalidTokenException.prototype.name = 'InvalidTokenException';
InvalidTokenException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
InvalidTokenException.prototype.write = function(output) {
output.writeStructBegin('InvalidTokenException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
AccountAlreadyExistsException = function(args) {
this.message = 'This email has already been registered. Reset your password if you forgot it.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(AccountAlreadyExistsException, Thrift.TException);
AccountAlreadyExistsException.prototype.name = 'AccountAlreadyExistsException';
AccountAlreadyExistsException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
AccountAlreadyExistsException.prototype.write = function(output) {
output.writeStructBegin('AccountAlreadyExistsException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
InvalidCodeException = function(args) {
this.message = 'The Reset Password is invalid';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(InvalidCodeException, Thrift.TException);
InvalidCodeException.prototype.name = 'InvalidCodeException';
InvalidCodeException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
InvalidCodeException.prototype.write = function(output) {
output.writeStructBegin('InvalidCodeException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
UnauthorizedException = function(args) {
this.message = 'Only an Owner can do that';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(UnauthorizedException, Thrift.TException);
UnauthorizedException.prototype.name = 'UnauthorizedException';
UnauthorizedException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
UnauthorizedException.prototype.write = function(output) {
output.writeStructBegin('UnauthorizedException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
DoesNotExistException = function(args) {
this.message = 'The requested resource does not exist';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(DoesNotExistException, Thrift.TException);
DoesNotExistException.prototype.name = 'DoesNotExistException';
DoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
DoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('DoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
ApplicationDoesNotExistException = function(args) {
this.message = 'The Specified Application does not exist.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(ApplicationDoesNotExistException, Thrift.TException);
ApplicationDoesNotExistException.prototype.name = 'ApplicationDoesNotExistException';
ApplicationDoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
ApplicationDoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('ApplicationDoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
ApplicationAlreadyRegisteredException = function(args) {
this.message = 'This Channel has already been registered for this Application.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(ApplicationAlreadyRegisteredException, Thrift.TException);
ApplicationAlreadyRegisteredException.prototype.name = 'ApplicationAlreadyRegisteredException';
ApplicationAlreadyRegisteredException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
ApplicationAlreadyRegisteredException.prototype.write = function(output) {
output.writeStructBegin('ApplicationAlreadyRegisteredException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
UserDoesNotExistException = function(args) {
this.message = 'The User you\'re referring to does not exist.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(UserDoesNotExistException, Thrift.TException);
UserDoesNotExistException.prototype.name = 'UserDoesNotExistException';
UserDoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
UserDoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('UserDoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
ThroughoutExceededException = function(args) {
this.message = 'You have exceeded your allocated throughput. Buy more or slow down.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(ThroughoutExceededException, Thrift.TException);
ThroughoutExceededException.prototype.name = 'ThroughoutExceededException';
ThroughoutExceededException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
ThroughoutExceededException.prototype.write = function(output) {
output.writeStructBegin('ThroughoutExceededException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
CustomChannelUnreachableException = function(args) {
this.message = 'The Custom Channel you\'ve supplied could not be reached. Please ensure the Application is reachable and operational.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(CustomChannelUnreachableException, Thrift.TException);
CustomChannelUnreachableException.prototype.name = 'CustomChannelUnreachableException';
CustomChannelUnreachableException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
CustomChannelUnreachableException.prototype.write = function(output) {
output.writeStructBegin('CustomChannelUnreachableException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
ChannelDoesNotExistException = function(args) {
this.message = 'The Channel specified does not exist in the System.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(ChannelDoesNotExistException, Thrift.TException);
ChannelDoesNotExistException.prototype.name = 'ChannelDoesNotExistException';
ChannelDoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
ChannelDoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('ChannelDoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
MessageDoesNotExistException = function(args) {
this.message = 'The Message specified does not exist.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(MessageDoesNotExistException, Thrift.TException);
MessageDoesNotExistException.prototype.name = 'MessageDoesNotExistException';
MessageDoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
MessageDoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('MessageDoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
OrganizationDoesNotExistException = function(args) {
this.message = 'The Organization specified does not exist.';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(OrganizationDoesNotExistException, Thrift.TException);
OrganizationDoesNotExistException.prototype.name = 'OrganizationDoesNotExistException';
OrganizationDoesNotExistException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
OrganizationDoesNotExistException.prototype.write = function(output) {
output.writeStructBegin('OrganizationDoesNotExistException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
OperationFailedException = function(args) {
this.message = 'The Operation could not be completed';
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
}
};
Thrift.inherits(OperationFailedException, Thrift.TException);
OperationFailedException.prototype.name = 'OperationFailedException';
OperationFailedException.prototype.read = function(input) {
input.readStructBegin();
while (true)
{
var ret = input.readFieldBegin();
var fname = ret.fname;
var ftype = ret.ftype;
var fid = ret.fid;
if (ftype == Thrift.Type.STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == Thrift.Type.STRING) {
this.message = input.readString().value;
} else {
input.skip(ftype);
}
break;
case 0:
input.skip(ftype);
break;
default:
input.skip(ftype);
}
input.readFieldEnd();
}
input.readStructEnd();
return;
};
OperationFailedException.prototype.write = function(output) {
output.writeStructBegin('OperationFailedException');
if (this.message !== null && this.message !== undefined) {
output.writeFieldBegin('message', Thrift.Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
}
output.writeFieldStop();
output.writeStructEnd();
return;
};
| {
"content_hash": "2b37a79dc559ecbbe409c3e80cdf9ac1",
"timestamp": "",
"source": "github",
"line_count": 864,
"max_line_length": 137,
"avg_line_length": 26.074074074074073,
"alnum_prop": 0.6472833806818182,
"repo_name": "RedRoma/banana-thrift",
"id": "73dedcc0f4723a1cabbca281c001c4aa21964205",
"size": "22652",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "src/main/js/Exceptions_types.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "20874"
},
{
"name": "Java",
"bytes": "64828"
},
{
"name": "Thrift",
"bytes": "73582"
}
],
"symlink_target": ""
} |
class Gemini::XyzRule < Marty::DeloreanRule
self.table_name = 'gemini_xyz_rules'
validates :rule_type, presence: true
gen_mcfly_lookup :lookup, {
name: false,
}
cached_mcfly_lookup :lookup_id, sig: 2 do
|pt, group_id|
find_by_group_id group_id
end
mcfly_validates_uniqueness_of :name
def self.results_cfg_var
'RULEOPTS_XYZ'
end
def self.guard_info
super + {"flavors" => { multi: true,
type: :string,
allow_not: false,
enum: Gemini::XyzEnum,
width: 150},
"guard_two" => { type: :string,
enum: Gemini::GuardTwo,
width: 100},
"g_date" => { type: :date },
"g_datetime" => { type: :datetime },
"g_string" => { type: :string,
width: 100},
"g_bool" => { type: :boolean,
width: 100,
null: false},
"g_range1" => { type: :range,
width: 100},
"g_range2" => { type: :range,
width: 100},
"g_integer" => { type: :integer,
width: 100}
}
end
mcfly_lookup :get_matches, sig: 3 do
|pt, attrs, params|
get_matches_(pt, attrs, params)
end
def compute(*args)
base_compute2(*args)
end
def compute_xyz(pt, xyz_param)
# Given a set of parameters, compute the RULE adjustment. Returns
# {} if precondition is not met.
xyz_keys = computed_guards.select{|k,_|k.starts_with?("xyz_")}.keys
return {} unless xyz_keys.present?
eclass = engine && engine.constantize || Marty::RuleScriptSet
engine = eclass.new(pt).get_engine(self_as_hash)
res = engine.evaluate("XyzNode", xyz_keys, {"xyz_param"=>xyz_param})
res.all?
end
end
| {
"content_hash": "40588c2be848583470421074dddc530a",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 72,
"avg_line_length": 29.651515151515152,
"alnum_prop": 0.4885028104241185,
"repo_name": "arman000/marty",
"id": "bbee948bddd10f4af4660a60ec312389dce60781",
"size": "1957",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/dummy/app/models/gemini/xyz_rule.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11758"
},
{
"name": "CoffeeScript",
"bytes": "583"
},
{
"name": "HTML",
"bytes": "6610"
},
{
"name": "JavaScript",
"bytes": "454002"
},
{
"name": "Makefile",
"bytes": "1396"
},
{
"name": "Python",
"bytes": "4061"
},
{
"name": "Ruby",
"bytes": "1085566"
}
],
"symlink_target": ""
} |
Task_t* Debounce(void);
#endif | {
"content_hash": "0ec6d2418f1c170c6d0b245d1c698b6c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 23,
"avg_line_length": 10.333333333333334,
"alnum_prop": 0.7096774193548387,
"repo_name": "ferdinandkeil/humidor-steuerung",
"id": "628e734eef5bf6095fa0dca910c22a784e3f79f6",
"size": "131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "debounce.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "107077"
},
{
"name": "C++",
"bytes": "131"
},
{
"name": "Objective-C",
"bytes": "1797"
},
{
"name": "PHP",
"bytes": "1013"
},
{
"name": "Shell",
"bytes": "78"
}
],
"symlink_target": ""
} |
require "rails_helper"
describe Project do
before do
@attr = {
url: 'https://github.com/some_project',
name: 'some_project'
}
end
after(:all) do
@attr.destroy
end
it "should create a new instance given a valid attribute" do
Project.create!(@attr)
end
it "should require url" do
no_url_project = Project.new(@attr.merge(:url => nil))
expect(no_url_project).not_to be_valid
end
it "should require name" do
no_name_project = Project.new(@attr.merge(:name => nil))
expect(no_name_project).not_to be_valid
end
end | {
"content_hash": "f38c90a0ee853cc2bd44d563d9961e8b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 62,
"avg_line_length": 19.96551724137931,
"alnum_prop": 0.6424870466321243,
"repo_name": "MarcosOcf/project-view",
"id": "176e72d9f292a9304a1c29adf8d73ad9872c5de3",
"size": "579",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/project_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15049"
},
{
"name": "CoffeeScript",
"bytes": "422"
},
{
"name": "JavaScript",
"bytes": "664"
},
{
"name": "Ruby",
"bytes": "25654"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TraffiSnooze.Domain.Models
{
public class WakeUpRoutine
{
public Guid Id { get; set; }
public Guid RouteId { get; set; }
public virtual Route Route { get; set; }
public string Name { get; set;}
public DateTime ShouldArriveAt { get; set; }
public TimeSpan TimeNeededAfterWakeUp { get; set; }
}
}
| {
"content_hash": "fa6efe71157138698f71ed10b2c71e08",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 59,
"avg_line_length": 21.565217391304348,
"alnum_prop": 0.6431451612903226,
"repo_name": "dbpieter/TraffiSnooze",
"id": "539dd7a54b2a985e48e1fe1b5de687923d9c6011",
"size": "498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TraffiSnooze.Domain/Models/WakeUpRoutine.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "31243"
},
{
"name": "HTML",
"bytes": "572"
},
{
"name": "JavaScript",
"bytes": "3728"
},
{
"name": "Shell",
"bytes": "363"
},
{
"name": "TypeScript",
"bytes": "449"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: mockie
* Date: 9/28/14
* Time: 5:20 PM.
*/
namespace LearnZF2Ajax\Model;
use Zend\InputFilter\Factory as InputFactory; // <-- Add this import
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class LoginInputFilter implements InputFilterAwareInterface
{
public $username;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->password = (isset($data['password'])) ? $data['password'] : null;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception('Not used');
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput([
'name' => 'username',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 4,
'max' => 10,
],
],
[
'name' => 'Regex',
'options' => [
'pattern' => '/admin/',
],
],
],
]));
$inputFilter->add($factory->createInput([
'name' => 'password',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 4,
'max' => 10,
],
],
[
'name' => 'Regex',
'options' => [
'pattern' => '/admin/',
],
],
],
]));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
| {
"content_hash": "bb581617b5b503571a8c2ca87941bd5c",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 82,
"avg_line_length": 28.905263157894737,
"alnum_prop": 0.3739985433357611,
"repo_name": "samsonasik/LearnZF2",
"id": "c7ba16314869e6ab8095034c873d43630226b8fb",
"size": "2746",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/LearnZF2Ajax/src/LearnZF2Ajax/Model/LoginInputFilter.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "751"
},
{
"name": "CSS",
"bytes": "18592"
},
{
"name": "HTML",
"bytes": "186899"
},
{
"name": "JavaScript",
"bytes": "11474"
},
{
"name": "PHP",
"bytes": "1247721"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 103: 301 (2008)
#### Original name
Candelabrochaete macaronesica M. Dueñas, Tellería & Melo
### Remarks
null | {
"content_hash": "6991a263a4c516208016370b5aa42ec5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 56,
"avg_line_length": 14,
"alnum_prop": 0.7252747252747253,
"repo_name": "mdoering/backbone",
"id": "f8be3c318b697ffd0761716599e45639e034886a",
"size": "266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Phanerochaetaceae/Candelabrochaete/Candelabrochaete macaronesica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "98e792eae1f209b6b43666e574484f3a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "3839ca969ede1c5954f05ea2372f351e1a11b46e",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Phragmipedium/Phragmipedium longifolium/ Syn. Selenipedium reichenbachii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<bill session="115" type="hc" number="42" updated="2017-09-19T20:00:13Z">
<state datetime="2017-03-29">REFERRED</state>
<status>
<introduced datetime="2017-03-29"/>
</status>
<introduced datetime="2017-03-29"/>
<titles>
<title type="official" as="introduced">Expressing the sense of Congress that the Supreme Court misinterpreted the First Amendment to the Constitution in the case of Buckley v. Valeo.</title>
<title type="display">Expressing the sense of Congress that the Supreme Court misinterpreted the First Amendment to the Constitution in the case of Buckley v. Valeo.</title>
</titles>
<sponsor bioguide_id="K000009"/>
<cosponsors>
<cosponsor bioguide_id="B000574" joined="2017-03-29"/>
<cosponsor bioguide_id="C000714" joined="2017-03-29"/>
<cosponsor bioguide_id="D000191" joined="2017-03-29"/>
<cosponsor bioguide_id="G000410" joined="2017-03-29"/>
<cosponsor bioguide_id="H001038" joined="2017-03-29"/>
<cosponsor bioguide_id="M001185" joined="2017-03-29"/>
<cosponsor bioguide_id="N000147" joined="2017-03-29"/>
<cosponsor bioguide_id="R000606" joined="2017-03-29"/>
<cosponsor bioguide_id="S001145" joined="2017-03-29"/>
<cosponsor bioguide_id="S000480" joined="2017-03-29"/>
<cosponsor bioguide_id="S001200" joined="2017-03-29"/>
</cosponsors>
<actions>
<action datetime="2017-03-29">
<text>Introduced in House</text>
</action>
<action datetime="2017-03-29">
<text>Sponsor introductory remarks on measure.</text>
<reference ref="CR H2550, E411"/>
</action>
<action datetime="2017-03-29" state="REFERRED">
<text>Referred to the House Committee on the Judiciary.</text>
</action>
<action datetime="2017-03-29">
<text>Referred to the Subcommittee on the Constitution and Civil Justice.</text>
</action>
</actions>
<committees>
<committee subcommittee="" code="HSJU" name="House Judiciary" activity="Referral"/>
<committee subcommittee="Constitution and Civil Justice" code="HSJU10" name="House Judiciary" activity="Referral"/>
</committees>
<relatedbills/>
<subjects>
<term name="Government operations and politics"/>
<term name="Constitution and constitutional amendments"/>
<term name="Elections, voting, political campaign regulation"/>
<term name="First Amendment rights"/>
<term name="Supreme Court"/>
</subjects>
<amendments/>
<summary date="2017-03-29T04:00:00Z" status="Introduced in House">Expresses the sense of Congress that the Supreme Court misinterpreted the First Amendment in the case of Buckley v. Valeo because the decision failed to recognize: (1) that the unlimited spending of large amounts of money on elections has a corrosive effect on the electoral process not simply because of direct transactions between those who give large amounts of money and candidates and elected officials but because the presence of unlimited amounts of money corrupts the process on a more fundamental level; and (2) other legitimate state interests which justify limiting money in campaigns, including the need to preserve the integrity of our republican form of government, restore public confidence in government, and ensure all citizens a more equal opportunity to participate in the political process.</summary>
<committee-reports/>
</bill>
| {
"content_hash": "d78ebce531af4fcfcda8999fc05e5535",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 888,
"avg_line_length": 60.836363636363636,
"alnum_prop": 0.726240286909743,
"repo_name": "peter765/power-polls",
"id": "9301b0dc538301d0a72e43d19443e2b52b872eaf",
"size": "3346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/bills/hconres/hconres42/data.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "58567"
},
{
"name": "JavaScript",
"bytes": "7370"
},
{
"name": "Python",
"bytes": "22988"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<LearningStandards>
<LearningStandardItem xml:lang="en" RefID="E8C42265F5F341ea9C0284AA7BDC65AF">
<RefURI>http://corestandards.org/Math/Content/HSF/IF/C/8/b/</RefURI>
<StandardHierarchyLevel>
<number>8</number>
<description>Component</description>
</StandardHierarchyLevel>
<StatementCodes>
<StatementCode>CCSS.Math.Content.HSF-IF.C.8b</StatementCode>
</StatementCodes>
<Statements>
<Statement>Use the properties of exponents to interpret expressions for exponential functions. For example, identify percent rate of change in functions such as y = (1.02)t, y = (0.97)t, y = (1.01)12t, y = (1.2)t/10, and classify them as representing exponential growth or decay.</Statement>
</Statements>
<GradeLevels>
<GradeLevel>09</GradeLevel>
<GradeLevel>10</GradeLevel>
<GradeLevel>11</GradeLevel>
<GradeLevel>12</GradeLevel>
</GradeLevels>
<LearningStandardDocumentRefId>B62C1C106873438AA0126760075A65A3</LearningStandardDocumentRefId>
<RelatedLearningStandardItems>
<LearningStandardItemRefId RelationshipType="childOf">B6B625DA12C4423d955A66BFD1193175</LearningStandardItemRefId>
</RelatedLearningStandardItems>
</LearningStandardItem>
</LearningStandards>
| {
"content_hash": "708c589bd52c78fe44b5a52ea00a0b98",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 297,
"avg_line_length": 49.76923076923077,
"alnum_prop": 0.7426584234930448,
"repo_name": "thricehex/CurricuLab",
"id": "edec9086658d0284a678b515e7f96bd4623a54ee",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CLResources/ccssi/xml/math/content/hsf/if/c/8/b.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2786"
},
{
"name": "Java",
"bytes": "64123"
}
],
"symlink_target": ""
} |
@interface EventCell ()
{
IBOutlet UILabel* _timeLabel;
IBOutlet UILabel* _titleLabel;
}
@end
@implementation EventCell
@synthesize timeLabel = _timeLabel;
@synthesize titleLabel = _titleLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
| {
"content_hash": "11c9e7d58f84467bb47584dbb9824a9c",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 91,
"avg_line_length": 20.533333333333335,
"alnum_prop": 0.7224025974025974,
"repo_name": "pantone170145/itCalendar",
"id": "abd8da0d6550bf49c27ef2ef42709d9f069d9c5a",
"size": "782",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ITCalendar/Classes/ViewControllers/Cell/EventCell.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4411"
},
{
"name": "Objective-C",
"bytes": "578332"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('inventory', '0011_auto_20160722_0918'),
('datastore', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('workflows', '0014_tasktemplate_multiple_products_on_labware'),
]
operations = [
migrations.CreateModel(
name='Run',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('tasks', models.CommaSeparatedIntegerField(blank=True, max_length=400)),
('identifier', models.UUIDField(editable=False, default=uuid.uuid4)),
('is_active', models.BooleanField(default=False)),
('date_started', models.DateTimeField(auto_now_add=True)),
('date_finished', models.DateTimeField(blank=True, null=True)),
],
options={
'ordering': ['-date_started'],
'permissions': (('view_run', 'View run'),),
},
),
migrations.CreateModel(
name='RunLabware',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('identifier', models.CharField(db_index=True, max_length=100)),
('labware', models.ForeignKey(to='inventory.Item')),
],
),
migrations.RemoveField(
model_name='workflowproduct',
name='run_identifier',
),
migrations.AddField(
model_name='dataentry',
name='data_files',
field=models.ManyToManyField(to='datastore.DataFile', blank=True),
),
migrations.AddField(
model_name='tasktemplate',
name='labware_amount',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='run',
name='labware',
field=models.ManyToManyField(to='workflows.RunLabware', blank=True, related_name='run_labware'),
),
migrations.AddField(
model_name='run',
name='products',
field=models.ManyToManyField(to='workflows.WorkflowProduct', blank=True, related_name='run'),
),
migrations.AddField(
model_name='run',
name='started_by',
field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
),
]
| {
"content_hash": "29c87ced37f0a40180dab17313f092c3",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 114,
"avg_line_length": 37.642857142857146,
"alnum_prop": 0.5620493358633776,
"repo_name": "GETLIMS/LIMS-Backend",
"id": "f7acb21cc0b2abb172c261a1b430783c8abac748",
"size": "2659",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lims/workflows/migrations/0015_auto_20160906_0833.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "474"
},
{
"name": "Python",
"bytes": "231759"
}
],
"symlink_target": ""
} |
package ch.uzh.ifi.seal.permo.lib.ui.swt.builder;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.ui.dialogs.PreferencesUtil;
import ch.uzh.ifi.seal.permo.lib.ui.eclipse.WorkbenchUtil;
/**
* A builder for {@link PreferenceDialog}'s.
*/
public class PreferenceDialogBuilder {
private String shownPageId;
private String[] displayedPageIds;
private Object data;
private PreferenceDialogBuilder() {
this.shownPageId = null;
this.displayedPageIds = null;
this.data = null;
}
/**
* Creates the {@link PreferenceDialog}.
*
* @return the created {@link PreferenceDialog}
*/
public PreferenceDialog create() {
return PreferencesUtil.createPreferenceDialogOn(WorkbenchUtil.activeShell(), shownPageId, displayedPageIds, data);
}
/**
* Specify the filter of the {@link PreferenceDialog}.
*
* @param pageIds
* the ID's of the preference pages that shall be included in the {@link PreferenceDialog}
* @return the current {@link PreferenceDialogBuilder}
*/
public PreferenceDialogBuilder filter(final String... pageIds) {
this.displayedPageIds = pageIds;
return this;
}
/**
* Specifies the page that shall be visible when opening the {@link PreferenceDialog}.
*
* @param pageId
* the ID of the page that shall be visible
* @return the current {@link PreferenceDialogBuilder}
*/
public PreferenceDialogBuilder show(final String pageId) {
this.shownPageId = pageId;
return this;
}
/**
* Specifies a single page that shall be included and visible in the {@link PreferenceDialog}.
*
* @param pageId
* the ID of the page to be included in the {@link PreferenceDialog}
* @return the current {@link PreferenceDialogBuilder}
*/
public PreferenceDialogBuilder showOnly(final String pageId) {
show(pageId);
filter(new String[] { pageId });
return this;
}
/**
* Creates a new builder for {@link PreferenceDialog}'s.
*
* @return a new builder for {@link PreferenceDialog}'s.
*/
public static PreferenceDialogBuilder of() {
return new PreferenceDialogBuilder();
}
}
| {
"content_hash": "f95b30c2a0290f86c39c3424d665a64e",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 118,
"avg_line_length": 27.531645569620252,
"alnum_prop": 0.6924137931034483,
"repo_name": "sealuzh/Permo",
"id": "b713e376dc78a95cbb9a6f93d7b162f612fd8d80",
"size": "2975",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Permo/src/ch/uzh/ifi/seal/permo/lib/ui/swt/builder/PreferenceDialogBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "11156"
},
{
"name": "Java",
"bytes": "376193"
}
],
"symlink_target": ""
} |
package org.reclipse.structure.generator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.fujaba.commons.console.IReportListener;
import org.reclipse.structure.generator.steps.AnnotateStep;
import org.reclipse.structure.generator.steps.FindAdditionalElementsStep;
import org.reclipse.structure.generator.steps.FindSetFragmentsStep;
import org.reclipse.structure.generator.util.Constants;
import org.reclipse.structure.generator.util.EcoreUtil;
import org.reclipse.structure.generator.util.IGenerator;
import org.reclipse.structure.generator.util.NameUtil;
import org.reclipse.structure.inference.annotations.AnnotationsPackage;
import org.reclipse.structure.specification.ModifierType;
import org.reclipse.structure.specification.PSCatalog;
import org.reclipse.structure.specification.PSCombinedFragment;
import org.reclipse.structure.specification.PSCombinedFragmentItem;
import org.reclipse.structure.specification.PSMetricConstraint;
import org.reclipse.structure.specification.PSNode;
import org.reclipse.structure.specification.PSNodeConstraint;
import org.reclipse.structure.specification.PSPatternSpecification;
import org.reclipse.structure.specification.SpecificationFactory;
import org.reclipse.structure.specification.util.SpecificationUtil;
import org.reclipse.structure.specification.util.TriggerManager;
import org.storydriven.storydiagrams.StorydiagramsPackage;
import org.storydriven.storydiagrams.activities.ActivitiesFactory;
import org.storydriven.storydiagrams.activities.Activity;
import org.storydriven.storydiagrams.activities.OperationExtension;
public class Generator implements IGenerator, Constants
{
private final IReportListener reporter;
private final Map<PSPatternSpecification, EClass> annotations;
private final Map<PSPatternSpecification, EClass> engines;
private final Map<PSPatternSpecification, Map<String, Activity>> activities;
private final AnnotateStep annotateGenerator;
private final FindSetFragmentsStep setsGenerator;
private final FindAdditionalElementsStep additionalsGenerator;
private TriggerManager triggerManager;
public Generator(IReportListener reporter)
{
// StorydiagramsPackage p = StorydiagramsPackage.eINSTANCE;
this.reporter = reporter;
annotateGenerator = new AnnotateStep(this);
setsGenerator = new FindSetFragmentsStep(this);
additionalsGenerator = new FindAdditionalElementsStep(this);
annotations = new HashMap<PSPatternSpecification, EClass>();
engines = new HashMap<PSPatternSpecification, EClass>();
activities = new HashMap<PSPatternSpecification, Map<String, Activity>>();
}
public void generate(Collection<EObject> container, PSCatalog catalog)
{
EPackage annotationPackage = createAnnotationsPackage(container);
createAnnotationClasses(catalog, annotationPackage);
triggerManager = new TriggerManager(this, catalog.getPatternSpecifications());
EPackage enginesPackage = createEnginesPackage(container);
createEngineClasses(catalog, enginesPackage);
}
/**
* Create engine classes.
*
* @param catalog
* @param enginesPackage
*/
private void createEngineClasses(PSCatalog catalog, EPackage enginesPackage)
{
for (PSPatternSpecification pattern : catalog.getPatternSpecifications())
{
if (!pattern.isAbstract())
{
workaroundSets(pattern);
workaroundNegatives(pattern);
// translate pattern into class with story patterns
addEngineClass(enginesPackage, pattern);
revertWorkaroundSets(pattern);
revertWorkaroundNegatives(pattern);
}
}
}
/**
* Create the engines package.
*
* @param container
* @return
*/
private EPackage createEnginesPackage(Collection<EObject> container)
{
debug("Creating package '%1s'...", PACKAGE_NAME_ENGINES);
EPackage enginesPackage = EcoreUtil.addEPackage(container, PACKAGE_NAME_ENGINES, PACKAGE_URI_ENGINES);
return enginesPackage;
}
/**
* Create annotation classes.
*
* @param catalog
* @param annotationPackage
*/
private void createAnnotationClasses(PSCatalog catalog, EPackage annotationPackage)
{
for (PSPatternSpecification pattern : catalog.getPatternSpecifications())
{
addAnnotationClass(annotationPackage, pattern);
}
}
/**
* Create the annotations package.
*
* @param container
* @return
*/
private EPackage createAnnotationsPackage(Collection<EObject> container)
{
debug("Creating package '%1s'...", PACKAGE_NAME_ANNOTATIONS);
EPackage annotationPackage = EcoreUtil.addEPackage(container, PACKAGE_NAME_ANNOTATIONS, PACKAGE_URI_ANNOTATIONS);
return annotationPackage;
}
private EClass addAnnotationClass(EPackage container, PSPatternSpecification pattern)
{
// check if the class is already created
if (annotations.containsKey(pattern))
{
return annotations.get(pattern);
}
// make name
String name = pattern.getName() + SUFFIX_ANNOTATION;
// create class
debug("Creating class '%1s'...", name);
EClass element = EcoreUtil.addEClass(container, name);
// cache it
annotations.put(pattern, element);
// get super type
EClass superType = AnnotationsPackage.Literals.ASG_ANNOTATION;
// create super annotation first
if (pattern.getSuperPattern() != null)
{
superType = addAnnotationClass(container, pattern.getSuperPattern());
}
element.getESuperTypes().add(superType);
return element;
}
private void addEngineClass(EPackage container, PSPatternSpecification pattern)
{
// make name
String name = pattern.getName() + SUFFIX_ENGINE;
// create engine class
debug("Creating class '%1s'...", pattern.getName() + SUFFIX_ENGINE);
EClass engineClass = EcoreUtil.addEClass(container, name);
engines.put(pattern, engineClass);
engineClass.getESuperTypes().add(AnnotationsPackage.Literals.ANNOTATION_ENGINE);
// create methods and activities
if (setsContainedIn(pattern))
{
Activity findSetFragements = createFindSets(engineClass, pattern);
setsGenerator.generate(findSetFragements, pattern);
}
if (SpecificationUtil.isAdditionalElements(pattern))
{
Activity findAdditionalElements = createFindAdditionals(engineClass, pattern);
additionalsGenerator.generate(findAdditionalElements, pattern);
}
// generate main method
Activity annotate = createAnnotate(engineClass, pattern);
annotateGenerator.generate(annotate, pattern);
}
private boolean setsContainedIn(PSPatternSpecification pattern)
{
return SpecificationUtil.isSetSearchRequired(pattern);
}
/**
* Replace every set node in the given pattern with a set fragment that contains that node. The
* set modifier is then removed. This workaround allows to handle set nodes and fragments
* uniformly (i.e. as set fragments).
*
* @param pattern The current pattern specification in which the set nodes are replaced.
*/
private void workaroundSets(PSPatternSpecification pattern)
{
for (PSNode node : pattern.getNodes())
{
if (ModifierType.SET.equals(node.getModifier()))
{
node.setModifier(ModifierType.NONE);
PSCombinedFragment wrapper = SpecificationFactory.eINSTANCE.createPSCombinedFragment();
wrapper.setKind(ModifierType.SET);
wrapper.setName(node.getName() + SUFFIX_WRAPPER);
wrapper.setWeight(node.getWeight());
wrapper.setPatternSpecification(pattern);
wrapper.getChildren().add(node);
PSNodeConstraint constraint = null;
for (PSNodeConstraint nodeConstraint : node.getNodeConstraints())
{
if (constraint != null)
{
warn("Could not wrap set node '%1s' with a fragment: Found more than one SIZE constraint!",
node.getName());
}
if (nodeConstraint instanceof PSMetricConstraint
&& "SIZE".equals(((PSMetricConstraint) nodeConstraint).getMetricAcronym()))
{
constraint = nodeConstraint;
}
}
node.getNodeConstraints().remove(constraint);
wrapper.setConstraint(constraint);
}
}
}
/**
* Replace every negative object in the given pattern with a negative fragment that contains that
* node. The negative modifier is then removed. This workaround allows to handle negative objects
* and fragments uniformly (i.e. as negative fragments).
*
* @param pattern The current pattern specification in which the negative objects are replaced.
*/
private void workaroundNegatives(PSPatternSpecification pattern)
{
for (PSNode node : pattern.getNodes())
{
if (ModifierType.NEGATIVE.equals(node.getModifier()))
{
node.setModifier(ModifierType.NONE);
PSCombinedFragment wrapper = SpecificationFactory.eINSTANCE.createPSCombinedFragment();
wrapper.setKind(ModifierType.NEGATIVE);
wrapper.setName(node.getName() + SUFFIX_WRAPPER);
wrapper.setWeight(node.getWeight());
wrapper.getChildren().add(node);
PSNodeConstraint constraint = null;
for (PSNodeConstraint nodeConstraint : node.getNodeConstraints())
{
if (constraint != null)
{
warn("Could not wrap negative node '%1s' with a fragment: Found more than one SIZE constraint!",
node.getName());
}
if (nodeConstraint instanceof PSMetricConstraint
&& "SIZE".equals(((PSMetricConstraint) nodeConstraint).getMetricAcronym()))
{
constraint = nodeConstraint;
}
}
node.getNodeConstraints().remove(constraint);
wrapper.setConstraint(constraint);
wrapper.setPatternSpecification(pattern);
}
}
}
private Activity createFindSets(EClass engineClass, PSPatternSpecification pattern)
{
// add the operation
EOperation operation = EcoreUtil.addEOperation(engineClass, METHOD_FIND_SETS);
operation.setEType(EcorePackage.Literals.EBOOLEAN);
// add 'this' parameter
EcoreUtil.addEParameter(operation, VAR_THIS, engineClass);
// add 'annotation' parameter
EcoreUtil.addEParameter(operation, VAR_ANNOTATION, AnnotationsPackage.Literals.ASG_ANNOTATION);
return createActivity(operation, pattern);
}
private Activity createFindAdditionals(EClass engineClass, PSPatternSpecification pattern)
{
// add the operation
EOperation operation = EcoreUtil.addEOperation(engineClass, METHOD_FIND_ADDITIONALS);
// parameter 'this'
EcoreUtil.addEParameter(operation, VAR_THIS, engineClass);
// parameter 'annotation'
EcoreUtil.addEParameter(operation, VAR_ANNOTATION, AnnotationsPackage.Literals.ASG_ANNOTATION);
return createActivity(operation, pattern);
}
private Activity createAnnotate(EClass engineClass, PSPatternSpecification pattern)
{
// add the operation
EOperation operation = EcoreUtil.addEOperation(engineClass, METHOD_ANNOTATE);
operation.setEType(AnnotationsPackage.Literals.ANNOTATION_SET);
// add 'this' parameter
EcoreUtil.addEParameter(operation, VAR_THIS, engineClass);
// add 'context' parameter
EcoreUtil.addEParameter(operation, VAR_CONTEXT, EcorePackage.Literals.EOBJECT);
// add 'additional' parameter
EcoreUtil.addEParameter(operation, VAR_SEARCH_ADDITIONALS, EcorePackage.Literals.EBOOLEAN);
return createActivity(operation, pattern);
}
@Override
public Activity createActivity(EOperation operation, PSPatternSpecification pattern)
{
// create activity
Activity activity = ActivitiesFactory.eINSTANCE.createActivity();
activity.setName(NameUtil.getName(operation));
activity.setComment(NameUtil.getName(operation));
// add operation extension
OperationExtension extension = ActivitiesFactory.eINSTANCE.createOperationExtension();
extension.setOwnedActivity(activity);
extension.setOperation(operation);
activity.getInParameters().addAll(operation.getEParameters());
// configure out parameter (should be ONLY ONE)
assert (extension.getOutParameters().size() <= 1) : "Activities should only have one out parameter.";
// TODO: The following commented code caused an exception. The default value for the out
// parameters should be enough here, shouldnt it?
// for (EParameter outParam : extension.getOutParameters())
// {
// outParam.setName(VAR_METHOD_RETURN_VALUE);
// activity.getOutParameters().add(outParam);
// }
// cache it
Map<String, Activity> cachedActivities = activities.get(pattern);
if (cachedActivities == null)
{
cachedActivities = new HashMap<String, Activity>();
activities.put(pattern, cachedActivities);
}
cachedActivities.put(operation.getName(), activity);
return activity;
}
private void revertWorkaroundSets(PSPatternSpecification pattern)
{
Collection<PSCombinedFragment> toRemove = new ArrayList<PSCombinedFragment>();
for (PSCombinedFragment fragment : pattern.getCombinedFragments())
{
if (ModifierType.SET.equals(fragment.getKind()) && fragment.getName().endsWith(SUFFIX_WRAPPER)
&& fragment.getChildren().size() == 1)
{
for (PSCombinedFragmentItem item : fragment.getChildren())
{
if (item instanceof PSNode && ModifierType.NONE.equals(((PSNode) item).getModifier()))
{
PSNode node = (PSNode) item;
node.setModifier(ModifierType.SET);
node.setWeight(fragment.getWeight());
PSNodeConstraint constraint = fragment.getConstraint();
if (constraint != null)
{
fragment.setConstraint(null);
node.getNodeConstraints().add(constraint);
}
}
}
toRemove.add(fragment);
}
}
pattern.getCombinedFragments().removeAll(toRemove);
}
private void revertWorkaroundNegatives(PSPatternSpecification pattern)
{
Collection<PSCombinedFragment> toRemove = new ArrayList<PSCombinedFragment>();
for (PSCombinedFragment fragment : pattern.getCombinedFragments())
{
if (ModifierType.NEGATIVE.equals(fragment.getKind()) && fragment.getName().endsWith(SUFFIX_WRAPPER)
&& fragment.getChildren().size() == 1)
{
for (PSCombinedFragmentItem item : fragment.getChildren())
{
if (item instanceof PSNode && ModifierType.NONE.equals(((PSNode) item).getModifier()))
{
PSNode node = (PSNode) item;
node.setModifier(ModifierType.NEGATIVE);
node.setWeight(fragment.getWeight());
PSNodeConstraint constraint = fragment.getConstraint();
if (constraint != null)
{
fragment.setConstraint(null);
node.getNodeConstraints().add(constraint);
}
}
}
toRemove.add(fragment);
}
}
pattern.getCombinedFragments().removeAll(toRemove);
}
@Override
public EClass getAnnotationClass(PSPatternSpecification pattern)
{
return annotations.get(pattern);
}
@Override
public EClass getEngineClass(PSPatternSpecification pattern)
{
return engines.get(pattern);
}
@Override
public Activity getActivity(PSPatternSpecification pattern, String name)
{
Map<String, Activity> cached = activities.get(pattern);
if (cached != null)
{
return cached.get(name);
}
return null;
}
@Override
public PSNode getTrigger(PSPatternSpecification pattern)
{
return triggerManager.getTrigger(pattern);
}
@Override
public IStatus error(String message, Object... args)
{
return reporter.error(message, args);
}
@Override
public void warn(String message, Object... args)
{
reporter.warn(message, args);
}
@Override
public void append(String message, Object... args)
{
reporter.append(message, args);
}
@Override
public void task(String message, Object... args)
{
reporter.task(message, args);
}
@Override
public void info(String message, Object... args)
{
reporter.info(message, args);
}
@Override
public void debug(String message, Object... args)
{
reporter.debug(message, args);
}
}
| {
"content_hash": "f263c5769ea98ddca440aa511c27eef7",
"timestamp": "",
"source": "github",
"line_count": 549,
"max_line_length": 119,
"avg_line_length": 33.10382513661202,
"alnum_prop": 0.6528007043028502,
"repo_name": "CloudScale-Project/StaticSpotter",
"id": "97a723151a70d09e0ee50e500fbeaeeb26571110",
"size": "18174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/org.reclipse.structure.generator/src/org/reclipse/structure/generator/Generator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "218"
},
{
"name": "HTML",
"bytes": "38155"
},
{
"name": "Java",
"bytes": "4313839"
},
{
"name": "Papyrus",
"bytes": "249770"
},
{
"name": "XML",
"bytes": "542398"
}
],
"symlink_target": ""
} |
/* global AFRAME */
AFRAME.registerComponent('button', {
schema: {
label: {default: 'label'},
width: {default: 0.11},
toggable: {default: false}
},
init: function () {
var el = this.el;
var labelEl = this.labelEl = document.createElement('a-entity');
this.color = '#3a50c5';
el.setAttribute('geometry', {
primitive: 'box',
width: this.data.width,
height: 0.05,
depth: 0.04
});
el.setAttribute('material', {color: this.color});
el.setAttribute('pressable', '');
labelEl.setAttribute('position', '0 0 0.02');
labelEl.setAttribute('text', {
value: this.data.label,
color: 'white',
align: 'center'
});
labelEl.setAttribute('scale', '0.75 0.75 0.75');
this.el.appendChild(labelEl);
this.bindMethods();
this.el.addEventListener('stateadded', this.stateChanged);
this.el.addEventListener('stateremoved', this.stateChanged);
this.el.addEventListener('pressedstarted', this.onPressedStarted);
this.el.addEventListener('pressedended', this.onPressedEnded);
},
bindMethods: function () {
this.stateChanged = this.stateChanged.bind(this);
this.onPressedStarted = this.onPressedStarted.bind(this);
this.onPressedEnded = this.onPressedEnded.bind(this);
},
update: function (oldData) {
if (oldData.label !== this.data.label) {
this.labelEl.setAttribute('text', 'value', this.data.label);
}
},
stateChanged: function () {
var color = this.el.is('pressed') ? 'green' : this.color;
this.el.setAttribute('material', {color: color});
},
onPressedStarted: function () {
var el = this.el;
el.setAttribute('material', {color: 'green'});
el.emit('click');
if (this.data.togabble) {
if (el.is('pressed')) {
el.removeState('pressed');
} else {
el.addState('pressed');
}
}
},
onPressedEnded: function () {
if (this.el.is('pressed')) { return; }
this.el.setAttribute('material', {color: this.color});
}
});
| {
"content_hash": "3caa76af2f56efa68f6c75bcc5a7929b",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 70,
"avg_line_length": 27.5,
"alnum_prop": 0.6181818181818182,
"repo_name": "aframevr/aframe",
"id": "9149e570e654e625d7ad1ce595c6f7254d27341d",
"size": "2035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/showcase/hand-tracking/button.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14601"
},
{
"name": "HTML",
"bytes": "2071"
},
{
"name": "JavaScript",
"bytes": "1254567"
}
],
"symlink_target": ""
} |
package org.saiku.reporting.core.builder;
import org.pentaho.reporting.engine.classic.core.AbstractReportDefinition;
import org.pentaho.reporting.engine.classic.core.function.FormulaExpression;
import org.saiku.reporting.core.model.FieldDefinition;
import org.saiku.reporting.core.model.ReportSpecification;
public class CalculatedColumnBuilder{
public void build(AbstractReportDefinition definition,
ReportSpecification reportSpecification){
for (FieldDefinition fieldDefinition : reportSpecification.getFieldDefinitions()) {
if(fieldDefinition.getFormula()!=null){
FormulaExpression calcColumn = new FormulaExpression();
calcColumn.setName(fieldDefinition.getId());
calcColumn.setFormula("=" + fieldDefinition.getFormula());
definition.addExpression(calcColumn);
}
}
}
}
| {
"content_hash": "8ebe83870047a686bd444bb9e2fbbea5",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 85,
"avg_line_length": 31.653846153846153,
"alnum_prop": 0.7910085054678008,
"repo_name": "Mgiepz/saiku-reporting-core",
"id": "c570b38db85aa58ebf17aa114ffbaca5e7704dde",
"size": "1585",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/saiku/reporting/core/builder/CalculatedColumnBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "326"
},
{
"name": "HTML",
"bytes": "11156"
},
{
"name": "Java",
"bytes": "226507"
}
],
"symlink_target": ""
} |
package com.flying.promotion.socket.client.processor;
import com.flying.promotion.socket.SocketWrapper;
import com.flying.promotion.socket.client.exceptions.NoOptionException;
import com.flying.promotion.socket.client.sender.Sendable;
import static com.flying.promotion.socket.Commons.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class LineProcessor {
private String []tokens;
private Sendable sendable;
public LineProcessor(String line) throws Exception {
line = preLine(line).trim();
if(line.trim().length() == 0) {//没有任何操作
throw new NoOptionException();
}
tokens = line.trim().split("\\s+");
String firstToken = tokens[0];
Class <?>clazz = findSendableClassByOrder(firstToken);
try {
sendable = (Sendable)clazz.getConstructor(String[].class)
.newInstance(new Object[] {tokens});
}catch(InvocationTargetException e) {
throw (Exception)e.getCause();
}
}
public void sendContentBySocket(SocketWrapper socketWrapper) throws IOException {
if(sendable != null && sendable.getSendType() > 0) {
socketWrapper.write(sendable.getSendType());//发送类型
sendable.sendContent(socketWrapper);
}
}
private String preLine(String line) {
if(line == null) return "";
if(line.startsWith(">")) return line.substring(1);
return line;
}
}
| {
"content_hash": "8bc194b6d14147c9876892f63949b31d",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 82,
"avg_line_length": 28.319148936170212,
"alnum_prop": 0.734785875281743,
"repo_name": "wangshijun101/JavaSenior",
"id": "0f5ae1b47c36bbe355fc550462fd93aab065e5ca",
"size": "1351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JavaLaoA/src/main/java/com/flying/promotion/socket/client/processor/LineProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "2136"
},
{
"name": "FreeMarker",
"bytes": "41804"
},
{
"name": "Java",
"bytes": "681846"
},
{
"name": "JavaScript",
"bytes": "209223"
},
{
"name": "Shell",
"bytes": "7058"
}
],
"symlink_target": ""
} |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.modules.net_tools.nios import nios_srv_record
from ansible.module_utils.net_tools.nios import api
from units.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosSRVRecordModule(TestNiosModule):
module = nios_srv_record
def setUp(self):
super(TestNiosSRVRecordModule, self).setUp()
self.module = MagicMock(name='ansible.modules.net_tools.nios.nios_srv_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible.modules.net_tools.nios.nios_srv_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible.modules.net_tools.nios.nios_srv_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosSRVRecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_srv_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10})
def test_nios_srv_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "srvrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "_sip._tcp.service.ansible.com",
'port': 5080,
"target": "mailhost.ansible.com",
"priority": 10,
'weight': 10,
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_srv_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
ref = "srvrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [
{
"comment": "test comment",
"_ref": ref,
"name": "_sip._tcp.service.ansible.com",
"port": 5080,
"target": "mailhost.ansible.com",
"priority": 10,
"weight": 10,
"extattrs": {'Site': {'value': 'test'}}
}
]
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
| {
"content_hash": "8c5c16d81b4300b7c9bc15c14747e007",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 144,
"avg_line_length": 38.31111111111111,
"alnum_prop": 0.5276488785769529,
"repo_name": "thaim/ansible",
"id": "2c0b27388c150314baebaf7275ad4de9983be213",
"size": "5858",
"binary": false,
"copies": "64",
"ref": "refs/heads/fix-broken-link",
"path": "test/units/modules/net_tools/nios/test_nios_srv_record.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "246"
}
],
"symlink_target": ""
} |
(function() {
var Map;
Map = (function() {
function Map() {
this.map = {};
}
Map.prototype.addRole = function(role) {
if (typeof role.getName !== 'function' || typeof role.isAllowed !== 'function') {
throw new Error('You must add a Role object.');
}
if (this.hasRole(role.getName())) {
throw new Error('Role already exists.');
}
this.map[role.getName()] = role;
return this;
};
Map.prototype.hasRole = function(roleName) {
return this.map.hasOwnProperty(roleName);
};
Map.prototype.checkRolePermission = function(path, method, roleName) {
if (!this.hasRole(roleName)) {
return false;
} else {
return this.map[roleName].isAllowed(path, method);
}
};
Map.prototype.check = function(roleNameList, permission, method) {
return roleNameList.map(this.checkRolePermission.bind(this, permission, method)).reduce(function(acc, cur) {
return acc || cur;
});
};
return Map;
})();
module.exports = function() {
return new Map();
};
}).call(this);
| {
"content_hash": "45d90559cc74fc65d7f4edd043951c5e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 114,
"avg_line_length": 24.347826086956523,
"alnum_prop": 0.5839285714285715,
"repo_name": "scull7/empower-role",
"id": "b1e462c10bd5c8652330106c6d07924b1ae12722",
"size": "1156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/map.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "11535"
}
],
"symlink_target": ""
} |
package org.powermock.core;
import org.powermock.core.spi.MethodInvocationControl;
import org.powermock.core.spi.NewInvocationControl;
import org.powermock.reflect.internal.TypeUtils;
import org.powermock.reflect.internal.WhiteboxImpl;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
/**
* All mock invocations are routed through this gateway. This includes method
* calls, construction of new instances and more. Do not use this class
* directly, but always go through the PowerMock facade.
*/
public class MockGateway {
/**
* {@link #noMockito} is wrapped into it's own static class to make sure it is initialized not earlier than
* {@link #calledFromMockito()} is called for the first time.
*/
private static final class NoMockito {
static final boolean noMockito = Package.getPackage("org.mockito") == null;
private NoMockito() {}
}
public static final Object PROCEED = new Object();
public static final Object SUPPRESS = new Object();
/**
* Used to tell the MockGateway that the next call should not be mocked
* regardless if a {@link MethodInvocationControl} is found in the
* {@link MockRepository}. Used to allow for e.g. recursive partial mocking.
*/
public static final String DONT_MOCK_NEXT_CALL = "DontMockNextCall";
/**
* Tells PowerMock to mock standard methods. These are
* {@link Object#toString()}, {@link Object#hashCode()} and
* {@link Object#equals(Object)}. By default this is {@code true}.
*/
public static boolean MOCK_STANDARD_METHODS = true;
@SuppressWarnings("UnusedDeclaration")
public static Object newInstanceCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {
final NewInvocationControl<?> newInvocationControl = MockRepository.getNewInstanceControl(type);
if (newInvocationControl != null) {
/*
* We need to deal with inner, local and anonymous inner classes
* specifically. For example when new is invoked on an inner class
* it seems like null is passed as an argument even though it
* shouldn't. We correct this here.
*
* Seems with Javassist 3.17.1-GA & Java 7, the 'null' is passed as the last argument.
*/
if (type.isMemberClass() && Modifier.isStatic(type.getModifiers())) {
if (args.length > 0
&& ((args[0] == null && sig[0].getCanonicalName() == null)
|| (args[args.length - 1] == null && sig[args.length - 1].getCanonicalName() == null))
&& sig.length > 0) {
args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], false);
}
} else if (type.isLocalClass() || type.isAnonymousClass() || type.isMemberClass()) {
if (args.length > 0 && sig.length > 0 && sig[0].equals(type.getEnclosingClass())) {
args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], true);
}
}
return newInvocationControl.invoke(type, args, sig);
}
// Check if we should suppress the constructor code
if (MockRepository.shouldSuppressConstructor(WhiteboxImpl.getConstructor(type, sig))) {
return WhiteboxImpl.getFirstParentConstructor(type);
}
return PROCEED;
}
@SuppressWarnings("UnusedDeclaration")
public static Object fieldCall(Object instanceOrClassContainingTheField, Class<?> classDefiningField,
String fieldName, Class<?> fieldType) {
if (MockRepository.shouldSuppressField(WhiteboxImpl.getField(classDefiningField, fieldName))) {
return TypeUtils.getDefaultValue(fieldType);
}
return PROCEED;
}
public static Object staticConstructorCall(String className) {
if (MockRepository.shouldSuppressStaticInitializerFor(className)) {
return "suppress";
}
return PROCEED;
}
@SuppressWarnings("UnusedDeclaration")
public static Object constructorCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {
final Constructor<?> constructor = WhiteboxImpl.getConstructor(type, sig);
if (MockRepository.shouldSuppressConstructor(constructor)) {
return null;
}
return PROCEED;
}
public static boolean suppressConstructorCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {
return constructorCall(type, args, sig) != PROCEED;
}
/**
* Tells PowerMock whether or not to mock
* {@link java.lang.Object#getClass()}.
*/
public static boolean MOCK_GET_CLASS_METHOD = false;
/**
* Tells PowerMock whether or not to mock
* {@link java.lang.Class#isAnnotationPresent(Class)} and
* {@link java.lang.Class#getAnnotation(Class)}.
*/
public static boolean MOCK_ANNOTATION_METHODS = false;
// used for instance methods
@SuppressWarnings("UnusedDeclaration")
public static Object methodCall(Object instance, String methodName, Object[] args, Class<?>[] sig,
String returnTypeAsString) throws Throwable {
return doMethodCall(instance, methodName, args, sig, returnTypeAsString);
}
// used for static methods
@SuppressWarnings("UnusedDeclaration")
public static Object methodCall(Class<?> type, String methodName, Object[] args, Class<?>[] sig,
String returnTypeAsString) throws Throwable {
return doMethodCall(type, methodName, args, sig, returnTypeAsString);
}
private static Object doMethodCall(Object object, String methodName, Object[] args, Class<?>[] sig,
String returnTypeAsString) throws Throwable {
if (!shouldMockMethod(methodName, sig)) {
return PROCEED;
}
MockInvocation mockInvocation = new MockInvocation(object, methodName, sig);
MethodInvocationControl methodInvocationControl = mockInvocation.getMethodInvocationControl();
Object returnValue = null;
// The following describes the equals non-static method.
if (isEqualsMethod(mockInvocation) && !isStaticMethod(mockInvocation)) {
returnValue = tryHandleEqualsMethod(mockInvocation);
}
if (returnValue != null) {
return returnValue;
}
return doMethodCall(object, args, returnTypeAsString, mockInvocation, methodInvocationControl);
}
private static Object doMethodCall(Object object, Object[] args,
String returnTypeAsString,
MockInvocation mockInvocation,
MethodInvocationControl methodInvocationControl) throws Throwable {
Object returnValue;
// At first should be checked that method not suppressed/stubbed, because otherwise for spies real
// method is involved.
// https://github.com/jayway/powermock/issues/327
if (MockRepository.shouldSuppressMethod(mockInvocation.getMethod(), mockInvocation.getObjectType())) {
returnValue = TypeUtils.getDefaultValue(returnTypeAsString);
} else if (MockRepository.shouldStubMethod(mockInvocation.getMethod())) {
returnValue = MockRepository.getMethodToStub(mockInvocation.getMethod());
} else if (methodInvocationControl != null && methodInvocationControl.isMocked(mockInvocation.getMethod()) && shouldMockThisCall()) {
returnValue = methodInvocationControl.invoke(object, mockInvocation.getMethod(), args);
if (returnValue == SUPPRESS) {
returnValue = TypeUtils.getDefaultValue(returnTypeAsString);
}
} else if (MockRepository.hasMethodProxy(mockInvocation.getMethod())) {
/*
* We must temporary remove the method proxy when invoking the
* invocation handler because if the invocation handler delegates
* the call we will end up here again and we'll get a
* StackOverflowError.
*/
final InvocationHandler invocationHandler = MockRepository.removeMethodProxy(mockInvocation.getMethod());
try {
returnValue = invocationHandler.invoke(object, mockInvocation.getMethod(), args);
} finally {
// Set the method proxy again after the invocation
MockRepository.putMethodProxy(mockInvocation.getMethod(), invocationHandler);
}
} else {
returnValue = PROCEED;
}
return returnValue;
}
/*
* Method handles exception cases with equals method.
*/
private static Object tryHandleEqualsMethod(MockInvocation mockInvocation) {
// Fix for Issue http://code.google.com/p/powermock/issues/detail?id=88
// For some reason the method call to equals() on final methods is
// intercepted and during the further processing in Mockito the same
// equals() method is called on the same instance. A StackOverflowError
// is the result. The following fix changes this by checking if the
// method to be called is a final equals() method. In that case the
// original method is called by returning PROCEED.
if (mockInvocation.getMethod().getParameterTypes().length == 1
&& mockInvocation.getMethod().getParameterTypes()[0] == Object.class
&& Modifier.isFinal(mockInvocation.getMethod().getModifiers())) {
return PROCEED;
}
if (calledFromMockito()){
return PROCEED;
}
return null;
}
private static boolean isEqualsMethod(MockInvocation mockInvocation) {
return "equals".equals(mockInvocation.getMethod().getName());
}
private static boolean isStaticMethod(MockInvocation mockInvocation) {
return Modifier.isStatic(mockInvocation.getMethod().getModifiers());
}
private static boolean calledFromMockito() {
if (NoMockito.noMockito) {
return false;
}
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if (stackTraceElement.getClassName().startsWith("org.mockito.")){
return true;
}
}
return false;
}
private static boolean shouldMockMethod(String methodName, Class<?>[] sig) {
if (isJavaStandardMethod(methodName, sig) && !MOCK_STANDARD_METHODS) {
return false;
} else if (isGetClassMethod(methodName, sig) && !MOCK_GET_CLASS_METHOD) {
return false;
} else { return !(isAnnotationMethod(methodName, sig) && !MOCK_ANNOTATION_METHODS); }
}
private static boolean isJavaStandardMethod(String methodName, Class<?>[] sig) {
return (methodName.equals("equals") && sig.length == 1) || (methodName.equals("hashCode") && sig.length == 0)
|| (methodName.equals("toString") && sig.length == 0);
}
private static boolean isGetClassMethod(String methodName, Class<?>[] sig) {
return methodName.equals("getClass") && sig.length == 0;
}
private static boolean isAnnotationMethod(String methodName, Class<?>[] sig) {
return (methodName.equals("isAnnotationPresent") && sig.length == 1) || (methodName.equals("getAnnotation") && sig.length == 1);
}
private static boolean shouldMockThisCall() {
Object shouldSkipMockingOfNextCall = MockRepository.getAdditionalState(DONT_MOCK_NEXT_CALL);
final boolean shouldMockThisCall = shouldSkipMockingOfNextCall == null;
MockRepository.removeAdditionalState(DONT_MOCK_NEXT_CALL);
return shouldMockThisCall;
}
/**
* The first parameter of an inner, local or anonymous inner class is
* {@code null} or the enclosing instance. This should not be included
* in the substitute invocation since it is never expected by the user.
* <p/>
* Seems with Javassist 3.17.1-GA & Java 7, the '{@code null}' is passed as the last argument.
*/
private static Object[] copyArgumentsForInnerOrLocalOrAnonymousClass(Object[] args, Class<?> sig,
boolean excludeEnclosingInstance) {
Object[] newArgs = new Object[args.length - 1];
final int start;
final int end;
int j = 0;
if ((args[0] == null && sig == null)|| excludeEnclosingInstance) {
start = 1;
end = args.length;
} else {
start = 0;
end = args.length - 1;
}
for (int i = start; i < end; i++) {
newArgs[j++] = args[i];
}
args = newArgs;
return args;
}
}
| {
"content_hash": "71ed8b1f87944f4e4643e7259de0c163",
"timestamp": "",
"source": "github",
"line_count": 301,
"max_line_length": 141,
"avg_line_length": 43.63787375415282,
"alnum_prop": 0.6339550818424058,
"repo_name": "powermock/powermock",
"id": "2c071b671c89e484f0ca5c0db4ab2d4b0bd5212f",
"size": "13745",
"binary": false,
"copies": "4",
"ref": "refs/heads/release/2.x",
"path": "powermock-core/src/main/java/org/powermock/core/MockGateway.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2490898"
}
],
"symlink_target": ""
} |
@protocol ConnectionInformation;
@class SceneState;
@protocol StartupInformation;
namespace metrics_mediator {
// Key in the UserDefaults to store the date/time that the background fetch
// handler was called.
extern NSString* const kAppEnteredBackgroundDateKey;
// The key to a NSUserDefaults entry logging the number of times application
// didFinishLaunching is called before a scene is attached.
extern NSString* const kAppDidFinishLaunchingConsecutiveCallsKey;
// Struct containing histogram names and number of buckets. Used for recording
// histograms fired in extensions.
struct HistogramNameCountPair {
NSString* name;
int buckets;
};
// Send histograms reporting the usage of widget metrics. Uses the provided list
// of histogram names to see if any histograms have been logged in widgets.
void RecordWidgetUsage(base::span<const HistogramNameCountPair> histograms);
} // namespace metrics_mediator
// Deals with metrics, checking and updating them accordingly to to the user
// preferences.
@interface MetricsMediator : NSObject
// Returns YES if the metrics pref is enabled. Does not take into account the
// wifi-only option or wwan state.
- (BOOL)areMetricsEnabled;
// Starts or stops the metrics service and crash report recording and/or
// uploading, based on the current user preferences. Must be
// called both on initialization and after user triggered preference change.
// `isUserTriggered` is used to distinguish between those cases.
- (void)updateMetricsStateBasedOnPrefsUserTriggered:(BOOL)isUserTriggered;
// Logs the duration of the cold start startup. Does nothing if there isn't a
// cold start.
+ (void)logStartupDuration:(id<StartupInformation>)startupInformation
connectionInformation:(id<ConnectionInformation>)connectionInformation;
// Logs the number of tabs open and the start type.
+ (void)logLaunchMetricsWithStartupInformation:
(id<StartupInformation>)startupInformation
connectedScenes:(NSArray<SceneState*>*)scenes;
// Logs in UserDefaults the current date with kAppEnteredBackgroundDateKey as
// key.
+ (void)logDateInUserDefaults;
// Logs that the application is in background and the number of memory warnings
// for this session.
+ (void)applicationDidEnterBackground:(NSInteger)memoryWarningCount;
@end
#endif // IOS_CHROME_APP_APPLICATION_DELEGATE_METRICS_MEDIATOR_H_
| {
"content_hash": "3eb9884226139d4c0ede8d64cbc32f9f",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 80,
"avg_line_length": 43.236363636363635,
"alnum_prop": 0.787636669470143,
"repo_name": "chromium/chromium",
"id": "da1307f62d2684d136077f803a2213bc6f4f79cc",
"size": "2711",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "ios/chrome/app/application_delegate/metrics_mediator.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.cbioportal.genome_nexus.service;
import com.mongodb.BasicDBObject;
import org.cbioportal.genome_nexus.model.MutationAssessor;
import org.cbioportal.genome_nexus.persistence.MutationAssessorRepository;
import org.cbioportal.genome_nexus.service.config.ExternalResourceObjectMapper;
import org.cbioportal.genome_nexus.service.exception.ResourceMappingException;
import org.cbioportal.genome_nexus.service.exception.MutationAssessorNotFoundException;
import org.cbioportal.genome_nexus.service.exception.MutationAssessorWebServiceException;
import org.cbioportal.genome_nexus.service.transformer.ExternalResourceTransformer;
import org.mockito.Mock;
import org.cbioportal.genome_nexus.service.internal.MutationAssessorServiceImpl;
import org.cbioportal.genome_nexus.service.remote.MutationAssessorDataFetcher;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import java.net.URL;
import static org.junit.Assert.*;
// TODO need to convert this into a proper integration test, disabled for now due to direct access to a real web API.
public class MutationAssessorTest
{
// for debugging
private static Logger log = Logger.getLogger(String.valueOf(MutationAssessorTest.class));
// normally taken from application.properties file
private String url =
"http://mutationassessor.org/r3/?cm=var&var=VARIANT&frm=json&fts=input,rgaa,rgvt,var,gene,F_impact,F_score,chr,rs_pos";
@Mock
MutationAssessorRepository mutationAssessorRepository;
//@Test
public void testStringInputs()
throws IOException, ResourceMappingException, MutationAssessorWebServiceException, MutationAssessorNotFoundException
{
ExternalResourceTransformer<MutationAssessor> transformer =
new ExternalResourceTransformer<>(new ExternalResourceObjectMapper());
MutationAssessorServiceImpl service = new MutationAssessorServiceImpl(mutationAssessorRepository, null);
String urlString1 = url.replace("VARIANT", "7,140453136,A,T");
MutationAssessor mutationObj1 = service.getMutationAssessorByMutationAssessorVariant("7,140453136,A,T"); // 7:g.140453136A>T
MutationAssessor mutationObj2 = transformer.transform(
new BasicDBObject(/*getReturnString(urlString1)*/), MutationAssessor.class).get(0);
// getVariant() not tested because variants set manually
assertEquals(mutationObj1.getHugoSymbol(), mutationObj2.getHugoSymbol());
assertEquals(mutationObj1.getFunctionalImpact(), mutationObj2.getFunctionalImpact());
assertEquals(mutationObj1.getFunctionalImpactScore(), mutationObj2.getFunctionalImpactScore(), 0);
String urlString2 = url.replace("VARIANT", "12,25398285,C,A");
MutationAssessor mutationObj21 = service.getMutationAssessorByMutationAssessorVariant("12,25398285,C,A"); // 12:g.25398285C>A
MutationAssessor mutationObj22 = transformer.transform(
new BasicDBObject(/*getReturnString(urlString2)*/), MutationAssessor.class).get(0);
assertEquals(mutationObj21.getHugoSymbol(), mutationObj22.getHugoSymbol());
assertEquals(mutationObj21.getFunctionalImpact(), mutationObj22.getFunctionalImpact());
assertEquals(mutationObj21.getFunctionalImpactScore(), mutationObj22.getFunctionalImpactScore(), 0);
}
//@Test
public void testJunk()
throws IOException, ResourceMappingException, MutationAssessorWebServiceException, MutationAssessorNotFoundException
{
ExternalResourceTransformer<MutationAssessor> transformer =
new ExternalResourceTransformer<>(new ExternalResourceObjectMapper());
MutationAssessorServiceImpl service = new MutationAssessorServiceImpl(mutationAssessorRepository, null);
String urlString = url.replace("VARIANT", "junkInput");
MutationAssessor mutationObj1 = service.getMutationAssessorByMutationAssessorVariant("junkInput");
MutationAssessor mutationObj2 = transformer.transform(
new BasicDBObject(/*getReturnString(urlString)*/), MutationAssessor.class).get(0);
// getVariant() not tested because variants set manually
assertEquals(mutationObj1.getHugoSymbol(), mutationObj2.getHugoSymbol());
assertEquals(mutationObj1.getFunctionalImpact(), mutationObj2.getFunctionalImpact());
assertEquals(mutationObj1.getFunctionalImpactScore(), mutationObj2.getFunctionalImpactScore(), 0);
}
private String getReturnString(String urlString) throws IOException {
String output = "";
URL url = new URL(urlString);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")))
{
for (String line; (line = reader.readLine()) != null;)
{
output += line;
}
}
return output;
}
}
| {
"content_hash": "a04bc415b3dea8fdd8242ca4609583b9",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 133,
"avg_line_length": 49.696969696969695,
"alnum_prop": 0.7577235772357723,
"repo_name": "genome-nexus/genome-nexus",
"id": "d02b3b6c2e3f7e4352dd0ea857a095ac4e8950d8",
"size": "4920",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "service/src/test/java/org/cbioportal/genome_nexus/service/MutationAssessorTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "275"
},
{
"name": "Java",
"bytes": "1103184"
},
{
"name": "Jupyter Notebook",
"bytes": "94581"
},
{
"name": "Procfile",
"bytes": "108"
},
{
"name": "Shell",
"bytes": "561"
}
],
"symlink_target": ""
} |
import { Trello } from "../../index";
const TEST_PARENT_ID = "d9a04f38b919f23b8cc7bf01";
const TEST_CHILD_ID = "dd7d4048bed6c23daebf1070";
describe("the Batch resource", () => {
const trello = new Trello(global.trelloConfig);
beforeEach(() => {
global.captureFetchMock();
});
afterEach(() => {
global.resetFetchMocks();
});
test("makes batch requests with no commas in requests", async () => {
const urls = [`/boards/${TEST_PARENT_ID}`, `/cards/${TEST_CHILD_ID}`];
await trello.batch().makeRequests(urls);
const result = global.getLastFetchCall();
expect(result.config.method).toBe("GET");
expect(result.url.pathname).toBe("/1/batch");
expect(result.url.searchParams.get("urls")).toBe(urls.join(","));
});
test("makes batch requests with commas in requests", async () => {
const requestUrls = [
`/boards/${TEST_PARENT_ID}/test=Other,Thing`,
`/cards/${TEST_CHILD_ID}`,
];
await trello.batch().makeRequests(requestUrls);
const result = global.getLastFetchCall();
expect(result.config.method).toBe("GET");
expect(result.url.pathname).toBe("/1/batch");
expect(result.url.searchParams.toString()).toMatch(/Other%2CThing/gi);
});
});
| {
"content_hash": "920eb09a580de345d4611c17424d4849",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 74,
"avg_line_length": 31.435897435897434,
"alnum_prop": 0.6492659053833605,
"repo_name": "mikerourke/trello-for-wolves",
"id": "4e989c04c83ec8639a41d177a51a0ac142b7dbfa",
"size": "1226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/resources/__tests__/Batch.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "466"
},
{
"name": "TypeScript",
"bytes": "350915"
}
],
"symlink_target": ""
} |
#ifndef STD_UNIV_SOCK_H
#define STD_UNIV_SOCK_H
#include "condor_common.h"
#include "condor_socket_types.h"
#include "stream.h"
#include "CondorError.h"
#include "std_univ_buffers.h"
#include "condor_sockaddr.h"
#if !defined(WIN32)
# ifndef SOCKET
# define SOCKET int
# endif
# ifndef INVALID_SOCKET
# define INVALID_SOCKET -1
# endif
#endif /* not WIN32 */
class StdUnivSock : public Stream {
public:
StdUnivSock();
virtual ~StdUnivSock();
int attach_to_file_desc(int);
int end_of_message();
virtual bool peek_end_of_message();
virtual int put_bytes(const void *, int);
virtual int get_bytes(void *, int);
virtual int get_ptr(void *&, char);
virtual int peek(char &);
float get_bytes_sent() { return _bytes_sent; }
float get_bytes_recvd() { return _bytes_recvd; }
/** if any operation takes more than sec seconds, timeout
call timeout(0) to set blocking mode (default)
@param sec the number of seconds to wait before timing out
@return previous timeout
*/
int timeout(int sec);
/// peer's IP address, string verison (e.g. "128.105.101.17")
const char* peer_ip_str();
/// local socket address
condor_sockaddr my_addr();
// remote socket address
condor_sockaddr peer_addr();
private:
void init(); /* shared initialization method */
int close();
int handle_incoming_packet();
/// called whenever the bound or connected state changes
void addr_changed();
/// sinful address of peer in form of "<a.b.c.d:pppp>"
char * get_sinful_peer();
/// sinful address of peer, suitable for passing to dprintf() (never NULL)
virtual char const *default_peer_description();
virtual bool canEncrypt();
int setsockopt(int, int, const char*, int);
class RcvMsg {
StdUnivSock * p_sock; //preserve parent pointer to use for condor_read/write
public:
RcvMsg();
~RcvMsg();
int rcv_packet(char const *peer_description, SOCKET, int);
void init_parent(StdUnivSock *tmp){ p_sock = tmp; }
StdUnivChainBuf buf;
int ready;
} rcv_msg;
class SndMsg {
StdUnivSock * p_sock;
public:
SndMsg();
~SndMsg();
StdUnivBuf buf;
int snd_packet(char const *peer_description, int, int, int);
//function to support the use of condor_read /write
void init_parent(StdUnivSock *tmp){
p_sock = tmp;
buf.init_parent(tmp);
}
} snd_msg;
int ignore_next_encode_eom;
int ignore_next_decode_eom;
float _bytes_sent, _bytes_recvd;
SOCKET _sock;
int _timeout;
condor_sockaddr _who; // endpoint of "connection"
char _peer_ip_buf[IP_STRING_BUF_SIZE];
char _sinful_peer_buf[SINFUL_STRING_BUF_SIZE];
private:
/*
* unimplemented stubs to make inheritance from Stream possible
*/
int bytes_available_to_read();
bool peer_is_local();
char * serialize(char *);
char * serialize() const;
Stream *CloneStream();
stream_type type();
const char* my_ip_str();
};
#endif /* SOCK_H */
| {
"content_hash": "e3ab78ae232d070d7274ed8c9066c5d6",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 83,
"avg_line_length": 20.67132867132867,
"alnum_prop": 0.6640730717185386,
"repo_name": "neurodebian/htcondor",
"id": "2c11364b51fc322976127de5f7d871e4501021c9",
"size": "3764",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/condor_io.std/std_univ_sock.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "18848"
},
{
"name": "Batchfile",
"bytes": "164295"
},
{
"name": "C",
"bytes": "1695675"
},
{
"name": "C++",
"bytes": "27269492"
},
{
"name": "CMake",
"bytes": "556754"
},
{
"name": "FORTRAN",
"bytes": "110251"
},
{
"name": "Groff",
"bytes": "6128"
},
{
"name": "HTML",
"bytes": "16109"
},
{
"name": "Java",
"bytes": "44327"
},
{
"name": "JavaScript",
"bytes": "2095"
},
{
"name": "Lex",
"bytes": "6527"
},
{
"name": "M4",
"bytes": "19489"
},
{
"name": "Makefile",
"bytes": "42701"
},
{
"name": "Objective-C",
"bytes": "42170"
},
{
"name": "PLpgSQL",
"bytes": "23393"
},
{
"name": "Perl",
"bytes": "4150910"
},
{
"name": "Python",
"bytes": "1048286"
},
{
"name": "Ruby",
"bytes": "24647"
},
{
"name": "SQLPL",
"bytes": "10933"
},
{
"name": "Shell",
"bytes": "1261504"
},
{
"name": "TeX",
"bytes": "17944"
},
{
"name": "Yacc",
"bytes": "62678"
}
],
"symlink_target": ""
} |
using Rg.Plugins.Popup.Tizen.Impl;
using Rg.Plugins.Popup.Tizen.Renderers;
namespace Rg.Plugins.Popup.Tizen
{
public static class Popup
{
internal static event EventHandler? OnInitialized;
internal static bool IsInitialized { get; private set; }
public static void Init()
{
LinkAssemblies();
IsInitialized = true;
OnInitialized?.Invoke(null, EventArgs.Empty);
}
private static void LinkAssemblies()
{
if (false.Equals(true))
{
var i = new PopupPlatformTizen();
var r = new PopupPageRenderer();
}
}
}
}
| {
"content_hash": "d3ea8674cffbd40a7ae5521a4a001e32",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 64,
"avg_line_length": 23.724137931034484,
"alnum_prop": 0.5581395348837209,
"repo_name": "rotorgames/Rg.Plugins.Popup",
"id": "545b642582a0d6ce06c7084ab0d8258889e1eea7",
"size": "690",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Rg.Plugins.Popup/Platforms/Tizen/Popup.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "129319"
},
{
"name": "PowerShell",
"bytes": "7433"
},
{
"name": "Shell",
"bytes": "2935"
}
],
"symlink_target": ""
} |
package io.alfredux.softbills.web.rest.errors;
public final class ErrorConstants {
public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure";
public static final String ERR_ACCESS_DENIED = "error.accessDenied";
public static final String ERR_VALIDATION = "error.validation";
public static final String ERR_METHOD_NOT_SUPPORTED = "error.methodNotSupported";
public static final String ERR_INTERNAL_SERVER_ERROR = "error.internalServerError";
private ErrorConstants() {
}
}
| {
"content_hash": "5d3a93150a08eaf2ce6e6331bfb53cd5",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 87,
"avg_line_length": 37.57142857142857,
"alnum_prop": 0.7585551330798479,
"repo_name": "Alfredux79/softbills",
"id": "f40f56ed390fe051617ecb17c67cfac7c93235c7",
"size": "526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/alfredux/softbills/web/rest/errors/ErrorConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "10404"
},
{
"name": "HTML",
"bytes": "159048"
},
{
"name": "Java",
"bytes": "380036"
},
{
"name": "JavaScript",
"bytes": "18512"
},
{
"name": "Shell",
"bytes": "7058"
},
{
"name": "TypeScript",
"bytes": "256431"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Trans. Wis. Acad. Sci. Arts Lett. 15: 779 (1907)
#### Original name
Cercospora coalescens Davis
### Remarks
null | {
"content_hash": "efc172177b1a7dd9cdee2a5a3db0f15c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 48,
"avg_line_length": 13.538461538461538,
"alnum_prop": 0.6988636363636364,
"repo_name": "mdoering/backbone",
"id": "9a6ab2548d1cd45b87e053cd6539cd213e5297db",
"size": "227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Cercospora/Cercospora coalescens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SHORTCUT="#!/usr/bin/env xdg-open
[Desktop Entry]
Comment=The Best Code Editor
Terminal=false
Name=Sublime Text 3
Exec=/usr/local/share/applications/sublime-text-3/sublime_text
Type=Application
Icon=/usr/local/share/applications/sublime-text-3/Icon/128x128/sublime-text.png"
curl -L "http://c758482.r82.cf2.rackcdn.com/sublime_text_3_build_3059_x64.tar.bz2" -o "/usr/src/Sublime Text 3.tar.bz2"
cd /usr/src
tar -xvjf "Sublime Text 3.tar.bz2"
cd "sublime_text_3"
mkdir -pv "/usr/local/share/applications/sublime-text-3"
mv -fv * "/usr/local/share/applications/sublime-text-3/"
yum -y install wget && wget "https://spideroak.com/share/PBSW433EMVZXS43UMVWXG/78656e6f6465/var/CDN/xenodecdn/sublime3-fedora/subl" -O /usr/bin/subl
chmod +x "/usr/bin/subl"
echo "${SHORTCUT}" > "/usr/share/applications/sublime-text-3.desktop"
echo "Finish!"
subl
| {
"content_hash": "c20a70cb31781bd017f23a03771e6e9c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 148,
"avg_line_length": 40.095238095238095,
"alnum_prop": 0.7600950118764845,
"repo_name": "yosoyvictorgarcia/Alegorista_Site",
"id": "924d0b7ebfa02202aab07426afda6b9156cf66fb",
"size": "986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sublime-text-3-x86_64.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1543708"
},
{
"name": "JavaScript",
"bytes": "1850977"
},
{
"name": "PHP",
"bytes": "8302477"
},
{
"name": "Shell",
"bytes": "986"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.