text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
<?php namespace Chamilo\Core\Repository\ContentObject\Assessment\Display; use Chamilo\Libraries\Platform\Translation; /** * * @package core\repository\content_object\assessment\display * @author Hans De Bisschop <hans.de.bisschop@ehb.be> * @author Magali Gillard <magali.gillard@ehb.be> * @author Eduard Vossen <eduard.vossen@ehb.be> */ class Configuration { // Properties const PROPERTY_ALLOW_HINTS = 'allow_hints'; const PROPERTY_SHOW_SCORE = 'show_score'; const PROPERTY_SHOW_CORRECTION = 'show_correction'; const PROPERTY_SHOW_SOLUTION = 'show_solution'; const PROPERTY_SHOW_ANSWER_FEEDBACK = 'show_answer_feedback'; const PROPERTY_FEEDBACK_LOCATION = 'feedback_location'; // Answer feedback types const ANSWER_FEEDBACK_TYPE_NONE = 0; const ANSWER_FEEDBACK_TYPE_QUESTION = 1; const ANSWER_FEEDBACK_TYPE_GIVEN = 2; const ANSWER_FEEDBACK_TYPE_GIVEN_CORRECT = 3; const ANSWER_FEEDBACK_TYPE_GIVEN_WRONG = 4; const ANSWER_FEEDBACK_TYPE_CORRECT = 5; const ANSWER_FEEDBACK_TYPE_WRONG = 6; const ANSWER_FEEDBACK_TYPE_ALL = 7; // Feedback location types const FEEDBACK_LOCATION_TYPE_NONE = 0; const FEEDBACK_LOCATION_TYPE_PAGE = 1; const FEEDBACK_LOCATION_TYPE_SUMMARY = 2; const FEEDBACK_LOCATION_TYPE_BOTH = 3; /** * * @var boolean */ private $allow_hints; /** * * @var boolean */ private $show_score; /** * * @var boolean */ private $show_correction; /** * * @var boolean */ private $show_solution; /** * * @var int */ private $show_answer_feedback; /** * * @var int */ private $feedback_location; /** * * @param boolean $allow_hints * @param boolean $show_score * @param boolean $show_correction * @param boolean $show_solution * @param int $show_answer_feedback * @param int $feedback_location */ public function __construct($allow_hints = true, $show_score = true, $show_correction = true, $show_solution = true, $show_answer_feedback = self :: ANSWER_FEEDBACK_TYPE_ALL, $feedback_location = self :: FEEDBACK_LOCATION_TYPE_BOTH) { $this->allow_hints = $allow_hints; $this->show_score = $show_score; $this->show_correction = $show_correction; $this->show_solution = $show_solution; $this->show_answer_feedback = $show_answer_feedback; $this->feedback_location = $feedback_location; } /** * * @return boolean */ public function get_allow_hints() { return $this->allow_hints; } /** * Disable hints */ public function disable_hints() { $this->allow_hints = false; } /** * Enable hints */ public function enable_hints() { $this->allow_hints = true; } /** * * @return boolean */ public function allow_hints() { return (bool) $this->get_allow_hints(); } /** * * @return boolean */ public function get_show_score() { return $this->show_score; } /** * * @return boolean */ public function show_score() { return $this->get_show_score(); } /** * * @return boolean */ public function get_show_correction() { return $this->show_correction; } /** * * @return boolean */ public function show_correction() { return $this->get_show_correction(); } /** * * @return boolean */ public function get_show_solution() { return $this->show_solution; } /** * * @return boolean */ public function show_solution() { return $this->get_show_solution(); } /** * * @return int */ public function get_show_answer_feedback() { return $this->show_answer_feedback; } /** * * @return boolean */ public function show_answer_feedback() { return $this->get_show_answer_feedback() != self::ANSWER_FEEDBACK_TYPE_NONE; } /** * * @return int */ public function get_feedback_location() { return $this->feedback_location; } /** * Disable feedback at the end of the assessment */ public function disable_feedback_summary() { switch ($this->get_feedback_location()) { case self::FEEDBACK_LOCATION_TYPE_BOTH : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_PAGE; break; case self::FEEDBACK_LOCATION_TYPE_SUMMARY : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_NONE; break; } } /** * Enable feedback at the end of the assessment */ public function enable_feedback_summary() { switch ($this->get_feedback_location()) { case self::FEEDBACK_LOCATION_TYPE_NONE : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_SUMMARY; break; case self::FEEDBACK_LOCATION_TYPE_PAGE : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_BOTH; break; } } /** * Disable feedback per page */ public function disable_feedback_per_page() { switch ($this->get_feedback_location()) { case self::FEEDBACK_LOCATION_TYPE_BOTH : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_SUMMARY; break; case self::FEEDBACK_LOCATION_TYPE_PAGE : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_NONE; break; } } /** * Enable feedback per page */ public function enable_feedback_per_page() { switch ($this->get_feedback_location()) { case self::FEEDBACK_LOCATION_TYPE_NONE : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_PAGE; break; case self::FEEDBACK_LOCATION_TYPE_SUMMARY : $this->feedback_location = self::FEEDBACK_LOCATION_TYPE_BOTH; break; } } /** * Returns whether or not any kind of "feedback" is enabled * * @return boolean */ public function show_feedback() { return $this->show_score() || $this->show_correction(); } /** * Should feedback be displayed after every page * * @return boolean */ public function show_feedback_after_every_page() { return $this->get_feedback_location() == self::FEEDBACK_LOCATION_TYPE_PAGE || $this->get_feedback_location() == self::FEEDBACK_LOCATION_TYPE_BOTH; } /** * Should feedback be displayed as a summary at the end of an assessment * * @return boolean */ public function show_feedback_summary() { return $this->get_feedback_location() == self::FEEDBACK_LOCATION_TYPE_SUMMARY || $this->get_feedback_location() == self::FEEDBACK_LOCATION_TYPE_BOTH; } /** * * @return string */ public function get_answer_feedback_string() { return self::answer_feedback_string($this->get_show_answer_feedback()); } /** * * @param int $answer_feedback_type * @return string * @throws \Exception */ static public function answer_feedback_string($answer_feedback_type) { switch ($answer_feedback_type) { case Configuration::ANSWER_FEEDBACK_TYPE_QUESTION : $variable = 'AnswerFeedbackQuestion'; break; case Configuration::ANSWER_FEEDBACK_TYPE_GIVEN : $variable = 'AnswerFeedbackOnGivenAnswers'; break; case Configuration::ANSWER_FEEDBACK_TYPE_GIVEN_CORRECT : $variable = 'AnswerFeedbackOnGivenAnswersWhenCorrect'; break; case Configuration::ANSWER_FEEDBACK_TYPE_GIVEN_WRONG : $variable = 'AnswerFeedbackOnGivenAnswersWhenWrong'; break; case Configuration::ANSWER_FEEDBACK_TYPE_CORRECT : $variable = 'AnswerFeedbackOnCorrectAnswers'; break; case Configuration::ANSWER_FEEDBACK_TYPE_WRONG : $variable = 'AnswerFeedbackOnWrongAnswers'; break; case Configuration::ANSWER_FEEDBACK_TYPE_ALL : $variable = 'AnswerFeedbackOnAllAnswers'; break; case Configuration::ANSWER_FEEDBACK_TYPE_NONE : $variable = 'AnswerFeedbackNone'; break; default : throw new \Exception(Translation::get('NoSuchAnswerFeedbackType')); break; } return Translation::get($variable); } /** * * @return int[] */ static public function get_answer_feedback_types() { return array( self::ANSWER_FEEDBACK_TYPE_NONE, self::ANSWER_FEEDBACK_TYPE_QUESTION, self::ANSWER_FEEDBACK_TYPE_GIVEN, self::ANSWER_FEEDBACK_TYPE_GIVEN_CORRECT, self::ANSWER_FEEDBACK_TYPE_GIVEN_WRONG, self::ANSWER_FEEDBACK_TYPE_CORRECT, self::ANSWER_FEEDBACK_TYPE_WRONG, self::ANSWER_FEEDBACK_TYPE_ALL); } }
{'content_hash': 'e9b2853e4d46be9518676fd3782b930a', 'timestamp': '', 'source': 'github', 'line_count': 373, 'max_line_length': 123, 'avg_line_length': 25.66756032171582, 'alnum_prop': 0.5595362439941508, 'repo_name': 'cosnicsTHLU/cosnics', 'id': '7cc7914ce52e256f7dc5a31f44c4db5e80f1a25d', 'size': '9574', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Chamilo/Core/Repository/ContentObject/Assessment/Display/Configuration.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '86189'}, {'name': 'C#', 'bytes': '23363'}, {'name': 'CSS', 'bytes': '1135928'}, {'name': 'CoffeeScript', 'bytes': '17503'}, {'name': 'Gherkin', 'bytes': '24033'}, {'name': 'HTML', 'bytes': '542339'}, {'name': 'JavaScript', 'bytes': '5296016'}, {'name': 'Makefile', 'bytes': '3221'}, {'name': 'PHP', 'bytes': '21903304'}, {'name': 'Ruby', 'bytes': '618'}, {'name': 'Shell', 'bytes': '6385'}, {'name': 'Smarty', 'bytes': '15750'}, {'name': 'XSLT', 'bytes': '44115'}]}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _variablesEs = require('../core/variables.es6.js'); var _variablesEs2 = _interopRequireDefault(_variablesEs); var _functionsEs = require('../core/functions.es6.js'); var _functionsEs2 = _interopRequireDefault(_functionsEs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // Specifies the number of columns an element should span. If the selector is nested the number of columns // of its parent element should be passed as an argument as well. // // @columns // The unitless number of columns the element spans. If is not passed, it is equal to `@neatElementColumns`. // `@columns` also accepts decimals for when it's necessary to break out of the standard grid. // E.g. Passing `2.4` in a standard 12 column grid will divide the row into 5 columns. // // @container-columns // The number of columns the parent element spans. If is not passed, it is equal to `@neatGridColumns`, // the total number of columns in the grid. // // @display // Sets the display property of the element. By default it sets the display property of the element to `block`. // If passed `block-collapse`, it also removes the margin gutter by adding it to the element width. // If passed `table`, it sets the display property to `table-cell` and calculates the width of the // element without taking gutters into consideration. The result does not align with the block-based grid. // // @example - PostCSS Usage // .element { // @neat-span-columns 6; // // .nested-element { // @neat-span-columns 2 6; // } // } // // @example - CSS Output // .element { // display: block; // float: left; // margin-right: 2.3576516%; // width: 48.8211742%; // } // // .element:last-child { // margin-right: 0; // } // // .element .nested-element { // display: block; // float: left; // margin-right: 4.82915791%; // width: 30.11389472%; // } // // .element .nested-element:last-child { // margin-right: 0; // } // var spanColumns = function spanColumns(columns, containerColumns, display, direction) { var options = arguments.length <= 4 || arguments[4] === undefined ? _variablesEs2.default : arguments[4]; columns = columns || options.neatElementColumns; containerColumns = containerColumns || options.neatGridColumns; display = display || options.neatDefaultDisplay; direction = direction || options.neatDefaultDirection; var directions = _functionsEs2.default.getDirection(direction); var columnWidth = _functionsEs2.default.flexWidth(columns, containerColumns, options.neatColumnWidth, options.neatGutterWidth); var columnGutter = _functionsEs2.default.flexGutter(containerColumns, options.neatColumnWidth, options.neatGutterWidth); if (display === 'table') { return { 'display': 'table-cell', 'width': _functionsEs2.default.percentage(columns / containerColumns) }; } else if (display === 'block-collapse') { return { 'display': 'block', 'float': directions.oppositeDirection, 'width': _functionsEs2.default.percentage(columnWidth + columnGutter), // --- '&:last-child': { 'width': _functionsEs2.default.percentage(columnWidth) } }; } else { var _ref; return _ref = { 'display': 'block', 'float': directions.oppositeDirection }, _defineProperty(_ref, 'margin-' + directions.direction, _functionsEs2.default.percentage(columnGutter)), _defineProperty(_ref, 'width', _functionsEs2.default.percentage(columnWidth)), _defineProperty(_ref, '&:last-child', _defineProperty({}, 'margin-' + directions.direction, 0)), _ref; } }; exports.default = spanColumns; //# sourceMappingURL=span-columns.es6.js.map
{'content_hash': '387e91116ee3f61160c904e593b4dd67', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 293, 'avg_line_length': 37.31481481481482, 'alnum_prop': 0.6821339950372208, 'repo_name': 'jo-asakura/postcss-neat', 'id': 'b5885c72060d7dc53b007986e6dd002cab10273d', 'size': '4030', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/grid/span-columns.es6.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14664'}, {'name': 'JavaScript', 'bytes': '37437'}]}
package org.batfish.datamodel.visitors; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.collect.ImmutableMap; import org.batfish.datamodel.AclIpSpace; import org.batfish.datamodel.EmptyIpSpace; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpIpSpace; import org.batfish.datamodel.IpSpace; import org.batfish.datamodel.IpSpaceReference; import org.batfish.datamodel.IpWildcard; import org.batfish.datamodel.IpWildcardIpSpace; import org.batfish.datamodel.IpWildcardSetIpSpace; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.UniverseIpSpace; import org.junit.Test; public class IpSpaceRenamerTest { private static final String FOO = "foo"; private static final IpSpaceReference FOO_REFERENCE = new IpSpaceReference(FOO); private static final String BAR = "bar"; private static final IpSpaceReference BAR_REFERENCE = new IpSpaceReference(BAR); private static final IpIpSpace IP_IP_SPACE = Ip.parse("1.1.1.1").toIpSpace(); private static final IpSpaceRenamer RENAMER = new IpSpaceRenamer(ImmutableMap.of(FOO, BAR)::get); private static final IpSpace PREFIX_IP_SPACE = Prefix.parse("1.0.0.0/8").toIpSpace(); private static final IpWildcardIpSpace IP_WILDCARD_IP_SPACE = IpWildcard.parse("1.2.0.0/16").toIpSpace(); private static final IpWildcardSetIpSpace IP_WILDCARD_SET_IP_SPACE = IpWildcardSetIpSpace.builder() .including(IpWildcard.parse("1.2.3.4")) .excluding(IpWildcard.parse("5.6.7.8")) .build(); @Test public void testIdentities() { assertThat(RENAMER.apply(UniverseIpSpace.INSTANCE), equalTo(UniverseIpSpace.INSTANCE)); assertThat(RENAMER.apply(EmptyIpSpace.INSTANCE), equalTo(EmptyIpSpace.INSTANCE)); assertThat(RENAMER.apply(IP_IP_SPACE), equalTo(IP_IP_SPACE)); assertThat(RENAMER.apply(PREFIX_IP_SPACE), equalTo(PREFIX_IP_SPACE)); assertThat(RENAMER.apply(IP_WILDCARD_IP_SPACE), equalTo(IP_WILDCARD_IP_SPACE)); assertThat(RENAMER.apply(IP_WILDCARD_SET_IP_SPACE), equalTo(IP_WILDCARD_SET_IP_SPACE)); } @Test public void testIpSpaceReference() { assertThat(RENAMER.apply(FOO_REFERENCE), equalTo(BAR_REFERENCE)); } @Test public void testAclIpSpace() { IpSpace input = AclIpSpace.builder() .thenPermitting(IP_IP_SPACE) .thenRejecting(PREFIX_IP_SPACE) .thenPermitting(FOO_REFERENCE) .thenRejecting(IP_WILDCARD_IP_SPACE) .thenPermitting(IP_WILDCARD_SET_IP_SPACE) .build(); IpSpace output = AclIpSpace.builder() .thenPermitting(IP_IP_SPACE) .thenRejecting(PREFIX_IP_SPACE) .thenPermitting(BAR_REFERENCE) .thenRejecting(IP_WILDCARD_IP_SPACE) .thenPermitting(IP_WILDCARD_SET_IP_SPACE) .build(); assertThat(RENAMER.apply(input), equalTo(output)); } }
{'content_hash': 'ec5bf3709b095821ad09d0893e97628c', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 99, 'avg_line_length': 39.66216216216216, 'alnum_prop': 0.723679727427598, 'repo_name': 'arifogel/batfish', 'id': '45f86e5e2c8f570c85313d7828b4803f2201b9d6', 'size': '2935', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/visitors/IpSpaceRenamerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1999103'}, {'name': 'HCL', 'bytes': '49266'}, {'name': 'Java', 'bytes': '25862751'}, {'name': 'Python', 'bytes': '11181'}, {'name': 'Shell', 'bytes': '6502'}, {'name': 'Starlark', 'bytes': '214539'}]}
/* @test * @summary Verify that DynamicPolicyProvider handles null inputs properly * @run main/othervm/policy=policy Test */ import java.security.*; import net.jini.security.policy.DynamicPolicyProvider; public class Test { public static void main(String[] args) throws Exception { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } DynamicPolicyProvider policy = new DynamicPolicyProvider(); policy.grant((Class) null,(Principal[]) null, (Permission[]) null); try { policy.grant((Class) null, new Principal[]{ null }, (Permission[]) null); throw new Error(); } catch (NullPointerException e) { } try { policy.grant((Class) null, (Principal[]) null, new Permission[]{ null }); throw new Error(); } catch (NullPointerException e) { } policy.getGrants(null, null); try { policy.getGrants(null, new Principal[]{ null }); throw new Error(); } catch (NullPointerException e) { } PermissionCollection pc = policy.getPermissions((ProtectionDomain) null); if (pc.elements().hasMoreElements()) { throw new Error("permissions returned for null protection domain"); } if (policy.implies(null, new RuntimePermission("foo"))) { throw new Error(); } } }
{'content_hash': '290875dc5d2e246bb17bb1c01132a268', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 78, 'avg_line_length': 30.19047619047619, 'alnum_prop': 0.6908517350157729, 'repo_name': 'pfirmstone/JGDMS', 'id': '7d024e6b9b1747e06ea1c24ba06d26116524a30b', 'size': '2074', 'binary': False, 'copies': '4', 'ref': 'refs/heads/trunk', 'path': 'qa/jtreg/net/jini/security/policy/DynamicPolicyProvider/nullCases/Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '38260'}, {'name': 'Groovy', 'bytes': '30510'}, {'name': 'HTML', 'bytes': '107806458'}, {'name': 'Java', 'bytes': '24863323'}, {'name': 'JavaScript', 'bytes': '1702'}, {'name': 'Makefile', 'bytes': '3032'}, {'name': 'Roff', 'bytes': '863'}, {'name': 'Shell', 'bytes': '68247'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '543bdb1662cad889895ba5e958bb3707', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '0855b6b9ce65591b70ddc2e3b95613f37716c80b', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Marsdenia/Marsdenia dracontea/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
"""Subscriber server application.""" from subscriber_server import ( db, server, main, )
{'content_hash': '37a41fb550ffac04540fc60b85b3197e', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 36, 'avg_line_length': 14.571428571428571, 'alnum_prop': 0.6372549019607843, 'repo_name': 'VRGhost/publish_subscribe_server_demo', 'id': '20caaee6b1cc661427a4ea0a451b01be07068637', 'size': '102', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'subscriber_server/__init__.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '634'}, {'name': 'Python', 'bytes': '20684'}, {'name': 'Shell', 'bytes': '685'}]}
<!-- HTML header for doxygen 1.8.8--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- For Mobile Devices --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.11"/> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <title>OxyEngine: Oxy.Framework.InputMap Class Reference</title> <!--<link href="tabs.css" rel="stylesheet" type="text/css"/>--> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="customdoxygen.css" rel="stylesheet" type="text/css"/> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="doxy-boot.js"></script> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand">OxyEngine 0.1.0pre</a> </div> </div> </nav> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div class="content" id="content"> <div class="container"> <div class="row"> <div class="col-sm-12 panel " style="padding-bottom: 15px;"> <div style="margin-bottom: 15px;"> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespace_oxy.html">Oxy</a></li><li class="navelem"><a class="el" href="namespace_oxy_1_1_framework.html">Framework</a></li><li class="navelem"><a class="el" href="class_oxy_1_1_framework_1_1_input_map.html">InputMap</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="class_oxy_1_1_framework_1_1_input_map-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">Oxy.Framework.InputMap Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>Class for mapping string to OpenTK Key enum <a href="class_oxy_1_1_framework_1_1_input_map.html#details">More...</a></p> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Class for mapping string to OpenTK Key enum </p> </div></div><!-- contents --> <!-- HTML footer for doxygen 1.8.8--> <!-- start footer part --> </div> </div> </div> </div> </div> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{'content_hash': '579c1af52bcb896f2d1594a965c738be', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 272, 'avg_line_length': 46.47933884297521, 'alnum_prop': 0.6205547652916074, 'repo_name': 'OxyTeam/OxyEngine', 'id': '002d768936d04f1edd87b0c494a0627c57c4d275', 'size': '5624', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'docs/html/class_oxy_1_1_framework_1_1_input_map.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '128159'}]}
declare function makeValue<T>(): T; export type BigIntLiteral = 1n; export const BigIntLiteralType = makeValue<1n>(); export type NegativeBigIntLiteral = -1n; export const NegativeBigIntLiteralType = makeValue<-1n>(); export type NumArray = number[]; export const numArray = makeValue<number[]>(); export type BigIntAlias = bigint; export type NegativeOne = -1; export const negativeOne = -1; export type FirstIfString<T extends unknown[]> = T extends [ infer S extends string, ...unknown[] ] ? S : never;
{'content_hash': 'ad0a3696950c82185e2c7605bbc426fd', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 60, 'avg_line_length': 24.0, 'alnum_prop': 0.7159090909090909, 'repo_name': 'TypeStrong/typedoc', 'id': 'db679fab776e5357866c782b667d45fa4514c838', 'size': '528', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/converter/types/general.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '189'}, {'name': 'CSS', 'bytes': '27924'}, {'name': 'JavaScript', 'bytes': '23874'}, {'name': 'Shell', 'bytes': '433'}, {'name': 'TypeScript', 'bytes': '1207272'}]}
using namespace DirectX; #include <iostream> BitmapClass::BitmapClass() { m_vertexBuffer = 0; m_indexBuffer = 0; m_Texture = 0; } BitmapClass::~BitmapClass() { } bool BitmapClass::Initialize(ID3D11Device* device, WCHAR* textureFilename, int screenWidth, int screenHeight, int bitmapWidth, int bitmapHeight) { bool result; // Store the screen size. m_screenWidth = screenWidth; m_screenHeight = screenHeight; // Store the size in pixels that this bitmap should be rendered at. m_bitmapWidth = bitmapWidth; m_bitmapHeight = bitmapHeight; // Initialize the previous rendering position to negative one. m_previousPosX = -1; m_previousPosY = -1; // Initialize the vertex and index buffer that hold the geometry for the triangle. result = InitializeBuffers(device); if(!result) { return false; } // Load the texture for this model. result = LoadTexture(device, textureFilename); if(!result) { return false; } return true; } bool BitmapClass::Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY) { bool result; // Re-build the dynamic vertex buffer for rendering to possibly a different location on the screen. result = UpdateBuffers(deviceContext, positionX, positionY); if(!result){ return false; } // Put the vertex and index buffers on the graphics pipeline to prepare them for drawing. RenderBuffers(deviceContext); return true; } void BitmapClass::Shutdown() { // Release the model texture. ReleaseTexture(); // Release the vertex and index buffers. ShutdownBuffers(); } ID3D11ShaderResourceView* BitmapClass::GetTexture() { return m_Texture->GetTexture(); } int BitmapClass::GetIndexCount() { return m_indexCount; } bool BitmapClass::InitializeBuffers(ID3D11Device* device) { m_vertexCount = m_indexCount = 6; // Create the vertex array. VertexType* vertices; vertices = new VertexType[m_vertexCount]; if(!vertices) { return false; } // Create the index array. unsigned long* indices; indices = new unsigned long[m_indexCount]; if(!indices) { return false; } // Initialize vertex array to zeros at first. ZeroMemory(vertices, (sizeof(VertexType) * m_vertexCount)); // Load the index array with data. for(int i=0; i<m_indexCount; i++) { indices[i] = i; } // Set up the description of the static vertex buffer. D3D11_BUFFER_DESC vertexBufferDesc; vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the vertex data. D3D11_SUBRESOURCE_DATA vertexData; vertexData.pSysMem = vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; // Now create the vertex buffer. HRESULT result; result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer); if(FAILED(result)) { return false; } // Set up the description of the static index buffer. D3D11_BUFFER_DESC indexBufferDesc; indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the index data. D3D11_SUBRESOURCE_DATA indexData; indexData.pSysMem = indices; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; // Create the index buffer. result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer); if(FAILED(result)) { return false; } // Release the arrays now that the vertex and index buffers have been created and loaded. delete [] vertices; vertices = 0; delete [] indices; indices = 0; return true; } bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY) { // If the position we are rendering this bitmap to has not changed then don't update the vertex buffer since it // currently has the correct parameters. if((positionX == m_previousPosX) && (positionY == m_previousPosY)) { return true; } // If it has changed then update the position it is being rendered to. m_previousPosX = positionX; m_previousPosY = positionY; float left, right, top, bottom; // Calculate the screen coordinates of the left side of the bitmap. left = (float)((m_screenWidth / 2) * -1) + (float)positionX; // Calculate the screen coordinates of the right side of the bitmap. right = left + (float)m_bitmapWidth; // Calculate the screen coordinates of the top of the bitmap. top = (float)(m_screenHeight / 2) - (float)positionY; // Calculate the screen coordinates of the bottom of the bitmap. bottom = top - (float)m_bitmapHeight; std::cout << "left: " << left << " " << "right: " << right << " " << "top: " << top << " " << "bottom: " << bottom << std::endl; // Create the vertex array. VertexType* vertices; vertices = new VertexType[m_vertexCount]; if(!vertices) { return false; } // Load the vertex array with data. // First triangle. vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[0].texture = XMFLOAT2(0.0f, 0.0f); vertices[1].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right. vertices[1].texture = XMFLOAT2(1.0f, 1.0f); vertices[2].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left. vertices[2].texture = XMFLOAT2(0.0f, 1.0f); // Second triangle. vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[3].texture = XMFLOAT2(0.0f, 0.0f); vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right. vertices[4].texture = XMFLOAT2(1.0f, 0.0f); vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right. vertices[5].texture = XMFLOAT2(1.0f, 1.0f); // Lock the vertex buffer so it can be written to. HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; result = deviceContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { return false; } // Get a pointer to the data in the vertex buffer VertexType* verticesPtr; verticesPtr = (VertexType*)mappedResource.pData; // Copy the data into the vertex buffer. memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * m_vertexCount)); // Unlock the vertex buffer. deviceContext->Unmap(m_vertexBuffer, 0); // Release the vertex array as it is no longer needed. delete [] vertices; vertices = 0; return true; } void BitmapClass::RenderBuffers(ID3D11DeviceContext* deviceContext) { unsigned int stride; unsigned int offset; // Set vertex buffer stride and offset. stride = sizeof(VertexType); offset = 0; // Set the vertex buffer to active in the input assembler so it can be rendered. deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset); // Set the index buffer to active in the input assembler so it can be rendered. deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles. deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); } void BitmapClass::ShutdownBuffers() { // Release the index buffer. if(m_indexBuffer) { m_indexBuffer->Release(); m_indexBuffer = 0; } // Release the vertex buffer. if(m_vertexBuffer) { m_vertexBuffer->Release(); m_vertexBuffer = 0; } } bool BitmapClass::LoadTexture(ID3D11Device* device, WCHAR* filename) { bool result; // Create the texture object. m_Texture = new TextureClass; if(!m_Texture) { return false; } // Initialize the texture object. result = m_Texture->Initialize(device, filename); if(!result) { return false; } return true; } void BitmapClass::ReleaseTexture() { // Release the texture object. if(m_Texture) { m_Texture->Shutdown(); delete m_Texture; m_Texture = 0; } }
{'content_hash': 'b1ba4dce3125385c254d228ccc18f7e7', 'timestamp': '', 'source': 'github', 'line_count': 325, 'max_line_length': 129, 'avg_line_length': 24.815384615384616, 'alnum_prop': 0.7217606943583385, 'repo_name': 'Cassio90/engine', 'id': '7d76aa25f1c3e5b1bd8cec05d5c71fce028507eb', 'size': '8091', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Engine/BitmapClass.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2058'}, {'name': 'C++', 'bytes': '244283'}]}
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0 To use the Who Played Bond - 007 Trivia skill, try saying... * *Alexa, open Who Played Bond* Think you know the James Bond films? Put your knowledge to the test with this Alexa Trivia Skill. Alexa will ask you "Who Played Bond" in 5 different 007 movies. Your job is to match up the correct actors with each movie. Enjoy! *** ### Skill Details * **Invocation Name:** who played bond * **Category:** null * **ID:** amzn1.echo-sdk-ams.app.052b92cd-025f-4b4e-92cf-fef35214b7de * **ASIN:** B01DEYA56M * **Author:** JGDev! * **Release Date:** March 25, 2016 @ 03:07:49 * **In-App Purchasing:** No
{'content_hash': '26c875dcfcc7ef970f85e8fb3db07a8e', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 287, 'avg_line_length': 38.65217391304348, 'alnum_prop': 0.6850393700787402, 'repo_name': 'dale3h/alexa-skills-list', 'id': '87bed5f368dbda2b39b5aa4a75c072cf368b10ce', 'size': '1015', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'skills/B01DEYA56M/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '16985'}]}
/** * Config file for the API */ exports.db_url = 'mongodb://localhost/my_mongorilla';
{'content_hash': '8055012150eba71a49d9f2625101f007', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 53, 'avg_line_length': 21.5, 'alnum_prop': 0.686046511627907, 'repo_name': 'shoptology/boilerplate', 'id': '28b86229c39d679967a33a4f6b1c295978c0d03e', 'size': '86', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'api/config.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '5124'}, {'name': 'CSS', 'bytes': '2423672'}, {'name': 'HTML', 'bytes': '2677337'}, {'name': 'JavaScript', 'bytes': '13933823'}, {'name': 'Makefile', 'bytes': '5620'}, {'name': 'PHP', 'bytes': '188824'}, {'name': 'PowerShell', 'bytes': '161'}, {'name': 'Python', 'bytes': '11423'}, {'name': 'Ruby', 'bytes': '2205'}, {'name': 'Shell', 'bytes': '111'}]}
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. defined('MOODLE_INTERNAL') || die(); /** * Provides the information to backup multianswer questions * * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class backup_qtype_multianswer_plugin extends backup_qtype_plugin { /** * Returns the qtype information to attach to question element */ protected function define_question_plugin_structure() { // Define the virtual plugin element with the condition to fulfill. $plugin = $this->get_plugin_element(null, '../../qtype', 'multianswer'); // Create one standard named plugin element (the visible container). $pluginwrapper = new backup_nested_element($this->get_recommended_name()); // Connect the visible container ASAP. $plugin->add_child($pluginwrapper); // This qtype uses standard question_answers, add them here // to the tree before any other information that will use them. $this->add_question_question_answers($pluginwrapper); // Now create the qtype own structures. $multianswer = new backup_nested_element('multianswer', array('id'), array( 'question', 'sequence')); // Now the own qtype tree. $pluginwrapper->add_child($multianswer); // Set source to populate the data. $multianswer->set_source_table('question_multianswer', array('question' => backup::VAR_PARENTID)); // Don't need to annotate ids nor files. return $plugin; } }
{'content_hash': 'ac47b24412086c75e2ae1fc8527b9c3c', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 83, 'avg_line_length': 35.734375, 'alnum_prop': 0.675120244862265, 'repo_name': 'sirromas/george', 'id': 'afe1b64c8f1aa05250534ec60392552207d16888', 'size': '2501', 'binary': False, 'copies': '512', 'ref': 'refs/heads/master', 'path': 'lms/question/type/multianswer/backup/moodle2/backup_qtype_multianswer_plugin.class.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '1205'}, {'name': 'ApacheConf', 'bytes': '240'}, {'name': 'CSS', 'bytes': '1510088'}, {'name': 'Gherkin', 'bytes': '1801305'}, {'name': 'HTML', 'bytes': '9090317'}, {'name': 'Java', 'bytes': '14870'}, {'name': 'JavaScript', 'bytes': '13189901'}, {'name': 'PHP', 'bytes': '80552810'}, {'name': 'PLSQL', 'bytes': '4867'}, {'name': 'Perl', 'bytes': '20769'}, {'name': 'XSLT', 'bytes': '33489'}]}
using System.Threading.Tasks; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// Partitioned stream recipient that will merge the results. /// </summary> internal class PartitionedStreamMerger<TOutput> : IPartitionedStreamRecipient<TOutput> { private bool _forEffectMerge; private ParallelMergeOptions _mergeOptions; private bool _isOrdered; private MergeExecutor<TOutput> _mergeExecutor = null; private TaskScheduler _taskScheduler; private int _queryId; // ID of the current query execution private CancellationState _cancellationState; #if DEBUG private bool _received = false; #endif // Returns the merge executor which merges the received partitioned stream. internal MergeExecutor<TOutput> MergeExecutor { get { #if DEBUG Contract.Assert(_received, "Cannot return the merge executor because Receive() has not been called yet."); #endif return _mergeExecutor; } } internal PartitionedStreamMerger(bool forEffectMerge, ParallelMergeOptions mergeOptions, TaskScheduler taskScheduler, bool outputOrdered, CancellationState cancellationState, int queryId) { _forEffectMerge = forEffectMerge; _mergeOptions = mergeOptions; _isOrdered = outputOrdered; _taskScheduler = taskScheduler; _cancellationState = cancellationState; _queryId = queryId; } public void Receive<TKey>(PartitionedStream<TOutput, TKey> partitionedStream) { #if DEBUG _received = true; #endif _mergeExecutor = MergeExecutor<TOutput>.Execute<TKey>( partitionedStream, _forEffectMerge, _mergeOptions, _taskScheduler, _isOrdered, _cancellationState, _queryId); TraceHelpers.TraceInfo("[timing]: {0}: finished opening - QueryOperator<>::GetEnumerator", DateTime.Now.Ticks); } } }
{'content_hash': 'f1e879500a20a0baf53af5ecfcdf332d', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 145, 'avg_line_length': 36.08771929824562, 'alnum_prop': 0.6562955760816723, 'repo_name': 'dmitry-shechtman/corefx', 'id': '417ad54d301820b50a779e2c6c0f4a2e8d3970dd', 'size': '2426', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/PartitionedStreamMerger.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1598'}, {'name': 'C#', 'bytes': '15067107'}, {'name': 'C++', 'bytes': '127'}, {'name': 'Visual Basic', 'bytes': '1609'}]}
package com.neoranga55.cleanguitestarchitecture.cucumber.steps; import android.support.test.espresso.EspressoException; import com.neoranga55.cleanguitestarchitecture.util.SpoonScreenshotAction; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import cucumber.api.Scenario; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.Given; /** * Class containing generic Cucumber test step definitions not related to specific views */ public class HelperSteps { private static Scenario scenario; @Before public static void before(final Scenario scenario) { HelperSteps.scenario = scenario; } public static Scenario getScenario() { return HelperSteps.scenario; } @After public static void after() { if ((HelperSteps.scenario != null) && (HelperSteps.scenario.isFailed())) { takeScreenshot("failed"); } } @Given("^I take a screenshot$") public void i_take_a_screenshot() { takeScreenshot("screenshot"); } /** * Take a screenshot of the current activity and embed it in the HTML report * * @param tag Name of the screenshot to include in the file name */ public static void takeScreenshot(final String tag) { if (scenario == null) { throw new ScreenshotException("Error taking screenshot: I'm missing a valid test scenario to attach the screenshot to"); } SpoonScreenshotAction.perform(tag); final File screenshot = SpoonScreenshotAction.getLastScreenshot(); if (screenshot == null) { throw new ScreenshotException("Screenshot was not taken correctly, check for failures in screenshot library"); } FileInputStream screenshotStream = null; try { screenshotStream = new FileInputStream(screenshot); final byte fileContent[] = new byte[(int) screenshot.length()]; final int readImageBytes = screenshotStream.read(fileContent); // Read data from input image file into an array of bytes if (readImageBytes != -1) { scenario.embed(fileContent, "image/png"); // Embed the screenshot in the report under current test step } } catch (final IOException ioe) { throw new ScreenshotException("Exception while reading file " + ioe); } finally { try { // close the streams using close method if (screenshotStream != null) { screenshotStream.close(); } } catch (final IOException ioe) { //noinspection ThrowFromFinallyBlock throw new ScreenshotException("Error while closing screenshot stream: " + ioe); } } } public static class ScreenshotException extends RuntimeException implements EspressoException { private static final long serialVersionUID = -1247022787790657324L; ScreenshotException(final String message) { super(message); } } }
{'content_hash': 'ae5de26d814a822f7036e78a72e7f0c7', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 132, 'avg_line_length': 35.21590909090909, 'alnum_prop': 0.6556953856082607, 'repo_name': 'whembed197923/CleanGUITestArchitecture', 'id': '363f7b5d3fa0a29ec245155159da28fc088a78db', 'size': '3099', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/androidTest/java/com/neoranga55/cleanguitestarchitecture/cucumber/steps/HelperSteps.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Cucumber', 'bytes': '981'}, {'name': 'Java', 'bytes': '26954'}]}
This is a Chrome extension that translates nasty troll terms into 💕 emojis ✨. It's not about sanitizing, but making your browser a place with less hate and more 🌺 🐣 🙊 🐳. Read that article, scan the comments, and be free of the hate speech and threatening language of internet trolls. And remember, DON'T FEED THE TROLLS. ## Install Pull down zip file. Unzip. In your Chrome browser, select "More Tools." Select "Extensions." Select "Load unpacked extension..." and choose the unzipped file. ## Usage Click the troll icon in your browser to trollmoji a page. If you have suggestions for new words or phrases to add to the library, get at us at trollmoji@gmail.com. ## This was made with [emojilib](https://github.com/muan/emojilib) and [emoji-translate](https://github.com/notwaldorf/emoji-translate).
{'content_hash': '877d95e1189288cf7aa48f83f473b5a2', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 133, 'avg_line_length': 30.48148148148148, 'alnum_prop': 0.7448359659781288, 'repo_name': 'ITP-DevPubInt/emoji-translate', 'id': '23bb98171dde40131af4a889cf2d6f6ccb28c342', 'size': '854', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3695'}]}
package com.walkertribe.ian.protocol.core; import org.junit.Test; import com.walkertribe.ian.util.TestUtil; public class CorePacketTypeTest { @Test public void makeEclEmmaHappy() { TestUtil.coverPrivateConstructor(CorePacketType.class); } }
{'content_hash': 'e9a9980296b829157f81b808dbbd8a73', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 57, 'avg_line_length': 20.75, 'alnum_prop': 0.7951807228915663, 'repo_name': 'rjwut/ian', 'id': 'b27fffdad40db30e865ef5f3ad8cfdab89d66edb', 'size': '249', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/walkertribe/ian/protocol/core/CorePacketTypeTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '875325'}]}
package com.siriusit.spezg.multilib.jsf.login; import java.io.IOException; import javax.annotation.Resource; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; /** * * @author Tommy Bø <Tommy.Bo@SiriusIT.com> * @author Svein Erik Løvland <svein-erik.lovland@siriusit.com> */ @Controller("loginBean") @Scope("request") public class LoginBean { private String username; private String password; private boolean rememberMe; @Resource private FacesContext context; public String logIn() throws IOException, ServletException { ExternalContext externalContext = context.getExternalContext(); ServletRequest servletRequest = (ServletRequest) externalContext.getRequest(); RequestDispatcher dispatcher = servletRequest.getRequestDispatcher("/j_spring_security_check"); dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); context.responseComplete(); return null; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } public boolean isRememberMe() { return rememberMe; } }
{'content_hash': '2645038deb080d6b07fa9473a5c3d882', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 103, 'avg_line_length': 28.166666666666668, 'alnum_prop': 0.6944593867670791, 'repo_name': 'sveintl/Multilib', 'id': '7ecfd9665448da26589811099910c6a74c8d998e', 'size': '2679', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'multilib-war/src/main/java/com/siriusit/spezg/multilib/jsf/login/LoginBean.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/* eslint-disable */ /** * Generated React hooks. * * THIS CODE IS AUTOMATICALLY GENERATED. * * Generated by convex@0.2.0. * To regenerate, run `npx convex codegen`. * @module */ import type { ApiFromModules, OptimisticLocalStore as GenericOptimisticLocalStore, } from "convex/browser"; import type { UseQueryForAPI, UseMutationForAPI, UseConvexForAPI, } from "convex/react"; import type * as getCounter from "../getCounter"; import type * as incrementCounter from "../incrementCounter"; /** * A type describing your app's public Convex API. * * This `ConvexAPI` type includes information about the arguments and return * types of your app's query and mutation functions. * * This type should be used with type-parameterized classes like * `ConvexReactClient` to create app-specific types. */ export type ConvexAPI = ApiFromModules<{ getCounter: typeof getCounter; incrementCounter: typeof incrementCounter; }>; /** * Load a reactive query within a React component. * * This React hook contains internal state that will cause a rerender whenever * the query result changes. * * This relies on the {@link ConvexProvider} being above in the React component tree. * * @param name - The name of the query function. * @param args - The arguments to the query function. * @returns `undefined` if loading and the query's return value otherwise. */ export declare const useQuery: UseQueryForAPI<ConvexAPI>; /** * Construct a new {@link ReactMutation}. * * Mutation objects can be called like functions to request execution of the * corresponding Convex function, or further configured with * [optimistic updates](https://docs.convex.dev/using/optimistic-updates). * * The value returned by this hook is stable across renders, so it can be used * by React dependency arrays and memoization logic relying on object identity * without causing rerenders. * * This relies on the {@link ConvexProvider} being above in the React component tree. * * @param name - The name of the mutation. * @returns The {@link ReactMutation} object with that name. */ export declare const useMutation: UseMutationForAPI<ConvexAPI>; /** * Get the {@link ConvexReactClient} within a React component. * * This relies on the {@link ConvexProvider} being above in the React component tree. * * @returns The active {@link ConvexReactClient} object, or `undefined`. */ export declare const useConvex: UseConvexForAPI<ConvexAPI>; /** * A view of the query results currently in the Convex client for use within * optimistic updates. */ export type OptimisticLocalStore = GenericOptimisticLocalStore<ConvexAPI>;
{'content_hash': 'aebb16e16e325e2896875a86cae6e836', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 85, 'avg_line_length': 31.83132530120482, 'alnum_prop': 0.7452687358062074, 'repo_name': 'JeromeFitz/next.js', 'id': '53b69d9b1246a612df41e2a54f796c3072beeb7c', 'size': '2642', 'binary': False, 'copies': '1', 'ref': 'refs/heads/canary', 'path': 'examples/convex/convex/_generated/react.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '579'}, {'name': 'CSS', 'bytes': '38864'}, {'name': 'JavaScript', 'bytes': '8065763'}, {'name': 'Rust', 'bytes': '165055'}, {'name': 'SCSS', 'bytes': '5957'}, {'name': 'Sass', 'bytes': '302'}, {'name': 'Shell', 'bytes': '4512'}, {'name': 'TypeScript', 'bytes': '4906530'}]}
"""Compare two Graphite clusters for a given list of queries. Through this module, a "query" is "the name of a query", a string. """ from __future__ import unicode_literals from __future__ import absolute_import from __future__ import print_function import argparse import urllib2 import json import base64 import time import sys import logging import urllib import collections import progressbar import operator import abc import netrc class Error(Exception): """Error.""" class RequestError(Error): """RequestError.""" class Request(object): """Runs HTTP requests and parses JSON.""" def __init__(self, url, auth_key, timeout_s, data=None): """Create a Request.""" self._request = self._prepare(url, auth_key, data=data) self._timeout_s = timeout_s def _prepare(self, url, auth_key, data=None): """Create an http request.""" headers = {} if auth_key is not None: headers["Authorization"] = "Basic %s" % auth_key request = urllib2.Request(url, data, headers) return request def _parse_request_result(self, json_str): """Parse a jsonObject into a list of DiffableTarget.""" if not json_str: return [] try: json_data = json.loads(json_str) except ValueError: return [] diffable_targets = [] for json_object in json_data: if "target" not in json_object: continue target = json_object["target"] # target are not always formated in the same way in every cluster, so we delete spaces target = target.replace(" ", "") ts_to_val = {ts: val for val, ts in json_object["datapoints"]} diffable_targets.append(DiffableTarget(target, ts_to_val)) return diffable_targets def execute(self): """Execute the request and returns a list of DiffableTarget, time_s.""" start = time.time() diffable_targets = [] try: response = urllib2.urlopen(self._request, timeout=self._timeout_s) json_str = response.read() diffable_targets = self._parse_request_result(json_str) except IOError as e: raise RequestError(e) time_s = time.time() - start return (diffable_targets, time_s) class HostResult(object): """Store all information on a given host.""" def __init__(self, name): """Create a HostResult.""" self.name = name self.query_to_error = {} self.query_to_time_s = {} self.diffable_queries = [] def add_error(self, query, e): """Add an error message for a given query.""" self.query_to_error[query] = "%s" % e def add_time_s(self, query, time_s): """Add a recorded time to fetch a query.""" self.query_to_time_s[query] = time_s def add_diffable_query(self, diffable_query): """Add a diffable_query to the list.""" self.diffable_queries.append(diffable_query) def compute_timing_pctls(self): """Compute a dict of pctl from query_to_time_s values.""" return _compute_pctls(self.query_to_time_s.values()) def get_error_to_query(self): """Reverse query_to_error to get error_to_queries.""" error_to_queries = collections.defaultdict(list) for query, err in self.query_to_error.iteritems(): error_to_queries[err].append(query) return error_to_queries class Diffable(object): """ABC for diffable objects.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def measure_dissymmetry(self, other): """Return measure of difference as a Dissymmetry.""" pass class DiffableTarget(Diffable): """DiffableTarget.""" def __init__(self, name, ts_to_val): """DiffableTarget.""" self.name = name self.ts_to_val = ts_to_val def _measure_relative_gap(self, val1, val2): if val1 == val2: return 0.0 if val1 is None or val2 is None: return 1.0 return abs(val1 - val2)/(abs(val1)+abs(val2)) def measure_dissymmetry(self, other): """Return measure of difference as a Dissymmetry.""" other_ts_to_val = other.ts_to_val if other else {} all_ts_set = self.ts_to_val.viewkeys() | other_ts_to_val.viewkeys() if not all_ts_set: return None val_tuples = [(self.ts_to_val.get(ts), other_ts_to_val.get(ts)) for ts in all_ts_set] diff_measures = [self._measure_relative_gap(val1, val2) for val1, val2 in val_tuples] return Dissymmetry(self.name, diff_measures) class DiffableQuery(Diffable): """DiffableQuery.""" def __init__(self, name, diffable_targets, threshold): """Create a DiffableQuery.""" self.name = name self.threshold = threshold self.diffable_targets = diffable_targets def _measure_non_equal_pts_percentage(self, diffable_targets1, diffable_targets2, threshold): if not diffable_targets1 or not diffable_targets2: return 1.0 # if target_dissymmetry is None, both host responses were empty for this target name target_dissymmetry = diffable_targets1.measure_dissymmetry(diffable_targets2) if not target_dissymmetry: return 0.0 val_diff_measures = target_dissymmetry.measures count = 0 for val_diff_measure in val_diff_measures: if val_diff_measure > threshold: count += 1 return float(count) / len(val_diff_measures) def measure_dissymmetry(self, other): """Return measure of difference as a Dissymmetry.""" # For each couple of diffable_target it calls measure_dissymmetries # and measure the percentage of non-equal points using a threshold. diffable_target_tuples = _outer_join_diffables( self.diffable_targets, other.diffable_targets) if not diffable_target_tuples: return None diff_measures = [self._measure_non_equal_pts_percentage(diffable_target1, diffable_target2, self.threshold) for diffable_target1, diffable_target2 in diffable_target_tuples] return Dissymmetry(self.name, diff_measures) class Dissymmetry(object): """Dissymmetry.""" def __init__(self, name, measures): """Create a Dissymmetry.""" self.name = name self.measures = measures self.pctls = _compute_pctls(measures) def get_99th(self): """Return only the 99pctl. Usefull to sort Percentiles. """ return self.pctls.get(99, None) class Printer(object): """ABC for printers.""" __metaclass__ = abc.ABCMeta QUERY_PCTLS_DESCRIPTION = "Percentage of almost non-equal points using threshold" TARGET_PCTLS_DESCRIPTION = "Percentage of dyssymmetries between values" TIMING_PCTLS_DESCRIPTION = "Durations in second to fetch queries" @abc.abstractmethod def print_parameters(self, opts): """Print all parameters of the script.""" pass @abc.abstractmethod def print_dissymetry_results(self, query_dissymmetries, query_to_target_dissymmetries, verbosity, show_max): """Print all percentiles per query and per target. The list is limited with the show_max parameter and target percentiles are shown only if the verbose parameter is True. """ pass @abc.abstractmethod def print_errors(self, hosts, error_counts_tuple, error_to_queries_tuple, verbosity): """Print per host the number of errors and the number of occurrences of errors. If the verbose parameter is True, the list of queries affected are printed after each error. """ pass @abc.abstractmethod def print_times(self, hosts, timing_pctls_tuple, query_to_time_s_tuple, verbosity, show_max): """Print per host the durations percentiles for fetching queries. If the verbose parameter is True, the list of the slowest queries is printed, limited with the show_max parameter. """ pass class TxtPrinter(Printer): """TxtPrinter.""" def __init__(self, fp=None): """Create a txt Printer.""" self._file = fp or sys.stdout def _print(self, *args, **kwargs): """Print in a given file.""" kwargs["file"] = self._file print(*args, **kwargs) def _format_header(self, header_title): seq = [ "", "".center(30, "="), header_title.upper().center(30, "=") ] return "\n".join(seq) def _format_pctl(self, pctls, nth, unit): val = pctls.get(nth) if unit == "%": val *= 100 return "%s pctl : %0.3f %s" % (nth, val, unit) def print_parameters(self, opts): """See Printer. Print all parameters of the script.""" seq = [ self._format_header("Parameters"), "|", "| netrc_filename : %s" % (opts.netrc_filename or "$HOME/$USER/.netrc"), "|", "| hosts :", "| \t- %s" % opts.hosts[0], "| \t- %s" % opts.hosts[1], "|", "| inputs filename : %s" % opts.input_filename, "| \t- from : %s" % opts.from_param, "| \t- until : %s" % opts.until_param, "| \t- timeout : %s seconds" % opts.timeout_s, "| \t- threshold : %s %%" % opts.threshold, "|", "| outputs filename : %s" % (opts.output_filename or "stdout"), "| \t- max number of shown results : %s" % opts.show_max, "| \t- verbosity : %s" % opts.verbosity, "|", ] self._print("\n".join(seq)) def _print_pctls(self, name, pctls, prefix="", chip="", delay=""): self._print("\n %s %s %s : %s" % (delay, chip, prefix, name)) if pctls is None: return for k in pctls.iterkeys(): if prefix == "host": self._print("\t%s %s" % (delay, self._format_pctl(pctls, k, unit="s"))) else: self._print("\t%s %s" % (delay, self._format_pctl(pctls, k, unit="%"))) def print_dissymetry_results(self, query_dissymmetries, query_to_target_dissymmetries, verbosity, show_max): """See Printer. Print all percentiles per query and per target. The list is limited with the show_max parameter and target percentiles are shown only if the verbose parameter is True. """ self._print(self._format_header("Comparison results")) all_query_dissymmetries_count = len(query_dissymmetries) query_dissymmetries = [query_dissymmetry for query_dissymmetry in query_dissymmetries if query_dissymmetry] self._print("\nThere was %s queries with empty response on both clusters." % ( all_query_dissymmetries_count - len(query_dissymmetries))) query_dissymmetries = sorted( query_dissymmetries, key=Dissymmetry.get_99th, reverse=True) del query_dissymmetries[show_max:] self._print("\nThe %s most dissymmetrical queries : " % show_max) self._print("%s for : " % Printer.QUERY_PCTLS_DESCRIPTION) for query_dissymmetry in query_dissymmetries: self._print_pctls(query_dissymmetry.name, query_dissymmetry.pctls, "query", chip=">") if verbosity >= 1: self._print("\n\tThe %s most dissymmetrical targets : " % show_max) self._print("\t%s for : " % Printer.TARGET_PCTLS_DESCRIPTION) for target_dissymmetry in query_to_target_dissymmetries[query_dissymmetry.name]: self._print_pctls(target_dissymmetry.name, target_dissymmetry.pctls, "target", chip=">>", delay="\t") def print_errors(self, hosts, error_counts_tuple, error_to_queries_tuple, verbosity): """See Printer. Print per host the number of errors and the number of occurrences of errors. If the verbose parameter is True, the list of queries affected are printed after each error. """ self._print(self._format_header("Error report")) for i, host in enumerate(hosts): error_counts = error_counts_tuple[i] total_errors = 0 for error, count in error_counts: total_errors += count self._print("\nThere was %s error(s) for %s" % (total_errors, host)) if error_counts: error_to_queries = error_to_queries_tuple[i] self._print("\tError counts : ") for (error, count) in error_counts: self._print("\t > %s : %s" % (error, count)) if verbosity >= 1: for query in error_to_queries[error]: self._print("\t\t >> %s " % query) def print_times(self, hosts, timing_pctls_tuple, query_to_time_s_tuple, verbosity, show_max): """See Printer. Print per host the durations percentiles for fetching queries. If the verbose parameter is True, the list of the slowest queries is printed, limited with the show_max parameter. """ self._print(self._format_header("Timing info")) self._print("\n%s for : " % Printer.TIMING_PCTLS_DESCRIPTION) for i in range(2): host = hosts[i] timing_pctls = timing_pctls_tuple[i] self._print_pctls(host, timing_pctls, prefix="host") if verbosity >= 1: query_to_time_s = query_to_time_s_tuple[i] query_time_s = sorted( query_to_time_s.items(), key=operator.itemgetter(1), reverse=True) del query_time_s[show_max:] self._print("\n\tThe %s slowest queries : " % show_max) for (query, time_s) in query_time_s: self._print("\t > %s : %s" % (query, time_s)) def _read_queries(filename): """Read the list of queries from a given input text file.""" with open(filename, "r") as f: lines = f.readlines() queries = [] for line in lines: query = line.partition("#")[0] query = query.strip() if not query: continue queries.append(query) return queries def _get_url_from_query(host, prefix, query, from_param, until_param): """Encode an url from a given query for a given host.""" # If the query is not already url-friendly, we make it be if "%" not in query: query = urllib.quote(query) url = "http://%s/render/?noCache&format=json&from=%s&until=%s&target=%s" % ( host, from_param, until_param, prefix + query) return url def fetch_queries(host, prefix, auth_key, queries, from_param, until_param, timeout_s, threshold, progress_cb): """Return a list of HostResult.""" host_result = HostResult(host) for n, query in enumerate(queries): url = _get_url_from_query(host, prefix, query, from_param, until_param) request = Request(url, auth_key, timeout_s) try: diffable_targets, time_s = request.execute() host_result.add_time_s(query, time_s) host_result.add_diffable_query(DiffableQuery(query, diffable_targets, threshold)) except RequestError as e: host_result.add_error(query, e) host_result.add_diffable_query(DiffableQuery(query, [], threshold)) progress_cb(n) return host_result def _compute_pctls(measures): """Return 50pctl, 90pctl, 99pctl, and 999pctl in a dict for the given dissymetries.""" # If measures is empty, then one of the diffables was empty and not the other, # so the dissymmetry pctls should all be set at 100% if not measures: return None pctls = collections.OrderedDict() sorted_measures = sorted(measures) for i in [50, 75, 90, 99, 99.9]: # Don't even try to interpolate. rank = int(i / 100. * (len(measures))) pctls[i] = sorted_measures[rank] return pctls def compute_dissymmetries(diffables_a, diffables_b): """Return a list of dissymmetry from two given diffable lists.""" if not diffables_a and not diffables_b: return [] dissymmetries = [] for a, b in _outer_join_diffables(diffables_a, diffables_b): if not a: dissymmetry = b.measure_dissymmetry(a) else: dissymmetry = a.measure_dissymmetry(b) dissymmetries.append(dissymmetry) return dissymmetries def _outer_join_diffables(diffables_a, diffables_b): """Return a safe list of tuples of diffables whose name is equal.""" index_a = {a.name: a for a in diffables_a} index_b = {b.name: b for b in diffables_b} names = {a.name for a in diffables_a} names.update([b.name for b in diffables_b]) return [(index_a.get(n), index_b.get(n)) for n in names] def _parse_opts(args): parser = argparse.ArgumentParser( description="Compare two Graphite clusters for a given list of queries.", epilog="Through this module, a \"query\" is \"the name of a query\", a string.") # authentication authentication = parser.add_argument_group("authentication") authentication.add_argument("--netrc-file", metavar="FILENAME", dest="netrc_filename", action="store", help="a netrc file (default: $HOME/$USER/.netrc)", default="") # clusters parameters comparison_params = parser.add_argument_group("comparison parameters") comparison_params.add_argument("--hosts", metavar="HOST", dest="hosts", action="store", nargs=2, help="hosts to compare", required=True) comparison_params.add_argument("--prefixes", metavar="PREFIX", dest="prefixes", action="store", nargs=2, help="prefix for each host.", required=False, default="") comparison_params.add_argument("--input-file", metavar="FILENAME", dest="input_filename", action="store", help="text file containing one query per line", required=True) comparison_params.add_argument("--from", metavar="FROM_PARAM", dest="from_param", action="store", default="-24hours", help="from param for Graphite API (default: %(default)s)") comparison_params.add_argument("--until", metavar="UNTIL_PARAM", dest="until_param", action="store", default="-2minutes", help="until param for Graphite API (default: %(default)s)") comparison_params.add_argument( "--timeout", metavar="SECONDS", dest="timeout_s", action="store", type=float, help="timeout in seconds used to fetch queries (default: %(default)ss)", default=5) comparison_params.add_argument( "--threshold", metavar="PERCENT", action="store", type=float, default=1, help="percent threshold to evaluate equality between two values (default: %(default)s%%)") # outputs parameters outputs_params = parser.add_argument_group("outputs parameters") outputs_params.add_argument("--output-file", metavar="FILENAME", dest="output_filename", action="store", help="file containing outputs (default: stdout)", default="") outputs_params.add_argument("-v", "--verbosity", action="count", default=0, help="increases verbosity, can be passed multiple times") outputs_params.add_argument( "--show-max", metavar="N_LINES", dest="show_max", type=int, default=5, help="truncate the number of shown dissymmetry in outputs (default: %(default)s)") # TODO (t.chataigner) enable several kind of outputs : txt, csv, html... opts = parser.parse_args(args) # compute authentication keys from netrc file opts.auth_keys = [None, None] for host in opts.hosts: auth = netrc.netrc().authenticators(host) if auth is not None: username = auth[0] password = auth[2] opts.auth_keys.append(base64.encodestring(username + ":" + password).replace("\n", "")) else: logging.info(netrc.NetrcParseError("No authenticators for %s" % host)) opts.threshold /= 100 return opts def main(args=None): """Entry point for the module.""" if not args: args = sys.argv[1:] opts = _parse_opts(args) # fetch inputs queries = _read_queries(opts.input_filename) # host_result_1 pbar = progressbar.ProgressBar(maxval=len(queries)).start() host_result_1 = fetch_queries(opts.hosts[0], opts.prefixes[0], opts.auth_keys[0], queries, opts.from_param, opts.until_param, opts.timeout_s, opts.threshold, pbar.update) pbar.finish() # host_result_2 pbar = progressbar.ProgressBar(maxval=len(queries)).start() host_result_2 = fetch_queries(opts.hosts[1], opts.prefixes[1], opts.auth_keys[1], queries, opts.from_param, opts.until_param, opts.timeout_s, opts.threshold, pbar.update) pbar.finish() # compute outputs query_dissymmetries = compute_dissymmetries( host_result_1.diffable_queries, host_result_2.diffable_queries) diffable_query_tuples = _outer_join_diffables( host_result_1.diffable_queries, host_result_2.diffable_queries) query_to_target_dissymmetries = { diffable_query_1.name: compute_dissymmetries( diffable_query_1.diffable_targets, diffable_query_2.diffable_targets) for diffable_query_1, diffable_query_2 in diffable_query_tuples} timing_pctls_tuple = ( host_result_1.compute_timing_pctls(), host_result_2.compute_timing_pctls(), ) query_to_time_s_tuple = ( host_result_1.query_to_time_s, host_result_2.query_to_time_s ) error_counts_tuple = ( collections.Counter(host_result_1.query_to_error.values()).most_common(), collections.Counter(host_result_2.query_to_error.values()).most_common() ) error_to_queries_tuple = ( host_result_1.get_error_to_query(), host_result_2.get_error_to_query() ) # print outputs if not opts.output_filename: fp = sys.stdout else: fp = open(opts.output_filename, 'w') printer = TxtPrinter(fp=fp) printer.print_parameters(opts) printer.print_times( opts.hosts, timing_pctls_tuple, query_to_time_s_tuple, opts.verbosity, opts.show_max) printer.print_errors( opts.hosts, error_counts_tuple, error_to_queries_tuple, opts.verbosity) printer.print_dissymetry_results( query_dissymmetries, query_to_target_dissymmetries, opts.verbosity, opts.show_max) if __name__ == "__main__": main()
{'content_hash': '24554a29ea0fff82cb37106a12e502ff', 'timestamp': '', 'source': 'github', 'line_count': 632, 'max_line_length': 100, 'avg_line_length': 37.26107594936709, 'alnum_prop': 0.5901312157628774, 'repo_name': 'dpanth3r/biggraphite', 'id': 'ec60fd1e456855237dd1c5e9f6f56a21acb45c04', 'size': '24141', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'biggraphite/cli/clusters_diff.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '452294'}]}
div.dataTables_length label { font-weight: normal; float: left; text-align: left; } div.dataTables_length select { width: 75px; } div.dataTables_filter label { font-weight: normal; float: right; } div.dataTables_filter input { width: 16em; } div.dataTables_info { padding-top: 8px; } div.dataTables_paginate { float: right; margin: 0; } div.dataTables_paginate ul.pagination { margin: 2px 0; white-space: nowrap; } table.dataTable td, table.dataTable th { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } table.dataTable { clear: both; margin-top: 6px !important; margin-bottom: 6px !important; max-width: none !important; } table.dataTable thead .sorting, table.dataTable thead .sorting_asc, table.dataTable thead .sorting_desc, table.dataTable thead .sorting_asc_disabled, table.dataTable thead .sorting_desc_disabled { cursor: pointer; } table.dataTable thead .sorting { background: url('../images/sort_both.png') no-repeat center right; } table.dataTable thead .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } table.dataTable thead .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } table.dataTable thead .sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; } table.dataTable thead .sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; } table.dataTable thead > tr > th { padding-left: 18px; padding-right: 18px; } table.dataTable th:active { outline: none; } /* Scrolling */ div.dataTables_scrollHead table { margin-bottom: 0 !important; border-bottom-left-radius: 0; border-bottom-right-radius: 0; } div.dataTables_scrollHead table thead tr:last-child th:first-child, div.dataTables_scrollHead table thead tr:last-child td:first-child { border-bottom-left-radius: 0 !important; border-bottom-right-radius: 0 !important; } div.dataTables_scrollBody table { border-top: none; margin-top: 0 !important; margin-bottom: 0 !important; } div.dataTables_scrollBody tbody tr:first-child th, div.dataTables_scrollBody tbody tr:first-child td { border-top: none; } div.dataTables_scrollFoot table { margin-top: 0 !important; border-top: none; } /* Frustratingly the border-collapse:collapse used by Bootstrap makes the column width calculations when using scrolling impossible to align columns. We have to use separate */ table.table-bordered.dataTable { border-collapse: separate !important; } table.table-bordered thead th, table.table-bordered thead td { border-left-width: 0; border-top-width: 0; } table.table-bordered tbody th, table.table-bordered tbody td { border-left-width: 0; border-bottom-width: 0; } table.table-bordered th:last-child, table.table-bordered td:last-child { border-right-width: 0; } div.dataTables_scrollHead table.table-bordered { border-bottom-width: 0; } /* * TableTools styles */ .table tbody tr.active td, .table tbody tr.active th { background-color: #08C; color: white; } .table tbody tr.active:hover td, .table tbody tr.active:hover th { background-color: #0075b0 !important; } .table tbody tr.active a { color: white; } .table-striped tbody tr.active:nth-child(odd) td, .table-striped tbody tr.active:nth-child(odd) th { background-color: #017ebc; } table.DTTT_selectable tbody tr { cursor: pointer; } div.DTTT .btn { color: #333 !important; font-size: 12px; } div.DTTT .btn:hover { text-decoration: none !important; } ul.DTTT_dropdown.dropdown-menu { z-index: 2003; } ul.DTTT_dropdown.dropdown-menu a { color: #333 !important; /* needed only when demo_page.css is included */ } ul.DTTT_dropdown.dropdown-menu li { position: relative; } ul.DTTT_dropdown.dropdown-menu li:hover a { background-color: #0088cc; color: white !important; } div.DTTT_collection_background { z-index: 2002; } /* TableTools information display */ div.DTTT_print_info.modal { height: 150px; margin-top: -75px; text-align: center; } div.DTTT_print_info h6 { font-weight: normal; font-size: 28px; line-height: 28px; margin: 1em; } div.DTTT_print_info p { font-size: 14px; line-height: 20px; } div.dataTables_processing { position: absolute; top: 50%; left: 50%; width: 100%; height: 40px; margin-left: -50%; margin-top: -25px; padding-top: 20px; text-align: center; font-size: 1.2em; background-color: white; background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0))); background: -webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%); background: -moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%); background: -ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%); background: -o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%); background: linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%); } /* * FixedColumns styles */ div.DTFC_LeftHeadWrapper table, div.DTFC_LeftFootWrapper table, div.DTFC_RightHeadWrapper table, div.DTFC_RightFootWrapper table, table.DTFC_Cloned tr.even { background-color: white; margin-bottom: 0; } div.DTFC_RightHeadWrapper table , div.DTFC_LeftHeadWrapper table { margin-bottom: 0 !important; border-top-right-radius: 0 !important; border-bottom-left-radius: 0 !important; border-bottom-right-radius: 0 !important; } div.DTFC_RightHeadWrapper table thead tr:last-child th:first-child, div.DTFC_RightHeadWrapper table thead tr:last-child td:first-child, div.DTFC_LeftHeadWrapper table thead tr:last-child th:first-child, div.DTFC_LeftHeadWrapper table thead tr:last-child td:first-child { border-bottom-left-radius: 0 !important; border-bottom-right-radius: 0 !important; } div.DTFC_RightBodyWrapper table, div.DTFC_LeftBodyWrapper table { border-top: none; margin: 0 !important; } div.DTFC_RightBodyWrapper tbody tr:first-child th, div.DTFC_RightBodyWrapper tbody tr:first-child td, div.DTFC_LeftBodyWrapper tbody tr:first-child th, div.DTFC_LeftBodyWrapper tbody tr:first-child td { border-top: none; } div.DTFC_RightFootWrapper table, div.DTFC_LeftFootWrapper table { border-top: none; } /* * FixedHeader styles */ div.FixedHeader_Cloned table { margin: 0 !important }
{'content_hash': '9149103ef38ced5d3a71e2af5116f873', 'timestamp': '', 'source': 'github', 'line_count': 281, 'max_line_length': 218, 'avg_line_length': 24.91103202846975, 'alnum_prop': 0.6988571428571428, 'repo_name': 'habibun/craft', 'id': '0ffe5ca952557b4ce98e35de6df11234c3b3f8c3', 'size': '7000', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/assets/data-tables-edited/theme-able/bootstrap/dataTables.bootstrap.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '15982'}, {'name': 'ApacheConf', 'bytes': '3365'}, {'name': 'CSS', 'bytes': '890625'}, {'name': 'CoffeeScript', 'bytes': '80553'}, {'name': 'Go', 'bytes': '6713'}, {'name': 'HTML', 'bytes': '4357397'}, {'name': 'JavaScript', 'bytes': '5282919'}, {'name': 'Makefile', 'bytes': '397'}, {'name': 'PHP', 'bytes': '513287'}, {'name': 'Python', 'bytes': '5173'}, {'name': 'Shell', 'bytes': '7411'}]}
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.dumu.housego.MapHouseMainActivity" > <item android:id="@+id/action_settings" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_settings"/> </menu>
{'content_hash': '065f309a40918efd225a35fca22c67a9', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 64, 'avg_line_length': 33.0, 'alnum_prop': 0.6776859504132231, 'repo_name': 'rentianhua/tsf_android', 'id': '40313b9666678a3a23327d699e856c0cb4530bd7', 'size': '363', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'houseAd/HouseGo/res/menu/map_house_main.xml', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '3172144'}]}
@implementation PHSessionView #pragma mark - property - (UIButton*)button { if (!_button) { _button = [UIButton buttonWithType:UIButtonTypeCustom]; _button.frame = CGRectMake(0, 40, self.frame.size.width, kHeaderTitleHeight-40); _button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; [self addSubview:_button]; } return _button; } - (UIView*)containView { if (!_containView) { _containView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeaderTitleHeight + 20, self.frame.size.width, self.frame.size.height - kHeaderTitleHeight)]; [self addSubview:_containView]; } return _containView; } #pragma mark - clean up - (void)dealloc { [_button removeFromSuperview]; _button = nil; [_containView removeFromSuperview]; _containView = nil; } @end
{'content_hash': 'e2f2526f0c8367675025d790da558643', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 161, 'avg_line_length': 24.457142857142856, 'alnum_prop': 0.677570093457944, 'repo_name': 'LLaurenter/IdeaBox', 'id': 'bd1339631dde6ebb646c8a92f8a4bd10c251c150', 'size': '1028', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'IdeaBox/Source/PHSessionView.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '848'}, {'name': 'Objective-C', 'bytes': '303294'}]}
<!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_66-internal) on Tue Dec 08 09:28:00 GMT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.apache.jena.riot.lang (Apache Jena ARQ)</title> <meta name="date" content="2015-12-08"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../org/apache/jena/riot/lang/package-summary.html" target="classFrame">org.apache.jena.riot.lang</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="BlankNodeAllocator.html" title="interface in org.apache.jena.riot.lang" target="classFrame"><span class="interfaceName">BlankNodeAllocator</span></a></li> <li><a href="LangRIOT.html" title="interface in org.apache.jena.riot.lang" target="classFrame"><span class="interfaceName">LangRIOT</span></a></li> <li><a href="StreamRDFCounting.html" title="interface in org.apache.jena.riot.lang" target="classFrame"><span class="interfaceName">StreamRDFCounting</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="BlankNodeAllocatorFixedSeedHash.html" title="class in org.apache.jena.riot.lang" target="classFrame">BlankNodeAllocatorFixedSeedHash</a></li> <li><a href="BlankNodeAllocatorHash.html" title="class in org.apache.jena.riot.lang" target="classFrame">BlankNodeAllocatorHash</a></li> <li><a href="BlankNodeAllocatorLabel.html" title="class in org.apache.jena.riot.lang" target="classFrame">BlankNodeAllocatorLabel</a></li> <li><a href="BlankNodeAllocatorLabelEncoded.html" title="class in org.apache.jena.riot.lang" target="classFrame">BlankNodeAllocatorLabelEncoded</a></li> <li><a href="BlankNodeAllocatorTraditional.html" title="class in org.apache.jena.riot.lang" target="classFrame">BlankNodeAllocatorTraditional</a></li> <li><a href="CollectorStreamBase.html" title="class in org.apache.jena.riot.lang" target="classFrame">CollectorStreamBase</a></li> <li><a href="CollectorStreamQuads.html" title="class in org.apache.jena.riot.lang" target="classFrame">CollectorStreamQuads</a></li> <li><a href="CollectorStreamRDF.html" title="class in org.apache.jena.riot.lang" target="classFrame">CollectorStreamRDF</a></li> <li><a href="CollectorStreamTriples.html" title="class in org.apache.jena.riot.lang" target="classFrame">CollectorStreamTriples</a></li> <li><a href="JsonLDReader.html" title="class in org.apache.jena.riot.lang" target="classFrame">JsonLDReader</a></li> <li><a href="LabelToNode.html" title="class in org.apache.jena.riot.lang" target="classFrame">LabelToNode</a></li> <li><a href="LangBase.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangBase</a></li> <li><a href="LangCSV.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangCSV</a></li> <li><a href="LangEngine.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangEngine</a></li> <li><a href="LangNQuads.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangNQuads</a></li> <li><a href="LangNTriples.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangNTriples</a></li> <li><a href="LangNTuple.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangNTuple</a></li> <li><a href="LangRDFJSON.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangRDFJSON</a></li> <li><a href="LangRDFXML.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangRDFXML</a></li> <li><a href="LangTriG.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangTriG</a></li> <li><a href="LangTurtle.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangTurtle</a></li> <li><a href="LangTurtleBase.html" title="class in org.apache.jena.riot.lang" target="classFrame">LangTurtleBase</a></li> <li><a href="PipedQuadsStream.html" title="class in org.apache.jena.riot.lang" target="classFrame">PipedQuadsStream</a></li> <li><a href="PipedRDFIterator.html" title="class in org.apache.jena.riot.lang" target="classFrame">PipedRDFIterator</a></li> <li><a href="PipedRDFStream.html" title="class in org.apache.jena.riot.lang" target="classFrame">PipedRDFStream</a></li> <li><a href="PipedTriplesStream.html" title="class in org.apache.jena.riot.lang" target="classFrame">PipedTriplesStream</a></li> <li><a href="PipedTuplesStream.html" title="class in org.apache.jena.riot.lang" target="classFrame">PipedTuplesStream</a></li> <li><a href="ReaderRDFNULL.html" title="class in org.apache.jena.riot.lang" target="classFrame">ReaderRDFNULL</a></li> <li><a href="ReaderTriX.html" title="class in org.apache.jena.riot.lang" target="classFrame">ReaderTriX</a></li> <li><a href="RiotParsers.html" title="class in org.apache.jena.riot.lang" target="classFrame">RiotParsers</a></li> <li><a href="SinkQuadsToDataset.html" title="class in org.apache.jena.riot.lang" target="classFrame">SinkQuadsToDataset</a></li> <li><a href="SinkTriplesToGraph.html" title="class in org.apache.jena.riot.lang" target="classFrame">SinkTriplesToGraph</a></li> <li><a href="TriX.html" title="class in org.apache.jena.riot.lang" target="classFrame">TriX</a></li> </ul> </div> </body> </html>
{'content_hash': 'f38cebe518ca916fdc910798791ee26c', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 167, 'avg_line_length': 92.37288135593221, 'alnum_prop': 0.74, 'repo_name': 'manonsys/MVC', 'id': '2558cf909369fc1b26f2b8ce80157ed0cee90e21', 'size': '5450', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'libs/Jena/javadoc-arq/org/apache/jena/riot/lang/package-frame.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '419'}, {'name': 'Batchfile', 'bytes': '14683'}, {'name': 'C', 'bytes': '233384'}, {'name': 'C++', 'bytes': '5473'}, {'name': 'CSS', 'bytes': '672088'}, {'name': 'HTML', 'bytes': '88037916'}, {'name': 'Java', 'bytes': '197704'}, {'name': 'JavaScript', 'bytes': '3308500'}, {'name': 'Makefile', 'bytes': '1758'}, {'name': 'PHP', 'bytes': '1202703'}, {'name': 'Perl', 'bytes': '1542'}, {'name': 'Shell', 'bytes': '97135'}, {'name': 'Web Ontology Language', 'bytes': '7918'}]}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractOverrideCompletionProvider : AbstractMemberInsertingCompletionProvider { private readonly SyntaxAnnotation _annotation = new SyntaxAnnotation(); public AbstractOverrideCompletionProvider() { } public abstract SyntaxToken FindStartingToken(SyntaxTree tree, int position, CancellationToken cancellationToken); public abstract ISet<ISymbol> FilterOverrides(ISet<ISymbol> members, ITypeSymbol returnType); public abstract bool TryDetermineModifiers(SyntaxToken startToken, SourceText text, int startLine, out Accessibility seenAccessibility, out DeclarationModifiers modifiers); public override async Task ProvideCompletionsAsync(CompletionContext context) { var state = await ItemGetter.CreateAsync(this, context.Document, context.Position, context.DefaultItemSpan, context.CancellationToken).ConfigureAwait(false); var items = await state.GetItemsAsync().ConfigureAwait(false); if (items?.Any() == true) { context.IsExclusive = true; context.AddItems(items); } } protected override async Task<ISymbol> GenerateMemberAsync(ISymbol newOverriddenMember, INamedTypeSymbol newContainingType, Document newDocument, CompletionItem completionItem, CancellationToken cancellationToken) { // Figure out what to insert, and do it. Throw if we've somehow managed to get this far and can't. var syntaxFactory = newDocument.GetLanguageService<SyntaxGenerator>(); var codeGenService = newDocument.GetLanguageService<ICodeGenerationService>(); var itemModifiers = MemberInsertionCompletionItem.GetModifiers(completionItem); var modifiers = itemModifiers.WithIsUnsafe(itemModifiers.IsUnsafe | newOverriddenMember.IsUnsafe()); if (newOverriddenMember.Kind == SymbolKind.Method) { return await syntaxFactory.OverrideMethodAsync((IMethodSymbol)newOverriddenMember, modifiers, newContainingType, newDocument, cancellationToken).ConfigureAwait(false); } else if (newOverriddenMember.Kind == SymbolKind.Property) { return await syntaxFactory.OverridePropertyAsync((IPropertySymbol)newOverriddenMember, modifiers, newContainingType, newDocument, cancellationToken).ConfigureAwait(false); } else { return syntaxFactory.OverrideEvent((IEventSymbol)newOverriddenMember, modifiers, newContainingType); } } public abstract bool TryDetermineReturnType( SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken); public bool IsOverridable(ISymbol member, INamedTypeSymbol containingType) { if (member.IsAbstract || member.IsVirtual || member.IsOverride) { if (member.IsSealed) { return false; } if (!member.IsAccessibleWithin(containingType)) { return false; } switch (member.Kind) { case SymbolKind.Event: return true; case SymbolKind.Method: return ((IMethodSymbol)member).MethodKind == MethodKind.Ordinary; case SymbolKind.Property: return !((IPropertySymbol)member).IsWithEvents; } } return false; } protected bool IsOnStartLine(int position, SourceText text, int startLine) { return text.Lines.IndexOf(position) == startLine; } protected ITypeSymbol GetReturnType(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: return ((IEventSymbol)symbol).Type; case SymbolKind.Method: return ((IMethodSymbol)symbol).ReturnType; case SymbolKind.Property: return ((IPropertySymbol)symbol).Type; default: throw ExceptionUtilities.Unreachable; } } } }
{'content_hash': 'd273134a05795afc429d75fd59d55766', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 221, 'avg_line_length': 42.52100840336134, 'alnum_prop': 0.6343873517786561, 'repo_name': 'jaredpar/roslyn', 'id': '3d03710c51e68e0202805b40f9b4b84a22ee0042', 'size': '5062', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/Features/Core/Portable/Completion/Providers/AbstractOverrideCompletionProvider.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '15099'}, {'name': 'C#', 'bytes': '80732271'}, {'name': 'C++', 'bytes': '6311'}, {'name': 'F#', 'bytes': '421'}, {'name': 'Groovy', 'bytes': '7036'}, {'name': 'Makefile', 'bytes': '3606'}, {'name': 'PowerShell', 'bytes': '25894'}, {'name': 'Shell', 'bytes': '7453'}, {'name': 'Visual Basic', 'bytes': '61232818'}]}
<?php // Get the PHP helper library from twilio.com/docs/php/install require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library // Your Account Sid and Auth Token from twilio.com/user/account $accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $authToken = "your_auth_token"; $workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $workerSid = "WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $client = new TaskRouter_Services_Twilio($accountSid, $authToken, $workspaceSid); foreach($client->workspace->workers->get($workerSid)->reservations as $reservation) { echo $reservation->reservation_status; echo $reservation->worker_name; }
{'content_hash': 'c2c70e5cbdbcbe86ad9cafc9f4b7a2df', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 83, 'avg_line_length': 38.0, 'alnum_prop': 0.7770897832817337, 'repo_name': 'teoreteetik/api-snippets', 'id': 'd63330fb0bfb162d3162ed28206fb388cc68f74b', 'size': '646', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rest/taskrouter/worker-reservations/list-get-example1/example-1.4.x.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '643369'}, {'name': 'HTML', 'bytes': '335'}, {'name': 'Java', 'bytes': '943336'}, {'name': 'JavaScript', 'bytes': '539577'}, {'name': 'M', 'bytes': '117'}, {'name': 'Mathematica', 'bytes': '93'}, {'name': 'Objective-C', 'bytes': '46198'}, {'name': 'PHP', 'bytes': '538312'}, {'name': 'Python', 'bytes': '467248'}, {'name': 'Ruby', 'bytes': '470316'}, {'name': 'Shell', 'bytes': '1564'}, {'name': 'Swift', 'bytes': '36563'}]}
package com.intellij.openapi.components.impl.stores; import com.intellij.openapi.components.*; import com.intellij.openapi.options.StreamProvider; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.io.fs.IFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author mike */ public interface StateStorageManager { void addMacro(String macro, String expansion); @Nullable TrackingPathMacroSubstitutor getMacroSubstitutor(); @Nullable StateStorage getStateStorage(@NotNull Storage storageSpec) throws StateStorageException; @Nullable StateStorage getFileStateStorage(@NotNull String fileSpec); Collection<String> getStorageFileNames(); void clearStateStorage(@NotNull String file); @NotNull ExternalizationSession startExternalization(); @NotNull SaveSession startSave(@NotNull ExternalizationSession externalizationSession); void finishSave(@NotNull SaveSession saveSession); @Nullable StateStorage getOldStorage(Object component, String componentName, StateStorageOperation operation) throws StateStorageException; @Nullable String expandMacros(String file); @Deprecated void registerStreamProvider(@SuppressWarnings("deprecation") StreamProvider streamProvider, final RoamingType type); void setStreamProvider(@Nullable com.intellij.openapi.components.impl.stores.StreamProvider streamProvider); @Nullable com.intellij.openapi.components.impl.stores.StreamProvider getStreamProvider(); void reset(); interface ExternalizationSession { void setState(@NotNull Storage[] storageSpecs, @NotNull Object component, String componentName, @NotNull Object state) throws StateStorageException; void setStateInOldStorage(@NotNull Object component, @NotNull String componentName, @NotNull Object state) throws StateStorageException; } interface SaveSession { //returns set of component which were changed, null if changes are much more than just component state. @Nullable Set<String> analyzeExternalChanges(@NotNull Set<Pair<VirtualFile, StateStorage>> files); @NotNull List<IFile> getAllStorageFilesToSave() throws StateStorageException; @NotNull List<IFile> getAllStorageFiles(); void save() throws StateStorageException; } }
{'content_hash': 'd21277a2492a17ceae8fb6b972dd5af2', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 152, 'avg_line_length': 31.337662337662337, 'alnum_prop': 0.7985909656029838, 'repo_name': 'IllusionRom-deprecated/android_platform_tools_idea', 'id': '0e2828e988a3553c3b69569adc0c6019594e7f3a', 'size': '3013', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManager.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '177802'}, {'name': 'C#', 'bytes': '390'}, {'name': 'C++', 'bytes': '78894'}, {'name': 'CSS', 'bytes': '102018'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '1906667'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '128322265'}, {'name': 'JavaScript', 'bytes': '123045'}, {'name': 'Objective-C', 'bytes': '22558'}, {'name': 'Perl', 'bytes': '6549'}, {'name': 'Python', 'bytes': '17760420'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Shell', 'bytes': '76554'}, {'name': 'TeX', 'bytes': '60798'}, {'name': 'XSLT', 'bytes': '113531'}]}
package com.vaadin.v7.tests.components.grid; import java.util.List; import java.util.Random; import com.vaadin.server.VaadinRequest; import com.vaadin.tests.components.AbstractTestUIWithLog; import com.vaadin.ui.CheckBox; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.ui.Grid; import com.vaadin.v7.ui.Grid.Column; import com.vaadin.v7.ui.Grid.SelectionMode; import com.vaadin.v7.ui.renderers.HtmlRenderer; import com.vaadin.v7.ui.renderers.TextRenderer; @SuppressWarnings("serial") public class GridSwitchRenderers extends AbstractTestUIWithLog { private static final int MANUALLY_FORMATTED_COLUMNS = 1; private static final int COLUMNS = 3; private static final int ROWS = 1000; private static final String EXPANSION_COLUMN_ID = "Column 0"; private IndexedContainer ds; @Override protected void setup(VaadinRequest request) { ds = new IndexedContainer() { @Override public List<Object> getItemIds(int startIndex, int numberOfIds) { log("Requested items " + startIndex + " - " + (startIndex + numberOfIds)); return super.getItemIds(startIndex, numberOfIds); } }; { ds.addContainerProperty(EXPANSION_COLUMN_ID, String.class, ""); int col = MANUALLY_FORMATTED_COLUMNS; for (; col < COLUMNS; col++) { ds.addContainerProperty(getColumnProperty(col), String.class, ""); } } Random rand = new Random(); rand.setSeed(13334); for (int row = 0; row < ROWS; row++) { Item item = ds.addItem(Integer.valueOf(row)); fillRow("" + row, item); item.getItemProperty(getColumnProperty(1)).setReadOnly(true); } final Grid grid = new Grid(ds); grid.setWidth("100%"); grid.getColumn(EXPANSION_COLUMN_ID).setWidth(50); for (int col = MANUALLY_FORMATTED_COLUMNS; col < COLUMNS; col++) { grid.getColumn(getColumnProperty(col)).setWidth(300); grid.getColumn(getColumnProperty(col)) .setRenderer(new TextRenderer()); } grid.setSelectionMode(SelectionMode.NONE); addComponent(grid); final CheckBox changeRenderer = new CheckBox( "SetHtmlRenderer for Column 2", false); changeRenderer.addValueChangeListener(event -> { Column column = grid.getColumn(getColumnProperty(1)); if (changeRenderer.getValue()) { column.setRenderer(new HtmlRenderer()); } else { column.setRenderer(new TextRenderer()); } grid.markAsDirty(); }); addComponent(changeRenderer); } @SuppressWarnings("unchecked") private void fillRow(String content, Item item) { int col = MANUALLY_FORMATTED_COLUMNS; for (; col < COLUMNS; col++) { item.getItemProperty(getColumnProperty(col)) .setValue("<b>(" + content + ", " + col + ")</b>"); } } private static String getColumnProperty(int c) { return "Column " + c; } }
{'content_hash': '453d71b1dc604ab9c955f225e74c794f', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 77, 'avg_line_length': 33.9375, 'alnum_prop': 0.6089625537139349, 'repo_name': 'kironapublic/vaadin', 'id': 'd26f5400385b0242d36fdac90fed413f3a1fb7ee', 'size': '3258', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'uitest/src/main/java/com/vaadin/v7/tests/components/grid/GridSwitchRenderers.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '740138'}, {'name': 'HTML', 'bytes': '102292'}, {'name': 'Java', 'bytes': '23876126'}, {'name': 'JavaScript', 'bytes': '128039'}, {'name': 'Python', 'bytes': '34992'}, {'name': 'Shell', 'bytes': '14720'}, {'name': 'Smarty', 'bytes': '175'}]}
import _ from 'lodash' import React from 'react' import Label from 'src/elements/Label/Label' import LabelDetail from 'src/elements/Label/LabelDetail' import LabelGroup from 'src/elements/Label/LabelGroup' import * as common from 'test/specs/commonTests' import { SUI } from 'src/lib' import { sandbox } from 'test/utils' describe('Label', () => { common.isConformant(Label) common.hasSubComponents(Label, [LabelDetail, LabelGroup]) common.hasUIClassName(Label) common.rendersChildren(Label) common.implementsCreateMethod(Label) common.implementsIconProp(Label) common.implementsImageProp(Label) common.implementsShorthandProp(Label, { propKey: 'detail', ShorthandComponent: LabelDetail, mapValueToProps: val => ({ content: val }), }) common.propKeyAndValueToClassName(Label, 'attached', [ 'top', 'bottom', 'top right', 'top left', 'bottom left', 'bottom right', ]) common.propKeyOnlyToClassName(Label, 'active') common.propKeyOnlyToClassName(Label, 'basic') common.propKeyOnlyToClassName(Label, 'circular') common.propKeyOnlyToClassName(Label, 'empty') common.propKeyOnlyToClassName(Label, 'floating') common.propKeyOnlyToClassName(Label, 'horizontal') common.propKeyOnlyToClassName(Label, 'tag') common.propKeyOrValueAndKeyToClassName(Label, 'corner', ['left', 'right']) common.propKeyOrValueAndKeyToClassName(Label, 'ribbon', ['right']) common.propValueOnlyToClassName(Label, 'color', SUI.COLORS) common.propValueOnlyToClassName(Label, 'size', SUI.SIZES) it('is a div by default', () => { shallow(<Label />) .should.have.tagName('div') }) describe('removeIcon', () => { it('has no icon without onRemove', () => { shallow(<Label />) .should.not.have.descendants('Icon') }) it('has delete icon by default', () => { shallow(<Label onRemove={_.noop} />) .find('Icon') .should.have.prop('name', 'delete') }) it('uses passed removeIcon string', () => { shallow(<Label onRemove={_.noop} removeIcon='foo' />) .find('Icon') .should.have.prop('name', 'foo') }) it('uses passed removeIcon props', () => { shallow(<Label onRemove={_.noop} removeIcon={{ 'data-foo': true }} />) .find('Icon') .should.have.prop('data-foo', true) }) it('handles events on Label and Icon', () => { const event = { target: null } const iconSpy = sandbox.spy() const labelSpy = sandbox.spy() const iconProps = { 'data-foo': true, onClick: iconSpy } const labelProps = { onRemove: labelSpy, removeIcon: iconProps } mount(<Label {...labelProps} />) .find('Icon') .simulate('click', event) iconSpy.should.have.been.calledOnce() labelSpy.should.have.been.calledOnce() labelSpy.should.have.been.calledWithMatch(event, labelProps) }) }) describe('image', () => { it('adds an image class when true', () => { shallow(<Label image />) .should.have.className('image') }) it('does not add an Image when true', () => { shallow(<Label image />) .should.not.have.descendants('Image') }) }) describe('onClick', () => { it('omitted when not defined', () => { const click = () => shallow(<Label />).simulate('click') expect(click).to.not.throw() }) it('is called with (e) when clicked', () => { const spy = sandbox.spy() const event = { target: null } shallow(<Label onClick={spy} />) .simulate('click', event) spy.should.have.been.calledOnce() spy.should.have.been.calledWithMatch(event) }) }) describe('pointing', () => { it('adds an poiting class when true', () => { shallow(<Label pointing />) .should.have.className('pointing') }) it('does not add any poiting option class when true', () => { const options = ['above', 'below', 'left', 'right'] const wrapper = shallow(<Label pointing />) options.map(className => wrapper.should.not.have.className(className)) }) it('adds `above` as suffix', () => { shallow(<Label pointing='above' />) .should.have.className('pointing above') }) it('adds `below` as suffix', () => { shallow(<Label pointing='below' />) .should.have.className('pointing below') }) it('adds `left` as prefix', () => { shallow(<Label pointing='left' />) .should.have.className('left pointing') }) it('adds `right` as prefix', () => { shallow(<Label pointing='right' />) .should.have.className('right pointing') }) }) })
{'content_hash': '252fc908170de5fc20c752cd9ef8395a', 'timestamp': '', 'source': 'github', 'line_count': 153, 'max_line_length': 76, 'avg_line_length': 30.352941176470587, 'alnum_prop': 0.6192937123169682, 'repo_name': 'shengnian/shengnian-ui-react', 'id': '5ba6362535dc1d0817c2da58892447f8355fb715', 'size': '4644', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/specs/elements/Label/Label-test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1233'}, {'name': 'JavaScript', 'bytes': '1168671'}, {'name': 'TypeScript', 'bytes': '116'}]}
module Nessus class Client # @author Erran Carey <me@errancarey.com> module Policy # GET /policy/list def policy_list response = get '/policy/list' response['reply']['contents']['policies']['policy'] end # @!group Policy Auxiliary Methods # @return [Array<Array<String>>] an object containing a list of policies # and their policy IDs def policies policy_list.map do |policy| [policy['policyname'], policy['policyid']] end end # @return [String] looks up policy ID by policy name def policy_id_by_name(name) policy_list.find{|policy| policy['policyname'].eql? name}['policyid'] rescue nil end # @return [String] looks up policy name by policy ID def policy_name_by_id(id) policy_list.find{|policy| policy['policyid'].eql? id}['policyname'] rescue nil end #@!endgroup end end end
{'content_hash': 'e573a6808e37466e19aa71d2002e48f7', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 78, 'avg_line_length': 25.68421052631579, 'alnum_prop': 0.5911885245901639, 'repo_name': 'threatagent/nessus.rb', 'id': 'baef1ac82e8fae5a606b994c62ac1d6089256f81', 'size': '976', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/nessus/client/policy.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '19273'}]}
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0 // Template File Name: methodTemplate.tt // Build date: 2017-10-08 // C# generater version: 1.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // About // // Unoffical sample for the Reseller v1 API for C#. // This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client) // // API Description: Creates and manages your customers and their subscriptions. // API Documentation Link https://developers.google.com/google-apps/reseller/ // // Discovery Doc https://www.googleapis.com/discovery/v1/apis/Reseller/v1/rest // //------------------------------------------------------------------------------ // Installation // // This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client) // // NuGet package: // // Location: https://www.nuget.org/packages/Google.Apis.Reseller.v1/ // Install Command: PM> Install-Package Google.Apis.Reseller.v1 // //------------------------------------------------------------------------------ using Google.Apis.Reseller.v1; using Google.Apis.Reseller.v1.Data; using System; namespace GoogleSamplecSharpSample.Resellerv1.Methods { public static class CustomersSample { /// <summary> /// Get a customer account. /// Documentation https://developers.google.com/reseller/v1/reference/customers/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reseller service.</param> /// <param name="customerId">Either the customer's primary domain name or the customer's unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates.</param> /// <returns>CustomerResponse</returns> public static Customer Get(ResellerService service, string customerId) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (customerId == null) throw new ArgumentNullException(customerId); // Make the request. return service.Customers.Get(customerId).Execute(); } catch (Exception ex) { throw new Exception("Request Customers.Get failed.", ex); } } public class CustomersInsertOptionalParms { /// The customerAuthToken query string is required when creating a resold account that transfers a direct customer's subscription or transfers another reseller customer's subscription to your reseller management. This is a hexadecimal authentication token needed to complete the subscription transfer. For more information, see the administrator help center. public string CustomerAuthToken { get; set; } } /// <summary> /// Order a new customer's account. /// Documentation https://developers.google.com/reseller/v1/reference/customers/insert /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reseller service.</param> /// <param name="body">A valid Reseller v1 body.</param> /// <param name="optional">Optional paramaters.</param> /// <returns>CustomerResponse</returns> public static Customer Insert(ResellerService service, Customer body, CustomersInsertOptionalParms optional = null) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); // Building the initial request. var request = service.Customers.Insert(body); // Applying optional parameters to the request. request = (CustomersResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return request.Execute(); } catch (Exception ex) { throw new Exception("Request Customers.Insert failed.", ex); } } /// <summary> /// Update a customer account's settings. This method supports patch semantics. /// Documentation https://developers.google.com/reseller/v1/reference/customers/patch /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reseller service.</param> /// <param name="customerId">Either the customer's primary domain name or the customer's unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates.</param> /// <param name="body">A valid Reseller v1 body.</param> /// <returns>CustomerResponse</returns> public static Customer Patch(ResellerService service, string customerId, Customer body) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); if (customerId == null) throw new ArgumentNullException(customerId); // Make the request. return service.Customers.Patch(body, customerId).Execute(); } catch (Exception ex) { throw new Exception("Request Customers.Patch failed.", ex); } } /// <summary> /// Update a customer account's settings. /// Documentation https://developers.google.com/reseller/v1/reference/customers/update /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reseller service.</param> /// <param name="customerId">Either the customer's primary domain name or the customer's unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates.</param> /// <param name="body">A valid Reseller v1 body.</param> /// <returns>CustomerResponse</returns> public static Customer Update(ResellerService service, string customerId, Customer body) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); if (customerId == null) throw new ArgumentNullException(customerId); // Make the request. return service.Customers.Update(body, customerId).Execute(); } catch (Exception ex) { throw new Exception("Request Customers.Update failed.", ex); } } } public static class SampleHelpers { /// <summary> /// Using reflection to apply optional parameters to the request. /// /// If the optonal parameters are null then we will just return the request as is. /// </summary> /// <param name="request">The request. </param> /// <param name="optional">The optional parameters. </param> /// <returns></returns> public static object ApplyOptionalParms(object request, object optional) { if (optional == null) return request; System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties(); foreach (System.Reflection.PropertyInfo property in optionalProperties) { // Copy value from optional parms to the request. They should have the same names and datatypes. System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name); if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null piShared.SetValue(request, property.GetValue(optional, null), null); } return request; } } }
{'content_hash': '8ce4951b365809d0b2d24f24872fd3de', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 370, 'avg_line_length': 48.0, 'alnum_prop': 0.6068199685534591, 'repo_name': 'LindaLawton/Google-Dotnet-Samples', 'id': '5c0240be30420f8123a58cf100ba2d40b20718e0', 'size': '10178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/Enterprise Apps Reseller API/v1/CustomersSample.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package editlog import ( "github.com/aerogo/aero" ) const ( entriesFirstLoad = 120 entriesPerScroll = 40 ) // Full edit log. func Full(ctx aero.Context) error { return render(ctx, false) } // Compact edit log. func Compact(ctx aero.Context) error { return render(ctx, true) }
{'content_hash': 'fbcd587682a9be6e6e26ec417b566f0e', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 38, 'avg_line_length': 14.25, 'alnum_prop': 0.7087719298245614, 'repo_name': 'animenotifier/notify.moe', 'id': 'a8640f8e89c59d07d65a2d53a6e65d1957755004', 'size': '285', 'binary': False, 'copies': '1', 'ref': 'refs/heads/go', 'path': 'pages/editlog/editlog.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '776515'}, {'name': 'Makefile', 'bytes': '1951'}, {'name': 'Shell', 'bytes': '4485'}, {'name': 'TypeScript', 'bytes': '149263'}]}
<!doctype html> <!-- This file is generated by build.py. --> <title>input wide.jpg; overflow:visible; -o-object-fit:none; -o-object-position:center right</title> <link rel="stylesheet" href="../../support/reftests.css"> <link rel='match' href='visible_none_center_right-ref.html'> <style> #test > * { overflow:visible; -o-object-fit:none; -o-object-position:center right } </style> <div id="test"> <input type=image src="../../support/wide.jpg"> </div>
{'content_hash': 'aee85b5a2bd81455ca86c8a95be9c6a4', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 100, 'avg_line_length': 41.36363636363637, 'alnum_prop': 0.6857142857142857, 'repo_name': 'operasoftware/presto-testo', 'id': '6d96c7332d2845fe27abebc1f6fa1d707660457f', 'size': '455', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'css/image-fit/reftests/input-jpg-wide/visible_none_center_right.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '2312'}, {'name': 'ActionScript', 'bytes': '23470'}, {'name': 'AutoHotkey', 'bytes': '8832'}, {'name': 'Batchfile', 'bytes': '5001'}, {'name': 'C', 'bytes': '116512'}, {'name': 'C++', 'bytes': '279128'}, {'name': 'CSS', 'bytes': '208905'}, {'name': 'Groff', 'bytes': '674'}, {'name': 'HTML', 'bytes': '106576719'}, {'name': 'Haxe', 'bytes': '3874'}, {'name': 'Java', 'bytes': '185827'}, {'name': 'JavaScript', 'bytes': '22531460'}, {'name': 'Makefile', 'bytes': '13409'}, {'name': 'PHP', 'bytes': '524372'}, {'name': 'POV-Ray SDL', 'bytes': '6542'}, {'name': 'Perl', 'bytes': '321672'}, {'name': 'Python', 'bytes': '954636'}, {'name': 'Ruby', 'bytes': '1006850'}, {'name': 'Shell', 'bytes': '12140'}, {'name': 'Smarty', 'bytes': '1860'}, {'name': 'XSLT', 'bytes': '2567445'}]}
import uuid from tempest.api.volume import base from tempest.common.utils.data_utils import rand_name from tempest import exceptions from tempest.test import attr class ExtraSpecsNegativeTest(base.BaseVolumeAdminTest): _interface = 'json' @classmethod def setUpClass(cls): super(ExtraSpecsNegativeTest, cls).setUpClass() vol_type_name = rand_name('Volume-type-') cls.extra_specs = {"spec1": "val1"} resp, cls.volume_type = cls.client.create_volume_type(vol_type_name, extra_specs= cls.extra_specs) @classmethod def tearDownClass(cls): cls.client.delete_volume_type(cls.volume_type['id']) super(ExtraSpecsNegativeTest, cls).tearDownClass() @attr(type='gate') def test_update_no_body(self): # Should not update volume type extra specs with no body extra_spec = {"spec1": "val2"} self.assertRaises(exceptions.BadRequest, self.client.update_volume_type_extra_specs, self.volume_type['id'], extra_spec.keys()[0], None) @attr(type='gate') def test_update_nonexistent_extra_spec_id(self): # Should not update volume type extra specs with nonexistent id. extra_spec = {"spec1": "val2"} self.assertRaises(exceptions.BadRequest, self.client.update_volume_type_extra_specs, self.volume_type['id'], str(uuid.uuid4()), extra_spec) @attr(type='gate') def test_update_none_extra_spec_id(self): # Should not update volume type extra specs with none id. extra_spec = {"spec1": "val2"} self.assertRaises(exceptions.BadRequest, self.client.update_volume_type_extra_specs, self.volume_type['id'], None, extra_spec) @attr(type='gate') def test_update_multiple_extra_spec(self): # Should not update volume type extra specs with multiple specs as # body. extra_spec = {"spec1": "val2", 'spec2': 'val1'} self.assertRaises(exceptions.BadRequest, self.client.update_volume_type_extra_specs, self.volume_type['id'], extra_spec.keys()[0], extra_spec) @attr(type='gate') def test_create_nonexistent_type_id(self): # Should not create volume type extra spec for nonexistent volume # type id. extra_specs = {"spec2": "val1"} self.assertRaises(exceptions.NotFound, self.client.create_volume_type_extra_specs, str(uuid.uuid4()), extra_specs) @attr(type='gate') def test_create_none_body(self): # Should not create volume type extra spec for none POST body. self.assertRaises(exceptions.BadRequest, self.client.create_volume_type_extra_specs, self.volume_type['id'], None) @attr(type='gate') def test_create_invalid_body(self): # Should not create volume type extra spec for invalid POST body. self.assertRaises(exceptions.BadRequest, self.client.create_volume_type_extra_specs, self.volume_type['id'], ['invalid']) @attr(type='gate') def test_delete_nonexistent_volume_type_id(self): # Should not delete volume type extra spec for nonexistent # type id. extra_specs = {"spec1": "val1"} self.assertRaises(exceptions.NotFound, self.client.delete_volume_type_extra_specs, str(uuid.uuid4()), extra_specs.keys()[0]) @attr(type='gate') def test_list_nonexistent_volume_type_id(self): # Should not list volume type extra spec for nonexistent type id. self.assertRaises(exceptions.NotFound, self.client.list_volume_types_extra_specs, str(uuid.uuid4())) @attr(type='gate') def test_get_nonexistent_volume_type_id(self): # Should not get volume type extra spec for nonexistent type id. extra_specs = {"spec1": "val1"} self.assertRaises(exceptions.NotFound, self.client.get_volume_type_extra_specs, str(uuid.uuid4()), extra_specs.keys()[0]) @attr(type='gate') def test_get_nonexistent_extra_spec_id(self): # Should not get volume type extra spec for nonexistent extra spec # id. self.assertRaises(exceptions.NotFound, self.client.get_volume_type_extra_specs, self.volume_type['id'], str(uuid.uuid4())) class ExtraSpecsNegativeTestXML(ExtraSpecsNegativeTest): _interface = 'xml'
{'content_hash': 'f4f6c307c60648cf9e42ab323d460b14', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 78, 'avg_line_length': 41.86440677966102, 'alnum_prop': 0.5777327935222673, 'repo_name': 'citrix-openstack/build-tempest', 'id': 'e76c0ac52e51d8f82d19259765ed1d51d6aa9ffb', 'size': '5621', 'binary': False, 'copies': '3', 'ref': 'refs/heads/ctx-nova-network-smoke-latest', 'path': 'tempest/api/volume/admin/test_volume_types_extra_specs_negative.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '1486517'}, {'name': 'Shell', 'bytes': '5648'}]}
package com.google.cloud.dialogflow.v2beta1; import static com.google.cloud.dialogflow.v2beta1.EntityTypesClient.ListEntityTypesPagedResponse; import static com.google.cloud.dialogflow.v2beta1.EntityTypesClient.ListLocationsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; import com.google.api.gax.grpc.testing.MockServiceHelper; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.api.gax.rpc.StatusCode; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import com.google.protobuf.AbstractMessage; import com.google.protobuf.Any; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class EntityTypesClientTest { private static MockEntityTypes mockEntityTypes; private static MockLocations mockLocations; private static MockServiceHelper mockServiceHelper; private LocalChannelProvider channelProvider; private EntityTypesClient client; @BeforeClass public static void startStaticServer() { mockEntityTypes = new MockEntityTypes(); mockLocations = new MockLocations(); mockServiceHelper = new MockServiceHelper( UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockEntityTypes, mockLocations)); mockServiceHelper.start(); } @AfterClass public static void stopServer() { mockServiceHelper.stop(); } @Before public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); EntityTypesSettings settings = EntityTypesSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = EntityTypesClient.create(settings); } @After public void tearDown() throws Exception { client.close(); } @Test public void listEntityTypesTest() throws Exception { EntityType responsesElement = EntityType.newBuilder().build(); ListEntityTypesResponse expectedResponse = ListEntityTypesResponse.newBuilder() .setNextPageToken("") .addAllEntityTypes(Arrays.asList(responsesElement)) .build(); mockEntityTypes.addResponse(expectedResponse); AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); ListEntityTypesPagedResponse pagedListResponse = client.listEntityTypes(parent); List<EntityType> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getEntityTypesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListEntityTypesRequest actualRequest = ((ListEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listEntityTypesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); client.listEntityTypes(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listEntityTypesTest2() throws Exception { EntityType responsesElement = EntityType.newBuilder().build(); ListEntityTypesResponse expectedResponse = ListEntityTypesResponse.newBuilder() .setNextPageToken("") .addAllEntityTypes(Arrays.asList(responsesElement)) .build(); mockEntityTypes.addResponse(expectedResponse); String parent = "parent-995424086"; ListEntityTypesPagedResponse pagedListResponse = client.listEntityTypes(parent); List<EntityType> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getEntityTypesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListEntityTypesRequest actualRequest = ((ListEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listEntityTypesExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; client.listEntityTypes(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listEntityTypesTest3() throws Exception { EntityType responsesElement = EntityType.newBuilder().build(); ListEntityTypesResponse expectedResponse = ListEntityTypesResponse.newBuilder() .setNextPageToken("") .addAllEntityTypes(Arrays.asList(responsesElement)) .build(); mockEntityTypes.addResponse(expectedResponse); AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); String languageCode = "languageCode-2092349083"; ListEntityTypesPagedResponse pagedListResponse = client.listEntityTypes(parent, languageCode); List<EntityType> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getEntityTypesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListEntityTypesRequest actualRequest = ((ListEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listEntityTypesExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); String languageCode = "languageCode-2092349083"; client.listEntityTypes(parent, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listEntityTypesTest4() throws Exception { EntityType responsesElement = EntityType.newBuilder().build(); ListEntityTypesResponse expectedResponse = ListEntityTypesResponse.newBuilder() .setNextPageToken("") .addAllEntityTypes(Arrays.asList(responsesElement)) .build(); mockEntityTypes.addResponse(expectedResponse); String parent = "parent-995424086"; String languageCode = "languageCode-2092349083"; ListEntityTypesPagedResponse pagedListResponse = client.listEntityTypes(parent, languageCode); List<EntityType> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getEntityTypesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListEntityTypesRequest actualRequest = ((ListEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listEntityTypesExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; String languageCode = "languageCode-2092349083"; client.listEntityTypes(parent, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getEntityTypeTest() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); EntityType actualResponse = client.getEntityType(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetEntityTypeRequest actualRequest = ((GetEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getEntityTypeExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); client.getEntityType(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getEntityTypeTest2() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); String name = "name3373707"; EntityType actualResponse = client.getEntityType(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetEntityTypeRequest actualRequest = ((GetEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getEntityTypeExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String name = "name3373707"; client.getEntityType(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getEntityTypeTest3() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); String languageCode = "languageCode-2092349083"; EntityType actualResponse = client.getEntityType(name, languageCode); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetEntityTypeRequest actualRequest = ((GetEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getEntityTypeExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); String languageCode = "languageCode-2092349083"; client.getEntityType(name, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getEntityTypeTest4() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); String name = "name3373707"; String languageCode = "languageCode-2092349083"; EntityType actualResponse = client.getEntityType(name, languageCode); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetEntityTypeRequest actualRequest = ((GetEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getEntityTypeExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String name = "name3373707"; String languageCode = "languageCode-2092349083"; client.getEntityType(name, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createEntityTypeTest() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); EntityType entityType = EntityType.newBuilder().build(); EntityType actualResponse = client.createEntityType(parent, entityType); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateEntityTypeRequest actualRequest = ((CreateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createEntityTypeExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); EntityType entityType = EntityType.newBuilder().build(); client.createEntityType(parent, entityType); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createEntityTypeTest2() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); String parent = "parent-995424086"; EntityType entityType = EntityType.newBuilder().build(); EntityType actualResponse = client.createEntityType(parent, entityType); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateEntityTypeRequest actualRequest = ((CreateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createEntityTypeExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; EntityType entityType = EntityType.newBuilder().build(); client.createEntityType(parent, entityType); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createEntityTypeTest3() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; EntityType actualResponse = client.createEntityType(parent, entityType, languageCode); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateEntityTypeRequest actualRequest = ((CreateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createEntityTypeExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; client.createEntityType(parent, entityType, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createEntityTypeTest4() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); String parent = "parent-995424086"; EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; EntityType actualResponse = client.createEntityType(parent, entityType, languageCode); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateEntityTypeRequest actualRequest = ((CreateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createEntityTypeExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; client.createEntityType(parent, entityType, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateEntityTypeTest() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); EntityType entityType = EntityType.newBuilder().build(); EntityType actualResponse = client.updateEntityType(entityType); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateEntityTypeRequest actualRequest = ((UpdateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateEntityTypeExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityType entityType = EntityType.newBuilder().build(); client.updateEntityType(entityType); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateEntityTypeTest2() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; EntityType actualResponse = client.updateEntityType(entityType, languageCode); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateEntityTypeRequest actualRequest = ((UpdateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateEntityTypeExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; client.updateEntityType(entityType, languageCode); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateEntityTypeTest3() throws Exception { EntityType expectedResponse = EntityType.newBuilder() .setName( EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]").toString()) .setDisplayName("displayName1714148973") .addAllEntities(new ArrayList<EntityType.Entity>()) .setEnableFuzzyExtraction(true) .build(); mockEntityTypes.addResponse(expectedResponse); EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; FieldMask updateMask = FieldMask.newBuilder().build(); EntityType actualResponse = client.updateEntityType(entityType, languageCode, updateMask); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateEntityTypeRequest actualRequest = ((UpdateEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(entityType, actualRequest.getEntityType()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateEntityTypeExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityType entityType = EntityType.newBuilder().build(); String languageCode = "languageCode-2092349083"; FieldMask updateMask = FieldMask.newBuilder().build(); client.updateEntityType(entityType, languageCode, updateMask); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void deleteEntityTypeTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); mockEntityTypes.addResponse(expectedResponse); EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); client.deleteEntityType(name); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteEntityTypeRequest actualRequest = ((DeleteEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteEntityTypeExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName name = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); client.deleteEntityType(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void deleteEntityTypeTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); mockEntityTypes.addResponse(expectedResponse); String name = "name3373707"; client.deleteEntityType(name); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteEntityTypeRequest actualRequest = ((DeleteEntityTypeRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteEntityTypeExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String name = "name3373707"; client.deleteEntityType(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void batchUpdateEntityTypesTest() throws Exception { BatchUpdateEntityTypesResponse expectedResponse = BatchUpdateEntityTypesResponse.newBuilder() .addAllEntityTypes(new ArrayList<EntityType>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("batchUpdateEntityTypesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); BatchUpdateEntityTypesRequest request = BatchUpdateEntityTypesRequest.newBuilder() .setParent(AgentName.ofProjectAgentName("[PROJECT]").toString()) .setLanguageCode("languageCode-2092349083") .setUpdateMask(FieldMask.newBuilder().build()) .build(); BatchUpdateEntityTypesResponse actualResponse = client.batchUpdateEntityTypesAsync(request).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchUpdateEntityTypesRequest actualRequest = ((BatchUpdateEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(request.getParent(), actualRequest.getParent()); Assert.assertEquals(request.getEntityTypeBatchUri(), actualRequest.getEntityTypeBatchUri()); Assert.assertEquals( request.getEntityTypeBatchInline(), actualRequest.getEntityTypeBatchInline()); Assert.assertEquals(request.getLanguageCode(), actualRequest.getLanguageCode()); Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchUpdateEntityTypesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { BatchUpdateEntityTypesRequest request = BatchUpdateEntityTypesRequest.newBuilder() .setParent(AgentName.ofProjectAgentName("[PROJECT]").toString()) .setLanguageCode("languageCode-2092349083") .setUpdateMask(FieldMask.newBuilder().build()) .build(); client.batchUpdateEntityTypesAsync(request).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntityTypesTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntityTypesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); List<String> entityTypeNames = new ArrayList<>(); client.batchDeleteEntityTypesAsync(parent, entityTypeNames).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntityTypesRequest actualRequest = ((BatchDeleteEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entityTypeNames, actualRequest.getEntityTypeNamesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntityTypesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { AgentName parent = AgentName.ofProjectAgentName("[PROJECT]"); List<String> entityTypeNames = new ArrayList<>(); client.batchDeleteEntityTypesAsync(parent, entityTypeNames).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntityTypesTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntityTypesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<String> entityTypeNames = new ArrayList<>(); client.batchDeleteEntityTypesAsync(parent, entityTypeNames).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntityTypesRequest actualRequest = ((BatchDeleteEntityTypesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entityTypeNames, actualRequest.getEntityTypeNamesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntityTypesExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<String> entityTypeNames = new ArrayList<>(); client.batchDeleteEntityTypesAsync(parent, entityTypeNames).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchCreateEntitiesTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchCreateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); client.batchCreateEntitiesAsync(parent, entities).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchCreateEntitiesRequest actualRequest = ((BatchCreateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchCreateEntitiesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); client.batchCreateEntitiesAsync(parent, entities).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchCreateEntitiesTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchCreateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); client.batchCreateEntitiesAsync(parent, entities).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchCreateEntitiesRequest actualRequest = ((BatchCreateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchCreateEntitiesExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); client.batchCreateEntitiesAsync(parent, entities).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchCreateEntitiesTest3() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchCreateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchCreateEntitiesAsync(parent, entities, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchCreateEntitiesRequest actualRequest = ((BatchCreateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchCreateEntitiesExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchCreateEntitiesAsync(parent, entities, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchCreateEntitiesTest4() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchCreateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchCreateEntitiesAsync(parent, entities, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchCreateEntitiesRequest actualRequest = ((BatchCreateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchCreateEntitiesExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchCreateEntitiesAsync(parent, entities, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchUpdateEntitiesTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchUpdateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); client.batchUpdateEntitiesAsync(parent, entities).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchUpdateEntitiesRequest actualRequest = ((BatchUpdateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchUpdateEntitiesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); client.batchUpdateEntitiesAsync(parent, entities).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchUpdateEntitiesTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchUpdateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); client.batchUpdateEntitiesAsync(parent, entities).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchUpdateEntitiesRequest actualRequest = ((BatchUpdateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchUpdateEntitiesExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); client.batchUpdateEntitiesAsync(parent, entities).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchUpdateEntitiesTest3() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchUpdateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchUpdateEntitiesAsync(parent, entities, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchUpdateEntitiesRequest actualRequest = ((BatchUpdateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchUpdateEntitiesExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchUpdateEntitiesAsync(parent, entities, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchUpdateEntitiesTest4() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchUpdateEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchUpdateEntitiesAsync(parent, entities, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchUpdateEntitiesRequest actualRequest = ((BatchUpdateEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entities, actualRequest.getEntitiesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchUpdateEntitiesExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<EntityType.Entity> entities = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchUpdateEntitiesAsync(parent, entities, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntitiesTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<String> entityValues = new ArrayList<>(); client.batchDeleteEntitiesAsync(parent, entityValues).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntitiesRequest actualRequest = ((BatchDeleteEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entityValues, actualRequest.getEntityValuesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntitiesExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<String> entityValues = new ArrayList<>(); client.batchDeleteEntitiesAsync(parent, entityValues).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntitiesTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<String> entityValues = new ArrayList<>(); client.batchDeleteEntitiesAsync(parent, entityValues).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntitiesRequest actualRequest = ((BatchDeleteEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entityValues, actualRequest.getEntityValuesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntitiesExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<String> entityValues = new ArrayList<>(); client.batchDeleteEntitiesAsync(parent, entityValues).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntitiesTest3() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<String> entityValues = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchDeleteEntitiesAsync(parent, entityValues, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntitiesRequest actualRequest = ((BatchDeleteEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(entityValues, actualRequest.getEntityValuesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntitiesExceptionTest3() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { EntityTypeName parent = EntityTypeName.ofProjectEntityTypeName("[PROJECT]", "[ENTITY_TYPE]"); List<String> entityValues = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchDeleteEntitiesAsync(parent, entityValues, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void batchDeleteEntitiesTest4() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("batchDeleteEntitiesTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockEntityTypes.addResponse(resultOperation); String parent = "parent-995424086"; List<String> entityValues = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchDeleteEntitiesAsync(parent, entityValues, languageCode).get(); List<AbstractMessage> actualRequests = mockEntityTypes.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchDeleteEntitiesRequest actualRequest = ((BatchDeleteEntitiesRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(entityValues, actualRequest.getEntityValuesList()); Assert.assertEquals(languageCode, actualRequest.getLanguageCode()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchDeleteEntitiesExceptionTest4() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockEntityTypes.addException(exception); try { String parent = "parent-995424086"; List<String> entityValues = new ArrayList<>(); String languageCode = "languageCode-2092349083"; client.batchDeleteEntitiesAsync(parent, entityValues, languageCode).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void listLocationsTest() throws Exception { Location responsesElement = Location.newBuilder().build(); ListLocationsResponse expectedResponse = ListLocationsResponse.newBuilder() .setNextPageToken("") .addAllLocations(Arrays.asList(responsesElement)) .build(); mockLocations.addResponse(expectedResponse); ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("name3373707") .setFilter("filter-1274492040") .setPageSize(883849137) .setPageToken("pageToken873572522") .build(); ListLocationsPagedResponse pagedListResponse = client.listLocations(request); List<Location> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getLocationsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockLocations.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListLocationsRequest actualRequest = ((ListLocationsRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertEquals(request.getFilter(), actualRequest.getFilter()); Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize()); Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listLocationsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockLocations.addException(exception); try { ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("name3373707") .setFilter("filter-1274492040") .setPageSize(883849137) .setPageToken("pageToken873572522") .build(); client.listLocations(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getLocationTest() throws Exception { Location expectedResponse = Location.newBuilder() .setName("name3373707") .setLocationId("locationId1541836720") .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setMetadata(Any.newBuilder().build()) .build(); mockLocations.addResponse(expectedResponse); GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); Location actualResponse = client.getLocation(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockLocations.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetLocationRequest actualRequest = ((GetLocationRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getLocationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockLocations.addException(exception); try { GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); client.getLocation(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
{'content_hash': '6d15e627b4223a4c304ccd71954e2582', 'timestamp': '', 'source': 'github', 'line_count': 1641, 'max_line_length': 100, 'avg_line_length': 41.17123705057892, 'alnum_prop': 0.728516029720849, 'repo_name': 'googleapis/google-cloud-java', 'id': '14daa00714a0dd4c7e550ab111dce4c57d0b2984', 'size': '68157', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'java-dialogflow/google-cloud-dialogflow/src/test/java/com/google/cloud/dialogflow/v2beta1/EntityTypesClientTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2614'}, {'name': 'HCL', 'bytes': '28592'}, {'name': 'Java', 'bytes': '826434232'}, {'name': 'Jinja', 'bytes': '2292'}, {'name': 'Python', 'bytes': '200408'}, {'name': 'Shell', 'bytes': '97954'}]}
/*global jQuery */ (function ($) { var foaf = $.uri("http://xmlns.com/foaf/0.1/"), work = $.rdf.resource('<' + $.uri.base() + '>'), foafPersonClass = $.rdf.resource('<' + foaf + 'Person>'), foafKnowsProp = $.rdf.resource('<' + foaf + 'knows>'), foafWeblogProp = $.rdf.resource('<' + foaf + 'weblog>'), person1Bnode = $.rdf.blank("[]"), meRegex = /(?:^|\s)me(?:\s|$)/, gleaner = function (options) { var rel = this.attr('rel'), href = this.attr('href'), m = meRegex.exec(rel), person2Bnode = $.rdf.blank("[]"); if (href !== undefined && m === null) { if (options && options.about !== undefined) { if (options.about === null) { return true; } else { return options.about === $.uri.base() || options.about === href; } } else if (options && options.type !== undefined) { if (options.type === null) { return true; } else { return options.type === foafPersonClass.uri; } } else { return [ $.rdf.triple(person1Bnode, $.rdf.type, foafPersonClass), $.rdf.triple(person1Bnode, foafWeblogProp, work), $.rdf.triple(person1Bnode, foafKnowsProp, person2Bnode), $.rdf.triple(person2Bnode, foafWeblogProp, '<' + href + '>'), $.rdf.triple(person2Bnode, $.rdf.type, foafPersonClass) ]; } } return options === undefined ? [] : false; }; $.fn.xfn = function (relationship) { //relationship e.g. 'friend' 'met' etc if (relationship === undefined) { var triples = $.map($(this), function (elem) { return gleaner.call($(elem)); }); return $.rdf({ triples: triples }); } else { $(this) .filter('[href]') // only add to elements with href attributes .each(function () { var elem = $(this), rel = elem.attr('rel'); if (rel === undefined || rel === '') { elem.attr('rel', relationship); } else if (!rel.toLowerCase().match(relationship.toLowerCase())) { elem.attr('rel', rel + ' ' + relationship); } }); return this; } }; $.rdf.gleaners.push(gleaner); })(jQuery);
{'content_hash': '8459bbac5e17a7e53de6420af2d08a83', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 85, 'avg_line_length': 33.89473684210526, 'alnum_prop': 0.44759316770186336, 'repo_name': 'linked-usdl/usdl-editor', 'id': '0ca42e56bcfea44ed7f10c31c873d84657b49c2c', 'size': '2830', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rdfquery/jquery.xfn.foaf.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23642'}, {'name': 'JavaScript', 'bytes': '589210'}]}
module InJs { export module DomFactory { export function div(): JQuery { return $('<div/>'); } export function span(): JQuery { return $('<span/>'); } export function checkbox(): JQuery { return $('<input type="checkbox"/>'); } export function ul(): JQuery { return $('<ul/>'); } export function li(): JQuery { return $('<li/>'); } export function button(): JQuery { return $('<input type="button"/>'); } export function select(): JQuery { return $('<select/>'); } export function textBox(): JQuery { return $('<input type="text"/>'); } export function img(): JQuery { return $('<img/>'); } export function iframe(): JQuery { return $('<iframe/>'); } } }
{'content_hash': '8024268af0d9192b125eedc45f9dfa92', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 49, 'avg_line_length': 20.73913043478261, 'alnum_prop': 0.429769392033543, 'repo_name': 'cswaroop/PowerBI-visuals', 'id': 'ec5a708225d84ed3f4feb64ae1f5a03e68475b72', 'size': '2176', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/Clients/JsCommon/Controls/DomFactory.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '398'}, {'name': 'C#', 'bytes': '1542'}, {'name': 'CSS', 'bytes': '50922'}, {'name': 'HTML', 'bytes': '913'}, {'name': 'JavaScript', 'bytes': '929076'}, {'name': 'TypeScript', 'bytes': '5231102'}]}
({ tagName: 'span', fieldTag: 'a', /** * Where is my server located at */ ioServer: 'http://localhost:5000', ioSocket: undefined, registered: false, users: [], count: 0, initialize: function(options) { this._super('initialize', [options]); if(app.api.isAuthenticated()) { this.ioSocket = io.connect(this.ioServer); this.ioSocket.on('registered', _.bind(function() { this.registered = true; }, this)); this.ioSocket.on('lookers', _.bind(function(room, data) { this.count = _.size(data); this.users = data; this.render(); }, this)); app.on('app:view:change', function(name, attributes) { var page = { 'module': attributes.module, 'action': name, 'id': attributes.modelId } if (this.registered) { this.ioSocket.emit('look-at-page', page); } else { var user = { id: app.user.get('id'), name: app.user.get('full_name'), image: app.user.get('picture') }; this.ioSocket.emit('register', user, page); } }, this); } else { // we are not rendered, so listen to before('render') and stop it this.before('render', function() { return false; }, null, this); } }, _dispose: function() { app.off('app:view:change', null, this); if(this.ioSocket) { this.ioSocket.disconnect(); this.ioSocket = undefined; } } })
{'content_hash': '17edfcb94941532bf524503295c2e723', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 77, 'avg_line_length': 28.276923076923076, 'alnum_prop': 0.43743199129488575, 'repo_name': 'jwhitcraft/whos-looking', 'id': '8b3f9add507da7d95ebbb1fdf37696e6776500cd', 'size': '1838', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sugarcrm_client/clients/base/views/looking/looking.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '11653'}, {'name': 'PHP', 'bytes': '3208'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '072ad1db211287050834d933c26faee8', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '90535f0ad164e81ac7dd86e0e4457716410d1cec', 'size': '187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Eugenia/Eugenia francavilleana/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
.class public LFormat52c; .super Ljava/lang/Object; .source "Format52c.smali" .method public constructor <init>()V .registers 1 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method .method public test-instance-of-jumbo-success()V .registers 258 .annotation runtime Lorg/junit/Test; .end annotation const-string v0, "test" new-instance v1, LStringWrapper; invoke-direct {v1, v0}, LStringWrapper;-><init>(Ljava/lang/String;)V move-object/16 v256, v1 instance-of/jumbo v257, v256, Ljava/lang/Object; const v0, 1 move/16 v256, v0 invoke-static/range {v256 .. v257}, LAssert;->assertEquals(II)V return-void .end method .method public test-instance-of-jumbo-failure()V .registers 258 .annotation runtime Lorg/junit/Test; .end annotation const-string v0, "test" new-instance v1, LStringWrapper; invoke-direct {v1, v0}, LStringWrapper;-><init>(Ljava/lang/String;)V move-object/16 v256, v1 instance-of/jumbo v257, v256, Lzzz99999; const v0, 0 move/16 v256, v0 invoke-static/range {v256 .. v257}, LAssert;->assertEquals(II)V return-void .end method .method public test-new-array-jumbo()V .registers 258 .annotation runtime Lorg/junit/Test; .end annotation const v0, 1 move/16 v256, v0 new-array/jumbo v257, v256, [Lzzz99999; move-object/16 v1, v257 array-length v2, v1 invoke-static {v0, v2}, LAssert;->assertEquals(II)V return-void .end method
{'content_hash': 'e7cf8ac8cf0f3634c3ac37c04c65ecc7', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 72, 'avg_line_length': 22.08695652173913, 'alnum_prop': 0.676509186351706, 'repo_name': 'indashnet/InDashNet.Open.UN2000', 'id': 'b407cd3f1744c09000fabae843707edb6ddb434b', 'size': '3027', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'android/external/smali/smali-integration-tests/src/test/smali/jumbo-type-tests/Format52c.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/* tslint:disable */ /* eslint-disable */ import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type UserInformationQueryVariables = {}; export type UserInformationQueryResponse = { readonly me: { readonly " $fragmentRefs": FragmentRefs<"UserInformation_me">; } | null; }; export type UserInformationQueryRawResponse = { readonly me: ({ readonly email: string | null; readonly name: string | null; readonly paddleNumber: string | null; readonly phone: string | null; readonly internalID: string; readonly id: string | null; }) | null; }; export type UserInformationQuery = { readonly response: UserInformationQueryResponse; readonly variables: UserInformationQueryVariables; readonly rawResponse: UserInformationQueryRawResponse; }; /* query UserInformationQuery { me { ...UserInformation_me id } } fragment UserInformation_me on Me { email name paddleNumber phone internalID } */ const node: ConcreteRequest = { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "UserInformationQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "UserInformation_me" } ], "storageKey": null } ], "type": "Query" }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "UserInformationQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "email", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "paddleNumber", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "phone", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null } ], "storageKey": null } ] }, "params": { "id": null, "metadata": {}, "name": "UserInformationQuery", "operationKind": "query", "text": "query UserInformationQuery {\n me {\n ...UserInformation_me\n id\n }\n}\n\nfragment UserInformation_me on Me {\n email\n name\n paddleNumber\n phone\n internalID\n}\n" } }; (node as any).hash = '77e70fe6f059d61db962f2645846adb8'; export default node;
{'content_hash': 'd4a5fb09c7c8deb1d74c11a2f124c02a', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 193, 'avg_line_length': 24.097902097902097, 'alnum_prop': 0.5023215322112594, 'repo_name': 'artsy/force-public', 'id': '6045073981d155898a773b8c58b3044f2780513e', 'size': '3446', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/v2/__generated__/UserInformationQuery.graphql.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '333575'}, {'name': 'CoffeeScript', 'bytes': '2034168'}, {'name': 'HTML', 'bytes': '425084'}, {'name': 'JavaScript', 'bytes': '17599'}, {'name': 'Makefile', 'bytes': '3116'}]}
from setuptools import find_packages, setup project = "microcosm-pubsub" version = "2.28.0" setup( name=project, version=version, description="PubSub with SNS/SQS", author="Globality Engineering", author_email="engineering@globality.com", url="https://github.com/globality-corp/microcosm-pubsub", packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), include_package_data=True, zip_safe=False, python_requires=">=3.6", install_requires=[ "boto3>=1.5.8", "dataclasses;python_version<'3.7'", "marshmallow>=3.0.0", "microcosm>=3.0.0", "microcosm-caching>=0.2.0", "microcosm-daemon>=1.2.0", "microcosm-logging>=1.3.0", ], extras_require={ "metrics": "microcosm-metrics>=2.5.0", "sentry": "sentry-sdk>=0.14.4", "test": [ "pytest", "pytest-cov", "sentry-sdk>=0.14.4", "PyHamcrest", ], "lint": [ "flake8", ] }, setup_requires=[ "nose>=1.3.6", ], dependency_links=[ ], entry_points={ "console_scripts": [ "publish-naive = microcosm_pubsub.main:make_naive_message", "pubsub = microcosm_pubsub.main:main", ], "microcosm.factories": [ "pubsub_message_schema_registry = microcosm_pubsub.registry:configure_schema_registry", "pubsub_lifecycle_change = microcosm_pubsub.conventions:LifecycleChange", "pubsub_send_batch_metrics = microcosm_pubsub.metrics:PubSubSendBatchMetrics", "pubsub_send_metrics = microcosm_pubsub.metrics:PubSubSendMetrics", "pubsub_producer_metrics = microcosm_pubsub.metrics:PubSubProducerMetrics", "sqs_message_context = microcosm_pubsub.context:SQSMessageContext", "sqs_consumer = microcosm_pubsub.consumer:configure_sqs_consumer", "sqs_envelope = microcosm_pubsub.envelope:configure_sqs_envelope", "sqs_message_dispatcher = microcosm_pubsub.dispatcher:SQSMessageDispatcher", "sqs_message_handler_registry = microcosm_pubsub.registry:configure_handler_registry", "sns_producer = microcosm_pubsub.producer:configure_sns_producer", "sns_topic_arns = microcosm_pubsub.producer:configure_sns_topic_arns", "sentry_logging_pubsub = microcosm_pubsub.sentry:configure_sentry_pubsub", ], }, )
{'content_hash': '10bfa1ee93ac63c3b80993f9733ca1c6', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 99, 'avg_line_length': 37.134328358208954, 'alnum_prop': 0.6097266881028939, 'repo_name': 'globality-corp/microcosm-pubsub', 'id': '1306f4aa69c4a0c3b48bd2ef55c184323e52219a', 'size': '2510', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'setup.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '3212'}, {'name': 'Python', 'bytes': '242990'}, {'name': 'Shell', 'bytes': '1520'}]}
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>etree</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <h1 class="toc">Module etree</h1> <hr /> <h2 class="toc">Classes</h2> <div class="private"> <a target="mainFrame" href="lxml.etree.AncestorsIterator-class.html" >AncestorsIterator</a><br /> </div> <a target="mainFrame" href="lxml.etree.AttributeBasedElementClassLookup-class.html" >AttributeBasedElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.C14NError-class.html" >C14NError</a><br /> <a target="mainFrame" href="lxml.etree.CDATA-class.html" >CDATA</a><br /> <a target="mainFrame" href="lxml.etree.CommentBase-class.html" >CommentBase</a><br /> <a target="mainFrame" href="lxml.etree.CustomElementClassLookup-class.html" >CustomElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.DTD-class.html" >DTD</a><br /> <a target="mainFrame" href="lxml.etree.DTDError-class.html" >DTDError</a><br /> <a target="mainFrame" href="lxml.etree.DTDParseError-class.html" >DTDParseError</a><br /> <a target="mainFrame" href="lxml.etree.DTDValidateError-class.html" >DTDValidateError</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.DocInfo-class.html" >DocInfo</a><br /> </div> <a target="mainFrame" href="lxml.etree.DocumentInvalid-class.html" >DocumentInvalid</a><br /> <a target="mainFrame" href="lxml.etree.ETCompatXMLParser-class.html" >ETCompatXMLParser</a><br /> <a target="mainFrame" href="lxml.etree.ETXPath-class.html" >ETXPath</a><br /> <a target="mainFrame" href="lxml.etree.ElementBase-class.html" >ElementBase</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.ElementChildIterator-class.html" >ElementChildIterator</a><br /> </div> <a target="mainFrame" href="lxml.etree.ElementClassLookup-class.html" >ElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.ElementDefaultClassLookup-class.html" >ElementDefaultClassLookup</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.ElementDepthFirstIterator-class.html" >ElementDepthFirstIterator</a><br /> </div> <a target="mainFrame" href="lxml.etree.ElementNamespaceClassLookup-class.html" >ElementNamespaceClassLookup</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.ElementTextIterator-class.html" >ElementTextIterator</a><br /> </div> <a target="mainFrame" href="lxml.etree.EntityBase-class.html" >EntityBase</a><br /> <a target="mainFrame" href="lxml.etree.Error-class.html" >Error</a><br /> <a target="mainFrame" href="lxml.etree.ErrorDomains-class.html" >ErrorDomains</a><br /> <a target="mainFrame" href="lxml.etree.ErrorLevels-class.html" >ErrorLevels</a><br /> <a target="mainFrame" href="lxml.etree.ErrorTypes-class.html" >ErrorTypes</a><br /> <a target="mainFrame" href="lxml.etree.FallbackElementClassLookup-class.html" >FallbackElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.HTMLParser-class.html" >HTMLParser</a><br /> <a target="mainFrame" href="lxml.etree.LxmlError-class.html" >LxmlError</a><br /> <a target="mainFrame" href="lxml.etree.LxmlRegistryError-class.html" >LxmlRegistryError</a><br /> <a target="mainFrame" href="lxml.etree.LxmlSyntaxError-class.html" >LxmlSyntaxError</a><br /> <a target="mainFrame" href="lxml.etree.NamespaceRegistryError-class.html" >NamespaceRegistryError</a><br /> <a target="mainFrame" href="lxml.etree.PIBase-class.html" >PIBase</a><br /> <a target="mainFrame" href="lxml.etree.ParseError-class.html" >ParseError</a><br /> <a target="mainFrame" href="lxml.etree.ParserBasedElementClassLookup-class.html" >ParserBasedElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.ParserError-class.html" >ParserError</a><br /> <a target="mainFrame" href="lxml.etree.PyErrorLog-class.html" >PyErrorLog</a><br /> <a target="mainFrame" href="lxml.etree.PythonElementClassLookup-class.html" >PythonElementClassLookup</a><br /> <a target="mainFrame" href="lxml.etree.QName-class.html" >QName</a><br /> <a target="mainFrame" href="lxml.etree.RelaxNG-class.html" >RelaxNG</a><br /> <a target="mainFrame" href="lxml.etree.RelaxNGError-class.html" >RelaxNGError</a><br /> <a target="mainFrame" href="lxml.etree.RelaxNGErrorTypes-class.html" >RelaxNGErrorTypes</a><br /> <a target="mainFrame" href="lxml.etree.RelaxNGParseError-class.html" >RelaxNGParseError</a><br /> <a target="mainFrame" href="lxml.etree.RelaxNGValidateError-class.html" >RelaxNGValidateError</a><br /> <a target="mainFrame" href="lxml.etree.Resolver-class.html" >Resolver</a><br /> <a target="mainFrame" href="lxml.etree.Schematron-class.html" >Schematron</a><br /> <a target="mainFrame" href="lxml.etree.SchematronError-class.html" >SchematronError</a><br /> <a target="mainFrame" href="lxml.etree.SchematronParseError-class.html" >SchematronParseError</a><br /> <a target="mainFrame" href="lxml.etree.SchematronValidateError-class.html" >SchematronValidateError</a><br /> <a target="mainFrame" href="lxml.etree.SerialisationError-class.html" >SerialisationError</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.SiblingsIterator-class.html" >SiblingsIterator</a><br /> </div> <a target="mainFrame" href="lxml.etree.TreeBuilder-class.html" >TreeBuilder</a><br /> <a target="mainFrame" href="lxml.etree.XInclude-class.html" >XInclude</a><br /> <a target="mainFrame" href="lxml.etree.XIncludeError-class.html" >XIncludeError</a><br /> <a target="mainFrame" href="lxml.etree.XMLParser-class.html" >XMLParser</a><br /> <a target="mainFrame" href="lxml.etree.XMLSchema-class.html" >XMLSchema</a><br /> <a target="mainFrame" href="lxml.etree.XMLSchemaError-class.html" >XMLSchemaError</a><br /> <a target="mainFrame" href="lxml.etree.XMLSchemaParseError-class.html" >XMLSchemaParseError</a><br /> <a target="mainFrame" href="lxml.etree.XMLSchemaValidateError-class.html" >XMLSchemaValidateError</a><br /> <a target="mainFrame" href="lxml.etree.XMLSyntaxError-class.html" >XMLSyntaxError</a><br /> <a target="mainFrame" href="lxml.etree.ETCompatXMLParser-class.html" >XMLTreeBuilder</a><br /> <a target="mainFrame" href="lxml.etree.XPath-class.html" >XPath</a><br /> <a target="mainFrame" href="lxml.etree.XPathDocumentEvaluator-class.html" >XPathDocumentEvaluator</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.XPathElementEvaluator-class.html" >XPathElementEvaluator</a><br /> </div> <a target="mainFrame" href="lxml.etree.XPathError-class.html" >XPathError</a><br /> <a target="mainFrame" href="lxml.etree.XPathEvalError-class.html" >XPathEvalError</a><br /> <a target="mainFrame" href="lxml.etree.XPathFunctionError-class.html" >XPathFunctionError</a><br /> <a target="mainFrame" href="lxml.etree.XPathResultError-class.html" >XPathResultError</a><br /> <a target="mainFrame" href="lxml.etree.XPathSyntaxError-class.html" >XPathSyntaxError</a><br /> <a target="mainFrame" href="lxml.etree.XSLT-class.html" >XSLT</a><br /> <a target="mainFrame" href="lxml.etree.XSLTAccessControl-class.html" >XSLTAccessControl</a><br /> <a target="mainFrame" href="lxml.etree.XSLTApplyError-class.html" >XSLTApplyError</a><br /> <a target="mainFrame" href="lxml.etree.XSLTError-class.html" >XSLTError</a><br /> <a target="mainFrame" href="lxml.etree.XSLTExtension-class.html" >XSLTExtension</a><br /> <a target="mainFrame" href="lxml.etree.XSLTExtensionError-class.html" >XSLTExtensionError</a><br /> <a target="mainFrame" href="lxml.etree.XSLTParseError-class.html" >XSLTParseError</a><br /> <a target="mainFrame" href="lxml.etree.XSLTSaveError-class.html" >XSLTSaveError</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree._Attrib-class.html" >_Attrib</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._BaseErrorLog-class.html" >_BaseErrorLog</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._Comment-class.html" >_Comment</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._Document-class.html" >_Document</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._DomainErrorLog-class.html" >_DomainErrorLog</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._Element-class.html" >_Element</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementIterator-class.html" >_ElementIterator</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementMatchIterator-class.html" >_ElementMatchIterator</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementStringResult-class.html" >_ElementStringResult</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementTagMatcher-class.html" >_ElementTagMatcher</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementTree-class.html" >_ElementTree</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ElementUnicodeResult-class.html" >_ElementUnicodeResult</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._Entity-class.html" >_Entity</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ErrorLog-class.html" >_ErrorLog</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._FeedParser-class.html" >_FeedParser</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._IDDict-class.html" >_IDDict</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ListErrorLog-class.html" >_ListErrorLog</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._LogEntry-class.html" >_LogEntry</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._ProcessingInstruction-class.html" >_ProcessingInstruction</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._RotatingErrorLog-class.html" >_RotatingErrorLog</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._SaxParserTarget-class.html" >_SaxParserTarget</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._TargetParserResult-class.html" >_TargetParserResult</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._Validator-class.html" >_Validator</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._XPathEvaluatorBase-class.html" >_XPathEvaluatorBase</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._XSLTProcessingInstruction-class.html" >_XSLTProcessingInstruction</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree._XSLTResultTree-class.html" >_XSLTResultTree</a><br /> </div> <a target="mainFrame" href="lxml.etree.iterparse-class.html" >iterparse</a><br /> <a target="mainFrame" href="lxml.etree.iterwalk-class.html" >iterwalk</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree.xmlfile-class.html" >xmlfile</a><br /> </div> <h2 class="toc">Functions</h2> <a target="mainFrame" href="lxml.etree-module.html#Comment" >Comment</a><br /> <a target="mainFrame" href="lxml.etree-module.html#Element" >Element</a><br /> <a target="mainFrame" href="lxml.etree-module.html#ElementTree" >ElementTree</a><br /> <a target="mainFrame" href="lxml.etree-module.html#Entity" >Entity</a><br /> <a target="mainFrame" href="lxml.etree-module.html#Extension" >Extension</a><br /> <a target="mainFrame" href="lxml.etree-module.html#FunctionNamespace" >FunctionNamespace</a><br /> <a target="mainFrame" href="lxml.etree-module.html#HTML" >HTML</a><br /> <a target="mainFrame" href="lxml.etree-module.html#PI" >PI</a><br /> <a target="mainFrame" href="lxml.etree-module.html#ProcessingInstruction" >ProcessingInstruction</a><br /> <a target="mainFrame" href="lxml.etree-module.html#SubElement" >SubElement</a><br /> <a target="mainFrame" href="lxml.etree-module.html#XML" >XML</a><br /> <a target="mainFrame" href="lxml.etree-module.html#XMLDTDID" >XMLDTDID</a><br /> <a target="mainFrame" href="lxml.etree-module.html#XMLID" >XMLID</a><br /> <a target="mainFrame" href="lxml.etree-module.html#XPathEvaluator" >XPathEvaluator</a><br /> <a target="mainFrame" href="lxml.etree-module.html#cleanup_namespaces" >cleanup_namespaces</a><br /> <a target="mainFrame" href="lxml.etree-module.html#clear_error_log" >clear_error_log</a><br /> <a target="mainFrame" href="lxml.etree-module.html#dump" >dump</a><br /> <a target="mainFrame" href="lxml.etree-module.html#fromstring" >fromstring</a><br /> <a target="mainFrame" href="lxml.etree-module.html#fromstringlist" >fromstringlist</a><br /> <a target="mainFrame" href="lxml.etree-module.html#get_default_parser" >get_default_parser</a><br /> <a target="mainFrame" href="lxml.etree-module.html#iselement" >iselement</a><br /> <a target="mainFrame" href="lxml.etree-module.html#parse" >parse</a><br /> <a target="mainFrame" href="lxml.etree-module.html#parseid" >parseid</a><br /> <a target="mainFrame" href="lxml.etree-module.html#register_namespace" >register_namespace</a><br /> <a target="mainFrame" href="lxml.etree-module.html#set_default_parser" >set_default_parser</a><br /> <a target="mainFrame" href="lxml.etree-module.html#set_element_class_lookup" >set_element_class_lookup</a><br /> <a target="mainFrame" href="lxml.etree-module.html#strip_attributes" >strip_attributes</a><br /> <a target="mainFrame" href="lxml.etree-module.html#strip_elements" >strip_elements</a><br /> <a target="mainFrame" href="lxml.etree-module.html#strip_tags" >strip_tags</a><br /> <a target="mainFrame" href="lxml.etree-module.html#tostring" >tostring</a><br /> <a target="mainFrame" href="lxml.etree-module.html#tostringlist" >tostringlist</a><br /> <a target="mainFrame" href="lxml.etree-module.html#tounicode" >tounicode</a><br /> <a target="mainFrame" href="lxml.etree-module.html#use_global_python_log" >use_global_python_log</a><br /> <h2 class="toc">Variables</h2> <a target="mainFrame" href="lxml.etree-module.html#DEBUG" >DEBUG</a><br /> <a target="mainFrame" href="lxml.etree-module.html#LIBXML_COMPILED_VERSION" >LIBXML_COMPILED_VERSION</a><br /> <a target="mainFrame" href="lxml.etree-module.html#LIBXML_VERSION" >LIBXML_VERSION</a><br /> <a target="mainFrame" href="lxml.etree-module.html#LIBXSLT_COMPILED_VERSION" >LIBXSLT_COMPILED_VERSION</a><br /> <a target="mainFrame" href="lxml.etree-module.html#LIBXSLT_VERSION" >LIBXSLT_VERSION</a><br /> <a target="mainFrame" href="lxml.etree-module.html#LXML_VERSION" >LXML_VERSION</a><br /> <div class="private"> <a target="mainFrame" href="lxml.etree-module.html#__package__" >__package__</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree-module.html#__pyx_capi__" >__pyx_capi__</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree-module.html#__test__" >__test__</a><br /> </div> <div class="private"> <a target="mainFrame" href="lxml.etree-module.html#memory_debugger" >memory_debugger</a><br /> </div> <hr /> <span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{'content_hash': '0c4bc65881eea685df4400d2d57cf4fe', 'timestamp': '', 'source': 'github', 'line_count': 257, 'max_line_length': 114, 'avg_line_length': 66.6147859922179, 'alnum_prop': 0.6679322429906542, 'repo_name': 'ioram7/keystone-federado-pgid2013', 'id': 'ee2af01be8a3aec72d5ce9b4becc3d56e522c57a', 'size': '17120', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/lxml/doc/html/api/toc-lxml.etree-module.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1841'}, {'name': 'C', 'bytes': '10584735'}, {'name': 'C++', 'bytes': '19231'}, {'name': 'CSS', 'bytes': '172341'}, {'name': 'JavaScript', 'bytes': '530938'}, {'name': 'Python', 'bytes': '26306359'}, {'name': 'Shell', 'bytes': '38138'}, {'name': 'XSLT', 'bytes': '306125'}]}
package org.apereo.cas.authentication.bypass; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.MultifactorAuthenticationProvider; import org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProviderBypassProperties; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.util.HttpUtils; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.http.HttpStatus; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; /** * This is {@link RestMultifactorAuthenticationProviderBypassEvaluator}. * * @author Misagh Moayyed * @since 5.2.0 */ @Slf4j public class RestMultifactorAuthenticationProviderBypassEvaluator extends BaseMultifactorAuthenticationProviderBypassEvaluator { private static final long serialVersionUID = -7553888418344342672L; private final MultifactorAuthenticationProviderBypassProperties bypassProperties; public RestMultifactorAuthenticationProviderBypassEvaluator(final MultifactorAuthenticationProviderBypassProperties bypassProperties, final String providerId) { super(providerId); this.bypassProperties = bypassProperties; } @Override public boolean shouldMultifactorAuthenticationProviderExecuteInternal(final Authentication authentication, final RegisteredService registeredService, final MultifactorAuthenticationProvider provider, final HttpServletRequest request) { try { val principal = authentication.getPrincipal(); val rest = bypassProperties.getRest(); LOGGER.debug("Evaluating multifactor authentication bypass properties for principal [{}], " + "service [{}] and provider [{}] via REST endpoint [{}]", principal.getId(), registeredService, provider, rest.getUrl()); val parameters = CollectionUtils.wrap("principal", principal.getId(), "provider", provider.getId()); if (registeredService != null) { parameters.put("service", registeredService.getServiceId()); } val response = HttpUtils.execute(rest.getUrl(), rest.getMethod(), rest.getBasicAuthUsername(), rest.getBasicAuthPassword(), parameters, new HashMap<>(0)); return response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); return true; } } }
{'content_hash': '43087192ffc0d9bbce5a2c906590d3fc', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 153, 'avg_line_length': 45.7, 'alnum_prop': 0.6863603209336251, 'repo_name': 'leleuj/cas', 'id': '0e7fc8d6aee10c48ca23240643de8469cee2e948', 'size': '2742', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/bypass/RestMultifactorAuthenticationProviderBypassEvaluator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '13992'}, {'name': 'Dockerfile', 'bytes': '75'}, {'name': 'Groovy', 'bytes': '28247'}, {'name': 'HTML', 'bytes': '196019'}, {'name': 'Java', 'bytes': '12783758'}, {'name': 'JavaScript', 'bytes': '85879'}, {'name': 'Python', 'bytes': '26699'}, {'name': 'Ruby', 'bytes': '1323'}, {'name': 'Shell', 'bytes': '173622'}]}
from os import path from django.template import TemplateDoesNotExist from django.template.loader import render_to_string from .inlines import Inline __all__ = ('TemplateInlineMixin', 'TemplateInline',) class TemplateInlineMixin(object): def get_context(self): return {} def get_full_context(self): ctx = {'inline': self.data} ctx.update(self.get_context()) return ctx def get_template_extension(self, variant=None, media=None): return 'html' def get_templates(self, variant=None, media=None): base_templates = [] base_tmpl_dir = 'inlines' app_label = self._meta.app_label template_path_options = { 'name': self.name, 'variant': variant, 'cls_name': self.__class__.__name__.lower(), 'ext': self.get_template_extension(variant=variant, media=media)} if variant is not None: base_templates.extend(( path.join( app_label, '%(name)s__%(variant)s.%(ext)s' % template_path_options), path.join( app_label, '%(cls_name)s__%(variant)s.%(ext)s' % template_path_options), '%(name)s__%(variant)s.%(ext)s' % template_path_options, '%(cls_name)s__%(variant)s.%(ext)s' % template_path_options,)) base_templates.extend(( path.join( app_label, '%(name)s.%(ext)s' % template_path_options), '%(name)s.%(ext)s' % template_path_options, path.join( app_label, '%(cls_name)s.%(ext)s' % template_path_options), '%(cls_name)s.%(ext)s' % template_path_options)) templates = [ path.join(base_tmpl_dir, tmpl) for tmpl in base_templates] if media is not None: templates = [ path.join(base_tmpl_dir, media, tmpl) for tmpl in base_templates] + templates return templates def full_render(self, variant=None, media=None): renderer = getattr(self, 'render_%s' % variant, None) if renderer is not None: return renderer() try: return render_to_string( self.get_templates(variant=variant, media=media), self.get_full_context()) except TemplateDoesNotExist as err: try: return self.render() except NotImplementedError: raise err class TemplateInline(TemplateInlineMixin, Inline): pass
{'content_hash': '94cc6638694eb9fbeaf0645c75f53fcc', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 78, 'avg_line_length': 31.16867469879518, 'alnum_prop': 0.5481252415925782, 'repo_name': 'acdha/django-inlines', 'id': '7fbe4a057e890166d1dc9178123fc7365fa13d82', 'size': '2587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'django_inlines/inlines/template_inlines.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '74374'}]}
package org.gradle.api.publish.maven; import org.gradle.api.provider.MapProperty; import org.gradle.api.provider.Property; import org.gradle.api.provider.SetProperty; /** * A developer of a Maven publication. * * @since 4.8 * @see MavenPom * @see MavenPomDeveloperSpec */ public interface MavenPomDeveloper { /** * The unique ID of this developer in the SCM. */ Property<String> getId(); /** * The name of this developer. */ Property<String> getName(); /** * The email */ Property<String> getEmail(); /** * The URL of this developer. */ Property<String> getUrl(); /** * The organization name of this developer. */ Property<String> getOrganization(); /** * The organization's URL of this developer. */ Property<String> getOrganizationUrl(); /** * The roles of this developer. */ SetProperty<String> getRoles(); /** * The timezone of this developer. */ Property<String> getTimezone(); /** * The properties of this developer. */ MapProperty<String, String> getProperties(); }
{'content_hash': '5e66863da916e56357b5c1615b142050', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 50, 'avg_line_length': 18.333333333333332, 'alnum_prop': 0.606926406926407, 'repo_name': 'gradle/gradle', 'id': '94c2d1c8e23fd4f82939d9affbbb74bd54766d7f', 'size': '1770', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'subprojects/maven/src/main/java/org/gradle/api/publish/maven/MavenPomDeveloper.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '277'}, {'name': 'Brainfuck', 'bytes': '54'}, {'name': 'C', 'bytes': '123600'}, {'name': 'C++', 'bytes': '1781062'}, {'name': 'CSS', 'bytes': '151435'}, {'name': 'GAP', 'bytes': '424'}, {'name': 'Gherkin', 'bytes': '191'}, {'name': 'Groovy', 'bytes': '30897043'}, {'name': 'HTML', 'bytes': '54458'}, {'name': 'Java', 'bytes': '28750090'}, {'name': 'JavaScript', 'bytes': '78583'}, {'name': 'Kotlin', 'bytes': '4154213'}, {'name': 'Objective-C', 'bytes': '652'}, {'name': 'Objective-C++', 'bytes': '441'}, {'name': 'Python', 'bytes': '57'}, {'name': 'Ruby', 'bytes': '16'}, {'name': 'Scala', 'bytes': '10840'}, {'name': 'Shell', 'bytes': '12148'}, {'name': 'Swift', 'bytes': '2040'}, {'name': 'XSLT', 'bytes': '42693'}]}
namespace foundation { class ImageAttributes; } namespace renderer { class AOV; } namespace renderer { class ParamArray; } namespace renderer { // // Denoiser AOV. // class DenoiserAOV : public AOV { public: ~DenoiserAOV() override; const char* get_model() const override; size_t get_channel_count() const override; const char** get_channel_names() const override; bool has_color_data() const override; void create_image( const size_t canvas_width, const size_t canvas_height, const size_t tile_width, const size_t tile_height, ImageStack& aov_images) override; void clear_image() override; void fill_empty_samples() const; const bcd::Deepimf& histograms_image() const; bcd::Deepimf& histograms_image(); void extract_num_samples_image(bcd::Deepimf& num_samples_image) const; void compute_covariances_image(bcd::Deepimf& covariances_image) const; bool write_images( const char* file_path, const foundation::ImageAttributes& image_attributes) const override; protected: foundation::auto_release_ptr<AOVAccumulator> create_accumulator() const override; private: friend class DenoiserAOVFactory; struct Impl; Impl* impl; DenoiserAOV( const float max_hist_value, const size_t num_bins); }; // // A factory for denoiser AOVs. // class DenoiserAOVFactory { public: static foundation::auto_release_ptr<DenoiserAOV> create( const float max_hist_value = 2.5f, const size_t num_bins = 20); }; } // namespace renderer
{'content_hash': 'f5903291393523440b24eac569b5a411', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 85, 'avg_line_length': 22.41891891891892, 'alnum_prop': 0.6503918022905365, 'repo_name': 'Biart95/appleseed', 'id': '01a9ab34723d9b2e729a5349b7159bd8e02c7aed', 'size': '3265', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/appleseed/renderer/modeling/aov/denoiseraov.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '68'}, {'name': 'C', 'bytes': '1968892'}, {'name': 'C++', 'bytes': '9605581'}, {'name': 'CMake', 'bytes': '245718'}, {'name': 'HTML', 'bytes': '39165'}, {'name': 'Makefile', 'bytes': '717'}, {'name': 'Objective-C', 'bytes': '6087'}, {'name': 'Python', 'bytes': '420655'}, {'name': 'Shell', 'bytes': '2688'}]}
module CommentHelper def new_post_comment_url(post) new_comment_url(post_type: post.class, post_id: post.id) end end
{'content_hash': '277c2a19529712c3dff22e2b082511f1', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 60, 'avg_line_length': 25.0, 'alnum_prop': 0.728, 'repo_name': 'thomas-mcdonald/qa', 'id': 'c2c7935e30bcd31c07eb1db3f8e788b9a2887575', 'size': '125', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/helpers/comment_helper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15958'}, {'name': 'CoffeeScript', 'bytes': '3475'}, {'name': 'Gherkin', 'bytes': '7396'}, {'name': 'HTML', 'bytes': '29985'}, {'name': 'JavaScript', 'bytes': '668'}, {'name': 'Ruby', 'bytes': '174294'}, {'name': 'Shell', 'bytes': '74'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '116e028fd688fad8e65d8ff5b43b91f3', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'd08417e6f9d81ef5d2422530712c3692741ac808', 'size': '206', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Prunus/Prunus armeniaca/Armeniaca vulgaris rushanica/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<div class="commune_descr limited"> <p> Gouillons est un village localisé dans le département de l'Eure-et-Loir en Centre. On dénombrait 338 habitants en 2008.</p> <p>À proximité de Gouillons sont positionnées géographiquement les villes de <a href="{{VLROOT}}/immobilier/denonville_28129/">Denonville</a> située à 5&nbsp;km, 805 habitants, <a href="{{VLROOT}}/immobilier/baudreville_28026/">Baudreville</a> localisée à 5&nbsp;km, 285 habitants, <a href="{{VLROOT}}/immobilier/louville-la-chenard_28215/">Louville-la-Chenard</a> à 4&nbsp;km, 273 habitants, <a href="{{VLROOT}}/immobilier/lethuin_28207/">Léthuin</a> à 3&nbsp;km, 203 habitants, <a href="{{VLROOT}}/immobilier/merouville_28243/">Mérouville</a> située à 6&nbsp;km, 229 habitants, <a href="{{VLROOT}}/immobilier/ouarville_28291/">Ouarville</a> située à 5&nbsp;km, 571 habitants, entre autres. De plus, Gouillons est située à seulement 28&nbsp;km de <a href="{{VLROOT}}/immobilier/chartres_28085/">Chartres</a>.</p> <p>Le parc d'habitations, à Gouillons, se décomposait en 2011 en quatre appartements et 143 maisons soit un marché relativement équilibré.</p> <p>La ville propose quelques équipements, elle dispose, entre autres, de un terrain de sport.</p> <p>Si vous pensez venir habiter à Gouillons, vous pourrez aisément trouver une maison à vendre. </p> </div>
{'content_hash': 'a99a998f507a645391a61223f6982b53', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 136, 'avg_line_length': 74.77777777777777, 'alnum_prop': 0.7407132243684993, 'repo_name': 'donaldinou/frontend', 'id': 'fd07633720d874ac5a9f6c9941e7bd571704670d', 'size': '1376', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Viteloge/CoreBundle/Resources/descriptions/28184.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3073'}, {'name': 'CSS', 'bytes': '111338'}, {'name': 'HTML', 'bytes': '58634405'}, {'name': 'JavaScript', 'bytes': '88564'}, {'name': 'PHP', 'bytes': '841919'}]}
// // This file contains the declaration of the VP9 packetizer class. // A packetizer object is created for each encoded video frame. The // constructor is called with the payload data and size. // // After creating the packetizer, the method NextPacket is called // repeatedly to get all packets for the frame. The method returns // false as long as there are more packets left to fetch. // #ifndef WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_VP9_H_ #define WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_VP9_H_ #include <queue> #include <string> #include "webrtc/base/constructormagic.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/modules/rtp_rtcp/source/rtp_format.h" #include "webrtc/typedefs.h" namespace webrtc { class RtpPacketizerVp9 : public RtpPacketizer { public: RtpPacketizerVp9(const RTPVideoHeaderVP9& hdr, size_t max_payload_length); virtual ~RtpPacketizerVp9(); ProtectionType GetProtectionType() override; StorageType GetStorageType(uint32_t retransmission_settings) override; std::string ToString() override; // The payload data must be one encoded VP9 frame. void SetPayloadData(const uint8_t* payload, size_t payload_size, const RTPFragmentationHeader* fragmentation) override; // Gets the next payload with VP9 payload header. // |buffer| is a pointer to where the output will be written. // |bytes_to_send| is an output variable that will contain number of bytes // written to buffer. // |last_packet| is true for the last packet of the frame, false otherwise // (i.e. call the function again to get the next packet). // Returns true on success, false otherwise. bool NextPacket(uint8_t* buffer, size_t* bytes_to_send, bool* last_packet) override; typedef struct { size_t payload_start_pos; size_t size; bool layer_begin; bool layer_end; } PacketInfo; typedef std::queue<PacketInfo> PacketInfoQueue; private: // Calculates all packet sizes and loads info to packet queue. void GeneratePackets(); // Writes the payload descriptor header and copies payload to the |buffer|. // |packet_info| determines which part of the payload to write. // |bytes_to_send| contains the number of written bytes to the buffer. // Returns true on success, false otherwise. bool WriteHeaderAndPayload(const PacketInfo& packet_info, uint8_t* buffer, size_t* bytes_to_send) const; // Writes payload descriptor header to |buffer|. // Returns true on success, false otherwise. bool WriteHeader(const PacketInfo& packet_info, uint8_t* buffer, size_t* header_length) const; const RTPVideoHeaderVP9 hdr_; const size_t max_payload_length_; // The max length in bytes of one packet. const uint8_t* payload_; // The payload data to be packetized. size_t payload_size_; // The size in bytes of the payload data. PacketInfoQueue packets_; RTC_DISALLOW_COPY_AND_ASSIGN(RtpPacketizerVp9); }; class RtpDepacketizerVp9 : public RtpDepacketizer { public: virtual ~RtpDepacketizerVp9() {} bool Parse(ParsedPayload* parsed_payload, const uint8_t* payload, size_t payload_length) override; }; } // namespace webrtc #endif // WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_VP9_H_
{'content_hash': 'ec1808bdd97287daa7237df8566bab8c', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 78, 'avg_line_length': 34.22, 'alnum_prop': 0.695791934541204, 'repo_name': 'sippet/webrtc', 'id': 'abce7e77919bbca7c373e6329c3f66ef461f7b67', 'size': '3834', 'binary': False, 'copies': '2', 'ref': 'refs/heads/custom', 'path': 'modules/rtp_rtcp/source/rtp_format_vp9.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '22479'}, {'name': 'C', 'bytes': '4547444'}, {'name': 'C++', 'bytes': '17516683'}, {'name': 'Java', 'bytes': '124220'}, {'name': 'Matlab', 'bytes': '42108'}, {'name': 'Objective-C', 'bytes': '27983'}, {'name': 'Objective-C++', 'bytes': '264581'}, {'name': 'Protocol Buffer', 'bytes': '9929'}, {'name': 'Python', 'bytes': '195262'}, {'name': 'Shell', 'bytes': '77553'}]}
namespace cppgc { class Visitor; namespace internal { // Pre-C++17 custom implementation of std::void_t. template <typename... Ts> struct make_void { typedef void type; }; template <typename... Ts> using void_t = typename make_void<Ts...>::type; // Not supposed to be specialized by the user. template <typename T> struct IsWeak : std::false_type {}; template <typename T, template <typename... V> class U> struct IsSubclassOfTemplate { private: template <typename... W> static std::true_type SubclassCheck(U<W...>*); static std::false_type SubclassCheck(...); public: static constexpr bool value = decltype(SubclassCheck(std::declval<T*>()))::value; }; // IsTraceMethodConst is used to verify that all Trace methods are marked as // const. It is equivalent to IsTraceable but for a non-const object. template <typename T, typename = void> struct IsTraceMethodConst : std::false_type {}; template <typename T> struct IsTraceMethodConst<T, void_t<decltype(std::declval<const T>().Trace( std::declval<Visitor*>()))>> : std::true_type { }; template <typename T, typename = void> struct IsTraceable : std::false_type { static_assert(sizeof(T), "T must be fully defined"); }; template <typename T> struct IsTraceable< T, void_t<decltype(std::declval<T>().Trace(std::declval<Visitor*>()))>> : std::true_type { // All Trace methods should be marked as const. If an object of type // 'T' is traceable then any object of type 'const T' should also // be traceable. static_assert(IsTraceMethodConst<T>(), "Trace methods should be marked as const."); }; template <typename T> constexpr bool IsTraceableV = IsTraceable<T>::value; template <typename T, typename = void> struct IsGarbageCollectedMixinType : std::false_type { static_assert(sizeof(T), "T must be fully defined"); }; template <typename T> struct IsGarbageCollectedMixinType< T, void_t<typename std::remove_const_t<T>::IsGarbageCollectedMixinTypeMarker>> : std::true_type { static_assert(sizeof(T), "T must be fully defined"); }; template <typename T, typename = void> struct IsGarbageCollectedType : IsGarbageCollectedMixinType<T> { static_assert(sizeof(T), "T must be fully defined"); }; template <typename T> struct IsGarbageCollectedType< T, void_t<typename std::remove_const_t<T>::IsGarbageCollectedTypeMarker>> : std::true_type { static_assert(sizeof(T), "T must be fully defined"); }; template <typename T> constexpr bool IsGarbageCollectedTypeV = internal::IsGarbageCollectedType<T>::value; template <typename T> constexpr bool IsGarbageCollectedMixinTypeV = internal::IsGarbageCollectedMixinType<T>::value; } // namespace internal template <typename T> constexpr bool IsWeakV = internal::IsWeak<T>::value; } // namespace cppgc #endif // INCLUDE_CPPGC_TYPE_TRAITS_H_
{'content_hash': '3c76206454b4641e58c89c8dc33b57fe', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 80, 'avg_line_length': 28.7, 'alnum_prop': 0.7073170731707317, 'repo_name': 'youtube/cobalt_sandbox', 'id': '4d8ab809c8d439ca040baa70a446a715f8351f38', 'size': '3137', 'binary': False, 'copies': '8', 'ref': 'refs/heads/main', 'path': 'third_party/v8/include/cppgc/type-traits.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
FN="Iyer517_1.34.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.13/data/experiment/src/contrib/Iyer517_1.34.0.tar.gz" "https://bioarchive.galaxyproject.org/Iyer517_1.34.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-iyer517/bioconductor-iyer517_1.34.0_src_all.tar.gz" ) MD5="d7f42c68533615e2c25278c4613f1293" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
{'content_hash': 'e069e016bc28cb13889e33080cd21096', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 108, 'avg_line_length': 28.333333333333332, 'alnum_prop': 0.6635294117647059, 'repo_name': 'peterjc/bioconda-recipes', 'id': 'fa414ae5492004dd7dc8c3ab2a609eb397e0c06a', 'size': '1287', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'recipes/bioconductor-iyer517/post-link.sh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '237'}, {'name': 'C', 'bytes': '154'}, {'name': 'CMake', 'bytes': '13967'}, {'name': 'Java', 'bytes': '286'}, {'name': 'M4', 'bytes': '726'}, {'name': 'Perl', 'bytes': '100982'}, {'name': 'Perl 6', 'bytes': '23942'}, {'name': 'Prolog', 'bytes': '1067'}, {'name': 'Python', 'bytes': '391790'}, {'name': 'Roff', 'bytes': '996'}, {'name': 'Shell', 'bytes': '3897495'}]}
from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six import numpy as np from io import BytesIO import xml.parsers.expat import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup from matplotlib.testing.decorators import image_comparison @cleanup def test_visibility(): fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read() fd.close() parser = xml.parsers.expat.ParserCreate() parser.Parse(buf) # this will raise ExpatError if the svg is invalid @image_comparison(baseline_images=['fill_black_with_alpha'], remove_text=True, extensions=['svg']) def test_fill_black_with_alpha(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000) @image_comparison(baseline_images=['noscale'], remove_text=True) def test_noscale(): X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.imshow(Z, cmap='gray') plt.rcParams['svg.image_noscale'] = True @cleanup def test_composite_images(): #Test that figures can be saved with and without combining multiple images #(on a single set of axes) into a single composite image. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, 3) ax.imshow(Z, extent=[0, 1, 0, 1]) ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) plt.rcParams['image.composite_image'] = True with BytesIO() as svg: fig.savefig(svg, format="svg") svg.seek(0) buff = svg.read() assert buff.count(six.b('<image ')) == 1 plt.rcParams['image.composite_image'] = False with BytesIO() as svg: fig.savefig(svg, format="svg") svg.seek(0) buff = svg.read() assert buff.count(six.b('<image ')) == 2 @cleanup def test_text_urls(): fig = plt.figure() test_url = "http://test_text_urls.matplotlib.org" fig.suptitle("test_text_urls", url=test_url) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read().decode() fd.close() expected = '<a xlink:href="{0}">'.format(test_url) assert expected in buf @image_comparison(baseline_images=['bold_font_output'], extensions=['svg']) def test_bold_font_output(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') @image_comparison(baseline_images=['bold_font_output_with_none_fonttype'], extensions=['svg']) def test_bold_font_output_with_none_fonttype(): plt.rcParams['svg.fonttype'] = 'none' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
{'content_hash': 'e2c84039d3e35ab156cc61699b2c7779', 'timestamp': '', 'source': 'github', 'line_count': 124, 'max_line_length': 78, 'avg_line_length': 28.637096774193548, 'alnum_prop': 0.6153196282737257, 'repo_name': 'marcsans/cnn-physics-perception', 'id': '9932250f0c5cd8ea7f73380e7695efd0031083de', 'size': '3551', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'phy/lib/python2.7/site-packages/matplotlib/tests/test_backend_svg.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '489272'}, {'name': 'C++', 'bytes': '3521811'}, {'name': 'CSS', 'bytes': '7132'}, {'name': 'Cuda', 'bytes': '232079'}, {'name': 'FORTRAN', 'bytes': '9868'}, {'name': 'HTML', 'bytes': '131419'}, {'name': 'JavaScript', 'bytes': '23881'}, {'name': 'Jupyter Notebook', 'bytes': '16254'}, {'name': 'Makefile', 'bytes': '75861'}, {'name': 'Matlab', 'bytes': '4346'}, {'name': 'Objective-C', 'bytes': '567'}, {'name': 'Python', 'bytes': '36682149'}, {'name': 'Shell', 'bytes': '3878'}, {'name': 'TeX', 'bytes': '14053'}]}
namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace GenericProxy { class Factory : public Envoy::Extensions::NetworkFilters::Common::FactoryBase<ProxyConfig> { public: Factory() : FactoryBase(Filter::name(), true) {} Envoy::Network::FilterFactoryCb createFilterFactoryFromProtoTyped(const ProxyConfig& proto_config, Envoy::Server::Configuration::FactoryContext& context) override; static std::pair<CodecFactoryPtr, ProxyFactoryPtr> factoriesFromProto(const envoy::config::core::v3::TypedExtensionConfig& codec_config, Server::Configuration::FactoryContext& context); static Rds::RouteConfigProviderSharedPtr routeConfigProviderFromProto(const ProxyConfig& config, Server::Configuration::FactoryContext& context, RouteConfigProviderManager& route_config_provider_manager); static std::vector<NamedFilterFactoryCb> filtersFactoryFromProto( const ProtobufWkt::RepeatedPtrField<envoy::config::core::v3::TypedExtensionConfig>& filters, const std::string stats_prefix, Server::Configuration::FactoryContext& context); }; } // namespace GenericProxy } // namespace NetworkFilters } // namespace Extensions } // namespace Envoy
{'content_hash': 'e2bc52e6fe657cf13715a5eb80065000', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 100, 'avg_line_length': 41.903225806451616, 'alnum_prop': 0.7228637413394919, 'repo_name': 'envoyproxy/envoy', 'id': 'b311762d34fcfabd23d75308c270a95d6397c420', 'size': '1745', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'contrib/generic_proxy/filters/network/source/config.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '439'}, {'name': 'C', 'bytes': '54172'}, {'name': 'C++', 'bytes': '36279350'}, {'name': 'CSS', 'bytes': '884'}, {'name': 'Dockerfile', 'bytes': '891'}, {'name': 'Emacs Lisp', 'bytes': '966'}, {'name': 'Go', 'bytes': '558'}, {'name': 'HTML', 'bytes': '582'}, {'name': 'Java', 'bytes': '1309139'}, {'name': 'JavaScript', 'bytes': '76'}, {'name': 'Jinja', 'bytes': '46306'}, {'name': 'Kotlin', 'bytes': '311319'}, {'name': 'Makefile', 'bytes': '303'}, {'name': 'NASL', 'bytes': '327095'}, {'name': 'Objective-C', 'bytes': '95941'}, {'name': 'PureBasic', 'bytes': '472'}, {'name': 'Python', 'bytes': '630897'}, {'name': 'Ruby', 'bytes': '47'}, {'name': 'Rust', 'bytes': '38041'}, {'name': 'Shell', 'bytes': '194810'}, {'name': 'Smarty', 'bytes': '3528'}, {'name': 'Starlark', 'bytes': '2229814'}, {'name': 'Swift', 'bytes': '307285'}, {'name': 'Thrift', 'bytes': '748'}]}
import os import re import sys import textwrap import _pytest._code import pytest from _pytest.compat import importlib_metadata from _pytest.config import _iter_rewritable_modules from _pytest.config import Config from _pytest.config import ExitCode from _pytest.config.exceptions import UsageError from _pytest.config.findpaths import determine_setup from _pytest.config.findpaths import get_common_ancestor from _pytest.config.findpaths import getcfg from _pytest.pathlib import Path class TestParseIni: @pytest.mark.parametrize( "section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")] ) def test_getcfg_and_config(self, testdir, tmpdir, section, filename): sub = tmpdir.mkdir("sub") sub.chdir() tmpdir.join(filename).write( textwrap.dedent( """\ [{section}] name = value """.format( section=section ) ) ) _, _, cfg = getcfg([sub]) assert cfg["name"] == "value" config = testdir.parseconfigure(sub) assert config.inicfg["name"] == "value" def test_getcfg_empty_path(self): """correctly handle zero length arguments (a la pytest '')""" getcfg([""]) def test_setupcfg_uses_toolpytest_with_pytest(self, testdir): p1 = testdir.makepyfile("def test(): pass") testdir.makefile( ".cfg", setup=""" [tool:pytest] testpaths=%s [pytest] testpaths=ignored """ % p1.basename, ) result = testdir.runpytest() result.stdout.fnmatch_lines(["*, inifile: setup.cfg, *", "* 1 passed in *"]) assert result.ret == 0 def test_append_parse_args(self, testdir, tmpdir, monkeypatch): monkeypatch.setenv("PYTEST_ADDOPTS", '--color no -rs --tb="short"') tmpdir.join("pytest.ini").write( textwrap.dedent( """\ [pytest] addopts = --verbose """ ) ) config = testdir.parseconfig(tmpdir) assert config.option.color == "no" assert config.option.reportchars == "s" assert config.option.tbstyle == "short" assert config.option.verbose def test_tox_ini_wrong_version(self, testdir): testdir.makefile( ".ini", tox=""" [pytest] minversion=9.0 """, ) result = testdir.runpytest() assert result.ret != 0 result.stderr.fnmatch_lines(["*tox.ini:2*requires*9.0*actual*"]) @pytest.mark.parametrize( "section, name", [("tool:pytest", "setup.cfg"), ("pytest", "tox.ini"), ("pytest", "pytest.ini")], ) def test_ini_names(self, testdir, name, section): testdir.tmpdir.join(name).write( textwrap.dedent( """ [{section}] minversion = 1.0 """.format( section=section ) ) ) config = testdir.parseconfig() assert config.getini("minversion") == "1.0" def test_toxini_before_lower_pytestini(self, testdir): sub = testdir.tmpdir.mkdir("sub") sub.join("tox.ini").write( textwrap.dedent( """ [pytest] minversion = 2.0 """ ) ) testdir.tmpdir.join("pytest.ini").write( textwrap.dedent( """ [pytest] minversion = 1.5 """ ) ) config = testdir.parseconfigure(sub) assert config.getini("minversion") == "2.0" def test_ini_parse_error(self, testdir): testdir.tmpdir.join("pytest.ini").write("addopts = -x") result = testdir.runpytest() assert result.ret != 0 result.stderr.fnmatch_lines(["ERROR: *pytest.ini:1: no section header defined"]) @pytest.mark.xfail(reason="probably not needed") def test_confcutdir(self, testdir): sub = testdir.mkdir("sub") sub.chdir() testdir.makeini( """ [pytest] addopts = --qwe """ ) result = testdir.inline_run("--confcutdir=.") assert result.ret == 0 class TestConfigCmdlineParsing: def test_parsing_again_fails(self, testdir): config = testdir.parseconfig() pytest.raises(AssertionError, lambda: config.parse([])) def test_explicitly_specified_config_file_is_loaded(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("custom", "") """ ) testdir.makeini( """ [pytest] custom = 0 """ ) testdir.makefile( ".ini", custom=""" [pytest] custom = 1 """, ) config = testdir.parseconfig("-c", "custom.ini") assert config.getini("custom") == "1" testdir.makefile( ".cfg", custom_tool_pytest_section=""" [tool:pytest] custom = 1 """, ) config = testdir.parseconfig("-c", "custom_tool_pytest_section.cfg") assert config.getini("custom") == "1" def test_absolute_win32_path(self, testdir): temp_ini_file = testdir.makefile( ".ini", custom=""" [pytest] addopts = --version """, ) from os.path import normpath temp_ini_file = normpath(str(temp_ini_file)) ret = pytest.main(["-c", temp_ini_file]) assert ret == ExitCode.OK class TestConfigAPI: def test_config_trace(self, testdir): config = testdir.parseconfig() values = [] config.trace.root.setwriter(values.append) config.trace("hello") assert len(values) == 1 assert values[0] == "hello [config]\n" def test_config_getoption(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addoption("--hello", "-X", dest="hello") """ ) config = testdir.parseconfig("--hello=this") for x in ("hello", "--hello", "-X"): assert config.getoption(x) == "this" pytest.raises(ValueError, config.getoption, "qweqwe") def test_config_getoption_unicode(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addoption('--hello', type=str) """ ) config = testdir.parseconfig("--hello=this") assert config.getoption("hello") == "this" def test_config_getvalueorskip(self, testdir): config = testdir.parseconfig() pytest.raises(pytest.skip.Exception, config.getvalueorskip, "hello") verbose = config.getvalueorskip("verbose") assert verbose == config.option.verbose def test_config_getvalueorskip_None(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addoption("--hello") """ ) config = testdir.parseconfig() with pytest.raises(pytest.skip.Exception): config.getvalueorskip("hello") def test_getoption(self, testdir): config = testdir.parseconfig() with pytest.raises(ValueError): config.getvalue("x") assert config.getoption("x", 1) == 1 def test_getconftest_pathlist(self, testdir, tmpdir): somepath = tmpdir.join("x", "y", "z") p = tmpdir.join("conftest.py") p.write("pathlist = ['.', %r]" % str(somepath)) config = testdir.parseconfigure(p) assert config._getconftest_pathlist("notexist", path=tmpdir) is None pl = config._getconftest_pathlist("pathlist", path=tmpdir) print(pl) assert len(pl) == 2 assert pl[0] == tmpdir assert pl[1] == somepath def test_addini(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("myname", "my new ini value") """ ) testdir.makeini( """ [pytest] myname=hello """ ) config = testdir.parseconfig() val = config.getini("myname") assert val == "hello" pytest.raises(ValueError, config.getini, "other") def test_addini_pathlist(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("paths", "my new ini value", type="pathlist") parser.addini("abc", "abc value") """ ) p = testdir.makeini( """ [pytest] paths=hello world/sub.py """ ) config = testdir.parseconfig() values = config.getini("paths") assert len(values) == 2 assert values[0] == p.dirpath("hello") assert values[1] == p.dirpath("world/sub.py") pytest.raises(ValueError, config.getini, "other") def test_addini_args(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("args", "new args", type="args") parser.addini("a2", "", "args", default="1 2 3".split()) """ ) testdir.makeini( """ [pytest] args=123 "123 hello" "this" """ ) config = testdir.parseconfig() values = config.getini("args") assert len(values) == 3 assert values == ["123", "123 hello", "this"] values = config.getini("a2") assert values == list("123") def test_addini_linelist(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("xy", "", type="linelist") parser.addini("a2", "", "linelist") """ ) testdir.makeini( """ [pytest] xy= 123 345 second line """ ) config = testdir.parseconfig() values = config.getini("xy") assert len(values) == 2 assert values == ["123 345", "second line"] values = config.getini("a2") assert values == [] @pytest.mark.parametrize( "str_val, bool_val", [("True", True), ("no", False), ("no-ini", True)] ) def test_addini_bool(self, testdir, str_val, bool_val): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("strip", "", type="bool", default=True) """ ) if str_val != "no-ini": testdir.makeini( """ [pytest] strip=%s """ % str_val ) config = testdir.parseconfig() assert config.getini("strip") is bool_val def test_addinivalue_line_existing(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("xy", "", type="linelist") """ ) testdir.makeini( """ [pytest] xy= 123 """ ) config = testdir.parseconfig() values = config.getini("xy") assert len(values) == 1 assert values == ["123"] config.addinivalue_line("xy", "456") values = config.getini("xy") assert len(values) == 2 assert values == ["123", "456"] def test_addinivalue_line_new(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("xy", "", type="linelist") """ ) config = testdir.parseconfig() assert not config.getini("xy") config.addinivalue_line("xy", "456") values = config.getini("xy") assert len(values) == 1 assert values == ["456"] config.addinivalue_line("xy", "123") values = config.getini("xy") assert len(values) == 2 assert values == ["456", "123"] def test_confcutdir_check_isdir(self, testdir): """Give an error if --confcutdir is not a valid directory (#2078)""" exp_match = r"^--confcutdir must be a directory, given: " with pytest.raises(pytest.UsageError, match=exp_match): testdir.parseconfig( "--confcutdir", testdir.tmpdir.join("file").ensure(file=1) ) with pytest.raises(pytest.UsageError, match=exp_match): testdir.parseconfig("--confcutdir", testdir.tmpdir.join("inexistant")) config = testdir.parseconfig( "--confcutdir", testdir.tmpdir.join("dir").ensure(dir=1) ) assert config.getoption("confcutdir") == str(testdir.tmpdir.join("dir")) @pytest.mark.parametrize( "names, expected", [ # dist-info based distributions root are files as will be put in PYTHONPATH (["bar.py"], ["bar"]), (["foo/bar.py"], ["bar"]), (["foo/bar.pyc"], []), (["foo/__init__.py"], ["foo"]), (["bar/__init__.py", "xz.py"], ["bar", "xz"]), (["setup.py"], []), # egg based distributions root contain the files from the dist root (["src/bar/__init__.py"], ["bar"]), (["src/bar/__init__.py", "setup.py"], ["bar"]), (["source/python/bar/__init__.py", "setup.py"], ["bar"]), ], ) def test_iter_rewritable_modules(self, names, expected): assert list(_iter_rewritable_modules(names)) == expected class TestConfigFromdictargs: def test_basic_behavior(self, _sys_snapshot): option_dict = {"verbose": 444, "foo": "bar", "capture": "no"} args = ["a", "b"] config = Config.fromdictargs(option_dict, args) with pytest.raises(AssertionError): config.parse(["should refuse to parse again"]) assert config.option.verbose == 444 assert config.option.foo == "bar" assert config.option.capture == "no" assert config.args == args def test_invocation_params_args(self, _sys_snapshot): """Show that fromdictargs can handle args in their "orig" format""" option_dict = {} args = ["-vvvv", "-s", "a", "b"] config = Config.fromdictargs(option_dict, args) assert config.args == ["a", "b"] assert config.invocation_params.args == tuple(args) assert config.option.verbose == 4 assert config.option.capture == "no" def test_inifilename(self, tmpdir): tmpdir.join("foo/bar.ini").ensure().write( textwrap.dedent( """\ [pytest] name = value """ ) ) inifile = "../../foo/bar.ini" option_dict = {"inifilename": inifile, "capture": "no"} cwd = tmpdir.join("a/b") cwd.join("pytest.ini").ensure().write( textwrap.dedent( """\ [pytest] name = wrong-value should_not_be_set = true """ ) ) with cwd.ensure(dir=True).as_cwd(): config = Config.fromdictargs(option_dict, ()) assert config.args == [str(cwd)] assert config.option.inifilename == inifile assert config.option.capture == "no" # this indicates this is the file used for getting configuration values assert config.inifile == inifile assert config.inicfg.get("name") == "value" assert config.inicfg.get("should_not_be_set") is None def test_options_on_small_file_do_not_blow_up(testdir): def runfiletest(opts): reprec = testdir.inline_run(*opts) passed, skipped, failed = reprec.countoutcomes() assert failed == 2 assert skipped == passed == 0 path = testdir.makepyfile( """ def test_f1(): assert 0 def test_f2(): assert 0 """ ) for opts in ( [], ["-l"], ["-s"], ["--tb=no"], ["--tb=short"], ["--tb=long"], ["--fulltrace"], ["--traceconfig"], ["-v"], ["-v", "-v"], ): runfiletest(opts + [path]) def test_preparse_ordering_with_setuptools(testdir, monkeypatch): monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) class EntryPoint: name = "mytestplugin" group = "pytest11" def load(self): class PseudoPlugin: x = 42 return PseudoPlugin() class Dist: files = () entry_points = (EntryPoint(),) def my_dists(): return (Dist,) monkeypatch.setattr(importlib_metadata, "distributions", my_dists) testdir.makeconftest( """ pytest_plugins = "mytestplugin", """ ) monkeypatch.setenv("PYTEST_PLUGINS", "mytestplugin") config = testdir.parseconfig() plugin = config.pluginmanager.getplugin("mytestplugin") assert plugin.x == 42 def test_setuptools_importerror_issue1479(testdir, monkeypatch): monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) class DummyEntryPoint: name = "mytestplugin" group = "pytest11" def load(self): raise ImportError("Don't hide me!") class Distribution: version = "1.0" files = ("foo.txt",) entry_points = (DummyEntryPoint(),) def distributions(): return (Distribution(),) monkeypatch.setattr(importlib_metadata, "distributions", distributions) with pytest.raises(ImportError): testdir.parseconfig() def test_importlib_metadata_broken_distribution(testdir, monkeypatch): """Integration test for broken distributions with 'files' metadata being None (#5389)""" monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) class DummyEntryPoint: name = "mytestplugin" group = "pytest11" def load(self): return object() class Distribution: version = "1.0" files = None entry_points = (DummyEntryPoint(),) def distributions(): return (Distribution(),) monkeypatch.setattr(importlib_metadata, "distributions", distributions) testdir.parseconfig() @pytest.mark.parametrize("block_it", [True, False]) def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block_it): monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) plugin_module_placeholder = object() class DummyEntryPoint: name = "mytestplugin" group = "pytest11" def load(self): return plugin_module_placeholder class Distribution: version = "1.0" files = ("foo.txt",) entry_points = (DummyEntryPoint(),) def distributions(): return (Distribution(),) monkeypatch.setattr(importlib_metadata, "distributions", distributions) args = ("-p", "no:mytestplugin") if block_it else () config = testdir.parseconfig(*args) config.pluginmanager.import_plugin("mytestplugin") if block_it: assert "mytestplugin" not in sys.modules assert config.pluginmanager.get_plugin("mytestplugin") is None else: assert ( config.pluginmanager.get_plugin("mytestplugin") is plugin_module_placeholder ) @pytest.mark.parametrize( "parse_args,should_load", [(("-p", "mytestplugin"), True), ((), False)] ) def test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load): class DummyEntryPoint: project_name = name = "mytestplugin" group = "pytest11" version = "1.0" def load(self): return sys.modules[self.name] class Distribution: entry_points = (DummyEntryPoint(),) files = () class PseudoPlugin: x = 42 attrs_used = [] def __getattr__(self, name): assert name == "__loader__" self.attrs_used.append(name) return object() def distributions(): return (Distribution(),) monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") monkeypatch.setattr(importlib_metadata, "distributions", distributions) monkeypatch.setitem(sys.modules, "mytestplugin", PseudoPlugin()) config = testdir.parseconfig(*parse_args) has_loaded = config.pluginmanager.get_plugin("mytestplugin") is not None assert has_loaded == should_load if should_load: assert PseudoPlugin.attrs_used == ["__loader__"] else: assert PseudoPlugin.attrs_used == [] def test_plugin_loading_order(testdir): """Test order of plugin loading with `-p`.""" p1 = testdir.makepyfile( """ def test_terminal_plugin(request): import myplugin assert myplugin.terminal_plugin == [False, True] """, **{ "myplugin": """ terminal_plugin = [] def pytest_configure(config): terminal_plugin.append(bool(config.pluginmanager.get_plugin("terminalreporter"))) def pytest_sessionstart(session): config = session.config terminal_plugin.append(bool(config.pluginmanager.get_plugin("terminalreporter"))) """ }, ) testdir.syspathinsert() result = testdir.runpytest("-p", "myplugin", str(p1)) assert result.ret == 0 def test_cmdline_processargs_simple(testdir): testdir.makeconftest( """ def pytest_cmdline_preparse(args): args.append("-h") """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["*pytest*", "*-h*"]) def test_invalid_options_show_extra_information(testdir): """display extra information when pytest exits due to unrecognized options in the command-line""" testdir.makeini( """ [pytest] addopts = --invalid-option """ ) result = testdir.runpytest() result.stderr.fnmatch_lines( [ "*error: unrecognized arguments: --invalid-option*", "* inifile: %s*" % testdir.tmpdir.join("tox.ini"), "* rootdir: %s*" % testdir.tmpdir, ] ) @pytest.mark.parametrize( "args", [ ["dir1", "dir2", "-v"], ["dir1", "-v", "dir2"], ["dir2", "-v", "dir1"], ["-v", "dir2", "dir1"], ], ) def test_consider_args_after_options_for_rootdir(testdir, args): """ Consider all arguments in the command-line for rootdir discovery, even if they happen to occur after an option. #949 """ # replace "dir1" and "dir2" from "args" into their real directory root = testdir.tmpdir.mkdir("myroot") d1 = root.mkdir("dir1") d2 = root.mkdir("dir2") for i, arg in enumerate(args): if arg == "dir1": args[i] = d1 elif arg == "dir2": args[i] = d2 with root.as_cwd(): result = testdir.runpytest(*args) result.stdout.fnmatch_lines(["*rootdir: *myroot"]) @pytest.mark.skipif("sys.platform == 'win32'") def test_toolongargs_issue224(testdir): result = testdir.runpytest("-m", "hello" * 500) assert result.ret == ExitCode.NO_TESTS_COLLECTED def test_config_in_subdirectory_colon_command_line_issue2148(testdir): conftest_source = """ def pytest_addoption(parser): parser.addini('foo', 'foo') """ testdir.makefile( ".ini", **{"pytest": "[pytest]\nfoo = root", "subdir/pytest": "[pytest]\nfoo = subdir"}, ) testdir.makepyfile( **{ "conftest": conftest_source, "subdir/conftest": conftest_source, "subdir/test_foo": """\ def test_foo(pytestconfig): assert pytestconfig.getini('foo') == 'subdir' """, } ) result = testdir.runpytest("subdir/test_foo.py::test_foo") assert result.ret == 0 def test_notify_exception(testdir, capfd): config = testdir.parseconfig() with pytest.raises(ValueError) as excinfo: raise ValueError(1) config.notify_exception(excinfo, config.option) _, err = capfd.readouterr() assert "ValueError" in err class A: def pytest_internalerror(self): return True config.pluginmanager.register(A()) config.notify_exception(excinfo, config.option) _, err = capfd.readouterr() assert not err config = testdir.parseconfig("-p", "no:terminal") with pytest.raises(ValueError) as excinfo: raise ValueError(1) config.notify_exception(excinfo, config.option) _, err = capfd.readouterr() assert "ValueError" in err def test_no_terminal_discovery_error(testdir): testdir.makepyfile("raise TypeError('oops!')") result = testdir.runpytest("-p", "no:terminal", "--collect-only") assert result.ret == ExitCode.INTERRUPTED def test_load_initial_conftest_last_ordering(_config_for_test): pm = _config_for_test.pluginmanager class My: def pytest_load_initial_conftests(self): pass m = My() pm.register(m) hc = pm.hook.pytest_load_initial_conftests values = hc._nonwrappers + hc._wrappers expected = ["_pytest.config", m.__module__, "_pytest.capture"] assert [x.function.__module__ for x in values] == expected def test_get_plugin_specs_as_list(): from _pytest.config import _get_plugin_specs_as_list def exp_match(val): return ( "Plugin specs must be a ','-separated string" " or a list/tuple of strings for plugin names. Given: {}".format( re.escape(repr(val)) ) ) with pytest.raises(pytest.UsageError, match=exp_match({"foo"})): _get_plugin_specs_as_list({"foo"}) with pytest.raises(pytest.UsageError, match=exp_match({})): _get_plugin_specs_as_list(dict()) assert _get_plugin_specs_as_list(None) == [] assert _get_plugin_specs_as_list("") == [] assert _get_plugin_specs_as_list("foo") == ["foo"] assert _get_plugin_specs_as_list("foo,bar") == ["foo", "bar"] assert _get_plugin_specs_as_list(["foo", "bar"]) == ["foo", "bar"] assert _get_plugin_specs_as_list(("foo", "bar")) == ["foo", "bar"] def test_collect_pytest_prefix_bug_integration(testdir): """Integration test for issue #3775""" p = testdir.copy_example("config/collect_pytest_prefix") result = testdir.runpytest(p) result.stdout.fnmatch_lines(["* 1 passed *"]) def test_collect_pytest_prefix_bug(pytestconfig): """Ensure we collect only actual functions from conftest files (#3775)""" class Dummy: class pytest_something: pass pm = pytestconfig.pluginmanager assert pm.parse_hookimpl_opts(Dummy(), "pytest_something") is None class TestRootdir: def test_simple_noini(self, tmpdir): assert get_common_ancestor([tmpdir]) == tmpdir a = tmpdir.mkdir("a") assert get_common_ancestor([a, tmpdir]) == tmpdir assert get_common_ancestor([tmpdir, a]) == tmpdir with tmpdir.as_cwd(): assert get_common_ancestor([]) == tmpdir no_path = tmpdir.join("does-not-exist") assert get_common_ancestor([no_path]) == tmpdir assert get_common_ancestor([no_path.join("a")]) == tmpdir @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split()) def test_with_ini(self, tmpdir, name) -> None: inifile = tmpdir.join(name) inifile.write("[pytest]\n" if name != "setup.cfg" else "[tool:pytest]\n") a = tmpdir.mkdir("a") b = a.mkdir("b") for args in ([tmpdir], [a], [b]): rootdir, parsed_inifile, _ = determine_setup(None, args) assert rootdir == tmpdir assert parsed_inifile == inifile rootdir, parsed_inifile, _ = determine_setup(None, [b, a]) assert rootdir == tmpdir assert parsed_inifile == inifile @pytest.mark.parametrize("name", "setup.cfg tox.ini".split()) def test_pytestini_overrides_empty_other(self, tmpdir, name) -> None: inifile = tmpdir.ensure("pytest.ini") a = tmpdir.mkdir("a") a.ensure(name) rootdir, parsed_inifile, _ = determine_setup(None, [a]) assert rootdir == tmpdir assert parsed_inifile == inifile def test_setuppy_fallback(self, tmpdir) -> None: a = tmpdir.mkdir("a") a.ensure("setup.cfg") tmpdir.ensure("setup.py") rootdir, inifile, inicfg = determine_setup(None, [a]) assert rootdir == tmpdir assert inifile is None assert inicfg == {} def test_nothing(self, tmpdir, monkeypatch) -> None: monkeypatch.chdir(str(tmpdir)) rootdir, inifile, inicfg = determine_setup(None, [tmpdir]) assert rootdir == tmpdir assert inifile is None assert inicfg == {} def test_with_specific_inifile(self, tmpdir) -> None: inifile = tmpdir.ensure("pytest.ini") rootdir, _, _ = determine_setup(inifile, [tmpdir]) assert rootdir == tmpdir def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch) -> None: monkeypatch.chdir(str(tmpdir)) a = tmpdir.mkdir("a") b = tmpdir.mkdir("b") rootdir, inifile, _ = determine_setup(None, [a, b]) assert rootdir == tmpdir assert inifile is None def test_with_arg_outside_cwd_with_inifile(self, tmpdir) -> None: a = tmpdir.mkdir("a") b = tmpdir.mkdir("b") inifile = a.ensure("pytest.ini") rootdir, parsed_inifile, _ = determine_setup(None, [a, b]) assert rootdir == a assert inifile == parsed_inifile @pytest.mark.parametrize("dirs", ([], ["does-not-exist"], ["a/does-not-exist"])) def test_with_non_dir_arg(self, dirs, tmpdir) -> None: with tmpdir.ensure(dir=True).as_cwd(): rootdir, inifile, _ = determine_setup(None, dirs) assert rootdir == tmpdir assert inifile is None def test_with_existing_file_in_subdir(self, tmpdir) -> None: a = tmpdir.mkdir("a") a.ensure("exist") with tmpdir.as_cwd(): rootdir, inifile, _ = determine_setup(None, ["a/exist"]) assert rootdir == tmpdir assert inifile is None class TestOverrideIniArgs: @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split()) def test_override_ini_names(self, testdir, name): section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]" testdir.tmpdir.join(name).write( textwrap.dedent( """ {section} custom = 1.0""".format( section=section ) ) ) testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("custom", "")""" ) testdir.makepyfile( """ def test_pass(pytestconfig): ini_val = pytestconfig.getini("custom") print('\\ncustom_option:%s\\n' % ini_val)""" ) result = testdir.runpytest("--override-ini", "custom=2.0", "-s") assert result.ret == 0 result.stdout.fnmatch_lines(["custom_option:2.0"]) result = testdir.runpytest( "--override-ini", "custom=2.0", "--override-ini=custom=3.0", "-s" ) assert result.ret == 0 result.stdout.fnmatch_lines(["custom_option:3.0"]) def test_override_ini_pathlist(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): parser.addini("paths", "my new ini value", type="pathlist")""" ) testdir.makeini( """ [pytest] paths=blah.py""" ) testdir.makepyfile( """ import py.path def test_pathlist(pytestconfig): config_paths = pytestconfig.getini("paths") print(config_paths) for cpf in config_paths: print('\\nuser_path:%s' % cpf.basename)""" ) result = testdir.runpytest( "--override-ini", "paths=foo/bar1.py foo/bar2.py", "-s" ) result.stdout.fnmatch_lines(["user_path:bar1.py", "user_path:bar2.py"]) def test_override_multiple_and_default(self, testdir): testdir.makeconftest( """ def pytest_addoption(parser): addini = parser.addini addini("custom_option_1", "", default="o1") addini("custom_option_2", "", default="o2") addini("custom_option_3", "", default=False, type="bool") addini("custom_option_4", "", default=True, type="bool")""" ) testdir.makeini( """ [pytest] custom_option_1=custom_option_1 custom_option_2=custom_option_2 """ ) testdir.makepyfile( """ def test_multiple_options(pytestconfig): prefix = "custom_option" for x in range(1, 5): ini_value=pytestconfig.getini("%s_%d" % (prefix, x)) print('\\nini%d:%s' % (x, ini_value)) """ ) result = testdir.runpytest( "--override-ini", "custom_option_1=fulldir=/tmp/user1", "-o", "custom_option_2=url=/tmp/user2?a=b&d=e", "-o", "custom_option_3=True", "-o", "custom_option_4=no", "-s", ) result.stdout.fnmatch_lines( [ "ini1:fulldir=/tmp/user1", "ini2:url=/tmp/user2?a=b&d=e", "ini3:True", "ini4:False", ] ) def test_override_ini_usage_error_bad_style(self, testdir): testdir.makeini( """ [pytest] xdist_strict=False """ ) result = testdir.runpytest("--override-ini", "xdist_strict", "True") result.stderr.fnmatch_lines( [ "ERROR: -o/--override-ini expects option=value style (got: 'xdist_strict').", ] ) @pytest.mark.parametrize("with_ini", [True, False]) def test_override_ini_handled_asap(self, testdir, with_ini): """-o should be handled as soon as possible and always override what's in ini files (#2238)""" if with_ini: testdir.makeini( """ [pytest] python_files=test_*.py """ ) testdir.makepyfile( unittest_ini_handle=""" def test(): pass """ ) result = testdir.runpytest("--override-ini", "python_files=unittest_*.py") result.stdout.fnmatch_lines(["*1 passed in*"]) def test_addopts_before_initini(self, monkeypatch, _config_for_test, _sys_snapshot): cache_dir = ".custom_cache" monkeypatch.setenv("PYTEST_ADDOPTS", "-o cache_dir=%s" % cache_dir) config = _config_for_test config._preparse([], addopts=True) assert config._override_ini == ["cache_dir=%s" % cache_dir] def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test): """PYTEST_ADDOPTS should not take values from normal args (#4265).""" monkeypatch.setenv("PYTEST_ADDOPTS", "-o") config = _config_for_test with pytest.raises(UsageError) as excinfo: config._preparse(["cache_dir=ignored"], addopts=True) assert ( "error: argument -o/--override-ini: expected one argument (via PYTEST_ADDOPTS)" in excinfo.value.args[0] ) def test_addopts_from_ini_not_concatenated(self, testdir): """addopts from ini should not take values from normal args (#4265).""" testdir.makeini( """ [pytest] addopts=-o """ ) result = testdir.runpytest("cache_dir=ignored") result.stderr.fnmatch_lines( [ "%s: error: argument -o/--override-ini: expected one argument (via addopts config)" % (testdir.request.config._parser.optparser.prog,) ] ) assert result.ret == _pytest.config.ExitCode.USAGE_ERROR def test_override_ini_does_not_contain_paths(self, _config_for_test, _sys_snapshot): """Check that -o no longer swallows all options after it (#3103)""" config = _config_for_test config._preparse(["-o", "cache_dir=/cache", "/some/test/path"]) assert config._override_ini == ["cache_dir=/cache"] def test_multiple_override_ini_options(self, testdir): """Ensure a file path following a '-o' option does not generate an error (#3103)""" testdir.makepyfile( **{ "conftest.py": """ def pytest_addoption(parser): parser.addini('foo', default=None, help='some option') parser.addini('bar', default=None, help='some option') """, "test_foo.py": """ def test(pytestconfig): assert pytestconfig.getini('foo') == '1' assert pytestconfig.getini('bar') == '0' """, "test_bar.py": """ def test(): assert False """, } ) result = testdir.runpytest("-o", "foo=1", "-o", "bar=0", "test_foo.py") assert "ERROR:" not in result.stderr.str() result.stdout.fnmatch_lines(["collected 1 item", "*= 1 passed in *="]) def test_help_via_addopts(testdir): testdir.makeini( """ [pytest] addopts = --unknown-option-should-allow-for-help --help """ ) result = testdir.runpytest() assert result.ret == 0 result.stdout.fnmatch_lines( [ "usage: *", "positional arguments:", # Displays full/default help. "to see available markers type: pytest --markers", ] ) def test_help_and_version_after_argument_error(testdir): testdir.makeconftest( """ def validate(arg): raise argparse.ArgumentTypeError("argerror") def pytest_addoption(parser): group = parser.getgroup('cov') group.addoption( "--invalid-option-should-allow-for-help", type=validate, ) """ ) testdir.makeini( """ [pytest] addopts = --invalid-option-should-allow-for-help """ ) result = testdir.runpytest("--help") result.stdout.fnmatch_lines( [ "usage: *", "positional arguments:", "NOTE: displaying only minimal help due to UsageError.", ] ) result.stderr.fnmatch_lines( [ "ERROR: usage: *", "%s: error: argument --invalid-option-should-allow-for-help: expected one argument" % (testdir.request.config._parser.optparser.prog,), ] ) # Does not display full/default help. assert "to see available markers type: pytest --markers" not in result.stdout.lines assert result.ret == ExitCode.USAGE_ERROR result = testdir.runpytest("--version") result.stderr.fnmatch_lines( ["*pytest*{}*imported from*".format(pytest.__version__)] ) assert result.ret == ExitCode.USAGE_ERROR def test_help_formatter_uses_py_get_terminal_width(monkeypatch): from _pytest.config.argparsing import DropShorterLongHelpFormatter monkeypatch.setenv("COLUMNS", "90") formatter = DropShorterLongHelpFormatter("prog") assert formatter._width == 90 monkeypatch.setattr("py.io.get_terminal_width", lambda: 160) formatter = DropShorterLongHelpFormatter("prog") assert formatter._width == 160 formatter = DropShorterLongHelpFormatter("prog", width=42) assert formatter._width == 42 def test_config_does_not_load_blocked_plugin_from_args(testdir): """This tests that pytest's config setup handles "-p no:X".""" p = testdir.makepyfile("def test(capfd): pass") result = testdir.runpytest(str(p), "-pno:capture") result.stdout.fnmatch_lines(["E fixture 'capfd' not found"]) assert result.ret == ExitCode.TESTS_FAILED result = testdir.runpytest(str(p), "-pno:capture", "-s") result.stderr.fnmatch_lines(["*: error: unrecognized arguments: -s"]) assert result.ret == ExitCode.USAGE_ERROR def test_invocation_args(testdir): """Ensure that Config.invocation_* arguments are correctly defined""" class DummyPlugin: pass p = testdir.makepyfile("def test(): pass") plugin = DummyPlugin() rec = testdir.inline_run(p, "-v", plugins=[plugin]) calls = rec.getcalls("pytest_runtest_protocol") assert len(calls) == 1 call = calls[0] config = call.item.config assert config.invocation_params.args == (p, "-v") assert config.invocation_params.dir == Path(str(testdir.tmpdir)) plugins = config.invocation_params.plugins assert len(plugins) == 2 assert plugins[0] is plugin assert type(plugins[1]).__name__ == "Collect" # installed by testdir.inline_run() # args cannot be None with pytest.raises(TypeError): Config.InvocationParams(args=None, plugins=None, dir=Path()) @pytest.mark.parametrize( "plugin", [ x for x in _pytest.config.default_plugins if x not in _pytest.config.essential_plugins ], ) def test_config_blocked_default_plugins(testdir, plugin): if plugin == "debugging": # Fixed in xdist master (after 1.27.0). # https://github.com/pytest-dev/pytest-xdist/pull/422 try: import xdist # noqa: F401 except ImportError: pass else: pytest.skip("does not work with xdist currently") p = testdir.makepyfile("def test(): pass") result = testdir.runpytest(str(p), "-pno:%s" % plugin) if plugin == "python": assert result.ret == ExitCode.USAGE_ERROR result.stderr.fnmatch_lines( [ "ERROR: not found: */test_config_blocked_default_plugins.py", "(no name '*/test_config_blocked_default_plugins.py' in any of [])", ] ) return assert result.ret == ExitCode.OK if plugin != "terminal": result.stdout.fnmatch_lines(["* 1 passed in *"]) p = testdir.makepyfile("def test(): assert 0") result = testdir.runpytest(str(p), "-pno:%s" % plugin) assert result.ret == ExitCode.TESTS_FAILED if plugin != "terminal": result.stdout.fnmatch_lines(["* 1 failed in *"]) else: assert result.stdout.lines == [] class TestSetupCfg: def test_pytest_setup_cfg_unsupported(self, testdir): testdir.makefile( ".cfg", setup=""" [pytest] addopts = --verbose """, ) with pytest.raises(pytest.fail.Exception): testdir.runpytest() def test_pytest_custom_cfg_unsupported(self, testdir): testdir.makefile( ".cfg", custom=""" [pytest] addopts = --verbose """, ) with pytest.raises(pytest.fail.Exception): testdir.runpytest("-c", "custom.cfg") class TestPytestPluginsVariable: def test_pytest_plugins_in_non_top_level_conftest_unsupported(self, testdir): testdir.makepyfile( **{ "subdirectory/conftest.py": """ pytest_plugins=['capture'] """ } ) testdir.makepyfile( """ def test_func(): pass """ ) res = testdir.runpytest() assert res.ret == 2 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported" res.stdout.fnmatch_lines( [ "*{msg}*".format(msg=msg), "*subdirectory{sep}conftest.py*".format(sep=os.sep), ] ) @pytest.mark.parametrize("use_pyargs", [True, False]) def test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs( self, testdir, use_pyargs ): """When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)""" files = { "src/pkg/__init__.py": "", "src/pkg/conftest.py": "", "src/pkg/test_root.py": "def test(): pass", "src/pkg/sub/__init__.py": "", "src/pkg/sub/conftest.py": "pytest_plugins=['capture']", "src/pkg/sub/test_bar.py": "def test(): pass", } testdir.makepyfile(**files) testdir.syspathinsert(testdir.tmpdir.join("src")) args = ("--pyargs", "pkg") if use_pyargs else () res = testdir.runpytest(*args) assert res.ret == (0 if use_pyargs else 2) msg = ( msg ) = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported" if use_pyargs: assert msg not in res.stdout.str() else: res.stdout.fnmatch_lines(["*{msg}*".format(msg=msg)]) def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest( self, testdir ): subdirectory = testdir.tmpdir.join("subdirectory") subdirectory.mkdir() testdir.makeconftest( """ pytest_plugins=['capture'] """ ) testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py")) testdir.makepyfile( """ def test_func(): pass """ ) res = testdir.runpytest_subprocess() assert res.ret == 2 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported" res.stdout.fnmatch_lines( [ "*{msg}*".format(msg=msg), "*subdirectory{sep}conftest.py*".format(sep=os.sep), ] ) def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives( self, testdir ): subdirectory = testdir.tmpdir.join("subdirectory") subdirectory.mkdir() testdir.makeconftest( """ pass """ ) testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py")) testdir.makeconftest( """ import warnings warnings.filterwarnings('always', category=DeprecationWarning) pytest_plugins=['capture'] """ ) testdir.makepyfile( """ def test_func(): pass """ ) res = testdir.runpytest_subprocess() assert res.ret == 0 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported" assert msg not in res.stdout.str()
{'content_hash': '7b2af0d9fac784cf3b5f152ca16dad98', 'timestamp': '', 'source': 'github', 'line_count': 1482, 'max_line_length': 111, 'avg_line_length': 32.15924426450742, 'alnum_prop': 0.550986151909358, 'repo_name': 'alfredodeza/pytest', 'id': '9035407b76b52a54c410cb0b75f57c5c701cd395', 'size': '47660', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'testing/test_config.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '837013'}]}
var config = { 'port': 8080, 'apiHost': process.env.__OW_API_HOST }; var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var logger = require('./src/logger').getLogger('logs/nodejsaction.log', 'nodejsAction'); /** * instantiate an object which handles REST calls from the Invoker */ var service = require('./src/service').getService(config, logger); app.set('port', config.port); app.use(bodyParser.json({ limit: "48mb" })); app.post('/init', wrapEndpoint(service.initCode)); app.post('/run', wrapEndpoint(service.runCode)); app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).json({ error: "Bad request." }); }); service.start(app); /** * Wraps an endpoint written to return a Promise into an express endpoint, * producing the appropriate HTTP response and closing it for all controlable * failure modes. * * The expected signature for the promise value (both completed and failed) * is { code: int, response: object }. * * @param ep a request=>promise function * @returns an express endpoint handler */ function wrapEndpoint(ep) { return function (req, res) { try { ep(req).then(function (result) { res.status(result.code).json(result.response); }).catch(function (error) { if (typeof error.code === "number" && typeof error.response !== "undefined") { res.status(error.code).json(error.response); } else { logger.error("[wrapEndpoint]", "invalid errored promise", JSON.stringify(error)); res.status(500).json({ error: "Internal error." }); } }); } catch (e) { // This should not happen, as the contract for the endpoints is to // never (externally) throw, and wrap failures in the promise instead, // but, as they say, better safe than sorry. logger.error("[wrapEndpoint]", "exception caught", e); res.status(500).json({ error: "Internal error (exception)." }); } } }
{'content_hash': 'a09d8d30c56b5aece6351939c4216aac', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 101, 'avg_line_length': 32.60606060606061, 'alnum_prop': 0.6068773234200744, 'repo_name': 'prccaraujo/openwhisk', 'id': 'eb818564f84efc7f37bb02e7ed726ccb66b6e99c', 'size': '2953', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'core/nodejsActionBase/app.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '623'}, {'name': 'Java', 'bytes': '42311'}, {'name': 'JavaScript', 'bytes': '129048'}, {'name': 'PHP', 'bytes': '13955'}, {'name': 'Python', 'bytes': '38087'}, {'name': 'Scala', 'bytes': '2158854'}, {'name': 'Shell', 'bytes': '10670'}, {'name': 'Swift', 'bytes': '24731'}]}
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/slidingPanel" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- left panel --> <LinearLayout android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start"> <!--ListView for sliding options--> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@mipmap/violi"/> </LinearLayout> <!-- main panel --> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@mipmap/omprelles"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="end" android:orientation="vertical"> <!-- past walks button--> <Button android:id="@+id/menu1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="20dp" android:layout_marginBottom="10dp" android:background="@color/transparent" android:textStyle="bold" android:textSize="22sp" android:text="@string/menu1" /> <!-- walk of day button--> <Button android:id="@+id/menu2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:background="@color/transparent" android:textStyle="bold" android:textSize="22sp" android:text="@string/menu2" /> <!-- coming soon button--> <Button android:id="@+id/menu3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:background="@color/transparent" android:textStyle="bold" android:textSize="22sp" android:text="@string/menu3" /> <ImageView android:id="@+id/ballarina" android:layout_width="match_parent" android:layout_height="250dp" android:background="@mipmap/ballarina"/> </LinearLayout> </ScrollView> </android.support.v4.widget.SlidingPaneLayout>
{'content_hash': '03b7f5c35349cfd03bd1ee86ea9f832d', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 103, 'avg_line_length': 36.21518987341772, 'alnum_prop': 0.5522544564837469, 'repo_name': 'kikitsa/csd-Thesis', 'id': '2918c88c51a5b96b97e8530a1133ce37806c8547', 'size': '2861', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/activity_main.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '217411'}]}
struct LinkListNode { void* pData; LinkListNode* pNext; }; struct LinkList { LinkListNode* pHead; LinkListNode* pTail; int iNodeCount; }; void InitLinkList(LinkList* pList); void FreeLinkList(LinkList* pList); int AddNode(LinkList* pList, void *pData); void DeleteNode(LinkList* pList, LinkListNode* pNode); struct Stack { LinkList elementList; }; void InitStack(Stack* pStack); void FreeStack(Stack* pStack); int IsStackEmpty(Stack* pStack); void Push(Stack* pStack, void* pData); void Pop(Stack* pStack); void* Peek(Stack* pStack); #endif
{'content_hash': '33c633a096bb9481e442e19fa0a34536', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 54, 'avg_line_length': 19.096774193548388, 'alnum_prop': 0.6976351351351351, 'repo_name': 'Hill1942/ScatterScript', 'id': 'b6826e11e6d630bcf52d80e45e937cc5e80604e0', 'size': '670', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/ssbase_type.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '15320'}, {'name': 'C++', 'bytes': '207712'}, {'name': 'CMake', 'bytes': '322'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#FFF" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="35dp" android:layout_marginLeft="34dp" android:typeface="monospace" android:textSize="13sp" android:gravity="center_vertical" android:id="@+id/hot_name" /> </LinearLayout>
{'content_hash': '396194737a164f5fe7209741aa1b2717', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 72, 'avg_line_length': 33.411764705882355, 'alnum_prop': 0.6602112676056338, 'repo_name': 'Shmilyz/Swap', 'id': 'aac7e199f0d556c95b9193d55a59ced06b3432eb', 'size': '568', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/hot_item.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '790363'}]}
<?php /** * @see Zend_Gdata_YouTube */ //require_once 'Zend/Gdata/YouTube.php'; /** * @see Zend_Gdata_Entry */ //require_once 'Zend/Gdata/Entry.php'; /** * @see Zend_Gdata_Extension_FeedLink */ //require_once 'Zend/Gdata/Extension/FeedLink.php'; /** * @see Zend_Gdata_YouTube_Extension_Description */ //require_once 'Zend/Gdata/YouTube/Extension/Description.php'; /** * @see Zend_Gdata_YouTube_Extension_PlaylistId */ //require_once 'Zend/Gdata/YouTube/Extension/PlaylistId.php'; /** * @see Zend_Gdata_YouTube_Extension_CountHint */ //require_once 'Zend/Gdata/YouTube/Extension/CountHint.php'; /** * Represents the YouTube video playlist flavor of an Atom entry * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_PlaylistListEntry extends Zend_Gdata_Entry { protected $_entryClassName = 'Zend_Gdata_YouTube_PlaylistListEntry'; /** * Nested feed links * * @var array */ protected $_feedLink = array(); /** * Description of this playlist * * @deprecated Deprecated as of version 2 of the YouTube API. * @var Zend_Gdata_YouTube_Extension_Description */ protected $_description = null; /** * Id of this playlist * * @var Zend_Gdata_YouTube_Extension_PlaylistId */ protected $_playlistId = null; /** * CountHint for this playlist. * * @var Zend_Gdata_YouTube_Extension_CountHint */ protected $_countHint = null; /** * Creates a Playlist list entry, representing an individual playlist * in a list of playlists, usually associated with an individual user. * * @param DOMElement $element (optional) DOMElement from which this * object should be constructed. */ public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct($element); } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for sending to the server upon updates, or * for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_description != null) { $element->appendChild($this->_description->getDOM($element->ownerDocument)); } if ($this->_countHint != null) { $element->appendChild($this->_countHint->getDOM($element->ownerDocument)); } if ($this->_playlistId != null) { $element->appendChild($this->_playlistId->getDOM($element->ownerDocument)); } if ($this->_feedLink != null) { foreach ($this->_feedLink as $feedLink) { $element->appendChild($feedLink->getDOM($element->ownerDocument)); } } return $element; } /** * Creates individual Entry objects of the appropriate type and * stores them in the $_entry array based upon DOM data. * * @param DOMNode $child The DOMNode to process */ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('yt') . ':' . 'description': $description = new Zend_Gdata_YouTube_Extension_Description(); $description->transferFromDOM($child); $this->_description = $description; break; case $this->lookupNamespace('yt') . ':' . 'countHint': $countHint = new Zend_Gdata_YouTube_Extension_CountHint(); $countHint->transferFromDOM($child); $this->_countHint = $countHint; break; case $this->lookupNamespace('yt') . ':' . 'playlistId': $playlistId = new Zend_Gdata_YouTube_Extension_PlaylistId(); $playlistId->transferFromDOM($child); $this->_playlistId = $playlistId; break; case $this->lookupNamespace('gd') . ':' . 'feedLink': $feedLink = new Zend_Gdata_Extension_FeedLink(); $feedLink->transferFromDOM($child); $this->_feedLink[] = $feedLink; break; default: parent::takeChildFromDOM($child); break; } } /** * Sets the description relating to the playlist. * * @deprecated Deprecated as of version 2 of the YouTube API. * @param Zend_Gdata_YouTube_Extension_Description $description The description relating to the video * @return Zend_Gdata_YouTube_PlaylistListEntry Provides a fluent interface */ public function setDescription($description = null) { if ($this->getMajorProtocolVersion() >= 2) { $this->setSummary($description); } else { $this->_description = $description; } return $this; } /** * Returns the description relating to the video. * * @return Zend_Gdata_YouTube_Extension_Description The description * relating to the video */ public function getDescription() { if ($this->getMajorProtocolVersion() >= 2) { return $this->getSummary(); } else { return $this->_description; } } /** * Returns the countHint relating to the playlist. * * The countHint is the number of videos on a playlist. * * @throws Zend_Gdata_App_VersionException * @return Zend_Gdata_YouTube_Extension_CountHint The count of videos on * a playlist. */ public function getCountHint() { if (($this->getMajorProtocolVersion() == null) || ($this->getMajorProtocolVersion() == 1)) { //require_once 'Zend/Gdata/App/VersionException.php'; throw new Zend_Gdata_App_VersionException('The yt:countHint ' . 'element is not supported in versions earlier than 2.'); } else { return $this->_countHint; } } /** * Returns the Id relating to the playlist. * * @throws Zend_Gdata_App_VersionException * @return Zend_Gdata_YouTube_Extension_PlaylistId The id of this playlist. */ public function getPlaylistId() { if (($this->getMajorProtocolVersion() == null) || ($this->getMajorProtocolVersion() == 1)) { //require_once 'Zend/Gdata/App/VersionException.php'; throw new Zend_Gdata_App_VersionException('The yt:playlistId ' . 'element is not supported in versions earlier than 2.'); } else { return $this->_playlistId; } } /** * Sets the array of embedded feeds related to the playlist * * @param array $feedLink The array of embedded feeds relating to the video * @return Zend_Gdata_YouTube_PlaylistListEntry Provides a fluent interface */ public function setFeedLink($feedLink = null) { $this->_feedLink = $feedLink; return $this; } /** * Get the feed link property for this entry. * * @see setFeedLink * @param string $rel (optional) The rel value of the link to be found. * If null, the array of links is returned. * @return mixed If $rel is specified, a Zend_Gdata_Extension_FeedLink * object corresponding to the requested rel value is returned * if found, or null if the requested value is not found. If * $rel is null or not specified, an array of all available * feed links for this entry is returned, or null if no feed * links are set. */ public function getFeedLink($rel = null) { if ($rel == null) { return $this->_feedLink; } else { foreach ($this->_feedLink as $feedLink) { if ($feedLink->rel == $rel) { return $feedLink; } } return null; } } /** * Returns the URL of the playlist video feed * * @return string The URL of the playlist video feed */ public function getPlaylistVideoFeedUrl() { if ($this->getMajorProtocolVersion() >= 2) { return $this->getContent()->getSrc(); } else { return $this->getFeedLink(Zend_Gdata_YouTube::PLAYLIST_REL)->href; } } }
{'content_hash': 'a5ef824c516d8014c3d55d7d3e51ec03', 'timestamp': '', 'source': 'github', 'line_count': 281, 'max_line_length': 105, 'avg_line_length': 31.97864768683274, 'alnum_prop': 0.5952592922323614, 'repo_name': 'illibejiep/YiiBoilerplate', 'id': '5330788a45d0bbc5a81a1789eb31683b423f877b', 'size': '9759', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'common/lib/Zend/Gdata/YouTube/PlaylistListEntry.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '49212'}, {'name': 'Batchfile', 'bytes': '1263'}, {'name': 'CSS', 'bytes': '111863'}, {'name': 'Gherkin', 'bytes': '514'}, {'name': 'HTML', 'bytes': '4160678'}, {'name': 'JavaScript', 'bytes': '1744248'}, {'name': 'PHP', 'bytes': '33269841'}, {'name': 'Shell', 'bytes': '273'}]}
namespace Nancy.Tests.Unit.IO { using System; using System.IO; using FakeItEasy; using Nancy.IO; using Xunit; public class RequestStreamFixture { private readonly Stream stream; public RequestStreamFixture() { this.stream = A.Fake<Stream>(); A.CallTo(() => this.stream.CanRead).Returns(true); A.CallTo(() => this.stream.CanSeek).Returns(true); A.CallTo(() => this.stream.CanTimeout).Returns(true); A.CallTo(() => this.stream.CanWrite).Returns(true); } [Fact] public void Should_move_non_seekable_stream_into_seekable_stream_when_stream_switching_is_disabled() { // Given A.CallTo(() => this.stream.CanSeek).Returns(false); // When var result = RequestStream.FromStream(stream, 0, 1, true); // Then result.CanSeek.ShouldBeTrue(); } [Fact] public void Should_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_enabled() { // Given var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); // When var result = RequestStream.FromStream(inputStream, 0, 4, false); // Then result.IsInMemory.ShouldBeFalse(); } [Fact] public void Should_not_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_disabled() { // Given var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); // When var result = RequestStream.FromStream(inputStream, 0, 4, true); // Then result.IsInMemory.ShouldBeTrue(); } [Fact] public void Should_throw_invalidoperationexception_when_created_with_non_readable_stream() { // Given A.CallTo(() => this.stream.CanRead).Returns(false); // When var exception = Record.Exception(() => RequestStream.FromStream(this.stream)); // Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_expected_lenght_is_less_than_zero() { // Given const int expectedLength = -1; // When var exception = Record.Exception(() => RequestStream.FromStream(this.stream, expectedLength)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_thresholdLength_is_less_than_zero() { // Given const int tresholdLength = -1; // When var exception = Record.Exception(() => RequestStream.FromStream(this.stream, 0, tresholdLength)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_work_even_with_a_non_seekable_stream() { var str = A.Fake<Stream>(); A.CallTo(() => str.CanRead).Returns(true); A.CallTo(() => str.CanSeek).Returns(false); A.CallTo(() => str.CanTimeout).Returns(true); A.CallTo(() => str.CanWrite).Returns(true); // Given var request = RequestStream.FromStream(str, 0, 1, false); // When var result = request.CanRead; // Then result.ShouldBeTrue(); } [Fact] public void Should_return_true_when_queried_about_supporting_reading() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.CanRead; // Then result.ShouldBeTrue(); } [Fact] public void Should_return_state_of_underlaying_stream_when_queried_about_supporting_writing() { // Given A.CallTo(() => this.stream.CanWrite).Returns(true); var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.CanWrite; // Then result.ShouldBeTrue(); } [Fact] public void Should_return_true_when_queried_about_supporting_seeking() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.CanSeek; // Then result.ShouldBeTrue(); } [Fact] public void Should_return_false_when_queried_about_supporting_timeout() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.CanTimeout; // Then result.ShouldBeFalse(); } [Fact] public void Should_return_length_of_underlaying_stream() { // Given A.CallTo(() => this.stream.Length).Returns(1234L); var request = RequestStream.FromStream(this.stream, 0, 1235, false); // When var result = request.Length; // Then result.ShouldEqual(1234L); } [Fact] public void Should_return_position_of_underlaying_stream() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); A.CallTo(() => this.stream.Position).Returns(1234L); // When var result = request.Position; // Then result.ShouldEqual(1234L); } [Fact] public void Should_set_position_of_underlaying_stream() { // Given A.CallTo(() => this.stream.Length).Returns(2000L); var request = RequestStream.FromStream(this.stream, 0, 2001, false); // When request.Position = 1234L; // Then this.stream.Position.ShouldEqual(1234L); } [Fact] public void Should_throw_argumentoutofrangexception_when_setting_position_to_less_than_zero() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var exception = Record.Exception(() => request.Position = -1); // Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public void Should_throw_invalidoperationexception_when_position_is_set_to_greater_than_length_of_stream() { // Given A.CallTo(() => this.stream.Length).Returns(100L); var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var exception = Record.Exception(() => request.Position = 1000); // Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public void Should_flush_underlaying_stream() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.Flush(); // Then A.CallTo(() => this.stream.Flush()).MustHaveHappened(); } [Fact] public void Should_throw_notsupportedexception_when_setting_length() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var exception = Record.Exception(() => request.SetLength(10L)); // Then exception.ShouldBeOfType<NotSupportedException>(); } [Fact] public void Should_set_position_of_underlaying_stream_to_zero_when_created() { // Given A.CallTo(() => this.stream.Position).Returns(10); // When var request = RequestStream.FromStream(this.stream, 0, 1, false); // Then this.stream.Position.ShouldEqual(0L); } [Fact] public void Should_seek_in_the_underlaying_stream_when_seek_is_called() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.Seek(10L, SeekOrigin.Current); // Then A.CallTo(() => this.stream.Seek(10L, SeekOrigin.Current)).MustHaveHappened(); } [Fact] public void Should_return_the_new_position_of_the_underlaying_stream_when_seek_is_called() { // Given A.CallTo(() => this.stream.Seek(A<long>.Ignored, A<SeekOrigin>.Ignored)).Returns(100L); var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.Seek(10L, SeekOrigin.Current); // Then result.ShouldEqual(100L); } [Fact] public void Should_read_byte_from_underlaying_stream_when_reading_byte() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.ReadByte(); // Then A.CallTo(() => this.stream.ReadByte()).MustHaveHappened(); } [Fact] public void Should_return_read_byte_from_underlaying_stream_when_readbyte_is_called() { // Given A.CallTo(() => this.stream.ReadByte()).Returns(5); var request = RequestStream.FromStream(this.stream, 0, 1, false); // When var result = request.ReadByte(); // Then result.ShouldEqual(5); } [Fact] public void Should_close_the_underlaying_stream_when_being_closed() { // Given var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.Close(); // Then A.CallTo(() => this.stream.Close()).MustHaveHappened(); } [Fact] public void Should_read_from_underlaying_stream_when_read_is_called() { // Given var buffer = new byte[1]; var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.Read(buffer, 0, buffer.Length); // Then A.CallTo(() => this.stream.Read(buffer, 0, buffer.Length)).MustHaveHappened(); } [Fact] public void Should_return_result_from_reading_underlaying_stream() { // Given var buffer = new byte[1]; var request = RequestStream.FromStream(this.stream, 0, 1, false); A.CallTo(() => this.stream.Read(buffer, 0, buffer.Length)).Returns(3); // When var result = request.Read(buffer, 0, buffer.Length); // Then result.ShouldEqual(3); } [Fact] public void Should_write_to_underlaying_stream_when_write_is_called() { // Given var buffer = new byte[1]; var request = RequestStream.FromStream(this.stream, 0, 1, false); // When request.Write(buffer, 0, buffer.Length); // Then A.CallTo(() => this.stream.Write(buffer, 0, buffer.Length)).MustHaveHappened(); } [Fact] public void Should_no_longer_be_in_memory_if_expected_length_is_greater_or_equal_to_threshold_length() { // Given, When var request = RequestStream.FromStream(this.stream, 1, 0, false); // Then request.IsInMemory.ShouldBeFalse(); } [Fact] public void Should_no_longer_be_in_memory_when_more_bytes_have_been_written_to_stream_then_size_of_the_threshold_and_stream_swapping_is_enabled() { // Given var buffer = new byte[100]; var request = RequestStream.FromStream(this.stream, 0, 10, false); A.CallTo(() => this.stream.Length).Returns(100); // When request.Write(buffer, 0, buffer.Length); // Then request.IsInMemory.ShouldBeFalse(); } [Fact] public void Should_still_be_in_memory_when_more_bytes_have_been_written_to_stream_than_size_of_threshold_and_stream_swapping_is_disabled() { // Given var buffer = new byte[100]; var request = RequestStream.FromStream(this.stream, 0, 10, true); A.CallTo(() => this.stream.Length).Returns(100); // When request.Write(buffer, 0, buffer.Length); // Then request.IsInMemory.ShouldBeTrue(); } [Fact] public void Should_call_beginread_on_underlaying_stream_when_beginread_is_called() { // Given var buffer = new byte[10]; AsyncCallback callback = x => { }; var state = new object(); var request = RequestStream.FromStream(this.stream, 0, 10, true); // When request.BeginRead(buffer, 0, buffer.Length, callback, state); // Then A.CallTo(() => this.stream.BeginRead(buffer, 0, buffer.Length, callback, state)).MustHaveHappened(); } [Fact] public void Should_return_result_from_underlaying_beginread_when_beginread_is_called() { // Given var buffer = new byte[10]; var asyncResult = A.Fake<IAsyncResult>(); AsyncCallback callback = x => { }; var state = new object(); var request = RequestStream.FromStream(this.stream, 0, 10, true); A.CallTo(() => this.stream.BeginRead(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult); // When var result = request.BeginRead(buffer, 0, buffer.Length, callback, state); // Then result.ShouldBeSameAs(asyncResult); } [Fact] public void Should_call_beginwrite_on_underlaying_stream_when_beginwrite_is_called() { // Given var buffer = new byte[10]; AsyncCallback callback = x => { }; var state = new object(); var request = RequestStream.FromStream(this.stream, 0, 10, true); // When request.BeginWrite(buffer, 0, buffer.Length, callback, state); // Then A.CallTo(() => this.stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).MustHaveHappened(); } [Fact] public void Should_return_result_from_underlaying_beginwrite_when_beginwrite_is_called() { // Given var buffer = new byte[10]; var asyncResult = A.Fake<IAsyncResult>(); AsyncCallback callback = x => { }; var state = new object(); var request = RequestStream.FromStream(this.stream, 0, 10, true); A.CallTo(() => this.stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult); // When var result = request.BeginWrite(buffer, 0, buffer.Length, callback, state); // Then result.ShouldBeSameAs(asyncResult); } [Fact] public void Should_call_endread_on_underlaying_stream_when_endread_is_called() { // Given var asyncResult = A.Fake<IAsyncResult>(); var request = RequestStream.FromStream(this.stream, 0, 10, true); // When request.EndRead(asyncResult); // Then A.CallTo(() => this.stream.EndRead(asyncResult)).MustHaveHappened(); } [Fact] public void Should_return_result_from_underlaying_endread_when_endread_is_called() { // Given var asyncResult = A.Fake<IAsyncResult>(); var request = RequestStream.FromStream(this.stream, 0, 10, true); A.CallTo(() => this.stream.EndRead(A<IAsyncResult>.Ignored)).Returns(4); // When var result = request.EndRead(asyncResult); // Then result.ShouldEqual(4); } [Fact] public void Should_call_endwrite_on_underlaying_stream_when_endwrite_is_called() { // Given var asyncResult = A.Fake<IAsyncResult>(); var request = RequestStream.FromStream(this.stream, 0, 10, true); // When request.EndWrite(asyncResult); // Then A.CallTo(() => this.stream.EndWrite(asyncResult)).MustHaveHappened(); } } }
{'content_hash': '79d251964a62fde25108c4ffb31ac957', 'timestamp': '', 'source': 'github', 'line_count': 545, 'max_line_length': 153, 'avg_line_length': 32.159633027522936, 'alnum_prop': 0.5202829919552691, 'repo_name': 'paulcbetts/Nancy', 'id': '755f144113225ca7b95b8397672d1617f5dbe4ee', 'size': '17527', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Nancy.Tests/Unit/IO/RequestStreamFixture.cs', 'mode': '33188', 'license': 'mit', 'language': []}
// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java // W. Tsai, "Moment-preserving thresholding: a new approach," Computer Vision, // Graphics, and Image Processing, vol. 29, pp. 377-393, 1985. // Ported to ImageJ plugin by G.Landini from the the open source project FOURIER 0.8 // by M. Emre Celebi , Department of Computer Science, Louisiana State University in Shreveport // Shreveport, LA 71115, USA // http://sourceforge.net/projects/fourier-ipal // http://www.lsus.edu/faculty/~ecelebi/fourier.htm export default function moments(histogram, total) { // moments const m0 = 1.0; let m1 = 0.0; let m2 = 0.0; let m3 = 0.0; let sum = 0.0; let threshold = -1; const histogramLength = histogram.length; const normalizedHistogram = new Array(histogramLength); for (let i = 0; i < histogramLength; i++) { normalizedHistogram[i] = histogram[i] / total; } /* Calculate the first, second, and third order moments */ for (let i = 0; i < histogramLength; i++) { m1 += i * normalizedHistogram[i]; m2 += i * i * normalizedHistogram[i]; m3 += i * i * i * normalizedHistogram[i]; } /* First 4 moments of the gray-level image should match the first 4 moments of the target binary image. This leads to 4 equalities whose solutions are given in the Appendix of Ref. 1 */ const cd = m0 * m2 - m1 * m1; // determinant of the matriz of hankel for moments 2x2 const c0 = (-m2 * m2 + m1 * m3) / cd; const c1 = (m0 * -m3 + m2 * m1) / cd; // new two gray values where z0<z1 const z0 = 0.5 * (-c1 - Math.sqrt(c1 * c1 - 4.0 * c0)); const z1 = 0.5 * (-c1 + Math.sqrt(c1 * c1 - 4.0 * c0)); const p0 = (z1 - m1) / (z1 - z0); /* Fraction of the object pixels in the target binary image (p0z0+p1z1=m1) */ // The threshold is the gray-level closest to the p0-tile of the normalized histogram for (let i = 0; i < histogramLength; i++) { sum += normalizedHistogram[i]; if (sum > p0) { threshold = i; break; } } return threshold; }
{'content_hash': 'f41e8cde67995a3b1f293c7703c1c2e0', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 106, 'avg_line_length': 40.0, 'alnum_prop': 0.6471153846153846, 'repo_name': 'image-js/core', 'id': '2ed2871d1d25c2861607ba74a548076d6c624d94', 'size': '2080', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/image-js/src/operations/thresholds/moments.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2117'}, {'name': 'JavaScript', 'bytes': '540616'}]}
"use strict"; var fluid = require("gpii-universal"), ffi = require("ffi-napi"), net = require("net"); var jqUnit = fluid.require("node-jqunit"); var gpii = fluid.registerNamespace("gpii"); fluid.registerNamespace("gpii.tests.serviceHandler"); process.env.GPII_SERVICE_PIPE_DISABLED = true; require("../index.js"); jqUnit.module("gpii.tests.serviceHandler"); gpii.tests.serviceHandler.kernel32 = ffi.Library("kernel32", { // https://msdn.microsoft.com/library/ms687032 "WaitForSingleObject": [ "ulong", ["uint", "ulong"] ], // https://msdn.microsoft.com/library/ms682396 "CreateEventW": [ "ulong", [ "int", "int", "int", "int" ] ] }); jqUnit.asyncTest("serviceChallenge tests", function () { var badHandles = [ null, "", 0, "0", 123, "123", "text" ]; // Try some invalid data. Nothing is expected to happen, it shouldn't crash. badHandles.forEach(function (handle) { fluid.log("serviceChallenge - trying: ", handle); gpii.windows.service.serviceChallenge(handle); }); // Try a real event handle. var eventHandle = gpii.tests.serviceHandler.kernel32.CreateEventW(0, false, false, 0); var timeout = 5000; gpii.tests.serviceHandler.kernel32.WaitForSingleObject.async(eventHandle, timeout, function (err, result) { if (err) { jqUnit.fail(err); } else { var WAIT_OBJECT_0 = 0; jqUnit.assertEquals("WaitForSingleObject should return WAIT_OBJECT_0", WAIT_OBJECT_0, result); jqUnit.start(); } }); gpii.windows.service.serviceChallenge(eventHandle); }); jqUnit.asyncTest("connectToService failure tests", function () { var tests = [ "aa", 123, "a:", ":a", "pipe:", "pipe:a/b", "pipe:a\\b", "pipe:aa bb", "pipe:aa/bb", "pipe:aa\nbb", "pipe:201-valid-characters-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ]; jqUnit.expect(tests.length * 3 + 4); var serviceHandler = gpii.windows.service.serviceHandler({ listeners: { // Don't auto-connect. "onCreate.connectToService": "fluid.identity" } }); var runTest = function (testIndex) { if (testIndex >= tests.length) { jqUnit.start(); return; } var test = tests[testIndex]; process.env.GPII_SERVICE_PIPE = test; var promise = serviceHandler.connectToService(); jqUnit.assertNotNull("connectToService must return non-null", promise); jqUnit.assertTrue("connectToService must return a promise", fluid.isPromise(promise)); promise.then(function () { jqUnit.fail("connectToService should have rejected"); }, function (e) { jqUnit.assertUndefined("connectToService should reject with undefined", e); runTest(testIndex + 1); }); }; // Test a valid name, but doesn't exist. process.env.GPII_SERVICE_PIPE = "pipe:test-not-exist" + Math.random().toString(36); var promise = serviceHandler.connectToService(); jqUnit.assertNotNull("connectToService must return non-null", promise); jqUnit.assertTrue("connectToService must return a promise", fluid.isPromise(promise)); promise.then(function () { jqUnit.fail("connectToService should have rejected"); }, function (e) { jqUnit.assertTrue("connectToService should reject with an error", e.isError); jqUnit.assertEquals("connectToService should reject with ENOENT", "ENOENT", e.error && e.error.code); runTest(0); }); }); jqUnit.asyncTest("connectToService tests", function () { var tests = [ { data: "challenge:none\nOK\n", expect: "resolve" }, { data: "challenge:1\nOK\n", expect: "resolve" }, { data: "challenge:2\nOK\n", expect: "resolve" }, { data: "challenge:A\nOK\n", expect: "reject" }, { data: "challenge:1\nchallenge:2\nOK\n", expect: "reject" }, { data: "stupid value\n", expect: "reject" }, { data: "OK\n", expect: "resolve" }, { data: null, disconnect: true, expect: "reject" }, { data: "challenge:1\n", disconnect: true, expect: "reject" }, { data: "challenge:none\n", disconnect: true, expect: "reject" }, { data: "challenge:none\nOK\n", disconnect: true, expect: "resolve" } ]; var serviceHandler = gpii.windows.service.serviceHandler({ listeners: { // Don't auto-connect. "onCreate.connectToService": "fluid.identity" }, reconnect: false }); var pipeIdPrefix = "test-connectToService-" + Math.random().toString(36); var runTest = function (testIndex) { if (testIndex >= tests.length) { jqUnit.start(); return; } var test = tests[testIndex]; var pipeId = pipeIdPrefix + testIndex; var pipeName = serviceHandler.options.pipePrefix + pipeId; var pipeServer = net.createServer(); var closed = 0; pipeServer.on("error", jqUnit.fail); pipeServer.listen(pipeName, function () { process.env.GPII_SERVICE_PIPE = "pipe:" + pipeId; var promise = serviceHandler.connectToService(); jqUnit.assertNotNull("connectToService must return non-null", promise); jqUnit.assertTrue("connectToService must return a promise", fluid.isPromise(promise)); promise.then(function () { jqUnit.assertEquals("connectToService must only resolve if expected", test.expect, "resolve"); runTest(testIndex + 1); }, function () { jqUnit.assertEquals("connectToService must only reject if expected", test.expect, "reject"); // Wait for the pipe to close. gpii.windows.waitForCondition(function () { return closed; }, { timeout: 5000, dontReject: true }).then(function (value) { jqUnit.assertNotEquals("connectToService should have closed the pipe", "timeout", value); runTest(testIndex + 1); }, jqUnit.fail); }); }); pipeServer.on("connection", function (pipe) { fluid.log("pipeServer.connection"); pipe.on("data", function (data) { fluid.log("pipeServer.data", data.toString()); }); pipe.on("close", function () { closed = true; }); if (test.data) { fluid.log("Sending ", test.data.replace(/\n/g, "\\n")); pipe.write(test.data); } if (test.disconnect) { fluid.log("Disconnecting"); pipe.destroy(); } }); }; runTest(0); }); jqUnit.test("status request tests", function () { var requestHandler = gpii.windows.service.requestHandler(); var result = requestHandler.status(); jqUnit.assertTrue("status should return an object", fluid.isPlainObject(result)); jqUnit.assertTrue("status should be 'running'", result.isRunning); requestHandler.destroy(); }); jqUnit.test("shutdown request tests", function () { var requestHandler = gpii.windows.service.requestHandler(); var sendMessageCalled = false; // Mock the sendMessage, instead of sending the real shutdown message. var sendMessageOrig = gpii.windows.messages.sendMessage; gpii.windows.messages.sendMessage = function (window, msg) { jqUnit.assertEquals("sendMessage should be called with the correct window", "gpii-message-window", window); jqUnit.assertEquals("sendMessage should be called with the correct message", gpii.windows.API_constants.WM_QUERYENDSESSION, msg); sendMessageCalled = true; }; try { requestHandler.shutdown(); jqUnit.assertTrue("sendMessage should have been invoked", sendMessageCalled); } finally { gpii.windows.messages.sendMessage = sendMessageOrig; } });
{'content_hash': '14f30d00eec21e4bca6d466474345f9f', 'timestamp': '', 'source': 'github', 'line_count': 296, 'max_line_length': 119, 'avg_line_length': 29.75337837837838, 'alnum_prop': 0.5705688656750312, 'repo_name': 'GPII/windows', 'id': '89cd74fa128cbd0b3b09d5f884ebd66d155a379a', 'size': '9413', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gpii/node_modules/gpii-service-handler/test/serviceHandlerTests.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '34676'}, {'name': 'JavaScript', 'bytes': '188121'}, {'name': 'PowerShell', 'bytes': '11538'}]}
from __future__ import print_function """ This file contains a sample AWS Lambda function that can be called from the UserCare service. This function should taken as a sample. It isn't as robust as a real function might need to be. We treat Zoho as the source and call it to retrieve the information and then push it into UserCare's database. This function has two call modes: `ticket_created` and `session`. `ticket_created` event types are called immediately upon creation of a ticket by the end user. It is expected that this function will update the user profile in UserCare quite quickly. The aim is that the call will complete before the agent opens the ticket, which could be a matter of a few seconds. `session` event types are called whenever the user creates a new session. As this happens all the time it is recommended that you store the customer id or IDFA to one side (maybe in a DynamoDB data store) and then periodically process the list and update UserCare in the background. """ import base64 from datetime import datetime, timedelta, tzinfo import json import logging import pytz import requests import pprint import sys # Settings for the web service connection to update the UserCare user profile PUBLISHER_ADMIN_USERNAME = u'CHANGE_THIS_TO_ADMIN_USER_INFO' PUBLISHER_ADMIN_PASSWORD = u'CHANGE_THIS_TO_ADMIN_USER_PASSWORD' PUBLISHER_API_KEY = u'CHANGE_THIS_TO_YOUR_API_KEY' # Setting for your CRM of choice (other systems might use different auth mechanisms) CRM_KEY = u'CHANGE_THIS_TO_ZOHO_CRM_API_KEY' # Constants # The UserCare host for the web service CUSTOMER_SYNC_HOST = u'sync.usercare.com' # The overall URL for the web service CUSTOMER_SYNC_URL = u'https://' + CUSTOMER_SYNC_HOST + u'/api/v1/' + PUBLISHER_API_KEY + u'/sync_customers' # The authentication header for the web service HTTP_BASIC_AUTHORIZATION = base64.b64encode(PUBLISHER_ADMIN_USERNAME + u':' + PUBLISHER_ADMIN_PASSWORD) # Logging - reduce level to WARNING or ERROR for production logging.basicConfig(level=logging.INFO) logger = logging.getLogger() def lambda_handler(event, context): """ AWS Lambda Function main entry point. Accepts the following event parameters: event_type - Event type triggering invocation, 'session' or 'ticket_created'. id - Externally defined customer id set via SDK or customer sync, optional. IDFA - Device identification supplied if id not set, optional. timestamp - Customer sync timestamp, ('2016-01-01T00:00:00.000Z', UTC), optional. When the UserCare server sends these events all the fields will be present. However, some of the values may be set to None in the event. Your code should check for that an handle accordingly. """ # Extract customer sync parameters from the event # To facilitate lookups, id param can be CRM id or an email address event_type = event.get('event_type','session') id = event.get('id',None) IDFA = event.get('IDFA',None) timestamp = parse_iso_8601_timestamp(event.get('timestamp',u'2016-05-29T11:45:13.381Z')) logger.info("got event: " + json.dumps(event)) # Ensure that the timestamp of last sync update was more than 10 seconds ago customer_sync_data_timestamp = pytz.UTC.localize(datetime.now()) if timestamp is not None and (customer_sync_data_timestamp - timestamp).total_seconds() < 10: logger.info("Last update was less than 10 seconds ago") return fields = search_zoho_id(id) if fields is None: email = id fields = search_zoho_email(email) # Build customer sync data object customer_sync_data = { u'customers': [{ u'id': content_of_val(fields, "CONTACTID"), u'IDFA': IDFA, u'email': content_of_val(fields, "Email"), u'first_name': content_of_val(fields, "First Name"), u'last_name': content_of_val(fields, "Last Name"), u'first_session': format_iso_8601_timestamp(parse_iso_8601_timestamp(u'2016-01-01T00:00:00.000Z')), u'properties': { u'Salutation': content_of_val(fields, "Salutation"), u'Title': content_of_val(fields, "Title"), }, u'timestamp': format_iso_8601_timestamp(customer_sync_data_timestamp) }] } # Convert the data structure to JSON to post to UserCare customer_sync_data_json = json.dumps(customer_sync_data) # Asynchronous sync customer data request response = requests.post(CUSTOMER_SYNC_URL, data=customer_sync_data_json, headers={ u'Authorization': u'Basic ' + HTTP_BASIC_AUTHORIZATION, u'Content-Type': u'application/json' }) # Raise and error back to the Lambda function caller if the sync fails if response.status_code != 200: raise RuntimeError(u'Customer sync post failed, status: {0}, message: {1}'.format(response.status_code, response.content)) # Check sync customer response to make sure we have no errors response_json = json.loads(response.content) created_count = response_json[u'created_count'] updated_count = response_json[u'updated_count'] error_count = response_json[u'error_count'] # If we do raise an error back to the Lambda function caller if error_count != 0: raise RuntimeError(u'Customer sync post response errors: {0}'.format(error_count)) # Send response back to caller return None def content_of_val(list, arg): for value in list: if value['val'] == arg: return (value['content']) # no need to return None on no match, Python handles that def search_zoho_email(email): zhContact = requests.get('https://crm.zoho.com/crm/private/json/Contacts/searchRecords?authtoken=' + CRM_KEY + '&scope=crmapi&criteria=(email:' + email + ')') data = zhContact.json() # useful for object format & debugging #pprint.pprint(data) try: return data['response']['result']['Contacts']['row']['FL'] except KeyError: logger.info("miss on email") return None def search_zoho_id(id): zhContact = requests.get('https://crm.zoho.com/crm/private/json/Contacts/getSearchRecordsByPDC?authtoken='+ CRM_KEY + '&scope=crmapi&searchColumn=contactid&searchValue=' + id) data = zhContact.json() # useful for object format & debugging #pprint.pprint(data) try: return data['response']['result']['Contacts']['row']['FL'] except KeyError: logger.info("miss on id") return None class UtcTZInfo(tzinfo): """ UTC timezone used for timestamps. """ def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return timedelta(0) UTC = UtcTZInfo() def parse_iso_8601_timestamp(timestamp): """ Parse ISO 8601 formatted timestamp strings. :param timestamp: UTC timestamp in ISO 8601 format :return: UTC datetime timestamp """ if timestamp is None or len(timestamp) != 24 or timestamp[-1] != 'Z': return None return datetime.strptime(timestamp[:-1]+u'000', u'%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=UTC) def format_iso_8601_timestamp(timestamp): """ Format datetime ISO 8601 formatted timestamp strings. :param timestamp: UTC datetime timestamp :return: UTC timestamp in ISO 8601 format """ if timestamp is None: return None return timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3]+'Z' if __name__ == '__main__': """ Command line main entry point. Usage: Examples: `> python aws-zoho.py ticket_created -id 1832093000000383491` `> python aws-zoho.py ticket_created -id fsmith@example.com` `> python aws-zoho.py session -idfa AEBE52E7-03EE-455A-B3C4-E57283966239` """ # Parse command line arguments event_type = unicode(sys.argv[1]) id = None IDFA = None if sys.argv[2] == '-id': id = unicode(sys.argv[3]) elif sys.argv[2] == '-idfa': IDFA = unicode(sys.argv[3]) timestamp = unicode(sys.argv[4]) if len(sys.argv) == 5 else None # Invoke AWS Lambda Function handler lambda_handler({ u'event_type': event_type, u'id': id, u'IDFA': IDFA, u'timestamp': timestamp }, None)
{'content_hash': '57262773fca03c2988913f689340c829', 'timestamp': '', 'source': 'github', 'line_count': 222, 'max_line_length': 179, 'avg_line_length': 37.648648648648646, 'alnum_prop': 0.6709739172050729, 'repo_name': 'usercare/demo-code', 'id': '9e6e0effde29fd8a295589769408f4a1581bcbf0', 'size': '8358', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lambda/aws-zoho.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '77625'}, {'name': 'JavaScript', 'bytes': '3560'}, {'name': 'Python', 'bytes': '26999'}]}
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>exist-book</groupId> <artifactId>build-parent</artifactId> <version>1.0</version> <relativePath>../../../build-parent</relativePath> </parent> <artifactId>webdav-client-examples</artifactId> <packaging>pom</packaging> <name>WebDAV Client Examples</name> <modules> <module>webdav-client-parent</module> <module>webdav-client-common</module> <module>webdav-client-retrieve</module> <module>webdav-client-store</module> </modules> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptors> <descriptor>assembly.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{'content_hash': 'bde21bb87f761611591ef9271dc75198', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 104, 'avg_line_length': 33.1875, 'alnum_prop': 0.5128688010043942, 'repo_name': 'npuddu/git', 'id': 'c6da1abf555866f3632041e63a88fe718371645a', 'size': '1593', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'chapters/integration/webdav-client/pom.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '10361'}, {'name': 'Java', 'bytes': '134721'}, {'name': 'Python', 'bytes': '2400'}, {'name': 'XQuery', 'bytes': '95711'}, {'name': 'XSLT', 'bytes': '3817'}]}
#define WINDOWS_PHONE #define SILVERLIGHT // =============================================================================== // Guard.cs // .NET Image Tools // =============================================================================== // Copyright (c) .NET Image Tools Development Group. // All rights reserved. // =============================================================================== using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace ImageTools.Helpers { /// <summary> /// A static class with a lot of helper methods, which guards /// a method agains invalid parameters. /// </summary> public static class Guard { /// <summary> /// Verifies that the specified value is between a lower and a upper value /// and throws an exception, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is not between /// the lower and the upper value.</exception> public static void Between<TValue>(TValue target, TValue lower, TValue upper, string parameterName) where TValue : IComparable { if (!target.IsBetween(lower, upper)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Value must be between {0} and {1}", lower, upper), parameterName); } } /// <summary> /// Verifies that the specified value is between a lower and a upper value /// and throws an exception with the passed message, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <param name="message">The message for the exception.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is not between /// the lower and the upper value.</exception> public static void Between<TValue>(TValue target, TValue lower, TValue upper, string parameterName, string message) where TValue : IComparable { if (!target.IsBetween(lower, upper)) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies that the specified value is greater than a lower value /// and throws an exception, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void GreaterThan<TValue>(TValue target, TValue lower, string parameterName) where TValue : IComparable { if (target.CompareTo(lower) <= 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Value must be greater than {0}", lower), parameterName); } } /// <summary> /// Verifies that the specified value is greater than a lower value /// and throws an exception with the passed message, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void GreaterThan<TValue>(TValue target, TValue lower, string parameterName, string message) where TValue : IComparable { if (target.CompareTo(lower) <= 0) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies that the specified value is greater or equals than a lower value /// and throws an exception, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void GreaterEquals<TValue>(TValue target, TValue lower, string parameterName) where TValue : IComparable { if (target.CompareTo(lower) < 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Value must be greater than {0}", lower), parameterName); } } /// <summary> /// Verifies that the specified value is greater or equals than a lower value /// and throws an exception with the passed message, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="lower">The lower value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void GreaterEquals<TValue>(TValue target, TValue lower, string parameterName, string message) where TValue : IComparable { if (target.CompareTo(lower) < 0) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies that the specified value is less than a upper value /// and throws an exception, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void LessThan<TValue>(TValue target, TValue upper, string parameterName) where TValue : IComparable { if (target.CompareTo(upper) <= 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Value must be less than {0}", upper), parameterName); } } /// <summary> /// Verifies that the specified value is less than a upper value /// and throws an exception with the passed message, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void LessThan<TValue>(TValue target, TValue upper, string parameterName, string message) where TValue : IComparable { if (target.CompareTo(upper) <= 0) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies that the specified value is less or equals than a upper value /// and throws an exception, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void LessEquals<TValue>(TValue target, TValue upper, string parameterName) where TValue : IComparable { if (target.CompareTo(upper) > 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Value must be less than {0}", upper), parameterName); } } /// <summary> /// Verifies that the specified value is less or equals than a upper value /// and throws an exception with the passed message, if not. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="target">The target value, which should be validated.</param> /// <param name="upper">The upper value.</param> /// <param name="parameterName">Name of the parameter, which should will be checked.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentException"><paramref name="target"/> is greater than /// the lower value.</exception> public static void LessEquals<TValue>(TValue target, TValue upper, string parameterName, string message) where TValue : IComparable { if (target.CompareTo(upper) > 0) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies, that the collection method parameter with specified reference /// contains one or more elements and throws an exception /// if the object contains no elements. /// </summary> /// <typeparam name="TType">The type of the items in the collection.</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="parameterName">Name of the parameter.</param> /// <exception cref="ArgumentException"><paramref name="enumerable"/> is /// empty or contains only blanks.</exception> public static void NotEmpty<TType>(ICollection<TType> enumerable, string parameterName) { if (enumerable == null) { throw new ArgumentNullException("enumerable"); } if (enumerable.Count == 0) { throw new ArgumentException("Collection does not contain an item", parameterName); } } /// <summary> /// Verifies, that the collection method parameter with specified reference /// contains one or more elements and throws an exception with /// the passed message if the object contains no elements. /// </summary> /// <typeparam name="TType">The type of the items in the collection.</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="parameterName">Name of the parameter.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentException"><paramref name="enumerable"/> is /// empty or contains only blanks.</exception> public static void NotEmpty<TType>(ICollection<TType> enumerable, string parameterName, string message) { if (enumerable == null) { throw new ArgumentNullException("enumerable"); } if (enumerable.Count == 0) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Verifies, that the method parameter with specified object value and message /// is not null and throws an exception if the object is null. /// </summary> /// <param name="target">The target object, which cannot be null.</param> /// <param name="parameterName">Name of the parameter.</param> /// <exception cref="ArgumentNullException"><paramref name="target"/> is /// null (Nothing in Visual Basic).</exception> public static void NotNull(object target, string parameterName) { if (target == null) { throw new ArgumentNullException(parameterName); } } /// <summary> /// Verifies, that the method parameter with specified object value and message /// is not null and throws an exception with the passed message if the object is null. /// </summary> /// <param name="target">The target object, which cannot be null.</param> /// <param name="parameterName">Name of the parameter.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentNullException"><paramref name="target"/> is /// null (Nothing in Visual Basic).</exception> /// <example> /// Use the following code to validate a parameter: /// <code> /// // A method with parameter 'name' which cannot be null. /// public void MyMethod(string name) /// { /// Guard.NotNull(name, "name", "Name is null!"); /// } /// </code> /// </example> public static void NotNull(object target, string parameterName, string message) { if (target == null) { throw new ArgumentNullException(message, parameterName); } } /// <summary> /// Verifies, that the string method parameter with specified object value and message /// is not null, not empty and does not contain only blanls and throws an exception /// if the object is null. /// </summary> /// <param name="target">The target string, which should be checked against being null or empty.</param> /// <param name="parameterName">Name of the parameter.</param> /// <exception cref="ArgumentNullException"><paramref name="target"/> is /// null (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="target"/> is /// empty or contains only blanks.</exception> public static void NotNullOrEmpty(string target, string parameterName) { if (target == null) { throw new ArgumentNullException(parameterName); } if (string.IsNullOrEmpty(target) || target.Trim().Equals(string.Empty)) { throw new ArgumentException("String parameter cannot be null or empty and cannot contain only blanks.", parameterName); } } /// <summary> /// Verifies, that the string method parameter with specified object value and message /// is not null, not empty and does not contain only blanls and throws an exception with /// the passed message if the object is null. /// </summary> /// <param name="target">The target string, which should be checked against being null or empty.</param> /// <param name="parameterName">Name of the parameter.</param> /// <param name="message">The message for the exception to throw.</param> /// <exception cref="ArgumentNullException"><paramref name="target"/> is /// null (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="target"/> is /// empty or contains only blanks.</exception> public static void NotNullOrEmpty(string target, string parameterName, string message) { if (target == null) { throw new ArgumentNullException(parameterName); } if (string.IsNullOrEmpty(target) || target.Trim().Equals(string.Empty)) { throw new ArgumentException(message, parameterName); } } } }
{'content_hash': 'a9503b84266ed37bfbb68aa393fe2653', 'timestamp': '', 'source': 'github', 'line_count': 351, 'max_line_length': 153, 'avg_line_length': 49.57549857549858, 'alnum_prop': 0.599505775530142, 'repo_name': 'wwqly12/Snaker', 'id': '6a384dfdc471827af42c7214b758f0d74b3d73f2', 'size': '17403', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Assets/Plugins/Reign/Platforms/Shared/ImageTools/Common/Helpers/Guard.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '3653340'}, {'name': 'JavaScript', 'bytes': '2544'}, {'name': 'Objective-C', 'bytes': '50061'}, {'name': 'Objective-C++', 'bytes': '69207'}]}
class Sns::Login::EnvironmentController < ApplicationController include Sns::BaseFilter include Sns::LoginFilter skip_before_action :verify_authenticity_token, raise: false, only: :consume skip_before_action :logged_in? before_action :set_item model Sys::Auth::Environment private def set_item @item ||= @model.find_by(filename: params[:id]) raise "404" if @item.blank? end public def login key = @item.keys.find do |key| request.env[key].present? end if key.blank? render_login nil, nil return end uid_or_email = request.env[key] user = SS::User.uid_or_email(uid_or_email).and_enabled.and_unlocked.first if user.blank? render_login nil, nil return end render_login user, nil, session: true end end
{'content_hash': '34dee6f1c7ea311e298e26e439d5d760', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 77, 'avg_line_length': 21.18421052631579, 'alnum_prop': 0.6658385093167701, 'repo_name': 'shirasagi/ss-handson', 'id': '66d3eb8de3dc6b45004bf2667971005d90fa34fd', 'size': '805', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/sns/login/environment_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '499975'}, {'name': 'HTML', 'bytes': '2587734'}, {'name': 'JavaScript', 'bytes': '4924103'}, {'name': 'Ruby', 'bytes': '6070866'}, {'name': 'Shell', 'bytes': '20799'}]}
* { padding: 0; margin: 0; box-sizing: border-box; } body, html { overflow: hidden; } /* Header */ header { position: absolute; z-index: 1001; top: 20px; right: 20px; color: white; text-align: right; } header h1 { font-family: Lato, Arial, Tahoma Helvetica, sans-serif; font-size: 32px; text-transform: uppercase; } header h2 { font-family: "Times New Roman", Times, serif; font-style: italic; font-weight: normal; letter-spacing: 1px; font-size: 11px; color: rgba(255, 255, 255, .5); } header h2 a { color: rgba(255, 255, 255, .5); } /* Soundtrack */ section.soundtrack { position: absolute; z-index: 1001; bottom: 20px; right: 20px; background-color: rgba(0, 0, 0, .5); padding: 10px; } section.soundtrack img { width: 100px; float: left; overflow: hidden; border: 3px solid white; } section.soundtrack ul.information { width: 200px; list-style-type: none; float: left; margin: 25px 0 0 15px; overflow: hidden; } section.soundtrack ul.information li { font-family: Lato, Arial, Tahoma Helvetica, sans-serif; color: white; } section.soundtrack ul.information li h3 { color: white; } section.soundtrack ul.information li a { text-transform: uppercase; color: lightgray; font-size: 11px; } /* Background */ section.background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: transparent url('../../images/background.png') no-repeat; background-size: cover; } section.border { position: absolute; top: 0; left: 0; z-index: 20001; pointer-events: none; width: 100%; height: 100%; box-shadow: inset 0 0 0 5px white; } /* Visualiser */ audio { display: none; } section.visualiser { position: absolute; z-index: 102; top: 0; left: 0; width: 100%; height: 100%; } div.canvas-container { position: relative; } section.visualiser svg { position: absolute; z-index: 103; top: 0; left: 0; width: 100%; height: 100%; opacity: .75; animation: amelie-rotation 45s infinite linear; -o-animation: amelie-rotation 45s infinite linear; -moz-animation: amelie-rotation 45s infinite linear; -webkit-animation: amelie-rotation 45s infinite linear; }
{'content_hash': '763fc9319cd386375279c833bee6b6d2', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 73, 'avg_line_length': 17.36231884057971, 'alnum_prop': 0.6151919866444073, 'repo_name': 'Wildhoney/Amelie', 'id': '888a425b95d4cab5ee1c1e066c8b83608c5abdec', 'size': '2396', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/Amelie.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8581'}, {'name': 'HTML', 'bytes': '1502'}, {'name': 'JavaScript', 'bytes': '25403'}]}
from test_fena.test_common import test_cmd def test_scoreboards(): test_cmd("@s _ti = players _ti2", "scoreboard players operation @s fena.ti = players fena.ti2") test_cmd("@s _ti = @r _ti2", "scoreboard players operation @s fena.ti = @r fena.ti2") test_cmd("@s _ti = @r", "scoreboard players operation @s fena.ti = @r fena.ti") test_cmd("@s _ti = 3", "scoreboard players set @s fena.ti 3") test_cmd(r"@s _ti = 3 {Nbt:1b}", r"scoreboard players set @s fena.ti 3 {Nbt:1b}") test_cmd("target _ti = players _ti2", "scoreboard players operation target fena.ti = players fena.ti2") test_cmd("target _ti = @r _ti2", "scoreboard players operation target fena.ti = @r fena.ti2") test_cmd("target _ti = @r", "scoreboard players operation target fena.ti = @r fena.ti") test_cmd("target _ti = 3", "scoreboard players set target fena.ti 3") test_cmd(r"target _ti = 3 {Nbt:1b}", r"scoreboard players set target fena.ti 3 {Nbt:1b}") test_cmd("setblock _ti = players _ti2", "scoreboard players operation setblock fena.ti = players fena.ti2") test_cmd("setblock _ti = @r _ti2", "scoreboard players operation setblock fena.ti = @r fena.ti2") test_cmd("setblock _ti = @r", "scoreboard players operation setblock fena.ti = @r fena.ti") test_cmd("setblock _ti = 3", "scoreboard players set setblock fena.ti 3") test_cmd(r"setblock _ti = 3 {Nbt:1b}", r"scoreboard players set setblock fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation @s fena.ti = players fena.ti2") test_cmd("scoreboard players operation @s fena.ti = @r fena.ti2") test_cmd("scoreboard players set @s fena.ti 3") test_cmd(r"scoreboard players set @s fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation target fena.ti = players fena.ti2") test_cmd("scoreboard players operation target fena.ti = @r fena.ti2") test_cmd("scoreboard players set target fena.ti 3") test_cmd(r"scoreboard players set target fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation setblock fena.ti = players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti = @r fena.ti2") test_cmd("scoreboard players set setblock fena.ti 3") test_cmd(r"scoreboard players set setblock fena.ti 3 {Nbt:1b}") test_cmd("@s _ti += players _ti2", "scoreboard players operation @s fena.ti += players fena.ti2") test_cmd("@s _ti += @r _ti2", "scoreboard players operation @s fena.ti += @r fena.ti2") test_cmd("@s _ti += @r", "scoreboard players operation @s fena.ti += @r fena.ti") test_cmd("@s _ti += 3", "scoreboard players add @s fena.ti 3") test_cmd(r"@s _ti += 3 {Nbt:1b}", r"scoreboard players add @s fena.ti 3 {Nbt:1b}") test_cmd("target _ti += players _ti2", "scoreboard players operation target fena.ti += players fena.ti2") test_cmd("target _ti += @r _ti2", "scoreboard players operation target fena.ti += @r fena.ti2") test_cmd("target _ti += @r", "scoreboard players operation target fena.ti += @r fena.ti") test_cmd("target _ti += 3", "scoreboard players add target fena.ti 3") test_cmd(r"target _ti += 3 {Nbt:1b}", r"scoreboard players add target fena.ti 3 {Nbt:1b}") test_cmd("setblock _ti += players _ti2", "scoreboard players operation setblock fena.ti += players fena.ti2") test_cmd("setblock _ti += @r _ti2", "scoreboard players operation setblock fena.ti += @r fena.ti2") test_cmd("setblock _ti += @r", "scoreboard players operation setblock fena.ti += @r fena.ti") test_cmd("setblock _ti += 3", "scoreboard players add setblock fena.ti 3") test_cmd(r"setblock _ti += 3 {Nbt:1b}", r"scoreboard players add setblock fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation @s fena.ti += players fena.ti2") test_cmd("scoreboard players operation @s fena.ti += @r fena.ti2") test_cmd("scoreboard players add @s fena.ti 3") test_cmd(r"scoreboard players add @s fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation target fena.ti += players fena.ti2") test_cmd("scoreboard players operation target fena.ti += @r fena.ti2") test_cmd("scoreboard players add target fena.ti 3") test_cmd(r"scoreboard players add target fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation setblock fena.ti += players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti += @r fena.ti2") test_cmd("scoreboard players add setblock fena.ti 3") test_cmd(r"scoreboard players add setblock fena.ti 3 {Nbt:1b}") test_cmd("@s _ti -= players _ti2", "scoreboard players operation @s fena.ti -= players fena.ti2") test_cmd("@s _ti -= @r _ti2", "scoreboard players operation @s fena.ti -= @r fena.ti2") test_cmd("@s _ti -= @r", "scoreboard players operation @s fena.ti -= @r fena.ti") test_cmd("@s _ti -= 3", "scoreboard players remove @s fena.ti 3") test_cmd(r"@s _ti -= 3 {Nbt:1b}", r"scoreboard players remove @s fena.ti 3 {Nbt:1b}") test_cmd("target _ti -= players _ti2", "scoreboard players operation target fena.ti -= players fena.ti2") test_cmd("target _ti -= @r _ti2", "scoreboard players operation target fena.ti -= @r fena.ti2") test_cmd("target _ti -= @r", "scoreboard players operation target fena.ti -= @r fena.ti") test_cmd("target _ti -= 3", "scoreboard players remove target fena.ti 3") test_cmd(r"target _ti -= 3 {Nbt:1b}", r"scoreboard players remove target fena.ti 3 {Nbt:1b}") test_cmd("setblock _ti -= players _ti2", "scoreboard players operation setblock fena.ti -= players fena.ti2") test_cmd("setblock _ti -= @r _ti2", "scoreboard players operation setblock fena.ti -= @r fena.ti2") test_cmd("setblock _ti -= @r", "scoreboard players operation setblock fena.ti -= @r fena.ti") test_cmd("setblock _ti -= 3", "scoreboard players remove setblock fena.ti 3") test_cmd(r"setblock _ti -= 3 {Nbt:1b}", r"scoreboard players remove setblock fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation @s fena.ti -= players fena.ti2") test_cmd("scoreboard players operation @s fena.ti -= @r fena.ti2") test_cmd("scoreboard players remove @s fena.ti 3") test_cmd(r"scoreboard players remove @s fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation target fena.ti -= players fena.ti2") test_cmd("scoreboard players operation target fena.ti -= @r fena.ti2") test_cmd("scoreboard players remove target fena.ti 3") test_cmd(r"scoreboard players remove target fena.ti 3 {Nbt:1b}") test_cmd("scoreboard players operation setblock fena.ti -= players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti -= @r fena.ti2") test_cmd("scoreboard players remove setblock fena.ti 3") test_cmd(r"scoreboard players remove setblock fena.ti 3 {Nbt:1b}") test_cmd("@s _ti *= players _ti2", "scoreboard players operation @s fena.ti *= players fena.ti2") test_cmd("@s _ti *= @r _ti2", "scoreboard players operation @s fena.ti *= @r fena.ti2") test_cmd("@s _ti *= @r", "scoreboard players operation @s fena.ti *= @r fena.ti") test_cmd("@s _ti *= 3", "scoreboard players operation @s fena.ti *= 3 g.number") test_cmd(r"@s _ti *= 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti *= players _ti2", "scoreboard players operation target fena.ti *= players fena.ti2") test_cmd("target _ti *= @r _ti2", "scoreboard players operation target fena.ti *= @r fena.ti2") test_cmd("target _ti *= @r", "scoreboard players operation target fena.ti *= @r fena.ti") test_cmd("target _ti *= 3", "scoreboard players operation target fena.ti *= 3 g.number") test_cmd(r"target _ti *= 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti *= players _ti2", "scoreboard players operation setblock fena.ti *= players fena.ti2") test_cmd("setblock _ti *= @r _ti2", "scoreboard players operation setblock fena.ti *= @r fena.ti2") test_cmd("setblock _ti *= @r", "scoreboard players operation setblock fena.ti *= @r fena.ti") test_cmd("setblock _ti *= 3", "scoreboard players operation setblock fena.ti *= 3 g.number") test_cmd(r"setblock _ti *= 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti *= players fena.ti2") test_cmd("scoreboard players operation @s fena.ti *= @r fena.ti2") test_cmd("scoreboard players operation @s fena.ti *= 3 g.number") test_cmd("scoreboard players operation target fena.ti *= players fena.ti2") test_cmd("scoreboard players operation target fena.ti *= @r fena.ti2") test_cmd("scoreboard players operation target fena.ti *= 3 g.number") test_cmd("scoreboard players operation setblock fena.ti *= players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti *= @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti *= 3 g.number") test_cmd("@s _ti /= players _ti2", "scoreboard players operation @s fena.ti /= players fena.ti2") test_cmd("@s _ti /= @r _ti2", "scoreboard players operation @s fena.ti /= @r fena.ti2") test_cmd("@s _ti /= @r", "scoreboard players operation @s fena.ti /= @r fena.ti") test_cmd("@s _ti /= 3", "scoreboard players operation @s fena.ti /= 3 g.number") test_cmd(r"@s _ti /= 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti /= players _ti2", "scoreboard players operation target fena.ti /= players fena.ti2") test_cmd("target _ti /= @r _ti2", "scoreboard players operation target fena.ti /= @r fena.ti2") test_cmd("target _ti /= @r", "scoreboard players operation target fena.ti /= @r fena.ti") test_cmd("target _ti /= 3", "scoreboard players operation target fena.ti /= 3 g.number") test_cmd(r"target _ti /= 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti /= players _ti2", "scoreboard players operation setblock fena.ti /= players fena.ti2") test_cmd("setblock _ti /= @r _ti2", "scoreboard players operation setblock fena.ti /= @r fena.ti2") test_cmd("setblock _ti /= @r", "scoreboard players operation setblock fena.ti /= @r fena.ti") test_cmd("setblock _ti /= 3", "scoreboard players operation setblock fena.ti /= 3 g.number") test_cmd(r"setblock _ti /= 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti /= players fena.ti2") test_cmd("scoreboard players operation @s fena.ti /= @r fena.ti2") test_cmd("scoreboard players operation @s fena.ti /= 3 g.number") test_cmd("scoreboard players operation target fena.ti /= players fena.ti2") test_cmd("scoreboard players operation target fena.ti /= @r fena.ti2") test_cmd("scoreboard players operation target fena.ti /= 3 g.number") test_cmd("scoreboard players operation setblock fena.ti /= players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti /= @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti /= 3 g.number") test_cmd("@s _ti %= players _ti2", "scoreboard players operation @s fena.ti %= players fena.ti2") test_cmd("@s _ti %= @r _ti2", "scoreboard players operation @s fena.ti %= @r fena.ti2") test_cmd("@s _ti %= @r", "scoreboard players operation @s fena.ti %= @r fena.ti") test_cmd("@s _ti %= 3", "scoreboard players operation @s fena.ti %= 3 g.number") test_cmd(r"@s _ti %= 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti %= players _ti2", "scoreboard players operation target fena.ti %= players fena.ti2") test_cmd("target _ti %= @r _ti2", "scoreboard players operation target fena.ti %= @r fena.ti2") test_cmd("target _ti %= @r", "scoreboard players operation target fena.ti %= @r fena.ti") test_cmd("target _ti %= 3", "scoreboard players operation target fena.ti %= 3 g.number") test_cmd(r"target _ti %= 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti %= players _ti2", "scoreboard players operation setblock fena.ti %= players fena.ti2") test_cmd("setblock _ti %= @r _ti2", "scoreboard players operation setblock fena.ti %= @r fena.ti2") test_cmd("setblock _ti %= @r", "scoreboard players operation setblock fena.ti %= @r fena.ti") test_cmd("setblock _ti %= 3", "scoreboard players operation setblock fena.ti %= 3 g.number") test_cmd(r"setblock _ti %= 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti %= players fena.ti2") test_cmd("scoreboard players operation @s fena.ti %= @r fena.ti2") test_cmd("scoreboard players operation @s fena.ti %= 3 g.number") test_cmd("scoreboard players operation target fena.ti %= players fena.ti2") test_cmd("scoreboard players operation target fena.ti %= @r fena.ti2") test_cmd("scoreboard players operation target fena.ti %= 3 g.number") test_cmd("scoreboard players operation setblock fena.ti %= players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti %= @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti %= 3 g.number") test_cmd("@s _ti <= players _ti2", "scoreboard players operation @s fena.ti < players fena.ti2") test_cmd("@s _ti <= @r _ti2", "scoreboard players operation @s fena.ti < @r fena.ti2") test_cmd("@s _ti <= @r", "scoreboard players operation @s fena.ti < @r fena.ti") test_cmd("@s _ti <= 3", "scoreboard players operation @s fena.ti < 3 g.number") test_cmd(r"@s _ti <= 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti <= players _ti2", "scoreboard players operation target fena.ti < players fena.ti2") test_cmd("target _ti <= @r _ti2", "scoreboard players operation target fena.ti < @r fena.ti2") test_cmd("target _ti <= @r", "scoreboard players operation target fena.ti < @r fena.ti") test_cmd("target _ti <= 3", "scoreboard players operation target fena.ti < 3 g.number") test_cmd(r"target _ti <= 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti <= players _ti2", "scoreboard players operation setblock fena.ti < players fena.ti2") test_cmd("setblock _ti <= @r _ti2", "scoreboard players operation setblock fena.ti < @r fena.ti2") test_cmd("setblock _ti <= @r", "scoreboard players operation setblock fena.ti < @r fena.ti") test_cmd("setblock _ti <= 3", "scoreboard players operation setblock fena.ti < 3 g.number") test_cmd(r"setblock _ti <= 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti < players fena.ti2") test_cmd("scoreboard players operation @s fena.ti < @r fena.ti2") test_cmd("scoreboard players operation @s fena.ti < 3 g.number") test_cmd("scoreboard players operation target fena.ti < players fena.ti2") test_cmd("scoreboard players operation target fena.ti < @r fena.ti2") test_cmd("scoreboard players operation target fena.ti < 3 g.number") test_cmd("scoreboard players operation setblock fena.ti < players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti < @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti < 3 g.number") test_cmd("@s _ti >= players _ti2", "scoreboard players operation @s fena.ti > players fena.ti2") test_cmd("@s _ti >= @r _ti2", "scoreboard players operation @s fena.ti > @r fena.ti2") test_cmd("@s _ti >= @r", "scoreboard players operation @s fena.ti > @r fena.ti") test_cmd("@s _ti >= 3", "scoreboard players operation @s fena.ti > 3 g.number") test_cmd(r"@s _ti >= 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti >= players _ti2", "scoreboard players operation target fena.ti > players fena.ti2") test_cmd("target _ti >= @r _ti2", "scoreboard players operation target fena.ti > @r fena.ti2") test_cmd("target _ti >= @r", "scoreboard players operation target fena.ti > @r fena.ti") test_cmd("target _ti >= 3", "scoreboard players operation target fena.ti > 3 g.number") test_cmd(r"target _ti >= 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti >= players _ti2", "scoreboard players operation setblock fena.ti > players fena.ti2") test_cmd("setblock _ti >= @r _ti2", "scoreboard players operation setblock fena.ti > @r fena.ti2") test_cmd("setblock _ti >= @r", "scoreboard players operation setblock fena.ti > @r fena.ti") test_cmd("setblock _ti >= 3", "scoreboard players operation setblock fena.ti > 3 g.number") test_cmd(r"setblock _ti >= 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti > players fena.ti2") test_cmd("scoreboard players operation @s fena.ti > @r fena.ti2") test_cmd("scoreboard players operation @s fena.ti > 3 g.number") test_cmd("scoreboard players operation target fena.ti > players fena.ti2") test_cmd("scoreboard players operation target fena.ti > @r fena.ti2") test_cmd("scoreboard players operation target fena.ti > 3 g.number") test_cmd("scoreboard players operation setblock fena.ti > players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti > @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti > 3 g.number") test_cmd("@s _ti swap players _ti2", "scoreboard players operation @s fena.ti >< players fena.ti2") test_cmd("@s _ti swap @r _ti2", "scoreboard players operation @s fena.ti >< @r fena.ti2") test_cmd("@s _ti swap @r", "scoreboard players operation @s fena.ti >< @r fena.ti") test_cmd("@s _ti swap 3", expect_error=True) test_cmd(r"@s _ti swap 3 {Nbt:1b}", expect_error=True) test_cmd("target _ti swap players _ti2", "scoreboard players operation target fena.ti >< players fena.ti2") test_cmd("target _ti swap @r _ti2", "scoreboard players operation target fena.ti >< @r fena.ti2") test_cmd("target _ti swap @r", "scoreboard players operation target fena.ti >< @r fena.ti") test_cmd("target _ti swap 3", expect_error=True) test_cmd(r"target _ti swap 3 {Nbt:1b}", expect_error=True) test_cmd("setblock _ti swap players _ti2", "scoreboard players operation setblock fena.ti >< players fena.ti2") test_cmd("setblock _ti swap @r _ti2", "scoreboard players operation setblock fena.ti >< @r fena.ti2") test_cmd("setblock _ti swap @r", "scoreboard players operation setblock fena.ti >< @r fena.ti") test_cmd("setblock _ti swap 3", expect_error=True) test_cmd(r"setblock _ti swap 3 {Nbt:1b}", expect_error=True) test_cmd("scoreboard players operation @s fena.ti >< players fena.ti2") test_cmd("scoreboard players operation @s fena.ti >< @r fena.ti2") test_cmd("scoreboard players operation target fena.ti >< players fena.ti2") test_cmd("scoreboard players operation target fena.ti >< @r fena.ti2") test_cmd("scoreboard players operation setblock fena.ti >< players fena.ti2") test_cmd("scoreboard players operation setblock fena.ti >< @r fena.ti2") test_cmd("@s reset _ti", "scoreboard players reset @s fena.ti") test_cmd("target reset _ti", "scoreboard players reset target fena.ti") test_cmd("setblock reset _ti", "scoreboard players reset setblock fena.ti") test_cmd("scoreboard players reset fena.ti @s") test_cmd("scoreboard players reset fena.ti target") test_cmd("scoreboard players reset fena.ti setblock") test_cmd("@s enable _ti", "scoreboard players enable @s fena.ti") test_cmd("target enable _ti", "scoreboard players enable target fena.ti") test_cmd("setblock enable _ti", "scoreboard players enable setblock fena.ti") test_cmd("scoreboard players enable fena.ti @s") test_cmd("scoreboard players enable fena.ti target") test_cmd("scoreboard players enable fena.ti setblock")
{'content_hash': 'c9bc51641a7a43e66dac2be0c0d71b3c', 'timestamp': '', 'source': 'github', 'line_count': 257, 'max_line_length': 115, 'avg_line_length': 79.89105058365759, 'alnum_prop': 0.6393434638612897, 'repo_name': 'Aquafina-water-bottle/Command-Compiler-Unlimited', 'id': '49394fd310fee5c98a26b0adca026b0a1d855ca2', 'size': '20532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/fena_v12', 'path': 'test_fena/v1_12/test_scoreboards.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '106276'}]}
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="google-site-verification" content="Rxyu4Us2dJhMBetPq3HsZnOQNAdJxUHdftvQrMswRHY" /> <title>{{ site.name }} - {{ site.description }}</title> <meta name="description" content="{{ site.meta_description}}" /> <meta name="HandheldFriendly" content="True" /> <meta name="MobileOptimized" content="320" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" /> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" /> <!-- Customisation --> <link rel="stylesheet" type="text/css" href="/assets/css/main.css" /> </head> <body class="{% if page.post_class %}{{page.post_class}}{% else %}home-template{% endif %}"> {{ content }} <footer class="site-footer clearfix"> <section class="copyright"> <a href="{{ site.baseurl }}">{{ site.name }}</a> &copy; {{date format="YYYY"}} &bull; All rights reserved. </section> <section class="poweredby">Made with Jekyll using <a href="http://github.com/rosario/kasper">Kasper theme</a> </section> </footer> <script type="text/javascript" src="/assets/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="/assets/js/jquery.fitvids.js"></script> <script type="text/javascript" src="/assets/js/index.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-57598343-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
{'content_hash': 'd29c45b7f3d92c3dca0bc91846045792', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 145, 'avg_line_length': 42.816326530612244, 'alnum_prop': 0.6329837940896091, 'repo_name': 'brunojabs/brunojabs.github.io', 'id': 'e2a7012d3f5f8d414ed3af8090db18d2594ef857', 'size': '2098', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_layouts/default.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '40541'}, {'name': 'HTML', 'bytes': '21289'}, {'name': 'JavaScript', 'bytes': '6508'}, {'name': 'Ruby', 'bytes': '17641'}]}
<!-- ! Licensed to the Apache Software Foundation (ASF) under one ! or more contributor license agreements. See the NOTICE file ! distributed with this work for additional information ! regarding copyright ownership. The ASF licenses this file ! to you under the Apache License, Version 2.0 (the ! "License"); you may not use this file except in compliance ! with the License. You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, ! software distributed under the License is distributed on an ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ! KIND, either express or implied. See the License for the ! specific language governing permissions and limitations ! under the License. !--> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>algebricks-common</artifactId> <name>algebricks-common</name> <parent> <groupId>org.apache.hyracks</groupId> <artifactId>algebricks</artifactId> <version>0.3.6-SNAPSHOT</version> </parent> <licenses> <license> <name>Apache License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> <comments>A business-friendly OSS license</comments> </license> </licenses> <properties> <root.dir>${basedir}/../..</root.dir> </properties> <dependencies> <dependency> <groupId>org.apache.hyracks</groupId> <artifactId>hyracks-api</artifactId> <version>${project.version}</version> </dependency> </dependencies> </project>
{'content_hash': '77d65306af61e0e4f45eca8aa06ffca1', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 201, 'avg_line_length': 35.84313725490196, 'alnum_prop': 0.7067833698030634, 'repo_name': 'apache/incubator-asterixdb', 'id': '9b357a27640afafcd200a0fa97763de40d077c8a', 'size': '1828', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hyracks-fullstack/algebricks/algebricks-common/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '6115'}, {'name': 'C', 'bytes': '421'}, {'name': 'CSS', 'bytes': '4763'}, {'name': 'Crystal', 'bytes': '453'}, {'name': 'Gnuplot', 'bytes': '89'}, {'name': 'HTML', 'bytes': '115120'}, {'name': 'Java', 'bytes': '10091258'}, {'name': 'JavaScript', 'bytes': '237719'}, {'name': 'Python', 'bytes': '281315'}, {'name': 'Ruby', 'bytes': '3078'}, {'name': 'Scheme', 'bytes': '1105'}, {'name': 'Shell', 'bytes': '186924'}, {'name': 'Smarty', 'bytes': '31412'}]}
<?php if (!isset($centreon)) { exit(); } $DBRESULT = $pearDB->query("SELECT * FROM `options`"); while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt["key"]] = myDecode($opt["value"]); } $DBRESULT->closeCursor(); $attrsText = array("size"=>"40"); $attrsText2 = array("size"=>"5"); $attrsAdvSelect = null; $form = new HTML_QuickFormCustom('Form', 'post', "?p=".$p); $form->addElement('header', 'title', _("Modify General Options")); $form->addElement('header', 'debug', _("Debug")); $form->addElement('text', 'debug_path', _("Logs Directory"), $attrsText); $form->addElement('checkbox', 'debug_auth', _("Authentication debug")); $form->addElement('checkbox', 'debug_sql', _("SQL debug")); $form->addElement('checkbox', 'debug_nagios_import', _("Monitoring Engine Import debug")); $form->addElement('checkbox', 'debug_rrdtool', _("RRDTool debug")); $form->addElement('checkbox', 'debug_ldap_import', _("LDAP User Import debug")); $form->addElement('checkbox', 'debug_gorgone', _("Centreon Gorgone debug")); $form->addElement('checkbox', 'debug_centreontrapd', _("Centreontrapd debug")); $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('debug_path', 'slash'); $form->registerRule('is_valid_path', 'callback', 'is_valid_path'); $form->registerRule('is_readable_path', 'callback', 'is_readable_path'); $form->registerRule('is_executable_binary', 'callback', 'is_executable_binary'); $form->registerRule('is_writable_path', 'callback', 'is_writable_path'); $form->registerRule('is_writable_file', 'callback', 'is_writable_file'); $form->registerRule('is_writable_file_if_exist', 'callback', 'is_writable_file_if_exist'); $form->addRule('debug_path', _("Can't write in directory"), 'is_writable_path'); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); /* * Smarty template Init */ $tpl = new Smarty(); $tpl = initSmartyTpl($path.'debug/', $tpl); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _("Save"), array("class" => "btc bt_success")); $DBRESULT = $form->addElement('reset', 'reset', _("Reset"), array("class" => "btc bt_default")); $valid = false; if ($form->validate()) { /* * Update in DB */ updateDebugConfigData($form->getSubmitValue("gopt_id")); /* * Update in Oreon Object */ $oreon->initOptGen($pearDB); $o = null; $valid = true; $form->freeze(); if (isset($_POST["debug_auth_clear"])) { @unlink($oreon->optGen["debug_path"]."auth.log"); } if (isset($_POST["debug_nagios_import_clear"])) { @unlink($oreon->optGen["debug_path"]."cfgimport.log"); } if (isset($_POST["debug_rrdtool_clear"])) { @unlink($oreon->optGen["debug_path"]."rrdtool.log"); } if (isset($_POST["debug_ldap_import_clear"])) { @unlink($oreon->optGen["debug_path"]."ldapsearch.log"); } if (isset($_POST["debug_inventory_clear"])) { @unlink($oreon->optGen["debug_path"]."inventory.log"); } } if (!$form->validate() && isset($_POST["gopt_id"])) { print("<div class='msg' align='center'>"._("Impossible to validate, one or more field is incorrect")."</div>"); } $form->addElement( "button", "change", _("Modify"), array("onClick"=>"javascript:window.location.href='?p=".$p."&o=debug'", 'class' => 'btc bt_info') ); // prepare help texts $helptext = ""; include_once("help.php"); foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:'.$key.'">'.$text.'</span>'."\n"; } $tpl->assign("helptext", $helptext); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign("genOpt_debug_options", _("Debug Properties")); $tpl->assign('valid', $valid); $tpl->display("form.ihtml");
{'content_hash': 'bcbcfa5ab9afc1d33f80647de994b78d', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 115, 'avg_line_length': 32.352, 'alnum_prop': 0.6204253214638972, 'repo_name': 'centreon/centreon', 'id': 'bfd7f421f2b95cd99a4863f78c312d3a54ea5487', 'size': '5790', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'centreon/www/include/Administration/parameters/debug/form.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '210043'}, {'name': 'Gherkin', 'bytes': '174313'}, {'name': 'HTML', 'bytes': '1276734'}, {'name': 'JavaScript', 'bytes': '865312'}, {'name': 'Makefile', 'bytes': '25883'}, {'name': 'NewLisp', 'bytes': '621'}, {'name': 'PHP', 'bytes': '15602217'}, {'name': 'Perl', 'bytes': '1866808'}, {'name': 'Python', 'bytes': '32748'}, {'name': 'Raku', 'bytes': '122'}, {'name': 'Shell', 'bytes': '473416'}, {'name': 'Smarty', 'bytes': '42689'}, {'name': 'TypeScript', 'bytes': '1698281'}, {'name': 'XSLT', 'bytes': '124586'}]}
package org.earthtime.UPb_Redux.valueModels.definedValueModels; import java.io.Serializable; import java.math.BigDecimal; import java.util.concurrent.ConcurrentMap; import org.earthtime.UPb_Redux.ReduxConstants; import org.earthtime.UPb_Redux.expressions.ExpTreeII; import org.earthtime.UPb_Redux.valueModels.ValueModel; import org.earthtime.dataDictionaries.AnalysisMeasures; /** * * @author James F. Bowring */ public class R265_267m extends ValueModel implements Comparable<ValueModel>, Serializable { // Class variables private static final long serialVersionUID = 6672361878564816125L; private final static String NAME = AnalysisMeasures.r265_267m.getName(); private final static String UNCT_TYPE = "ABS"; // instance variables private ValueModel r18O_16O; private ValueModel r233_235m; /** Creates a new instance of R265_267m */ public R265_267m() { super(NAME, UNCT_TYPE); } /** * * @param inputValueModels * @param parDerivTerms */ @Override public void calculateValue( ValueModel[] inputValueModels, ConcurrentMap<String, BigDecimal> parDerivTerms) { r18O_16O = inputValueModels[0]; r233_235m = inputValueModels[1]; try { setValue(r233_235m.getValue().// divide(BigDecimal.ONE.// add(new BigDecimal(2.0).// multiply(r18O_16O.getValue().// multiply(r233_235m.getValue()))), ReduxConstants.mathContext15)); } catch (Exception e) { } try { // ExpTreeII term2 = r18O_16O.getValueTree().// // multiply(r233_235m.getValueTree()); // term2.setNodeName("term2"); // // ExpTreeII denominator = ExpTreeII.ONE.// // add(new ExpTreeII(2.0).// // multiply(term2)); // denominator.setNodeName("denominator"); // // setValueTree(// // r233_235m.getValueTree().// // divide(denominator)); setValueTree(// r233_235m.getValueTree().// divide(ExpTreeII.ONE.// add(new ExpTreeII(2.0).// multiply(r18O_16O.getValueTree().// multiply(r233_235m.getValueTree()))))); } catch (Exception e) { } // System.out.println(getName() + " " + getValue().toPlainString() + "\n" + getValueTree().treeToLaTeX(1, false)); if (getValue().compareTo(getValueTree().getNodeValue()) != 0) { // System.out.println( differenceValueCalcs() ); } } /** * * @param tracerUncertaintiesOn * @param lambdaUncertaintiesOn * @param parDerivTerms * @param coVariances */ public void calculateOneSigma( boolean tracerUncertaintiesOn, boolean lambdaUncertaintiesOn, ConcurrentMap<String, BigDecimal> parDerivTerms, ConcurrentMap<String, BigDecimal> coVariances) { try { setOneSigma(r233_235m.getOneSigmaAbs().// divide(BigDecimal.ONE.// add(new BigDecimal(2.0).// multiply(r18O_16O.getValue().// multiply(r233_235m.getValue()))), ReduxConstants.mathContext15)); } catch (Exception e) { setOneSigma(BigDecimal.ZERO); } // align this calculated measured ratio with the others toggleUncertaintyType(); } }
{'content_hash': 'c2cee360d213a88e89502c0e254187b8', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 122, 'avg_line_length': 31.289473684210527, 'alnum_prop': 0.5825623773479114, 'repo_name': 'johnzeringue/ET_Redux', 'id': '761a9dfedde87d558d05ab9f9f406dc6eef9960c', 'size': '4227', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/earthtime/UPb_Redux/valueModels/definedValueModels/R265_267m.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '24270'}, {'name': 'Java', 'bytes': '8531623'}]}
<?php class Phoenix_CashOnDelivery_Block_Adminhtml_Sales_Creditmemo_Create_Totals extends Mage_Adminhtml_Block_Template { /** * Holds the creditmemo object. * @var Mage_Sales_Model_Order_Creditmemo */ protected $_source; /** * Initialize creditmemo CoD totals * * @return Phoenix_CashOnDelivery_Block_Adminhtml_Sales_Creditmemo_Create_Totals */ public function initTotals() { $parent = $this->getParentBlock(); $this->_source = $parent->getSource(); $total = new Varien_Object(array( 'code' => 'phoenix_cashondelivery_fee', 'value' => $this->getCodAmount(), 'base_value'=> $this->getCodAmount(), 'label' => $this->helper('phoenix_cashondelivery')->__('Refund Cash on Delivery fee') )); $parent->addTotalBefore($total, 'shipping'); return $this; } /** * Getter for the creditmemo object. * * @return Mage_Sales_Model_Order_Creditmemo */ public function getSource() { return $this->_source; } /** * Get CoD fee amount for actual invoice. * @return float */ public function getCodAmount() { $codFee = $this->_source->getCodFee() + $this->_source->getCodTaxAmount(); return Mage::app()->getStore()->roundPrice($codFee); } }
{'content_hash': '34bebc48d5938c2750163207302007f5', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 113, 'avg_line_length': 28.02, 'alnum_prop': 0.5724482512491078, 'repo_name': '5452/durex', 'id': 'edb7b43bba2bc4bfeb49f799e711b215a393ef69', 'size': '1401', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'includes/src/Phoenix_CashOnDelivery_Block_Adminhtml_Sales_Creditmemo_Create_Totals.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '19946'}, {'name': 'CSS', 'bytes': '2190550'}, {'name': 'JavaScript', 'bytes': '1290492'}, {'name': 'PHP', 'bytes': '102689019'}, {'name': 'Shell', 'bytes': '642'}, {'name': 'XSLT', 'bytes': '2066'}]}
/** * AdUnitHierarchyError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201311; /** * Caused by creating an {@link AdUnit} object with an invalid hierarchy. */ public class AdUnitHierarchyError extends com.google.api.ads.dfp.v201311.ApiError implements java.io.Serializable { private com.google.api.ads.dfp.v201311.AdUnitHierarchyErrorReason reason; public AdUnitHierarchyError() { } public AdUnitHierarchyError( java.lang.String fieldPath, java.lang.String trigger, java.lang.String errorString, java.lang.String apiErrorType, com.google.api.ads.dfp.v201311.AdUnitHierarchyErrorReason reason) { super( fieldPath, trigger, errorString, apiErrorType); this.reason = reason; } /** * Gets the reason value for this AdUnitHierarchyError. * * @return reason */ public com.google.api.ads.dfp.v201311.AdUnitHierarchyErrorReason getReason() { return reason; } /** * Sets the reason value for this AdUnitHierarchyError. * * @param reason */ public void setReason(com.google.api.ads.dfp.v201311.AdUnitHierarchyErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof AdUnitHierarchyError)) return false; AdUnitHierarchyError other = (AdUnitHierarchyError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AdUnitHierarchyError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "AdUnitHierarchyError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "AdUnitHierarchyError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
{'content_hash': '9da5f8bf9cc98889e406ad0132595d88', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 144, 'avg_line_length': 32.0, 'alnum_prop': 0.6235902255639098, 'repo_name': 'google-code-export/google-api-dfp-java', 'id': 'ab1258e1f9a194a8c1f81f95d5663b7d651c3164', 'size': '4256', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/google/api/ads/dfp/v201311/AdUnitHierarchyError.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '39950935'}]}
<group> <Video_input>Video input</Video_input> <Video_On_Off>0</Video_On_Off> <Load_Video>0</Load_Video> <Scale>1, 1</Scale> <Fit_to_quad>0</Fit_to_quad> <Keep_aspect_ratio>0</Keep_aspect_ratio> <Horizontal_flip>0</Horizontal_flip> <Vertical_flip>0</Vertical_flip> <color>255, 255, 255, 255</color> <Video_Speed>-2</Video_Speed> <Video_Loop>0</Video_Loop> <Video_Greenscreen>0</Video_Greenscreen> <Video_Audio_Volume>0</Video_Audio_Volume> </group>
{'content_hash': 'a871706f8cb0ec8471b32eeca17b4477', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 43, 'avg_line_length': 30.8, 'alnum_prop': 0.7012987012987013, 'repo_name': 'nanu-c/remoteX-1', 'id': 'f5f6ac828b8111a642fd41d9bb7ecb303cf5db21', 'size': '462', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'bin/data/settings.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '63865'}, {'name': 'Makefile', 'bytes': '382'}, {'name': 'Shell', 'bytes': '490'}]}
namespace Apache.Arrow.Flatbuf { using global::System; using global::FlatBuffers; /// A Struct_ in the flatbuffer metadata is the same as an Arrow Struct /// (according to the physical memory layout). We used Struct_ here as /// Struct is a reserved word in Flatbuffers public struct Struct_ : IFlatbufferObject { private Table __p; public ByteBuffer ByteBuffer { get { return __p.bb; } } public static Struct_ GetRootAsStruct_(ByteBuffer _bb) { return GetRootAsStruct_(_bb, new Struct_()); } public static Struct_ GetRootAsStruct_(ByteBuffer _bb, Struct_ obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; } public Struct_ __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public static void StartStruct_(FlatBufferBuilder builder) { builder.StartObject(0); } public static Offset<Struct_> EndStruct_(FlatBufferBuilder builder) { int o = builder.EndObject(); return new Offset<Struct_>(o); } }; }
{'content_hash': 'd58b72f03abc812771236c8db3047d97', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 142, 'avg_line_length': 37.5, 'alnum_prop': 0.6952380952380952, 'repo_name': 'pcmoritz/arrow', 'id': 'f1d7aa27dcf6dfcc53d5748f979e08986fea6b59', 'size': '1163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'csharp/src/Apache.Arrow/Flatbuf/Types/Struct_.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '73655'}, {'name': 'Awk', 'bytes': '3683'}, {'name': 'Batchfile', 'bytes': '33278'}, {'name': 'C', 'bytes': '380611'}, {'name': 'C#', 'bytes': '333149'}, {'name': 'C++', 'bytes': '6386150'}, {'name': 'CMake', 'bytes': '351656'}, {'name': 'CSS', 'bytes': '3946'}, {'name': 'Dockerfile', 'bytes': '39378'}, {'name': 'FreeMarker', 'bytes': '2256'}, {'name': 'Go', 'bytes': '343789'}, {'name': 'HTML', 'bytes': '23351'}, {'name': 'Java', 'bytes': '2205214'}, {'name': 'JavaScript', 'bytes': '83169'}, {'name': 'Lua', 'bytes': '8741'}, {'name': 'M4', 'bytes': '8628'}, {'name': 'MATLAB', 'bytes': '9068'}, {'name': 'Makefile', 'bytes': '44948'}, {'name': 'Meson', 'bytes': '36954'}, {'name': 'Objective-C', 'bytes': '2533'}, {'name': 'Perl', 'bytes': '3799'}, {'name': 'Python', 'bytes': '1439764'}, {'name': 'R', 'bytes': '149758'}, {'name': 'Ruby', 'bytes': '583523'}, {'name': 'Rust', 'bytes': '1192382'}, {'name': 'Shell', 'bytes': '218636'}, {'name': 'Thrift', 'bytes': '137291'}, {'name': 'TypeScript', 'bytes': '836757'}]}
() => { // ------- variable definitions that does not exist in the original code. These are for typescript. var container: HTMLDivElement, stats: Stats; var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer, objects: THREE.Mesh[]; var pointLight: THREE.PointLight; init(); animate(); function init() { container = document.createElement('div'); document.body.appendChild(container); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); camera.position.set(0, 200, 800); scene = new THREE.Scene(); // Grid var size = 500, step = 100; var geometry = new THREE.Geometry(); for (var i = - size; i <= size; i += step) { geometry.vertices.push(new THREE.Vector3(- size, - 120, i)); geometry.vertices.push(new THREE.Vector3(size, - 120, i)); geometry.vertices.push(new THREE.Vector3(i, - 120, - size)); geometry.vertices.push(new THREE.Vector3(i, - 120, size)); } var material = new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 0.2 }); var line = new THREE.Line(geometry, material, THREE.LinePieces); scene.add(line); // Spheres var geometry2 = new THREE.SphereGeometry(100, 14, 7); type MeshMaterial = THREE.MeshBasicMaterial | THREE.MeshFaceMaterial | THREE.MeshLambertMaterial | THREE.MeshDepthMaterial | THREE.MeshNormalMaterial; var materials: MeshMaterial[] = [ new THREE.MeshBasicMaterial({ color: 0x00ffff, wireframe: true, side: THREE.DoubleSide }), new THREE.MeshBasicMaterial({ color: 0xff0000, blending: THREE.AdditiveBlending }), new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 }), new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 }), new THREE.MeshDepthMaterial({ overdraw: 0.5 }), new THREE.MeshNormalMaterial({ overdraw: 0.5 }), new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('textures/land_ocean_ice_cloud_2048.jpg') }), new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', THREE.SphericalReflectionMapping), overdraw: 0.5 }) ]; for (var i = 0, l = geometry2.faces.length; i < l; i++) { var face = geometry2.faces[i]; if (Math.random() > 0.5) face.materialIndex = Math.floor(Math.random() * materials.length); } materials.push(new THREE.MeshFaceMaterial(materials)); objects = []; for (var i = 0, l = materials.length; i < l; i++) { var sphere = new THREE.Mesh(geometry, materials[i]); sphere.position.x = (i % 5) * 200 - 400; sphere.position.z = Math.floor(i / 5) * 200 - 200; sphere.rotation.x = Math.random() * 200 - 100; sphere.rotation.y = Math.random() * 200 - 100; sphere.rotation.z = Math.random() * 200 - 100; objects.push(sphere); scene.add(sphere); } var PI2 = Math.PI * 2; var program = function (context: CanvasRenderingContext2D) { context.beginPath(); context.arc(0, 0, 0.5, 0, PI2, true); context.fill(); } // Lights scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff); directionalLight.position.x = Math.random() - 0.5; directionalLight.position.y = Math.random() - 0.5; directionalLight.position.z = Math.random() - 0.5; directionalLight.position.normalize(); scene.add(directionalLight); pointLight = new THREE.PointLight(0xffffff, 1); scene.add(pointLight); var sprite = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program })); sprite.scale.set(8, 8, 8); pointLight.add(sprite); renderer = new THREE.CanvasRenderer(); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(renderer.domElement); var debugCanvas = document.createElement('canvas'); debugCanvas.width = 512; debugCanvas.height = 512; debugCanvas.style.position = 'absolute'; debugCanvas.style.top = '0px'; debugCanvas.style.left = '0px'; container.appendChild(debugCanvas); var debugContext = debugCanvas.getContext('2d'); debugContext.setTransform(1, 0, 0, 1, 256, 256); debugContext.strokeStyle = '#000000'; stats = new Stats(); stats.dom.style.position = 'absolute'; stats.dom.style.top = '0px'; container.appendChild(stats.dom); // window.addEventListener('resize', onWindowResize, false); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function loadImage(path: string) { var image = document.createElement('img'); var texture = new THREE.Texture(image, THREE.UVMapping) image.onload = function () { texture.needsUpdate = true; }; image.src = path; return texture; } // function animate() { requestAnimationFrame(animate); render(); stats.update(); } function render() { var timer = Date.now() * 0.0001; camera.position.x = Math.cos(timer) * 1000; camera.position.z = Math.sin(timer) * 1000; camera.lookAt(scene.position); for (var i = 0, l = objects.length; i < l; i++) { var object = objects[i]; object.rotation.x += 0.01; object.rotation.y += 0.005; } pointLight.position.x = Math.sin(timer * 7) * 300; pointLight.position.y = Math.cos(timer * 5) * 400; pointLight.position.z = Math.cos(timer * 3) * 300; renderer.render(scene, camera); } }
{'content_hash': 'b2180fa49f2591f5b0095b9217cb1958', 'timestamp': '', 'source': 'github', 'line_count': 202, 'max_line_length': 158, 'avg_line_length': 30.945544554455445, 'alnum_prop': 0.6015037593984962, 'repo_name': 'aaronryden/DefinitelyTyped', 'id': 'dd0ebbf60171736056999ce77fc12660a96c7de6', 'size': '6333', 'binary': False, 'copies': '23', 'ref': 'refs/heads/master', 'path': 'types/three/test/canvas/canvas_materials.ts', 'mode': '33188', 'license': 'mit', 'language': []}
package net.spy.memcached.protocol.ascii; import junit.framework.TestCase; import net.spy.memcached.ops.OperationErrorType; import net.spy.memcached.ops.OperationException; /** * Test operation exception constructors and accessors and stuff. */ public class OperationExceptionTest extends TestCase { public void testEmpty() { OperationException oe = new OperationException(); assertSame(OperationErrorType.GENERAL, oe.getType()); assertEquals("OperationException: GENERAL", String.valueOf(oe)); } public void testServer() { OperationException oe = new OperationException( OperationErrorType.SERVER, "SERVER_ERROR figures"); assertSame(OperationErrorType.SERVER, oe.getType()); assertEquals("OperationException: SERVER: SERVER_ERROR figures", String.valueOf(oe)); } public void testClient() { OperationException oe = new OperationException( OperationErrorType.CLIENT, "CLIENT_ERROR nope"); assertSame(OperationErrorType.CLIENT, oe.getType()); assertEquals("OperationException: CLIENT: CLIENT_ERROR nope", String.valueOf(oe)); } public void testGeneral() { // General type doesn't have additional info OperationException oe = new OperationException( OperationErrorType.GENERAL, "GENERAL wtf"); assertSame(OperationErrorType.GENERAL, oe.getType()); assertEquals("OperationException: GENERAL", String.valueOf(oe)); } }
{'content_hash': 'ca80fbf6a5d8dbdccb6c59d4ff447d05', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 68, 'avg_line_length': 35.390243902439025, 'alnum_prop': 0.7284631288766368, 'repo_name': 'naver/arcus-java-client', 'id': '28c480f005e4d4b4ace1526eb6e2fe5813378aa6', 'size': '1451', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/net/spy/memcached/protocol/ascii/OperationExceptionTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '6243'}, {'name': 'Java', 'bytes': '2624439'}, {'name': 'Ruby', 'bytes': '2376'}, {'name': 'Shell', 'bytes': '116'}]}
#ifndef _FSL_SPI_DMA_H_ #define _FSL_SPI_DMA_H_ #include "fsl_dma.h" #include "fsl_spi.h" /*! * @addtogroup spi_dma_driver * @{ */ /*! @file */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @name Driver version */ /*@{*/ /*! @brief SPI DMA driver version 2.0.3. */ #define FSL_SPI_DMA_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) /*@}*/ typedef struct _spi_dma_handle spi_dma_handle_t; /*! @brief SPI DMA callback called at the end of transfer. */ typedef void (*spi_dma_callback_t)(SPI_Type *base, spi_dma_handle_t *handle, status_t status, void *userData); /*! @brief SPI DMA transfer handle, users should not touch the content of the handle.*/ struct _spi_dma_handle { volatile bool txInProgress; /*!< Send transfer finished */ volatile bool rxInProgress; /*!< Receive transfer finished */ dma_handle_t *txHandle; /*!< DMA handler for SPI send */ dma_handle_t *rxHandle; /*!< DMA handler for SPI receive */ uint8_t bytesPerFrame; /*!< Bytes in a frame for SPI tranfer */ spi_dma_callback_t callback; /*!< Callback for SPI DMA transfer */ void *userData; /*!< User Data for SPI DMA callback */ uint32_t state; /*!< Internal state of SPI DMA transfer */ size_t transferSize; /*!< Bytes need to be transfer */ }; /******************************************************************************* * APIs ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name DMA Transactional * @{ */ /*! * @brief Initialize the SPI master DMA handle. * * This function initializes the SPI master DMA handle which can be used for other SPI master transactional APIs. * Usually, for a specified SPI instance, user need only call this API once to get the initialized handle. * * @param base SPI peripheral base address. * @param handle SPI handle pointer. * @param callback User callback function called at the end of a transfer. * @param userData User data for callback. * @param txHandle DMA handle pointer for SPI Tx, the handle shall be static allocated by users. * @param rxHandle DMA handle pointer for SPI Rx, the handle shall be static allocated by users. */ status_t SPI_MasterTransferCreateHandleDMA(SPI_Type *base, spi_dma_handle_t *handle, spi_dma_callback_t callback, void *userData, dma_handle_t *txHandle, dma_handle_t *rxHandle); /*! * @brief Perform a non-blocking SPI transfer using DMA. * * @note This interface returned immediately after transfer initiates, users should call * SPI_GetTransferStatus to poll the transfer status to check whether SPI transfer finished. * * @param base SPI peripheral base address. * @param handle SPI DMA handle pointer. * @param xfer Pointer to dma transfer structure. * @retval kStatus_Success Successfully start a transfer. * @retval kStatus_InvalidArgument Input argument is invalid. * @retval kStatus_SPI_Busy SPI is not idle, is running another transfer. */ status_t SPI_MasterTransferDMA(SPI_Type *base, spi_dma_handle_t *handle, spi_transfer_t *xfer); /*! * @brief Transfers a block of data using a DMA method. * * This function using polling way to do the first half transimission and using DMA way to * do the srcond half transimission, the transfer mechanism is half-duplex. * When do the second half transimission, code will return right away. When all data is transferred, * the callback function is called. * * @param base SPI base pointer * @param handle A pointer to the spi_master_dma_handle_t structure which stores the transfer state. * @param transfer A pointer to the spi_half_duplex_transfer_t structure. * @return status of status_t. */ status_t SPI_MasterHalfDuplexTransferDMA(SPI_Type *base, spi_dma_handle_t *handle, spi_half_duplex_transfer_t *xfer); /*! * @brief Initialize the SPI slave DMA handle. * * This function initializes the SPI slave DMA handle which can be used for other SPI master transactional APIs. * Usually, for a specified SPI instance, user need only call this API once to get the initialized handle. * * @param base SPI peripheral base address. * @param handle SPI handle pointer. * @param callback User callback function called at the end of a transfer. * @param userData User data for callback. * @param txHandle DMA handle pointer for SPI Tx, the handle shall be static allocated by users. * @param rxHandle DMA handle pointer for SPI Rx, the handle shall be static allocated by users. */ static inline status_t SPI_SlaveTransferCreateHandleDMA(SPI_Type *base, spi_dma_handle_t *handle, spi_dma_callback_t callback, void *userData, dma_handle_t *txHandle, dma_handle_t *rxHandle) { return SPI_MasterTransferCreateHandleDMA(base, handle, callback, userData, txHandle, rxHandle); } /*! * @brief Perform a non-blocking SPI transfer using DMA. * * @note This interface returned immediately after transfer initiates, users should call * SPI_GetTransferStatus to poll the transfer status to check whether SPI transfer finished. * * @param base SPI peripheral base address. * @param handle SPI DMA handle pointer. * @param xfer Pointer to dma transfer structure. * @retval kStatus_Success Successfully start a transfer. * @retval kStatus_InvalidArgument Input argument is invalid. * @retval kStatus_SPI_Busy SPI is not idle, is running another transfer. */ static inline status_t SPI_SlaveTransferDMA(SPI_Type *base, spi_dma_handle_t *handle, spi_transfer_t *xfer) { return SPI_MasterTransferDMA(base, handle, xfer); } /*! * @brief Abort a SPI transfer using DMA. * * @param base SPI peripheral base address. * @param handle SPI DMA handle pointer. */ void SPI_MasterTransferAbortDMA(SPI_Type *base, spi_dma_handle_t *handle); /*! * @brief Gets the master DMA transfer remaining bytes. * * This function gets the master DMA transfer remaining bytes. * * @param base SPI peripheral base address. * @param handle A pointer to the spi_dma_handle_t structure which stores the transfer state. * @param count A number of bytes transferred by the non-blocking transaction. * @return status of status_t. */ status_t SPI_MasterTransferGetCountDMA(SPI_Type *base, spi_dma_handle_t *handle, size_t *count); /*! * @brief Abort a SPI transfer using DMA. * * @param base SPI peripheral base address. * @param handle SPI DMA handle pointer. */ static inline void SPI_SlaveTransferAbortDMA(SPI_Type *base, spi_dma_handle_t *handle) { SPI_MasterTransferAbortDMA(base, handle); } /*! * @brief Gets the slave DMA transfer remaining bytes. * * This function gets the slave DMA transfer remaining bytes. * * @param base SPI peripheral base address. * @param handle A pointer to the spi_dma_handle_t structure which stores the transfer state. * @param count A number of bytes transferred by the non-blocking transaction. * @return status of status_t. */ static inline status_t SPI_SlaveTransferGetCountDMA(SPI_Type *base, spi_dma_handle_t *handle, size_t *count) { return SPI_MasterTransferGetCountDMA(base, handle, count); } /*! @} */ #if defined(__cplusplus) } #endif /*! @} */ #endif /* _FSL_SPI_DMA_H_*/
{'content_hash': '9f0ef9dbdfc4b27193de2d54a7949fb6', 'timestamp': '', 'source': 'github', 'line_count': 202, 'max_line_length': 117, 'avg_line_length': 38.57425742574257, 'alnum_prop': 0.6482289527720739, 'repo_name': 'explora26/zephyr', 'id': 'cc7ffe28f28d3f2fed5122df9acb9a44626167bf', 'size': '7946', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ext/hal/nxp/mcux/drivers/lpc/fsl_spi_dma.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1293047'}, {'name': 'Batchfile', 'bytes': '110'}, {'name': 'C', 'bytes': '340251497'}, {'name': 'C++', 'bytes': '3179665'}, {'name': 'CMake', 'bytes': '531524'}, {'name': 'EmberScript', 'bytes': '793'}, {'name': 'Makefile', 'bytes': '3313'}, {'name': 'Objective-C', 'bytes': '34223'}, {'name': 'Perl', 'bytes': '202106'}, {'name': 'Python', 'bytes': '909223'}, {'name': 'Shell', 'bytes': '42672'}, {'name': 'Verilog', 'bytes': '6394'}]}
/* This file was generated by SableCC's ObjectMacro. */ package org.sablecc.sablecc.codegeneration.java.macro; public class MReduceNormalPop { private final String pElementName; private final MReduceNormalPop mReduceNormalPop = this; MReduceNormalPop( String pElementName) { if (pElementName == null) { throw new NullPointerException(); } this.pElementName = pElementName; } String pElementName() { return this.pElementName; } private String rElementName() { return this.mReduceNormalPop.pElementName(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" AbstractForest l"); sb.append(rElementName()); sb.append(" = stack.pop();"); sb.append(System.getProperty("line.separator")); return sb.toString(); } }
{'content_hash': '262713c6ee5f49a9ebe8b030ca17b600', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 59, 'avg_line_length': 22.463414634146343, 'alnum_prop': 0.6254071661237784, 'repo_name': 'vanderock1/sablecc', 'id': '65dee3b35e60e73845306da6f7354c072deb5caa', 'size': '921', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/org/sablecc/sablecc/codegeneration/java/macro/MReduceNormalPop.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
using esencialAdmin.Models.HomeViewModels; namespace esencialAdmin.Services { public interface IStatisticService { OverviewHomeViewModel getOverViewModel(); } }
{'content_hash': 'de39b839e332051b7a23c6f815212cde', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 49, 'avg_line_length': 20.22222222222222, 'alnum_prop': 0.7527472527472527, 'repo_name': 'Che4ter/PAWI', 'id': '2b6338ff98d55b1850a64128315b0e1acf67847a', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/esencialAdmin/Services/IStatisticService.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '320358'}, {'name': 'CSS', 'bytes': '392644'}, {'name': 'HTML', 'bytes': '711140'}, {'name': 'JavaScript', 'bytes': '3105033'}, {'name': 'PLpgSQL', 'bytes': '2921'}, {'name': 'Ruby', 'bytes': '161'}, {'name': 'Smarty', 'bytes': '436'}]}
package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence; import java.util.List; import java.util.Map.Entry; import java.util.regex.Pattern; import org.apache.synapse.endpoints.Endpoint; import org.apache.synapse.mediators.base.SequenceMediator; import org.apache.synapse.mediators.eip.Target; import org.apache.synapse.util.xpath.SynapseXPath; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.jaxen.JaxenException; import org.wso2.carbon.mediators.router.impl.Route; import org.wso2.developerstudio.eclipse.gmf.esb.EsbNode; import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty; import org.wso2.developerstudio.eclipse.gmf.esb.RouterMediator; import org.wso2.developerstudio.eclipse.gmf.esb.RouterTargetContainer; import org.wso2.developerstudio.eclipse.gmf.esb.TargetSequenceType; import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformationInfo; import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformerException; /** * Router mediator transformer * */ public class RouterMediatorTransformer extends AbstractEsbNodeTransformer { public void transform(TransformationInfo information, EsbNode subject) throws TransformerException { try { information.getParentSequence().addChild(createRouterMediator(information, subject)); doTransform(information, ((RouterMediator) subject).getOutputConnector()); } catch (JaxenException e) { throw new TransformerException(e); } } public void createSynapseObject(TransformationInfo info, EObject subject, List<Endpoint> endPoints) { } public void transformWithinSequence(TransformationInfo information, EsbNode subject, SequenceMediator sequence) throws TransformerException { try { sequence.addChild(createRouterMediator(information, subject)); doTransformWithinSequence(information, ((RouterMediator) subject).getOutputConnector().getOutgoingLink(), sequence); } catch (JaxenException e) { throw new TransformerException(e); } } private org.wso2.carbon.mediators.router.impl.RouterMediator createRouterMediator(TransformationInfo information, EsbNode subject) throws JaxenException, TransformerException { Assert.isTrue(subject instanceof RouterMediator, "Unsupported mediator passed in for serialization"); RouterMediator routerModel = (RouterMediator) subject; org.wso2.carbon.mediators.router.impl.RouterMediator router = new org.wso2.carbon.mediators.router.impl.RouterMediator(); router.setContinueAfter(routerModel.isContinueAfterRouting()); EList<RouterTargetContainer> routerTargets = routerModel.getRouterContainer().getRouterTargetContainer(); for (int i = 0; i < routerTargets.size(); i++) { Route route = new Route(); Pattern match = Pattern.compile(routerTargets.get(i).getRoutePattern()); route.setMatch(match); NamespacedProperty routeExpressionModel = routerTargets.get(i).getRouteExpression(); SynapseXPath routeExpression = new SynapseXPath(routeExpressionModel.getPropertyValue()); for (Entry<String, String> entry : routeExpressionModel.getNamespaces().entrySet()) { routeExpression.addNamespace(entry.getKey(), entry.getValue()); } route.setExpression(routeExpression); route.setBreakRouter(routerTargets.get(i).isBreakAfterRoute()); Target target = new Target(); if (routerTargets.get(i).getTarget().getSequenceType() == TargetSequenceType.REGISTRY_REFERENCE) { target.setSequenceRef(routerTargets.get(i).getTarget().getSequenceKey().getKeyValue()); } else { SequenceMediator targetSequence = new SequenceMediator(); TransformationInfo newOnCompleteInfo = new TransformationInfo(); newOnCompleteInfo.setTraversalDirection(information.getTraversalDirection()); newOnCompleteInfo.setSynapseConfiguration(information.getSynapseConfiguration()); newOnCompleteInfo.setOriginInSequence(information.getOriginInSequence()); newOnCompleteInfo.setOriginOutSequence(information.getOriginOutSequence()); newOnCompleteInfo.setCurrentProxy(information.getCurrentProxy()); newOnCompleteInfo.setParentSequence(targetSequence); doTransform(newOnCompleteInfo, routerModel.getTargetOutputConnector().get(i)); target.setSequence(targetSequence); } /* * TODO: add target endpoint serialization, note : current implementation of the GMF * RouterMediator model does not support the creation of target endpoints */ route.setTarget(target); router.addRoute(route); } return router; } }
{'content_hash': 'ad230de933a9283acfa886c328c5e941', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 129, 'avg_line_length': 48.2, 'alnum_prop': 0.7172495554238293, 'repo_name': 'wso2/devstudio-tooling-esb', 'id': '8b301d816d15c92980c5383463a9e88ae9ea6161', 'size': '5673', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'plugins/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/RouterMediatorTransformer.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '41098'}, {'name': 'HTML', 'bytes': '731356'}, {'name': 'Java', 'bytes': '77354104'}, {'name': 'JavaScript', 'bytes': '475592'}, {'name': 'Shell', 'bytes': '7727'}]}
/* Generated by */ #include <winpr/assert.h> #include <freerdp/settings.h> #include <freerdp/log.h> #include "../core/settings.h" #define TAG FREERDP_TAG("common.settings") static BOOL update_string(char** current, const char* next, size_t next_len, BOOL cleanup) { if (cleanup) { if (*current) memset(*current, 0, strlen(*current)); free(*current); } if (!next && (next_len > 0)) { *current = calloc(next_len, 1); return (*current != NULL); } *current = (next ? strndup(next, next_len) : NULL); return !next || (*current != NULL); } BOOL freerdp_settings_get_bool(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_AllowCacheWaitingList: return settings->AllowCacheWaitingList; case FreeRDP_AllowDesktopComposition: return settings->AllowDesktopComposition; case FreeRDP_AllowFontSmoothing: return settings->AllowFontSmoothing; case FreeRDP_AllowUnanouncedOrdersFromServer: return settings->AllowUnanouncedOrdersFromServer; case FreeRDP_AltSecFrameMarkerSupport: return settings->AltSecFrameMarkerSupport; case FreeRDP_AsyncChannels: return settings->AsyncChannels; case FreeRDP_AsyncUpdate: return settings->AsyncUpdate; case FreeRDP_AudioCapture: return settings->AudioCapture; case FreeRDP_AudioPlayback: return settings->AudioPlayback; case FreeRDP_Authentication: return settings->Authentication; case FreeRDP_AuthenticationOnly: return settings->AuthenticationOnly; case FreeRDP_AutoAcceptCertificate: return settings->AutoAcceptCertificate; case FreeRDP_AutoDenyCertificate: return settings->AutoDenyCertificate; case FreeRDP_AutoLogonEnabled: return settings->AutoLogonEnabled; case FreeRDP_AutoReconnectionEnabled: return settings->AutoReconnectionEnabled; case FreeRDP_BitmapCacheEnabled: return settings->BitmapCacheEnabled; case FreeRDP_BitmapCachePersistEnabled: return settings->BitmapCachePersistEnabled; case FreeRDP_BitmapCacheV3Enabled: return settings->BitmapCacheV3Enabled; case FreeRDP_BitmapCompressionDisabled: return settings->BitmapCompressionDisabled; case FreeRDP_CertificateCallbackPreferPEM: return settings->CertificateCallbackPreferPEM; case FreeRDP_CertificateUseKnownHosts: return settings->CertificateUseKnownHosts; case FreeRDP_ColorPointerFlag: return settings->ColorPointerFlag; case FreeRDP_CompressionEnabled: return settings->CompressionEnabled; case FreeRDP_ConsoleSession: return settings->ConsoleSession; case FreeRDP_CredentialsFromStdin: return settings->CredentialsFromStdin; case FreeRDP_DeactivateClientDecoding: return settings->DeactivateClientDecoding; case FreeRDP_Decorations: return settings->Decorations; case FreeRDP_DesktopResize: return settings->DesktopResize; case FreeRDP_DeviceRedirection: return settings->DeviceRedirection; case FreeRDP_DisableCredentialsDelegation: return settings->DisableCredentialsDelegation; case FreeRDP_DisableCtrlAltDel: return settings->DisableCtrlAltDel; case FreeRDP_DisableCursorBlinking: return settings->DisableCursorBlinking; case FreeRDP_DisableCursorShadow: return settings->DisableCursorShadow; case FreeRDP_DisableFullWindowDrag: return settings->DisableFullWindowDrag; case FreeRDP_DisableMenuAnims: return settings->DisableMenuAnims; case FreeRDP_DisableRemoteAppCapsCheck: return settings->DisableRemoteAppCapsCheck; case FreeRDP_DisableThemes: return settings->DisableThemes; case FreeRDP_DisableWallpaper: return settings->DisableWallpaper; case FreeRDP_DrawAllowColorSubsampling: return settings->DrawAllowColorSubsampling; case FreeRDP_DrawAllowDynamicColorFidelity: return settings->DrawAllowDynamicColorFidelity; case FreeRDP_DrawAllowSkipAlpha: return settings->DrawAllowSkipAlpha; case FreeRDP_DrawGdiPlusCacheEnabled: return settings->DrawGdiPlusCacheEnabled; case FreeRDP_DrawGdiPlusEnabled: return settings->DrawGdiPlusEnabled; case FreeRDP_DrawNineGridEnabled: return settings->DrawNineGridEnabled; case FreeRDP_DumpRemoteFx: return settings->DumpRemoteFx; case FreeRDP_DynamicDaylightTimeDisabled: return settings->DynamicDaylightTimeDisabled; case FreeRDP_DynamicResolutionUpdate: return settings->DynamicResolutionUpdate; case FreeRDP_EmbeddedWindow: return settings->EmbeddedWindow; case FreeRDP_EnableWindowsKey: return settings->EnableWindowsKey; case FreeRDP_EncomspVirtualChannel: return settings->EncomspVirtualChannel; case FreeRDP_ExtSecurity: return settings->ExtSecurity; case FreeRDP_ExternalCertificateManagement: return settings->ExternalCertificateManagement; case FreeRDP_FIPSMode: return settings->FIPSMode; case FreeRDP_FastPathInput: return settings->FastPathInput; case FreeRDP_FastPathOutput: return settings->FastPathOutput; case FreeRDP_ForceEncryptedCsPdu: return settings->ForceEncryptedCsPdu; case FreeRDP_ForceMultimon: return settings->ForceMultimon; case FreeRDP_FrameMarkerCommandEnabled: return settings->FrameMarkerCommandEnabled; case FreeRDP_Fullscreen: return settings->Fullscreen; case FreeRDP_GatewayBypassLocal: return settings->GatewayBypassLocal; case FreeRDP_GatewayEnabled: return settings->GatewayEnabled; case FreeRDP_GatewayHttpTransport: return settings->GatewayHttpTransport; case FreeRDP_GatewayHttpUseWebsockets: return settings->GatewayHttpUseWebsockets; case FreeRDP_GatewayRpcTransport: return settings->GatewayRpcTransport; case FreeRDP_GatewayUdpTransport: return settings->GatewayUdpTransport; case FreeRDP_GatewayUseSameCredentials: return settings->GatewayUseSameCredentials; case FreeRDP_GfxAVC444: return settings->GfxAVC444; case FreeRDP_GfxAVC444v2: return settings->GfxAVC444v2; case FreeRDP_GfxH264: return settings->GfxH264; case FreeRDP_GfxPlanar: return settings->GfxPlanar; case FreeRDP_GfxProgressive: return settings->GfxProgressive; case FreeRDP_GfxProgressiveV2: return settings->GfxProgressiveV2; case FreeRDP_GfxSendQoeAck: return settings->GfxSendQoeAck; case FreeRDP_GfxSmallCache: return settings->GfxSmallCache; case FreeRDP_GfxThinClient: return settings->GfxThinClient; case FreeRDP_GrabKeyboard: return settings->GrabKeyboard; case FreeRDP_GrabMouse: return settings->GrabMouse; case FreeRDP_HasExtendedMouseEvent: return settings->HasExtendedMouseEvent; case FreeRDP_HasHorizontalWheel: return settings->HasHorizontalWheel; case FreeRDP_HasMonitorAttributes: return settings->HasMonitorAttributes; case FreeRDP_HiDefRemoteApp: return settings->HiDefRemoteApp; case FreeRDP_IPv6Enabled: return settings->IPv6Enabled; case FreeRDP_IgnoreCertificate: return settings->IgnoreCertificate; case FreeRDP_JpegCodec: return settings->JpegCodec; case FreeRDP_ListMonitors: return settings->ListMonitors; case FreeRDP_LocalConnection: return settings->LocalConnection; case FreeRDP_LogonErrors: return settings->LogonErrors; case FreeRDP_LogonNotify: return settings->LogonNotify; case FreeRDP_LongCredentialsSupported: return settings->LongCredentialsSupported; case FreeRDP_LyncRdpMode: return settings->LyncRdpMode; case FreeRDP_MaximizeShell: return settings->MaximizeShell; case FreeRDP_MouseAttached: return settings->MouseAttached; case FreeRDP_MouseHasWheel: return settings->MouseHasWheel; case FreeRDP_MouseMotion: return settings->MouseMotion; case FreeRDP_MouseUseRelativeMove: return settings->MouseUseRelativeMove; case FreeRDP_MstscCookieMode: return settings->MstscCookieMode; case FreeRDP_MultiTouchGestures: return settings->MultiTouchGestures; case FreeRDP_MultiTouchInput: return settings->MultiTouchInput; case FreeRDP_NSCodec: return settings->NSCodec; case FreeRDP_NSCodecAllowDynamicColorFidelity: return settings->NSCodecAllowDynamicColorFidelity; case FreeRDP_NSCodecAllowSubsampling: return settings->NSCodecAllowSubsampling; case FreeRDP_NegotiateSecurityLayer: return settings->NegotiateSecurityLayer; case FreeRDP_NetworkAutoDetect: return settings->NetworkAutoDetect; case FreeRDP_NlaSecurity: return settings->NlaSecurity; case FreeRDP_NoBitmapCompressionHeader: return settings->NoBitmapCompressionHeader; case FreeRDP_OldLicenseBehaviour: return settings->OldLicenseBehaviour; case FreeRDP_PasswordIsSmartcardPin: return settings->PasswordIsSmartcardPin; case FreeRDP_PercentScreenUseHeight: return settings->PercentScreenUseHeight; case FreeRDP_PercentScreenUseWidth: return settings->PercentScreenUseWidth; case FreeRDP_PlayRemoteFx: return settings->PlayRemoteFx; case FreeRDP_PreferIPv6OverIPv4: return settings->PreferIPv6OverIPv4; case FreeRDP_PrintReconnectCookie: return settings->PrintReconnectCookie; case FreeRDP_PromptForCredentials: return settings->PromptForCredentials; case FreeRDP_RdpSecurity: return settings->RdpSecurity; case FreeRDP_RedirectClipboard: return settings->RedirectClipboard; case FreeRDP_RedirectDrives: return settings->RedirectDrives; case FreeRDP_RedirectHomeDrive: return settings->RedirectHomeDrive; case FreeRDP_RedirectParallelPorts: return settings->RedirectParallelPorts; case FreeRDP_RedirectPrinters: return settings->RedirectPrinters; case FreeRDP_RedirectSerialPorts: return settings->RedirectSerialPorts; case FreeRDP_RedirectSmartCards: return settings->RedirectSmartCards; case FreeRDP_RefreshRect: return settings->RefreshRect; case FreeRDP_RemdeskVirtualChannel: return settings->RemdeskVirtualChannel; case FreeRDP_RemoteAppLanguageBarSupported: return settings->RemoteAppLanguageBarSupported; case FreeRDP_RemoteApplicationMode: return settings->RemoteApplicationMode; case FreeRDP_RemoteAssistanceMode: return settings->RemoteAssistanceMode; case FreeRDP_RemoteAssistanceRequestControl: return settings->RemoteAssistanceRequestControl; case FreeRDP_RemoteConsoleAudio: return settings->RemoteConsoleAudio; case FreeRDP_RemoteFxCodec: return settings->RemoteFxCodec; case FreeRDP_RemoteFxImageCodec: return settings->RemoteFxImageCodec; case FreeRDP_RemoteFxOnly: return settings->RemoteFxOnly; case FreeRDP_RestrictedAdminModeRequired: return settings->RestrictedAdminModeRequired; case FreeRDP_SaltedChecksum: return settings->SaltedChecksum; case FreeRDP_SendPreconnectionPdu: return settings->SendPreconnectionPdu; case FreeRDP_ServerMode: return settings->ServerMode; case FreeRDP_SmartSizing: return settings->SmartSizing; case FreeRDP_SmartcardEmulation: return settings->SmartcardEmulation; case FreeRDP_SmartcardLogon: return settings->SmartcardLogon; case FreeRDP_SoftwareGdi: return settings->SoftwareGdi; case FreeRDP_SoundBeepsEnabled: return settings->SoundBeepsEnabled; case FreeRDP_SpanMonitors: return settings->SpanMonitors; case FreeRDP_SupportAsymetricKeys: return settings->SupportAsymetricKeys; case FreeRDP_SupportDisplayControl: return settings->SupportDisplayControl; case FreeRDP_SupportDynamicChannels: return settings->SupportDynamicChannels; case FreeRDP_SupportDynamicTimeZone: return settings->SupportDynamicTimeZone; case FreeRDP_SupportEchoChannel: return settings->SupportEchoChannel; case FreeRDP_SupportErrorInfoPdu: return settings->SupportErrorInfoPdu; case FreeRDP_SupportGeometryTracking: return settings->SupportGeometryTracking; case FreeRDP_SupportGraphicsPipeline: return settings->SupportGraphicsPipeline; case FreeRDP_SupportHeartbeatPdu: return settings->SupportHeartbeatPdu; case FreeRDP_SupportMonitorLayoutPdu: return settings->SupportMonitorLayoutPdu; case FreeRDP_SupportMultitransport: return settings->SupportMultitransport; case FreeRDP_SupportSSHAgentChannel: return settings->SupportSSHAgentChannel; case FreeRDP_SupportStatusInfoPdu: return settings->SupportStatusInfoPdu; case FreeRDP_SupportVideoOptimized: return settings->SupportVideoOptimized; case FreeRDP_SuppressOutput: return settings->SuppressOutput; case FreeRDP_SurfaceCommandsEnabled: return settings->SurfaceCommandsEnabled; case FreeRDP_SurfaceFrameMarkerEnabled: return settings->SurfaceFrameMarkerEnabled; case FreeRDP_SuspendInput: return settings->SuspendInput; case FreeRDP_TcpKeepAlive: return settings->TcpKeepAlive; case FreeRDP_TlsSecurity: return settings->TlsSecurity; case FreeRDP_ToggleFullscreen: return settings->ToggleFullscreen; case FreeRDP_TransportDump: return settings->TransportDump; case FreeRDP_TransportDumpReplay: return settings->TransportDumpReplay; case FreeRDP_UnicodeInput: return settings->UnicodeInput; case FreeRDP_UnmapButtons: return settings->UnmapButtons; case FreeRDP_UseMultimon: return settings->UseMultimon; case FreeRDP_UseRdpSecurityLayer: return settings->UseRdpSecurityLayer; case FreeRDP_UsingSavedCredentials: return settings->UsingSavedCredentials; case FreeRDP_VideoDisable: return settings->VideoDisable; case FreeRDP_VmConnectMode: return settings->VmConnectMode; case FreeRDP_WaitForOutputBufferFlush: return settings->WaitForOutputBufferFlush; case FreeRDP_Workarea: return settings->Workarea; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_bool(rdpSettings* settings, size_t id, BOOL val) { union { void* v; const void* cv; BOOL c; const BOOL cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { case FreeRDP_AllowCacheWaitingList: settings->AllowCacheWaitingList = cnv.c; break; case FreeRDP_AllowDesktopComposition: settings->AllowDesktopComposition = cnv.c; break; case FreeRDP_AllowFontSmoothing: settings->AllowFontSmoothing = cnv.c; break; case FreeRDP_AllowUnanouncedOrdersFromServer: settings->AllowUnanouncedOrdersFromServer = cnv.c; break; case FreeRDP_AltSecFrameMarkerSupport: settings->AltSecFrameMarkerSupport = cnv.c; break; case FreeRDP_AsyncChannels: settings->AsyncChannels = cnv.c; break; case FreeRDP_AsyncUpdate: settings->AsyncUpdate = cnv.c; break; case FreeRDP_AudioCapture: settings->AudioCapture = cnv.c; break; case FreeRDP_AudioPlayback: settings->AudioPlayback = cnv.c; break; case FreeRDP_Authentication: settings->Authentication = cnv.c; break; case FreeRDP_AuthenticationOnly: settings->AuthenticationOnly = cnv.c; break; case FreeRDP_AutoAcceptCertificate: settings->AutoAcceptCertificate = cnv.c; break; case FreeRDP_AutoDenyCertificate: settings->AutoDenyCertificate = cnv.c; break; case FreeRDP_AutoLogonEnabled: settings->AutoLogonEnabled = cnv.c; break; case FreeRDP_AutoReconnectionEnabled: settings->AutoReconnectionEnabled = cnv.c; break; case FreeRDP_BitmapCacheEnabled: settings->BitmapCacheEnabled = cnv.c; break; case FreeRDP_BitmapCachePersistEnabled: settings->BitmapCachePersistEnabled = cnv.c; break; case FreeRDP_BitmapCacheV3Enabled: settings->BitmapCacheV3Enabled = cnv.c; break; case FreeRDP_BitmapCompressionDisabled: settings->BitmapCompressionDisabled = cnv.c; break; case FreeRDP_CertificateCallbackPreferPEM: settings->CertificateCallbackPreferPEM = cnv.c; break; case FreeRDP_CertificateUseKnownHosts: settings->CertificateUseKnownHosts = cnv.c; break; case FreeRDP_ColorPointerFlag: settings->ColorPointerFlag = cnv.c; break; case FreeRDP_CompressionEnabled: settings->CompressionEnabled = cnv.c; break; case FreeRDP_ConsoleSession: settings->ConsoleSession = cnv.c; break; case FreeRDP_CredentialsFromStdin: settings->CredentialsFromStdin = cnv.c; break; case FreeRDP_DeactivateClientDecoding: settings->DeactivateClientDecoding = cnv.c; break; case FreeRDP_Decorations: settings->Decorations = cnv.c; break; case FreeRDP_DesktopResize: settings->DesktopResize = cnv.c; break; case FreeRDP_DeviceRedirection: settings->DeviceRedirection = cnv.c; break; case FreeRDP_DisableCredentialsDelegation: settings->DisableCredentialsDelegation = cnv.c; break; case FreeRDP_DisableCtrlAltDel: settings->DisableCtrlAltDel = cnv.c; break; case FreeRDP_DisableCursorBlinking: settings->DisableCursorBlinking = cnv.c; break; case FreeRDP_DisableCursorShadow: settings->DisableCursorShadow = cnv.c; break; case FreeRDP_DisableFullWindowDrag: settings->DisableFullWindowDrag = cnv.c; break; case FreeRDP_DisableMenuAnims: settings->DisableMenuAnims = cnv.c; break; case FreeRDP_DisableRemoteAppCapsCheck: settings->DisableRemoteAppCapsCheck = cnv.c; break; case FreeRDP_DisableThemes: settings->DisableThemes = cnv.c; break; case FreeRDP_DisableWallpaper: settings->DisableWallpaper = cnv.c; break; case FreeRDP_DrawAllowColorSubsampling: settings->DrawAllowColorSubsampling = cnv.c; break; case FreeRDP_DrawAllowDynamicColorFidelity: settings->DrawAllowDynamicColorFidelity = cnv.c; break; case FreeRDP_DrawAllowSkipAlpha: settings->DrawAllowSkipAlpha = cnv.c; break; case FreeRDP_DrawGdiPlusCacheEnabled: settings->DrawGdiPlusCacheEnabled = cnv.c; break; case FreeRDP_DrawGdiPlusEnabled: settings->DrawGdiPlusEnabled = cnv.c; break; case FreeRDP_DrawNineGridEnabled: settings->DrawNineGridEnabled = cnv.c; break; case FreeRDP_DumpRemoteFx: settings->DumpRemoteFx = cnv.c; break; case FreeRDP_DynamicDaylightTimeDisabled: settings->DynamicDaylightTimeDisabled = cnv.c; break; case FreeRDP_DynamicResolutionUpdate: settings->DynamicResolutionUpdate = cnv.c; break; case FreeRDP_EmbeddedWindow: settings->EmbeddedWindow = cnv.c; break; case FreeRDP_EnableWindowsKey: settings->EnableWindowsKey = cnv.c; break; case FreeRDP_EncomspVirtualChannel: settings->EncomspVirtualChannel = cnv.c; break; case FreeRDP_ExtSecurity: settings->ExtSecurity = cnv.c; break; case FreeRDP_ExternalCertificateManagement: settings->ExternalCertificateManagement = cnv.c; break; case FreeRDP_FIPSMode: settings->FIPSMode = cnv.c; break; case FreeRDP_FastPathInput: settings->FastPathInput = cnv.c; break; case FreeRDP_FastPathOutput: settings->FastPathOutput = cnv.c; break; case FreeRDP_ForceEncryptedCsPdu: settings->ForceEncryptedCsPdu = cnv.c; break; case FreeRDP_ForceMultimon: settings->ForceMultimon = cnv.c; break; case FreeRDP_FrameMarkerCommandEnabled: settings->FrameMarkerCommandEnabled = cnv.c; break; case FreeRDP_Fullscreen: settings->Fullscreen = cnv.c; break; case FreeRDP_GatewayBypassLocal: settings->GatewayBypassLocal = cnv.c; break; case FreeRDP_GatewayEnabled: settings->GatewayEnabled = cnv.c; break; case FreeRDP_GatewayHttpTransport: settings->GatewayHttpTransport = cnv.c; break; case FreeRDP_GatewayHttpUseWebsockets: settings->GatewayHttpUseWebsockets = cnv.c; break; case FreeRDP_GatewayRpcTransport: settings->GatewayRpcTransport = cnv.c; break; case FreeRDP_GatewayUdpTransport: settings->GatewayUdpTransport = cnv.c; break; case FreeRDP_GatewayUseSameCredentials: settings->GatewayUseSameCredentials = cnv.c; break; case FreeRDP_GfxAVC444: settings->GfxAVC444 = cnv.c; break; case FreeRDP_GfxAVC444v2: settings->GfxAVC444v2 = cnv.c; break; case FreeRDP_GfxH264: settings->GfxH264 = cnv.c; break; case FreeRDP_GfxPlanar: settings->GfxPlanar = cnv.c; break; case FreeRDP_GfxProgressive: settings->GfxProgressive = cnv.c; break; case FreeRDP_GfxProgressiveV2: settings->GfxProgressiveV2 = cnv.c; break; case FreeRDP_GfxSendQoeAck: settings->GfxSendQoeAck = cnv.c; break; case FreeRDP_GfxSmallCache: settings->GfxSmallCache = cnv.c; break; case FreeRDP_GfxThinClient: settings->GfxThinClient = cnv.c; break; case FreeRDP_GrabKeyboard: settings->GrabKeyboard = cnv.c; break; case FreeRDP_GrabMouse: settings->GrabMouse = cnv.c; break; case FreeRDP_HasExtendedMouseEvent: settings->HasExtendedMouseEvent = cnv.c; break; case FreeRDP_HasHorizontalWheel: settings->HasHorizontalWheel = cnv.c; break; case FreeRDP_HasMonitorAttributes: settings->HasMonitorAttributes = cnv.c; break; case FreeRDP_HiDefRemoteApp: settings->HiDefRemoteApp = cnv.c; break; case FreeRDP_IPv6Enabled: settings->IPv6Enabled = cnv.c; break; case FreeRDP_IgnoreCertificate: settings->IgnoreCertificate = cnv.c; break; case FreeRDP_JpegCodec: settings->JpegCodec = cnv.c; break; case FreeRDP_ListMonitors: settings->ListMonitors = cnv.c; break; case FreeRDP_LocalConnection: settings->LocalConnection = cnv.c; break; case FreeRDP_LogonErrors: settings->LogonErrors = cnv.c; break; case FreeRDP_LogonNotify: settings->LogonNotify = cnv.c; break; case FreeRDP_LongCredentialsSupported: settings->LongCredentialsSupported = cnv.c; break; case FreeRDP_LyncRdpMode: settings->LyncRdpMode = cnv.c; break; case FreeRDP_MaximizeShell: settings->MaximizeShell = cnv.c; break; case FreeRDP_MouseAttached: settings->MouseAttached = cnv.c; break; case FreeRDP_MouseHasWheel: settings->MouseHasWheel = cnv.c; break; case FreeRDP_MouseMotion: settings->MouseMotion = cnv.c; break; case FreeRDP_MouseUseRelativeMove: settings->MouseUseRelativeMove = cnv.c; break; case FreeRDP_MstscCookieMode: settings->MstscCookieMode = cnv.c; break; case FreeRDP_MultiTouchGestures: settings->MultiTouchGestures = cnv.c; break; case FreeRDP_MultiTouchInput: settings->MultiTouchInput = cnv.c; break; case FreeRDP_NSCodec: settings->NSCodec = cnv.c; break; case FreeRDP_NSCodecAllowDynamicColorFidelity: settings->NSCodecAllowDynamicColorFidelity = cnv.c; break; case FreeRDP_NSCodecAllowSubsampling: settings->NSCodecAllowSubsampling = cnv.c; break; case FreeRDP_NegotiateSecurityLayer: settings->NegotiateSecurityLayer = cnv.c; break; case FreeRDP_NetworkAutoDetect: settings->NetworkAutoDetect = cnv.c; break; case FreeRDP_NlaSecurity: settings->NlaSecurity = cnv.c; break; case FreeRDP_NoBitmapCompressionHeader: settings->NoBitmapCompressionHeader = cnv.c; break; case FreeRDP_OldLicenseBehaviour: settings->OldLicenseBehaviour = cnv.c; break; case FreeRDP_PasswordIsSmartcardPin: settings->PasswordIsSmartcardPin = cnv.c; break; case FreeRDP_PercentScreenUseHeight: settings->PercentScreenUseHeight = cnv.c; break; case FreeRDP_PercentScreenUseWidth: settings->PercentScreenUseWidth = cnv.c; break; case FreeRDP_PlayRemoteFx: settings->PlayRemoteFx = cnv.c; break; case FreeRDP_PreferIPv6OverIPv4: settings->PreferIPv6OverIPv4 = cnv.c; break; case FreeRDP_PrintReconnectCookie: settings->PrintReconnectCookie = cnv.c; break; case FreeRDP_PromptForCredentials: settings->PromptForCredentials = cnv.c; break; case FreeRDP_RdpSecurity: settings->RdpSecurity = cnv.c; break; case FreeRDP_RedirectClipboard: settings->RedirectClipboard = cnv.c; break; case FreeRDP_RedirectDrives: settings->RedirectDrives = cnv.c; break; case FreeRDP_RedirectHomeDrive: settings->RedirectHomeDrive = cnv.c; break; case FreeRDP_RedirectParallelPorts: settings->RedirectParallelPorts = cnv.c; break; case FreeRDP_RedirectPrinters: settings->RedirectPrinters = cnv.c; break; case FreeRDP_RedirectSerialPorts: settings->RedirectSerialPorts = cnv.c; break; case FreeRDP_RedirectSmartCards: settings->RedirectSmartCards = cnv.c; break; case FreeRDP_RefreshRect: settings->RefreshRect = cnv.c; break; case FreeRDP_RemdeskVirtualChannel: settings->RemdeskVirtualChannel = cnv.c; break; case FreeRDP_RemoteAppLanguageBarSupported: settings->RemoteAppLanguageBarSupported = cnv.c; break; case FreeRDP_RemoteApplicationMode: settings->RemoteApplicationMode = cnv.c; break; case FreeRDP_RemoteAssistanceMode: settings->RemoteAssistanceMode = cnv.c; break; case FreeRDP_RemoteAssistanceRequestControl: settings->RemoteAssistanceRequestControl = cnv.c; break; case FreeRDP_RemoteConsoleAudio: settings->RemoteConsoleAudio = cnv.c; break; case FreeRDP_RemoteFxCodec: settings->RemoteFxCodec = cnv.c; break; case FreeRDP_RemoteFxImageCodec: settings->RemoteFxImageCodec = cnv.c; break; case FreeRDP_RemoteFxOnly: settings->RemoteFxOnly = cnv.c; break; case FreeRDP_RestrictedAdminModeRequired: settings->RestrictedAdminModeRequired = cnv.c; break; case FreeRDP_SaltedChecksum: settings->SaltedChecksum = cnv.c; break; case FreeRDP_SendPreconnectionPdu: settings->SendPreconnectionPdu = cnv.c; break; case FreeRDP_ServerMode: settings->ServerMode = cnv.c; break; case FreeRDP_SmartSizing: settings->SmartSizing = cnv.c; break; case FreeRDP_SmartcardEmulation: settings->SmartcardEmulation = cnv.c; break; case FreeRDP_SmartcardLogon: settings->SmartcardLogon = cnv.c; break; case FreeRDP_SoftwareGdi: settings->SoftwareGdi = cnv.c; break; case FreeRDP_SoundBeepsEnabled: settings->SoundBeepsEnabled = cnv.c; break; case FreeRDP_SpanMonitors: settings->SpanMonitors = cnv.c; break; case FreeRDP_SupportAsymetricKeys: settings->SupportAsymetricKeys = cnv.c; break; case FreeRDP_SupportDisplayControl: settings->SupportDisplayControl = cnv.c; break; case FreeRDP_SupportDynamicChannels: settings->SupportDynamicChannels = cnv.c; break; case FreeRDP_SupportDynamicTimeZone: settings->SupportDynamicTimeZone = cnv.c; break; case FreeRDP_SupportEchoChannel: settings->SupportEchoChannel = cnv.c; break; case FreeRDP_SupportErrorInfoPdu: settings->SupportErrorInfoPdu = cnv.c; break; case FreeRDP_SupportGeometryTracking: settings->SupportGeometryTracking = cnv.c; break; case FreeRDP_SupportGraphicsPipeline: settings->SupportGraphicsPipeline = cnv.c; break; case FreeRDP_SupportHeartbeatPdu: settings->SupportHeartbeatPdu = cnv.c; break; case FreeRDP_SupportMonitorLayoutPdu: settings->SupportMonitorLayoutPdu = cnv.c; break; case FreeRDP_SupportMultitransport: settings->SupportMultitransport = cnv.c; break; case FreeRDP_SupportSSHAgentChannel: settings->SupportSSHAgentChannel = cnv.c; break; case FreeRDP_SupportStatusInfoPdu: settings->SupportStatusInfoPdu = cnv.c; break; case FreeRDP_SupportVideoOptimized: settings->SupportVideoOptimized = cnv.c; break; case FreeRDP_SuppressOutput: settings->SuppressOutput = cnv.c; break; case FreeRDP_SurfaceCommandsEnabled: settings->SurfaceCommandsEnabled = cnv.c; break; case FreeRDP_SurfaceFrameMarkerEnabled: settings->SurfaceFrameMarkerEnabled = cnv.c; break; case FreeRDP_SuspendInput: settings->SuspendInput = cnv.c; break; case FreeRDP_TcpKeepAlive: settings->TcpKeepAlive = cnv.c; break; case FreeRDP_TlsSecurity: settings->TlsSecurity = cnv.c; break; case FreeRDP_ToggleFullscreen: settings->ToggleFullscreen = cnv.c; break; case FreeRDP_TransportDump: settings->TransportDump = cnv.c; break; case FreeRDP_TransportDumpReplay: settings->TransportDumpReplay = cnv.c; break; case FreeRDP_UnicodeInput: settings->UnicodeInput = cnv.c; break; case FreeRDP_UnmapButtons: settings->UnmapButtons = cnv.c; break; case FreeRDP_UseMultimon: settings->UseMultimon = cnv.c; break; case FreeRDP_UseRdpSecurityLayer: settings->UseRdpSecurityLayer = cnv.c; break; case FreeRDP_UsingSavedCredentials: settings->UsingSavedCredentials = cnv.c; break; case FreeRDP_VideoDisable: settings->VideoDisable = cnv.c; break; case FreeRDP_VmConnectMode: settings->VmConnectMode = cnv.c; break; case FreeRDP_WaitForOutputBufferFlush: settings->WaitForOutputBufferFlush = cnv.c; break; case FreeRDP_Workarea: settings->Workarea = cnv.c; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } UINT16 freerdp_settings_get_uint16(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_DesktopOrientation: return settings->DesktopOrientation; case FreeRDP_ProxyPort: return settings->ProxyPort; case FreeRDP_TLSMaxVersion: return settings->TLSMaxVersion; case FreeRDP_TLSMinVersion: return settings->TLSMinVersion; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_uint16(rdpSettings* settings, size_t id, UINT16 val) { union { void* v; const void* cv; UINT16 c; const UINT16 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { case FreeRDP_DesktopOrientation: settings->DesktopOrientation = cnv.c; break; case FreeRDP_ProxyPort: settings->ProxyPort = cnv.c; break; case FreeRDP_TLSMaxVersion: settings->TLSMaxVersion = cnv.c; break; case FreeRDP_TLSMinVersion: settings->TLSMinVersion = cnv.c; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } INT16 freerdp_settings_get_int16(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_int16(rdpSettings* settings, size_t id, INT16 val) { union { void* v; const void* cv; INT16 c; const INT16 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } UINT32 freerdp_settings_get_uint32(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_AcceptedCertLength: return settings->AcceptedCertLength; case FreeRDP_AuthenticationLevel: return settings->AuthenticationLevel; case FreeRDP_AutoReconnectMaxRetries: return settings->AutoReconnectMaxRetries; case FreeRDP_BitmapCacheV2NumCells: return settings->BitmapCacheV2NumCells; case FreeRDP_BitmapCacheV3CodecId: return settings->BitmapCacheV3CodecId; case FreeRDP_BitmapCacheVersion: return settings->BitmapCacheVersion; case FreeRDP_BrushSupportLevel: return settings->BrushSupportLevel; case FreeRDP_ChannelCount: return settings->ChannelCount; case FreeRDP_ChannelDefArraySize: return settings->ChannelDefArraySize; case FreeRDP_ClientBuild: return settings->ClientBuild; case FreeRDP_ClientRandomLength: return settings->ClientRandomLength; case FreeRDP_ClientSessionId: return settings->ClientSessionId; case FreeRDP_ClusterInfoFlags: return settings->ClusterInfoFlags; case FreeRDP_ColorDepth: return settings->ColorDepth; case FreeRDP_CompDeskSupportLevel: return settings->CompDeskSupportLevel; case FreeRDP_CompressionLevel: return settings->CompressionLevel; case FreeRDP_ConnectionType: return settings->ConnectionType; case FreeRDP_CookieMaxLength: return settings->CookieMaxLength; case FreeRDP_DesktopHeight: return settings->DesktopHeight; case FreeRDP_DesktopPhysicalHeight: return settings->DesktopPhysicalHeight; case FreeRDP_DesktopPhysicalWidth: return settings->DesktopPhysicalWidth; case FreeRDP_DesktopPosX: return settings->DesktopPosX; case FreeRDP_DesktopPosY: return settings->DesktopPosY; case FreeRDP_DesktopScaleFactor: return settings->DesktopScaleFactor; case FreeRDP_DesktopWidth: return settings->DesktopWidth; case FreeRDP_DeviceArraySize: return settings->DeviceArraySize; case FreeRDP_DeviceCount: return settings->DeviceCount; case FreeRDP_DeviceScaleFactor: return settings->DeviceScaleFactor; case FreeRDP_DrawNineGridCacheEntries: return settings->DrawNineGridCacheEntries; case FreeRDP_DrawNineGridCacheSize: return settings->DrawNineGridCacheSize; case FreeRDP_DynamicChannelArraySize: return settings->DynamicChannelArraySize; case FreeRDP_DynamicChannelCount: return settings->DynamicChannelCount; case FreeRDP_EarlyCapabilityFlags: return settings->EarlyCapabilityFlags; case FreeRDP_EncryptionLevel: return settings->EncryptionLevel; case FreeRDP_EncryptionMethods: return settings->EncryptionMethods; case FreeRDP_ExtEncryptionMethods: return settings->ExtEncryptionMethods; case FreeRDP_Floatbar: return settings->Floatbar; case FreeRDP_FrameAcknowledge: return settings->FrameAcknowledge; case FreeRDP_GatewayAcceptedCertLength: return settings->GatewayAcceptedCertLength; case FreeRDP_GatewayCredentialsSource: return settings->GatewayCredentialsSource; case FreeRDP_GatewayPort: return settings->GatewayPort; case FreeRDP_GatewayUsageMethod: return settings->GatewayUsageMethod; case FreeRDP_GfxCapsFilter: return settings->GfxCapsFilter; case FreeRDP_GlyphSupportLevel: return settings->GlyphSupportLevel; case FreeRDP_JpegCodecId: return settings->JpegCodecId; case FreeRDP_JpegQuality: return settings->JpegQuality; case FreeRDP_KeySpec: return settings->KeySpec; case FreeRDP_KeyboardCodePage: return settings->KeyboardCodePage; case FreeRDP_KeyboardFunctionKey: return settings->KeyboardFunctionKey; case FreeRDP_KeyboardHook: return settings->KeyboardHook; case FreeRDP_KeyboardLayout: return settings->KeyboardLayout; case FreeRDP_KeyboardSubType: return settings->KeyboardSubType; case FreeRDP_KeyboardType: return settings->KeyboardType; case FreeRDP_LargePointerFlag: return settings->LargePointerFlag; case FreeRDP_LoadBalanceInfoLength: return settings->LoadBalanceInfoLength; case FreeRDP_MaxTimeInCheckLoop: return settings->MaxTimeInCheckLoop; case FreeRDP_MonitorAttributeFlags: return settings->MonitorAttributeFlags; case FreeRDP_MonitorCount: return settings->MonitorCount; case FreeRDP_MonitorDefArraySize: return settings->MonitorDefArraySize; case FreeRDP_MonitorFlags: return settings->MonitorFlags; case FreeRDP_MonitorLocalShiftX: return settings->MonitorLocalShiftX; case FreeRDP_MonitorLocalShiftY: return settings->MonitorLocalShiftY; case FreeRDP_MultifragMaxRequestSize: return settings->MultifragMaxRequestSize; case FreeRDP_MultitransportFlags: return settings->MultitransportFlags; case FreeRDP_NSCodecColorLossLevel: return settings->NSCodecColorLossLevel; case FreeRDP_NSCodecId: return settings->NSCodecId; case FreeRDP_NegotiationFlags: return settings->NegotiationFlags; case FreeRDP_NumMonitorIds: return settings->NumMonitorIds; case FreeRDP_OffscreenCacheEntries: return settings->OffscreenCacheEntries; case FreeRDP_OffscreenCacheSize: return settings->OffscreenCacheSize; case FreeRDP_OffscreenSupportLevel: return settings->OffscreenSupportLevel; case FreeRDP_OsMajorType: return settings->OsMajorType; case FreeRDP_OsMinorType: return settings->OsMinorType; case FreeRDP_Password51Length: return settings->Password51Length; case FreeRDP_PduSource: return settings->PduSource; case FreeRDP_PercentScreen: return settings->PercentScreen; case FreeRDP_PerformanceFlags: return settings->PerformanceFlags; case FreeRDP_PointerCacheSize: return settings->PointerCacheSize; case FreeRDP_PreconnectionId: return settings->PreconnectionId; case FreeRDP_ProxyType: return settings->ProxyType; case FreeRDP_RdpVersion: return settings->RdpVersion; case FreeRDP_ReceivedCapabilitiesSize: return settings->ReceivedCapabilitiesSize; case FreeRDP_RedirectedSessionId: return settings->RedirectedSessionId; case FreeRDP_RedirectionAcceptedCertLength: return settings->RedirectionAcceptedCertLength; case FreeRDP_RedirectionFlags: return settings->RedirectionFlags; case FreeRDP_RedirectionPasswordLength: return settings->RedirectionPasswordLength; case FreeRDP_RedirectionPreferType: return settings->RedirectionPreferType; case FreeRDP_RedirectionTsvUrlLength: return settings->RedirectionTsvUrlLength; case FreeRDP_RemoteAppNumIconCacheEntries: return settings->RemoteAppNumIconCacheEntries; case FreeRDP_RemoteAppNumIconCaches: return settings->RemoteAppNumIconCaches; case FreeRDP_RemoteApplicationExpandCmdLine: return settings->RemoteApplicationExpandCmdLine; case FreeRDP_RemoteApplicationExpandWorkingDir: return settings->RemoteApplicationExpandWorkingDir; case FreeRDP_RemoteApplicationSupportLevel: return settings->RemoteApplicationSupportLevel; case FreeRDP_RemoteApplicationSupportMask: return settings->RemoteApplicationSupportMask; case FreeRDP_RemoteFxCaptureFlags: return settings->RemoteFxCaptureFlags; case FreeRDP_RemoteFxCodecId: return settings->RemoteFxCodecId; case FreeRDP_RemoteFxCodecMode: return settings->RemoteFxCodecMode; case FreeRDP_RemoteWndSupportLevel: return settings->RemoteWndSupportLevel; case FreeRDP_RequestedProtocols: return settings->RequestedProtocols; case FreeRDP_SelectedProtocol: return settings->SelectedProtocol; case FreeRDP_ServerCertificateLength: return settings->ServerCertificateLength; case FreeRDP_ServerPort: return settings->ServerPort; case FreeRDP_ServerRandomLength: return settings->ServerRandomLength; case FreeRDP_ShareId: return settings->ShareId; case FreeRDP_SmartSizingHeight: return settings->SmartSizingHeight; case FreeRDP_SmartSizingWidth: return settings->SmartSizingWidth; case FreeRDP_StaticChannelArraySize: return settings->StaticChannelArraySize; case FreeRDP_StaticChannelCount: return settings->StaticChannelCount; case FreeRDP_TargetNetAddressCount: return settings->TargetNetAddressCount; case FreeRDP_TcpAckTimeout: return settings->TcpAckTimeout; case FreeRDP_TcpConnectTimeout: return settings->TcpConnectTimeout; case FreeRDP_TcpKeepAliveDelay: return settings->TcpKeepAliveDelay; case FreeRDP_TcpKeepAliveInterval: return settings->TcpKeepAliveInterval; case FreeRDP_TcpKeepAliveRetries: return settings->TcpKeepAliveRetries; case FreeRDP_ThreadingFlags: return settings->ThreadingFlags; case FreeRDP_TlsSecLevel: return settings->TlsSecLevel; case FreeRDP_VirtualChannelChunkSize: return settings->VirtualChannelChunkSize; case FreeRDP_VirtualChannelCompressionFlags: return settings->VirtualChannelCompressionFlags; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_uint32(rdpSettings* settings, size_t id, UINT32 val) { union { void* v; const void* cv; UINT32 c; const UINT32 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { case FreeRDP_AcceptedCertLength: settings->AcceptedCertLength = cnv.c; break; case FreeRDP_AuthenticationLevel: settings->AuthenticationLevel = cnv.c; break; case FreeRDP_AutoReconnectMaxRetries: settings->AutoReconnectMaxRetries = cnv.c; break; case FreeRDP_BitmapCacheV2NumCells: settings->BitmapCacheV2NumCells = cnv.c; break; case FreeRDP_BitmapCacheV3CodecId: settings->BitmapCacheV3CodecId = cnv.c; break; case FreeRDP_BitmapCacheVersion: settings->BitmapCacheVersion = cnv.c; break; case FreeRDP_BrushSupportLevel: settings->BrushSupportLevel = cnv.c; break; case FreeRDP_ChannelCount: settings->ChannelCount = cnv.c; break; case FreeRDP_ChannelDefArraySize: settings->ChannelDefArraySize = cnv.c; break; case FreeRDP_ClientBuild: settings->ClientBuild = cnv.c; break; case FreeRDP_ClientRandomLength: settings->ClientRandomLength = cnv.c; break; case FreeRDP_ClientSessionId: settings->ClientSessionId = cnv.c; break; case FreeRDP_ClusterInfoFlags: settings->ClusterInfoFlags = cnv.c; break; case FreeRDP_ColorDepth: settings->ColorDepth = cnv.c; break; case FreeRDP_CompDeskSupportLevel: settings->CompDeskSupportLevel = cnv.c; break; case FreeRDP_CompressionLevel: settings->CompressionLevel = cnv.c; break; case FreeRDP_ConnectionType: settings->ConnectionType = cnv.c; break; case FreeRDP_CookieMaxLength: settings->CookieMaxLength = cnv.c; break; case FreeRDP_DesktopHeight: settings->DesktopHeight = cnv.c; break; case FreeRDP_DesktopPhysicalHeight: settings->DesktopPhysicalHeight = cnv.c; break; case FreeRDP_DesktopPhysicalWidth: settings->DesktopPhysicalWidth = cnv.c; break; case FreeRDP_DesktopPosX: settings->DesktopPosX = cnv.c; break; case FreeRDP_DesktopPosY: settings->DesktopPosY = cnv.c; break; case FreeRDP_DesktopScaleFactor: settings->DesktopScaleFactor = cnv.c; break; case FreeRDP_DesktopWidth: settings->DesktopWidth = cnv.c; break; case FreeRDP_DeviceArraySize: settings->DeviceArraySize = cnv.c; break; case FreeRDP_DeviceCount: settings->DeviceCount = cnv.c; break; case FreeRDP_DeviceScaleFactor: settings->DeviceScaleFactor = cnv.c; break; case FreeRDP_DrawNineGridCacheEntries: settings->DrawNineGridCacheEntries = cnv.c; break; case FreeRDP_DrawNineGridCacheSize: settings->DrawNineGridCacheSize = cnv.c; break; case FreeRDP_DynamicChannelArraySize: settings->DynamicChannelArraySize = cnv.c; break; case FreeRDP_DynamicChannelCount: settings->DynamicChannelCount = cnv.c; break; case FreeRDP_EarlyCapabilityFlags: settings->EarlyCapabilityFlags = cnv.c; break; case FreeRDP_EncryptionLevel: settings->EncryptionLevel = cnv.c; break; case FreeRDP_EncryptionMethods: settings->EncryptionMethods = cnv.c; break; case FreeRDP_ExtEncryptionMethods: settings->ExtEncryptionMethods = cnv.c; break; case FreeRDP_Floatbar: settings->Floatbar = cnv.c; break; case FreeRDP_FrameAcknowledge: settings->FrameAcknowledge = cnv.c; break; case FreeRDP_GatewayAcceptedCertLength: settings->GatewayAcceptedCertLength = cnv.c; break; case FreeRDP_GatewayCredentialsSource: settings->GatewayCredentialsSource = cnv.c; break; case FreeRDP_GatewayPort: settings->GatewayPort = cnv.c; break; case FreeRDP_GatewayUsageMethod: settings->GatewayUsageMethod = cnv.c; break; case FreeRDP_GfxCapsFilter: settings->GfxCapsFilter = cnv.c; break; case FreeRDP_GlyphSupportLevel: settings->GlyphSupportLevel = cnv.c; break; case FreeRDP_JpegCodecId: settings->JpegCodecId = cnv.c; break; case FreeRDP_JpegQuality: settings->JpegQuality = cnv.c; break; case FreeRDP_KeySpec: settings->KeySpec = cnv.c; break; case FreeRDP_KeyboardCodePage: settings->KeyboardCodePage = cnv.c; break; case FreeRDP_KeyboardFunctionKey: settings->KeyboardFunctionKey = cnv.c; break; case FreeRDP_KeyboardHook: settings->KeyboardHook = cnv.c; break; case FreeRDP_KeyboardLayout: settings->KeyboardLayout = cnv.c; break; case FreeRDP_KeyboardSubType: settings->KeyboardSubType = cnv.c; break; case FreeRDP_KeyboardType: settings->KeyboardType = cnv.c; break; case FreeRDP_LargePointerFlag: settings->LargePointerFlag = cnv.c; break; case FreeRDP_LoadBalanceInfoLength: settings->LoadBalanceInfoLength = cnv.c; break; case FreeRDP_MaxTimeInCheckLoop: settings->MaxTimeInCheckLoop = cnv.c; break; case FreeRDP_MonitorAttributeFlags: settings->MonitorAttributeFlags = cnv.c; break; case FreeRDP_MonitorCount: settings->MonitorCount = cnv.c; break; case FreeRDP_MonitorDefArraySize: settings->MonitorDefArraySize = cnv.c; break; case FreeRDP_MonitorFlags: settings->MonitorFlags = cnv.c; break; case FreeRDP_MonitorLocalShiftX: settings->MonitorLocalShiftX = cnv.c; break; case FreeRDP_MonitorLocalShiftY: settings->MonitorLocalShiftY = cnv.c; break; case FreeRDP_MultifragMaxRequestSize: settings->MultifragMaxRequestSize = cnv.c; break; case FreeRDP_MultitransportFlags: settings->MultitransportFlags = cnv.c; break; case FreeRDP_NSCodecColorLossLevel: settings->NSCodecColorLossLevel = cnv.c; break; case FreeRDP_NSCodecId: settings->NSCodecId = cnv.c; break; case FreeRDP_NegotiationFlags: settings->NegotiationFlags = cnv.c; break; case FreeRDP_NumMonitorIds: settings->NumMonitorIds = cnv.c; break; case FreeRDP_OffscreenCacheEntries: settings->OffscreenCacheEntries = cnv.c; break; case FreeRDP_OffscreenCacheSize: settings->OffscreenCacheSize = cnv.c; break; case FreeRDP_OffscreenSupportLevel: settings->OffscreenSupportLevel = cnv.c; break; case FreeRDP_OsMajorType: settings->OsMajorType = cnv.c; break; case FreeRDP_OsMinorType: settings->OsMinorType = cnv.c; break; case FreeRDP_Password51Length: settings->Password51Length = cnv.c; break; case FreeRDP_PduSource: settings->PduSource = cnv.c; break; case FreeRDP_PercentScreen: settings->PercentScreen = cnv.c; break; case FreeRDP_PerformanceFlags: settings->PerformanceFlags = cnv.c; break; case FreeRDP_PointerCacheSize: settings->PointerCacheSize = cnv.c; break; case FreeRDP_PreconnectionId: settings->PreconnectionId = cnv.c; break; case FreeRDP_ProxyType: settings->ProxyType = cnv.c; break; case FreeRDP_RdpVersion: settings->RdpVersion = cnv.c; break; case FreeRDP_ReceivedCapabilitiesSize: settings->ReceivedCapabilitiesSize = cnv.c; break; case FreeRDP_RedirectedSessionId: settings->RedirectedSessionId = cnv.c; break; case FreeRDP_RedirectionAcceptedCertLength: settings->RedirectionAcceptedCertLength = cnv.c; break; case FreeRDP_RedirectionFlags: settings->RedirectionFlags = cnv.c; break; case FreeRDP_RedirectionPasswordLength: settings->RedirectionPasswordLength = cnv.c; break; case FreeRDP_RedirectionPreferType: settings->RedirectionPreferType = cnv.c; break; case FreeRDP_RedirectionTsvUrlLength: settings->RedirectionTsvUrlLength = cnv.c; break; case FreeRDP_RemoteAppNumIconCacheEntries: settings->RemoteAppNumIconCacheEntries = cnv.c; break; case FreeRDP_RemoteAppNumIconCaches: settings->RemoteAppNumIconCaches = cnv.c; break; case FreeRDP_RemoteApplicationExpandCmdLine: settings->RemoteApplicationExpandCmdLine = cnv.c; break; case FreeRDP_RemoteApplicationExpandWorkingDir: settings->RemoteApplicationExpandWorkingDir = cnv.c; break; case FreeRDP_RemoteApplicationSupportLevel: settings->RemoteApplicationSupportLevel = cnv.c; break; case FreeRDP_RemoteApplicationSupportMask: settings->RemoteApplicationSupportMask = cnv.c; break; case FreeRDP_RemoteFxCaptureFlags: settings->RemoteFxCaptureFlags = cnv.c; break; case FreeRDP_RemoteFxCodecId: settings->RemoteFxCodecId = cnv.c; break; case FreeRDP_RemoteFxCodecMode: settings->RemoteFxCodecMode = cnv.c; break; case FreeRDP_RemoteWndSupportLevel: settings->RemoteWndSupportLevel = cnv.c; break; case FreeRDP_RequestedProtocols: settings->RequestedProtocols = cnv.c; break; case FreeRDP_SelectedProtocol: settings->SelectedProtocol = cnv.c; break; case FreeRDP_ServerCertificateLength: settings->ServerCertificateLength = cnv.c; break; case FreeRDP_ServerPort: settings->ServerPort = cnv.c; break; case FreeRDP_ServerRandomLength: settings->ServerRandomLength = cnv.c; break; case FreeRDP_ShareId: settings->ShareId = cnv.c; break; case FreeRDP_SmartSizingHeight: settings->SmartSizingHeight = cnv.c; break; case FreeRDP_SmartSizingWidth: settings->SmartSizingWidth = cnv.c; break; case FreeRDP_StaticChannelArraySize: settings->StaticChannelArraySize = cnv.c; break; case FreeRDP_StaticChannelCount: settings->StaticChannelCount = cnv.c; break; case FreeRDP_TargetNetAddressCount: settings->TargetNetAddressCount = cnv.c; break; case FreeRDP_TcpAckTimeout: settings->TcpAckTimeout = cnv.c; break; case FreeRDP_TcpConnectTimeout: settings->TcpConnectTimeout = cnv.c; break; case FreeRDP_TcpKeepAliveDelay: settings->TcpKeepAliveDelay = cnv.c; break; case FreeRDP_TcpKeepAliveInterval: settings->TcpKeepAliveInterval = cnv.c; break; case FreeRDP_TcpKeepAliveRetries: settings->TcpKeepAliveRetries = cnv.c; break; case FreeRDP_ThreadingFlags: settings->ThreadingFlags = cnv.c; break; case FreeRDP_TlsSecLevel: settings->TlsSecLevel = cnv.c; break; case FreeRDP_VirtualChannelChunkSize: settings->VirtualChannelChunkSize = cnv.c; break; case FreeRDP_VirtualChannelCompressionFlags: settings->VirtualChannelCompressionFlags = cnv.c; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } INT32 freerdp_settings_get_int32(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_XPan: return settings->XPan; case FreeRDP_YPan: return settings->YPan; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_int32(rdpSettings* settings, size_t id, INT32 val) { union { void* v; const void* cv; INT32 c; const INT32 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { case FreeRDP_XPan: settings->XPan = cnv.c; break; case FreeRDP_YPan: settings->YPan = cnv.c; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } UINT64 freerdp_settings_get_uint64(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_ParentWindowId: return settings->ParentWindowId; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_uint64(rdpSettings* settings, size_t id, UINT64 val) { union { void* v; const void* cv; UINT64 c; const UINT64 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { case FreeRDP_ParentWindowId: settings->ParentWindowId = cnv.c; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } INT64 freerdp_settings_get_int64(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_int64(rdpSettings* settings, size_t id, INT64 val) { union { void* v; const void* cv; INT64 c; const INT64 cc; } cnv; WINPR_ASSERT(settings); cnv.c = val; switch (id) { default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } const char* freerdp_settings_get_string(const rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_AcceptedCert: return settings->AcceptedCert; case FreeRDP_ActionScript: return settings->ActionScript; case FreeRDP_AllowedTlsCiphers: return settings->AllowedTlsCiphers; case FreeRDP_AlternateShell: return settings->AlternateShell; case FreeRDP_AssistanceFile: return settings->AssistanceFile; case FreeRDP_AuthenticationPackageList: return settings->AuthenticationPackageList; case FreeRDP_AuthenticationServiceClass: return settings->AuthenticationServiceClass; case FreeRDP_BitmapCachePersistFile: return settings->BitmapCachePersistFile; case FreeRDP_CardName: return settings->CardName; case FreeRDP_CertificateAcceptedFingerprints: return settings->CertificateAcceptedFingerprints; case FreeRDP_CertificateContent: return settings->CertificateContent; case FreeRDP_CertificateFile: return settings->CertificateFile; case FreeRDP_CertificateName: return settings->CertificateName; case FreeRDP_ClientAddress: return settings->ClientAddress; case FreeRDP_ClientDir: return settings->ClientDir; case FreeRDP_ClientHostname: return settings->ClientHostname; case FreeRDP_ClientProductId: return settings->ClientProductId; case FreeRDP_ComputerName: return settings->ComputerName; case FreeRDP_ConfigPath: return settings->ConfigPath; case FreeRDP_ConnectionFile: return settings->ConnectionFile; case FreeRDP_ContainerName: return settings->ContainerName; case FreeRDP_CspName: return settings->CspName; case FreeRDP_CurrentPath: return settings->CurrentPath; case FreeRDP_Domain: return settings->Domain; case FreeRDP_DrivesToRedirect: return settings->DrivesToRedirect; case FreeRDP_DumpRemoteFxFile: return settings->DumpRemoteFxFile; case FreeRDP_DynamicDSTTimeZoneKeyName: return settings->DynamicDSTTimeZoneKeyName; case FreeRDP_GatewayAcceptedCert: return settings->GatewayAcceptedCert; case FreeRDP_GatewayAccessToken: return settings->GatewayAccessToken; case FreeRDP_GatewayDomain: return settings->GatewayDomain; case FreeRDP_GatewayHostname: return settings->GatewayHostname; case FreeRDP_GatewayPassword: return settings->GatewayPassword; case FreeRDP_GatewayUsername: return settings->GatewayUsername; case FreeRDP_HomePath: return settings->HomePath; case FreeRDP_ImeFileName: return settings->ImeFileName; case FreeRDP_KerberosArmor: return settings->KerberosArmor; case FreeRDP_KerberosCache: return settings->KerberosCache; case FreeRDP_KerberosKdcUrl: return settings->KerberosKdcUrl; case FreeRDP_KerberosKeytab: return settings->KerberosKeytab; case FreeRDP_KerberosLifeTime: return settings->KerberosLifeTime; case FreeRDP_KerberosRealm: return settings->KerberosRealm; case FreeRDP_KerberosRenewableLifeTime: return settings->KerberosRenewableLifeTime; case FreeRDP_KerberosStartTime: return settings->KerberosStartTime; case FreeRDP_KeyboardRemappingList: return settings->KeyboardRemappingList; case FreeRDP_NtlmSamFile: return settings->NtlmSamFile; case FreeRDP_Password: return settings->Password; case FreeRDP_PasswordHash: return settings->PasswordHash; case FreeRDP_Pkcs11Module: return settings->Pkcs11Module; case FreeRDP_PkinitAnchors: return settings->PkinitAnchors; case FreeRDP_PlayRemoteFxFile: return settings->PlayRemoteFxFile; case FreeRDP_PreconnectionBlob: return settings->PreconnectionBlob; case FreeRDP_PrivateKeyContent: return settings->PrivateKeyContent; case FreeRDP_PrivateKeyFile: return settings->PrivateKeyFile; case FreeRDP_ProxyHostname: return settings->ProxyHostname; case FreeRDP_ProxyPassword: return settings->ProxyPassword; case FreeRDP_ProxyUsername: return settings->ProxyUsername; case FreeRDP_RDP2TCPArgs: return settings->RDP2TCPArgs; case FreeRDP_ReaderName: return settings->ReaderName; case FreeRDP_RedirectionAcceptedCert: return settings->RedirectionAcceptedCert; case FreeRDP_RedirectionDomain: return settings->RedirectionDomain; case FreeRDP_RedirectionTargetFQDN: return settings->RedirectionTargetFQDN; case FreeRDP_RedirectionTargetNetBiosName: return settings->RedirectionTargetNetBiosName; case FreeRDP_RedirectionUsername: return settings->RedirectionUsername; case FreeRDP_RemoteApplicationCmdLine: return settings->RemoteApplicationCmdLine; case FreeRDP_RemoteApplicationFile: return settings->RemoteApplicationFile; case FreeRDP_RemoteApplicationGuid: return settings->RemoteApplicationGuid; case FreeRDP_RemoteApplicationIcon: return settings->RemoteApplicationIcon; case FreeRDP_RemoteApplicationName: return settings->RemoteApplicationName; case FreeRDP_RemoteApplicationProgram: return settings->RemoteApplicationProgram; case FreeRDP_RemoteApplicationWorkingDir: return settings->RemoteApplicationWorkingDir; case FreeRDP_RemoteAssistancePassStub: return settings->RemoteAssistancePassStub; case FreeRDP_RemoteAssistancePassword: return settings->RemoteAssistancePassword; case FreeRDP_RemoteAssistanceRCTicket: return settings->RemoteAssistanceRCTicket; case FreeRDP_RemoteAssistanceSessionId: return settings->RemoteAssistanceSessionId; case FreeRDP_ServerHostname: return settings->ServerHostname; case FreeRDP_ShellWorkingDirectory: return settings->ShellWorkingDirectory; case FreeRDP_SmartcardCertificate: return settings->SmartcardCertificate; case FreeRDP_SmartcardPrivateKey: return settings->SmartcardPrivateKey; case FreeRDP_SspiModule: return settings->SspiModule; case FreeRDP_TargetNetAddress: return settings->TargetNetAddress; case FreeRDP_TlsSecretsFile: return settings->TlsSecretsFile; case FreeRDP_TransportDumpFile: return settings->TransportDumpFile; case FreeRDP_Username: return settings->Username; case FreeRDP_WindowTitle: return settings->WindowTitle; case FreeRDP_WmClass: return settings->WmClass; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } char* freerdp_settings_get_string_writable(rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_AcceptedCert: return settings->AcceptedCert; case FreeRDP_ActionScript: return settings->ActionScript; case FreeRDP_AllowedTlsCiphers: return settings->AllowedTlsCiphers; case FreeRDP_AlternateShell: return settings->AlternateShell; case FreeRDP_AssistanceFile: return settings->AssistanceFile; case FreeRDP_AuthenticationPackageList: return settings->AuthenticationPackageList; case FreeRDP_AuthenticationServiceClass: return settings->AuthenticationServiceClass; case FreeRDP_BitmapCachePersistFile: return settings->BitmapCachePersistFile; case FreeRDP_CardName: return settings->CardName; case FreeRDP_CertificateAcceptedFingerprints: return settings->CertificateAcceptedFingerprints; case FreeRDP_CertificateContent: return settings->CertificateContent; case FreeRDP_CertificateFile: return settings->CertificateFile; case FreeRDP_CertificateName: return settings->CertificateName; case FreeRDP_ClientAddress: return settings->ClientAddress; case FreeRDP_ClientDir: return settings->ClientDir; case FreeRDP_ClientHostname: return settings->ClientHostname; case FreeRDP_ClientProductId: return settings->ClientProductId; case FreeRDP_ComputerName: return settings->ComputerName; case FreeRDP_ConfigPath: return settings->ConfigPath; case FreeRDP_ConnectionFile: return settings->ConnectionFile; case FreeRDP_ContainerName: return settings->ContainerName; case FreeRDP_CspName: return settings->CspName; case FreeRDP_CurrentPath: return settings->CurrentPath; case FreeRDP_Domain: return settings->Domain; case FreeRDP_DrivesToRedirect: return settings->DrivesToRedirect; case FreeRDP_DumpRemoteFxFile: return settings->DumpRemoteFxFile; case FreeRDP_DynamicDSTTimeZoneKeyName: return settings->DynamicDSTTimeZoneKeyName; case FreeRDP_GatewayAcceptedCert: return settings->GatewayAcceptedCert; case FreeRDP_GatewayAccessToken: return settings->GatewayAccessToken; case FreeRDP_GatewayDomain: return settings->GatewayDomain; case FreeRDP_GatewayHostname: return settings->GatewayHostname; case FreeRDP_GatewayPassword: return settings->GatewayPassword; case FreeRDP_GatewayUsername: return settings->GatewayUsername; case FreeRDP_HomePath: return settings->HomePath; case FreeRDP_ImeFileName: return settings->ImeFileName; case FreeRDP_KerberosArmor: return settings->KerberosArmor; case FreeRDP_KerberosCache: return settings->KerberosCache; case FreeRDP_KerberosKdcUrl: return settings->KerberosKdcUrl; case FreeRDP_KerberosKeytab: return settings->KerberosKeytab; case FreeRDP_KerberosLifeTime: return settings->KerberosLifeTime; case FreeRDP_KerberosRealm: return settings->KerberosRealm; case FreeRDP_KerberosRenewableLifeTime: return settings->KerberosRenewableLifeTime; case FreeRDP_KerberosStartTime: return settings->KerberosStartTime; case FreeRDP_KeyboardRemappingList: return settings->KeyboardRemappingList; case FreeRDP_NtlmSamFile: return settings->NtlmSamFile; case FreeRDP_Password: return settings->Password; case FreeRDP_PasswordHash: return settings->PasswordHash; case FreeRDP_Pkcs11Module: return settings->Pkcs11Module; case FreeRDP_PkinitAnchors: return settings->PkinitAnchors; case FreeRDP_PlayRemoteFxFile: return settings->PlayRemoteFxFile; case FreeRDP_PreconnectionBlob: return settings->PreconnectionBlob; case FreeRDP_PrivateKeyContent: return settings->PrivateKeyContent; case FreeRDP_PrivateKeyFile: return settings->PrivateKeyFile; case FreeRDP_ProxyHostname: return settings->ProxyHostname; case FreeRDP_ProxyPassword: return settings->ProxyPassword; case FreeRDP_ProxyUsername: return settings->ProxyUsername; case FreeRDP_RDP2TCPArgs: return settings->RDP2TCPArgs; case FreeRDP_ReaderName: return settings->ReaderName; case FreeRDP_RedirectionAcceptedCert: return settings->RedirectionAcceptedCert; case FreeRDP_RedirectionDomain: return settings->RedirectionDomain; case FreeRDP_RedirectionTargetFQDN: return settings->RedirectionTargetFQDN; case FreeRDP_RedirectionTargetNetBiosName: return settings->RedirectionTargetNetBiosName; case FreeRDP_RedirectionUsername: return settings->RedirectionUsername; case FreeRDP_RemoteApplicationCmdLine: return settings->RemoteApplicationCmdLine; case FreeRDP_RemoteApplicationFile: return settings->RemoteApplicationFile; case FreeRDP_RemoteApplicationGuid: return settings->RemoteApplicationGuid; case FreeRDP_RemoteApplicationIcon: return settings->RemoteApplicationIcon; case FreeRDP_RemoteApplicationName: return settings->RemoteApplicationName; case FreeRDP_RemoteApplicationProgram: return settings->RemoteApplicationProgram; case FreeRDP_RemoteApplicationWorkingDir: return settings->RemoteApplicationWorkingDir; case FreeRDP_RemoteAssistancePassStub: return settings->RemoteAssistancePassStub; case FreeRDP_RemoteAssistancePassword: return settings->RemoteAssistancePassword; case FreeRDP_RemoteAssistanceRCTicket: return settings->RemoteAssistanceRCTicket; case FreeRDP_RemoteAssistanceSessionId: return settings->RemoteAssistanceSessionId; case FreeRDP_ServerHostname: return settings->ServerHostname; case FreeRDP_ShellWorkingDirectory: return settings->ShellWorkingDirectory; case FreeRDP_SmartcardCertificate: return settings->SmartcardCertificate; case FreeRDP_SmartcardPrivateKey: return settings->SmartcardPrivateKey; case FreeRDP_SspiModule: return settings->SspiModule; case FreeRDP_TargetNetAddress: return settings->TargetNetAddress; case FreeRDP_TlsSecretsFile: return settings->TlsSecretsFile; case FreeRDP_TransportDumpFile: return settings->TransportDumpFile; case FreeRDP_Username: return settings->Username; case FreeRDP_WindowTitle: return settings->WindowTitle; case FreeRDP_WmClass: return settings->WmClass; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_string_(rdpSettings* settings, size_t id, const char* val, size_t len, BOOL cleanup) { union { void* v; const void* cv; char* c; const char* cc; } cnv; WINPR_ASSERT(settings); cnv.cc = val; switch (id) { case FreeRDP_AcceptedCert: return update_string(&settings->AcceptedCert, cnv.cc, len, cleanup); case FreeRDP_ActionScript: return update_string(&settings->ActionScript, cnv.cc, len, cleanup); case FreeRDP_AllowedTlsCiphers: return update_string(&settings->AllowedTlsCiphers, cnv.cc, len, cleanup); case FreeRDP_AlternateShell: return update_string(&settings->AlternateShell, cnv.cc, len, cleanup); case FreeRDP_AssistanceFile: return update_string(&settings->AssistanceFile, cnv.cc, len, cleanup); case FreeRDP_AuthenticationPackageList: return update_string(&settings->AuthenticationPackageList, cnv.cc, len, cleanup); case FreeRDP_AuthenticationServiceClass: return update_string(&settings->AuthenticationServiceClass, cnv.cc, len, cleanup); case FreeRDP_BitmapCachePersistFile: return update_string(&settings->BitmapCachePersistFile, cnv.cc, len, cleanup); case FreeRDP_CardName: return update_string(&settings->CardName, cnv.cc, len, cleanup); case FreeRDP_CertificateAcceptedFingerprints: return update_string(&settings->CertificateAcceptedFingerprints, cnv.cc, len, cleanup); case FreeRDP_CertificateContent: return update_string(&settings->CertificateContent, cnv.cc, len, cleanup); case FreeRDP_CertificateFile: return update_string(&settings->CertificateFile, cnv.cc, len, cleanup); case FreeRDP_CertificateName: return update_string(&settings->CertificateName, cnv.cc, len, cleanup); case FreeRDP_ClientAddress: return update_string(&settings->ClientAddress, cnv.cc, len, cleanup); case FreeRDP_ClientDir: return update_string(&settings->ClientDir, cnv.cc, len, cleanup); case FreeRDP_ClientHostname: return update_string(&settings->ClientHostname, cnv.cc, len, cleanup); case FreeRDP_ClientProductId: return update_string(&settings->ClientProductId, cnv.cc, len, cleanup); case FreeRDP_ComputerName: return update_string(&settings->ComputerName, cnv.cc, len, cleanup); case FreeRDP_ConfigPath: return update_string(&settings->ConfigPath, cnv.cc, len, cleanup); case FreeRDP_ConnectionFile: return update_string(&settings->ConnectionFile, cnv.cc, len, cleanup); case FreeRDP_ContainerName: return update_string(&settings->ContainerName, cnv.cc, len, cleanup); case FreeRDP_CspName: return update_string(&settings->CspName, cnv.cc, len, cleanup); case FreeRDP_CurrentPath: return update_string(&settings->CurrentPath, cnv.cc, len, cleanup); case FreeRDP_Domain: return update_string(&settings->Domain, cnv.cc, len, cleanup); case FreeRDP_DrivesToRedirect: return update_string(&settings->DrivesToRedirect, cnv.cc, len, cleanup); case FreeRDP_DumpRemoteFxFile: return update_string(&settings->DumpRemoteFxFile, cnv.cc, len, cleanup); case FreeRDP_DynamicDSTTimeZoneKeyName: return update_string(&settings->DynamicDSTTimeZoneKeyName, cnv.cc, len, cleanup); case FreeRDP_GatewayAcceptedCert: return update_string(&settings->GatewayAcceptedCert, cnv.cc, len, cleanup); case FreeRDP_GatewayAccessToken: return update_string(&settings->GatewayAccessToken, cnv.cc, len, cleanup); case FreeRDP_GatewayDomain: return update_string(&settings->GatewayDomain, cnv.cc, len, cleanup); case FreeRDP_GatewayHostname: return update_string(&settings->GatewayHostname, cnv.cc, len, cleanup); case FreeRDP_GatewayPassword: return update_string(&settings->GatewayPassword, cnv.cc, len, cleanup); case FreeRDP_GatewayUsername: return update_string(&settings->GatewayUsername, cnv.cc, len, cleanup); case FreeRDP_HomePath: return update_string(&settings->HomePath, cnv.cc, len, cleanup); case FreeRDP_ImeFileName: return update_string(&settings->ImeFileName, cnv.cc, len, cleanup); case FreeRDP_KerberosArmor: return update_string(&settings->KerberosArmor, cnv.cc, len, cleanup); case FreeRDP_KerberosCache: return update_string(&settings->KerberosCache, cnv.cc, len, cleanup); case FreeRDP_KerberosKdcUrl: return update_string(&settings->KerberosKdcUrl, cnv.cc, len, cleanup); case FreeRDP_KerberosKeytab: return update_string(&settings->KerberosKeytab, cnv.cc, len, cleanup); case FreeRDP_KerberosLifeTime: return update_string(&settings->KerberosLifeTime, cnv.cc, len, cleanup); case FreeRDP_KerberosRealm: return update_string(&settings->KerberosRealm, cnv.cc, len, cleanup); case FreeRDP_KerberosRenewableLifeTime: return update_string(&settings->KerberosRenewableLifeTime, cnv.cc, len, cleanup); case FreeRDP_KerberosStartTime: return update_string(&settings->KerberosStartTime, cnv.cc, len, cleanup); case FreeRDP_KeyboardRemappingList: return update_string(&settings->KeyboardRemappingList, cnv.cc, len, cleanup); case FreeRDP_NtlmSamFile: return update_string(&settings->NtlmSamFile, cnv.cc, len, cleanup); case FreeRDP_Password: return update_string(&settings->Password, cnv.cc, len, cleanup); case FreeRDP_PasswordHash: return update_string(&settings->PasswordHash, cnv.cc, len, cleanup); case FreeRDP_Pkcs11Module: return update_string(&settings->Pkcs11Module, cnv.cc, len, cleanup); case FreeRDP_PkinitAnchors: return update_string(&settings->PkinitAnchors, cnv.cc, len, cleanup); case FreeRDP_PlayRemoteFxFile: return update_string(&settings->PlayRemoteFxFile, cnv.cc, len, cleanup); case FreeRDP_PreconnectionBlob: return update_string(&settings->PreconnectionBlob, cnv.cc, len, cleanup); case FreeRDP_PrivateKeyContent: return update_string(&settings->PrivateKeyContent, cnv.cc, len, cleanup); case FreeRDP_PrivateKeyFile: return update_string(&settings->PrivateKeyFile, cnv.cc, len, cleanup); case FreeRDP_ProxyHostname: return update_string(&settings->ProxyHostname, cnv.cc, len, cleanup); case FreeRDP_ProxyPassword: return update_string(&settings->ProxyPassword, cnv.cc, len, cleanup); case FreeRDP_ProxyUsername: return update_string(&settings->ProxyUsername, cnv.cc, len, cleanup); case FreeRDP_RDP2TCPArgs: return update_string(&settings->RDP2TCPArgs, cnv.cc, len, cleanup); case FreeRDP_ReaderName: return update_string(&settings->ReaderName, cnv.cc, len, cleanup); case FreeRDP_RedirectionAcceptedCert: return update_string(&settings->RedirectionAcceptedCert, cnv.cc, len, cleanup); case FreeRDP_RedirectionDomain: return update_string(&settings->RedirectionDomain, cnv.cc, len, cleanup); case FreeRDP_RedirectionTargetFQDN: return update_string(&settings->RedirectionTargetFQDN, cnv.cc, len, cleanup); case FreeRDP_RedirectionTargetNetBiosName: return update_string(&settings->RedirectionTargetNetBiosName, cnv.cc, len, cleanup); case FreeRDP_RedirectionUsername: return update_string(&settings->RedirectionUsername, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationCmdLine: return update_string(&settings->RemoteApplicationCmdLine, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationFile: return update_string(&settings->RemoteApplicationFile, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationGuid: return update_string(&settings->RemoteApplicationGuid, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationIcon: return update_string(&settings->RemoteApplicationIcon, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationName: return update_string(&settings->RemoteApplicationName, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationProgram: return update_string(&settings->RemoteApplicationProgram, cnv.cc, len, cleanup); case FreeRDP_RemoteApplicationWorkingDir: return update_string(&settings->RemoteApplicationWorkingDir, cnv.cc, len, cleanup); case FreeRDP_RemoteAssistancePassStub: return update_string(&settings->RemoteAssistancePassStub, cnv.cc, len, cleanup); case FreeRDP_RemoteAssistancePassword: return update_string(&settings->RemoteAssistancePassword, cnv.cc, len, cleanup); case FreeRDP_RemoteAssistanceRCTicket: return update_string(&settings->RemoteAssistanceRCTicket, cnv.cc, len, cleanup); case FreeRDP_RemoteAssistanceSessionId: return update_string(&settings->RemoteAssistanceSessionId, cnv.cc, len, cleanup); case FreeRDP_ServerHostname: return update_string(&settings->ServerHostname, cnv.cc, len, cleanup); case FreeRDP_ShellWorkingDirectory: return update_string(&settings->ShellWorkingDirectory, cnv.cc, len, cleanup); case FreeRDP_SmartcardCertificate: return update_string(&settings->SmartcardCertificate, cnv.cc, len, cleanup); case FreeRDP_SmartcardPrivateKey: return update_string(&settings->SmartcardPrivateKey, cnv.cc, len, cleanup); case FreeRDP_SspiModule: return update_string(&settings->SspiModule, cnv.cc, len, cleanup); case FreeRDP_TargetNetAddress: return update_string(&settings->TargetNetAddress, cnv.cc, len, cleanup); case FreeRDP_TlsSecretsFile: return update_string(&settings->TlsSecretsFile, cnv.cc, len, cleanup); case FreeRDP_TransportDumpFile: return update_string(&settings->TransportDumpFile, cnv.cc, len, cleanup); case FreeRDP_Username: return update_string(&settings->Username, cnv.cc, len, cleanup); case FreeRDP_WindowTitle: return update_string(&settings->WindowTitle, cnv.cc, len, cleanup); case FreeRDP_WmClass: return update_string(&settings->WmClass, cnv.cc, len, cleanup); default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; } BOOL freerdp_settings_set_string_len(rdpSettings* settings, size_t id, const char* val, size_t len) { return freerdp_settings_set_string_(settings, id, val, len, TRUE); } BOOL freerdp_settings_set_string(rdpSettings* settings, size_t id, const char* val) { size_t len = 0; if (val) len = strlen(val); return freerdp_settings_set_string_(settings, id, val, len, TRUE); } void* freerdp_settings_get_pointer_writable(rdpSettings* settings, size_t id) { WINPR_ASSERT(settings); switch (id) { case FreeRDP_BitmapCacheV2CellInfo: return settings->BitmapCacheV2CellInfo; case FreeRDP_ChannelDefArray: return settings->ChannelDefArray; case FreeRDP_ClientAutoReconnectCookie: return settings->ClientAutoReconnectCookie; case FreeRDP_ClientRandom: return settings->ClientRandom; case FreeRDP_ClientTimeZone: return settings->ClientTimeZone; case FreeRDP_DeviceArray: return settings->DeviceArray; case FreeRDP_DynamicChannelArray: return settings->DynamicChannelArray; case FreeRDP_FragCache: return settings->FragCache; case FreeRDP_GlyphCache: return settings->GlyphCache; case FreeRDP_LoadBalanceInfo: return settings->LoadBalanceInfo; case FreeRDP_MonitorDefArray: return settings->MonitorDefArray; case FreeRDP_MonitorIds: return settings->MonitorIds; case FreeRDP_OrderSupport: return settings->OrderSupport; case FreeRDP_Password51: return settings->Password51; case FreeRDP_RdpServerCertificate: return settings->RdpServerCertificate; case FreeRDP_RdpServerRsaKey: return settings->RdpServerRsaKey; case FreeRDP_ReceivedCapabilities: return settings->ReceivedCapabilities; case FreeRDP_RedirectionPassword: return settings->RedirectionPassword; case FreeRDP_RedirectionTsvUrl: return settings->RedirectionTsvUrl; case FreeRDP_ServerAutoReconnectCookie: return settings->ServerAutoReconnectCookie; case FreeRDP_ServerCertificate: return settings->ServerCertificate; case FreeRDP_ServerRandom: return settings->ServerRandom; case FreeRDP_StaticChannelArray: return settings->StaticChannelArray; case FreeRDP_TargetNetAddresses: return settings->TargetNetAddresses; case FreeRDP_TargetNetPorts: return settings->TargetNetPorts; case FreeRDP_instance: return settings->instance; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } } BOOL freerdp_settings_set_pointer(rdpSettings* settings, size_t id, const void* val) { union { void* v; const void* cv; } cnv; WINPR_ASSERT(settings); cnv.cv = val; switch (id) { case FreeRDP_BitmapCacheV2CellInfo: settings->BitmapCacheV2CellInfo = cnv.v; break; case FreeRDP_ChannelDefArray: settings->ChannelDefArray = cnv.v; break; case FreeRDP_ClientAutoReconnectCookie: settings->ClientAutoReconnectCookie = cnv.v; break; case FreeRDP_ClientRandom: settings->ClientRandom = cnv.v; break; case FreeRDP_ClientTimeZone: settings->ClientTimeZone = cnv.v; break; case FreeRDP_DeviceArray: settings->DeviceArray = cnv.v; break; case FreeRDP_DynamicChannelArray: settings->DynamicChannelArray = cnv.v; break; case FreeRDP_FragCache: settings->FragCache = cnv.v; break; case FreeRDP_GlyphCache: settings->GlyphCache = cnv.v; break; case FreeRDP_LoadBalanceInfo: settings->LoadBalanceInfo = cnv.v; break; case FreeRDP_MonitorDefArray: settings->MonitorDefArray = cnv.v; break; case FreeRDP_MonitorIds: settings->MonitorIds = cnv.v; break; case FreeRDP_OrderSupport: settings->OrderSupport = cnv.v; break; case FreeRDP_Password51: settings->Password51 = cnv.v; break; case FreeRDP_RdpServerCertificate: settings->RdpServerCertificate = cnv.v; break; case FreeRDP_RdpServerRsaKey: settings->RdpServerRsaKey = cnv.v; break; case FreeRDP_ReceivedCapabilities: settings->ReceivedCapabilities = cnv.v; break; case FreeRDP_RedirectionPassword: settings->RedirectionPassword = cnv.v; break; case FreeRDP_RedirectionTsvUrl: settings->RedirectionTsvUrl = cnv.v; break; case FreeRDP_ServerAutoReconnectCookie: settings->ServerAutoReconnectCookie = cnv.v; break; case FreeRDP_ServerCertificate: settings->ServerCertificate = cnv.v; break; case FreeRDP_ServerRandom: settings->ServerRandom = cnv.v; break; case FreeRDP_StaticChannelArray: settings->StaticChannelArray = cnv.v; break; case FreeRDP_TargetNetAddresses: settings->TargetNetAddresses = cnv.v; break; case FreeRDP_TargetNetPorts: settings->TargetNetPorts = cnv.v; break; case FreeRDP_instance: settings->instance = cnv.v; break; default: WLog_ERR(TAG, "[%s] Invalid key index %" PRIuz, __FUNCTION__, id); return FALSE; } return TRUE; }
{'content_hash': '684c3003788d1793d5aba095e11551ca', 'timestamp': '', 'source': 'github', 'line_count': 3391, 'max_line_length': 99, 'avg_line_length': 23.464169861397817, 'alnum_prop': 0.757399424384481, 'repo_name': 'awakecoding/FreeRDP', 'id': '255a4c917805667e20dc6e09ff11168be4939f8e', 'size': '79567', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'libfreerdp/common/settings_getters.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '15084706'}, {'name': 'C#', 'bytes': '6365'}, {'name': 'C++', 'bytes': '138156'}, {'name': 'CMake', 'bytes': '635168'}, {'name': 'CSS', 'bytes': '5696'}, {'name': 'HTML', 'bytes': '99139'}, {'name': 'Java', 'bytes': '371005'}, {'name': 'Lua', 'bytes': '27390'}, {'name': 'Makefile', 'bytes': '1677'}, {'name': 'Objective-C', 'bytes': '517001'}, {'name': 'Perl', 'bytes': '8044'}, {'name': 'Python', 'bytes': '53966'}, {'name': 'Rich Text Format', 'bytes': '937'}, {'name': 'Roff', 'bytes': '12141'}, {'name': 'Shell', 'bytes': '33001'}]}
using OpenIDConnect.Core.Models.UserManagement; namespace OpenIDConnect.IdentityServer.MembershipReboot.Models { public abstract class ExecutablePropertyMetadata : PropertyMetadata { protected ExecutablePropertyMetadata(string displayFieldType, string claimType, string name, bool required) : base(displayFieldType, claimType, name, required) { } public abstract string Get(object instance); public abstract UserManagementResult Set(object instance, string value); } }
{'content_hash': '0b7d694d65837b49d6c2695498fba24c', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 116, 'avg_line_length': 35.8, 'alnum_prop': 0.7355679702048417, 'repo_name': 'mtinning/openidconnect', 'id': '4a8298ce29ff0f6e6f60896bc40fbc2da14513ad', 'size': '539', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'OpenIDConnect.IdentityServer.MembershipReboot/Models/ExecutablePropertyMetadata.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '564631'}, {'name': 'CSS', 'bytes': '7241'}, {'name': 'HTML', 'bytes': '90886'}, {'name': 'JavaScript', 'bytes': '93542'}]}
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_17b.html">Class Test_AbaRouteValidator_17b</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_37335_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b.html?line=54041#src-54041" >testAbaNumberCheck_37335_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:46:37 </td> <td> 0.009 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_37335_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=42888#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{'content_hash': 'bf444daff43604377dd1a435ce5ff01f', 'timestamp': '', 'source': 'github', 'line_count': 209, 'max_line_length': 297, 'avg_line_length': 43.952153110047846, 'alnum_prop': 0.5100152405834967, 'repo_name': 'dcarda/aba.route.validator', 'id': 'a556505a452c026fdab5a269615cec44cd404756', 'size': '9186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b_testAbaNumberCheck_37335_good_x3c.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]}
package com.jivesoftware.os.miru.service.index; import com.google.common.collect.Lists; import com.jivesoftware.os.filer.io.api.StackBuffer; import com.jivesoftware.os.jive.utils.ordered.id.ConstantWriterIdProvider; import com.jivesoftware.os.jive.utils.ordered.id.JiveEpochTimestampProvider; import com.jivesoftware.os.jive.utils.ordered.id.OrderIdProviderImpl; import com.jivesoftware.os.jive.utils.ordered.id.SnowflakeIdPacker; import com.jivesoftware.os.miru.bitmaps.roaring6.MiruBitmapsRoaring; import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps; import com.jivesoftware.os.miru.plugin.index.MiruInvertedIndex; import com.jivesoftware.os.miru.plugin.partition.TrackError; import com.jivesoftware.os.miru.service.IndexTestUtil; import com.jivesoftware.os.miru.service.index.lab.LabInvertedIndex; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.roaringbitmap.FastAggregation; import org.roaringbitmap.RoaringBitmap; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static com.jivesoftware.os.miru.service.IndexTestUtil.getIndex; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * */ public class MiruInvertedIndexTest { @Test(dataProvider = "miruInvertedIndexDataProviderWithData", groups = "slow", enabled = false, description = "Performance test") public void testSetId(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, int appends, int sets) throws Exception { StackBuffer stackBuffer = new StackBuffer(); Random r = new Random(1_234); int id = 0; int[] ids = new int[sets + appends]; for (int i = 0; i < appends; i++) { id += 1 + (r.nextDouble() * 120_000); miruInvertedIndex.set(stackBuffer, id); ids[i] = id; if (i % 100_000 == 0) { System.out.println("add " + i); } } System.out.println("max id " + id); System.out.println("bitmap size " + getIndex(miruInvertedIndex, stackBuffer).getBitmap().getSizeInBytes()); //Thread.sleep(2000); long timestamp = System.currentTimeMillis(); long subTimestamp = System.currentTimeMillis(); for (int i = 0; i < sets; i++) { miruInvertedIndex.remove(stackBuffer, ids[i]); id += 1 + (r.nextDouble() * 120); miruInvertedIndex.set(stackBuffer, id); ids[appends + i] = id; if (i % 1_000 == 0) { //System.out.println("set " + i); System.out.println(String.format("set 1000, elapsed = %s, max id = %s, bitmap size = %s", (System.currentTimeMillis() - subTimestamp), id, getIndex(miruInvertedIndex, stackBuffer).getBitmap().getSizeInBytes())); subTimestamp = System.currentTimeMillis(); } } System.out.println("elapsed: " + (System.currentTimeMillis() - timestamp) + " ms"); } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testAppend(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); int lastId = ids.get(ids.size() - 1); miruInvertedIndex.set(stackBuffer, lastId + 1); miruInvertedIndex.set(stackBuffer, lastId + 3); for (int id : ids) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), id)); } assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 1)); assertFalse(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 2)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 3)); assertFalse(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 4)); } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testRemove(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); RoaringBitmap index = getIndex(miruInvertedIndex, stackBuffer).getBitmap(); assertEquals(index.getCardinality(), ids.size()); for (int id : ids) { assertTrue(index.contains(id)); } for (int i = 0; i < ids.size() / 2; i++) { miruInvertedIndex.remove(stackBuffer, ids.get(i)); } ids = ids.subList(ids.size() / 2, ids.size()); index = getIndex(miruInvertedIndex, stackBuffer).getBitmap(); assertEquals(index.getCardinality(), ids.size()); for (int id : ids) { assertTrue(index.contains(id)); } } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testSet(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); int lastId = ids.get(ids.size() - 1); miruInvertedIndex.set(stackBuffer, lastId + 2); miruInvertedIndex.set(stackBuffer, lastId + 1); for (int id : ids) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), id)); } assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 1)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 2)); } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testSetNonIntermediateBit(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); int lastId = ids.get(ids.size() - 1); miruInvertedIndex.set(stackBuffer, lastId + 1); miruInvertedIndex.set(stackBuffer, lastId + 2); for (int id : ids) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), id)); } assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 1)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 2)); } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testAndNot(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); RoaringBitmap bitmap = new RoaringBitmap(); for (int i = 0; i < ids.size() / 2; i++) { bitmap.add(ids.get(i)); } miruInvertedIndex.andNot(bitmap, stackBuffer); for (int i = 0; i < ids.size() / 2; i++) { RoaringBitmap got = getIndex(miruInvertedIndex, stackBuffer).getBitmap(); assertFalse(bitmaps.isSet(got, ids.get(i)), "Mismatch at " + i); } for (int i = ids.size() / 2; i < ids.size(); i++) { RoaringBitmap got = getIndex(miruInvertedIndex, stackBuffer).getBitmap(); assertTrue(bitmaps.isSet(got, ids.get(i)), "Mismatch at " + i); } } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testAndNotToSourceSize(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); RoaringBitmap bitmap = new RoaringBitmap(); for (int i = 0; i < ids.size() / 2; i++) { bitmap.add(ids.get(i)); } miruInvertedIndex.andNotToSourceSize(Collections.singletonList(bitmap), stackBuffer); for (int i = 0; i < ids.size() / 2; i++) { assertFalse(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), ids.get(i))); } for (int i = ids.size() / 2; i < ids.size(); i++) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), ids.get(i))); } } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testOr(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); int lastId = ids.get(ids.size() - 1); miruInvertedIndex.set(stackBuffer, lastId + 2); RoaringBitmap bitmap = new RoaringBitmap(); bitmap.add(lastId + 1); bitmap.add(lastId + 3); miruInvertedIndex.or(bitmap, stackBuffer); for (int id : ids) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), id)); } assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 1)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 2)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 3)); } @Test(dataProvider = "miruInvertedIndexDataProviderWithData") public void testOrToSourceSize(MiruInvertedIndex<RoaringBitmap, RoaringBitmap> miruInvertedIndex, List<Integer> ids) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmaps<RoaringBitmap, RoaringBitmap> bitmaps = new MiruBitmapsRoaring(); int lastId = ids.get(ids.size() - 1); miruInvertedIndex.set(stackBuffer, lastId + 2); RoaringBitmap bitmap = new RoaringBitmap(); bitmap.add(lastId + 1); bitmap.add(lastId + 3); miruInvertedIndex.orToSourceSize(bitmap, stackBuffer); for (int id : ids) { assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), id)); } assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 1)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 2)); assertTrue(bitmaps.isSet(getIndex(miruInvertedIndex, stackBuffer).getBitmap(), lastId + 3)); // roaring ignores source size requirement } @Test public void testSetIfEmpty() throws Exception { StackBuffer stackBuffer = new StackBuffer(); //MiruSchema schema = new Builder("test", 1).build(); MiruBitmapsRoaring bitmaps = new MiruBitmapsRoaring(); for (boolean atomized : new boolean[] { false, true }) { MiruInvertedIndex<RoaringBitmap, RoaringBitmap> index = buildInvertedIndex(atomized, bitmaps); // setIfEmpty index 1 index.setIfEmpty(stackBuffer, 1); RoaringBitmap got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); assertTrue(got.contains(1)); // setIfEmpty index 2 noops index.setIfEmpty(stackBuffer, 2); got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); assertTrue(got.contains(1)); assertFalse(got.contains(2)); // check index 1 is still set after merge got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); assertTrue(got.contains(1)); // setIfEmpty index 3 noops index.setIfEmpty(stackBuffer, 3); got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); assertTrue(got.contains(1)); assertFalse(got.contains(3)); // set index 4 index.set(stackBuffer, 4); got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 2); assertTrue(got.contains(1)); assertTrue(got.contains(4)); // remove index 1, 4 index.remove(stackBuffer, 1); index.remove(stackBuffer, 4); if (atomized) { assertFalse(getIndex(index, stackBuffer).isSet()); } else { got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 0); } // setIfEmpty index 5 index.setIfEmpty(stackBuffer, 5); got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); // setIfEmpty index 6 noops index.setIfEmpty(stackBuffer, 6); got = getIndex(index, stackBuffer).getBitmap(); assertEquals(got.getCardinality(), 1); } } @DataProvider(name = "miruInvertedIndexDataProviderWithData") public Object[][] miruInvertedIndexDataProviderWithData() throws Exception { StackBuffer stackBuffer = new StackBuffer(); //MiruSchema schema = new Builder("test", 1).build(); MiruBitmapsRoaring bitmaps = new MiruBitmapsRoaring(); MiruInvertedIndex<RoaringBitmap, RoaringBitmap> mergedIndex = buildInvertedIndex(false, bitmaps); mergedIndex.set(stackBuffer, 1, 2, 3, 4); MiruInvertedIndex<RoaringBitmap, RoaringBitmap> atomizedIndex = buildInvertedIndex(true, bitmaps); atomizedIndex.set(stackBuffer, 1, 2, 3, 4); return new Object[][] { { mergedIndex, Arrays.asList(1, 2, 3, 4) }, { atomizedIndex, Arrays.asList(1, 2, 3, 4) } }; } private <BM extends IBM, IBM> MiruInvertedIndex<BM, IBM> buildInvertedIndex(boolean atomized, MiruBitmaps<BM, IBM> bitmaps) throws Exception { return new LabInvertedIndex<>( new OrderIdProviderImpl(new ConstantWriterIdProvider(1), new SnowflakeIdPacker(), new JiveEpochTimestampProvider()), bitmaps, new TrackError() { @Override public void error(String reason) { } @Override public void reset() { } }, "test", 0, atomized, new byte[] { 0 }, IndexTestUtil.buildValueIndex("bitmap"), new byte[] { 0 }, IndexTestUtil.buildValueIndex("term"), new Object()); } @Test(groups = "slow", enabled = false, description = "Concurrency test") public void testConcurrency() throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruBitmapsRoaring bitmaps = new MiruBitmapsRoaring(); ExecutorService executorService = Executors.newFixedThreadPool(8); final MiruInvertedIndex<RoaringBitmap, RoaringBitmap> invertedIndex = buildInvertedIndex(false, bitmaps); final AtomicInteger idProvider = new AtomicInteger(); final AtomicInteger done = new AtomicInteger(); final int runs = 10_000; final Random random = new Random(); List<Future<?>> futures = Lists.newArrayListWithCapacity(8); futures.add(executorService.submit(() -> { while (done.get() < 7) { int id = idProvider.incrementAndGet(); if (id == Integer.MAX_VALUE) { System.out.println("appender hit max value"); break; } if (random.nextBoolean()) { try { invertedIndex.set(stackBuffer, id); } catch (Exception e) { throw new RuntimeException(e); } } } try { RoaringBitmap index = getIndex(invertedIndex, stackBuffer).getBitmap(); System.out.println("appender is done, final cardinality=" + index.getCardinality() + " bytes=" + index.getSizeInBytes()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } })); System.out.println("started appender"); for (int i = 0; i < 7; i++) { futures.add(executorService.submit(() -> { RoaringBitmap other = new RoaringBitmap(); int r = 0; for (int i1 = 0; i1 < runs; i1++) { int size = idProvider.get(); while (r < size) { if (random.nextBoolean()) { other.add(r); } r++; } try { RoaringBitmap index = getIndex(invertedIndex, stackBuffer).getBitmap(); RoaringBitmap container = FastAggregation.and(index, other); } catch (Exception e) { done.incrementAndGet(); e.printStackTrace(); throw new RuntimeException(e); } } System.out.println("aggregator is done, final cardinality=" + other.getCardinality() + " bytes=" + other.getSizeInBytes()); done.incrementAndGet(); })); System.out.println("started aggregators"); } for (Future<?> future : futures) { future.get(); System.out.println("got a future"); } System.out.println("all done"); } @Test(groups = "slow", enabled = false, description = "Performance test") public void testInMemoryAppenderSpeed() throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruInvertedIndex<RoaringBitmap, RoaringBitmap> invertedIndex = buildInvertedIndex(false, new MiruBitmapsRoaring()); Random r = new Random(); long t = System.currentTimeMillis(); for (int i = 0; i < 1_000_000; i++) { if (r.nextBoolean()) { invertedIndex.set(stackBuffer, i); } } long elapsed = System.currentTimeMillis() - t; RoaringBitmap index = getIndex(invertedIndex, stackBuffer).getBitmap(); System.out.println("cardinality=" + index.getCardinality() + " bytes=" + index.getSizeInBytes() + " elapsed=" + elapsed); } }
{'content_hash': 'f5ddc547c924044ac93c2ca8c632dc57', 'timestamp': '', 'source': 'github', 'line_count': 434, 'max_line_length': 146, 'avg_line_length': 43.82258064516129, 'alnum_prop': 0.6245333613754667, 'repo_name': 'bruceadowns/miru', 'id': '9f139d8a31438cb440bdb6daedd1740955a2e39c', 'size': '19019', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'miru-service-test/src/test/java/com/jivesoftware/os/miru/service/index/MiruInvertedIndexTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '83434'}, {'name': 'HTML', 'bytes': '346179'}, {'name': 'Java', 'bytes': '4688478'}, {'name': 'JavaScript', 'bytes': '338937'}, {'name': 'Shell', 'bytes': '3033'}]}
<!-- --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en-US"> <head> <title>Applet Takes Params</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> </head> <body> <noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript> <h1>Applet Takes Params</h1> <script src="http://www.java.com/js/deployJava.js"></script> <script> var attributes = { code:'AppletTakesParams.class', archive:'applet_AppletWithParameters.jar', width:800, height:50} ; var parameters = {jnlp_href: 'applettakesparams.jnlp', paramOutsideJNLPFile: 'fooOutsideJNLP'} ; deployJava.runApplet(attributes, parameters, '1.6'); </script> <!-- Start SiteCatalyst code --> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script> <!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** --> <!-- Below code will send the info to Omniture server --> <script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script> <!-- End SiteCatalyst code --> </body> </html>
{'content_hash': 'beb147574a905d78d6c9169ab6dc605b', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 146, 'avg_line_length': 39.2, 'alnum_prop': 0.6756559766763849, 'repo_name': 'bartdag/recodoc2', 'id': '994f89eb4b5b2aae70f5994eed790e9ffd581fae', 'size': '2970', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'recodoc2/testdata/java70tutorial/deployment/applet/examples/dist/applet_AppletWithParameters/AppletPage.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '5581'}, {'name': 'HTML', 'bytes': '32211467'}, {'name': 'Java', 'bytes': '13646'}, {'name': 'Perl', 'bytes': '503'}, {'name': 'Python', 'bytes': '717834'}]}
class AddGroupSupportToBroadcastAddressings < ActiveRecord::Migration[4.2] def up # Might as well do this, should have been done before. execute("DELETE FROM broadcast_addressings WHERE user_id IS NULL OR broadcast_id IS NULL") change_column_null :broadcast_addressings, :user_id, false change_column_null :broadcast_addressings, :broadcast_id, false remove_foreign_key "broadcast_addressings", "user" rename_column :broadcast_addressings, :user_id, :addressee_id add_column :broadcast_addressings, :addressee_type, :string execute("UPDATE broadcast_addressings SET addressee_type = 'User'") change_column_null :broadcast_addressings, :addressee_type, false end end
{'content_hash': 'ce46e49f1c1fffd3bbf8aad46a53d532', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 94, 'avg_line_length': 44.3125, 'alnum_prop': 0.7517630465444288, 'repo_name': 'thecartercenter/elmo', 'id': 'b74737ffc9cc07bcfca35ecc413c54d2187e70b6', 'size': '709', 'binary': False, 'copies': '1', 'ref': 'refs/heads/12085_prevent_dupes', 'path': 'db/migrate/20160822144404_add_group_support_to_broadcast_addressings.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '97107'}, {'name': 'CoffeeScript', 'bytes': '57714'}, {'name': 'HTML', 'bytes': '144925'}, {'name': 'JavaScript', 'bytes': '194066'}, {'name': 'Ruby', 'bytes': '1756251'}]}
RelationVertex::RelationVertex(size_t idx, size_t primitiveIdx1) { _relationVertexType = RVT_SINGLE_PRIMITIVE; _idx = idx; _primitiveIdx1 = primitiveIdx1; _parent = idx; } RelationVertex::RelationVertex(size_t idx, size_t primitiveIdx1, size_t primitiveIdx2) { _relationVertexType = RVT_DOUBLE_PRIMITIVE; _idx = idx; _primitiveIdx1 = primitiveIdx1; _primitiveIdx2 = primitiveIdx2; _parent = idx; } RelationVertex::~RelationVertex(void) { } size_t RelationVertex::getPrimitiveIdx1() const { assert(_relationVertexType>=RVT_SINGLE_PRIMITIVE); return _primitiveIdx1; } size_t RelationVertex::getPrimitiveIdx2() const { assert(_relationVertexType>=RVT_DOUBLE_PRIMITIVE); return _primitiveIdx2; } bool RelationVertex::operator<(const RelationVertex& other) const { return _primitiveIdx1 < other._primitiveIdx1 || (_primitiveIdx1 == other._primitiveIdx1 && _primitiveIdx2 < other._primitiveIdx2); }
{'content_hash': 'd3bc09cd74378d910b64ca6a903e73fd', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 93, 'avg_line_length': 25.05, 'alnum_prop': 0.6926147704590818, 'repo_name': 'NUAAXXY/globOpt', 'id': 'ca221e22f4061d98c9369a7b9267e2cbb4325dac', 'size': '1051', 'binary': False, 'copies': '2', 'ref': 'refs/heads/spatially_smooth', 'path': 'globfit/src/RelationVertex.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '79972'}, {'name': 'C++', 'bytes': '1358703'}, {'name': 'CMake', 'bytes': '31244'}, {'name': 'CSS', 'bytes': '950'}, {'name': 'Gnuplot', 'bytes': '518'}, {'name': 'HTML', 'bytes': '35161'}, {'name': 'M', 'bytes': '353'}, {'name': 'Mathematica', 'bytes': '2707'}, {'name': 'Matlab', 'bytes': '96797'}, {'name': 'Objective-C', 'bytes': '250'}, {'name': 'Python', 'bytes': '132051'}, {'name': 'Shell', 'bytes': '108272'}, {'name': 'TeX', 'bytes': '27525'}]}
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('portfolio.urls', namespace='portfolio')), url(r'^accounts/login/$', auth_views.login, name='login'), url(r'^accounts/logout/$', auth_views.logout, name='logout', kwargs={'next_page': '/'}), url(r'^password-reset/$', auth_views.password_reset, name='password_reset'), url(r'^password-reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^password-reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'), ]
{'content_hash': 'cd6e1fa2aa73b3c3b5f24cabb2fd9085', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 141, 'avg_line_length': 59.42857142857143, 'alnum_prop': 0.6887019230769231, 'repo_name': 'macmohan26/EagleFinancialServices', 'id': 'b1721ee4b4f6cd795ac2d5c6d82f3b675a055234', 'size': '832', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'efsfaa/urls.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '980'}, {'name': 'HTML', 'bytes': '25321'}, {'name': 'Python', 'bytes': '26569'}]}
using QuantConnect.Orders; namespace QuantConnect.Securities.Positions { /// <summary> /// Defines the parameters for <see cref="IPositionGroupBuyingPowerModel.GetPositionGroupBuyingPower"/> /// </summary> public class PositionGroupBuyingPowerParameters { /// <summary> /// Gets the position group /// </summary> public IPositionGroup PositionGroup { get; } /// <summary> /// Gets the algorithm's portfolio manager /// </summary> public SecurityPortfolioManager Portfolio { get; } /// <summary> /// Gets the direction in which buying power is to be computed /// </summary> public OrderDirection Direction { get; } /// <summary> /// Initializes a new instance of the <see cref="PositionGroupBuyingPowerParameters"/> class /// </summary> /// <param name="portfolio">The algorithm's portfolio manager</param> /// <param name="positionGroup">The position group</param> /// <param name="direction">The direction to compute buying power in</param> public PositionGroupBuyingPowerParameters( SecurityPortfolioManager portfolio, IPositionGroup positionGroup, OrderDirection direction ) { Portfolio = portfolio; Direction = direction; PositionGroup = positionGroup; } /// <summary> /// Implicit operator to dependent function to remove noise /// </summary> public static implicit operator ReservedBuyingPowerForPositionGroupParameters( PositionGroupBuyingPowerParameters parameters ) { return new ReservedBuyingPowerForPositionGroupParameters(parameters.Portfolio, parameters.PositionGroup); } } }
{'content_hash': '2226e944f1f40aeacc19859c336c31af', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 117, 'avg_line_length': 34.370370370370374, 'alnum_prop': 0.6260775862068966, 'repo_name': 'jameschch/Lean', 'id': '8c1ff95ae4754351b93abac3c40b0893dbf08f30', 'size': '2560', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'Common/Securities/Positions/PositionGroupBuyingPowerParameters.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2540'}, {'name': 'C#', 'bytes': '15402085'}, {'name': 'Dockerfile', 'bytes': '1226'}, {'name': 'F#', 'bytes': '1723'}, {'name': 'HTML', 'bytes': '2607907'}, {'name': 'Java', 'bytes': '852'}, {'name': 'Jupyter Notebook', 'bytes': '16348'}, {'name': 'Python', 'bytes': '654580'}, {'name': 'Shell', 'bytes': '2307'}, {'name': 'Visual Basic', 'bytes': '2448'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Bossiaea spinescens Meissner ### Remarks null
{'content_hash': '74eb89463b30e849f9b431a2423672a1', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 11.538461538461538, 'alnum_prop': 0.74, 'repo_name': 'mdoering/backbone', 'id': '82ea50546ed557ee3acf844550a947ce075a4a7c', 'size': '207', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Bossiaea/Bossiaea rufa/Bossiaea rufa foliosa/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package org.elasticsearch.gateway; import org.elasticsearch.Version; import org.elasticsearch.action.FailedNodeException; import org.elasticsearch.action.support.nodes.BaseNodeResponse; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; import org.junit.Before; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Collections.emptySet; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.sameInstance; /** */ public class AsyncShardFetchTests extends ESTestCase { private final DiscoveryNode node1 = new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), Collections.emptyMap(), Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT); private final Response response1 = new Response(node1); private final Throwable failure1 = new Throwable("simulated failure 1"); private final DiscoveryNode node2 = new DiscoveryNode("node2", LocalTransportAddress.buildUnique(), Collections.emptyMap(), Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT); private final Response response2 = new Response(node2); private final Throwable failure2 = new Throwable("simulate failure 2"); private ThreadPool threadPool; private TestFetch test; @Override @Before public void setUp() throws Exception { super.setUp(); this.threadPool = new TestThreadPool(getTestName()); this.test = new TestFetch(threadPool); } @After public void terminate() throws Exception { terminate(threadPool); } public void testClose() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).build(); test.addSimulation(node1.getId(), response1); // first fetch, no data, still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire a response, wait on reroute incrementing test.fireSimulationAndWait(node1.getId()); // verify we get back the data node assertThat(test.reroute.get(), equalTo(1)); test.close(); try { test.fetchData(nodes, emptySet()); fail("fetch data should fail when closed"); } catch (IllegalStateException e) { // all is well } } public void testFullCircleSingleNodeSuccess() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).build(); test.addSimulation(node1.getId(), response1); // first fetch, no data, still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire a response, wait on reroute incrementing test.fireSimulationAndWait(node1.getId()); // verify we get back the data node assertThat(test.reroute.get(), equalTo(1)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(1)); assertThat(fetchData.getData().get(node1), sameInstance(response1)); } public void testFullCircleSingleNodeFailure() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).build(); // add a failed response for node1 test.addSimulation(node1.getId(), failure1); // first fetch, no data, still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire a response, wait on reroute incrementing test.fireSimulationAndWait(node1.getId()); // failure, fetched data exists, but has no data assertThat(test.reroute.get(), equalTo(1)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(0)); // on failure, we reset the failure on a successive call to fetchData, and try again afterwards test.addSimulation(node1.getId(), response1); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); test.fireSimulationAndWait(node1.getId()); // 2 reroutes, cause we have a failure that we clear assertThat(test.reroute.get(), equalTo(3)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(1)); assertThat(fetchData.getData().get(node1), sameInstance(response1)); } public void testTwoNodesOnSetup() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).put(node2).build(); test.addSimulation(node1.getId(), response1); test.addSimulation(node2.getId(), response2); // no fetched data, 2 requests still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire the first response, it should trigger a reroute test.fireSimulationAndWait(node1.getId()); // there is still another on going request, so no data assertThat(test.getNumberOfInFlightFetches(), equalTo(1)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); // fire the second simulation, this should allow us to get the data test.fireSimulationAndWait(node2.getId()); // no more ongoing requests, we should fetch the data assertThat(test.reroute.get(), equalTo(2)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(2)); assertThat(fetchData.getData().get(node1), sameInstance(response1)); assertThat(fetchData.getData().get(node2), sameInstance(response2)); } public void testTwoNodesOnSetupAndFailure() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).put(node2).build(); test.addSimulation(node1.getId(), response1); test.addSimulation(node2.getId(), failure2); // no fetched data, 2 requests still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire the first response, it should trigger a reroute test.fireSimulationAndWait(node1.getId()); assertThat(test.reroute.get(), equalTo(1)); fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); // fire the second simulation, this should allow us to get the data test.fireSimulationAndWait(node2.getId()); assertThat(test.reroute.get(), equalTo(2)); // since one of those failed, we should only have one entry fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(1)); assertThat(fetchData.getData().get(node1), sameInstance(response1)); } public void testTwoNodesAddedInBetween() throws Exception { DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).build(); test.addSimulation(node1.getId(), response1); // no fetched data, 2 requests still on going AsyncShardFetch.FetchResult<Response> fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); assertThat(test.reroute.get(), equalTo(0)); // fire the first response, it should trigger a reroute test.fireSimulationAndWait(node1.getId()); // now, add a second node to the nodes, it should add it to the ongoing requests nodes = DiscoveryNodes.builder(nodes).put(node2).build(); test.addSimulation(node2.getId(), response2); // no fetch data, has a new node introduced fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(false)); // fire the second simulation, this should allow us to get the data test.fireSimulationAndWait(node2.getId()); // since one of those failed, we should only have one entry fetchData = test.fetchData(nodes, emptySet()); assertThat(fetchData.hasData(), equalTo(true)); assertThat(fetchData.getData().size(), equalTo(2)); assertThat(fetchData.getData().get(node1), sameInstance(response1)); assertThat(fetchData.getData().get(node2), sameInstance(response2)); } static class TestFetch extends AsyncShardFetch<Response> { static class Entry { public final Response response; public final Throwable failure; private final CountDownLatch executeLatch = new CountDownLatch(1); private final CountDownLatch waitLatch = new CountDownLatch(1); public Entry(Response response, Throwable failure) { this.response = response; this.failure = failure; } } private final ThreadPool threadPool; private final Map<String, Entry> simulations = new ConcurrentHashMap<>(); private AtomicInteger reroute = new AtomicInteger(); public TestFetch(ThreadPool threadPool) { super(Loggers.getLogger(TestFetch.class), "test", new ShardId("test", "_na_", 1), null); this.threadPool = threadPool; } public void addSimulation(String nodeId, Response response) { simulations.put(nodeId, new Entry(response, null)); } public void addSimulation(String nodeId, Throwable t) { simulations.put(nodeId, new Entry(null, t)); } public void fireSimulationAndWait(String nodeId) throws InterruptedException { simulations.get(nodeId).executeLatch.countDown(); simulations.get(nodeId).waitLatch.await(); simulations.remove(nodeId); } @Override protected void reroute(ShardId shardId, String reason) { reroute.incrementAndGet(); } @Override protected void asyncFetch(final ShardId shardId, DiscoveryNode[] nodes) { for (final DiscoveryNode node : nodes) { final String nodeId = node.getId(); threadPool.generic().execute(new Runnable() { @Override public void run() { Entry entry = null; try { entry = simulations.get(nodeId); if (entry == null) { // we are simulating a master node switch, wait for it to not be null awaitBusy(() -> simulations.containsKey(nodeId)); } assert entry != null; entry.executeLatch.await(); if (entry.failure != null) { processAsyncFetch(shardId, null, Collections.singletonList(new FailedNodeException(nodeId, "unexpected", entry.failure))); } else { processAsyncFetch(shardId, Collections.singletonList(entry.response), null); } } catch (Exception e) { logger.error("unexpected failure", e); } finally { if (entry != null) { entry.waitLatch.countDown(); } } } }); } } } static class Response extends BaseNodeResponse { public Response(DiscoveryNode node) { super(node); } } }
{'content_hash': '99ce3328aa6a2d0730d7821dd4cdb525', 'timestamp': '', 'source': 'github', 'line_count': 298, 'max_line_length': 132, 'avg_line_length': 44.34228187919463, 'alnum_prop': 0.6307703950355683, 'repo_name': 'avikurapati/elasticsearch', 'id': '092e6eaff8a0cdc22ad9d07c2ce9f86883969403', 'size': '14002', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '12298'}, {'name': 'Batchfile', 'bytes': '16353'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '251795'}, {'name': 'HTML', 'bytes': '5348'}, {'name': 'Java', 'bytes': '36819105'}, {'name': 'Perl', 'bytes': '7116'}, {'name': 'Python', 'bytes': '76127'}, {'name': 'Shell', 'bytes': '102829'}]}
#import "ProjectSettings.h" #import "NSString+RelativePath.h" #import "HashValue.h" #import "PlugInManager.h" #import "PlugInExport.h" #import "ResourceManager.h" #import "ResourceManagerUtil.h" #import "CocosBuilderAppDelegate.h" #import "PlayerConnection.h" #import "PlayerDeviceInfo.h" #import <ApplicationServices/ApplicationServices.h> @implementation ProjectSettingsGeneratedSpriteSheet @synthesize isDirty; @synthesize textureFileFormat; @synthesize dither; @synthesize compress; @synthesize textureFileFormatAndroid; @synthesize ditherAndroid; @synthesize textureFileFormatHTML5; @synthesize ditherHTML5; - (id)init { self = [super init]; if (!self) return NULL; self.isDirty = NO; self.textureFileFormat = 0; // PNG self.dither = YES; self.compress = YES; self.textureFileFormatAndroid = 0; self.ditherAndroid = YES; self.textureFileFormatHTML5 = 0; self.ditherHTML5 = YES; return self; } - (id)initWithSerialization:(id)dict { self = [super init]; if (!self) return NULL; self.isDirty = [[dict objectForKey:@"isDirty"] boolValue]; self.textureFileFormat = [[dict objectForKey:@"textureFileFormat"] intValue]; self.dither = [[dict objectForKey:@"dither"] boolValue]; self.compress = [[dict objectForKey:@"compress"] boolValue]; self.textureFileFormatAndroid = [[dict objectForKey:@"textureFileFormatAndroid"] intValue]; self.ditherAndroid = [[dict objectForKey:@"ditherAndroid"] boolValue]; self.textureFileFormatHTML5 = [[dict objectForKey:@"textureFileFormatHTML5"] intValue]; self.ditherHTML5 = [[dict objectForKey:@"ditherHTML5"] boolValue]; return self; } - (id) serialize { NSMutableDictionary* ser = [NSMutableDictionary dictionary]; [ser setObject:[NSNumber numberWithBool:self.isDirty] forKey:@"isDirty"]; [ser setObject:[NSNumber numberWithInt:self.textureFileFormat] forKey:@"textureFileFormat"]; [ser setObject:[NSNumber numberWithBool:self.dither] forKey:@"dither"]; [ser setObject:[NSNumber numberWithBool:self.compress] forKey:@"compress"]; [ser setObject:[NSNumber numberWithInt:self.textureFileFormatAndroid] forKey:@"textureFileFormatAndroid"]; [ser setObject:[NSNumber numberWithBool:self.ditherAndroid] forKey:@"ditherAndroid"]; [ser setObject:[NSNumber numberWithInt:self.textureFileFormatHTML5] forKey:@"textureFileFormatHTML5"]; [ser setObject:[NSNumber numberWithBool:self.ditherHTML5] forKey:@"ditherHTML5"]; return ser; } @end @implementation ProjectSettings @synthesize projectPath; @synthesize resourcePaths; @synthesize publishDirectory; @synthesize publishDirectoryAndroid; @synthesize publishDirectoryHTML5; @synthesize publishEnablediPhone; @synthesize publishEnabledAndroid; @synthesize publishEnabledHTML5; @synthesize publishResolution_; @synthesize publishResolution_hd; @synthesize publishResolution_ipad; @synthesize publishResolution_ipadhd; @synthesize publishResolution_xsmall; @synthesize publishResolution_small; @synthesize publishResolution_medium; @synthesize publishResolution_large; @synthesize publishResolution_xlarge; @synthesize publishResolutionHTML5_width; @synthesize publishResolutionHTML5_height; @synthesize publishResolutionHTML5_scale; @synthesize isSafariExist; @synthesize isChromeExist; @synthesize isFirefoxExist; @synthesize flattenPaths; @synthesize publishToZipFile; @synthesize javascriptBased; @synthesize javascriptMainCCB; @synthesize onlyPublishCCBs; @synthesize exporter; @synthesize availableExporters; @synthesize deviceOrientationPortrait; @synthesize deviceOrientationUpsideDown; @synthesize deviceOrientationLandscapeLeft; @synthesize deviceOrientationLandscapeRight; @synthesize resourceAutoScaleFactor; @synthesize generatedSpriteSheets; @synthesize breakpoints; @synthesize versionStr; @synthesize needRepublish; - (id) init { self = [super init]; if (!self) return NULL; resourcePaths = [[NSMutableArray alloc] init]; [resourcePaths addObject:[NSMutableDictionary dictionaryWithObject:@"Resources" forKey:@"path"]]; self.publishDirectory = @"Published-iOS"; self.publishDirectoryAndroid = @"Published-Android"; self.publishDirectoryHTML5 = @"Published-HTML5"; self.onlyPublishCCBs = NO; self.flattenPaths = NO; self.javascriptBased = YES; self.publishToZipFile = NO; self.javascriptMainCCB = @"MainScene"; self.deviceOrientationLandscapeLeft = YES; self.deviceOrientationLandscapeRight = YES; self.resourceAutoScaleFactor = 4; self.publishEnablediPhone = YES; self.publishEnabledAndroid = NO; self.publishEnabledHTML5 = YES; self.publishResolution_ = YES; self.publishResolution_hd = YES; self.publishResolution_ipad = YES; self.publishResolution_ipadhd = YES; self.publishResolution_xsmall = YES; self.publishResolution_small = YES; self.publishResolution_medium = YES; self.publishResolution_large = YES; self.publishResolution_xlarge = YES; self.publishResolutionHTML5_width = 480; self.publishResolutionHTML5_height = 320; self.publishResolutionHTML5_scale = 1; breakpoints = [[NSMutableDictionary dictionary] retain]; generatedSpriteSheets = [[NSMutableDictionary dictionary] retain]; // Load available exporters self.availableExporters = [NSMutableArray array]; for (PlugInExport* plugIn in [[PlugInManager sharedManager] plugInsExporters]) { [availableExporters addObject: plugIn.extension]; } [self detectBrowserPresence]; self.versionStr = [self getVersion]; self.needRepublish = NO; return self; } - (id) initWithSerialization:(id)dict { self = [self init]; if (!self) return NULL; // Check filetype if (![[dict objectForKey:@"fileType"] isEqualToString:@"CocosBuilderProject"]) { [self release]; return NULL; } // Read settings self.resourcePaths = [dict objectForKey:@"resourcePaths"]; self.publishDirectory = [dict objectForKey:@"publishDirectory"]; self.publishDirectoryAndroid = [dict objectForKey:@"publishDirectoryAndroid"]; self.publishDirectoryHTML5 = [dict objectForKey:@"publishDirectoryHTML5"]; if (!publishDirectory) self.publishDirectory = @""; if (!publishDirectoryAndroid) self.publishDirectoryAndroid = @""; if (!publishDirectoryHTML5) self.publishDirectoryHTML5 = @""; self.publishEnablediPhone = [[dict objectForKey:@"publishEnablediPhone"] boolValue]; self.publishEnabledAndroid = [[dict objectForKey:@"publishEnabledAndroid"] boolValue]; self.publishEnabledHTML5 = [[dict objectForKey:@"publishEnabledHTML5"] boolValue]; self.publishResolution_ = [[dict objectForKey:@"publishResolution_"] boolValue]; self.publishResolution_hd = [[dict objectForKey:@"publishResolution_hd"] boolValue]; self.publishResolution_ipad = [[dict objectForKey:@"publishResolution_ipad"] boolValue]; self.publishResolution_ipadhd = [[dict objectForKey:@"publishResolution_ipadhd"] boolValue]; self.publishResolution_xsmall = [[dict objectForKey:@"publishResolution_xsmall"] boolValue]; self.publishResolution_small = [[dict objectForKey:@"publishResolution_small"] boolValue]; self.publishResolution_medium = [[dict objectForKey:@"publishResolution_medium"] boolValue]; self.publishResolution_large = [[dict objectForKey:@"publishResolution_large"] boolValue]; self.publishResolution_xlarge = [[dict objectForKey:@"publishResolution_xlarge"] boolValue]; self.publishResolutionHTML5_width = [[dict objectForKey:@"publishResolutionHTML5_width"]intValue]; self.publishResolutionHTML5_height = [[dict objectForKey:@"publishResolutionHTML5_height"]intValue]; self.publishResolutionHTML5_scale = [[dict objectForKey:@"publishResolutionHTML5_scale"]intValue]; if (!publishResolutionHTML5_width) publishResolutionHTML5_width = 960; if (!publishResolutionHTML5_height) publishResolutionHTML5_height = 640; if (!publishResolutionHTML5_scale) publishResolutionHTML5_scale = 2; self.flattenPaths = [[dict objectForKey:@"flattenPaths"] boolValue]; self.publishToZipFile = [[dict objectForKey:@"publishToZipFile"] boolValue]; self.javascriptBased = [[dict objectForKey:@"javascriptBased"] boolValue]; self.onlyPublishCCBs = [[dict objectForKey:@"onlyPublishCCBs"] boolValue]; self.exporter = [dict objectForKey:@"exporter"]; self.deviceOrientationPortrait = [[dict objectForKey:@"deviceOrientationPortrait"] boolValue]; self.deviceOrientationUpsideDown = [[dict objectForKey:@"deviceOrientationUpsideDown"] boolValue]; self.deviceOrientationLandscapeLeft = [[dict objectForKey:@"deviceOrientationLandscapeLeft"] boolValue]; self.deviceOrientationLandscapeRight = [[dict objectForKey:@"deviceOrientationLandscapeRight"] boolValue]; self.resourceAutoScaleFactor = [[dict objectForKey:@"resourceAutoScaleFactor"]intValue]; if (resourceAutoScaleFactor == 0) self.resourceAutoScaleFactor = 4; // Load generated sprite sheet settings NSDictionary* generatedSpriteSheetsDict = [dict objectForKey:@"generatedSpriteSheets"]; generatedSpriteSheets = [NSMutableDictionary dictionary]; if (generatedSpriteSheetsDict) { for (NSString* ssFile in generatedSpriteSheetsDict) { NSDictionary* ssDict = [generatedSpriteSheetsDict objectForKey:ssFile]; ProjectSettingsGeneratedSpriteSheet* ssInfo = [[[ProjectSettingsGeneratedSpriteSheet alloc] initWithSerialization:ssDict] autorelease]; [generatedSpriteSheets setObject:ssInfo forKey:ssFile]; } } [generatedSpriteSheets retain]; NSString* mainCCB = [dict objectForKey:@"javascriptMainCCB"]; if (!mainCCB) mainCCB = @""; self.javascriptMainCCB = mainCCB; [self detectBrowserPresence]; // Check if we are running a new version of CocosBuilder // in which case the project needs to be republished NSString* oldVersionHash = [dict objectForKey:@"versionStr"]; NSString* newVersionHash = [self getVersion]; if (newVersionHash && ![newVersionHash isEqual:oldVersionHash]) { self.versionStr = [self getVersion]; self.needRepublish = YES; } else { self.needRepublish = NO; } return self; } - (void) dealloc { self.versionStr = NULL; self.resourcePaths = NULL; self.projectPath = NULL; self.publishDirectory = NULL; self.exporter = NULL; self.availableExporters = NULL; [generatedSpriteSheets release]; [breakpoints release]; [super dealloc]; } - (NSString*) exporter { if (exporter) return exporter; return kCCBDefaultExportPlugIn; } - (id) serialize { NSMutableDictionary* dict = [NSMutableDictionary dictionary]; [dict setObject:@"CocosBuilderProject" forKey:@"fileType"]; [dict setObject:[NSNumber numberWithInt:kCCBProjectSettingsVersion] forKey:@"fileVersion"]; [dict setObject:resourcePaths forKey:@"resourcePaths"]; [dict setObject:publishDirectory forKey:@"publishDirectory"]; [dict setObject:publishDirectoryAndroid forKey:@"publishDirectoryAndroid"]; [dict setObject:publishDirectoryHTML5 forKey:@"publishDirectoryHTML5"]; [dict setObject:[NSNumber numberWithBool:publishEnablediPhone] forKey:@"publishEnablediPhone"]; [dict setObject:[NSNumber numberWithBool:publishEnabledAndroid] forKey:@"publishEnabledAndroid"]; [dict setObject:[NSNumber numberWithBool:publishEnabledHTML5] forKey:@"publishEnabledHTML5"]; [dict setObject:[NSNumber numberWithBool:publishResolution_] forKey:@"publishResolution_"]; [dict setObject:[NSNumber numberWithBool:publishResolution_hd] forKey:@"publishResolution_hd"]; [dict setObject:[NSNumber numberWithBool:publishResolution_ipad] forKey:@"publishResolution_ipad"]; [dict setObject:[NSNumber numberWithBool:publishResolution_ipadhd] forKey:@"publishResolution_ipadhd"]; [dict setObject:[NSNumber numberWithBool:publishResolution_xsmall] forKey:@"publishResolution_xsmall"]; [dict setObject:[NSNumber numberWithBool:publishResolution_small] forKey:@"publishResolution_small"]; [dict setObject:[NSNumber numberWithBool:publishResolution_medium] forKey:@"publishResolution_medium"]; [dict setObject:[NSNumber numberWithBool:publishResolution_large] forKey:@"publishResolution_large"]; [dict setObject:[NSNumber numberWithBool:publishResolution_xlarge] forKey:@"publishResolution_xlarge"]; [dict setObject:[NSNumber numberWithInt:publishResolutionHTML5_width] forKey:@"publishResolutionHTML5_width"]; [dict setObject:[NSNumber numberWithInt:publishResolutionHTML5_height] forKey:@"publishResolutionHTML5_height"]; [dict setObject:[NSNumber numberWithInt:publishResolutionHTML5_scale] forKey:@"publishResolutionHTML5_scale"]; [dict setObject:[NSNumber numberWithBool:flattenPaths] forKey:@"flattenPaths"]; [dict setObject:[NSNumber numberWithBool:publishToZipFile] forKey:@"publishToZipFile"]; [dict setObject:[NSNumber numberWithBool:javascriptBased] forKey:@"javascriptBased"]; [dict setObject:[NSNumber numberWithBool:onlyPublishCCBs] forKey:@"onlyPublishCCBs"]; [dict setObject:self.exporter forKey:@"exporter"]; [dict setObject:[NSNumber numberWithBool:deviceOrientationPortrait] forKey:@"deviceOrientationPortrait"]; [dict setObject:[NSNumber numberWithBool:deviceOrientationUpsideDown] forKey:@"deviceOrientationUpsideDown"]; [dict setObject:[NSNumber numberWithBool:deviceOrientationLandscapeLeft] forKey:@"deviceOrientationLandscapeLeft"]; [dict setObject:[NSNumber numberWithBool:deviceOrientationLandscapeRight] forKey:@"deviceOrientationLandscapeRight"]; [dict setObject:[NSNumber numberWithInt:resourceAutoScaleFactor] forKey:@"resourceAutoScaleFactor"]; if (!javascriptMainCCB) self.javascriptMainCCB = @""; if (!javascriptBased) self.javascriptMainCCB = @""; [dict setObject:javascriptMainCCB forKey:@"javascriptMainCCB"]; NSMutableDictionary* generatedSpriteSheetsDict = [NSMutableDictionary dictionary]; for (NSString* ssFile in generatedSpriteSheets) { ProjectSettingsGeneratedSpriteSheet* ssInfo = [generatedSpriteSheets objectForKey:ssFile]; id ssDict = [ssInfo serialize]; [generatedSpriteSheetsDict setObject:ssDict forKey:ssFile]; } [dict setObject:generatedSpriteSheetsDict forKey:@"generatedSpriteSheets"]; // if (versionStr) // { // [dict setObject:versionStr forKey:@"versionStr"]; // } [dict setObject:[NSNumber numberWithBool:NO] forKey:@"needRepublish"]; return dict; } - (NSArray*) absoluteResourcePaths { NSString* projectDirectory = [self.projectPath stringByDeletingLastPathComponent]; NSMutableArray* paths = [NSMutableArray array]; for (NSDictionary* dict in resourcePaths) { NSString* path = [dict objectForKey:@"path"]; NSString* absPath = [path absolutePathFromBaseDirPath:projectDirectory]; [paths addObject:absPath]; } if ([paths count] == 0) { [paths addObject:projectDirectory]; } return paths; } - (NSString*) projectPathHashed { if (projectPath) { HashValue* hash = [HashValue md5HashWithString:projectPath]; return [hash description]; } else { return NULL; } } - (NSString*) displayCacheDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [[[[paths objectAtIndex:0] stringByAppendingPathComponent:@"com.cocosbuilder.CocosBuilder"] stringByAppendingPathComponent:@"display"]stringByAppendingPathComponent:self.projectPathHashed]; } - (NSString*) publishCacheDirectory { NSString* uuid = [PlayerConnection sharedPlayerConnection].selectedDeviceInfo.uuid; NSAssert(uuid, @"No uuid for selected device"); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [[[[[paths objectAtIndex:0] stringByAppendingPathComponent:@"com.cocosbuilder.CocosBuilder"] stringByAppendingPathComponent:@"publish"]stringByAppendingPathComponent:self.projectPathHashed] stringByAppendingPathComponent:uuid]; } - (NSString*) tempSpriteSheetCacheDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"com.cocosbuilder.CocosBuilder"] stringByAppendingPathComponent:@"spritesheet"]; } - (BOOL) store { return [[self serialize] writeToFile:self.projectPath atomically:YES]; } - (void) makeSmartSpriteSheet:(RMResource*) res { NSAssert(res.type == kCCBResTypeDirectory, @"Resource must be directory"); NSString* relPath = [ResourceManagerUtil relativePathFromAbsolutePath:res.filePath]; [generatedSpriteSheets setObject:[[[ProjectSettingsGeneratedSpriteSheet alloc] init] autorelease] forKey:relPath]; [self store]; [[CocosBuilderAppDelegate appDelegate].resManager notifyResourceObserversResourceListUpdated]; } - (void) removeSmartSpriteSheet:(RMResource*) res { NSAssert(res.type == kCCBResTypeDirectory, @"Resource must be directory"); NSString* relPath = [ResourceManagerUtil relativePathFromAbsolutePath:res.filePath]; [generatedSpriteSheets removeObjectForKey:relPath]; [self store]; [[CocosBuilderAppDelegate appDelegate].resManager notifyResourceObserversResourceListUpdated]; } - (ProjectSettingsGeneratedSpriteSheet*) smartSpriteSheetForRes:(RMResource*) res { NSAssert(res.type == kCCBResTypeDirectory, @"Resource must be directory"); NSString* relPath = [ResourceManagerUtil relativePathFromAbsolutePath:res.filePath]; return [generatedSpriteSheets objectForKey:relPath]; } - (ProjectSettingsGeneratedSpriteSheet*) smartSpriteSheetForSubPath:(NSString*) relPath { return [generatedSpriteSheets objectForKey:relPath]; } - (void) toggleBreakpointForFile:(NSString*)file onLine:(int)line { // Get breakpoints for file NSMutableSet* bps = [breakpoints objectForKey:file]; if (!bps) { bps = [NSMutableSet set]; [breakpoints setObject:bps forKey:file]; } NSNumber* num = [NSNumber numberWithInt:line]; if ([bps containsObject:num]) { [bps removeObject:num]; } else { [bps addObject:num]; } // Send new list of bps to player [[PlayerConnection sharedPlayerConnection] debugSendBreakpoints:breakpoints]; } - (NSSet*) breakpointsForFile:(NSString*)file { NSSet* bps = [breakpoints objectForKey:file]; if (!bps) bps = [NSSet set]; return bps; } - (void) detectBrowserPresence { isSafariExist = FALSE; isChromeExist = FALSE; isFirefoxExist = FALSE; OSStatus result = LSFindApplicationForInfo (kLSUnknownCreator, CFSTR("com.apple.Safari"), NULL, NULL, NULL); if (result == noErr) { isSafariExist = TRUE; } result = LSFindApplicationForInfo (kLSUnknownCreator, CFSTR("com.google.Chrome"), NULL, NULL, NULL); if (result == noErr) { isChromeExist = TRUE; } result = LSFindApplicationForInfo (kLSUnknownCreator, CFSTR("org.mozilla.firefox"), NULL, NULL, NULL); if (result == noErr) { isFirefoxExist = TRUE; } } - (NSString* ) getVersion { NSString* versionPath = [[NSBundle mainBundle] pathForResource:@"Version" ofType:@"txt" inDirectory:@"version"]; NSString* version = [NSString stringWithContentsOfFile:versionPath encoding:NSUTF8StringEncoding error:NULL]; return version; } @end
{'content_hash': '3039b4304276ff4001b2e7a3c6363bd6', 'timestamp': '', 'source': 'github', 'line_count': 522, 'max_line_length': 238, 'avg_line_length': 37.99233716475096, 'alnum_prop': 0.7405707946752723, 'repo_name': 'mafiagame/CocosBuilder', 'id': '587b60518835717d9b96551a523fbd0e6305d997', 'size': '20994', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CocosBuilder/ccBuilder/ProjectSettings.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '6112'}, {'name': 'C++', 'bytes': '50445'}, {'name': 'DTrace', 'bytes': '12324'}, {'name': 'Groff', 'bytes': '19312'}, {'name': 'HTML', 'bytes': '17681003'}, {'name': 'JavaScript', 'bytes': '216616'}, {'name': 'Objective-C', 'bytes': '1795914'}, {'name': 'Objective-C++', 'bytes': '52858'}, {'name': 'Shell', 'bytes': '1559'}]}
package org.apache.flink.table.api.stream.table.stringexpr import org.apache.flink.api.java.typeutils.RowTypeInfo import org.apache.flink.api.scala._ import org.apache.flink.table.api._ import org.apache.flink.table.api.scala._ import org.apache.flink.table.utils._ import org.apache.flink.types.Row import org.junit.Test import org.mockito.Mockito.{mock, when} import org.apache.flink.streaming.api.datastream.{DataStream => JDataStream} import org.apache.flink.streaming.api.scala.DataStream class CorrelateStringExpressionTest extends TableTestBase { @Test def testCorrelateJoinsWithJoinLateral(): Unit = { val util = streamTestUtil() val typeInfo = new RowTypeInfo(Seq(Types.INT, Types.LONG, Types.STRING): _*) val jDs = mock(classOf[JDataStream[Row]]) when(jDs.getType).thenReturn(typeInfo) val sDs = mock(classOf[DataStream[Row]]) when(sDs.javaStream).thenReturn(jDs) val jTab = util.javaTableEnv.fromDataStream(jDs, "a, b, c") val sTab = util.tableEnv.fromDataStream(sDs, 'a, 'b, 'c) // test cross join val func1 = new TableFunc1 util.javaTableEnv.registerFunction("func1", func1) var scalaTable = sTab.joinLateral(func1('c) as 's).select('c, 's) var javaTable = jTab.joinLateral("func1(c).as(s)").select("c, s") verifyTableEquals(scalaTable, javaTable) // test left outer join scalaTable = sTab.leftOuterJoinLateral(func1('c) as 's).select('c, 's) javaTable = jTab.leftOuterJoinLateral("as(func1(c), s)").select("c, s") verifyTableEquals(scalaTable, javaTable) // test overloading scalaTable = sTab.joinLateral(func1('c, "$") as 's).select('c, 's) javaTable = jTab.joinLateral("func1(c, '$') as (s)").select("c, s") verifyTableEquals(scalaTable, javaTable) // test custom result type val func2 = new TableFunc2 util.javaTableEnv.registerFunction("func2", func2) scalaTable = sTab.joinLateral(func2('c) as ('name, 'len)).select('c, 'name, 'len) javaTable = jTab.joinLateral( "func2(c).as(name, len)").select("c, name, len") verifyTableEquals(scalaTable, javaTable) // test hierarchy generic type val hierarchy = new HierarchyTableFunction util.javaTableEnv.registerFunction("hierarchy", hierarchy) scalaTable = sTab.joinLateral( hierarchy('c) as ('name, 'adult, 'len)).select('c, 'name, 'len, 'adult) javaTable = jTab.joinLateral("AS(hierarchy(c), name, adult, len)") .select("c, name, len, adult") verifyTableEquals(scalaTable, javaTable) // test pojo type val pojo = new PojoTableFunc util.javaTableEnv.registerFunction("pojo", pojo) scalaTable = sTab.joinLateral(pojo('c)).select('c, 'name, 'age) javaTable = jTab.joinLateral("pojo(c)").select("c, name, age") verifyTableEquals(scalaTable, javaTable) // test with filter scalaTable = sTab.joinLateral( func2('c) as ('name, 'len)).select('c, 'name, 'len).filter('len > 2) javaTable = jTab.joinLateral("func2(c) as (name, len)") .select("c, name, len").filter("len > 2") verifyTableEquals(scalaTable, javaTable) // test with scalar function scalaTable = sTab.joinLateral(func1('c.substring(2)) as 's).select('a, 'c, 's) javaTable = jTab.joinLateral( "func1(substring(c, 2)) as (s)").select("a, c, s") verifyTableEquals(scalaTable, javaTable) } @Test def testFlatMap(): Unit = { val util = streamTestUtil() val typeInfo = new RowTypeInfo(Seq(Types.INT, Types.LONG, Types.STRING): _*) val jDs = mock(classOf[JDataStream[Row]]) when(jDs.getType).thenReturn(typeInfo) val sDs = mock(classOf[DataStream[Row]]) when(sDs.javaStream).thenReturn(jDs) val jTab = util.javaTableEnv.fromDataStream(jDs, "a, b, c") val sTab = util.tableEnv.fromDataStream(sDs, 'a, 'b, 'c) // test flatMap val func1 = new TableFunc1 util.javaTableEnv.registerFunction("func1", func1) var scalaTable = sTab.flatMap(func1('c)).as('s).select('s) var javaTable = jTab.flatMap("func1(c)").as("s").select("s") verifyTableEquals(scalaTable, javaTable) // test custom result type val func2 = new TableFunc2 util.javaTableEnv.registerFunction("func2", func2) scalaTable = sTab.flatMap(func2('c)).as('name, 'len).select('name, 'len) javaTable = jTab.flatMap("func2(c)").as("name, len").select("name, len") verifyTableEquals(scalaTable, javaTable) // test hierarchy generic type val hierarchy = new HierarchyTableFunction util.javaTableEnv.registerFunction("hierarchy", hierarchy) scalaTable = sTab.flatMap(hierarchy('c)).as('name, 'adult, 'len).select('name, 'len, 'adult) javaTable = jTab.flatMap("hierarchy(c)").as("name, adult, len").select("name, len, adult") verifyTableEquals(scalaTable, javaTable) // test pojo type val pojo = new PojoTableFunc util.javaTableEnv.registerFunction("pojo", pojo) scalaTable = sTab.flatMap(pojo('c)).select('name, 'age) javaTable = jTab.flatMap("pojo(c)").select("name, age") verifyTableEquals(scalaTable, javaTable) // test with filter scalaTable = sTab.flatMap(func2('c)).as('name, 'len).select('name, 'len).filter('len > 2) javaTable = jTab.flatMap("func2(c)").as("name, len").select("name, len").filter("len > 2") verifyTableEquals(scalaTable, javaTable) // test with scalar function scalaTable = sTab.flatMap(func1('c.substring(2))).as('s).select('s) javaTable = jTab.flatMap("func1(substring(c, 2))").as("s").select("s") verifyTableEquals(scalaTable, javaTable) } }
{'content_hash': '2a7525005983902c6741eee4d062a1c4', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 96, 'avg_line_length': 39.94244604316547, 'alnum_prop': 0.6853386167146974, 'repo_name': 'fhueske/flink', 'id': 'e2068e7a31fd8a29debcdc90bcf3f576c3a81115', 'size': '6357', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/stringexpr/CorrelateStringExpressionTest.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4588'}, {'name': 'CSS', 'bytes': '57936'}, {'name': 'Clojure', 'bytes': '93205'}, {'name': 'Dockerfile', 'bytes': '10793'}, {'name': 'FreeMarker', 'bytes': '17422'}, {'name': 'HTML', 'bytes': '224476'}, {'name': 'Java', 'bytes': '48798371'}, {'name': 'JavaScript', 'bytes': '1829'}, {'name': 'Makefile', 'bytes': '5134'}, {'name': 'Python', 'bytes': '809835'}, {'name': 'Scala', 'bytes': '13339497'}, {'name': 'Shell', 'bytes': '485338'}, {'name': 'TypeScript', 'bytes': '243702'}]}
var BC = require(__dirname+'/../bc') ,_ = require('underscore') ,moment = require('moment') ,RSS = require('rss') ,View = BC.require('bc/view').View ,Content = BC.require('bc/content').Content; exports.RSSView = BC.Base.extend({ data: {} ,constructor: function(data) { this.data = data; } ,render: function() { var feed_params = {} ,feed ,pages ,data = this.data; if (!this.data.pages) { throw new Error('RSSView needs data.pages to be set to the Content URL for the feed contents'); } pages = Content.find_pages(this.data.pages); // Build basic feed params _.each(['title', 'description', 'author'], function(prop){ if (data[prop]) { feed_params[prop] = data[prop]; } }); // Set site URL and feed URL feed_params.site_url = data.site_url || BC.Cfg.site.base_url; feed_params.feed_url = data.url; feed = new RSS(feed_params); // Add posts to feed if (pages) { _.each(pages, function(page){ var p = page.get_view().get_formatted_data(); feed.item({ title: p.title, description: p.content, url: p.url, date: p.pub_date.toString() }); }); } return feed.xml(); } });
{'content_hash': 'e3dbb63adba7c041d9cf6b185aa0b335', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 107, 'avg_line_length': 27.38888888888889, 'alnum_prop': 0.48005409060175797, 'repo_name': 'banks/banksco.de', 'id': '2e11dd73af5038094f4527172e35f6a923924cff', 'size': '1479', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/bc/rss_view.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9513'}, {'name': 'JavaScript', 'bytes': '31563'}, {'name': 'Shell', 'bytes': '2193'}, {'name': 'mupad', 'bytes': '6256'}]}
<!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_14) on Fri Sep 18 14:09:14 BST 2009 --> <TITLE> uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs </TITLE> <META NAME="date" CONTENT="2009-09-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/stubs/package-summary.html" target="classFrame">uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="InterProScanJobPortType.html" title="interface in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame"><I>InterProScanJobPortType</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="GetErrorRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetErrorRequest</A> <BR> <A HREF="GetErrorResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetErrorResponse</A> <BR> <A HREF="GetInputsRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetInputsRequest</A> <BR> <A HREF="GetInputsResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetInputsResponse</A> <BR> <A HREF="GetOutputsRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetOutputsRequest</A> <BR> <A HREF="GetOutputsResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetOutputsResponse</A> <BR> <A HREF="GetStatusRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetStatusRequest</A> <BR> <A HREF="GetStatusResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">GetStatusResponse</A> <BR> <A HREF="InterProScanJobResourceProperties.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.stubs" target="classFrame">InterProScanJobResourceProperties</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{'content_hash': 'bb683d8c8de62f38cd5c90ebf39d7ba2', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 222, 'avg_line_length': 48.52542372881356, 'alnum_prop': 0.7341949004540692, 'repo_name': 'NCIP/taverna-grid', 'id': '9caf9856cc658fa9e4041fdab14500213ccdd71d', 'size': '2863', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'servicewrapper/doc/uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/stubs/package-frame.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '1390844'}, {'name': 'Logos', 'bytes': '7894620'}]}
^title Welcome ## Wren is a small, fast, class-based concurrent scripting language Think Smalltalk in a Lua-sized package with a dash of Erlang and wrapped up in a familiar, modern [syntax][]. :::dart IO.print("Hello, world!") class Wren { flyTo(city) { IO.print("Flying to ", city) } } var adjectives = new Fiber { ["small", "clean", "fast"].map {|word| Fiber.yield(word) } } while (!adjectives.isDone) IO.print(adjectives.call) * **Wren is small.** The codebase is about [5,000 lines][src]. You can skim the whole thing in an afternoon. It's *small*, but not *dense*. It is readable and [lovingly-commented][nan]. * **Wren is fast.** A fast single-pass compiler to tight bytecode, and a compact object representation help Wren [compete with other dynamic languages][perf]. * **Wren is class-based.** There are lots of scripting languages out there, but many have unusual or non-existent object models. Wren places [classes][] front and center. * **Wren is concurrent.** Lightweight [fibers][] are core to the execution model and let you organize your program into an army of communicating coroutines. * **Wren is a scripting language.** Wren is intended for embedding in applications. It has no dependencies, a small standard library, and [an easy-to-use C API][embedding]. It's written in warning-free standard C99. If you like the sound of this, [give it a try][try]! Even better, you can [contribute to Wren itself][contribute]. [syntax]: syntax.html [src]: https://github.com/munificent/wren/tree/master/src [nan]: https://github.com/munificent/wren/blob/46c1ba92492e9257aba6418403161072d640cb29/src/wren_value.h#L378-L433 [perf]: performance.html [classes]: classes.html [fibers]: fibers.html [embedding]: embedding-api.html [try]: getting-started.html [contribute]: contributing.html
{'content_hash': 'cd1f26cd000cb0e6aa3b9d8fcd4de44e', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 114, 'avg_line_length': 34.763636363636365, 'alnum_prop': 0.7013598326359832, 'repo_name': 'lluchs/wren', 'id': 'e328c4f24245a6f11dc8eeb99ed86860f8803571', 'size': '1912', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/site/index.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '218278'}, {'name': 'C++', 'bytes': '22045'}, {'name': 'CSS', 'bytes': '5648'}, {'name': 'Lua', 'bytes': '5473'}, {'name': 'Makefile', 'bytes': '1875'}, {'name': 'Python', 'bytes': '44788'}, {'name': 'Ruby', 'bytes': '4513'}]}
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import { MatDialog, MatDialogRef, MatDialogConfig, MatSnackBar } from '@angular/material'; import { ToolEditComponent } from '../tool-edit/tool-edit.component'; import { StixService } from '../../../stix.service'; import { Tool, AttackPattern, Indicator, IntrusionSet, CourseOfAction, Filter, Relationship } from '../../../../models'; import { Constance } from '../../../../utils/constance'; @Component({ selector: 'tool-new', templateUrl: './tool-new.component.html', }) export class ToolNewComponent extends ToolEditComponent implements OnInit { constructor( public stixService: StixService, public route: ActivatedRoute, public router: Router, public dialog: MatDialog, public location: Location, public snackBar: MatSnackBar) { super(stixService, route, router, dialog, location, snackBar); } public ngOnInit() { } public saveNewTool(): void { console.log(this.tool.url); const sub = super.create(this.tool).subscribe( (data) => { // this.tool = new Tool(data); this.location.back(); // if (this.newRelationships.length > 0) { // let count = this.newRelationships.length; // this.newRelationships.forEach((relationship) => { // this.saveRelationship(relationship); // --count; // if (count <= 0) { // this.location.back(); // } // }); // } else { // this.location.back(); // } }, (error) => { // handle errors here console.log('error ' + error); }, () => { // prevent memory links if (sub) { sub.unsubscribe(); } } ); } }
{'content_hash': 'b669c901af7a4927caa52cbac283ff06', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 120, 'avg_line_length': 37.3859649122807, 'alnum_prop': 0.5180666353824496, 'repo_name': 'unfetter-discover/unfetter-ui', 'id': '0a6dff9e98a6d38dd3d75007e50b3408821f611e', 'size': '2131', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/app/settings/stix-objects/tools/tool-new/tool-new.component.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '141878'}, {'name': 'Dockerfile', 'bytes': '1707'}, {'name': 'HTML', 'bytes': '497299'}, {'name': 'JavaScript', 'bytes': '4883'}, {'name': 'Shell', 'bytes': '595'}, {'name': 'TypeScript', 'bytes': '2672398'}]}