text
stringlengths
2
1.04M
meta
dict
package com.mentatlabs.nsa package scalac package dsl import experimental._ trait ScalacOptionsExperimentalDSL extends ScalacExperimentalDSL // core options experimental with ScalacDeprecationDSL with ScalacEncodingDSL with ScalacExplaintypesDSL with ScalacFeatureDSL with ScalacGDSL with ScalacHelpDSL with ScalacLanguageDSL with ScalacNobootcpDSL with ScalacNoDSL with ScalacNowarnDSL with ScalacOptimiseDSL with ScalacPrintDSL with ScalacSourcepathDSL with ScalacTargetDSL with ScalacUncheckedDSL with ScalacUniqidDSL with ScalacUsejavacpDSL with ScalacUsemanifestcpDSL with ScalacVerboseDSL with ScalacVersionDSL with ScalacXDSL // advanced options experimental with ScalacXCheckinitDSL with ScalacXDevDSL with ScalacXDisableDSL with ScalacXElideDSL with ScalacXExperimentalDSL with ScalacXFatalDSL with ScalacXFullDSL with ScalacXFutureDSL with ScalacXLintDSL with ScalacXLogDSL with ScalacXMaxDSL with ScalacXNoDSL with ScalacXNojlineDSL with ScalacXPluginDSL with ScalacXPrintDSL with ScalacXPromptDSL with ScalacXResidentDSL with ScalacXShowDSL with ScalacXSourceDSL with ScalacXStrictDSL with ScalacXVerifyDSL with ScalacYDSL // private additional experimental with ScalacYBackendDSL with ScalacYBreakDSL with ScalacYClosureDSL with ScalacYCompactDSL with ScalacYConstDSL with ScalacYDeadDSL with ScalacYDebugDSL with ScalacYDelambdafyDSL with ScalacYDisableDSL with ScalacYDocDSL with ScalacYEtaDSL with ScalacYIdeDSL with ScalacYInferDSL with ScalacYInlineDSL with ScalacYIssueDSL with ScalacYLogDSL with ScalacYMacroDSL with ScalacYNoDSL with ScalacYNooptimiseDSL with ScalacYOptDSL with ScalacYOverrideDSL with ScalacYPatmatDSL with ScalacYPosDSL with ScalacYPresentationDSL with ScalacYQuasiquoteDSL with ScalacYRangeposDSL with ScalacYReifyDSL with ScalacYReplDSL with ScalacYResolveDSL with ScalacYShowDSL with ScalacYSkipDSL with ScalacYStatisticsDSL with ScalacYStopDSL with ScalacYTyperDSL with ScalacYWarnDSL
{ "content_hash": "f0eeb7b59400986ba0f1a4dcfddb9972", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 38, "avg_line_length": 24.58695652173913, "alnum_prop": 0.768788682581786, "repo_name": "mentat-labs/sbt-nsa", "id": "982c01148c47cf350cb229872d4139747f8af2fd", "size": "2262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "nsa-dsl/src/main/scala/com/mentatlabs/nsa/scalac/dsl/ScalacOptionsExperimentalDSL.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Scala", "bytes": "210674" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <!-- <link rel="icon" href="../../favicon.ico"> --> <title>OriginJS - Data Manipulation JS</title> <!-- Bootstrap core CSS --> <link href="WebContent/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="WebContent/lib/bootstrap/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="WebContent/lib/bootstrap/css/jumbotron.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">OriginJS</a> </div> <!-- <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right"> <div class="form-group"> <input type="text" placeholder="Email" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="Password" class="form-control"> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div> --> <!--/.navbar-collapse --> </div> </nav> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Hello, OriginJS Developers!</h1> <p>This is a JS Library used to manipulate the data's in the form of HTML tables and Canvas based Visualization Charts. This library consumes JSON data used to plot the charts and tables. We are working on tables right now, the charts will be included on later releases.</p> <p> <a class="btn btn-primary btn-lg" href="#" role="button">Learn more &raquo;</a> </p> </div> </div> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-md-6"> <h2>JQuery Plugin</h2> <p>TBD</p> <p> <a class="btn btn-default" href="#" role="button">View details &raquo;</a> </p> </div> <div class="col-md-6"> <h2>Angular JS 1.x Plugin</h2> <p>TBD</p> <p> <a class="btn btn-default" href="#" role="button">View details &raquo;</a> </p> </div> </div> <hr> <!-- <footer> <p>&copy; 2016 Company, Inc.</p> </footer> --> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="WebContent/lib/jquery/js/jquery-1.11.1.min.js"></script> <script src="WebContent/lib/bootstrap/js/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="WebContent/lib/bootstrap/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
{ "content_hash": "3a7274f8c82444defa9b8109733d27ca", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 113, "avg_line_length": 32.86666666666667, "alnum_prop": 0.5988843813387424, "repo_name": "originjsdev/OriginJS", "id": "955bd15f13cbc12597b9351252b28a0d1f6e976e", "size": "3944", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4082" }, { "name": "JavaScript", "bytes": "180" } ], "symlink_target": "" }
layout: post title: Comment on Project 1 (Other Teams) published: true --- In this post, I will download, run, examine, and comment on other projects submitted for PROJECT 1 in the CS 491 - Virtual and Augmented Reality class. The two projects I have selected are ones I found well implemented and carefully thought out. This review is more of a personal comment than a formal review. Let us explore start with the first project I found awesome! # 1. TEAM 1 (Amico, Simone | Foglio, Matteo | Milanta, Andrea) At first glance, the scene of their project looks simple and similar to every other project in the class. However, at closer inspection and probing, the project seems to deliver new concepts not mentioned in the project requirements. Before going into too much detail, the team implemented some really cool concepts such as music looping through wand interactions, GameObject creation through colliders, custom lighting, and extension of two rooms in a singular classroom. Let us go into details as to how. ## Interactions Firstly, I love how they managed to implement GameObject creation with the Coke vending machine. Whenever you tap on the Coke vending machine button, a coke bottle drops from the machine. That would be creation of a GameObject when some interaction is done. Why don’t we see that through a gif interaction instead of an image: ![Vending Machine]({{ site.url }}/assets/project1_review/coke.gif) That is clearly a cool concept that was implemented and I have not seen that with any of the other teams (including mine). ## Sound Loop The second thing I found great was the sound looping. We implemented in our project too, but this team added the ability to pause music instead of just stopping it. My sound loop works on 4 songs and it stops (you can restart), but you cannot pause in mine. The sound controls look pretty decent on the wall to for easy use. ![Song Control]({{ site.url }}/assets/project1_review/sounds.png) ## Lighting Thirdly, I like the party mode/disco lighting that was implemented when you hit the button on the wall. They used a custom lighting model instead of the usual point light and what not. That is a really creative use of lighting in a scene. A gif of that: ![Lights]({{ site.url }}/assets/project1_review/lights.gif) 
## Effective Use of Space Lastly, the use of the sound room and more to convert into a music room and kitchen was nicely done. The objects there are appropriate. Also, this gives the team an opportunity to fill the scene with more objects. ![Whole Room]({{ site.url }}/assets/project1_review/whole_room.png) Final thoughts would be how they also implemented frame rates well. On my laptop, the executable lagged a bit. However, the demonstration on the Vive in the classroom had ample frame-rate and was decent. This was the first project I found particularly good. # 2. TEAM 2 (Jyothula, Sai Priya | Sakhnini, Nina) The second team project I found innovative and well implemented is the project by Sai Priya and Nina. This project is simple and well made. There are many interactions to play around with and all of them have a functional use rather than just an aesthetic appeal. Some of the things I loved was that you can remove the roof (which I will get to), you can pickup individual chess pieces (our project just picks up the entire chess board), and the effective use of space with respect to work cubicles in the middle of the room. ## Interactions The first interaction that I love is the way the roof opens up when you trigger into the switch in the left side of the room. The switch is located besides another switch which turns on/off the main light source in the room. The roof opening/closing is also accompanied by a sound trigger. The only thing I did not like about this implementation though is the fact that the roof disappears immediately. The sound trigger suggests the roof is sliding in or out of the ceiling. However, the roof simply disappears in this implementation. That is okay and can be built upon. A gif with these interactions: ![Lights GIF]({{ site.url }}/assets/project1_review/lights2.gif) The second interaction I liked was you can pick up individual chess pieces. The implementation requires a box collider on each of the chess pieces. I believe box colliders do not use that much processing and thus the frame rate was saved. Had they used mesh colliders, the application would have been painfully slow or would have crashed. An image of the colliders and a gif is below: ![Chess]({{ site.url }}/assets/project1_review/chess.png) ![Chess GIF]({{ site.url }}/assets/project1_review/chess.gif) ## Sound Triggers Almost every actionable item in the scene has a sound trigger attached to it which is pretty cool. The speakers have bongo music playing, going near the cat makes a meow sound, and the aquarium has a bubble noise when you go close to it. One thing I believe that could be improved is the effective range of these items. For the speakers to work, I have to literally go through the speakers (this is specific to when testing the application on a laptop because you could just touch the speaker using the wand on a HTC Vive). ## Effective Use of Space The last thing I liked about this project is the effective usage of space. Every part of the room has a dedicated space with a meaning. The front of the room is the meeting area (with the roof placed strategically over it), the middle is the working area with cubicles or polygons, and the rear of the room is the enjoyment area with speakers, water fountain, and chess board. ![Whole Room]({{ site.url }}/assets/project1_review/whole_room2.png) All in all, the project is really well made with simple concepts and well executed implementations. Finally, these are the two projects I found well made and worth a good grade!
{ "content_hash": "af17c8982e3c6e834431ec82b04751ba", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 602, "avg_line_length": 83.38571428571429, "alnum_prop": 0.7820798355319514, "repo_name": "amlaanb/amlaanb.github.io", "id": "2a1ceb9a5ef8c14c2b4bee2070aaa9e4c3a6acdf", "size": "5845", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-10-04-WEEK5_PROJECT1_review.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "63525" }, { "name": "HTML", "bytes": "6266" } ], "symlink_target": "" }
mvn clean mvn install svn update
{ "content_hash": "1a64a1da9df9e93ebc2c7753eaa6ce69", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 11, "avg_line_length": 11, "alnum_prop": 0.8181818181818182, "repo_name": "ngallagher/simplexml", "id": "53fefd20dea9f3a7b4c4e7d1d4bfa1b31de27c95", "size": "33", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "script/maven-package.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2876322" }, { "name": "Java", "bytes": "3359734" }, { "name": "Shell", "bytes": "922" } ], "symlink_target": "" }
UPDATE jforum_categories SET display_order = categories_id; ALTER TABLE jforum_users ADD user_karma DECIMAL(10, 2); ALTER TABLE jforum_posts ADD attach TINYINT(1) DEFAULT '0'; ALTER TABLE jforum_posts ADD need_moderate TINYINT(1) DEFAULT '0'; ALTER TABLE jforum_categories ADD moderated TINYINT(1) DEFAULT '0'; ALTER TABLE jforum_forums CHANGE moderated moderated TINYINT(1) DEFAULT '0'; ALTER TABLE jforum_topics CHANGE moderated moderated TINYINT(1) DEFAULT '0'; ALTER TABLE jforum_search_topics CHANGE topic_title topic_title VARCHAR(100); -- -- Table structure for table 'jforum_karma' -- DROP TABLE IF EXISTS jforum_karma; CREATE TABLE jforum_karma ( karma_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, post_id INT NOT NULL, topic_id INT NOT NULL, post_user_id INT NOT NULL, from_user_id INT NOT NULL, points INT NOT NULL, rate_date datetime NULL, KEY(post_id), KEY(topic_id), KEY(post_user_id), KEY(from_user_id) ) Engine=InnoDB; -- -- Table structure for table 'jforum_bookmark' -- DROP TABLE IF EXISTS jforum_bookmarks; CREATE TABLE jforum_bookmarks ( bookmark_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT NOT NULL, relation_id INT NOT NULL, relation_type INT NOT NULL, public_visible INT DEFAULT '1', title varchar(255), description varchar(255), INDEX book_idx_relation (relation_id), KEY(user_id) ) Engine=InnoDB; -- -- Table structure for table 'jforum_quota_limit' -- DROP TABLE IF EXISTS jforum_quota_limit; CREATE TABLE jforum_quota_limit ( quota_limit_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, quota_desc VARCHAR(50) NOT NULL, quota_limit INT NOT NULL, quota_type TINYINT(1) DEFAULT '1' ) Engine=InnoDB; -- -- Table structure for table 'jforum_extension_groups' -- DROP TABLE IF EXISTS jforum_extension_groups; CREATE TABLE jforum_extension_groups ( extension_group_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, allow TINYINT(1) DEFAULT '1', upload_icon VARCHAR(100), download_mode TINYINT(1) DEFAULT '1' ) Engine=InnoDB; -- -- Table structure for table 'jforum_extensions' -- DROP TABLE IF EXISTS jforum_extensions; CREATE TABLE jforum_extensions ( extension_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, extension_group_id INT NOT NULL, description VARCHAR(100), upload_icon VARCHAR(100), extension VARCHAR(10), allow TINYINT(1) DEFAULT '1', KEY(extension_group_id) ) Engine=InnoDB; -- -- Table structure for table 'jforum_attach' -- DROP TABLE IF EXISTS jforum_attach; CREATE TABLE jforum_attach ( attach_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, post_id INT, privmsgs_id INT, user_id INT NOT NULL, INDEX idx_att_post(post_id), INDEX idx_att_priv(privmsgs_id), INDEX idx_att_user(user_id) ) Engine=InnoDB; -- -- Table structure for table 'jforum_attach_desc' -- DROP TABLE IF EXISTS jforum_attach_desc; CREATE TABLE jforum_attach_desc ( attach_desc_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, attach_id INT NOT NULL, physical_filename VARCHAR(255) NOT NULL, real_filename VARCHAR(255) NOT NULL, download_count INT, description VARCHAR(255), mimetype VARCHAR(50), filesize INT, upload_time DATETIME, thumb TINYINT(1) DEFAULT '0', extension_id INT, INDEX idx_att_d_att(attach_id), INDEX idx_att_d_ext(extension_id) ) Engine=InnoDB; -- -- Table structure for table 'jforum_attach_quota' -- DROP TABLE IF EXISTS jforum_attach_quota; CREATE TABLE jforum_attach_quota ( attach_quota_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, group_id INT NOT NULL, quota_limit_id INT NOT NULL, KEY(group_id) ) Engine=InnoDB;
{ "content_hash": "da2b05a03add31d6a021a4b7362ae2dd", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 77, "avg_line_length": 28.69918699186992, "alnum_prop": 0.7504249291784703, "repo_name": "seaclouds-atos/softcare-secondary-implementation", "id": "a7d33e80188c3c51c1702a56c09cbcd36268543e", "size": "3530", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "softcare-forum/upgrade/2.1/mysql_2.0.2_to_2.1.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "360" }, { "name": "C#", "bytes": "1025142" }, { "name": "CSS", "bytes": "207017" }, { "name": "FreeMarker", "bytes": "17703" }, { "name": "HTML", "bytes": "362811" }, { "name": "Java", "bytes": "4199232" }, { "name": "JavaScript", "bytes": "91246" }, { "name": "PLSQL", "bytes": "47043" }, { "name": "Shell", "bytes": "219" }, { "name": "XSLT", "bytes": "21697" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#000" android:orientation="vertical" > <com.markupartist.android.widget.ActionBar android:id="@+id/actionBar1" style="@style/ActionBar" > </com.markupartist.android.widget.ActionBar> <CheckBox android:id="@+id/notificationSettingsCheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="50dp" android:text="@string/notification_settings_text" /> </LinearLayout>
{ "content_hash": "099f7a61b3835d21b9ef9bbb36c3b987", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 72, "avg_line_length": 35.85, "alnum_prop": 0.6694560669456067, "repo_name": "the100rabh/Barcamp-Bangalore-Android-App", "id": "2c92ec062a961d436bbaf6d9fa3724f12ae43c0e", "size": "717", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bcb_app/res/layout/settings_screen.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "115670" }, { "name": "Java", "bytes": "331782" }, { "name": "JavaScript", "bytes": "84163" }, { "name": "Perl", "bytes": "1313" }, { "name": "Python", "bytes": "1457469" } ], "symlink_target": "" }
<?php namespace craft\feedme\helpers; class DuplicateHelper { public const Add = 'add'; public const Update = 'update'; public const Disable = 'disable'; public const DisableForSite = 'disableForSite'; public const Delete = 'delete'; // Public Methods // ========================================================================= /** * @param $handles * @return string */ public static function getFriendly($handles): string { $array = []; foreach ($handles as $handle) { $array[] = ucfirst($handle); } return implode(' & ', $array); } /** * @param $handles * @param $handle * @param false $only * @return bool */ public static function contains($handles, $handle, bool $only = false): bool { if (in_array($handle, $handles, true)) { if ($only) { if (count($handles) == 1) { return true; } } else { return true; } } return false; } /** * @param $feedData * @param false $only * @return bool */ public static function isAdd($feedData, bool $only = false): bool { return self::contains($feedData['duplicateHandle'], self::Add, $only); } /** * @param $feedData * @param false $only * @return bool */ public static function isUpdate($feedData, bool $only = false): bool { return self::contains($feedData['duplicateHandle'], self::Update, $only); } /** * @param $feedData * @param false $only * @return bool */ public static function isDisable($feedData, bool $only = false): bool { return self::contains($feedData['duplicateHandle'], self::Disable, $only); } /** * @param $feedData * @param false $only * @return bool */ public static function isDisableForSite($feedData, bool $only = false): bool { return self::contains($feedData['duplicateHandle'], self::DisableForSite, $only); } /** * @param $feedData * @param false $only * @return bool */ public static function isDelete($feedData, bool $only = false): bool { return self::contains($feedData['duplicateHandle'], self::Delete, $only); } }
{ "content_hash": "c0935cde58a87e8f9eacd49e089f0131", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 89, "avg_line_length": 23.712871287128714, "alnum_prop": 0.5198329853862212, "repo_name": "engram-design/FeedMe", "id": "f65389bd3d16c0da98da2336353d835b103060f0", "size": "2395", "binary": false, "copies": "1", "ref": "refs/heads/dependabot/npm_and_yarn/grunt-1.5.3", "path": "src/helpers/DuplicateHelper.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11247" }, { "name": "HTML", "bytes": "114184" }, { "name": "JavaScript", "bytes": "145104" }, { "name": "PHP", "bytes": "249588" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.stats.power.TTestPower &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.power.TTestPower.plot_power" href="statsmodels.stats.power.TTestPower.plot_power.html" /> <link rel="prev" title="statsmodels.stats.power.TTestIndPower.solve_power" href="statsmodels.stats.power.TTestIndPower.solve_power.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.stats.power.TTestPower" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.13.5</span> <span class="md-header-nav__topic"> statsmodels.stats.power.TTestPower </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.13.5</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-stats-power-ttestpower--page-root" class="md-nav__link">statsmodels.stats.power.TTestPower</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.stats.power.TTestPower" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">TTestPower</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.power.TTestPower.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-stats-power-ttestpower"> <h1 id="generated-statsmodels-stats-power-ttestpower--page-root">statsmodels.stats.power.TTestPower<a class="headerlink" href="#generated-statsmodels-stats-power-ttestpower--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py class"> <dt class="sig sig-object py" id="statsmodels.stats.power.TTestPower"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">statsmodels.stats.power.</span></span><span class="sig-name descname"><span class="pre">TTestPower</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/stats/power.html#TTestPower"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.stats.power.TTestPower" title="Permalink to this definition">¶</a></dt> <dd><p>Statistical Power calculations for one sample or paired sample t-test</p> <p class="rubric">Methods</p> <table class="autosummary longtable docutils align-default"> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.TTestPower.plot_power.html#statsmodels.stats.power.TTestPower.plot_power" title="statsmodels.stats.power.TTestPower.plot_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">plot_power</span></code></a>([dep_var, nobs, effect_size, ...])</p></td> <td><p>Plot power with number of observations or effect size on x-axis</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.power.TTestPower.power.html#statsmodels.stats.power.TTestPower.power" title="statsmodels.stats.power.TTestPower.power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">power</span></code></a>(effect_size, nobs, alpha[, df, ...])</p></td> <td><p>Calculate the power of a t-test for one sample or paired samples.</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.TTestPower.solve_power.html#statsmodels.stats.power.TTestPower.solve_power" title="statsmodels.stats.power.TTestPower.solve_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">solve_power</span></code></a>([effect_size, nobs, alpha, ...])</p></td> <td><p>solve for any one parameter of the power of a one sample t-test</p></td> </tr> </tbody> </table> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.stats.power.TTestIndPower.solve_power.html" title="statsmodels.stats.power.TTestIndPower.solve_power" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.stats.power.TTestIndPower.solve_power </span> </div> </a> <a href="statsmodels.stats.power.TTestPower.plot_power.html" title="statsmodels.stats.power.TTestPower.plot_power" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.stats.power.TTestPower.plot_power </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 02, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "306c8eb170f22ae3d1c2d02a53370a94", "timestamp": "", "source": "github", "line_count": 519, "max_line_length": 999, "avg_line_length": 39.95375722543353, "alnum_prop": 0.6037808641975309, "repo_name": "statsmodels/statsmodels.github.io", "id": "27f8ff07ac6bddeca20af67e9e8d02380842cee9", "size": "20750", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "v0.13.5/generated/statsmodels.stats.power.TTestPower.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/xing_gray" android:state_checked="false"></item> <item android:drawable="@drawable/xing_red" android:state_checked="true"></item> <!--<item android:drawable="@drawable/guanzhu" android:state_checkable="true"></item>--> </selector>
{ "content_hash": "061d8600a312c58a2a32ed065fca9417", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 92, "avg_line_length": 64.16666666666667, "alnum_prop": 0.7090909090909091, "repo_name": "liangsheng888/Estore", "id": "a8ce25125baffd67030878bb9313989a1a6127ae", "size": "385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/guanzhu_selector.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1327685" } ], "symlink_target": "" }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@egjs/hammerjs'), require('@egjs/component')) : typeof define === 'function' && define.amd ? define(['@egjs/hammerjs', '@egjs/component'], factory) : (global.eg = global.eg || {}, global.eg.Axes = factory(global.Hammer,global.eg.Component)); }(this, (function (hammerjs,Component) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; function getInsidePosition(destPos, range, circular, bounce) { var toDestPos = destPos; var targetRange = [circular[0] ? range[0] : bounce ? range[0] - bounce[0] : range[0], circular[1] ? range[1] : bounce ? range[1] + bounce[1] : range[1]]; toDestPos = Math.max(targetRange[0], toDestPos); toDestPos = Math.min(targetRange[1], toDestPos); return +toDestPos.toFixed(5); } // determine outside function isOutside(pos, range) { return pos < range[0] || pos > range[1]; } function getDuration(distance, deceleration) { var duration = Math.sqrt(distance / deceleration * 2); // when duration is under 100, then value is zero return duration < 100 ? 0 : duration; } function isCircularable(destPos, range, circular) { return circular[1] && destPos > range[1] || circular[0] && destPos < range[0]; } function getCirculatedPos(pos, range, circular) { var toPos = pos; var min = range[0]; var max = range[1]; var length = max - min; if (circular[1] && pos > max) { // right toPos = (toPos - max) % length + min; } if (circular[0] && pos < min) { // left toPos = (toPos - min) % length + max; } return +toPos.toFixed(5); } function equal(target, base) { for (var k in target) { if (target[k] !== base[k]) { return false; } } return true; } var AxisManager = /*#__PURE__*/ function () { function AxisManager(axis, options) { var _this = this; this.axis = axis; this.options = options; this._complementOptions(); this._pos = Object.keys(this.axis).reduce(function (acc, v) { acc[v] = _this.axis[v].range[0]; return acc; }, {}); } /** * set up 'css' expression * @private */ var __proto = AxisManager.prototype; __proto._complementOptions = function () { var _this = this; Object.keys(this.axis).forEach(function (axis) { _this.axis[axis] = __assign({ range: [0, 100], bounce: [0, 0], circular: [false, false] }, _this.axis[axis]); ["bounce", "circular"].forEach(function (v) { var axisOption = _this.axis; var key = axisOption[axis][v]; if (/string|number|boolean/.test(typeof key)) { axisOption[axis][v] = [key, key]; } }); }); }; __proto.getDelta = function (depaPos, destPos) { var fullDepaPos = this.get(depaPos); return this.map(this.get(destPos), function (v, k) { return v - fullDepaPos[k]; }); }; __proto.get = function (axes) { var _this = this; if (axes && Array.isArray(axes)) { return axes.reduce(function (acc, v) { if (v && v in _this._pos) { acc[v] = _this._pos[v]; } return acc; }, {}); } else { return __assign({}, this._pos, axes || {}); } }; __proto.moveTo = function (pos) { var _this = this; var delta = this.map(this._pos, function (v, key) { return pos[key] ? pos[key] - _this._pos[key] : 0; }); this.set(pos); return { pos: __assign({}, this._pos), delta: delta }; }; __proto.set = function (pos) { for (var k in pos) { if (k && k in this._pos) { this._pos[k] = pos[k]; } } }; __proto.every = function (pos, callback) { var axisOptions = this.axis; for (var k in pos) { if (k) { if (!callback(pos[k], k, axisOptions[k])) { return false; } } } return true; }; __proto.filter = function (pos, callback) { var filtered = {}; var axisOptions = this.axis; for (var k in pos) { if (k) { callback(pos[k], k, axisOptions[k]) && (filtered[k] = pos[k]); } } return filtered; }; __proto.map = function (pos, callback) { var tranformed = {}; var axisOptions = this.axis; for (var k in pos) { if (k) { tranformed[k] = callback(pos[k], k, axisOptions[k]); } } return tranformed; }; __proto.isOutside = function (axes) { return !this.every(axes ? this.get(axes) : this._pos, function (v, k, opt) { return !isOutside(v, opt.range); }); }; return AxisManager; }(); /* eslint-disable no-new-func, no-nested-ternary */ var win; if (typeof window === "undefined") { // window is undefined in node.js win = {}; } else { win = window; } function toArray(nodes) { // const el = Array.prototype.slice.call(nodes); // for IE8 var el = []; for (var i = 0, len = nodes.length; i < len; i++) { el.push(nodes[i]); } return el; } function $(param, multi) { if (multi === void 0) { multi = false; } var el; if (typeof param === "string") { // String (HTML, Selector) // check if string is HTML tag format var match = param.match(/^<([a-z]+)\s*([^>]*)>/); // creating element if (match) { // HTML var dummy = document.createElement("div"); dummy.innerHTML = param; el = toArray(dummy.childNodes); } else { // Selector el = toArray(document.querySelectorAll(param)); } if (!multi) { el = el.length >= 1 ? el[0] : undefined; } } else if (param === win) { // window el = param; } else if (param.nodeName && (param.nodeType === 1 || param.nodeType === 9)) { // HTMLElement, Document el = param; } else if ("jQuery" in win && param instanceof jQuery || param.constructor.prototype.jquery) { // jQuery el = multi ? param.toArray() : param.get(0); } else if (Array.isArray(param)) { el = param.map(function (v) { return $(v); }); if (!multi) { el = el.length >= 1 ? el[0] : undefined; } } return el; } var raf = win.requestAnimationFrame || win.webkitRequestAnimationFrame; var caf = win.cancelAnimationFrame || win.webkitCancelAnimationFrame; if (raf && !caf) { var keyInfo_1 = {}; var oldraf_1 = raf; raf = function (callback) { function wrapCallback(timestamp) { if (keyInfo_1[key]) { callback(timestamp); } } var key = oldraf_1(wrapCallback); keyInfo_1[key] = true; return key; }; caf = function (key) { delete keyInfo_1[key]; }; } else if (!(raf && caf)) { raf = function (callback) { return win.setTimeout(function () { callback(win.performance && win.performance.now && win.performance.now() || new Date().getTime()); }, 16); }; caf = win.clearTimeout; } /** * A polyfill for the window.requestAnimationFrame() method. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame * @private */ function requestAnimationFrame(fp) { return raf(fp); } /** * A polyfill for the window.cancelAnimationFrame() method. It cancels an animation executed through a call to the requestAnimationFrame() method. * @param {Number} key − The ID value returned through a call to the requestAnimationFrame() method. <ko>requestAnimationFrame() 메서드가 반환한 아이디 값</ko> * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame * @private */ function cancelAnimationFrame(key) { caf(key); } function minMax(value, min, max) { return Math.max(Math.min(value, max), min); } var AnimationManager = /*#__PURE__*/ function () { function AnimationManager(_a) { var options = _a.options, itm = _a.itm, em = _a.em, axm = _a.axm; this.options = options; this.itm = itm; this.em = em; this.axm = axm; this.animationEnd = this.animationEnd.bind(this); } var __proto = AnimationManager.prototype; __proto.getDuration = function (depaPos, destPos, wishDuration) { var _this = this; var duration; if (typeof wishDuration !== "undefined") { duration = wishDuration; } else { var durations_1 = this.axm.map(destPos, function (v, k) { return getDuration(Math.abs(Math.abs(v) - Math.abs(depaPos[k])), _this.options.deceleration); }); duration = Object.keys(durations_1).reduce(function (max, v) { return Math.max(max, durations_1[v]); }, -Infinity); } return minMax(duration, this.options.minimumDuration, this.options.maximumDuration); }; __proto.createAnimationParam = function (pos, duration, option) { var depaPos = this.axm.get(); var destPos = pos; var inputEvent = option && option.event || null; return { depaPos: depaPos, destPos: destPos, duration: minMax(duration, this.options.minimumDuration, this.options.maximumDuration), delta: this.axm.getDelta(depaPos, destPos), inputEvent: inputEvent, input: option && option.input || null, isTrusted: !!inputEvent, done: this.animationEnd }; }; __proto.grab = function (axes, option) { if (this._animateParam && axes.length) { var orgPos_1 = this.axm.get(axes); var pos = this.axm.map(orgPos_1, function (v, k, opt) { return getCirculatedPos(v, opt.range, opt.circular); }); if (!this.axm.every(pos, function (v, k) { return orgPos_1[k] === v; })) { this.em.triggerChange(pos, option, !!option); } this._animateParam = null; this._raf && cancelAnimationFrame(this._raf); this._raf = null; this.em.triggerAnimationEnd(!!(option && option.event)); } }; __proto.getEventInfo = function () { if (this._animateParam && this._animateParam.input && this._animateParam.inputEvent) { return { input: this._animateParam.input, event: this._animateParam.inputEvent }; } else { return null; } }; __proto.restore = function (option) { var pos = this.axm.get(); var destPos = this.axm.map(pos, function (v, k, opt) { return Math.min(opt.range[1], Math.max(opt.range[0], v)); }); this.animateTo(destPos, this.getDuration(pos, destPos), option); }; __proto.animationEnd = function () { var beforeParam = this.getEventInfo(); this._animateParam = null; // for Circular var circularTargets = this.axm.filter(this.axm.get(), function (v, k, opt) { return isCircularable(v, opt.range, opt.circular); }); Object.keys(circularTargets).length > 0 && this.setTo(this.axm.map(circularTargets, function (v, k, opt) { return getCirculatedPos(v, opt.range, opt.circular); })); this.itm.setInterrupt(false); this.em.triggerAnimationEnd(!!beforeParam); if (this.axm.isOutside()) { this.restore(beforeParam); } else { this.em.triggerFinish(!!beforeParam); } }; __proto.animateLoop = function (param, complete) { this._animateParam = __assign({}, param); this._animateParam.startTime = new Date().getTime(); if (param.duration) { var info_1 = this._animateParam; var self_1 = this; (function loop() { self_1._raf = null; if (self_1.frame(info_1) >= 1) { if (!equal(param.destPos, self_1.axm.get(Object.keys(param.destPos)))) { self_1.em.triggerChange(param.destPos); } complete(); return; } // animationEnd self_1._raf = requestAnimationFrame(loop); })(); } else { this.em.triggerChange(param.destPos); complete(); } }; __proto.getUserControll = function (param) { var userWish = param.setTo(); userWish.destPos = this.axm.get(userWish.destPos); userWish.duration = minMax(userWish.duration, this.options.minimumDuration, this.options.maximumDuration); return userWish; }; __proto.animateTo = function (destPos, duration, option) { var _this = this; var param = this.createAnimationParam(destPos, duration, option); var depaPos = __assign({}, param.depaPos); var retTrigger = this.em.triggerAnimationStart(param); // to control var userWish = this.getUserControll(param); // You can't stop the 'animationStart' event when 'circular' is true. if (!retTrigger && this.axm.every(userWish.destPos, function (v, k, opt) { return isCircularable(v, opt.range, opt.circular); })) { console.warn("You can't stop the 'animation' event when 'circular' is true."); } if (retTrigger && !equal(userWish.destPos, depaPos)) { var inputEvent = option && option.event || null; this.animateLoop({ depaPos: depaPos, destPos: userWish.destPos, duration: userWish.duration, delta: this.axm.getDelta(depaPos, userWish.destPos), isTrusted: !!inputEvent, inputEvent: inputEvent, input: option && option.input || null }, function () { return _this.animationEnd(); }); } }; // animation frame (0~1) __proto.frame = function (param) { var curTime = new Date().getTime() - param.startTime; var easingPer = this.easing(curTime / param.duration); var toPos = param.depaPos; toPos = this.axm.map(toPos, function (v, k, opt) { v += param.delta[k] * easingPer; return getCirculatedPos(v, opt.range, opt.circular); }); this.em.triggerChange(toPos); return easingPer; }; __proto.easing = function (p) { return p > 1 ? 1 : this.options.easing(p); }; __proto.setTo = function (pos, duration) { if (duration === void 0) { duration = 0; } var axes = Object.keys(pos); this.grab(axes); var orgPos = this.axm.get(axes); if (equal(pos, orgPos)) { return this; } this.itm.setInterrupt(true); var movedPos = this.axm.filter(pos, function (v, k) { return orgPos[k] !== v; }); if (!Object.keys(movedPos).length) { return this; } movedPos = this.axm.map(movedPos, function (v, k, opt) { if (opt.circular && (opt.circular[0] || opt.circular[1])) { return duration > 0 ? v : getCirculatedPos(v, opt.range, opt.circular); } else { return getInsidePosition(v, opt.range, opt.circular); } }); if (equal(movedPos, orgPos)) { return this; } if (duration > 0) { this.animateTo(movedPos, duration); } else { this.em.triggerChange(movedPos); this.itm.setInterrupt(false); } return this; }; __proto.setBy = function (pos, duration) { if (duration === void 0) { duration = 0; } return this.setTo(this.axm.map(this.axm.get(Object.keys(pos)), function (v, k) { return v + pos[k]; }), duration); }; return AnimationManager; }(); var EventManager = /*#__PURE__*/ function () { function EventManager(axes) { this.axes = axes; } /** * This event is fired when a user holds an element on the screen of the device. * @ko 사용자가 기기의 화면에 손을 대고 있을 때 발생하는 이벤트 * @name eg.Axes#hold * @event * @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Object.<string, number>} pos coordinate <ko>좌표 정보</ko> * @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko> * @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("hold", function(event) { * // event.pos * // event.input * // event.inputEvent * // isTrusted * }); */ var __proto = EventManager.prototype; __proto.triggerHold = function (pos, option) { this.axes.trigger("hold", { pos: pos, input: option.input || null, inputEvent: option.event || null, isTrusted: true }); }; /** * Specifies the coordinates to move after the 'change' event. It works when the holding value of the change event is true. * @ko 'change' 이벤트 이후 이동할 좌표를 지정한다. change이벤트의 holding 값이 true일 경우에 동작한다 * @name set * @function * @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("change", function(event) { * event.holding && event.set({x: 10}); * }); */ /** Specifies the animation coordinates to move after the 'release' or 'animationStart' events. * @ko 'release' 또는 'animationStart' 이벤트 이후 이동할 좌표를 지정한다. * @name setTo * @function * @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko> * @param {Number} [duration] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("animationStart", function(event) { * event.setTo({x: 10}, 2000); * }); */ /** * This event is fired when a user release an element on the screen of the device. * @ko 사용자가 기기의 화면에서 손을 뗐을 때 발생하는 이벤트 * @name eg.Axes#release * @event * @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Object.<string, number>} depaPos The coordinates when releasing an element<ko>손을 뗐을 때의 좌표 </ko> * @property {Object.<string, number>} destPos The coordinates to move to after releasing an element<ko>손을 뗀 뒤에 이동할 좌표</ko> * @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko> * @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko> * @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko> * @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("release", function(event) { * // event.depaPos * // event.destPos * // event.delta * // event.input * // event.inputEvent * // event.setTo * // event.isTrusted * * // if you want to change the animation coordinates to move after the 'release' event. * event.setTo({x: 10}, 2000); * }); */ __proto.triggerRelease = function (param) { param.setTo = this.createUserControll(param.destPos, param.duration); this.axes.trigger("release", param); }; /** * This event is fired when coordinate changes. * @ko 좌표가 변경됐을 때 발생하는 이벤트 * @name eg.Axes#change * @event * @type {object} The object of data to be sent when the event is fired <ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Object.<string, number>} pos The coordinate <ko>좌표</ko> * @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko> * @property {Boolean} holding Indicates whether a user holds an element on the screen of the device.<ko>사용자가 기기의 화면을 누르고 있는지 여부</ko> * @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko> * @property {Object} inputEvent The event object received from inputType. If the value is changed by animation, it returns 'null'.<ko>inputType으로 부터 받은 이벤트 객체. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko> * @property {set} set Specifies the coordinates to move after the event. It works when the holding value is true <ko>이벤트 이후 이동할 좌표를 지정한다. holding 값이 true일 경우에 동작한다.</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("change", function(event) { * // event.pos * // event.delta * // event.input * // event.inputEvent * // event.holding * // event.set * // event.isTrusted * * // if you want to change the coordinates to move after the 'change' event. * // it works when the holding value of the change event is true. * event.holding && event.set({x: 10}); * }); */ __proto.triggerChange = function (pos, option, holding) { if (option === void 0) { option = null; } if (holding === void 0) { holding = false; } var eventInfo = this.am.getEventInfo(); var moveTo = this.am.axm.moveTo(pos); var inputEvent = option && option.event || eventInfo && eventInfo.event || null; var param = { pos: moveTo.pos, delta: moveTo.delta, holding: holding, inputEvent: inputEvent, isTrusted: !!inputEvent, input: option && option.input || eventInfo && eventInfo.input || null, set: inputEvent ? this.createUserControll(moveTo.pos) : function () {} }; this.axes.trigger("change", param); inputEvent && this.am.axm.set(param.set()["destPos"]); }; /** * This event is fired when animation starts. * @ko 에니메이션이 시작할 때 발생한다. * @name eg.Axes#animationStart * @event * @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Object.<string, number>} depaPos The coordinates when animation starts<ko>애니메이션이 시작 되었을 때의 좌표 </ko> * @property {Object.<string, number>} destPos The coordinates to move to. If you change this value, you can run the animation<ko>이동할 좌표. 이값을 변경하여 애니메이션을 동작시킬수 있다</ko> * @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko> * @property {Number} duration Duration of the animation (unit: ms). If you change this value, you can control the animation duration time.<ko>애니메이션 진행 시간(단위: ms). 이값을 변경하여 애니메이션의 이동시간을 조절할 수 있다.</ko> * @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko> * @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko> * @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("release", function(event) { * // event.depaPos * // event.destPos * // event.delta * // event.input * // event.inputEvent * // event.setTo * // event.isTrusted * * // if you want to change the animation coordinates to move after the 'animationStart' event. * event.setTo({x: 10}, 2000); * }); */ __proto.triggerAnimationStart = function (param) { param.setTo = this.createUserControll(param.destPos, param.duration); return this.axes.trigger("animationStart", param); }; /** * This event is fired when animation ends. * @ko 에니메이션이 끝났을 때 발생한다. * @name eg.Axes#animationEnd * @event * @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("animationEnd", function(event) { * // event.isTrusted * }); */ __proto.triggerAnimationEnd = function (isTrusted) { if (isTrusted === void 0) { isTrusted = false; } this.axes.trigger("animationEnd", { isTrusted: isTrusted }); }; /** * This event is fired when all actions have been completed. * @ko 에니메이션이 끝났을 때 발생한다. * @name eg.Axes#finish * @event * @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko> * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko> * * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "zoom": { * range: [50, 30] * } * }).on("finish", function(event) { * // event.isTrusted * }); */ __proto.triggerFinish = function (isTrusted) { if (isTrusted === void 0) { isTrusted = false; } this.axes.trigger("finish", { isTrusted: isTrusted }); }; __proto.createUserControll = function (pos, duration) { if (duration === void 0) { duration = 0; } // to controll var userControl = { destPos: __assign({}, pos), duration: duration }; return function (toPos, userDuration) { toPos && (userControl.destPos = __assign({}, toPos)); userDuration !== undefined && (userControl.duration = userDuration); return userControl; }; }; __proto.setAnimationManager = function (am) { this.am = am; }; __proto.destroy = function () { this.axes.off(); }; return EventManager; }(); var InterruptManager = /*#__PURE__*/ function () { function InterruptManager(options) { this.options = options; this._prevented = false; // check whether the animation event was prevented } var __proto = InterruptManager.prototype; __proto.isInterrupting = function () { // when interruptable is 'true', return value is always 'true'. return this.options.interruptable || this._prevented; }; __proto.isInterrupted = function () { return !this.options.interruptable && this._prevented; }; __proto.setInterrupt = function (prevented) { !this.options.interruptable && (this._prevented = prevented); }; return InterruptManager; }(); var InputObserver = /*#__PURE__*/ function () { function InputObserver(_a) { var options = _a.options, itm = _a.itm, em = _a.em, axm = _a.axm, am = _a.am; this.isOutside = false; this.moveDistance = null; this.options = options; this.itm = itm; this.em = em; this.axm = axm; this.am = am; } // when move pointer is held in outside var __proto = InputObserver.prototype; __proto.atOutside = function (pos) { var _this = this; if (this.isOutside) { return this.axm.map(pos, function (v, k, opt) { var tn = opt.range[0] - opt.bounce[0]; var tx = opt.range[1] + opt.bounce[1]; return v > tx ? tx : v < tn ? tn : v; }); } else { // when start pointer is held in inside // get a initialization slope value to prevent smooth animation. var initSlope_1 = this.am.easing(0.00001) / 0.00001; return this.axm.map(pos, function (v, k, opt) { var min = opt.range[0]; var max = opt.range[1]; var out = opt.bounce; if (v < min) { // left return min - _this.am.easing((min - v) / (out[0] * initSlope_1)) * out[0]; } else if (v > max) { // right return max + _this.am.easing((v - max) / (out[1] * initSlope_1)) * out[1]; } return v; }); } }; __proto.get = function (input) { return this.axm.get(input.axes); }; __proto.hold = function (input, event) { if (this.itm.isInterrupted() || !input.axes.length) { return; } var changeOption = { input: input, event: event }; this.itm.setInterrupt(true); this.am.grab(input.axes, changeOption); !this.moveDistance && this.em.triggerHold(this.axm.get(), changeOption); this.isOutside = this.axm.isOutside(input.axes); this.moveDistance = this.axm.get(input.axes); }; __proto.change = function (input, event, offset) { if (!this.itm.isInterrupting() || this.axm.every(offset, function (v) { return v === 0; })) { return; } var depaPos = this.axm.get(input.axes); var destPos; // for outside logic destPos = this.axm.map(this.moveDistance || depaPos, function (v, k) { return v + (offset[k] || 0); }); this.moveDistance && (this.moveDistance = destPos); destPos = this.axm.map(destPos, function (v, k, opt) { return getCirculatedPos(v, opt.range, opt.circular); }); // from outside to inside if (this.isOutside && this.axm.every(depaPos, function (v, k, opt) { return !isOutside(v, opt.range); })) { this.isOutside = false; } destPos = this.atOutside(destPos); this.em.triggerChange(destPos, { input: input, event: event }, true); }; __proto.release = function (input, event, offset, inputDuration) { if (!this.itm.isInterrupting()) { return; } if (!this.moveDistance) { return; } var pos = this.axm.get(input.axes); var depaPos = this.axm.get(); var destPos = this.axm.get(this.axm.map(offset, function (v, k, opt) { if (opt.circular && (opt.circular[0] || opt.circular[1])) { return pos[k] + v; } else { return getInsidePosition(pos[k] + v, opt.range, opt.circular, opt.bounce); } })); var duration = this.am.getDuration(destPos, pos, inputDuration); if (duration === 0) { destPos = __assign({}, depaPos); } // prepare params var param = { depaPos: depaPos, destPos: destPos, duration: duration, delta: this.axm.getDelta(depaPos, destPos), inputEvent: event, input: input, isTrusted: true }; this.em.triggerRelease(param); this.moveDistance = null; // to contol var userWish = this.am.getUserControll(param); var isEqual = equal(userWish.destPos, depaPos); var changeOption = { input: input, event: event }; if (isEqual || userWish.duration === 0) { !isEqual && this.em.triggerChange(userWish.destPos, changeOption, true); this.itm.setInterrupt(false); if (this.axm.isOutside()) { this.am.restore(changeOption); } else { this.em.triggerFinish(true); } } else { this.am.animateTo(userWish.destPos, userWish.duration, changeOption); } }; return InputObserver; }(); // export const DIRECTION_NONE = 1; var TRANSFORM = function () { if (typeof document === "undefined") { return ""; } var bodyStyle = (document.head || document.getElementsByTagName("head")[0]).style; var target = ["transform", "webkitTransform", "msTransform", "mozTransform"]; for (var i = 0, len = target.length; i < len; i++) { if (target[i] in bodyStyle) { return target[i]; } } return ""; }(); /** * @typedef {Object} AxisOption The Axis information. The key of the axis specifies the name to use as the logical virtual coordinate system. * @ko 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다. * @property {Number[]} [range] The coordinate of range <ko>좌표 범위</ko> * @property {Number} [range.0=0] The coordinate of the minimum <ko>최소 좌표</ko> * @property {Number} [range.1=0] The coordinate of the maximum <ko>최대 좌표</ko> * @property {Number[]} [bounce] The size of bouncing area. The coordinates can exceed the coordinate area as much as the bouncing area based on user action. If the coordinates does not exceed the bouncing area when an element is dragged, the coordinates where bouncing effects are applied are retuned back into the coordinate area<ko>바운스 영역의 크기. 사용자의 동작에 따라 좌표가 좌표 영역을 넘어 바운스 영역의 크기만큼 더 이동할 수 있다. 사용자가 끌어다 놓는 동작을 했을 때 좌표가 바운스 영역에 있으면, 바운스 효과가 적용된 좌표가 다시 좌표 영역 안으로 들어온다</ko> * @property {Number} [bounce.0=0] The size of coordinate of the minimum area <ko>최소 좌표 바운스 영역의 크기</ko> * @property {Number} [bounce.1=0] The size of coordinate of the maximum area <ko>최대 좌표 바운스 영역의 크기</ko> * @property {Boolean[]} [circular] Indicates whether a circular element is available. If it is set to "true" and an element is dragged outside the coordinate area, the element will appear on the other side.<ko>순환 여부. 'true'로 설정한 방향의 좌표 영역 밖으로 엘리먼트가 이동하면 반대 방향에서 엘리먼트가 나타난다</ko> * @property {Boolean} [circular.0=false] Indicates whether to circulate to the coordinate of the minimum <ko>최소 좌표 방향의 순환 여부</ko> * @property {Boolean} [circular.1=false] Indicates whether to circulate to the coordinate of the maximum <ko>최대 좌표 방향의 순환 여부</ko> **/ /** * @typedef {Object} AxesOption The option object of the eg.Axes module * @ko eg.Axes 모듈의 옵션 객체 * @property {Function} [easing=easing.easeOutCubic] The easing function to apply to an animation <ko>애니메이션에 적용할 easing 함수</ko> * @property {Number} [maximumDuration=Infinity] Maximum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최대 좌표 이동 시간</ko> * @property {Number} [minimumDuration=0] Minimum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최소 좌표 이동 시간</ko> * @property {Number} [deceleration=0.0006] Deceleration of the animation where acceleration is manually enabled by user. A higher value indicates shorter running time. <ko>사용자의 동작으로 가속도가 적용된 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다</ko> * @property {Boolean} [interruptable=true] Indicates whether an animation is interruptible.<br>- true: It can be paused or stopped by user action or the API.<br>- false: It cannot be paused or stopped by user action or the API while it is running.<ko>진행 중인 애니메이션 중지 가능 여부.<br>- true: 사용자의 동작이나 API로 애니메이션을 중지할 수 있다.<br>- false: 애니메이션이 진행 중일 때는 사용자의 동작이나 API가 적용되지 않는다</ko> **/ /** * @class eg.Axes * @classdesc A module used to change the information of user action entered by various input devices such as touch screen or mouse into the logical virtual coordinates. You can easily create a UI that responds to user actions. * @ko 터치 입력 장치나 마우스와 같은 다양한 입력 장치를 통해 전달 받은 사용자의 동작을 논리적인 가상 좌표로 변경하는 모듈이다. 사용자 동작에 반응하는 UI를 손쉽게 만들수 있다. * @extends eg.Component * * @param {Object.<string, AxisOption>} axis Axis information managed by eg.Axes. The key of the axis specifies the name to use as the logical virtual coordinate system. <ko>eg.Axes가 관리하는 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.</ko> * @param {AxesOption} [options] The option object of the eg.Axes module<ko>eg.Axes 모듈의 옵션 객체</ko> * @param {Object.<string, number>} [startPos] The coordinates to be moved when creating an instance. not triggering change event.<ko>인스턴스 생성시 이동할 좌표, change 이벤트는 발생하지 않음.</ko> * * @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.3+ (except 3.x)"} * @example * * // 1. Initialize eg.Axes * const axes = new eg.Axes({ * something1: { * range: [0, 150], * bounce: 50 * }, * something2: { * range: [0, 200], * bounce: 100 * }, * somethingN: { * range: [1, 10], * } * }, { * deceleration : 0.0024 * }); * * // 2. attach event handler * axes.on({ * "hold" : function(evt) { * }, * "release" : function(evt) { * }, * "animationStart" : function(evt) { * }, * "animationEnd" : function(evt) { * }, * "change" : function(evt) { * } * }); * * // 3. Initialize inputTypes * const panInputArea = new eg.Axes.PanInput("#area", { * scale: [0.5, 1] * }); * const panInputHmove = new eg.Axes.PanInput("#hmove"); * const panInputVmove = new eg.Axes.PanInput("#vmove"); * const pinchInputArea = new eg.Axes.PinchInput("#area", { * scale: 1.5 * }); * * // 4. Connect eg.Axes and InputTypes * // [PanInput] When the mouse or touchscreen is down and moved. * // Connect the 'something2' axis to the mouse or touchscreen x position and * // connect the 'somethingN' axis to the mouse or touchscreen y position. * axes.connect(["something2", "somethingN"], panInputArea); // or axes.connect("something2 somethingN", panInputArea); * * // Connect only one 'something1' axis to the mouse or touchscreen x position. * axes.connect(["something1"], panInputHmove); // or axes.connect("something1", panInputHmove); * * // Connect only one 'something2' axis to the mouse or touchscreen y position. * axes.connect(["", "something2"], panInputVmove); // or axes.connect(" something2", panInputVmove); * * // [PinchInput] Connect 'something2' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out). * axes.connect("something2", pinchInputArea); */ var Axes = /*#__PURE__*/ function (_super) { __extends(Axes, _super); function Axes(axis, options, startPos) { if (axis === void 0) { axis = {}; } var _this = _super.call(this) || this; _this.axis = axis; _this._inputs = []; _this.options = __assign({ easing: function easeOutCubic(x) { return 1 - Math.pow(1 - x, 3); }, interruptable: true, maximumDuration: Infinity, minimumDuration: 0, deceleration: 0.0006 }, options); _this.itm = new InterruptManager(_this.options); _this.axm = new AxisManager(_this.axis, _this.options); _this.em = new EventManager(_this); _this.am = new AnimationManager(_this); _this.io = new InputObserver(_this); _this.em.setAnimationManager(_this.am); startPos && _this.em.triggerChange(startPos); return _this; } /** * Connect the axis of eg.Axes to the inputType. * @ko eg.Axes의 축과 inputType을 연결한다 * @method eg.Axes#connect * @param {(String[]|String)} axes The name of the axis to associate with inputType <ko>inputType과 연결할 축의 이름</ko> * @param {Object} inputType The inputType instance to associate with the axis of eg.Axes <ko>eg.Axes의 축과 연결할 inputType 인스턴스<ko> * @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * } * }); * * axes.connect("x", new eg.Axes.PanInput("#area1")) * .connect("x xOther", new eg.Axes.PanInput("#area2")) * .connect(" xOther", new eg.Axes.PanInput("#area3")) * .connect(["x"], new eg.Axes.PanInput("#area4")) * .connect(["xOther", "x"], new eg.Axes.PanInput("#area5")) * .connect(["", "xOther"], new eg.Axes.PanInput("#area6")); */ var __proto = Axes.prototype; __proto.connect = function (axes, inputType) { var mapped; if (typeof axes === "string") { mapped = axes.split(" "); } else { mapped = axes.concat(); } // check same instance if (~this._inputs.indexOf(inputType)) { this.disconnect(inputType); } // check same element in hammer type for share if ("hammer" in inputType) { var targets = this._inputs.filter(function (v) { return v.hammer && v.element === inputType.element; }); if (targets.length) { inputType.hammer = targets[0].hammer; } } inputType.mapAxes(mapped); inputType.connect(this.io); this._inputs.push(inputType); return this; }; /** * Disconnect the axis of eg.Axes from the inputType. * @ko eg.Axes의 축과 inputType의 연결을 끊는다. * @method eg.Axes#disconnect * @param {Object} [inputType] An inputType instance associated with the axis of eg.Axes <ko>eg.Axes의 축과 연결한 inputType 인스턴스<ko> * @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * } * }); * * const input1 = new eg.Axes.PanInput("#area1"); * const input2 = new eg.Axes.PanInput("#area2"); * const input3 = new eg.Axes.PanInput("#area3"); * * axes.connect("x", input1); * .connect("x xOther", input2) * .connect(["xOther", "x"], input3); * * axes.disconnect(input1); // disconnects input1 * axes.disconnect(); // disconnects all of them */ __proto.disconnect = function (inputType) { if (inputType) { var index = this._inputs.indexOf(inputType); if (index >= 0) { this._inputs[index].disconnect(); this._inputs.splice(index, 1); } } else { this._inputs.forEach(function (v) { return v.disconnect(); }); this._inputs = []; } return this; }; /** * Returns the current position of the coordinates. * @ko 좌표의 현재 위치를 반환한다 * @method eg.Axes#get * @param {Object} [axes] The names of the axis <ko>축 이름들</ko> * @return {Object.<string, number>} Axis coordinate information <ko>축 좌표 정보</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * }, * "zoom": { * range: [50, 30] * } * }); * * axes.get(); // {"x": 0, "xOther": -100, "zoom": 50} * axes.get(["x", "zoom"]); // {"x": 0, "zoom": 50} */ __proto.get = function (axes) { return this.axm.get(axes); }; /** * Moves an axis to specific coordinates. * @ko 좌표를 이동한다. * @method eg.Axes#setTo * @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko> * @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko> * @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * }, * "zoom": { * range: [50, 30] * } * }); * * axes.setTo({"x": 30, "zoom": 60}); * axes.get(); // {"x": 30, "xOther": -100, "zoom": 60} * * axes.setTo({"x": 100, "xOther": 60}, 1000); // animatation * * // after 1000 ms * axes.get(); // {"x": 100, "xOther": 60, "zoom": 60} */ __proto.setTo = function (pos, duration) { if (duration === void 0) { duration = 0; } this.am.setTo(pos, duration); return this; }; /** * Moves an axis from the current coordinates to specific coordinates. * @ko 현재 좌표를 기준으로 좌표를 이동한다. * @method eg.Axes#setBy * @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko> * @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko> * @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * }, * "zoom": { * range: [50, 30] * } * }); * * axes.setBy({"x": 30, "zoom": 10}); * axes.get(); // {"x": 30, "xOther": -100, "zoom": 60} * * axes.setBy({"x": 70, "xOther": 60}, 1000); // animatation * * // after 1000 ms * axes.get(); // {"x": 100, "xOther": -40, "zoom": 60} */ __proto.setBy = function (pos, duration) { if (duration === void 0) { duration = 0; } this.am.setBy(pos, duration); return this; }; /** * Returns whether there is a coordinate in the bounce area of ​​the target axis. * @ko 대상 축 중 bounce영역에 좌표가 존재하는지를 반환한다 * @method eg.Axes#isBounceArea * @param {Object} [axes] The names of the axis <ko>축 이름들</ko> * @return {Boolen} Whether the bounce area exists. <ko>bounce 영역 존재 여부</ko> * @example * const axes = new eg.Axes({ * "x": { * range: [0, 100] * }, * "xOther": { * range: [-100, 100] * }, * "zoom": { * range: [50, 30] * } * }); * * axes.isBounceArea(["x"]); * axes.isBounceArea(["x", "zoom"]); * axes.isBounceArea(); */ __proto.isBounceArea = function (axes) { return this.axm.isOutside(axes); }; /** * Destroys properties, and events used in a module and disconnect all connections to inputTypes. * @ko 모듈에 사용한 속성, 이벤트를 해제한다. 모든 inputType과의 연결을 끊는다. * @method eg.Axes#destroy */ __proto.destroy = function () { this.disconnect(); this.em.destroy(); }; /** * Version info string * @ko 버전정보 문자열 * @name VERSION * @static * @type {String} * @example * eg.Axes.VERSION; // ex) 3.3.3 * @memberof eg.Axes */ Axes.VERSION = "2.5.8"; /** * @name eg.Axes.TRANSFORM * @desc Returns the transform attribute with CSS vendor prefixes. * @ko CSS vendor prefixes를 붙인 transform 속성을 반환한다. * * @constant * @type {String} * @example * eg.Axes.TRANSFORM; // "transform" or "webkitTransform" */ Axes.TRANSFORM = TRANSFORM; /** * @name eg.Axes.DIRECTION_NONE * @constant * @type {Number} */ Axes.DIRECTION_NONE = hammerjs.DIRECTION_NONE; /** * @name eg.Axes.DIRECTION_LEFT * @constant * @type {Number} */ Axes.DIRECTION_LEFT = hammerjs.DIRECTION_LEFT; /** * @name eg.Axes.DIRECTION_RIGHT * @constant * @type {Number} */ Axes.DIRECTION_RIGHT = hammerjs.DIRECTION_RIGHT; /** * @name eg.Axes.DIRECTION_UP * @constant * @type {Number} */ Axes.DIRECTION_UP = hammerjs.DIRECTION_UP; /** * @name eg.Axes.DIRECTION_DOWN * @constant * @type {Number} */ Axes.DIRECTION_DOWN = hammerjs.DIRECTION_DOWN; /** * @name eg.Axes.DIRECTION_HORIZONTAL * @constant * @type {Number} */ Axes.DIRECTION_HORIZONTAL = hammerjs.DIRECTION_HORIZONTAL; /** * @name eg.Axes.DIRECTION_VERTICAL * @constant * @type {Number} */ Axes.DIRECTION_VERTICAL = hammerjs.DIRECTION_VERTICAL; /** * @name eg.Axes.DIRECTION_ALL * @constant * @type {Number} */ Axes.DIRECTION_ALL = hammerjs.DIRECTION_ALL; return Axes; }(Component); var SUPPORT_POINTER_EVENTS = "PointerEvent" in win || "MSPointerEvent" in win; var SUPPORT_TOUCH = "ontouchstart" in win; var UNIQUEKEY = "_EGJS_AXES_INPUTTYPE_"; function toAxis(source, offset) { return offset.reduce(function (acc, v, i) { if (source[i]) { acc[source[i]] = v; } return acc; }, {}); } function createHammer(element, options) { try { // create Hammer return new hammerjs.Manager(element, __assign({}, options)); } catch (e) { return null; } } function convertInputType(inputType) { if (inputType === void 0) { inputType = []; } var hasTouch = false; var hasMouse = false; var hasPointer = false; inputType.forEach(function (v) { switch (v) { case "mouse": hasMouse = true; break; case "touch": hasTouch = SUPPORT_TOUCH; break; case "pointer": hasPointer = SUPPORT_POINTER_EVENTS; // no default } }); if (hasPointer) { return hammerjs.PointerEventInput; } else if (hasTouch && hasMouse) { return hammerjs.TouchMouseInput; } else if (hasTouch) { return hammerjs.TouchInput; } else if (hasMouse) { return hammerjs.MouseInput; } return null; } function getDirectionByAngle(angle, thresholdAngle) { if (thresholdAngle < 0 || thresholdAngle > 90) { return hammerjs.DIRECTION_NONE; } var toAngle = Math.abs(angle); return toAngle > thresholdAngle && toAngle < 180 - thresholdAngle ? hammerjs.DIRECTION_VERTICAL : hammerjs.DIRECTION_HORIZONTAL; } function getNextOffset(speeds, deceleration) { var normalSpeed = Math.sqrt(speeds[0] * speeds[0] + speeds[1] * speeds[1]); var duration = Math.abs(normalSpeed / -deceleration); return [speeds[0] / 2 * duration, speeds[1] / 2 * duration]; } function useDirection(checkType, direction, userDirection) { if (userDirection) { return !!(direction === hammerjs.DIRECTION_ALL || direction & checkType && userDirection & checkType); } else { return !!(direction & checkType); } } /** * @typedef {Object} PanInputOption The option object of the eg.Axes.PanInput module. * @ko eg.Axes.PanInput 모듈의 옵션 객체 * @property {String[]} [inputType=["touch","mouse", "pointer"]] Types of input devices.<br>- touch: Touch screen<br>- mouse: Mouse <ko>입력 장치 종류.<br>- touch: 터치 입력 장치<br>- mouse: 마우스</ko> * @property {Number[]} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko> * @property {Number} [scale.0=1] horizontal axis scale <ko>수평축 배율</ko> * @property {Number} [scale.1=1] vertical axis scale <ko>수직축 배율</ko> * @property {Number} [thresholdAngle=45] The threshold value that determines whether user action is horizontal or vertical (0~90) <ko>사용자의 동작이 가로 방향인지 세로 방향인지 판단하는 기준 각도(0~90)</ko> * @property {Number} [threshold=0] Minimal pan distance required before recognizing <ko>사용자의 Pan 동작을 인식하기 위해산 최소한의 거리</ko> * @property {Object} [hammerManagerOptions={cssProps: {userSelect: "none",touchSelect: "none",touchCallout: "none",userDrag: "none"}] Options of Hammer.Manager <ko>Hammer.Manager의 옵션</ko> **/ /** * @class eg.Axes.PanInput * @classdesc A module that passes the amount of change to eg.Axes when the mouse or touchscreen is down and moved. use less than two axes. * @ko 마우스나 터치 스크린을 누르고 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 두개 이하의 축을 사용한다. * * @example * const pan = new eg.Axes.PanInput("#area", { * inputType: ["touch"], * scale: [1, 1.3], * }); * * // Connect the 'something2' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved. * // Connect the 'somethingN' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved. * axes.connect(["something2", "somethingN"], pan); // or axes.connect("something2 somethingN", pan); * * // Connect only one 'something1' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved. * axes.connect(["something1"], pan); // or axes.connect("something1", pan); * * // Connect only one 'something2' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved. * axes.connect(["", "something2"], pan); // or axes.connect(" something2", pan); * * @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.PanInput module <ko>eg.Axes.PanInput 모듈을 사용할 엘리먼트</ko> * @param {PanInputOption} [options] The option object of the eg.Axes.PanInput module<ko>eg.Axes.PanInput 모듈의 옵션 객체</ko> */ var PanInput = /*#__PURE__*/ function () { function PanInput(el, options) { this.axes = []; this.hammer = null; this.element = null; this.panRecognizer = null; /** * Hammer helps you add support for touch gestures to your page * * @external Hammer * @see {@link http://hammerjs.github.io|Hammer.JS} * @see {@link http://hammerjs.github.io/jsdoc/Hammer.html|Hammer.JS API documents} * @see Hammer.JS applies specific CSS properties by {@link http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html|default} when creating an instance. The eg.Axes module removes all default CSS properties provided by Hammer.JS */ if (typeof hammerjs.Manager === "undefined") { throw new Error("The Hammerjs must be loaded before eg.Axes.PanInput.\nhttp://hammerjs.github.io/"); } this.element = $(el); this.options = __assign({ inputType: ["touch", "mouse", "pointer"], scale: [1, 1], thresholdAngle: 45, threshold: 0, hammerManagerOptions: { // css properties were removed due to usablility issue // http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html cssProps: { userSelect: "none", touchSelect: "none", touchCallout: "none", userDrag: "none" } } }, options); this.onHammerInput = this.onHammerInput.bind(this); this.onPanmove = this.onPanmove.bind(this); this.onPanend = this.onPanend.bind(this); } var __proto = PanInput.prototype; __proto.mapAxes = function (axes) { var useHorizontal = !!axes[0]; var useVertical = !!axes[1]; if (useHorizontal && useVertical) { this._direction = hammerjs.DIRECTION_ALL; } else if (useHorizontal) { this._direction = hammerjs.DIRECTION_HORIZONTAL; } else if (useVertical) { this._direction = hammerjs.DIRECTION_VERTICAL; } else { this._direction = hammerjs.DIRECTION_NONE; } this.axes = axes; }; __proto.connect = function (observer) { var hammerOption = { direction: this._direction, threshold: this.options.threshold }; if (this.hammer) { // for sharing hammer instance. // hammer remove previous PanRecognizer. this.removeRecognizer(); this.dettachEvent(); } else { var keyValue = this.element[UNIQUEKEY]; if (!keyValue) { keyValue = String(Math.round(Math.random() * new Date().getTime())); } var inputClass = convertInputType(this.options.inputType); if (!inputClass) { throw new Error("Wrong inputType parameter!"); } this.hammer = createHammer(this.element, __assign({ inputClass: inputClass }, this.options.hammerManagerOptions)); this.element[UNIQUEKEY] = keyValue; } this.panRecognizer = new hammerjs.Pan(hammerOption); this.hammer.add(this.panRecognizer); this.attachEvent(observer); return this; }; __proto.disconnect = function () { this.removeRecognizer(); if (this.hammer) { this.dettachEvent(); } this._direction = hammerjs.DIRECTION_NONE; return this; }; /** * Destroys elements, properties, and events used in a module. * @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다. * @method eg.Axes.PanInput#destroy */ __proto.destroy = function () { this.disconnect(); if (this.hammer && this.hammer.recognizers.length === 0) { this.hammer.destroy(); } delete this.element[UNIQUEKEY]; this.element = null; this.hammer = null; }; /** * Enables input devices * @ko 입력 장치를 사용할 수 있게 한다 * @method eg.Axes.PanInput#enable * @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.enable = function () { this.hammer && (this.hammer.get("pan").options.enable = true); return this; }; /** * Disables input devices * @ko 입력 장치를 사용할 수 없게 한다. * @method eg.Axes.PanInput#disable * @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.disable = function () { this.hammer && (this.hammer.get("pan").options.enable = false); return this; }; /** * Returns whether to use an input device * @ko 입력 장치를 사용 여부를 반환한다. * @method eg.Axes.PanInput#isEnable * @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko> */ __proto.isEnable = function () { return !!(this.hammer && this.hammer.get("pan").options.enable); }; __proto.removeRecognizer = function () { if (this.hammer && this.panRecognizer) { this.hammer.remove(this.panRecognizer); this.panRecognizer = null; } }; __proto.onHammerInput = function (event) { if (this.isEnable()) { if (event.isFirst) { this.observer.hold(this, event); } else if (event.isFinal) { this.onPanend(event); } } }; __proto.onPanmove = function (event) { var userDirection = getDirectionByAngle(event.angle, this.options.thresholdAngle); // not support offset properties in Hammerjs - start var prevInput = this.hammer.session.prevInput; /* eslint-disable no-param-reassign */ if (prevInput) { event.offsetX = event.deltaX - prevInput.deltaX; event.offsetY = event.deltaY - prevInput.deltaY; } else { event.offsetX = 0; event.offsetY = 0; } var offset = this.getOffset([event.offsetX, event.offsetY], [useDirection(hammerjs.DIRECTION_HORIZONTAL, this._direction, userDirection), useDirection(hammerjs.DIRECTION_VERTICAL, this._direction, userDirection)]); var prevent = offset.some(function (v) { return v !== 0; }); if (prevent) { event.srcEvent.preventDefault(); event.srcEvent.stopPropagation(); } event.preventSystemEvent = prevent; prevent && this.observer.change(this, event, toAxis(this.axes, offset)); }; __proto.onPanend = function (event) { var offset = this.getOffset([Math.abs(event.velocityX) * (event.deltaX < 0 ? -1 : 1), Math.abs(event.velocityY) * (event.deltaY < 0 ? -1 : 1)], [useDirection(hammerjs.DIRECTION_HORIZONTAL, this._direction), useDirection(hammerjs.DIRECTION_VERTICAL, this._direction)]); offset = getNextOffset(offset, this.observer.options.deceleration); this.observer.release(this, event, toAxis(this.axes, offset)); }; __proto.attachEvent = function (observer) { this.observer = observer; this.hammer.on("hammer.input", this.onHammerInput).on("panstart panmove", this.onPanmove); }; __proto.dettachEvent = function () { this.hammer.off("hammer.input", this.onHammerInput).off("panstart panmove", this.onPanmove); this.observer = null; }; __proto.getOffset = function (properties, direction) { var offset = [0, 0]; var scale = this.options.scale; if (direction[0]) { offset[0] = properties[0] * scale[0]; } if (direction[1]) { offset[1] = properties[1] * scale[1]; } return offset; }; return PanInput; }(); /** * @typedef {Object} PinchInputOption The option object of the eg.Axes.PinchInput module * @ko eg.Axes.PinchInput 모듈의 옵션 객체 * @property {Number} [scale=1] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko> * @property {Number} [threshold=0] Minimal scale before recognizing <ko>사용자의 Pinch 동작을 인식하기 위해산 최소한의 배율</ko> * @property {Object} [hammerManagerOptions={cssProps: {userSelect: "none",touchSelect: "none",touchCallout: "none",userDrag: "none"}] Options of Hammer.Manager <ko>Hammer.Manager의 옵션</ko> **/ /** * @class eg.Axes.PinchInput * @classdesc A module that passes the amount of change to eg.Axes when two pointers are moving toward (zoom-in) or away from each other (zoom-out). use one axis. * @ko 2개의 pointer를 이용하여 zoom-in하거나 zoom-out 하는 동작의 변화량을 eg.Axes에 전달하는 모듈. 한 개 의 축을 사용한다. * @example * const pinch = new eg.Axes.PinchInput("#area", { * scale: 1 * }); * * // Connect 'something' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out). * axes.connect("something", pinch); * * @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.PinchInput module <ko>eg.Axes.PinchInput 모듈을 사용할 엘리먼트</ko> * @param {PinchInputOption} [options] The option object of the eg.Axes.PinchInput module<ko>eg.Axes.PinchInput 모듈의 옵션 객체</ko> */ var PinchInput = /*#__PURE__*/ function () { function PinchInput(el, options) { this.axes = []; this.hammer = null; this.element = null; this._base = null; this._prev = null; this.pinchRecognizer = null; /** * Hammer helps you add support for touch gestures to your page * * @external Hammer * @see {@link http://hammerjs.github.io|Hammer.JS} * @see {@link http://hammerjs.github.io/jsdoc/Hammer.html|Hammer.JS API documents} * @see Hammer.JS applies specific CSS properties by {@link http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html|default} when creating an instance. The eg.Axes module removes all default CSS properties provided by Hammer.JS */ if (typeof hammerjs.Manager === "undefined") { throw new Error("The Hammerjs must be loaded before eg.Axes.PinchInput.\nhttp://hammerjs.github.io/"); } this.element = $(el); this.options = __assign({ scale: 1, threshold: 0, inputType: ["touch", "pointer"], hammerManagerOptions: { // css properties were removed due to usablility issue // http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html cssProps: { userSelect: "none", touchSelect: "none", touchCallout: "none", userDrag: "none" } } }, options); this.onPinchStart = this.onPinchStart.bind(this); this.onPinchMove = this.onPinchMove.bind(this); this.onPinchEnd = this.onPinchEnd.bind(this); } var __proto = PinchInput.prototype; __proto.mapAxes = function (axes) { this.axes = axes; }; __proto.connect = function (observer) { var hammerOption = { threshold: this.options.threshold }; if (this.hammer) { // for sharing hammer instance. // hammer remove previous PinchRecognizer. this.removeRecognizer(); this.dettachEvent(); } else { var keyValue = this.element[UNIQUEKEY]; if (!keyValue) { keyValue = String(Math.round(Math.random() * new Date().getTime())); } var inputClass = convertInputType(this.options.inputType); if (!inputClass) { throw new Error("Wrong inputType parameter!"); } this.hammer = createHammer(this.element, __assign({ inputClass: inputClass }, this.options.hammerManagerOptions)); this.element[UNIQUEKEY] = keyValue; } this.pinchRecognizer = new hammerjs.Pinch(hammerOption); this.hammer.add(this.pinchRecognizer); this.attachEvent(observer); return this; }; __proto.disconnect = function () { this.removeRecognizer(); if (this.hammer) { this.hammer.remove(this.pinchRecognizer); this.pinchRecognizer = null; this.dettachEvent(); } return this; }; /** * Destroys elements, properties, and events used in a module. * @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다. * @method eg.Axes.PinchInput#destroy */ __proto.destroy = function () { this.disconnect(); if (this.hammer && this.hammer.recognizers.length === 0) { this.hammer.destroy(); } delete this.element[UNIQUEKEY]; this.element = null; this.hammer = null; }; __proto.removeRecognizer = function () { if (this.hammer && this.pinchRecognizer) { this.hammer.remove(this.pinchRecognizer); this.pinchRecognizer = null; } }; __proto.onPinchStart = function (event) { this._base = this.observer.get(this)[this.axes[0]]; var offset = this.getOffset(event.scale); this.observer.hold(this, event); this.observer.change(this, event, toAxis(this.axes, [offset])); this._prev = event.scale; }; __proto.onPinchMove = function (event) { var offset = this.getOffset(event.scale, this._prev); this.observer.change(this, event, toAxis(this.axes, [offset])); this._prev = event.scale; }; __proto.onPinchEnd = function (event) { var offset = this.getOffset(event.scale, this._prev); this.observer.change(this, event, toAxis(this.axes, [offset])); this.observer.release(this, event, toAxis(this.axes, [0]), 0); this._base = null; this._prev = null; }; __proto.getOffset = function (pinchScale, prev) { if (prev === void 0) { prev = 1; } return this._base * (pinchScale - prev) * this.options.scale; }; __proto.attachEvent = function (observer) { this.observer = observer; this.hammer.on("pinchstart", this.onPinchStart).on("pinchmove", this.onPinchMove).on("pinchend", this.onPinchEnd); }; __proto.dettachEvent = function () { this.hammer.off("pinchstart", this.onPinchStart).off("pinchmove", this.onPinchMove).off("pinchend", this.onPinchEnd); this.observer = null; this._prev = null; }; /** * Enables input devices * @ko 입력 장치를 사용할 수 있게 한다 * @method eg.Axes.PinchInput#enable * @return {eg.Axes.PinchInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.enable = function () { this.hammer && (this.hammer.get("pinch").options.enable = true); return this; }; /** * Disables input devices * @ko 입력 장치를 사용할 수 없게 한다. * @method eg.Axes.PinchInput#disable * @return {eg.Axes.PinchInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.disable = function () { this.hammer && (this.hammer.get("pinch").options.enable = false); return this; }; /** * Returns whether to use an input device * @ko 입력 장치를 사용 여부를 반환한다. * @method eg.Axes.PinchInput#isEnable * @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko> */ __proto.isEnable = function () { return !!(this.hammer && this.hammer.get("pinch").options.enable); }; return PinchInput; }(); /** * @typedef {Object} WheelInputOption The option object of the eg.Axes.WheelInput module * @ko eg.Axes.WheelInput 모듈의 옵션 객체 * @property {Number} [scale=1] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko> **/ /** * @class eg.Axes.WheelInput * @classdesc A module that passes the amount of change to eg.Axes when the mouse wheel is moved. use one axis. * @ko 마우스 휠이 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 한 개 의 축을 사용한다. * * @example * const wheel = new eg.Axes.WheelInput("#area", { * scale: 1 * }); * * // Connect 'something' axis when the mousewheel is moved. * axes.connect("something", wheel); * * @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.WheelInput module <ko>eg.Axes.WheelInput 모듈을 사용할 엘리먼트</ko> * @param {WheelInputOption} [options] The option object of the eg.Axes.WheelInput module<ko>eg.Axes.WheelInput 모듈의 옵션 객체</ko> */ var WheelInput = /*#__PURE__*/ function () { function WheelInput(el, options) { this.axes = []; this.element = null; this._isEnabled = false; this._isHolded = false; this._timer = null; this.element = $(el); this.options = __assign({ scale: 1, useNormalized: true }, options); this.onWheel = this.onWheel.bind(this); } var __proto = WheelInput.prototype; __proto.mapAxes = function (axes) { this.axes = axes; }; __proto.connect = function (observer) { this.dettachEvent(); this.attachEvent(observer); return this; }; __proto.disconnect = function () { this.dettachEvent(); return this; }; /** * Destroys elements, properties, and events used in a module. * @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다. * @method eg.Axes.WheelInput#destroy */ __proto.destroy = function () { this.disconnect(); this.element = null; }; __proto.onWheel = function (event) { var _this = this; if (!this._isEnabled) { return; } event.preventDefault(); if (event.deltaY === 0) { return; } if (!this._isHolded) { this.observer.hold(this, event); this._isHolded = true; } var offset = (event.deltaY > 0 ? -1 : 1) * this.options.scale * (this.options.useNormalized ? 1 : Math.abs(event.deltaY)); this.observer.change(this, event, toAxis(this.axes, [offset])); clearTimeout(this._timer); this._timer = setTimeout(function () { if (_this._isHolded) { _this._isHolded = false; _this.observer.release(_this, event, toAxis(_this.axes, [0])); } }, 50); }; __proto.attachEvent = function (observer) { this.observer = observer; this.element.addEventListener("wheel", this.onWheel); this._isEnabled = true; }; __proto.dettachEvent = function () { this.element.removeEventListener("wheel", this.onWheel); this._isEnabled = false; this.observer = null; if (this._timer) { clearTimeout(this._timer); this._timer = null; } }; /** * Enables input devices * @ko 입력 장치를 사용할 수 있게 한다 * @method eg.Axes.WheelInput#enable * @return {eg.Axes.WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.enable = function () { this._isEnabled = true; return this; }; /** * Disables input devices * @ko 입력 장치를 사용할 수 없게 한다. * @method eg.Axes.WheelInput#disable * @return {eg.Axes.WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.disable = function () { this._isEnabled = false; return this; }; /** * Returns whether to use an input device * @ko 입력 장치를 사용 여부를 반환한다. * @method eg.Axes.WheelInput#isEnable * @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko> */ __proto.isEnable = function () { return this._isEnabled; }; return WheelInput; }(); var KEY_LEFT_ARROW = 37; var KEY_A = 65; var KEY_UP_ARROW = 38; var KEY_W = 87; var KEY_RIGHT_ARROW = 39; var KEY_D = 68; var KEY_DOWN_ARROW = 40; var KEY_S = 83; var DIRECTION_REVERSE = -1; var DIRECTION_FORWARD = 1; var DIRECTION_HORIZONTAL = -1; var DIRECTION_VERTICAL = 1; var DELAY = 80; /** * @typedef {Object} MoveKeyInputOption The option object of the eg.Axes.MoveKeyInput module * @ko eg.Axes.MoveKeyInput 모듈의 옵션 객체 * @property {Array<Number>} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko> * @property {Number} [scale[0]=1] Coordinate scale for the first axis<ko>첫번째 축의 배율</ko> * @property {Number} [scale[1]=1] Coordinate scale for the decond axis<ko>두번째 축의 배율</ko> **/ /** * @class eg.Axes.MoveKeyInput * @classdesc A module that passes the amount of change to eg.Axes when the move key stroke is occured. use two axis. * @ko 이동키 입력이 발생했을 때의 변화량을 eg.Axes에 전달하는 모듈. 두 개 의 축을 사용한다. * * @example * const moveKey = new eg.Axes.MoveKeyInput("#area", { * scale: [1, 1] * }); * * // Connect 'x', 'y' axes when the moveKey is pressed. * axes.connect(["x", "y"], moveKey); * * @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.MoveKeyInput module <ko>eg.Axes.MoveKeyInput 모듈을 사용할 엘리먼트</ko> * @param {MoveKeyInputOption} [options] The option object of the eg.Axes.MoveKeyInput module<ko>eg.Axes.MoveKeyInput 모듈의 옵션 객체</ko> */ var MoveKeyInput = /*#__PURE__*/ function () { function MoveKeyInput(el, options) { this.axes = []; this.element = null; this._isEnabled = false; this._isHolded = false; this._timer = null; this.element = $(el); this.options = __assign({ scale: [1, 1] }, options); this.onKeydown = this.onKeydown.bind(this); this.onKeyup = this.onKeyup.bind(this); } var __proto = MoveKeyInput.prototype; __proto.mapAxes = function (axes) { this.axes = axes; }; __proto.connect = function (observer) { this.dettachEvent(); // add tabindex="0" to the container for making it focusable if (this.element.getAttribute("tabindex") !== "0") { this.element.setAttribute("tabindex", "0"); } this.attachEvent(observer); return this; }; __proto.disconnect = function () { this.dettachEvent(); return this; }; /** * Destroys elements, properties, and events used in a module. * @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다. * @method eg.Axes.MoveKeyInput#destroy */ __proto.destroy = function () { this.disconnect(); this.element = null; }; __proto.onKeydown = function (e) { if (!this._isEnabled) { return; } var isMoveKey = true; var direction = DIRECTION_FORWARD; var move = DIRECTION_HORIZONTAL; switch (e.keyCode) { case KEY_LEFT_ARROW: case KEY_A: direction = DIRECTION_REVERSE; break; case KEY_RIGHT_ARROW: case KEY_D: break; case KEY_DOWN_ARROW: case KEY_S: direction = DIRECTION_REVERSE; move = DIRECTION_VERTICAL; break; case KEY_UP_ARROW: case KEY_W: move = DIRECTION_VERTICAL; break; default: isMoveKey = false; } if (move === DIRECTION_HORIZONTAL && !this.axes[0] || move === DIRECTION_VERTICAL && !this.axes[1]) { isMoveKey = false; } if (!isMoveKey) { return; } var offsets = move === DIRECTION_HORIZONTAL ? [+this.options.scale[0] * direction, 0] : [0, +this.options.scale[1] * direction]; if (!this._isHolded) { this.observer.hold(this, event); this._isHolded = true; } clearTimeout(this._timer); this.observer.change(this, event, toAxis(this.axes, offsets)); }; __proto.onKeyup = function (e) { var _this = this; if (!this._isHolded) { return; } clearTimeout(this._timer); this._timer = setTimeout(function () { _this.observer.release(_this, e, toAxis(_this.axes, [0, 0])); _this._isHolded = false; }, DELAY); }; __proto.attachEvent = function (observer) { this.observer = observer; this.element.addEventListener("keydown", this.onKeydown, false); this.element.addEventListener("keypress", this.onKeydown, false); this.element.addEventListener("keyup", this.onKeyup, false); this._isEnabled = true; }; __proto.dettachEvent = function () { this.element.removeEventListener("keydown", this.onKeydown, false); this.element.removeEventListener("keypress", this.onKeydown, false); this.element.removeEventListener("keyup", this.onKeyup, false); this._isEnabled = false; this.observer = null; }; /** * Enables input devices * @ko 입력 장치를 사용할 수 있게 한다 * @method eg.Axes.MoveKeyInput#enable * @return {eg.Axes.MoveKeyInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.enable = function () { this._isEnabled = true; return this; }; /** * Disables input devices * @ko 입력 장치를 사용할 수 없게 한다. * @method eg.Axes.MoveKeyInput#disable * @return {eg.Axes.MoveKeyInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko> */ __proto.disable = function () { this._isEnabled = false; return this; }; /** * Returns whether to use an input device * @ko 입력 장치를 사용 여부를 반환한다. * @method eg.Axes.MoveKeyInput#isEnable * @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko> */ __proto.isEnable = function () { return this._isEnabled; }; return MoveKeyInput; }(); Axes.PanInput = PanInput; Axes.PinchInput = PinchInput; Axes.WheelInput = WheelInput; Axes.MoveKeyInput = MoveKeyInput; return Axes; }))); //# sourceMappingURL=axes.js.map
{ "content_hash": "af09146c3f28513cb8ff5122e79bd1d6", "timestamp": "", "source": "github", "line_count": 2552, "max_line_length": 478, "avg_line_length": 33.336598746081506, "alnum_prop": 0.55494563620335, "repo_name": "cdnjs/cdnjs", "id": "d266b8d8f9cb8e70764e8b7d6e9af9957b15412c", "size": "90088", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ajax/libs/egjs-axes/2.5.8/axes.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!doctype html> <html> <head> <title>The Animatron HTML5 Player Docs</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" type="image/x-icon" href="../favicon.ico" /> <link rel="stylesheet" href="./md.css" type="text/css" /> </head> <body>
{ "content_hash": "be37a81d99e2cb8641c5c37795dd8215", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 74, "avg_line_length": 34.22222222222222, "alnum_prop": 0.6428571428571429, "repo_name": "Animatron/player", "id": "7f94953a6896e49f6303f4489e78b204d439266b", "size": "308", "binary": false, "copies": "3", "ref": "refs/heads/test", "path": "doc/_head.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4663" }, { "name": "HTML", "bytes": "13154" }, { "name": "Java", "bytes": "68240" }, { "name": "JavaScript", "bytes": "773845" } ], "symlink_target": "" }
const html = require('choo/html') const Component = require('choo/component') const asElement = require('prismic-element') const { asText, Elements } = require('prismic-richtext') const resolve = require('../../lib/resolve') const { __ } = require('../../lib/locale') const { loader } = require('../icons') const SPEED_FACTOR = 1000 module.exports = class Onboarding extends Component { constructor (id, state, emit) { super(id) this.id = id this.page = 0 this.isLoading = false this.state = state this.emit = emit } load (element) { const reel = element.querySelector('.js-reel') if (!reel) return let timeout const onscroll = event => { window.clearTimeout(timeout) timeout = window.setTimeout(() => this.align(), 200) } reel.addEventListener('scroll', onscroll) this.unload = () => { reel.removeEventListener('scroll', onscroll) } } update (callback) { this.callback = callback if (!this.isLoading) this.align() return this.isLoading } afterupdate (el) { this.load(el) } align () { let currentTime = 0 const reel = this.element.querySelector('.js-reel') const { scrollLeft, offsetWidth } = reel const offset = offsetWidth * this.page if (scrollLeft !== offset) { // Modulate between 300ms and 800ms animation const time = Math.max(0.3, Math.min(Math.abs(scrollLeft - offset) / SPEED_FACTOR, 0.8)) const tick = () => { currentTime += 1 / 60 const progress = currentTime / time const factor = easeInOut(progress) // As long as progress is greater than 1, keep animating. if (progress < 1) { window.requestAnimationFrame(tick) reel.scrollLeft = scrollLeft + ((offset - scrollLeft) * factor) } else { reel.scrollLeft = offset this.rerender() } } tick() } } createElement (callback) { this.callback = callback const { emit, state, isLoading } = this const doc = state.content && state.content.onboarding if (!doc) { if (!isLoading) emit('content:fetch', 'onboarding') this.isLoading = true return html` <div class="Onboarding"> <div class="u-marginVl u-flexGrow1 u-sizeFull u-flex u-flexAlignItemsCenter"> ${loader()} </div> </div> ` } const cards = doc.data.cards const onclick = page => event => { if (page >= cards.length) { callback() } else { this.page = page this.align() } event.preventDefault() } return html` <div class="Onboarding"> <div class="Onboarding-reel js-reel"> ${cards.map((card, index) => { return html` <article class="Onboarding-card" id="${this.name}-${index}"> ${card.image.url ? html` <div class="Onboarding-container"> <img class="Onboarding-image" src="${card.image.url}" /> </div> ` : null} <h2 class="Display Display--4"> ${asText(card.title)} </h2> <div class="Type"> ${asElement(card.body, resolve, serialize)} </div> </article> ` })} </div> <ol class="Onboarding-pagination"> ${cards.map((card, index) => html` <li> <a href="#${this.id}-${index}" class="Onboarding-page ${this.page === index ? 'is-active' : ''}" onclick=${onclick(index)}> ${asText(card.title)} </a> </li> `)} </ol> ${typeof window === 'undefined' || this.page === (cards.length - 1) ? html` <form action="${this.state.href}" method="GET"> <button type="submit" name="hasBoarded" value="true" class="Button u-block u-sizeFull" onclick=${onclick(this.page + 1)}> ${__('Close')} </button> </form> ` : html` <a href="#${this.id}-${this.page + 1}" class="Button u-block u-sizeFull" onclick=${onclick(this.page + 1)}> ${__('Next')} </a> `} </div> ` function serialize (type, element, content, children) { if (type !== Elements.hyperlink) return null const isDocument = element.data.link_type === 'Document' const href = isDocument ? resolve(element.data.url) : element.data.url const attrs = { onclick: onnavigate, href: href.replace(process.env.BRFENERGI_SERVICE_URL, '') } if (element.data.target && element.data.target === '_blank') { attrs.target = '_blank' attrs.rel = 'noopener noreferrer' } return html`<a ${attrs}>${children}</a>` function onnavigate (event) { callback().then(() => emit('pushState', attrs.href)) event.preventDefault() } } } } function easeInOut (progress) { return (-0.5 * (Math.cos(Math.PI * progress) - 1)) }
{ "content_hash": "0c282503ea535155b1c1260a97fb8839", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 137, "avg_line_length": 28.519553072625698, "alnum_prop": 0.5392752203721841, "repo_name": "CIVIS-project/BRFApp", "id": "f43c2b14f0e76aa2edec4a8fad1d3fbbcebeeef1", "size": "5105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/onboarding/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "46621" }, { "name": "Dockerfile", "bytes": "374" }, { "name": "JavaScript", "bytes": "233160" } ], "symlink_target": "" }
<?php namespace Integrated\Bundle\ContentBundle\Twig\Extension; use Integrated\Common\Content\Channel\ChannelContextInterface; use Integrated\Common\Content\Channel\ChannelInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Twig\Extension\AbstractExtension; use Twig\Extension\GlobalsInterface; /** * @author Ger Jan van den Bosch <gerjan@e-active.nl> */ class ChannelExtension extends AbstractExtension implements GlobalsInterface { /** * @var ContainerInterface */ private $container; /** * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * {@inheritdoc} */ public function getGlobals(): array { return [ '_channel' => $this->getChannel(), ]; } /** * @return ChannelInterface|null */ public function getChannel() { $context = $this->container->get('channel.context'); if (!$context instanceof ChannelContextInterface) { throw new \RuntimeException('Unable to get channel context.'); } return $context->getChannel(); } /** * {@inheritdoc} */ public function getName() { return 'integrated_content_channel_extension'; } }
{ "content_hash": "17f045f2422757b207d47ca3d7ba2279", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 76, "avg_line_length": 21.93548387096774, "alnum_prop": 0.6375, "repo_name": "integratedfordevelopers/integrated", "id": "ecc7b43eedc5a0544b09538118d675889162a922", "size": "1593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Bundle/ContentBundle/Twig/Extension/ChannelExtension.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4803" }, { "name": "HTML", "bytes": "1438" }, { "name": "JavaScript", "bytes": "64697" }, { "name": "PHP", "bytes": "3152918" }, { "name": "SCSS", "bytes": "48270" }, { "name": "Twig", "bytes": "540896" } ], "symlink_target": "" }
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkGeometryFilter(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGeometryFilter(), 'Processing.', ('vtkDataSet',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
{ "content_hash": "f2d82109a401b84af6e3cf01caef802e", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 63, "avg_line_length": 38.81818181818182, "alnum_prop": 0.6604215456674473, "repo_name": "fvpolpeta/devide", "id": "93b89ab1e81ac79131098fa293eedfb258120c3b", "size": "488", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "modules/vtk_basic/vtkGeometryFilter.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "NSIS", "bytes": "2786" }, { "name": "Python", "bytes": "3104368" }, { "name": "Shell", "bytes": "7369" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Indentation { internal partial class CSharpIndentationService { protected override bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken syntaxToken) => ShouldUseSmartTokenFormatterInsteadOfIndenter( indenter.Rules, indenter.Root, indenter.LineToBeIndented, indenter.Options, out syntaxToken); protected override ISmartTokenFormatter CreateSmartTokenFormatter(Indenter indenter) { var services = indenter.Document.Project.Solution.Workspace.Services; var formattingRuleFactory = services.GetRequiredService<IHostDependentFormattingRuleFactoryService>(); var rules = formattingRuleFactory.CreateRule(indenter.Document.Document, indenter.LineToBeIndented.Start).Concat(Formatter.GetDefaultFormattingRules(indenter.Document.Document)); return new CSharpSmartTokenFormatter(indenter.Options, rules, indenter.Root); } protected override IndentationResult? GetDesiredIndentationWorker(Indenter indenter, SyntaxToken? tokenOpt, SyntaxTrivia? triviaOpt) => TryGetDesiredIndentation(indenter, triviaOpt) ?? TryGetDesiredIndentation(indenter, tokenOpt); private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxTrivia? triviaOpt) { // If we have a // comment, and it's the only thing on the line, then if we hit enter, we should align to // that. This helps for cases like: // // int goo; // this comment // // continues // // onwards // // The user will have to manually indent `// continues`, but we'll respect that indentation from that point on. if (triviaOpt == null) return null; var trivia = triviaOpt.Value; if (!trivia.IsSingleOrMultiLineComment() && !trivia.IsDocComment()) return null; var line = indenter.Text.Lines.GetLineFromPosition(trivia.FullSpan.Start); if (line.GetFirstNonWhitespacePosition() != trivia.FullSpan.Start) return null; // Previous line just contained this single line comment. Align us with it. return new IndentationResult(trivia.FullSpan.Start, 0); } private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxToken? tokenOpt) { if (tokenOpt == null) return null; return GetIndentationBasedOnToken(indenter, tokenOpt.Value); } private static IndentationResult GetIndentationBasedOnToken(Indenter indenter, SyntaxToken token) { Contract.ThrowIfNull(indenter.Tree); Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None); var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // case: """$$ // """ if (token.IsKind(SyntaxKind.MultiLineRawStringLiteralToken)) { var endLine = sourceText.Lines.GetLineFromPosition(token.Span.End); var nonWhitespaceOffset = endLine.GetFirstNonWhitespaceOffset(); Contract.ThrowIfNull(nonWhitespaceOffset); return new IndentationResult(indenter.LineToBeIndented.Start, nonWhitespaceOffset.Value); } // case 1: $"""$$ // """ // case 2: $""" // text$$ // """ if (token.Kind() is SyntaxKind.InterpolatedMultiLineRawStringStartToken or SyntaxKind.InterpolatedStringTextToken) { var interpolatedExpression = token.GetAncestor<InterpolatedStringExpressionSyntax>(); Contract.ThrowIfNull(interpolatedExpression); if (interpolatedExpression.StringStartToken.IsKind(SyntaxKind.InterpolatedMultiLineRawStringStartToken)) { var endLinePosition = sourceText.Lines.GetLineFromPosition(interpolatedExpression.StringEndToken.Span.End); var nonWhitespaceOffset = endLinePosition.GetFirstNonWhitespaceOffset(); Contract.ThrowIfNull(nonWhitespaceOffset); return new IndentationResult(indenter.LineToBeIndented.Start, nonWhitespaceOffset.Value); } } // special cases // case 1: token belongs to verbatim token literal // case 2: $@"$${0}" // case 3: $@"Comment$$ in-between{0}" // case 4: $@"{0}$$" if (token.IsVerbatimStringLiteral() || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || (token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation))) { return indenter.IndentFromStartOfLine(0); } // if previous statement belong to labeled statement, don't follow label's indentation // but its previous one. if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement()) { token = token.GetAncestor<LabeledStatementSyntax>()!.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); } var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // first check operation service to see whether we can determine indentation from it var indentation = indenter.Finder.FromIndentBlockOperations(indenter.Tree, token, position, indenter.CancellationToken); if (indentation.HasValue) { return indenter.IndentFromStartOfLine(indentation.Value); } var alignmentTokenIndentation = indenter.Finder.FromAlignTokensOperations(indenter.Tree, token); if (alignmentTokenIndentation.HasValue) { return indenter.IndentFromStartOfLine(alignmentTokenIndentation.Value); } // if we couldn't determine indentation from the service, use heuristic to find indentation. // If this is the last token of an embedded statement, walk up to the top-most parenting embedded // statement owner and use its indentation. // // cases: // if (true) // if (false) // Goo(); // // if (true) // { } if (token.IsSemicolonOfEmbeddedStatement() || token.IsCloseBraceOfEmbeddedBlock()) { Debug.Assert( token.Parent != null && (token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax)); var embeddedStatementOwner = token.Parent.Parent; while (embeddedStatementOwner.IsEmbeddedStatement()) { RoslynDebug.AssertNotNull(embeddedStatementOwner.Parent); embeddedStatementOwner = embeddedStatementOwner.Parent; } return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart)); } switch (token.Kind()) { case SyntaxKind.SemicolonToken: { // special cases if (token.IsSemicolonInForStatement()) { return GetDefaultIndentationFromToken(indenter, token); } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.CloseBraceToken: { if (token.Parent.IsKind(SyntaxKind.AccessorList) && token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration)) { if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers()) { return GetDefaultIndentationFromToken(indenter, token); } } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.OpenBraceToken: { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.ColonToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); if (nonTerminalNode is SwitchLabelSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), indenter.Options.FormattingOptions.IndentationSize); } goto default; } case SyntaxKind.CloseBracketToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); // if this is closing an attribute, we shouldn't indent. if (nonTerminalNode is AttributeListSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart)); } goto default; } case SyntaxKind.XmlTextLiteralToken: { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(token.SpanStart)); } case SyntaxKind.CommaToken: { return GetIndentationFromCommaSeparatedList(indenter, token); } case SyntaxKind.CloseParenToken: { if (token.Parent.IsKind(SyntaxKind.ArgumentList)) { return GetDefaultIndentationFromToken(indenter, token.Parent.GetFirstToken(includeZeroWidth: true)); } goto default; } default: { return GetDefaultIndentationFromToken(indenter, token); } } } private static IndentationResult GetIndentationFromCommaSeparatedList(Indenter indenter, SyntaxToken token) => token.Parent switch { BaseArgumentListSyntax argument => GetIndentationFromCommaSeparatedList(indenter, argument.Arguments, token), BaseParameterListSyntax parameter => GetIndentationFromCommaSeparatedList(indenter, parameter.Parameters, token), TypeArgumentListSyntax typeArgument => GetIndentationFromCommaSeparatedList(indenter, typeArgument.Arguments, token), TypeParameterListSyntax typeParameter => GetIndentationFromCommaSeparatedList(indenter, typeParameter.Parameters, token), EnumDeclarationSyntax enumDeclaration => GetIndentationFromCommaSeparatedList(indenter, enumDeclaration.Members, token), InitializerExpressionSyntax initializerSyntax => GetIndentationFromCommaSeparatedList(indenter, initializerSyntax.Expressions, token), _ => GetDefaultIndentationFromToken(indenter, token), }; private static IndentationResult GetIndentationFromCommaSeparatedList<T>( Indenter indenter, SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode { var index = list.GetWithSeparators().IndexOf(token); if (index < 0) { return GetDefaultIndentationFromToken(indenter, token); } // find node that starts at the beginning of a line var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); for (var i = (index - 1) / 2; i >= 0; i--) { var node = list[i]; var firstToken = node.GetFirstToken(includeZeroWidth: true); if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(firstToken.SpanStart)); } } // smart indenter has a special indent block rule for comma separated list, so don't // need to add default additional space for multiline expressions return GetDefaultIndentationFromTokenLine(indenter, token, additionalSpace: 0); } private static IndentationResult GetDefaultIndentationFromToken(Indenter indenter, SyntaxToken token) { if (IsPartOfQueryExpression(token)) { return GetIndentationForQueryExpression(indenter, token); } return GetDefaultIndentationFromTokenLine(indenter, token); } private static IndentationResult GetIndentationForQueryExpression(Indenter indenter, SyntaxToken token) { // find containing non terminal node var queryExpressionClause = GetQueryExpressionClause(token); if (queryExpressionClause == null) { return GetDefaultIndentationFromTokenLine(indenter, token); } // find line where first token of the node is var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true); var firstTokenLine = sourceText.Lines.GetLineFromPosition(firstToken.SpanStart); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); if (firstTokenLine.LineNumber != givenTokenLine.LineNumber) { // do default behavior return GetDefaultIndentationFromTokenLine(indenter, token); } // okay, we are right under the query expression. // align caret to query expression if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(firstToken); } // find query body that has a token that is a first token on the line if (queryExpressionClause.Parent is not QueryBodySyntax queryBody) { return indenter.GetIndentationOfToken(firstToken); } // find preceding clause that starts on its own. var clauses = queryBody.Clauses; for (var i = clauses.Count - 1; i >= 0; i--) { var clause = clauses[i]; if (firstToken.SpanStart <= clause.SpanStart) { continue; } var clauseToken = clause.GetFirstToken(includeZeroWidth: true); if (clauseToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(clauseToken); } } // no query clause start a line. use the first token of the query expression RoslynDebug.AssertNotNull(queryBody.Parent); return indenter.GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true)); } private static SyntaxNode? GetQueryExpressionClause(SyntaxToken token) { var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax or SelectOrGroupClauseSyntax); if (clause != null) { return clause; } // If this is a query continuation, use the last clause of its parenting query. var body = token.GetAncestor<QueryBodySyntax>(); if (body != null) { if (body.SelectOrGroup.IsMissing) { return body.Clauses.LastOrDefault(); } else { return body.SelectOrGroup; } } return null; } private static bool IsPartOfQueryExpression(SyntaxToken token) { var queryExpression = token.GetAncestor<QueryExpressionSyntax>(); return queryExpression != null; } private static IndentationResult GetDefaultIndentationFromTokenLine( Indenter indenter, SyntaxToken token, int? additionalSpace = null) { var spaceToAdd = additionalSpace ?? indenter.Options.FormattingOptions.IndentationSize; var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); // find right position var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // find containing non expression node var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax); if (nonExpressionNode == null) { // well, I can't find any non expression node. use default behavior return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // find line where first token of the node is var firstTokenLine = sourceText.Lines.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart); // single line expression if (firstTokenLine.LineNumber == givenTokenLine.LineNumber) { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token return indenter.GetIndentationOfLine(givenTokenLine); } } }
{ "content_hash": "c02fe150b8cf8c237100dd4849b1624b", "timestamp": "", "source": "github", "line_count": 435, "max_line_length": 220, "avg_line_length": 46.19310344827586, "alnum_prop": 0.6053050661889121, "repo_name": "KevinRansom/roslyn", "id": "34921a5b63d7fc7e3ea6474f1ee66039ef940077", "size": "20096", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/Workspaces/CSharp/Portable/Indentation/CSharpIndentationService.Indenter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8186" }, { "name": "C#", "bytes": "165251418" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "11076" }, { "name": "Dockerfile", "bytes": "441" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "279605" }, { "name": "Shell", "bytes": "123448" }, { "name": "Vim Snippet", "bytes": "6353" }, { "name": "Visual Basic .NET", "bytes": "73602862" } ], "symlink_target": "" }
#pragma once #include <string> #include <iostream> #include <opencv/cxcore.h> #include <opencv/cv.h> #include <opencv/cvaux.h> #include <opencv/highgui.h> using namespace std; class ConfidenceVector{ public: ConfidenceVector(const cv::String & algName, int size); string getName(void); void addElement(int row, double element); double getMaxValue(void); int getMaxIndex(); int getSize(void); double getElement(int index); void print(ostream & out = cout) const; virtual ~ConfidenceVector(void){delete(&cv);}; private: int getIndexMax(void); void sortVector(void); CvMat * cv; cv::String name; int ONE, ZERO, maxIndex; }; ostream & operator<<(ostream & out, const ConfidenceVector & cv);
{ "content_hash": "e6ec9a07e03c57d33c206b977b80a913", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 65, "avg_line_length": 20.257142857142856, "alnum_prop": 0.7263751763046544, "repo_name": "binary42/elars", "id": "510d6f534bd33401b105e86f698f997a934fe8b9", "size": "1877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Lib/Elars/ConfidenceVector.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1383" }, { "name": "C++", "bytes": "314336" } ], "symlink_target": "" }
#ifndef HAL_QUADROTOR_EMERGENCY_H #define HAL_QUADROTOR_EMERGENCY_H // Base controller type #include <hal_quadrotor/control/Controller.h> // Messages used by this controller #include <hal_quadrotor/Emergency.h> namespace hal { namespace quadrotor { //! A quadrotor Emergency controller /*! A more elaborate class description. */ class Emergency : public Controller { public: //! Callback for goal update /*! \param req the goal request \param res the goal response \return whether the control was accepted */ bool SetGoal( hal_quadrotor::Emergency::Request& req, hal_quadrotor::Emergency::Response& res ); //! Obtain control from state and timestep /*! \param state the current platform state \param dt the discrete time step \param control the output control from the controller \return if the state could be updated */ void Update(const hal_quadrotor::State &state, double dt, hal_quadrotor::Control &control); //! Goal reach implementations /*! \return Whether the goal has been reached */ bool HasGoalBeenReached(); //! Reset implementation /*! \return Reset the internal state of the controller */ void Reset(); }; } } #endif
{ "content_hash": "f31dfb5b009d29c73fa9b77b5618403f", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 67, "avg_line_length": 27.06779661016949, "alnum_prop": 0.5385097056981841, "repo_name": "jiangchenzhu/crates_zhejiang", "id": "1a0e62f1bf300fb16f22d60a9e1ebe9f7d6b255b", "size": "1597", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/hal_quadrotor/include/hal_quadrotor/control/Emergency.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "91195" }, { "name": "C++", "bytes": "398461" }, { "name": "CMake", "bytes": "14527" }, { "name": "Protocol Buffer", "bytes": "1645" }, { "name": "Shell", "bytes": "4795" } ], "symlink_target": "" }
import {ResetBrowserProxy} from 'chrome://settings/settings.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; export class TestResetBrowserProxy extends TestBrowserProxy implements ResetBrowserProxy { constructor() { super([ 'performResetProfileSettings', 'onHideResetProfileDialog', 'onHideResetProfileBanner', 'onShowResetProfileDialog', 'showReportedSettings', 'getTriggeredResetToolName', ]); } performResetProfileSettings(_sendSettings: boolean, requestOrigin: string) { this.methodCalled('performResetProfileSettings', requestOrigin); return Promise.resolve(); } onHideResetProfileDialog() { this.methodCalled('onHideResetProfileDialog'); } onHideResetProfileBanner() { this.methodCalled('onHideResetProfileBanner'); } onShowResetProfileDialog() { this.methodCalled('onShowResetProfileDialog'); } showReportedSettings() { this.methodCalled('showReportedSettings'); } getTriggeredResetToolName() { this.methodCalled('getTriggeredResetToolName'); return Promise.resolve('WonderfulAV'); } }
{ "content_hash": "767781eee6ed424e86fb785718f8c558", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 78, "avg_line_length": 27.142857142857142, "alnum_prop": 0.7350877192982456, "repo_name": "scheib/chromium", "id": "658f3e33fb81880da8828dc2f57ac14bd5100334", "size": "1306", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "chrome/test/data/webui/settings/test_reset_browser_proxy.ts", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
.class public Lcom/android/keyguard/biometric/KeyguardBiometricIconView; .super Landroid/widget/FrameLayout; .source "KeyguardBiometricIconView.java" # annotations .annotation system Ldalvik/annotation/MemberClasses; value = { Lcom/android/keyguard/biometric/KeyguardBiometricIconView$1;, Lcom/android/keyguard/biometric/KeyguardBiometricIconView$2; } .end annotation # instance fields .field protected mBouncerShowing:Z .field protected mKnoxStateMonitor:Lcom/android/systemui/KnoxStateMonitor; .field protected mPowerManager:Landroid/os/PowerManager; .field private mSettingsCallback:Lcom/android/systemui/util/SettingsHelper$OnChangedCallback; .field protected mState:I .field protected final mUpdateMonitorCallback:Lcom/android/keyguard/KeyguardUpdateMonitorCallback; # direct methods .method static synthetic -get0(Lcom/android/keyguard/biometric/KeyguardBiometricIconView;)Landroid/content/Context; .locals 1 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; return-object v0 .end method .method public constructor <init>(Landroid/content/Context;)V .locals 1 const/4 v0, 0x0 invoke-direct {p0, p1, v0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V return-void .end method .method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V .locals 2 invoke-direct {p0, p1, p2}, Landroid/widget/FrameLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V const/4 v0, 0x0 iput v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mState:I new-instance v0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView$1; invoke-direct {v0, p0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView$1;-><init>(Lcom/android/keyguard/biometric/KeyguardBiometricIconView;)V iput-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mUpdateMonitorCallback:Lcom/android/keyguard/KeyguardUpdateMonitorCallback; new-instance v0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView$2; invoke-direct {v0, p0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView$2;-><init>(Lcom/android/keyguard/biometric/KeyguardBiometricIconView;)V iput-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mSettingsCallback:Lcom/android/systemui/util/SettingsHelper$OnChangedCallback; iput-object p1, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; const-string/jumbo v1, "power" invoke-virtual {v0, v1}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object; move-result-object v0 check-cast v0, Landroid/os/PowerManager; iput-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mPowerManager:Landroid/os/PowerManager; const-class v0, Lcom/android/systemui/KnoxStateMonitor; invoke-static {v0}, Lcom/android/systemui/Dependency;->get(Ljava/lang/Class;)Ljava/lang/Object; move-result-object v0 check-cast v0, Lcom/android/systemui/KnoxStateMonitor; iput-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mKnoxStateMonitor:Lcom/android/systemui/KnoxStateMonitor; return-void .end method .method private isOnIconExact(Landroid/view/View;FF)Z .locals 3 const/4 v2, 0x0 const/4 v0, 0x0 cmpl-float v1, p2, v2 if-lez v1, :cond_0 invoke-virtual {p1}, Landroid/view/View;->getWidth()I move-result v1 int-to-float v1, v1 cmpg-float v1, p2, v1 if-gez v1, :cond_0 cmpl-float v1, p3, v2 if-lez v1, :cond_0 invoke-virtual {p1}, Landroid/view/View;->getHeight()I move-result v1 int-to-float v1, v1 cmpg-float v1, p3, v1 if-gez v1, :cond_0 const/4 v0, 0x1 :cond_0 return v0 .end method # virtual methods .method protected getIconState()I .locals 3 const/4 v1, 0x3 const/4 v2, 0x0 iget v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mState:I if-ne v0, v1, :cond_0 return v1 :cond_0 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mKnoxStateMonitor:Lcom/android/systemui/KnoxStateMonitor; invoke-virtual {v0}, Lcom/android/systemui/KnoxStateMonitor;->isMultifactorAuthEnforced()Z move-result v0 if-eqz v0, :cond_1 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-static {}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getCurrentUser()I move-result v1 invoke-virtual {v0, v1}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isAuthenticatedWithBiometric(I)Z move-result v0 if-eqz v0, :cond_1 return v2 :cond_1 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isFaceRecognitionRunning()Z move-result v0 if-nez v0, :cond_2 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isIBRunning()Z move-result v0 if-eqz v0, :cond_3 :cond_2 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isDexMode()Z move-result v0 xor-int/lit8 v0, v0, 0x1 if-eqz v0, :cond_3 const/4 v0, 0x1 return v0 :cond_3 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isShowingFaceRecognitionRetry()Z move-result v0 if-nez v0, :cond_4 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isShowingIrisRetryButton()Z move-result v0 if-nez v0, :cond_4 iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 invoke-virtual {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->isShowingIBRetryButton()Z move-result v0 if-eqz v0, :cond_5 :cond_4 const/4 v0, 0x2 return v0 :cond_5 return v2 .end method .method protected isBiometricRetryIconSelected(Landroid/view/View;FF)Z .locals 2 const/4 v1, 0x0 if-eqz p1, :cond_0 invoke-virtual {p1}, Landroid/view/View;->getVisibility()I move-result v0 if-nez v0, :cond_0 invoke-direct {p0, p1, p2, p3}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->isOnIconExact(Landroid/view/View;FF)Z move-result v0 if-eqz v0, :cond_0 const/4 v0, 0x1 return v0 :cond_0 return v1 .end method .method protected onAttachedToWindow()V .locals 5 invoke-super {p0}, Landroid/widget/FrameLayout;->onAttachedToWindow()V iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 iget-object v1, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mUpdateMonitorCallback:Lcom/android/keyguard/KeyguardUpdateMonitorCallback; invoke-virtual {v0, v1}, Lcom/android/keyguard/KeyguardUpdateMonitor;->registerCallback(Lcom/android/keyguard/KeyguardUpdateMonitorCallback;)V invoke-static {}, Lcom/android/systemui/util/SettingsHelper;->getInstance()Lcom/android/systemui/util/SettingsHelper; move-result-object v0 iget-object v1, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mSettingsCallback:Lcom/android/systemui/util/SettingsHelper$OnChangedCallback; const/4 v2, 0x1 new-array v2, v2, [Landroid/net/Uri; const-string/jumbo v3, "white_lockscreen_wallpaper" invoke-static {v3}, Landroid/provider/Settings$System;->getUriFor(Ljava/lang/String;)Landroid/net/Uri; move-result-object v3 const/4 v4, 0x0 aput-object v3, v2, v4 invoke-virtual {v0, v1, v2}, Lcom/android/systemui/util/SettingsHelper;->registerCallback(Lcom/android/systemui/util/SettingsHelper$OnChangedCallback;[Landroid/net/Uri;)V return-void .end method .method protected onDetachedFromWindow()V .locals 2 invoke-super {p0}, Landroid/widget/FrameLayout;->onDetachedFromWindow()V iget-object v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mContext:Landroid/content/Context; invoke-static {v0}, Lcom/android/keyguard/KeyguardUpdateMonitor;->getInstance(Landroid/content/Context;)Lcom/android/keyguard/KeyguardUpdateMonitor; move-result-object v0 iget-object v1, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mUpdateMonitorCallback:Lcom/android/keyguard/KeyguardUpdateMonitorCallback; invoke-virtual {v0, v1}, Lcom/android/keyguard/KeyguardUpdateMonitor;->removeCallback(Lcom/android/keyguard/KeyguardUpdateMonitorCallback;)V invoke-static {}, Lcom/android/systemui/util/SettingsHelper;->getInstance()Lcom/android/systemui/util/SettingsHelper; move-result-object v0 iget-object v1, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mSettingsCallback:Lcom/android/systemui/util/SettingsHelper$OnChangedCallback; invoke-virtual {v0, v1}, Lcom/android/systemui/util/SettingsHelper;->unregisterCallback(Lcom/android/systemui/util/SettingsHelper$OnChangedCallback;)V return-void .end method .method protected onFinishInflate()V .locals 0 invoke-super {p0}, Landroid/widget/FrameLayout;->onFinishInflate()V return-void .end method .method protected updateErrorText(Ljava/lang/String;Ljava/lang/String;)V .locals 0 return-void .end method .method protected updateHelpText(Ljava/lang/String;)V .locals 0 return-void .end method .method protected updateIconDrawable(I)V .locals 0 return-void .end method .method protected updateIconVisibility()V .locals 3 const/4 v2, 0x0 invoke-virtual {p0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->getIconState()I move-result v0 iput v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mState:I iget v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mState:I const/4 v1, 0x1 if-eq v0, v1, :cond_0 iget v0, p0, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->mState:I const/4 v1, 0x2 if-ne v0, v1, :cond_1 :cond_0 const/4 v0, -0x1 invoke-virtual {p0, v0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->updateIconDrawable(I)V invoke-virtual {p0, v2}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->setVisibility(I)V return-void :cond_1 invoke-virtual {p0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->getVisibility()I move-result v0 if-nez v0, :cond_2 const/16 v0, 0x8 invoke-virtual {p0, v0}, Lcom/android/keyguard/biometric/KeyguardBiometricIconView;->setVisibility(I)V :cond_2 return-void .end method .method protected updateVisualCueIcon()V .locals 0 return-void .end method
{ "content_hash": "c8b6987b914b32b4f07b5b758ba73148", "timestamp": "", "source": "github", "line_count": 439, "max_line_length": 174, "avg_line_length": 29.767653758542142, "alnum_prop": 0.7578053259871441, "repo_name": "BatMan-Rom/ModdedFiles", "id": "9f031c58dae44dce425f782ed1fcc3f249039a41", "size": "13068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SystemUI/smali/com/android/keyguard/biometric/KeyguardBiometricIconView.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
package com.kaltiz.ItsAboutTime; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; public class TimeCalculator { private ItsAboutTime plugin; private int daysInWeek; private int monthInYear; private List<Integer> daysInMonth; private int secondsInMinute; private int minutesInHours; private int hourInDay; private double realYearsInYear; private int yearModifier; private List<String> monthNames; private List<String> weekdayNames; private String timezone; private String formatStr; private int updateTime; private Time cached = null; private Long cachedTime = 0L; private long cacheHoldTime; public TimeCalculator(ItsAboutTime plugin) { this.plugin = plugin; } /** * Checks and reads the config, returns false on error * @return */ public boolean readConfig() { daysInWeek = plugin.getConfig().getInt("days-in-week"); monthInYear = plugin.getConfig().getInt("months-in-year"); daysInMonth = plugin.getConfig().getIntegerList("days-in-month"); secondsInMinute = plugin.getConfig().getInt("seconds-in-minute"); minutesInHours = plugin.getConfig().getInt("minutes-in-hour"); hourInDay = plugin.getConfig().getInt("hours-in-day"); realYearsInYear = plugin.getConfig().getDouble("year-length"); yearModifier = plugin.getConfig().getInt("year-modifier"); monthNames = plugin.getConfig().getStringList("month-names"); weekdayNames = plugin.getConfig().getStringList("weekday-names"); timezone = plugin.getConfig().getString("timezone"); formatStr = plugin.getConfig().getString("time-format"); cacheHoldTime = plugin.getConfig().getLong("clock-cache"); updateTime = plugin.getConfig().getInt("update-interval"); // Check days in month length, should be equal to months in year if (daysInMonth.size() != monthInYear) { plugin.getLogger().severe("There should be an entry for each month in days-in-month"); return false; } // Check the month names, should be equal to months in year if (monthNames.size() != daysInWeek) { plugin.getLogger().severe("There should be an entry for each month in month-names"); return false; } // Check the weekday names, should be equal to days in week if (weekdayNames.size() != daysInWeek) { plugin.getLogger().severe("There should be an entry for each day in weekday-names"); return false; } return true; } public Time calculateTime() { if ((this.cachedTime + this.cacheHoldTime) > System.currentTimeMillis()/1000 && this.cached != null) return this.cached; // Get the current time Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.setTimeZone(TimeZone.getTimeZone(timezone)); // Calculate the year int year = cal.get(Calendar.YEAR); year = (int) (year / realYearsInYear); year = year + yearModifier; // Turn Real days into hours double realDaysInHours = (cal.get(Calendar.DAY_OF_YEAR) - 1) * 24; // Catch Spare Days through the real day double calhours = cal.get(Calendar.HOUR_OF_DAY); double calminutes = (double) cal.get(Calendar.MINUTE) / 60; double calseconds = (double) cal.get(Calendar.SECOND) / 3600; realDaysInHours += (double) (calhours + calminutes + calseconds); // Work out days in the year; int daysInYear = 0; for (int days : daysInMonth) { daysInYear += days; } // Work out the real hours in a fake day // Days become slightly longer in a leap year double realHoursInDay = (double) (cal.getActualMaximum(Calendar.DAY_OF_YEAR) * 24) / daysInYear; // Take out any leftover hours Double Ahour = (double) realDaysInHours / realHoursInDay; // Now convert the realDaysInHours to fake days // Note 0 indexed int dayInYear = (int) Math.floor(Ahour); // Now we figure out the month int totalDays = 0; int month = 0; for (int days : daysInMonth) { if (dayInYear >= totalDays && dayInYear < totalDays + days) { break; } month++; totalDays += days; } // Now lets workout the time // Extract fulldays double fragment = Double.parseDouble("." + String.valueOf(Ahour).split("\\.")[1]); // hourFrag is now in days, so times it by the number of hours in a day Double Amin = fragment * hourInDay; int hours = (int) Math.floor(Amin); // Amin is now in hours, get the number of minutes fragment = Double.parseDouble("." + String.valueOf(Amin).split("\\.")[1]); Double Asecs = fragment * minutesInHours; int minutes = (int) Math.floor(Asecs); // Asecs is now in minutes, get the number of minutes fragment = Double.parseDouble("." + String.valueOf(Asecs).split("\\.")[1]); int seconds = (int) Math.floor(fragment * secondsInMinute); // Now make a time object Time time = new Time(year, month + 1, dayInYear + 1 - totalDays, dayInYear + 1, (dayInYear + 1) % daysInWeek, hours, minutes, seconds); this.cached = time; this.cachedTime = System.currentTimeMillis()/1000; return time; } public String format(Time time) { String ret = this.formatStr; ret = ret.replaceAll("%d", leadingZeros(time.getDayOfMonth())); ret = ret.replaceAll("%D", String.valueOf(time.getDayOfMonth())); ret = ret.replaceAll("%l", weekdayNames.get(time.getWeekDay())); ret = ret.replaceAll("%o", this.getOrdinal(time.getDayOfMonth())); ret = ret.replaceAll("%F", monthNames.get(time.getMonth() -1)); ret = ret.replaceAll("%m", leadingZeros(time.getMonth())); ret = ret.replaceAll("%M", String.valueOf(time.getMonth())); ret = ret.replaceAll("%y", String.valueOf(time.getYear())); ret = ret.replaceAll("%Y", String.valueOf(time.getYear()).substring(String.valueOf(time.getYear()).length() - 2)); String ampm; if (time.getHour() > (hourInDay / 2)) ampm = "pm"; else ampm = "am"; ret = ret.replaceAll("%a", ampm); ret = ret.replaceAll("%A", ampm.toUpperCase()); ret = ret.replaceAll("%g", String.valueOf(time.getHour() - (hourInDay / 2))); ret = ret.replaceAll("%G", String.valueOf(time.getHour())); ret = ret.replaceAll("%h", leadingZeros(time.getHour() - (hourInDay / 2))); ret = ret.replaceAll("%H", leadingZeros(time.getHour())); ret = ret.replaceAll("%i", leadingZeros(time.getMinute())); ret = ret.replaceAll("%I", String.valueOf(time.getMinute())); ret = ret.replaceAll("%s", leadingZeros(time.getSecond())); ret = ret.replaceAll("%S", String.valueOf(time.getSecond())); ret = ret.replaceAll("%%", "%"); return ret; } public String getOrdinal(int value) { int hundredRemainder = value % 100; if(hundredRemainder >= 10 && hundredRemainder <= 20) { return "th"; } int tenRemainder = value % 10; switch (tenRemainder) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } } public String leadingZeros(int value) { if (value < 10) { return "0" + String.valueOf(value); } return String.valueOf(value); } }
{ "content_hash": "22b3e426ee7f8ddeb29509b07f366e7b", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 143, "avg_line_length": 33.575630252100844, "alnum_prop": 0.5925416093104743, "repo_name": "Kaltiz/ItsAboutTime", "id": "dd665d62f488e8ffeeff8f205ebbb9fb8845ed5d", "size": "7991", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/kaltiz/ItsAboutTime/TimeCalculator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "12622" } ], "symlink_target": "" }
package typeutil // import "golang.org/x/tools/go/types/typeutil" import ( "bytes" "fmt" "go/types" "reflect" "golang.org/x/tools/internal/typeparams" ) // Map is a hash-table-based mapping from types (types.Type) to // arbitrary interface{} values. The concrete types that implement // the Type interface are pointers. Since they are not canonicalized, // == cannot be used to check for equivalence, and thus we cannot // simply use a Go map. // // Just as with map[K]V, a nil *Map is a valid empty map. // // Not thread-safe. type Map struct { hasher Hasher // shared by many Maps table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused length int // number of map entries } // entry is an entry (key/value association) in a hash bucket. type entry struct { key types.Type value interface{} } // SetHasher sets the hasher used by Map. // // All Hashers are functionally equivalent but contain internal state // used to cache the results of hashing previously seen types. // // A single Hasher created by MakeHasher() may be shared among many // Maps. This is recommended if the instances have many keys in // common, as it will amortize the cost of hash computation. // // A Hasher may grow without bound as new types are seen. Even when a // type is deleted from the map, the Hasher never shrinks, since other // types in the map may reference the deleted type indirectly. // // Hashers are not thread-safe, and read-only operations such as // Map.Lookup require updates to the hasher, so a full Mutex lock (not a // read-lock) is require around all Map operations if a shared // hasher is accessed from multiple threads. // // If SetHasher is not called, the Map will create a private hasher at // the first call to Insert. func (m *Map) SetHasher(hasher Hasher) { m.hasher = hasher } // Delete removes the entry with the given key, if any. // It returns true if the entry was found. func (m *Map) Delete(key types.Type) bool { if m != nil && m.table != nil { hash := m.hasher.Hash(key) bucket := m.table[hash] for i, e := range bucket { if e.key != nil && types.Identical(key, e.key) { // We can't compact the bucket as it // would disturb iterators. bucket[i] = entry{} m.length-- return true } } } return false } // At returns the map entry for the given key. // The result is nil if the entry is not present. func (m *Map) At(key types.Type) interface{} { if m != nil && m.table != nil { for _, e := range m.table[m.hasher.Hash(key)] { if e.key != nil && types.Identical(key, e.key) { return e.value } } } return nil } // Set sets the map entry for key to val, // and returns the previous entry, if any. func (m *Map) Set(key types.Type, value interface{}) (prev interface{}) { if m.table != nil { hash := m.hasher.Hash(key) bucket := m.table[hash] var hole *entry for i, e := range bucket { if e.key == nil { hole = &bucket[i] } else if types.Identical(key, e.key) { prev = e.value bucket[i].value = value return } } if hole != nil { *hole = entry{key, value} // overwrite deleted entry } else { m.table[hash] = append(bucket, entry{key, value}) } } else { if m.hasher.memo == nil { m.hasher = MakeHasher() } hash := m.hasher.Hash(key) m.table = map[uint32][]entry{hash: {entry{key, value}}} } m.length++ return } // Len returns the number of map entries. func (m *Map) Len() int { if m != nil { return m.length } return 0 } // Iterate calls function f on each entry in the map in unspecified order. // // If f should mutate the map, Iterate provides the same guarantees as // Go maps: if f deletes a map entry that Iterate has not yet reached, // f will not be invoked for it, but if f inserts a map entry that // Iterate has not yet reached, whether or not f will be invoked for // it is unspecified. func (m *Map) Iterate(f func(key types.Type, value interface{})) { if m != nil { for _, bucket := range m.table { for _, e := range bucket { if e.key != nil { f(e.key, e.value) } } } } } // Keys returns a new slice containing the set of map keys. // The order is unspecified. func (m *Map) Keys() []types.Type { keys := make([]types.Type, 0, m.Len()) m.Iterate(func(key types.Type, _ interface{}) { keys = append(keys, key) }) return keys } func (m *Map) toString(values bool) string { if m == nil { return "{}" } var buf bytes.Buffer fmt.Fprint(&buf, "{") sep := "" m.Iterate(func(key types.Type, value interface{}) { fmt.Fprint(&buf, sep) sep = ", " fmt.Fprint(&buf, key) if values { fmt.Fprintf(&buf, ": %q", value) } }) fmt.Fprint(&buf, "}") return buf.String() } // String returns a string representation of the map's entries. // Values are printed using fmt.Sprintf("%v", v). // Order is unspecified. func (m *Map) String() string { return m.toString(true) } // KeysString returns a string representation of the map's key set. // Order is unspecified. func (m *Map) KeysString() string { return m.toString(false) } //////////////////////////////////////////////////////////////////////// // Hasher // A Hasher maps each type to its hash value. // For efficiency, a hasher uses memoization; thus its memory // footprint grows monotonically over time. // Hashers are not thread-safe. // Hashers have reference semantics. // Call MakeHasher to create a Hasher. type Hasher struct { memo map[types.Type]uint32 // ptrMap records pointer identity. ptrMap map[interface{}]uint32 // sigTParams holds type parameters from the signature being hashed. // Signatures are considered identical modulo renaming of type parameters, so // within the scope of a signature type the identity of the signature's type // parameters is just their index. // // Since the language does not currently support referring to uninstantiated // generic types or functions, and instantiated signatures do not have type // parameter lists, we should never encounter a second non-empty type // parameter list when hashing a generic signature. sigTParams *typeparams.TypeParamList } // MakeHasher returns a new Hasher instance. func MakeHasher() Hasher { return Hasher{ memo: make(map[types.Type]uint32), ptrMap: make(map[interface{}]uint32), sigTParams: nil, } } // Hash computes a hash value for the given type t such that // Identical(t, t') => Hash(t) == Hash(t'). func (h Hasher) Hash(t types.Type) uint32 { hash, ok := h.memo[t] if !ok { hash = h.hashFor(t) h.memo[t] = hash } return hash } // hashString computes the Fowler–Noll–Vo hash of s. func hashString(s string) uint32 { var h uint32 for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } return h } // hashFor computes the hash of t. func (h Hasher) hashFor(t types.Type) uint32 { // See Identical for rationale. switch t := t.(type) { case *types.Basic: return uint32(t.Kind()) case *types.Array: return 9043 + 2*uint32(t.Len()) + 3*h.Hash(t.Elem()) case *types.Slice: return 9049 + 2*h.Hash(t.Elem()) case *types.Struct: var hash uint32 = 9059 for i, n := 0, t.NumFields(); i < n; i++ { f := t.Field(i) if f.Anonymous() { hash += 8861 } hash += hashString(t.Tag(i)) hash += hashString(f.Name()) // (ignore f.Pkg) hash += h.Hash(f.Type()) } return hash case *types.Pointer: return 9067 + 2*h.Hash(t.Elem()) case *types.Signature: var hash uint32 = 9091 if t.Variadic() { hash *= 8863 } // Use a separate hasher for types inside of the signature, where type // parameter identity is modified to be (index, constraint). We must use a // new memo for this hasher as type identity may be affected by this // masking. For example, in func[T any](*T), the identity of *T depends on // whether we are mapping the argument in isolation, or recursively as part // of hashing the signature. // // We should never encounter a generic signature while hashing another // generic signature, but defensively set sigTParams only if h.mask is // unset. tparams := typeparams.ForSignature(t) if h.sigTParams == nil && tparams.Len() != 0 { h = Hasher{ // There may be something more efficient than discarding the existing // memo, but it would require detecting whether types are 'tainted' by // references to type parameters. memo: make(map[types.Type]uint32), // Re-using ptrMap ensures that pointer identity is preserved in this // hasher. ptrMap: h.ptrMap, sigTParams: tparams, } } for i := 0; i < tparams.Len(); i++ { tparam := tparams.At(i) hash += 7 * h.Hash(tparam.Constraint()) } return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results()) case *typeparams.Union: return h.hashUnion(t) case *types.Interface: // Interfaces are identical if they have the same set of methods, with // identical names and types, and they have the same set of type // restrictions. See go/types.identical for more details. var hash uint32 = 9103 // Hash methods. for i, n := 0, t.NumMethods(); i < n; i++ { // Method order is not significant. // Ignore m.Pkg(). m := t.Method(i) hash += 3*hashString(m.Name()) + 5*h.Hash(m.Type()) } // Hash type restrictions. terms, err := typeparams.InterfaceTermSet(t) // if err != nil t has invalid type restrictions. if err == nil { hash += h.hashTermSet(terms) } return hash case *types.Map: return 9109 + 2*h.Hash(t.Key()) + 3*h.Hash(t.Elem()) case *types.Chan: return 9127 + 2*uint32(t.Dir()) + 3*h.Hash(t.Elem()) case *types.Named: hash := h.hashPtr(t.Obj()) targs := typeparams.NamedTypeArgs(t) for i := 0; i < targs.Len(); i++ { targ := targs.At(i) hash += 2 * h.Hash(targ) } return hash case *typeparams.TypeParam: return h.hashTypeParam(t) case *types.Tuple: return h.hashTuple(t) } panic(fmt.Sprintf("%T: %v", t, t)) } func (h Hasher) hashTuple(tuple *types.Tuple) uint32 { // See go/types.identicalTypes for rationale. n := tuple.Len() hash := 9137 + 2*uint32(n) for i := 0; i < n; i++ { hash += 3 * h.Hash(tuple.At(i).Type()) } return hash } func (h Hasher) hashUnion(t *typeparams.Union) uint32 { // Hash type restrictions. terms, err := typeparams.UnionTermSet(t) // if err != nil t has invalid type restrictions. Fall back on a non-zero // hash. if err != nil { return 9151 } return h.hashTermSet(terms) } func (h Hasher) hashTermSet(terms []*typeparams.Term) uint32 { hash := 9157 + 2*uint32(len(terms)) for _, term := range terms { // term order is not significant. termHash := h.Hash(term.Type()) if term.Tilde() { termHash *= 9161 } hash += 3 * termHash } return hash } // hashTypeParam returns a hash of the type parameter t, with a hash value // depending on whether t is contained in h.sigTParams. // // If h.sigTParams is set and contains t, then we are in the process of hashing // a signature, and the hash value of t must depend only on t's index and // constraint: signatures are considered identical modulo type parameter // renaming. To avoid infinite recursion, we only hash the type parameter // index, and rely on types.Identical to handle signatures where constraints // are not identical. // // Otherwise the hash of t depends only on t's pointer identity. func (h Hasher) hashTypeParam(t *typeparams.TypeParam) uint32 { if h.sigTParams != nil { i := t.Index() if i >= 0 && i < h.sigTParams.Len() && t == h.sigTParams.At(i) { return 9173 + 3*uint32(i) } } return h.hashPtr(t.Obj()) } // hashPtr hashes the pointer identity of ptr. It uses h.ptrMap to ensure that // pointers values are not dependent on the GC. func (h Hasher) hashPtr(ptr interface{}) uint32 { if hash, ok := h.ptrMap[ptr]; ok { return hash } hash := uint32(reflect.ValueOf(ptr).Pointer()) h.ptrMap[ptr] = hash return hash }
{ "content_hash": "9cbdc1e4dcad13a8c37d71e79940d610", "timestamp": "", "source": "github", "line_count": 430, "max_line_length": 79, "avg_line_length": 27.683720930232557, "alnum_prop": 0.6614583333333334, "repo_name": "google/syzkaller", "id": "dcc029b8733a87c95af593d7fada2ad6e0219376", "size": "12190", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "vendor/golang.org/x/tools/go/types/typeutil/map.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "9100" }, { "name": "C", "bytes": "448683" }, { "name": "C++", "bytes": "75794" }, { "name": "CSS", "bytes": "3831" }, { "name": "Dockerfile", "bytes": "8250" }, { "name": "Go", "bytes": "3184669" }, { "name": "HTML", "bytes": "32032" }, { "name": "JavaScript", "bytes": "2810" }, { "name": "Makefile", "bytes": "17695" }, { "name": "Python", "bytes": "45845" }, { "name": "Ragel", "bytes": "4743" }, { "name": "Roff", "bytes": "164496" }, { "name": "Shell", "bytes": "49844" }, { "name": "Yacc", "bytes": "6042" } ], "symlink_target": "" }
(function() { /*************************************************************************************/ var ValueTypeHelper = Firecrow.ValueTypeHelper; var FIRECROW_AJAX_PROXY_URL = "http://localhost/Firecrow/proxy/proxy.php"; var fXMLHttpRequest = Firecrow.N_Interpreter.XMLHttpRequest = function(xmlHttpRequestObject, globalObject, codeConstruct) { this.initObject(globalObject, codeConstruct, xmlHttpRequestObject); this.constructor = fXMLHttpRequest; this.name = "XMLHttpRequest"; this.openConstruct = null; this.sendConstruct = null; this.setHeadersConstructs = []; this.addProperty("status", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.implementationObject.status)); this.addProperty("readyState", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, 0), codeConstruct); this.addProperty("responseType", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, ""), codeConstruct); this.addProperty("responseText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, ""), codeConstruct); XMLHttpRequestPrototype.CONST.INTERNAL_PROPERTIES.METHODS.forEach(function(propertyName) { var internalFunction = globalObject.internalExecutor.createInternalFunction(XMLHttpRequest.prototype[propertyName], propertyName, this, true); this[propertyName] = internalFunction; this.addProperty(propertyName, internalFunction, null, false); }, this); this.updateToOpened = function(codeConstruct) { this.addProperty("readyState", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, 1)); }; this.updateToSent = function(codeConstruct) { this.addProperty("readyState", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, 2)); this.addProperty("status", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.status)); this.addProperty("statusText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.statusText)); }; this.updateToLoading = function(codeConstruct) { this.addProperty("readyState", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, 3)); this.addProperty("responseText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.responseText)); this.addProperty("responseType", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.responseType)); this.addProperty("status", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.status)); this.addProperty("statusText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.statusText)); }; this.updateToDone = function(codeConstruct) { this.addProperty("readyState", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, 4)); this.addProperty("responseText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.responseText)); this.addProperty("responseType", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.responseType)); this.addProperty("status", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.status)); this.addProperty("statusText", this.globalObject.internalExecutor.createInternalPrimitiveObject(codeConstruct, this.statusText)) }; this.updateToNext = function() { switch(this.getPropertyValue("readyState").jsValue) { case 1: this.updateToSent(this.sendConstruct); break; case 2: this.updateToLoading(this.sendConstruct); break; case 3: this.updateToDone(this.sendConstruct); break; default: break; } }; }; fXMLHttpRequest.prototype = new Firecrow.N_Interpreter.Object(); var XMLHttpRequestPrototype = Firecrow.N_Interpreter.XMLHttpRequestPrototype = function(globalObject) { this.initObject(globalObject); this.constructor = XMLHttpRequestPrototype; this.name = "XMLHttpRequestPrototype"; XMLHttpRequestPrototype.CONST.INTERNAL_PROPERTIES.METHODS.forEach(function(propertyName) { var internalFunction = globalObject.internalExecutor.createInternalFunction(XMLHttpRequest.prototype[propertyName], propertyName, this, true); this[propertyName] = internalFunction; this.addProperty(propertyName, internalFunction, null, false); }, this); }; fXMLHttpRequest.notifyError = function(message) { alert("XMLHttpRequest - " + message); } XMLHttpRequestPrototype.prototype = new Firecrow.N_Interpreter.Object(); XMLHttpRequestPrototype.CONST = { INTERNAL_PROPERTIES : { METHODS: ["open","setRequestHeader","send", "abort", "getAllResponseHeaders", "getResponseHeader"], PROPERTIES: ["onreadystatechange", "readyState", "response", "responseText", "responseType", "responseXML", "status", "statusText", "timeout", "upload", "withCredentials"] } }; var XMLHttpRequestFunction = Firecrow.N_Interpreter.XMLHttpRequestFunction = function(globalObject) { this.initObject(globalObject); this.addProperty("prototype", globalObject.fcXMLHttpRequestPrototype); this.isInternalFunction = true; this.name = "XMLHttpRequest"; }; XMLHttpRequestFunction.prototype = new Firecrow.N_Interpreter.Object(); Firecrow.N_Interpreter.XMLHttpRequestExecutor = { executeInternalXmlHttpRequestMethod: function(thisObject, functionObject, args, callExpression) { try { if(!ValueTypeHelper.isXMLHttpRequest(thisObject.jsValue)) { this.notifyError("The called on object should be a XMLHttpRequest!"); return; } if(!functionObject.isInternalFunction) { this.notifyError("The function should be internal when executing XMLHttpRequest method!"); return; } var functionObjectValue = functionObject.jsValue; var thisObjectValue = thisObject.jsValue; var functionName = functionObjectValue.name; var fcThisValue = thisObject.iValue; var globalObject = fcThisValue.globalObject; var nativeArgs = globalObject.getJsValues(args); //this.addModification(callExpression); //this.addDependencyToAllModifications(callExpression); switch(functionName) { case "open": this._updateOpenParameters(fcThisValue, nativeArgs, globalObject, callExpression); this._updateNativeOpenArguments(nativeArgs, globalObject); thisObjectValue[functionName].apply(thisObjectValue, nativeArgs); break; case "send": this._updateNativeSendArguments(fcThisValue, nativeArgs); thisObjectValue[functionName].apply(thisObjectValue, nativeArgs); this._updateSendParameters(fcThisValue, callExpression); fcThisValue.async ? this._aggregateEvents(fcThisValue, globalObject, callExpression) : fcThisValue.updateToDone(callExpression); this._createSendDependencies(fcThisValue, globalObject, callExpression); break; case "setRequestHeader": thisObjectValue[functionName].apply(thisObjectValue, nativeArgs); fcThisValue.setHeadersConstructs.push(callExpression); break; case "getAllResponseHeaders": case "getResponseHeader": return globalObject.internalExecutor.createInternalPrimitiveObject(callExpression, thisObjectValue[functionName].apply(thisObjectValue, nativeArgs)); this._createGetResponseHeaderDependencies(fcThisValue, globalObject, callExpression); default: this.notifyError("Unknown method on XMLHttpRequest object: " + functionName); } } catch(e) { debugger; this.notifyError("Error when executing internal XMLHttpRequest method: " + e); } }, _createSendDependencies: function(fcThisValue, globalObject, callExpression) { globalObject.dependencyCreator.createDataDependency(callExpression, fcThisValue.openConstruct, globalObject.getPreciseEvaluationPositionId()); fcThisValue.setHeadersConstructs.forEach(function(construct) { globalObject.dependencyCreator.createDataDependency(callExpression, construct, globalObject.getPreciseEvaluationPositionId()); }); }, _createGetResponseHeaderDependencies: function(fcThisValue, globalObject, callExpression) { globalObject.dependencyCreator.createDataDependency(callExpression, fcThisValue.openConstruct, globalObject.getPreciseEvaluationPositionId()); if(fcThisValue.sendConstruct != null) { globalObject.dependencyCreator.createDataDependency(callExpression, fcThisValue.sendConstruct, globalObject.getPreciseEvaluationPositionId()) } }, _updateNativeOpenArguments: function(nativeArgs, globalObject) { nativeArgs[0] = nativeArgs[0] || "GET"; var url = Firecrow.UriHelper.getAbsoluteUrl(nativeArgs[1], globalObject.browser.url); if(Firecrow.UriHelper.areOnSameDomain(url, Firecrow.getDocument().location.href)) { nativeArgs[1] = url; } else { var requestUrl = Firecrow.UriHelper.getRequestAddress(url); if(nativeArgs[0] == "GET") { var extendedRequest = Firecrow.UriHelper.appendQuery(url, "csurl", requestUrl); nativeArgs[1] = FIRECROW_AJAX_PROXY_URL + "?" + Firecrow.UriHelper.getQuery(extendedRequest); } else { nativeArgs[1] = FIRECROW_AJAX_PROXY_URL; } } nativeArgs[2] = false; //Apply to native object, but change to sync }, _updateNativeSendArguments: function(fcThisValue, nativeArgs) { if(fcThisValue.method != "POST") { return; } if(nativeArgs[0] == null) { nativeArgs[0] = ""; } if(nativeArgs[0] != "") { nativeArgs[0] += "&"; } nativeArgs[0] += "csurl=" + encodeURIComponent(fcThisValue.absoluteUrl); }, _updateOpenParameters: function(fcThisValue, nativeArgs, globalObject, callExpression) { fcThisValue.method = nativeArgs[0] || "GET"; fcThisValue.url = nativeArgs[1] || ""; fcThisValue.absoluteUrl = Firecrow.UriHelper.getAbsoluteUrl(nativeArgs[1], globalObject.browser.url); fcThisValue.async = nativeArgs[2]; fcThisValue.user = nativeArgs[3] || ""; fcThisValue.password = nativeArgs[4] || ""; fcThisValue.updateToOpened(callExpression); fcThisValue.openConstruct = callExpression; }, _updateSendParameters: function(fcThisValue, callExpression) { fcThisValue.readyState = fcThisValue.implementationObject.readyState; fcThisValue.timeout = fcThisValue.implementationObject.timeout; fcThisValue.status = fcThisValue.implementationObject.status; fcThisValue.responseText = fcThisValue.implementationObject.responseText; fcThisValue.response = fcThisValue.implementationObject.response; fcThisValue.responseType = fcThisValue.implementationObject.responseType; fcThisValue.responseXML = fcThisValue.implementationObject.responseXML; fcThisValue.statusText = fcThisValue.implementationObject.statusText; fcThisValue.sendConstruct = callExpression; }, _aggregateEvents: function(fcThisValue, globalObject, callExpression) { for(var i = 0; i < 4; i++) { globalObject.preRegisterAjaxEvent ( fcThisValue, { codeConstruct: callExpression, evaluationPositionId: globalObject.getPreciseEvaluationPositionId() } ); } }, notifyError: function(message) { debugger; fXMLHttpRequest.notifyError(message);} }; /*************************************************************************************/ })();
{ "content_hash": "037cc049a0b07c128dc7b676f61064e5", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 183, "avg_line_length": 49.82835820895522, "alnum_prop": 0.646472966901303, "repo_name": "jomaras/jFirecrow", "id": "4beb97d7b10fe33d6d924c6d9a4aa2b233adf688", "size": "13354", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "interpreter/internals/XMLHttpRequest.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "925642" } ], "symlink_target": "" }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class DiscordUser extends Model { protected $table = "seen_users"; public $incrementing = false; protected $keyType = 'string'; public function getDiscriminatorAttribute($value) { if ($value < 1000) { return "0$value"; } else { return $value; } } }
{ "content_hash": "23c4e914ea21033933400b799ee38d34", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 53, "avg_line_length": 17.17391304347826, "alnum_prop": 0.589873417721519, "repo_name": "mrkirby153/KirBotPanel", "id": "c66907976fd60903267399fa83a584c26f6ce4de", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Models/DiscordUser.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "11280" }, { "name": "JavaScript", "bytes": "5050" }, { "name": "PHP", "bytes": "209070" }, { "name": "Shell", "bytes": "852" }, { "name": "TypeScript", "bytes": "193263" } ], "symlink_target": "" }
 #pragma once #include <aws/codestar-notifications/CodeStarNotifications_EXPORTS.h> #include <aws/codestar-notifications/CodeStarNotificationsRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace CodeStarNotifications { namespace Model { /** */ class AWS_CODESTARNOTIFICATIONS_API DeleteNotificationRuleRequest : public CodeStarNotificationsRequest { public: DeleteNotificationRuleRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DeleteNotificationRule"; } Aws::String SerializePayload() const override; /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline DeleteNotificationRuleRequest& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline DeleteNotificationRuleRequest& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the notification rule you want to * delete.</p> */ inline DeleteNotificationRuleRequest& WithArn(const char* value) { SetArn(value); return *this;} private: Aws::String m_arn; bool m_arnHasBeenSet = false; }; } // namespace Model } // namespace CodeStarNotifications } // namespace Aws
{ "content_hash": "09a9beecd37787d03093167f5d2eb885", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 113, "avg_line_length": 31.443181818181817, "alnum_prop": 0.6729309721720275, "repo_name": "aws/aws-sdk-cpp", "id": "39a316ec793339bee7636be3d47cca72c9aaaf10", "size": "2886", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-codestar-notifications/include/aws/codestar-notifications/model/DeleteNotificationRuleRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
package org.jetbrains.plugins.groovy.lang.completion; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.completion.impl.BetterPrefixMatcher; import com.intellij.codeInsight.completion.impl.CamelHumpMatcher; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.util.registry.Registry; import com.intellij.psi.*; import com.intellij.psi.search.PsiShortNamesCache; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnnotationTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import static com.intellij.patterns.PsiJavaPatterns.psiElement; /** * @author peter */ public class GroovyNoVariantsDelegator extends CompletionContributor { private static boolean suggestMetaAnnotations(CompletionParameters parameters) { PsiElement position = parameters.getPosition(); return psiElement().withParents(GrCodeReferenceElement.class, GrAnnotation.class, GrModifierList.class, GrAnnotationTypeDefinition.class).accepts(position); } @Override public void fillCompletionVariants(final CompletionParameters parameters, CompletionResultSet result) { LinkedHashSet<CompletionResult> plainResults = result.runRemainingContributors(parameters, true); final boolean empty = JavaNoVariantsDelegator.containsOnlyPackages(plainResults) || suggestMetaAnnotations(parameters); if (!empty && parameters.getInvocationCount() == 0) { result.restartCompletionWhenNothingMatches(); } if (empty) { delegate(parameters, result); } else if (Registry.is("ide.completion.show.better.matching.classes")) { if (parameters.getCompletionType() == CompletionType.BASIC && parameters.getInvocationCount() <= 1 && JavaCompletionContributor.mayStartClassName(result) && GroovyCompletionContributor.isClassNamePossible(parameters.getPosition()) && !MapArgumentCompletionProvider.isMapKeyCompletion(parameters) && !GroovySmartCompletionContributor.AFTER_NEW.accepts(parameters.getPosition())) { result = result.withPrefixMatcher(new BetterPrefixMatcher(result.getPrefixMatcher(), BetterPrefixMatcher.getBestMatchingDegree(plainResults))); suggestNonImportedClasses(parameters, result); } } } private static void delegate(CompletionParameters parameters, CompletionResultSet result) { if (parameters.getCompletionType() == CompletionType.BASIC) { if (parameters.getInvocationCount() <= 1 && JavaCompletionContributor.mayStartClassName(result) && GroovyCompletionContributor.isClassNamePossible(parameters.getPosition()) && !MapArgumentCompletionProvider.isMapKeyCompletion(parameters)) { suggestNonImportedClasses(parameters, result); } suggestChainedCalls(parameters, result); } } private static void suggestNonImportedClasses(CompletionParameters parameters, final CompletionResultSet result) { GroovyCompletionContributor.addAllClasses(parameters, new Consumer<LookupElement>() { @Override public void consume(LookupElement element) { JavaPsiClassReferenceElement classElement = element.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); if (classElement != null) { classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); } result.addElement(element); } }, new InheritorsHolder(parameters.getPosition(), result), result.getPrefixMatcher()); } private static void suggestChainedCalls(CompletionParameters parameters, CompletionResultSet result) { PsiElement position = parameters.getPosition(); PsiElement parent = position.getParent(); if (!(parent instanceof GrReferenceElement)) { return; } PsiElement qualifier = ((GrReferenceElement)parent).getQualifier(); if (!(qualifier instanceof GrReferenceElement) || ((GrReferenceElement)qualifier).getQualifier() != null) { return; } PsiElement target = ((GrReferenceElement)qualifier).resolve(); if (target != null && !(target instanceof PsiPackage)) { return; } String fullPrefix = position.getContainingFile().getText().substring(parent.getTextRange().getStartOffset(), parameters.getOffset()); final CompletionResultSet qualifiedCollector = result.withPrefixMatcher(fullPrefix); InheritorsHolder inheritors = new InheritorsHolder(position, result); for (final LookupElement base : suggestQualifierItems(parameters, (GrReferenceElement)qualifier, inheritors)) { final PsiType type = JavaCompletionUtil.getLookupElementType(base); if (type != null && !PsiType.VOID.equals(type)) { GrReferenceElement ref = createMockReference(position, type, base); PsiElement refName = ref.getReferenceNameElement(); assert refName != null; CompletionParameters newParams = parameters.withPosition(refName, refName.getTextRange().getStartOffset()); GroovyCompletionContributor.completeReference(newParams, ref, inheritors, result.getPrefixMatcher(), new Consumer<LookupElement>() { @Override public void consume(LookupElement element) { qualifiedCollector.addElement(new JavaChainLookupElement(base, element) { @Override protected boolean shouldParenthesizeQualifier(PsiFile file, int startOffset, int endOffset) { return false; } }); } }); } } } private static GrReferenceElement createMockReference(final PsiElement place, @NotNull PsiType qualifierType, LookupElement qualifierItem) { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(place.getProject()); if (qualifierItem.getObject() instanceof PsiClass) { return factory .createReferenceExpressionFromText(((PsiClass)qualifierItem.getObject()).getQualifiedName() + ".xxx", place); } return factory.createReferenceExpressionFromText("xxx.xxx", JavaCompletionUtil .createContextWithXxxVariable(place, qualifierType)); } private static Set<LookupElement> suggestQualifierItems(CompletionParameters _parameters, GrReferenceElement qualifier, InheritorsHolder inheritors) { CompletionParameters parameters = _parameters.withPosition(qualifier.getReferenceNameElement(), qualifier.getTextRange().getEndOffset()); String referenceName = qualifier.getReferenceName(); if (referenceName == null) { return Collections.emptySet(); } final PrefixMatcher qMatcher = new CamelHumpMatcher(referenceName); final Set<LookupElement> variants = new LinkedHashSet<LookupElement>(); GroovyCompletionContributor.completeReference(parameters, qualifier, inheritors, qMatcher, new Consumer<LookupElement>() { @Override public void consume(LookupElement element) { if (qMatcher.prefixMatches(element)) { variants.add(element); } } }); for (PsiClass aClass : PsiShortNamesCache.getInstance(qualifier.getProject()).getClassesByName(referenceName, qualifier.getResolveScope())) { variants.add(GroovyCompletionUtil.createClassLookupItem(aClass)); } if (variants.isEmpty()) { GroovyCompletionContributor.addAllClasses(parameters, new Consumer<LookupElement>() { @Override public void consume(LookupElement element) { if (qMatcher.prefixMatches(element)) { variants.add(element); } } }, inheritors, qMatcher); } return variants; } }
{ "content_hash": "4a70c8f381913a5516c0f007f3be8ba8", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 160, "avg_line_length": 46, "alnum_prop": 0.7263497372193024, "repo_name": "lshain-android-source/tools-idea", "id": "7fac754642b55015617e68d0eb68c65f9e977cd1", "size": "8972", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "182" }, { "name": "C", "bytes": "172277" }, { "name": "C#", "bytes": "390" }, { "name": "C++", "bytes": "77776" }, { "name": "CSS", "bytes": "11575" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groovy", "bytes": "1838147" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "117312672" }, { "name": "JavaScript", "bytes": "112" }, { "name": "Objective-C", "bytes": "19631" }, { "name": "Perl", "bytes": "6549" }, { "name": "Python", "bytes": "2787996" }, { "name": "Shell", "bytes": "68540" }, { "name": "XSLT", "bytes": "113531" } ], "symlink_target": "" }
from datetime import datetime from django.test import TestCase from django.contrib.auth.models import User from django.db import IntegrityError from django.core.exceptions import ValidationError from datetime import datetime, timedelta from ..models import Period, Subject from ..testhelper import TestHelper from ..models.model_utils import EtagMismatchException class TestPeriod(TestCase, TestHelper): def setUp(self): self.add(nodes="uio:admin(uioadmin).ifi", subjects=["inf1100"], periods=["old:begins(-2):ends(1)", "looong"], assignments=["assignment1", "assignment2"], assignmentgroups=["g1:examiner(examiner1)", "g2:examiner(examiner2)"]) def test_unique(self): n = Period(parentnode=Subject.objects.get(short_name='inf1100'), short_name='old', long_name='Old', start_time=datetime.now(), end_time=datetime.now()) self.assertRaises(IntegrityError, n.save) def test_etag_update(self): etag = datetime.now() obj = self.inf1100_looong obj.minimum_points = 66 self.assertRaises(EtagMismatchException, obj.etag_update, etag) try: obj.etag_update(etag) except EtagMismatchException as e: # Should not raise exception obj.etag_update(e.etag) obj2 = Period.objects.get(id=obj.id) self.assertEquals(obj2.minimum_points, 66) def test_where_is_admin(self): self.assertEquals(Period.where_is_admin(self.uioadmin).count(), 2) def test_clean(self): self.inf1100_looong.start_time = datetime(2010, 1, 1) self.inf1100_looong.end_time = datetime(2011, 1, 1) self.inf1100_looong.clean() self.inf1100_looong.start_time = datetime(2012, 1, 1) self.assertRaises(ValidationError, self.inf1100_looong.clean) def test_where_is_examiner(self): q = Period.where_is_examiner(self.examiner1).order_by('short_name') self.assertEquals(q.count(), 2) self.assertEquals(q[0].short_name, 'looong') self.assertEquals(q[1].short_name, 'old') # Add on different period self.add_to_path('uio.ifi;inf1010.spring10.oblig1.student1:examiner(examiner1)') self.assertEquals(q.count(), 3) self.assertEquals(q[0].short_name, 'looong') self.assertEquals(q[1].short_name, 'old') self.assertEquals(q[2].short_name, 'spring10') def test_published_where_is_examiner(self): examiner1 = User.objects.get(username='examiner1') self.add_to_path('uio.ifi;inf1010.spring10.oblig1.student1:examiner(examiner1)') q = Period.published_where_is_examiner(examiner1).order_by('short_name') self.assertEquals(q.count(), 3) assignment1010 = self.inf1010_spring10_oblig1_student1.parentnode assignment1010.publishing_time = datetime.now() + timedelta(10) assignment1010.save() self.assertEquals(q.count(), 2)
{ "content_hash": "2e1dcc688318728ae5a73c1e26ec0fae", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 88, "avg_line_length": 41.958333333333336, "alnum_prop": 0.6550810989738497, "repo_name": "vegarang/devilry-django", "id": "7bde64be0bce64428b9052a109c67e7833208315", "size": "3021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "devilry/apps/core/tests/period.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "697906" }, { "name": "Python", "bytes": "931589" } ], "symlink_target": "" }
package ly.kite.payment; /** * Created by deonbotha on 16/02/2014. */ public interface PayPalCardChargeListener { void onChargeSuccess(PayPalCard card, String proofOfPayment); void onError(PayPalCard card, Exception ex); }
{ "content_hash": "3e1a16db97e3f9a9b4b2d8097663c5fe", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 65, "avg_line_length": 26, "alnum_prop": 0.7521367521367521, "repo_name": "bearprada/Android-Print-SDK", "id": "0db66c10bc1beac6f44c571c079dea07b31aa47f", "size": "234", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "KitePrintSDK/src/main/java/ly/kite/payment/PayPalCardChargeListener.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1028746" } ], "symlink_target": "" }
import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) log.debug("KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
{ "content_hash": "77473d628fd2951b21aaac1bf875cd0e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 79, "avg_line_length": 37.59375, "alnum_prop": 0.5286783042394015, "repo_name": "henrysher/kamboo", "id": "da8566d9519c63c7fc7d8d634174c3c850bb3647", "size": "1784", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "kamboo/core.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "5569" }, { "name": "Python", "bytes": "39556" }, { "name": "Shell", "bytes": "5103" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="msapplication-tap-highlight" content="no"> <meta name="description" content="Materialize is a modern responsive CSS framework based on Material Design by Google. "> <title>Themes - Materialize</title> <!-- Favicons--> <link rel="apple-touch-icon-precomposed" href="images/favicon/apple-touch-icon-152x152.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="images/favicon/mstile-144x144.png"> <link rel="icon" href="images/favicon/favicon-32x32.png" sizes="32x32"> <!-- Android 5 Chrome Color--> <meta name="theme-color" content="#EE6E73"> <!-- CSS--> <link href="css/prism.css" rel="stylesheet"> <link href="css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script> window.liveSettings = { api_key: "a0b49b34b93844c38eaee15690d86413", picker: "bottom-right", detectlang: true, dynamic: true, autocollect: true }; </script> <script src="//cdn.transifex.com/live.js"></script> </head> <body class="themes rtl"> <header> <nav class="top-nav"> <div class="container"> <div class="nav-wrapper"> <div class="row"> <div class="col s12 m10 offset-m1"> <h1 class="header">Themes</h1> </div> </div> </div> </div> </nav> <div class="container"><a href="#" data-target="nav-mobile" class="button-collapse top-nav sidenav-trigger full hide-on-large-only"><i class="material-icons">menu</i></a></div> <ul id="nav-mobile" class="sidenav sidenav-fixed"> <li class="logo"><a id="logo-container" href="/" class="brand-logo"> <object id="front-page-logo" type="image/svg+xml" data="res/materialize.svg">Your browser does not support SVG</object></a></li> <li class="search"> <div class="search-wrapper"> <input id="search" placeholder="Search"><i class="material-icons">search</i> <div class="search-results"></div> </div> </li> <li class="bold"><a href="about.html" class="waves-effect waves-teal">About</a></li> <li class="bold"><a href="getting-started.html" class="waves-effect waves-teal">Getting Started</a></li> <li class="no-padding"> <ul class="collapsible collapsible-accordion"> <li class="bold"><a class="collapsible-header waves-effect waves-teal">CSS</a> <div class="collapsible-body"> <ul> <li><a href="color.html">Color</a></li> <li><a href="grid.html">Grid</a></li> <li><a href="helpers.html">Helpers</a></li> <li><a href="media-css.html">Media</a></li> <li><a href="pulse.html">Pulse</a></li> <li><a href="sass.html">Sass</a></li> <li><a href="shadow.html">Shadow</a></li> <li><a href="table.html">Table</a></li> <li><a href="css-transitions.html">Transitions</a></li> <li><a href="typography.html">Typography</a></li> </ul> </div> </li> <li class="bold"><a class="collapsible-header waves-effect waves-teal">Components</a> <div class="collapsible-body"> <ul> <li><a href="badges.html">Badges</a></li> <li><a href="buttons.html">Buttons</a></li> <li><a href="breadcrumbs.html">Breadcrumbs</a></li> <li><a href="cards.html">Cards</a></li> <li><a href="collections.html">Collections</a></li> <li><a href="footer.html">Footer</a></li> <li><a href="icons.html">Icons</a></li> <li><a href="navbar.html">Navbar</a></li> <li><a href="pagination.html">Pagination</a></li> <li><a href="preloader.html">Preloader</a></li> </ul> </div> </li> <li class="bold"><a class="collapsible-header waves-effect waves-teal">JavaScript</a> <div class="collapsible-body"> <ul> <li><a href="carousel.html">Carousel</a></li> <li><a href="collapsible.html">Collapsible</a></li> <li><a href="dropdown.html">Dropdown</a></li> <li><a href="feature-discovery.html">FeatureDiscovery</a></li> <li><a href="media.html">Media</a></li> <li><a href="modals.html">Modals</a></li> <li><a href="parallax.html">Parallax</a></li> <li><a href="pushpin.html">Pushpin</a></li> <li><a href="scrollspy.html">Scrollspy</a></li> <li><a href="sidenav.html">Sidenav</a></li> <li><a href="tabs.html">Tabs</a></li> <li><a href="toasts.html">Toasts</a></li> <li><a href="tooltips.html">Tooltips</a></li> <li><a href="waves.html">Waves</a></li> </ul> </div> </li> <li class="bold"><a class="collapsible-header waves-effect waves-teal">Forms</a> <div class="collapsible-body"> <ul> <li><a href="autocomplete.html">Autocomplete</a></li> <li><a href="checkboxes.html">Checkboxes</a></li> <li><a href="chips.html">Chips</a></li> <li><a href="pickers.html">Pickers</a></li> <li><a href="radio-buttons.html">Radio Buttons</a></li> <li><a href="range.html">Range</a></li> <li><a href="select.html">Select</a></li> <li><a href="switches.html">Switches</a></li> <li><a href="text-inputs.html">Text Inputs</a></li> </ul> </div> </li> </ul> </li> <li class="bold"><a href="mobile.html" class="waves-effect waves-teal">Mobile</a></li> <li class="bold"><a href="showcase.html" class="waves-effect waves-teal">Showcase</a></li> <li class="bold active"><a href="themes.html" class="waves-effect waves-teal">Themes<span class="new badge"></span></a></li> </ul> <div class="patreon-ad"><a href="https://www.patreon.com/materialize" target="_blank" class="waves-effect">Become a Patron</a></div> </header> <main><div class="container"> <div class="row"> <div class="col s12 m10 offset-m1"> <div class="row themes-section"> <div class="col s12 m4"> <h4>Gallery Shopify Theme<span class="new badge"></span></h4> <p class="caption" style="margin-bottom: 0;">Make your products pop with this Shopify Theme and its Google Play Store inspired content transition. Have a more seamless store experience with this powerful ecommerce platform. This theme is in active development and will be maintained.</p> <p style="margin-bottom: 0;"><b>Note: This is a theme made for the Shopify Ecommerce Platform</b></p> <div id='product-component-8655a280051'></div> <script type="text/javascript"> /*<![CDATA[*/ (function () { var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js'; if (window.ShopifyBuy) { if (window.ShopifyBuy.UI) { ShopifyBuyInit(); } else { loadScript(); } } else { loadScript(); } function loadScript() { var script = document.createElement('script'); script.async = true; script.src = scriptURL; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script); script.onload = ShopifyBuyInit; } function ShopifyBuyInit() { var client = ShopifyBuy.buildClient({ domain: 'materialize-themes.myshopify.com', apiKey: '2d9a0b3001fe4fcbe3ba50c42a7df88e', appId: '6', }); ShopifyBuy.UI.onReady(client).then(function (ui) { ui.createComponent('product', { id: [136059551773], node: document.getElementById('product-component-8655a280051'), moneyFormat: '%24%7B%7Bamount%7D%7D', options: { "product": { "buttonDestination": "checkout", "variantId": "all", "width": "240px", "contents": { "img": false, "imgWithCarousel": false, "title": false, "variantTitle": false, "price": false, "description": false, "buttonWithQuantity": false, "quantity": false }, "text": { "button": "BUY $49" }, "styles": { "product": { "text-align": "left", "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0", "margin-bottom": "50px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" }, "title": { "font-size": "26px" }, "price": { "font-size": "18px" }, "compareAt": { "font-size": "15px" } } }, "cart": { "contents": { "button": true }, "styles": { "button": { "border-radius": "2px" }, "footer": { "background-color": "#ffffff" } } }, "modalProduct": { "contents": { "img": false, "imgWithCarousel": true, "variantTitle": false, "buttonWithQuantity": true, "button": false, "quantity": false }, "styles": { "product": { "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0px", "margin-bottom": "0px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" } } }, "productSet": { "styles": { "products": { "@media (min-width: 601px)": { "margin-left": "-20px" } } } } } }); }); } })(); /*]]>*/ </script> <a class="shopify-btn" target="_blank" href="https://materialize-shopify-themes.myshopify.com/">DEMO</a> </div> <div class="col s12 m7 offset-m1"> <img class="theme-preview" src="https://s1.postimg.org/53rni1cvbj/gallery-shopify.png" alt=""> </div> </div> <div class="row themes-section right-aligned"> <div class="col s12 m4 offset-m1"> <h4>Startup</h4> <p class="caption" style="margin-bottom: 0;">Startup is a perfect theme for showcasing your new app, company or project. With the help of GSAP and ScrollMagic, create unique scrolling experiences that will keep users engaged.</p> <p style="margin-bottom: 0;"><b>Note: This is a static HTML template</b></p> <div id='product-component-7b7b0511630'></div> <script type="text/javascript"> /*<![CDATA[*/ (function () { var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js'; if (window.ShopifyBuy) { if (window.ShopifyBuy.UI) { ShopifyBuyInit(); } else { loadScript(); } } else { loadScript(); } function loadScript() { var script = document.createElement('script'); script.async = true; script.src = scriptURL; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script); script.onload = ShopifyBuyInit; } function ShopifyBuyInit() { var client = ShopifyBuy.buildClient({ domain: 'materialize-themes.myshopify.com', apiKey: '2d9a0b3001fe4fcbe3ba50c42a7df88e', appId: '6', }); ShopifyBuy.UI.onReady(client).then(function (ui) { ui.createComponent('product', { id: [9462627457], node: document.getElementById('product-component-7b7b0511630'), moneyFormat: '%24%7B%7Bamount%7D%7D', options: { "product": { "buttonDestination": "checkout", "variantId": "all", "width": "240px", "contents": { "img": false, "imgWithCarousel": false, "title": false, "variantTitle": false, "price": false, "description": false, "buttonWithQuantity": false, "quantity": false }, "text": { "button": "BUY 29$" }, "styles": { "product": { "text-align": "left", "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0", "margin-bottom": "50px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" }, "title": { "font-size": "26px" }, "price": { "font-size": "18px" }, "compareAt": { "font-size": "15px" } } }, "cart": { "contents": { "button": true }, "styles": { "button": { "border-radius": "2px" }, "footer": { "background-color": "#ffffff" } } }, "modalProduct": { "contents": { "img": false, "imgWithCarousel": true, "variantTitle": false, "buttonWithQuantity": true, "button": false, "quantity": false }, "styles": { "product": { "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0px", "margin-bottom": "0px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" } } }, "productSet": { "styles": { "products": { "@media (min-width: 601px)": { "margin-left": "-20px" } } } } } }); }); } })(); /*]]>*/ </script> <a class="shopify-btn" target="_blank" href="https://themes.materializecss.com/pages/startup-horizontal-half.html">DEMO</a> </div> <div class="col s12 m7"> <img class="theme-preview" src="https://s14.postimg.org/sai9xfjrl/materialize.png" alt=""> </div> </div> <div class="row themes-section"> <div class="col s12 m4"> <h4>Gallery</h4> <p class="caption" style="margin-bottom: 0;">This theme is perfect for Portfolio, Blogs, and Stores with its Google Play Store inspired content transition. This theme is in active development and will have more features and styles added to it in the future.</p> <p style="margin-bottom: 0;"><b>Note: This is a static HTML template</b></p> <div id='product-component-f979385da90'></div> <script type="text/javascript"> /*<![CDATA[*/ (function () { var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js'; if (window.ShopifyBuy) { if (window.ShopifyBuy.UI) { ShopifyBuyInit(); } else { loadScript(); } } else { loadScript(); } function loadScript() { var script = document.createElement('script'); script.async = true; script.src = scriptURL; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script); script.onload = ShopifyBuyInit; } function ShopifyBuyInit() { var client = ShopifyBuy.buildClient({ domain: 'materialize-themes.myshopify.com', apiKey: '2d9a0b3001fe4fcbe3ba50c42a7df88e', appId: '6', }); ShopifyBuy.UI.onReady(client).then(function (ui) { ui.createComponent('product', { id: [8831109057], node: document.getElementById('product-component-f979385da90'), moneyFormat: '%24%7B%7Bamount%7D%7D', options: { "product": { "buttonDestination": "checkout", "variantId": "all", "width": "240px", "contents": { "img": false, "title": false, "variantTitle": false, "price": false, "description": false, "buttonWithQuantity": false, "quantity": false }, "text": { "button": "BUY $19" }, "styles": { "product": { "text-align": "left", "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0", "margin-bottom": "50px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" }, "title": { "font-size": "26px" }, "price": { "font-size": "18px" }, "compareAt": { "font-size": "15px" } } }, "cart": { "contents": { "button": true }, "styles": { "button": { "border-radius": "2px" }, "footer": { "background-color": "#ffffff" } } }, "modalProduct": { "contents": { "variantTitle": false, "buttonWithQuantity": true, "button": false, "quantity": false }, "styles": { "product": { "@media (min-width: 601px)": { "max-width": "100%", "margin-left": "0px", "margin-bottom": "0px" } }, "button": { "padding-left": "20px", "padding-right": "20px", "border-radius": "2px" } } }, "productSet": { "styles": { "products": { "@media (min-width: 601px)": { "margin-left": "-20px" } } } } } }); }); } })(); /*]]>*/ </script> <a class="shopify-btn" target="_blank" href="https://themes.materializecss.com/pages/demo">DEMO</a> </div> <div class="col s12 m7 offset-m1"> <img class="theme-preview" src="https://s23.postimg.org/9g7ajckrf/thunder.png" alt=""> </div> </div> </div> </div> </div> <!-- End Container --> <div class="themes-banner"> <div class="container"> <div class="row"> <div class="col s12 m10 offset-m1"> <p>All themes come with active support. Send your questions and concerns to <a href="mailto:materializethemes@gmail.com?Subject=Theme%20support" target="_top">MaterializeThemes</a></p> <p>All themes are under the Personal Use License meaning you can use and modify these themes for personal and client projects. You cannot redistribute or resell these themes in any way.</p> </div> </div> </div> </div> </main> <footer class="page-footer docs-footer"> <div class="container"> <div class="row" style="margin-bottom: 0;"> <div class="col s12 m10 offset-m1"> <div class="row"> <div class="col l4 s12"> <h5>Help Materialize Grow</h5> <p class="grey-text text-darken-2">We hope you have enjoyed using Materialize and if you feel like it has helped you out and want to support the team you can help us by donating or backing us on Patreon. Any amount would help support and continue development on this project and is greatly appreciated.</p> <a class="btn waves-effect waves-light red lighten-2" href="/support-us.html">Support Us</a> </div> <div class="col l4 s12"> <h5>Join the Discussion</h5> <p class="grey-text text-darken-2">We have a Gitter chat room set up where you can talk directly with us. Come in and discuss new features, future goals, general problems or questions, or anything else you can think of.</p> <a class="btn waves-effect waves-light red lighten-2" target="_blank" href="https://gitter.im/Dogfalo/materialize">Chat</a> </div> <div class="col l4 s12" style="overflow: hidden;"> <h5>Connect</h5> <iframe src="https://ghbtns.com/github-btn.html?user=dogfalo&repo=materialize&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe> <br> <a href="https://twitter.com/MaterializeCSS" class="twitter-follow-button" data-show-count="true" data-size="large" data-dnt="true">Follow @MaterializeCSS</a> <br> <div class="g-follow" data-annotation="bubble" data-height="24" data-href="https://plus.google.com/108619793845925798422" data-rel="publisher"></div> </div> </div> <div class="footer-copyright"> © 2014-2017 Materialize, All rights reserved. <a class="grey-text text-darken-1 right" href="https://github.com/Dogfalo/materialize/blob/master/LICENSE">MIT License</a> </div> </div> </div> </div> </footer> <!-- Scripts--> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script>if (!window.jQuery) { document.write('<script src="bin/jquery-3.2.1.min.js"><\/script>'); } </script> <script src="js/jquery.timeago.min.js"></script> <script src="js/prism.js"></script> <script src="jade/lunr.min.js"></script> <script src="jade/search.js"></script> <script src="bin/materialize.js"></script> <script src="js/init.js"></script> <!-- Twitter Button --> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <!-- Google Plus Button--> <script src="https://apis.google.com/js/platform.js" async defer></script> <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-56218128-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> </body> </html>
{ "content_hash": "b79f4c2b497be2e1563fffdb0fb7f504", "timestamp": "", "source": "github", "line_count": 651, "max_line_length": 322, "avg_line_length": 36.9815668202765, "alnum_prop": 0.5139771547248183, "repo_name": "MahdiMajidzadeh/materialize-rtl", "id": "79180b7488ab0fd98cc93fed3383c1fc663d1b8f", "size": "24076", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "themes.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "183954" }, { "name": "JavaScript", "bytes": "452818" }, { "name": "Pug", "bytes": "24063" }, { "name": "SCSS", "bytes": "144104" } ], "symlink_target": "" }
ctypes test ------------- note: `ctypes.CDLL('')` loads from the current process address space, TODO what is the C name of C++ `hello_world`? even when defined with extern, which makes the function compatible, it fails to be exported here, or at least ctypes is unable to reach it using `ctypes.CDLL('')` @embed ```python import ctypes def run_test(): print 'cpython: running test...' lib = ctypes.CDLL('') print 'ctypes lib', lib #lib.hello_world() if not hasattr(lib, 'hello_world'): print 'hello_world C function missing' hw = getattr(lib, 'hello_world') ## crashes here print hw #hw.restype = ctypes.. #hw.argtypes = tuple(...) print 'test OK' ``` Build Options ------------- * @link:python2.7 * @include:/usr/include/python2.7 ```rusthon #backend:c++ import cpython with extern(): def hello_world(): print 'hello world' def main(): state = cpython.initalize() with gil: cpython.run_test() cpython.finalize(state) ```
{ "content_hash": "1ba220fc3ed48cdf1d164b985fdc2f06", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 76, "avg_line_length": 19.833333333333332, "alnum_prop": 0.6712184873949579, "repo_name": "rootfs/Rusthon", "id": "9ea1fbad7d6f43b68c4be4ebf710b7aa6b1c2038", "size": "952", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "examples/cpython_ctypes.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "23667" }, { "name": "HTML", "bytes": "44433" }, { "name": "Perl", "bytes": "66040" }, { "name": "Python", "bytes": "360782" }, { "name": "Shell", "bytes": "1033" } ], "symlink_target": "" }
package com.baseframe.common.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * ClassName: Authority <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * date: 2017年10月17日 下午12:06:36 <br/> * 权限注解 * @author Jin.He (mailto:hejin@primeton.com) * @version */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Authority { String opCode(); String opName(); int opSeq() default 1; }
{ "content_hash": "69a63c095f85bf96c1c3e6f98eb1f0e2", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 45, "avg_line_length": 22.666666666666668, "alnum_prop": 0.6977124183006536, "repo_name": "hejingit/Skybird-WorkSpace", "id": "f4f4f45b1f0d12eb4e4bfd5887cfc4b106cc9a85", "size": "634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "baseframe/src/main/java/com/baseframe/common/annotation/Authority.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "972" }, { "name": "CSS", "bytes": "4022330" }, { "name": "HTML", "bytes": "646857" }, { "name": "Java", "bytes": "2251042" }, { "name": "JavaScript", "bytes": "10770310" }, { "name": "PLpgSQL", "bytes": "171522" }, { "name": "Ruby", "bytes": "1549" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Wed Mar 30 21:34:44 CST 2011 --> <TITLE> Uses of Package org.apache.hadoop.examples.terasort (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API) </TITLE> <META NAME="date" CONTENT="2011-03-30"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.apache.hadoop.examples.terasort (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/examples/terasort/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.apache.hadoop.examples.terasort</B></H2> </CENTER> No usage of org.apache.hadoop.examples.terasort <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/examples/terasort/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> This release is based on the Facebook's version of Hadoop.<br>Copyright &copy; 2009 The Apache Software Foundation. </BODY> </HTML>
{ "content_hash": "9f9a9404c2e050ed0410acfea05f4fee", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 196, "avg_line_length": 41.49305555555556, "alnum_prop": 0.6235983263598326, "repo_name": "submergerock/avatar-hadoop", "id": "b0171ed03625e4a5db2f2f576704c18dde845d81", "size": "5975", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "build/hadoop-0.20.1-dev/docs/api/org/apache/hadoop/examples/terasort/package-use.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "612208" }, { "name": "C++", "bytes": "761828" }, { "name": "CSS", "bytes": "193290" }, { "name": "Erlang", "bytes": "88936" }, { "name": "Java", "bytes": "25500555" }, { "name": "JavaScript", "bytes": "142545" }, { "name": "Objective-C", "bytes": "236546" }, { "name": "PHP", "bytes": "510600" }, { "name": "Perl", "bytes": "389970" }, { "name": "Python", "bytes": "2637563" }, { "name": "Ruby", "bytes": "57003" }, { "name": "Shell", "bytes": "4340242" }, { "name": "Smalltalk", "bytes": "113124" }, { "name": "XSLT", "bytes": "456945" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Intl\Intl; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class CurrencyType extends AbstractType { /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'choices' => Intl::getCurrencyBundle()->getCurrencyNames(), )); } /** * {@inheritdoc} */ public function getParent() { return 'choice'; } /** * {@inheritdoc} */ public function getName() { return 'currency'; } }
{ "content_hash": "54bd1d6ff8b4e35c3e4643091ff43228", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 73, "avg_line_length": 19.57894736842105, "alnum_prop": 0.5860215053763441, "repo_name": "elias63/e_institut", "id": "0ce923f0ee2fcf1afb51faecfa448bbf2ed4e0da", "size": "980", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/Type/CurrencyType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "1294408" }, { "name": "CSS", "bytes": "1923544" }, { "name": "JavaScript", "bytes": "6404232" }, { "name": "PHP", "bytes": "1054161" }, { "name": "Python", "bytes": "176744" } ], "symlink_target": "" }
<?php /** * ALIPAY API: alipay.offline.market.mcomment.query request * * @author auto create * @since 1.0, 2016-06-13 20:25:02 */ class AlipayOfflineMarketMcommentQueryRequest { /** * 查询交易评价信息 **/ private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; private $returnUrl; private $needEncrypt=false; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.offline.market.mcomment.query"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function setReturnUrl($returnUrl) { $this->returnUrl=$returnUrl; } public function getReturnUrl() { return $this->returnUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } public function setNeedEncrypt($needEncrypt) { $this->needEncrypt=$needEncrypt; } public function getNeedEncrypt() { return $this->needEncrypt; } }
{ "content_hash": "8333a715406e168d8f5c6d0430de5b69", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 59, "avg_line_length": 16.050847457627118, "alnum_prop": 0.6953537486800423, "repo_name": "sunxguo/aewebapp", "id": "fa0875ee4a4d844f7721f49e58edce326efb67fc", "size": "1910", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "application/libraries/alipay/aop/request/AlipayOfflineMarketMcommentQueryRequest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "32778" }, { "name": "ApacheConf", "bytes": "402" }, { "name": "C#", "bytes": "16603" }, { "name": "CSS", "bytes": "681786" }, { "name": "HTML", "bytes": "1642798" }, { "name": "Java", "bytes": "138935" }, { "name": "JavaScript", "bytes": "5870048" }, { "name": "PHP", "bytes": "3997582" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.csgroup_platzigram2.mora.platzigramv2.LoginActivity" android:background="@color/colorPrimary"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="1"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="0.6"> <ImageView android:id="@+id/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@drawable/platzigram"> </ImageView> </RelativeLayout> <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="0.4" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/EditTextWhite"> <!--android:theme="@style/EditTextWhite"--> <android.support.design.widget.TextInputEditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_username" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/EditTextWhite"> <android.support.design.widget.TextInputEditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_password" android:inputType="textPassword" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/text_button_login" android:theme="@style/RaisedButtonDark" android:onClick="goHome" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/donHaveAccount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dont_have_account" android:textColor="@android:color/white" android:textStyle="bold" android:textSize="@dimen/textsize_dont_have_account"> </TextView> <TextView android:id="@+id/createHere" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/white" android:text="@string/create_here" android:textStyle="bold" android:textSize="@dimen/textsize_dont_have_account" android:layout_toRightOf="@id/donHaveAccount" android:onClick="goCreateAccount"> </TextView> </RelativeLayout> </LinearLayout> </ScrollView> </LinearLayout> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "8f339603809cc7647cd2219692a1f71b", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 77, "avg_line_length": 46.26470588235294, "alnum_prop": 0.5350709896164442, "repo_name": "DanielMoraCSG/gramplatzi", "id": "e7632ecacd5b9abca8e691a40b577b5e34e7ffa3", "size": "4719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_login.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "8879" } ], "symlink_target": "" }
namespace { struct RunState { RunState(base::MessagePump::Delegate* delegate, int run_depth) : delegate(delegate), run_depth(run_depth), should_quit(false) { } base::MessagePump::Delegate* delegate; // Used to count how many Run() invocations are on the stack. int run_depth; // Used to flag that the current Run() invocation should return ASAP. bool should_quit; }; RunState* g_state = NULL; // A singleton WaitableEvent wrapper so we avoid a busy loop in // MessagePumpForUIStub. Other platforms use the native event loop which blocks // when there are no pending messages. class Waitable { public: static Waitable* GetInstance() { return base::Singleton<Waitable>::get(); } // Signals that there are more work to do. void Signal() { waitable_event_.Signal(); } // Blocks until more work is scheduled. void Block() { waitable_event_.Wait(); } void Quit() { g_state->should_quit = true; Signal(); } private: friend struct base::DefaultSingletonTraits<Waitable>; Waitable() : waitable_event_(false, false) { } base::WaitableEvent waitable_event_; DISALLOW_COPY_AND_ASSIGN(Waitable); }; // The MessagePumpForUI implementation for test purpose. class MessagePumpForUIStub : public base::MessagePumpForUI { ~MessagePumpForUIStub() override {} void Start(base::MessagePump::Delegate* delegate) override { NOTREACHED() << "The Start() method shouldn't be called in test, using" " Run() method should be used."; } void Run(base::MessagePump::Delegate* delegate) override { // The following was based on message_pump_glib.cc, except we're using a // WaitableEvent since there are no native message loop to use. RunState state(delegate, g_state ? g_state->run_depth + 1 : 1); RunState* previous_state = g_state; g_state = &state; bool more_work_is_plausible = true; for (;;) { if (!more_work_is_plausible) { Waitable::GetInstance()->Block(); if (g_state->should_quit) break; } more_work_is_plausible = g_state->delegate->DoWork(); if (g_state->should_quit) break; base::TimeTicks delayed_work_time; more_work_is_plausible |= g_state->delegate->DoDelayedWork(&delayed_work_time); if (g_state->should_quit) break; if (more_work_is_plausible) continue; more_work_is_plausible = g_state->delegate->DoIdleWork(); if (g_state->should_quit) break; more_work_is_plausible |= !delayed_work_time.is_null(); } g_state = previous_state; } void Quit() override { Waitable::GetInstance()->Quit(); } void ScheduleWork() override { Waitable::GetInstance()->Signal(); } void ScheduleDelayedWork(const base::TimeTicks& delayed_work_time) override { Waitable::GetInstance()->Signal(); } }; scoped_ptr<base::MessagePump> CreateMessagePumpForUIStub() { return scoped_ptr<base::MessagePump>(new MessagePumpForUIStub()); }; // Provides the test path for DIR_MODULE and DIR_ANDROID_APP_DATA. bool GetTestProviderPath(int key, base::FilePath* result) { switch (key) { case base::DIR_ANDROID_APP_DATA: { // For tests, app data is put in external storage. return base::android::GetExternalStorageDirectory(result); } default: return false; } } void InitPathProvider(int key) { base::FilePath path; // If failed to override the key, that means the way has not been registered. if (GetTestProviderPath(key, &path) && !PathService::Override(key, path)) PathService::RegisterProvider(&GetTestProviderPath, key, key + 1); } } // namespace namespace base { void InitAndroidTestLogging() { logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; logging::InitLogging(settings); // To view log output with IDs and timestamps use "adb logcat -v threadtime". logging::SetLogItems(false, // Process ID false, // Thread ID false, // Timestamp false); // Tick count } void InitAndroidTestPaths() { InitPathProvider(DIR_MODULE); InitPathProvider(DIR_ANDROID_APP_DATA); } void InitAndroidTestMessageLoop() { if (!MessageLoop::InitMessagePumpForUIFactory(&CreateMessagePumpForUIStub)) LOG(INFO) << "MessagePumpForUIFactory already set, unable to override."; } void InitAndroidTest() { InitAndroidTestLogging(); InitAndroidTestPaths(); InitAndroidTestMessageLoop(); } } // namespace base
{ "content_hash": "3b610224ad7ea00d836ff87b7c3e3380", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 79, "avg_line_length": 27.518072289156628, "alnum_prop": 0.667031523642732, "repo_name": "joone/chromium-crosswalk", "id": "a8cadec9c1fe9d395ddf2b6dbcacde54937060fb", "size": "5113", "binary": false, "copies": "11", "ref": "refs/heads/2016.04.css-round-display-edtior-draft-1", "path": "base/test/test_support_android.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
{% extends "base.html" %} {% load Kraggne_tags contentblocks %} {% block page.body %} {% containeur page.slug %} {% include "Kraggne/pagination.inc.html" %} <div class="contentblocks containeur"> <div class="contentblocks object"> {% for object in object_list %} {% try_display object %} {% endfor %} </div> </div> {% include "Kraggne/pagination.inc.html" %} {% endblock %}
{ "content_hash": "26930f0ea401c16d7afd94d8d02903a8", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 43, "avg_line_length": 27.2, "alnum_prop": 0.6151960784313726, "repo_name": "Krozark/Kraggne", "id": "233269a6e8094c7e5f346da47743bd306833a209", "size": "408", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Kraggne/templates/Kraggne/genericListPage.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "30807" }, { "name": "HTML", "bytes": "21673" }, { "name": "JavaScript", "bytes": "161130" }, { "name": "Python", "bytes": "115072" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0"> <App xmlns="" ProductID="{8e6e4673-8a0d-42bc-87fc-9fe2d296833d}" Title="PerformanceMeasuring" RuntimeType="XNA" Version="1.0.0.0" Genre="Apps.Normal" Author="" Description="" Publisher=""> <IconPath IsRelative="true" IsResource="false"></IconPath> <Capabilities> <Capability Name="ID_CAP_NETWORKING" /> <Capability Name="ID_CAP_LOCATION" /> <Capability Name="ID_CAP_SENSORS" /> <Capability Name="ID_CAP_MICROPHONE" /> <Capability Name="ID_CAP_MEDIALIB" /> <Capability Name="ID_CAP_GAMERSERVICES" /> <Capability Name="ID_CAP_PHONEDIALER" /> <Capability Name="ID_CAP_PUSH_NOTIFICATION" /> <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" /> <Capability Name="ID_CAP_IDENTITY_USER" /> <Capability Name="ID_CAP_IDENTITY_DEVICE" /> </Capabilities> <Tasks> <DefaultTask Name="_default"/> </Tasks> <Tokens> <PrimaryToken TokenID="PerformanceMeasuringToken" TaskName="_default"> <TemplateType5> <BackgroundImageURI IsRelative="true" IsResource="false"></BackgroundImageURI> <Count>0</Count> <Title></Title> </TemplateType5> </PrimaryToken> </Tokens> </App> </Deployment>
{ "content_hash": "03c7ff5f2438a1921b59013749d478df", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 190, "avg_line_length": 42.71875, "alnum_prop": 0.653986832479883, "repo_name": "DDReaper/XNAGameStudio", "id": "7bf0461b3c62547d6c3a0671941449e52f0c4b70", "size": "1367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Samples/PerformanceMeasuringSample_4_0/PerformanceMeasuring/PerformanceMeasuring/Properties/WMAppManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "77207" } ], "symlink_target": "" }
A simple Javascript-based proof-of-concept for analyzing family relationships. ## Demo [http://bencrowder.net/sandbox/gen/family-analysis/](http://bencrowder.net/sandbox/gen/family-analysis/)
{ "content_hash": "b95bfab98686205a2a6a54a70e924bfa", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 104, "avg_line_length": 38.8, "alnum_prop": 0.788659793814433, "repo_name": "bencrowder/family-analysis", "id": "5dadcf0f6022bd8343787ce739ad401980285a6d", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "19785" } ], "symlink_target": "" }
package org.protobee.session; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({HandshakeBootstrapperTest.class}) public class SessionTestSuite { }
{ "content_hash": "10523d34f0896803d41fd7945bd05339", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 48, "avg_line_length": 25.7, "alnum_prop": 0.7859922178988327, "repo_name": "dmurph/protobee", "id": "7f305b484b0213d25bd6ffd995ca38806be3a462", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core-tests/src/main/java/org/protobee/session/SessionTestSuite.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "815452" }, { "name": "Protocol Buffer", "bytes": "962" } ], "symlink_target": "" }
A simple authentication system for Codeigniter 3. 1. Set up Auth for Codeigniter 3 from complete system. 2. Prepping your system 3. Prepping Codeigniter for your system (new or complete system) 4. Integrating auth into your pages. INTRODUCTION<br /> There are two versions of the mcl-Auth system, one each for the two versions of Codeigniter. mcl-Auth has two variants in each version: a bare system to be copied into an existing Codeigniter install, or a complete system that needs only a couple of config changes to run. These note describe the version for Codeigniter 3. There are several watch-points that need to be addressed when moving from CI2 to CI3. Only two are relevant to this project. The major one is that all controllers and models need UCFirst() on the filename and class names. The second is that the CI sessions are now based on the PHP session rather than a separate implementation. Instead of session_start() at the beginning of each controller that uses sessions, the session is started when the class is invoked (in my case by autoload). ASSUMPTIONS<br /> I am going to assume that you are using an apache server on test server. I always use a separate server to handle website development since any webserver running on a development machine seems to rum so much slower. If you can’t run your own server locally, sign up for a 30-day free trial at Microsoft Azure and set up a website there. SETTING UP MCL-AUTH COMPLETE SYSTEM.<br /> There are three steps to getting the system up and running. We need a database to hold the user and group tables. If you don’t have a database server or webserver, set up a WAMP system on your dev machine. First: Create or use an existing database and run the SQL code in the file mysql.sql. This creates and populates two tables with two groups (Please don’t delete them, you’ll break the mcl-Auth system) and one admin user. Second: In your IDE (I use Netbeans) open application/config/autoload.php. In the Libraries section add database, form validation and session. In the helpers section add url and form. The line should look like this: ``` $autoload['libraries'] = array('database','form_validation','session'); $autoload['helper'] = array('url','form'); ``` Save and close the file. Open config.php from the same folder. In the base_url section type in your domain name for the test server. The line should look similar to: ``` $config['base_url'] = 'http://www.domainname.com/'; ``` Note the final slash is needed. Check the Index_page entry has an empty string. If it shows index.php, remove it. Further down the page find the encryption_key entry. Obtain a Codeigniter enctyption key from the internet and paste it into the entry. Save the file and close it. Now open the database.php file in the same directory. Type in the username for your database, the user’s password and the database name. Third: Check you have an .htaccess file in the project root. The complete system has a file but it may not suit your system. The only way to find out is to try it. Upload the entire project to your server and open a browser and go to your site. You should get my home page. You have a working website you can now adapt to your own uses. To use the login and admin side of things, see my later notes. GETTING MCL-AUTH INVOLVED<br /> First we need to be able to login. We are going to add an if-then statement that will either display Login or Logout depending on whether a user is logged in. In the header.php file, type in the following after the ContactUs list item. ``` <?php if($this->session->userdata('loggedin')){ echo "<li><a href="; echo base_url('/admin/login/logout'). ">Logout</a></li>"; }else{ echo "<li><a href="; echo base_url('/admin/login/login'). ">Login</a></li>"; } ?> ``` Save the file and refresh the browser. We now have a Login item on the right of the menu. Click it. The mcl-Auth login page should appear. The user’s name is admin and the password is Pa$$w@rd. When you have logged on, the Login changes to Logout. Click Logout. That is the login process working. As admins we need to be able to manage our user and group accounts. What we need is another menu item. We will set up that menu item to appear only when a member of the admin group is logged in. In between the Home and Example menu items insert the following code: ``` <?php if($this->session->userdata('loggedin') && $this->session->userdata('group') == '1'){ echo "<li><a href="; echo base_url('/admin/admin_view'). ">Admin</a></li>"; } ?> ``` This code checks if the session-group variable is set and that it is set to ‘1’ for the admin group. If both are true, the Admin menu link is displayed. We have to check if the group variable exists because when no one is logged in, it doesn’t exist and the group=1 check will through a php error. Login as admin. The Admin menu item is there, click it. We can now work with our users and groups accounts. Create a new user. All data items are required. The loginname must be unique, the email should be in lower case, the password at least 8 characters long. Notice the user group is pre-selected. You need a conscious decision and action to create a admin user. Similarly, all new users and groups are not activated. Once created you need to activate the user or group. I haven’t added these function to the user or group listing because I want the admin to make a conscious decision and act on it to activate or deactivate a user. Otherwise someone could accidentally deactivate a user in the user list. Adding security to your own controllers. I could have used the MY_Controller technique to enforce security for new controllers but stuck with modifying each one individually for the moment. Create a new controller called Secrets.php and add the following text to it: ``` <?php class Secret extends CI_Controller{ function __construct() { parent::__construct(); session_start(); if (!$this->session->userdata('loggedin')) { redirect('Location:admin/login'); } else { if ($this->session->userdata('group') != '1') { redirect('Location:/admin/login'); } } } function index() { $data['title'] = 'secrets/secret_hoard'; $this->load->view('start', $data); } } ``` Now we need a view to display our secrets. Create a new folder in the views folder called secrets and inside that, a file called secret_hoard.php. Type in something secret only admins should read. Save both files and add the word secret to the address bar. You should have www.yourdomain.com/secret Press Enter and your secret should be revealed (if you’re logged in as admin) If you didn’t create a new user a little earlier, create one now, making sure they are in the Users group not Admin. Login as that user and try to access the secret page. Hoho straight to the login page. But still logged in, look at the Logout button in the menu. I have chosen to put people back to the login page simply for convenience. You will need your own Access Denied landing page if you want to change that. Ok, you have a working system, Good luck.
{ "content_hash": "3cbb1c9ae1a49367cbf4b7aebaeec8af", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 489, "avg_line_length": 71.57692307692308, "alnum_prop": 0.7172219236969372, "repo_name": "microchipthefirst/mclAuth-with-CI3", "id": "76ab4e8e496e630cee4b9c2d9378cac8fdd75b03", "size": "7468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "385" }, { "name": "CSS", "bytes": "30303" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "441180" }, { "name": "PHP", "bytes": "1814278" } ], "symlink_target": "" }
#ifndef _LINUX_FIEMAP_H #define _LINUX_FIEMAP_H #include <linux/types.h> struct fiemap_extent { __u64 fe_logical; /* logical offset in bytes for the start of * the extent from the beginning of the file */ __u64 fe_physical; /* physical offset in bytes for the start * of the extent from the beginning of the disk */ __u64 fe_length; /* length in bytes for this extent */ __u64 fe_reserved64[2]; __u32 fe_flags; /* FIEMAP_EXTENT_* flags for this extent */ __u32 fe_reserved[3]; }; struct fiemap { __u64 fm_start; /* logical offset (inclusive) at * which to start mapping (in) */ __u64 fm_length; /* logical length of mapping which * userspace wants (in) */ __u32 fm_flags; /* FIEMAP_FLAG_* flags for request (in/out) */ __u32 fm_mapped_extents;/* number of extents that were mapped (out) */ __u32 fm_extent_count; /* size of fm_extents array (in) */ __u32 fm_reserved; struct fiemap_extent fm_extents[0]; /* array of mapped extents (out) */ }; #define FIEMAP_MAX_OFFSET (~0ULL) #define FIEMAP_FLAG_SYNC 0x00000001 /* sync file data before map */ #define FIEMAP_FLAG_XATTR 0x00000002 /* map extended attribute tree */ #define FIEMAP_FLAGS_COMPAT (FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR) #define FIEMAP_EXTENT_LAST 0x00000001 /* Last extent in file. */ #define FIEMAP_EXTENT_UNKNOWN 0x00000002 /* Data location unknown. */ #define FIEMAP_EXTENT_DELALLOC 0x00000004 /* Location still pending. * Sets EXTENT_UNKNOWN. */ #define FIEMAP_EXTENT_ENCODED 0x00000008 /* Data can not be read * while fs is unmounted */ #define FIEMAP_EXTENT_DATA_ENCRYPTED 0x00000080 /* Data is encrypted by fs. * Sets EXTENT_NO_BYPASS. */ #define FIEMAP_EXTENT_NOT_ALIGNED 0x00000100 /* Extent offsets may not be * block aligned. */ #define FIEMAP_EXTENT_DATA_INLINE 0x00000200 /* Data mixed with metadata. * Sets EXTENT_NOT_ALIGNED.*/ #define FIEMAP_EXTENT_DATA_TAIL 0x00000400 /* Multiple files in block. * Sets EXTENT_NOT_ALIGNED.*/ #define FIEMAP_EXTENT_UNWRITTEN 0x00000800 /* Space allocated, but * no data (i.e. zero). */ #define FIEMAP_EXTENT_MERGED 0x00001000 /* File does not natively * support extents. Result * merged for efficiency. */ #endif /* _LINUX_FIEMAP_H */
{ "content_hash": "cbbf1b9059c9e370734be534eec741b0", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 75, "avg_line_length": 39.672413793103445, "alnum_prop": 0.6770969143850499, "repo_name": "Xperia-Nicki/android_platform_sony_nicki", "id": "934e22d65801e508f03774f5cb86fd4ae7b35e68", "size": "2548", "binary": false, "copies": "590", "ref": "refs/heads/master", "path": "external/e2fsprogs/lib/ext2fs/fiemap.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "212775" }, { "name": "Awk", "bytes": "19252" }, { "name": "C", "bytes": "68667466" }, { "name": "C#", "bytes": "55625" }, { "name": "C++", "bytes": "54670920" }, { "name": "CLIPS", "bytes": "12224" }, { "name": "CSS", "bytes": "283405" }, { "name": "D", "bytes": "1931" }, { "name": "Java", "bytes": "4882" }, { "name": "JavaScript", "bytes": "19597804" }, { "name": "Objective-C", "bytes": "5849156" }, { "name": "PHP", "bytes": "17224" }, { "name": "Pascal", "bytes": "42411" }, { "name": "Perl", "bytes": "1632149" }, { "name": "Prolog", "bytes": "214621" }, { "name": "Python", "bytes": "3493321" }, { "name": "R", "bytes": "290" }, { "name": "Ruby", "bytes": "78743" }, { "name": "Scilab", "bytes": "554" }, { "name": "Shell", "bytes": "265637" }, { "name": "TypeScript", "bytes": "45459" }, { "name": "XSLT", "bytes": "11219" } ], "symlink_target": "" }
/*global define*/ define([ './defaultValue', './defined', './DeveloperError', './freezeObject' ], function( defaultValue, defined, DeveloperError, freezeObject) { 'use strict'; /** * A vertex format defines what attributes make up a vertex. A VertexFormat can be provided * to a {@link Geometry} to request that certain properties be computed, e.g., just position, * position and normal, etc. * * @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example. * * @alias VertexFormat * @constructor * * @example * // Create a vertex format with position and 2D texture coordinate attributes. * var format = new Cesium.VertexFormat({ * position : true, * st : true * }); * * @see Geometry#attributes * @see Packable */ function VertexFormat(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); /** * When <code>true</code>, the vertex has a 3D position attribute. * <p> * 64-bit floating-point (for precision). 3 components per attribute. * </p> * * @type Boolean * * @default false */ this.position = defaultValue(options.position, false); /** * When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting. * <p> * 32-bit floating-point. 3 components per attribute. * </p> * * @type Boolean * * @default false */ this.normal = defaultValue(options.normal, false); /** * When <code>true</code>, the vertex has a 2D texture coordinate attribute. * <p> * 32-bit floating-point. 2 components per attribute * </p> * * @type Boolean * * @default false */ this.st = defaultValue(options.st, false); /** * When <code>true</code>, the vertex has a bitangent attribute (normalized), which is used for tangent-space effects like bump mapping. * <p> * 32-bit floating-point. 3 components per attribute. * </p> * * @type Boolean * * @default false */ this.bitangent = defaultValue(options.bitangent, false); /** * When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping. * <p> * 32-bit floating-point. 3 components per attribute. * </p> * * @type Boolean * * @default false */ this.tangent = defaultValue(options.tangent, false); /** * When <code>true</code>, the vertex has an RGB color attribute. * <p> * 8-bit unsigned byte. 3 components per attribute. * </p> * * @type Boolean * * @default false */ this.color = defaultValue(options.color, false); } /** * An immutable vertex format with only a position attribute. * * @type {VertexFormat} * @constant * * @see VertexFormat#position */ VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({ position : true })); /** * An immutable vertex format with position and normal attributes. * This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#normal */ VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({ position : true, normal : true })); /** * An immutable vertex format with position, normal, and st attributes. * This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport} * is <code>TEXTURED/code>. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#normal * @see VertexFormat#st */ VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({ position : true, normal : true, st : true })); /** * An immutable vertex format with position and st attributes. * This is compatible with {@link EllipsoidSurfaceAppearance}. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#st */ VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({ position : true, st : true })); /** * An immutable vertex format with position and color attributes. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#color */ VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({ position : true, color : true })); /** * An immutable vertex format with well-known attributes: position, normal, st, tangent, and bitangent. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#normal * @see VertexFormat#st * @see VertexFormat#tangent * @see VertexFormat#bitangent */ VertexFormat.ALL = freezeObject(new VertexFormat({ position : true, normal : true, st : true, tangent : true, bitangent : true })); /** * An immutable vertex format with position, normal, and st attributes. * This is compatible with most appearances and materials; however * normal and st attributes are not always required. When this is * known in advance, another <code>VertexFormat</code> should be used. * * @type {VertexFormat} * @constant * * @see VertexFormat#position * @see VertexFormat#normal */ VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST; /** * The number of elements used to pack the object into an array. * @type {Number} */ VertexFormat.packedLength = 6; /** * Stores the provided instance into the provided array. * * @param {VertexFormat} value The value to pack. * @param {Number[]} array The array to pack into. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements. * * @returns {Number[]} The array that was packed into */ VertexFormat.pack = function(value, array, startingIndex) { //>>includeStart('debug', pragmas.debug); if (!defined(value)) { throw new DeveloperError('value is required'); } if (!defined(array)) { throw new DeveloperError('array is required'); } //>>includeEnd('debug'); startingIndex = defaultValue(startingIndex, 0); array[startingIndex++] = value.position ? 1.0 : 0.0; array[startingIndex++] = value.normal ? 1.0 : 0.0; array[startingIndex++] = value.st ? 1.0 : 0.0; array[startingIndex++] = value.tangent ? 1.0 : 0.0; array[startingIndex++] = value.bitangent ? 1.0 : 0.0; array[startingIndex++] = value.color ? 1.0 : 0.0; return array; }; /** * Retrieves an instance from a packed array. * * @param {Number[]} array The packed array. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked. * @param {VertexFormat} [result] The object into which to store the result. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. */ VertexFormat.unpack = function(array, startingIndex, result) { //>>includeStart('debug', pragmas.debug); if (!defined(array)) { throw new DeveloperError('array is required'); } //>>includeEnd('debug'); startingIndex = defaultValue(startingIndex, 0); if (!defined(result)) { result = new VertexFormat(); } result.position = array[startingIndex++] === 1.0; result.normal = array[startingIndex++] === 1.0; result.st = array[startingIndex++] === 1.0; result.tangent = array[startingIndex++] === 1.0; result.bitangent = array[startingIndex++] === 1.0; result.color = array[startingIndex++] === 1.0; return result; }; /** * Duplicates a VertexFormat instance. * * @param {VertexFormat} vertexFormat The vertex format to duplicate. * @param {VertexFormat} [result] The object onto which to store the result. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined) */ VertexFormat.clone = function(vertexFormat, result) { if (!defined(vertexFormat)) { return undefined; } if (!defined(result)) { result = new VertexFormat(); } result.position = vertexFormat.position; result.normal = vertexFormat.normal; result.st = vertexFormat.st; result.tangent = vertexFormat.tangent; result.bitangent = vertexFormat.bitangent; result.color = vertexFormat.color; return result; }; return VertexFormat; });
{ "content_hash": "4af758b9def5f48ad758aa296bc07047", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 165, "avg_line_length": 32.18064516129032, "alnum_prop": 0.5648556535685646, "repo_name": "atrawog/360-flight-explorer", "id": "e60331a4a45a514c852800c573fd3e9acea1a209", "size": "9976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Core/VertexFormat.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "672812" }, { "name": "GLSL", "bytes": "202655" }, { "name": "HTML", "bytes": "1435020" }, { "name": "JavaScript", "bytes": "53268214" }, { "name": "Shell", "bytes": "297" } ], "symlink_target": "" }
require 'bitbucket_rest_api' require_relative 'performers/bitbucket_git_repository' require_relative 'performers/bitbucket_git_wiki' module BackupRepos class BackupBitbucket def process ask_credentials process_git_repositories process_git_wikis end private def client @client ||= ::BitBucket.new(login: @username, password: @password) end def ask_credentials cli = HighLine.new @username = BackupRepos.config.dig('bitbucket', 'username') || cli.ask('BitBucket Username: ') @password = BackupRepos.config.dig('bitbucket', 'password') || cli.ask('BitBucket Password: ') { |q| q.echo = false } end def process_git_repositories git_repos.each do |repo_params| Performers::BitbucketGitRepository.new(repo_params).backup end end def process_git_wikis wiki_repos = git_repos.select(&:has_wiki) wiki_repos.each do |repo_params| Performers::BitbucketGitWiki.new(repo_params).backup end end def git_repos repos.select { |repo| repo.scm == 'git' } end def repos @repos ||= client.repos.list end end end
{ "content_hash": "1d5cf446d743f833581ccf15e3914262", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 124, "avg_line_length": 24.3125, "alnum_prop": 0.6555269922879178, "repo_name": "jpalumickas/backup-repos", "id": "247dea848d061cd526803cc7a8fed85d0f6b83e8", "size": "1198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/backup_repos/backup_bitbucket.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "28120" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
#ifndef _GPU_RENDERERIMPL_H__ #define _GPU_RENDERERIMPL_H__ #include "SDL_gpu.h" #ifdef __cplusplus extern "C" { #endif // Internal API for managing window mappings DECLSPEC void SDLCALL GPU_AddWindowMapping(GPU_Target* target); DECLSPEC void SDLCALL GPU_RemoveWindowMapping(Uint32 windowID); DECLSPEC void SDLCALL GPU_RemoveWindowMappingByTarget(GPU_Target* target); /*! Private implementation of renderer members. */ typedef struct GPU_RendererImpl { /*! \see GPU_Init() * \see GPU_InitRenderer() * \see GPU_InitRendererByID() */ GPU_Target* (SDLCALL *Init)(GPU_Renderer* renderer, GPU_RendererID renderer_request, Uint16 w, Uint16 h, GPU_WindowFlagEnum SDL_flags); /*! \see GPU_CreateTargetFromWindow * The extra parameter is used internally to reuse/reinit a target. */ GPU_Target* (SDLCALL *CreateTargetFromWindow)(GPU_Renderer* renderer, Uint32 windowID, GPU_Target* target); /*! \see GPU_CreateAliasTarget() */ GPU_Target* (SDLCALL *CreateAliasTarget)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_MakeCurrent */ void (SDLCALL *MakeCurrent)(GPU_Renderer* renderer, GPU_Target* target, Uint32 windowID); /*! Sets up this renderer to act as the current renderer. Called automatically by GPU_SetCurrentRenderer(). */ void (SDLCALL *SetAsCurrent)(GPU_Renderer* renderer); /*! \see GPU_ResetRendererState() */ void (SDLCALL *ResetRendererState)(GPU_Renderer* renderer); /*! \see GPU_SetWindowResolution() */ Uint8 (SDLCALL *SetWindowResolution)(GPU_Renderer* renderer, Uint16 w, Uint16 h); /*! \see GPU_SetVirtualResolution() */ void (SDLCALL *SetVirtualResolution)(GPU_Renderer* renderer, GPU_Target* target, Uint16 w, Uint16 h); /*! \see GPU_UnsetVirtualResolution() */ void (SDLCALL *UnsetVirtualResolution)(GPU_Renderer* renderer, GPU_Target* target); /*! Clean up the renderer state. */ void (SDLCALL *Quit)(GPU_Renderer* renderer); /*! \see GPU_SetFullscreen() */ Uint8 (SDLCALL *SetFullscreen)(GPU_Renderer* renderer, Uint8 enable_fullscreen, Uint8 use_desktop_resolution); /*! \see GPU_SetCamera() */ GPU_Camera (SDLCALL *SetCamera)(GPU_Renderer* renderer, GPU_Target* target, GPU_Camera* cam); /*! \see GPU_CreateImage() */ GPU_Image* (SDLCALL *CreateImage)(GPU_Renderer* renderer, Uint16 w, Uint16 h, GPU_FormatEnum format); /*! \see GPU_CreateImageUsingTexture() */ GPU_Image* (SDLCALL *CreateImageUsingTexture)(GPU_Renderer* renderer, Uint32 handle, Uint8 take_ownership); /*! \see GPU_LoadImage() */ GPU_Image* (SDLCALL *LoadImage)(GPU_Renderer* renderer, const char* filename); /*! \see GPU_CreateAliasImage() */ GPU_Image* (SDLCALL *CreateAliasImage)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_SaveImage() */ Uint8 (SDLCALL *SaveImage)(GPU_Renderer* renderer, GPU_Image* image, const char* filename, GPU_FileFormatEnum format); /*! \see GPU_CopyImage() */ GPU_Image* (SDLCALL *CopyImage)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_UpdateImage */ void (SDLCALL *UpdateImage)(GPU_Renderer* renderer, GPU_Image* image, const GPU_Rect* image_rect, SDL_Surface* surface, const GPU_Rect* surface_rect); /*! \see GPU_UpdateImageBytes */ void (SDLCALL *UpdateImageBytes)(GPU_Renderer* renderer, GPU_Image* image, const GPU_Rect* image_rect, const unsigned char* bytes, int bytes_per_row); /*! \see GPU_ReplaceImage */ Uint8 (SDLCALL *ReplaceImage)(GPU_Renderer* renderer, GPU_Image* image, SDL_Surface* surface, const GPU_Rect* surface_rect); /*! \see GPU_CopyImageFromSurface() */ GPU_Image* (SDLCALL *CopyImageFromSurface)(GPU_Renderer* renderer, SDL_Surface* surface); /*! \see GPU_CopyImageFromTarget() */ GPU_Image* (SDLCALL *CopyImageFromTarget)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_CopySurfaceFromTarget() */ SDL_Surface* (SDLCALL *CopySurfaceFromTarget)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_CopySurfaceFromImage() */ SDL_Surface* (SDLCALL *CopySurfaceFromImage)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_FreeImage() */ void (SDLCALL *FreeImage)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_LoadTarget() */ GPU_Target* (SDLCALL *LoadTarget)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_FreeTarget() */ void (SDLCALL *FreeTarget)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_Blit() */ void (SDLCALL *Blit)(GPU_Renderer* renderer, GPU_Image* image, GPU_Rect* src_rect, GPU_Target* target, float x, float y); /*! \see GPU_BlitRotate() */ void (SDLCALL *BlitRotate)(GPU_Renderer* renderer, GPU_Image* image, GPU_Rect* src_rect, GPU_Target* target, float x, float y, float degrees); /*! \see GPU_BlitScale() */ void (SDLCALL *BlitScale)(GPU_Renderer* renderer, GPU_Image* image, GPU_Rect* src_rect, GPU_Target* target, float x, float y, float scaleX, float scaleY); /*! \see GPU_BlitTransform */ void (SDLCALL *BlitTransform)(GPU_Renderer* renderer, GPU_Image* image, GPU_Rect* src_rect, GPU_Target* target, float x, float y, float degrees, float scaleX, float scaleY); /*! \see GPU_BlitTransformX() */ void (SDLCALL *BlitTransformX)(GPU_Renderer* renderer, GPU_Image* image, GPU_Rect* src_rect, GPU_Target* target, float x, float y, float pivot_x, float pivot_y, float degrees, float scaleX, float scaleY); /*! \see GPU_TriangleBatch() */ void (SDLCALL *TriangleBatch)(GPU_Renderer* renderer, GPU_Image* image, GPU_Target* target, unsigned short num_vertices, float* values, unsigned int num_indices, unsigned short* indices, GPU_BatchFlagEnum flags); /*! \see GPU_GenerateMipmaps() */ void (SDLCALL *GenerateMipmaps)(GPU_Renderer* renderer, GPU_Image* image); /*! \see GPU_SetClip() */ GPU_Rect (SDLCALL *SetClip)(GPU_Renderer* renderer, GPU_Target* target, Sint16 x, Sint16 y, Uint16 w, Uint16 h); /*! \see GPU_UnsetClip() */ void (SDLCALL *UnsetClip)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_GetPixel() */ SDL_Color (SDLCALL *GetPixel)(GPU_Renderer* renderer, GPU_Target* target, Sint16 x, Sint16 y); /*! \see GPU_SetImageFilter() */ void (SDLCALL *SetImageFilter)(GPU_Renderer* renderer, GPU_Image* image, GPU_FilterEnum filter); /*! \see GPU_SetWrapMode() */ void (SDLCALL *SetWrapMode)(GPU_Renderer* renderer, GPU_Image* image, GPU_WrapEnum wrap_mode_x, GPU_WrapEnum wrap_mode_y); /*! \see GPU_ClearRGBA() */ void (SDLCALL *ClearRGBA)(GPU_Renderer* renderer, GPU_Target* target, Uint8 r, Uint8 g, Uint8 b, Uint8 a); /*! \see GPU_FlushBlitBuffer() */ void (SDLCALL *FlushBlitBuffer)(GPU_Renderer* renderer); /*! \see GPU_Flip() */ void (SDLCALL *Flip)(GPU_Renderer* renderer, GPU_Target* target); /*! \see GPU_CreateShaderProgram() */ Uint32 (SDLCALL *CreateShaderProgram)(GPU_Renderer* renderer); /*! \see GPU_FreeShaderProgram() */ void (SDLCALL *FreeShaderProgram)(GPU_Renderer* renderer, Uint32 program_object); /*! \see GPU_CompileShader_RW() */ Uint32 (SDLCALL *CompileShader_RW)(GPU_Renderer* renderer, GPU_ShaderEnum shader_type, SDL_RWops* shader_source, Uint8 free_rwops); /*! \see GPU_CompileShader() */ Uint32 (SDLCALL *CompileShader)(GPU_Renderer* renderer, GPU_ShaderEnum shader_type, const char* shader_source); /*! \see GPU_FreeShader() */ void (SDLCALL *FreeShader)(GPU_Renderer* renderer, Uint32 shader_object); /*! \see GPU_AttachShader() */ void (SDLCALL *AttachShader)(GPU_Renderer* renderer, Uint32 program_object, Uint32 shader_object); /*! \see GPU_DetachShader() */ void (SDLCALL *DetachShader)(GPU_Renderer* renderer, Uint32 program_object, Uint32 shader_object); /*! \see GPU_LinkShaderProgram() */ Uint8 (SDLCALL *LinkShaderProgram)(GPU_Renderer* renderer, Uint32 program_object); /*! \see GPU_ActivateShaderProgram() */ void (SDLCALL *ActivateShaderProgram)(GPU_Renderer* renderer, Uint32 program_object, GPU_ShaderBlock* block); /*! \see GPU_DeactivateShaderProgram() */ void (SDLCALL *DeactivateShaderProgram)(GPU_Renderer* renderer); /*! \see GPU_GetShaderMessage() */ const char* (SDLCALL *GetShaderMessage)(GPU_Renderer* renderer); /*! \see GPU_GetAttribLocation() */ int (SDLCALL *GetAttributeLocation)(GPU_Renderer* renderer, Uint32 program_object, const char* attrib_name); /*! \see GPU_GetUniformLocation() */ int (SDLCALL *GetUniformLocation)(GPU_Renderer* renderer, Uint32 program_object, const char* uniform_name); /*! \see GPU_LoadShaderBlock() */ GPU_ShaderBlock (SDLCALL *LoadShaderBlock)(GPU_Renderer* renderer, Uint32 program_object, const char* position_name, const char* texcoord_name, const char* color_name, const char* modelViewMatrix_name); /*! \see GPU_SetShaderBlock() */ void (SDLCALL *SetShaderBlock)(GPU_Renderer* renderer, GPU_ShaderBlock block); /*! \see GPU_SetShaderImage() */ void (SDLCALL *SetShaderImage)(GPU_Renderer* renderer, GPU_Image* image, int location, int image_unit); /*! \see GPU_GetUniformiv() */ void (SDLCALL *GetUniformiv)(GPU_Renderer* renderer, Uint32 program_object, int location, int* values); /*! \see GPU_SetUniformi() */ void (SDLCALL *SetUniformi)(GPU_Renderer* renderer, int location, int value); /*! \see GPU_SetUniformiv() */ void (SDLCALL *SetUniformiv)(GPU_Renderer* renderer, int location, int num_elements_per_value, int num_values, int* values); /*! \see GPU_GetUniformuiv() */ void (SDLCALL *GetUniformuiv)(GPU_Renderer* renderer, Uint32 program_object, int location, unsigned int* values); /*! \see GPU_SetUniformui() */ void (SDLCALL *SetUniformui)(GPU_Renderer* renderer, int location, unsigned int value); /*! \see GPU_SetUniformuiv() */ void (SDLCALL *SetUniformuiv)(GPU_Renderer* renderer, int location, int num_elements_per_value, int num_values, unsigned int* values); /*! \see GPU_GetUniformfv() */ void (SDLCALL *GetUniformfv)(GPU_Renderer* renderer, Uint32 program_object, int location, float* values); /*! \see GPU_SetUniformf() */ void (SDLCALL *SetUniformf)(GPU_Renderer* renderer, int location, float value); /*! \see GPU_SetUniformfv() */ void (SDLCALL *SetUniformfv)(GPU_Renderer* renderer, int location, int num_elements_per_value, int num_values, float* values); /*! \see GPU_SetUniformMatrixfv() */ void (SDLCALL *SetUniformMatrixfv)(GPU_Renderer* renderer, int location, int num_matrices, int num_rows, int num_columns, Uint8 transpose, float* values); /*! \see GPU_SetAttributef() */ void (SDLCALL *SetAttributef)(GPU_Renderer* renderer, int location, float value); /*! \see GPU_SetAttributei() */ void (SDLCALL *SetAttributei)(GPU_Renderer* renderer, int location, int value); /*! \see GPU_SetAttributeui() */ void (SDLCALL *SetAttributeui)(GPU_Renderer* renderer, int location, unsigned int value); /*! \see GPU_SetAttributefv() */ void (SDLCALL *SetAttributefv)(GPU_Renderer* renderer, int location, int num_elements, float* value); /*! \see GPU_SetAttributeiv() */ void (SDLCALL *SetAttributeiv)(GPU_Renderer* renderer, int location, int num_elements, int* value); /*! \see GPU_SetAttributeuiv() */ void (SDLCALL *SetAttributeuiv)(GPU_Renderer* renderer, int location, int num_elements, unsigned int* value); /*! \see GPU_SetAttributeSource() */ void (SDLCALL *SetAttributeSource)(GPU_Renderer* renderer, int num_values, GPU_Attribute source); // Shapes /*! \see GPU_SetLineThickness() */ float (SDLCALL *SetLineThickness)(GPU_Renderer* renderer, float thickness); /*! \see GPU_GetLineThickness() */ float (SDLCALL *GetLineThickness)(GPU_Renderer* renderer); /*! \see GPU_Pixel() */ void (SDLCALL *Pixel)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, SDL_Color color); /*! \see GPU_Line() */ void (SDLCALL *Line)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, SDL_Color color); /*! \see GPU_Arc() */ void (SDLCALL *Arc)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float radius, float start_angle, float end_angle, SDL_Color color); /*! \see GPU_ArcFilled() */ void (SDLCALL *ArcFilled)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float radius, float start_angle, float end_angle, SDL_Color color); /*! \see GPU_Circle() */ void (SDLCALL *Circle)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float radius, SDL_Color color); /*! \see GPU_CircleFilled() */ void (SDLCALL *CircleFilled)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float radius, SDL_Color color); /*! \see GPU_Ellipse() */ void (SDLCALL *Ellipse)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float rx, float ry, float degrees, SDL_Color color); /*! \see GPU_EllipseFilled() */ void (SDLCALL *EllipseFilled)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float rx, float ry, float degrees, SDL_Color color); /*! \see GPU_Sector() */ void (SDLCALL *Sector)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float inner_radius, float outer_radius, float start_angle, float end_angle, SDL_Color color); /*! \see GPU_SectorFilled() */ void (SDLCALL *SectorFilled)(GPU_Renderer* renderer, GPU_Target* target, float x, float y, float inner_radius, float outer_radius, float start_angle, float end_angle, SDL_Color color); /*! \see GPU_Tri() */ void (SDLCALL *Tri)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, float x3, float y3, SDL_Color color); /*! \see GPU_TriFilled() */ void (SDLCALL *TriFilled)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, float x3, float y3, SDL_Color color); /*! \see GPU_Rectangle() */ void (SDLCALL *Rectangle)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, SDL_Color color); /*! \see GPU_RectangleFilled() */ void (SDLCALL *RectangleFilled)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, SDL_Color color); /*! \see GPU_RectangleRound() */ void (SDLCALL *RectangleRound)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, float radius, SDL_Color color); /*! \see GPU_RectangleRoundFilled() */ void (SDLCALL *RectangleRoundFilled)(GPU_Renderer* renderer, GPU_Target* target, float x1, float y1, float x2, float y2, float radius, SDL_Color color); /*! \see GPU_Polygon() */ void (SDLCALL *Polygon)(GPU_Renderer* renderer, GPU_Target* target, unsigned int num_vertices, float* vertices, SDL_Color color); /*! \see GPU_PolygonFilled() */ void (SDLCALL *PolygonFilled)(GPU_Renderer* renderer, GPU_Target* target, unsigned int num_vertices, float* vertices, SDL_Color color); } GPU_RendererImpl; #ifdef __cplusplus } #endif #endif
{ "content_hash": "5feab2c55b97a8b1626371409841e1cb", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 213, "avg_line_length": 47.65094339622642, "alnum_prop": 0.6893684418926945, "repo_name": "masonwheeler/sdl-gpu", "id": "299406d6b6cb49cda3f009650f8e798587145337", "size": "15153", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/SDL_gpu_RendererImpl.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2849026" }, { "name": "C++", "bytes": "235781" }, { "name": "CMake", "bytes": "126717" }, { "name": "GLSL", "bytes": "1491" }, { "name": "Makefile", "bytes": "4685" }, { "name": "Objective-C", "bytes": "794" }, { "name": "Objective-C++", "bytes": "580" }, { "name": "Perl", "bytes": "24748" }, { "name": "Shell", "bytes": "323" } ], "symlink_target": "" }
<!-- jQuery Version 1.11.0 --> <script src="{{ "/js/jquery-1.11.0.js" | prepend: site.baseurl }}"></script> <!-- Bootstrap Core JavaScript --> <script src="{{ "/js/bootstrap.min.js" | prepend: site.baseurl }}"></script> <!-- Plugin JavaScript --> <script src="{{ "/js/jquery.easing.min.js" | prepend: site.baseurl }}"></script> <script src="{{ "/js/classie.js" | prepend: site.baseurl }}"></script> <script src="{{ "/js/cbpAnimatedHeader.js" | prepend: site.baseurl }}"></script> <!-- Contact Form JavaScript --> <script src="{{ "/js/jqBootstrapValidation.js" | prepend: site.baseurl }}"></script> <script src="{{ "/js/contact_me.js" | prepend: site.baseurl }}"></script> <!-- Custom Theme JavaScript --> <script src="{{ "/js/agency.js" | prepend: site.baseurl }}"></script> <!-- tooltip --> <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script>
{ "content_hash": "97e05ee971c2630c7f703474e69cdd05", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 88, "avg_line_length": 40.291666666666664, "alnum_prop": 0.5739400206825233, "repo_name": "stephansahm/stephansahm.github.io", "id": "bd5464f6622cfc210a0374d858e47410b6c0355d", "size": "967", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_includes/js.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "27059" }, { "name": "HTML", "bytes": "27133" }, { "name": "JavaScript", "bytes": "42758" }, { "name": "PHP", "bytes": "1092" } ], "symlink_target": "" }
from quicklock import singleton
{ "content_hash": "922b1475ddf99cf2f7f213ec456383ff", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.875, "repo_name": "NateFerrero/quicklock", "id": "0d9e271c6b3a013c198c081e9d7347da909fac42", "size": "32", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quicklock/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1001" }, { "name": "Python", "bytes": "3215" } ], "symlink_target": "" }
$ver = [regex]::Match((Get-Content NBXplorer\NBXplorer.csproj), '<Version>([^<]+)<').Groups[1].Value git tag -a "v$ver" -m "$ver" git push origin "v$ver"
{ "content_hash": "41b08255105f3b1e72aa68c3e990ad2e", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 100, "avg_line_length": 51, "alnum_prop": 0.6405228758169934, "repo_name": "dgarage/NBXplorer", "id": "9653e6427b74f46d3a27fefd7f18a5e95b165241", "size": "153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "publish-docker.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "129" }, { "name": "C#", "bytes": "1008909" }, { "name": "Dockerfile", "bytes": "201" }, { "name": "PLpgSQL", "bytes": "107377" }, { "name": "PowerShell", "bytes": "833" }, { "name": "Shell", "bytes": "460" } ], "symlink_target": "" }
package org.apache.river.test.spec.discoveryservice.event; import java.util.logging.Level; import org.apache.river.qa.harness.QAConfig; import org.apache.river.qa.harness.Test; /** * This class verifies that, upon registration, so-called "late-joiner" * registrations that request discovery of locators that have already been * discovered for other registration(s) will receive notification of all * of those previously discovered lookup services. That is, this class * verifies that when one or more registrations -- configured for discovery * of a set of locators -- are added to a lookup discovery service after * an initial set of registration(s) -- similarly configured for * locator discovery -- have been made with that lookup discovery service, the * second set of registrations are notified of the discovery of all lookup * services having the locators with which the registraions were configured. * * The environment in which this class expects to operate is as follows: * <p><ul> * <li> one or more lookup services, each belonging to either a finite set * of member groups, or no groups (groups membership is irrelevant * for this test) * <li> one instance of the lookup discovery service * <li> a set of one or more initial registrations with the lookup * discovery service, each configured for discovery of the * locator(s) of those lookup service(s) * <li> each initial registration with the lookup discovery service should * receive remote discovery events through an instance of * RemoteEventListener * <li> after verification that the initial registrations have received * the appropriate notifications, an additional set of one or more * registrations with the lookup discovery service, each configured * for discovery of the same locator(s) as the initial set * <li> each additional registration should also receive remote discovery * events through an instance of RemoteEventListener * </ul><p> * * If the lookup discovery service functions as specified, then upon * requesting the additional registrations, the listener of each such * registration will receive an instance of <code>RemoteDiscoveryEvent</code> * which accurately reflects the expected lookup services. */ public class LateRegsNotifiedLocs extends LateRegsNotifiedGroups { /** Performs actions necessary to prepare for execution of the * current test. Populates the sets of group and/or locators to use. */ public Test construct(QAConfig config) throws Exception { super.construct(config); logger.log(Level.FINE, "setup()"); groupsToDiscover = getGroupsToDiscover(getUseOnlyLocDiscovery()); locsToDiscover = getLocatorsToDiscover(getUseOnlyLocDiscovery()); return this; }//end construct } //end class LateRegsNotifiedLocs
{ "content_hash": "0557ffac5669d445972530b2d90d4a82", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 78, "avg_line_length": 48.35, "alnum_prop": 0.7425025853154085, "repo_name": "pfirmstone/JGDMS", "id": "b0d90f2f7ed1f883409cb91fe03d005619f557f4", "size": "3707", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "qa/src/org/apache/river/test/spec/discoveryservice/event/LateRegsNotifiedLocs.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" } ], "symlink_target": "" }
#include "src/backing/client/client_factory.h" #include <chrono> #include <memory> #include <utility> #include "absl/types/optional.h" #include "absl/memory/memory.h" #include "grpcpp/grpcpp.h" #include "src/backing/client/client.h" #include "src/backing/client/grpc_client/client_context_factory.h" #include "src/backing/client/grpc_client/grpc_client.h" #include "src/backing/client/grpc_client/key_management_service_stub.h" namespace kmsengine { namespace backing { namespace { using ::kmsengine::backing::grpc_client::GrpcClient; // Default API endpoint for making gRPC requests against. // // Should not be prefixed with "https://" to comply with the gRPC library. constexpr char kDefaultApiEndpoint[] = "cloudkms.googleapis.com"; std::unique_ptr<Client> MakeDefaultClient( absl::optional<std::chrono::milliseconds> timeout) { return absl::make_unique<GrpcClient>( grpc_client::CreateKeyManagementServiceStub( kDefaultApiEndpoint, grpc::GoogleDefaultCredentials()), grpc_client::CreateClientContextFactory( timeout, std::make_shared<client::SystemClock>())); } } // namespace std::unique_ptr<Client> MakeDefaultClientWithTimeout( std::chrono::milliseconds timeout) { return MakeDefaultClient(timeout); } std::unique_ptr<Client> MakeDefaultClientWithoutTimeout() { return MakeDefaultClient(absl::nullopt); } } // namespace backing } // namespace kmsengine
{ "content_hash": "f6b7f84a5e743c57ee6ea60a93acf760", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 74, "avg_line_length": 29.020408163265305, "alnum_prop": 0.7482419127988749, "repo_name": "googleinterns/cloud-kms-oss-tools", "id": "3ff9653620bebd3faafe40f04b6ab02b992da6de", "size": "2018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/backing/client/client_factory.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2627" }, { "name": "C++", "bytes": "282703" }, { "name": "Shell", "bytes": "2852" }, { "name": "Starlark", "bytes": "39743" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Inverse Hyperbolic Functions</title> <link rel="stylesheet" href="../math.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.77.1"> <link rel="home" href="../index.html" title="Math Toolkit 2.2.0"> <link rel="up" href="../special.html" title="Chapter&#160;6.&#160;Special Functions"> <link rel="prev" href="sinc/sinhc_pi.html" title="sinhc_pi"> <link rel="next" href="inv_hyper/inv_hyper_over.html" title="Inverse Hyperbolic Functions Overview"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="sinc/sinhc_pi.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../special.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="inv_hyper/inv_hyper_over.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="math_toolkit.inv_hyper"></a><a class="link" href="inv_hyper.html" title="Inverse Hyperbolic Functions">Inverse Hyperbolic Functions</a> </h2></div></div></div> <div class="toc"><dl> <dt><span class="section"><a href="inv_hyper/inv_hyper_over.html">Inverse Hyperbolic Functions Overview</a></span></dt> <dt><span class="section"><a href="inv_hyper/acosh.html">acosh</a></span></dt> <dt><span class="section"><a href="inv_hyper/asinh.html">asinh</a></span></dt> <dt><span class="section"><a href="inv_hyper/atanh.html">atanh</a></span></dt> </dl></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2006-2010, 2012-2014 Nikhar Agrawal, Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock, Johan R&#229;de, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="sinc/sinhc_pi.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../special.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="inv_hyper/inv_hyper_over.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "30ecdca988a7219c1a53ccdcf518821f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 431, "avg_line_length": 67, "alnum_prop": 0.6423542664038299, "repo_name": "BenKeyFSI/poedit", "id": "306a93dda28ed2e31a93b71837fe691d8db6d66c", "size": "3551", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "deps/boost/libs/math/doc/html/math_toolkit/inv_hyper.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "24827" }, { "name": "C++", "bytes": "913779" }, { "name": "Inno Setup", "bytes": "11293" }, { "name": "Makefile", "bytes": "9174" }, { "name": "Objective-C", "bytes": "4693" }, { "name": "Objective-C++", "bytes": "15875" }, { "name": "Python", "bytes": "3040" }, { "name": "Ruby", "bytes": "232" }, { "name": "Shell", "bytes": "10607" } ], "symlink_target": "" }
<?php /** * REST API: WP_REST_Controller class * * @package WordPress * @subpackage REST_API * @since 4.7.0 */ /** * Core base controller for managing and interacting with REST API items. * * @since 4.7.0 */ abstract class WP_REST_Controller { /** * The namespace of this controller's route. * * @since 4.7.0 * @var string */ protected $namespace; /** * The base of this controller's route. * * @since 4.7.0 * @var string */ protected $rest_base; /** * Registers the routes for the objects of the controller. * * @since 4.7.0 */ public function register_routes() { /* translators: %s: register_routes() */ _doing_it_wrong( 'WP_REST_Controller::register_routes', sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ), '4.7' ); } /** * Checks if a given request has access to get items. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|bool True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Retrieves a collection of items. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Checks if a given request has access to get a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|bool True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Retrieves one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Checks if a given request has access to create items. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|bool True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Creates one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Checks if a given request has access to update a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|bool True if the request has access to update the item, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Updates one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Checks if a given request has access to delete a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|bool True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Deletes one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Prepares one item for create or update operation. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return WP_Error|object The prepared item, or WP_Error object on failure. */ protected function prepare_item_for_database( $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Prepares the item for the REST response. * * @since 4.7.0 * * @param mixed $item WordPress representation of the item. * @param WP_REST_Request $request Request object. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $item, $request ) { /* translators: %s: method name */ return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) ); } /** * Prepares a response for insertion into a collection. * * @since 4.7.0 * * @param WP_REST_Response $response Response object. * @return array|mixed Response data, ready for insertion into collection data. */ public function prepare_response_for_collection( $response ) { if ( ! ( $response instanceof WP_REST_Response ) ) { return $response; } $data = (array) $response->get_data(); $server = rest_get_server(); $links = $server->get_compact_response_links( $response ); if ( ! empty( $links ) ) { $data['_links'] = $links; } return $data; } /** * Filters a response based on the context defined in the schema. * * @since 4.7.0 * * @param array $data Response data to fiter. * @param string $context Context defined in the schema. * @return array Filtered response. */ public function filter_response_by_context( $data, $context ) { $schema = $this->get_item_schema(); foreach ( $data as $key => $value ) { if ( empty( $schema['properties'][ $key ] ) || empty( $schema['properties'][ $key ]['context'] ) ) { continue; } if ( ! in_array( $context, $schema['properties'][ $key ]['context'], true ) ) { unset( $data[ $key ] ); continue; } if ( 'object' === $schema['properties'][ $key ]['type'] && ! empty( $schema['properties'][ $key ]['properties'] ) ) { foreach ( $schema['properties'][ $key ]['properties'] as $attribute => $details ) { if ( empty( $details['context'] ) ) { continue; } if ( ! in_array( $context, $details['context'], true ) ) { if ( isset( $data[ $key ][ $attribute ] ) ) { unset( $data[ $key ][ $attribute ] ); } } } } } return $data; } /** * Retrieves the item's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ public function get_item_schema() { return $this->add_additional_fields_schema( array() ); } /** * Retrieves the item's schema for display / public consumption purposes. * * @since 4.7.0 * * @return array Public item schema data. */ public function get_public_item_schema() { $schema = $this->get_item_schema(); foreach ( $schema['properties'] as &$property ) { unset( $property['arg_options'] ); } return $schema; } /** * Retrieves the query params for the collections. * * @since 4.7.0 * * @return array Query parameters for the collection. */ public function get_collection_params() { return array( 'context' => $this->get_context_param(), 'page' => array( 'description' => __( 'Current page of the collection.' ), 'type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', 'minimum' => 1, ), 'per_page' => array( 'description' => __( 'Maximum number of items to be returned in result set.' ), 'type' => 'integer', 'default' => 10, 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'search' => array( 'description' => __( 'Limit results to those matching a string.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), ); } /** * Retrieves the magical context param. * * Ensures consistent descriptions between endpoints, and populates enum from schema. * * @since 4.7.0 * * @param array $args Optional. Additional arguments for context parameter. Default empty array. * @return array Context parameter details. */ public function get_context_param( $args = array() ) { $param_details = array( 'description' => __( 'Scope under which the request is made; determines fields present in response.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ); $schema = $this->get_item_schema(); if ( empty( $schema['properties'] ) ) { return array_merge( $param_details, $args ); } $contexts = array(); foreach ( $schema['properties'] as $attributes ) { if ( ! empty( $attributes['context'] ) ) { $contexts = array_merge( $contexts, $attributes['context'] ); } } if ( ! empty( $contexts ) ) { $param_details['enum'] = array_unique( $contexts ); rsort( $param_details['enum'] ); } return array_merge( $param_details, $args ); } /** * Adds the values from additional fields to a data object. * * @since 4.7.0 * * @param array $object Data object. * @param WP_REST_Request $request Full details about the request. * @return array Modified data object with additional fields. */ protected function add_additional_fields_to_object( $object, $request ) { $additional_fields = $this->get_additional_fields(); $requested_fields = $this->get_fields_for_response( $request ); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['get_callback'] ) { continue; } if ( ! in_array( $field_name, $requested_fields, true ) ) { continue; } $object[ $field_name ] = call_user_func( $field_options['get_callback'], $object, $field_name, $request, $this->get_object_type() ); } return $object; } /** * Updates the values of additional fields added to a data object. * * @since 4.7.0 * * @param array $object Data Object. * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error True on success, WP_Error object if a field cannot be updated. */ protected function update_additional_fields_for_object( $object, $request ) { $additional_fields = $this->get_additional_fields(); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['update_callback'] ) { continue; } // Don't run the update callbacks if the data wasn't passed in the request. if ( ! isset( $request[ $field_name ] ) ) { continue; } $result = call_user_func( $field_options['update_callback'], $request[ $field_name ], $object, $field_name, $request, $this->get_object_type() ); if ( is_wp_error( $result ) ) { return $result; } } return true; } /** * Adds the schema from additional fields to a schema array. * * The type of object is inferred from the passed schema. * * @since 4.7.0 * * @param array $schema Schema array. * @return array Modified Schema array. */ protected function add_additional_fields_schema( $schema ) { if ( empty( $schema['title'] ) ) { return $schema; } // Can't use $this->get_object_type otherwise we cause an inf loop. $object_type = $schema['title']; $additional_fields = $this->get_additional_fields( $object_type ); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['schema'] ) { continue; } $schema['properties'][ $field_name ] = $field_options['schema']; } return $schema; } /** * Retrieves all of the registered additional fields for a given object-type. * * @since 4.7.0 * * @param string $object_type Optional. The object type. * @return array Registered additional fields (if any), empty array if none or if the object type could * not be inferred. */ protected function get_additional_fields( $object_type = null ) { if ( ! $object_type ) { $object_type = $this->get_object_type(); } if ( ! $object_type ) { return array(); } global $wp_rest_additional_fields; if ( ! $wp_rest_additional_fields || ! isset( $wp_rest_additional_fields[ $object_type ] ) ) { return array(); } return $wp_rest_additional_fields[ $object_type ]; } /** * Retrieves the object type this controller is responsible for managing. * * @since 4.7.0 * * @return string Object type for the controller. */ protected function get_object_type() { $schema = $this->get_item_schema(); if ( ! $schema || ! isset( $schema['title'] ) ) { return null; } return $schema['title']; } /** * Gets an array of fields to be included on the response. * * Included fields are based on item schema and `_fields=` request argument. * * @since 4.9.6 * * @param WP_REST_Request $request Full details about the request. * @return array Fields to be included in the response. */ public function get_fields_for_response( $request ) { $schema = $this->get_item_schema(); $fields = isset( $schema['properties'] ) ? array_keys( $schema['properties'] ) : array(); $additional_fields = $this->get_additional_fields(); foreach ( $additional_fields as $field_name => $field_options ) { // For back-compat, include any field with an empty schema // because it won't be present in $this->get_item_schema(). if ( is_null( $field_options['schema'] ) ) { $fields[] = $field_name; } } if ( ! isset( $request['_fields'] ) ) { return $fields; } $requested_fields = is_array( $request['_fields'] ) ? $request['_fields'] : preg_split( '/[\s,]+/', $request['_fields'] ); if ( 0 === count( $requested_fields ) ) { return $fields; } // Trim off outside whitespace from the comma delimited list. $requested_fields = array_map( 'trim', $requested_fields ); // Always persist 'id', because it can be needed for add_additional_fields_to_object(). if ( in_array( 'id', $fields, true ) ) { $requested_fields[] = 'id'; } return array_intersect( $fields, $requested_fields ); } /** * Retrieves an array of endpoint arguments from the item schema for the controller. * * @since 4.7.0 * * @param string $method Optional. HTTP method of the request. The arguments for `CREATABLE` requests are * checked for required values and may fall-back to a given default, this is not done * on `EDITABLE` requests. Default WP_REST_Server::CREATABLE. * @return array Endpoint arguments. */ public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) { $schema = $this->get_item_schema(); $schema_properties = ! empty( $schema['properties'] ) ? $schema['properties'] : array(); $endpoint_args = array(); foreach ( $schema_properties as $field_id => $params ) { // Arguments specified as `readonly` are not allowed to be set. if ( ! empty( $params['readonly'] ) ) { continue; } $endpoint_args[ $field_id ] = array( 'validate_callback' => 'rest_validate_request_arg', 'sanitize_callback' => 'rest_sanitize_request_arg', ); if ( isset( $params['description'] ) ) { $endpoint_args[ $field_id ]['description'] = $params['description']; } if ( WP_REST_Server::CREATABLE === $method && isset( $params['default'] ) ) { $endpoint_args[ $field_id ]['default'] = $params['default']; } if ( WP_REST_Server::CREATABLE === $method && ! empty( $params['required'] ) ) { $endpoint_args[ $field_id ]['required'] = true; } foreach ( array( 'type', 'format', 'enum', 'items', 'properties', 'additionalProperties' ) as $schema_prop ) { if ( isset( $params[ $schema_prop ] ) ) { $endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ]; } } // Merge in any options provided by the schema property. if ( isset( $params['arg_options'] ) ) { // Only use required / default from arg_options on CREATABLE endpoints. if ( WP_REST_Server::CREATABLE !== $method ) { $params['arg_options'] = array_diff_key( $params['arg_options'], array( 'required' => '', 'default' => '' ) ); } $endpoint_args[ $field_id ] = array_merge( $endpoint_args[ $field_id ], $params['arg_options'] ); } } return $endpoint_args; } /** * Sanitizes the slug value. * * @since 4.7.0 * * @internal We can't use sanitize_title() directly, as the second * parameter is the fallback title, which would end up being set to the * request object. * * @see https://github.com/WP-API/WP-API/issues/1585 * * @todo Remove this in favour of https://core.trac.wordpress.org/ticket/34659 * * @param string $slug Slug value passed in request. * @return string Sanitized value for the slug. */ public function sanitize_slug( $slug ) { return sanitize_title( $slug ); } }
{ "content_hash": "c6f5375d0e1fdebe3b79be17d6e15c06", "timestamp": "", "source": "github", "line_count": 628, "max_line_length": 161, "avg_line_length": 30.96019108280255, "alnum_prop": 0.6233605925011573, "repo_name": "agencja-acclaim/gulp-bower-webapp", "id": "caee7204eafb3fe5a8ebbaee882cd3c22ab30171", "size": "19443", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "wp-includes/rest-api/endpoints/class-wp-rest-controller.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "290204" }, { "name": "JavaScript", "bytes": "455702" }, { "name": "PHP", "bytes": "159275" } ], "symlink_target": "" }
require 'reviewlette/trello_connection' require 'reviewlette/github_connection' require 'yaml' class Reviewlette def initialize(members:, github_config: nil, trello_config: nil) @trello = TrelloConnection.new(trello_config) @github = github_config || YAML.load_file("#{File.dirname(__FILE__)}/../config/github.yml") @members = members end def run @github['repos'].each do |repo| puts "Checking repository #{repo}..." check_repo(repo, @github['token']) end end def check_repo(repo_name, token) repo = GithubConnection.new(repo_name, token) unless repo.repo_exists? puts "Repository #{repo_name} does not exist. Check your configuration" return end repo.pull_requests.each do |issue| issue_id = issue[:number] issue_title = issue[:title] issue_labels = repo.labels(issue_id) puts "*** Checking GitHub pull request: #{issue_title}" matched = issue_title.match(/\d+[_'"]?$/) unless matched puts 'Pull request not assigned to a trello card' next end card_id = matched[0].to_i card = @trello.find_card_by_id(card_id) unless card puts "No matching card found (id #{card_id})" next end puts "Found matching trello card: #{card.name}" assignees = issue[:assignees].map(&:login) already_assigned_members = @members.select { |m| assignees.include? m.github_handle } wanted_number = how_many_should_review(issue_labels) if assignees.size < wanted_number reviewers = select_reviewers(card, wanted_number, already_assigned_members) if reviewers.empty? puts "Could not find a reviewer for card: #{card.name}" next end repo.add_assignees(issue_id, reviewers.map { |r| r.github_handle } ) repo.comment_reviewers(issue_id, reviewers, card) @trello.comment_reviewers(card, repo_name, issue_id, reviewers) @trello.move_card_to_list(card, 'In review') already_assigned_members end end end def select_reviewers(card, number = 1, already_assigned = []) reviewers = @members reviewers.reject! { |r| card.members.map(&:username).include? r.trello_handle } reviewers -= already_assigned reviewers.sample(number - already_assigned.size) + already_assigned end def how_many_should_review(labels) return 2 if labels.include? '2 reviewers' 1 end end
{ "content_hash": "e30fa66ad114bfc03fc4440b80180569", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 96, "avg_line_length": 29.734939759036145, "alnum_prop": 0.6438411669367909, "repo_name": "SUSE/reviewlette", "id": "74a094f6398f273cc2ade2e13c102907475e88e1", "size": "2468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/reviewlette.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "25992" } ], "symlink_target": "" }
#include <assert.h> #include <string.h> /* strlen () */ #include <event2/buffer.h> #include "transmission.h" #include "crypto-utils.h" /* tr_sha1 */ #include "file.h" #include "log.h" #include "metainfo.h" #include "platform.h" /* tr_getTorrentDir () */ #include "session.h" #include "utils.h" #include "variant.h" /*** **** ***/ #ifdef _WIN32 #define PATH_DELIMITER_CHARS "/\\" #else #define PATH_DELIMITER_CHARS "/" #endif static inline bool char_is_path_separator (char c) { return strchr(PATH_DELIMITER_CHARS, c) != NULL; } char* tr_metainfoGetBasename (const tr_info * inf) { size_t i; const char * name = inf->originalName; const size_t name_len = strlen (name); char * ret = tr_strdup_printf ("%s.%16.16s", name, inf->hashString); for (i=0; i<name_len; ++i) if (char_is_path_separator (ret[i])) ret[i] = '_'; return ret; } static char* getTorrentFilename (const tr_session * session, const tr_info * inf) { char * base = tr_metainfoGetBasename (inf); char * filename = tr_strdup_printf ("%s" TR_PATH_DELIMITER_STR "%s.torrent", tr_getTorrentDir (session), base); tr_free (base); return filename; } /*** **** ***/ static bool path_component_is_suspicious (const char * component) { return (component == NULL) || (strpbrk (component, PATH_DELIMITER_CHARS) != NULL) || (strcmp (component, ".") == 0) || (strcmp (component, "..") == 0); } static bool getfile (char ** setme, const char * root, tr_variant * path, struct evbuffer * buf) { bool success = false; size_t root_len = 0; *setme = NULL; /* root's already been checked by caller */ assert (!path_component_is_suspicious (root)); if (tr_variantIsList (path)) { int i; const int n = tr_variantListSize (path); success = true; evbuffer_drain (buf, evbuffer_get_length (buf)); root_len = strlen (root); evbuffer_add (buf, root, root_len); for (i=0; i<n; i++) { size_t len; const char * str; if (!tr_variantGetStr (tr_variantListChild (path, i), &str, &len) || path_component_is_suspicious (str)) { success = false; break; } if (!*str) continue; evbuffer_add (buf, TR_PATH_DELIMITER_STR, 1); evbuffer_add (buf, str, len); } } if (success && (evbuffer_get_length (buf) <= root_len)) { success = false; } if (success) { *setme = tr_utf8clean ((char*)evbuffer_pullup (buf, -1), evbuffer_get_length (buf)); /*fprintf (stderr, "[%s]\n", *setme);*/ } return success; } static const char* parseFiles (tr_info * inf, tr_variant * files, const tr_variant * length) { int64_t len; inf->totalSize = 0; if (tr_variantIsList (files)) /* multi-file mode */ { tr_file_index_t i; struct evbuffer * buf; const char * result; if (path_component_is_suspicious (inf->name)) return "path"; buf = evbuffer_new (); result = NULL; inf->isFolder = true; inf->fileCount = tr_variantListSize (files); inf->files = tr_new0 (tr_file, inf->fileCount); for (i=0; i<inf->fileCount; i++) { tr_variant * file; tr_variant * path; file = tr_variantListChild (files, i); if (!tr_variantIsDict (file)) { result = "files"; break; } if (!tr_variantDictFindList (file, TR_KEY_path_utf_8, &path)) if (!tr_variantDictFindList (file, TR_KEY_path, &path)) { result = "path"; break; } if (!getfile (&inf->files[i].name, inf->name, path, buf)) { result = "path"; break; } if (!tr_variantDictFindInt (file, TR_KEY_length, &len)) { result = "length"; break; } inf->files[i].length = len; inf->totalSize += len; } evbuffer_free (buf); return result; } else if (tr_variantGetInt (length, &len)) /* single-file mode */ { if (path_component_is_suspicious (inf->name)) return "path"; inf->isFolder = false; inf->fileCount = 1; inf->files = tr_new0 (tr_file, 1); inf->files[0].name = tr_strdup (inf->name); inf->files[0].length = len; inf->totalSize += len; } else { return "length"; } return NULL; } static char * tr_convertAnnounceToScrape (const char * announce) { char * scrape = NULL; const char * s; /* To derive the scrape URL use the following steps: * Begin with the announce URL. Find the last '/' in it. * If the text immediately following that '/' isn't 'announce' * it will be taken as a sign that that tracker doesn't support * the scrape convention. If it does, substitute 'scrape' for * 'announce' to find the scrape page. */ if (((s = strrchr (announce, '/'))) && !strncmp (++s, "announce", 8)) { const char * prefix = announce; const size_t prefix_len = s - announce; const char * suffix = s + 8; const size_t suffix_len = strlen (suffix); const size_t alloc_len = prefix_len + 6 + suffix_len + 1; char * walk = scrape = tr_new (char, alloc_len); memcpy (walk, prefix, prefix_len); walk += prefix_len; memcpy (walk, "scrape", 6); walk += 6; memcpy (walk, suffix, suffix_len); walk += suffix_len; *walk++ = '\0'; assert (walk - scrape == (int)alloc_len); } /* Some torrents with UDP annouce URLs don't have /announce. */ else if (!strncmp (announce, "udp:", 4)) { scrape = tr_strdup (announce); } return scrape; } static const char* getannounce (tr_info * inf, tr_variant * meta) { size_t len; const char * str; tr_tracker_info * trackers = NULL; int trackerCount = 0; tr_variant * tiers; /* Announce-list */ if (tr_variantDictFindList (meta, TR_KEY_announce_list, &tiers)) { int n; int i, j, validTiers; const int numTiers = tr_variantListSize (tiers); n = 0; for (i=0; i<numTiers; i++) n += tr_variantListSize (tr_variantListChild (tiers, i)); trackers = tr_new0 (tr_tracker_info, n); for (i=0, validTiers=0; i<numTiers; i++) { tr_variant * tier = tr_variantListChild (tiers, i); const int tierSize = tr_variantListSize (tier); bool anyAdded = false; for (j=0; j<tierSize; j++) { if (tr_variantGetStr (tr_variantListChild (tier, j), &str, &len)) { char * url = tr_strstrip (tr_strndup (str, len)); if (!tr_urlIsValidTracker (url)) { tr_free (url); } else { tr_tracker_info * t = trackers + trackerCount; t->tier = validTiers; t->announce = url; t->scrape = tr_convertAnnounceToScrape (url); t->id = trackerCount; anyAdded = true; ++trackerCount; } } } if (anyAdded) ++validTiers; } /* did we use any of the tiers? */ if (!trackerCount) { tr_free (trackers); trackers = NULL; } } /* Regular announce value */ if (!trackerCount && tr_variantDictFindStr (meta, TR_KEY_announce, &str, &len)) { char * url = tr_strstrip (tr_strndup (str, len)); if (!tr_urlIsValidTracker (url)) { tr_free (url); } else { trackers = tr_new0 (tr_tracker_info, 1); trackers[trackerCount].tier = 0; trackers[trackerCount].announce = url; trackers[trackerCount].scrape = tr_convertAnnounceToScrape (url); trackers[trackerCount].id = 0; trackerCount++; /*fprintf (stderr, "single announce: [%s]\n", url);*/ } } inf->trackers = trackers; inf->trackerCount = trackerCount; return NULL; } /** * @brief Ensure that the URLs for multfile torrents end in a slash. * * See http://bittorrent.org/beps/bep_0019.html#metadata-extension * for background on how the trailing slash is used for "url-list" * fields. * * This function is to workaround some .torrent generators, such as * mktorrent and very old versions of utorrent, that don't add the * trailing slash for multifile torrents if omitted by the end user. */ static char* fix_webseed_url (const tr_info * inf, const char * url_in) { size_t len; char * url; char * ret = NULL; url = tr_strdup (url_in); tr_strstrip (url); len = strlen (url); if (tr_urlIsValid (url, len)) { if ((inf->fileCount > 1) && (len > 0) && (url[len-1] != '/')) ret = tr_strdup_printf ("%*.*s/", (int)len, (int)len, url); else ret = tr_strndup (url, len); } tr_free (url); return ret; } static void geturllist (tr_info * inf, tr_variant * meta) { tr_variant * urls; const char * url; if (tr_variantDictFindList (meta, TR_KEY_url_list, &urls)) { int i; const int n = tr_variantListSize (urls); inf->webseedCount = 0; inf->webseeds = tr_new0 (char*, n); for (i=0; i<n; i++) { if (tr_variantGetStr (tr_variantListChild (urls, i), &url, NULL)) { char * fixed_url = fix_webseed_url (inf, url); if (fixed_url != NULL) inf->webseeds[inf->webseedCount++] = fixed_url; } } } else if (tr_variantDictFindStr (meta, TR_KEY_url_list, &url, NULL)) /* handle single items in webseeds */ { char * fixed_url = fix_webseed_url (inf, url); if (fixed_url != NULL) { inf->webseedCount = 1; inf->webseeds = tr_new0 (char*, 1); inf->webseeds[0] = fixed_url; } } } static const char* tr_metainfoParseImpl (const tr_session * session, tr_info * inf, bool * hasInfoDict, size_t * infoDictLength, const tr_variant * meta_in) { int64_t i; size_t len; const char * str; const uint8_t * raw; tr_variant * d; tr_variant * infoDict = NULL; tr_variant * meta = (tr_variant *) meta_in; bool b; bool isMagnet = false; /* info_hash: urlencoded 20-byte SHA1 hash of the value of the info key * from the Metainfo file. Note that the value will be a bencoded * dictionary, given the definition of the info key above. */ b = tr_variantDictFindDict (meta, TR_KEY_info, &infoDict); if (hasInfoDict != NULL) *hasInfoDict = b; if (!b) { /* no info dictionary... is this a magnet link? */ if (tr_variantDictFindDict (meta, TR_KEY_magnet_info, &d)) { isMagnet = true; /* get the info-hash */ if (!tr_variantDictFindRaw (d, TR_KEY_info_hash, &raw, &len)) return "info_hash"; if (len != SHA_DIGEST_LENGTH) return "info_hash"; memcpy (inf->hash, raw, len); tr_sha1_to_hex (inf->hashString, inf->hash); /* maybe get the display name */ if (tr_variantDictFindStr (d, TR_KEY_display_name, &str, &len)) { tr_free (inf->name); tr_free (inf->originalName); inf->name = tr_strndup (str, len); inf->originalName = tr_strndup (str, len); } if (!inf->name) inf->name = tr_strdup (inf->hashString); if (!inf->originalName) inf->originalName = tr_strdup (inf->hashString); } else /* not a magnet link and has no info dict... */ { return "info"; } } else { size_t len; char * bstr = tr_variantToStr (infoDict, TR_VARIANT_FMT_BENC, &len); tr_sha1 (inf->hash, bstr, len, NULL); tr_sha1_to_hex (inf->hashString, inf->hash); if (infoDictLength != NULL) *infoDictLength = len; tr_free (bstr); } /* name */ if (!isMagnet) { len = 0; if (!tr_variantDictFindStr (infoDict, TR_KEY_name_utf_8, &str, &len)) if (!tr_variantDictFindStr (infoDict, TR_KEY_name, &str, &len)) str = ""; if (!str || !*str) return "name"; tr_free (inf->name); tr_free (inf->originalName); inf->name = tr_utf8clean (str, len); inf->originalName = tr_strdup (inf->name); } /* comment */ len = 0; if (!tr_variantDictFindStr (meta, TR_KEY_comment_utf_8, &str, &len)) if (!tr_variantDictFindStr (meta, TR_KEY_comment, &str, &len)) str = ""; tr_free (inf->comment); inf->comment = tr_utf8clean (str, len); /* created by */ len = 0; if (!tr_variantDictFindStr (meta, TR_KEY_created_by_utf_8, &str, &len)) if (!tr_variantDictFindStr (meta, TR_KEY_created_by, &str, &len)) str = ""; tr_free (inf->creator); inf->creator = tr_utf8clean (str, len); /* creation date */ if (!tr_variantDictFindInt (meta, TR_KEY_creation_date, &i)) i = 0; inf->dateCreated = i; /* private */ if (!tr_variantDictFindInt (infoDict, TR_KEY_private, &i)) if (!tr_variantDictFindInt (meta, TR_KEY_private, &i)) i = 0; inf->isPrivate = i != 0; /* piece length */ if (!isMagnet) { if (!tr_variantDictFindInt (infoDict, TR_KEY_piece_length, &i) || (i < 1)) return "piece length"; inf->pieceSize = i; } /* pieces */ if (!isMagnet) { if (!tr_variantDictFindRaw (infoDict, TR_KEY_pieces, &raw, &len)) return "pieces"; if (len % SHA_DIGEST_LENGTH) return "pieces"; inf->pieceCount = len / SHA_DIGEST_LENGTH; inf->pieces = tr_new0 (tr_piece, inf->pieceCount); for (i=0; i<inf->pieceCount; i++) memcpy (inf->pieces[i].hash, &raw[i * SHA_DIGEST_LENGTH], SHA_DIGEST_LENGTH); } /* files */ if (!isMagnet) { if ((str = parseFiles (inf, tr_variantDictFind (infoDict, TR_KEY_files), tr_variantDictFind (infoDict, TR_KEY_length)))) return str; if (!inf->fileCount || !inf->totalSize) return "files"; if ((uint64_t) inf->pieceCount != (inf->totalSize + inf->pieceSize - 1) / inf->pieceSize) return "files"; } /* get announce or announce-list */ if ((str = getannounce (inf, meta))) return str; /* get the url-list */ geturllist (inf, meta); /* filename of Transmission's copy */ tr_free (inf->torrent); inf->torrent = session ? getTorrentFilename (session, inf) : NULL; return NULL; } bool tr_metainfoParse (const tr_session * session, const tr_variant * meta_in, tr_info * inf, bool * hasInfoDict, size_t * infoDictLength) { const char * badTag = tr_metainfoParseImpl (session, inf, hasInfoDict, infoDictLength, meta_in); const bool success = badTag == NULL; if (badTag) { tr_logAddNamedError (inf->name, _("Invalid metadata entry \"%s\""), badTag); tr_metainfoFree (inf); } return success; } void tr_metainfoFree (tr_info * inf) { unsigned int i; tr_file_index_t ff; for (i=0; i<inf->webseedCount; i++) tr_free (inf->webseeds[i]); for (ff=0; ff<inf->fileCount; ff++) tr_free (inf->files[ff].name); tr_free (inf->webseeds); tr_free (inf->pieces); tr_free (inf->files); tr_free (inf->comment); tr_free (inf->creator); tr_free (inf->torrent); tr_free (inf->originalName); tr_free (inf->name); for (i=0; i<inf->trackerCount; i++) { tr_free (inf->trackers[i].announce); tr_free (inf->trackers[i].scrape); } tr_free (inf->trackers); memset (inf, '\0', sizeof (tr_info)); } void tr_metainfoRemoveSaved (const tr_session * session, const tr_info * inf) { char * filename; filename = getTorrentFilename (session, inf); tr_sys_path_remove (filename, NULL); tr_free (filename); }
{ "content_hash": "076d2dcae0900cef93eb82d908e2ce5d", "timestamp": "", "source": "github", "line_count": 630, "max_line_length": 107, "avg_line_length": 26.355555555555554, "alnum_prop": 0.5359551915201156, "repo_name": "Prodito/Torrentor", "id": "2c04e4d887a083ca2796bf1135e14342b0873753", "size": "16779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/libtransmission/metainfo.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1609231" }, { "name": "C++", "bytes": "593961" }, { "name": "Objective-C", "bytes": "60805" }, { "name": "Shell", "bytes": "1398" } ], "symlink_target": "" }
import $ from "jquery"; import Promise from "bluebird"; /** * Function to convert jquery deferred to promise like style * @param url path to endpoitn * @param type request type (GET|POST etc) * @param params url parameters as object * @param body request body (object to json) * @returns {Promise} */ export function request({url, type, params, body={}}) { if (!_.isUndefined(params)) { url = `${url}${$.param(params, true)}`; } return $.ajax(url, { type, data: body, contentType: "application/json", dataType: "json" }) .then((result) => { Promise.resolve(result); }) .catch((error) => { let customError = new Error(error.status ? error.message || "MALFORMED_ERROR" : "MALFORMED_ERROR"); Promise.reject(customError); }) } export const GET = ({url, params}) => { return request({url, type: "GET", params}) }; export const POST = ({url, body}) => { return request({url, type: "POST", body}) }; export const PUT = ({url, body}) => { return request({url, type: "PUT", body}) };
{ "content_hash": "608a6203424f928fc6a346a657f54cce", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 115, "avg_line_length": 27.857142857142858, "alnum_prop": 0.5538461538461539, "repo_name": "yavalvas/react-blog", "id": "1cb0b45abf67ea91a0063f49f0e35a6507006103", "size": "1170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/public/javascripts/middleware/middleware_utils.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "526" }, { "name": "HTML", "bytes": "1309" }, { "name": "JavaScript", "bytes": "24820" } ], "symlink_target": "" }
""" Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. """ __author__ = 'Danyang' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): """ O(n)+O(n) :param head: head node :param n: the nth node from the end :return: ListNode, head node """ # construct dummy dummy = ListNode(0) dummy.next = head # get length of the linked list length = 0 pre = dummy while pre.next: length += 1 pre=pre.next # find & remove pre = dummy count = 0 while pre.next: cur = pre.next if count==length-n: pre.next = cur.next # remove break else: count += 1 pre = pre.next return dummy.next
{ "content_hash": "904d99197e9df29ab7460d4764e2e7e5", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 83, "avg_line_length": 23.943396226415093, "alnum_prop": 0.4980299448384555, "repo_name": "algorhythms/LeetCode", "id": "41529a7bd2c40f1bb47863031dffc9d358a8a34b", "size": "1269", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "019 Remove Nth Node From End of List.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "1444167" } ], "symlink_target": "" }
const gulp = require('gulp'), nodemon = require('gulp-nodemon'), sass = require('gulp-sass'), buffer = require('vinyl-buffer'), // check if needed babelify = require('babelify'), browserify = require('browserify'), source = require('vinyl-source-stream'), // check if needed sourcemaps = require('gulp-sourcemaps'), rev = require('gulp-rev'), revDel = require('rev-del'), uglify = require('gulp-uglify'), size = require('gulp-size'), mocha = require('gulp-mocha'), concat = require('gulp-concat'); gulp.task('js:vendor', () => { gulp.src([ 'frontend/js/vendor/jquery.js', 'node_modules/tether/dist/js/tether.min.js', 'node_modules/bootstrap/dist/js/bootstrap.min.js' ]).pipe(concat('vendor.js')) .pipe(size()) .pipe(rev()) .pipe(gulp.dest('public/js')) .pipe(rev.manifest('config/assets.json', { base: 'config', merge: true })) .pipe(revDel({ dest: 'public/js', oldManifest: 'config/assets.json' })) .pipe(gulp.dest('config')); }); gulp.task('js:application', () => { var bundler = browserify({ entries: 'frontend/js/application.js', debug: true }); bundler.transform(babelify, { presets: ["es2015"] }); bundler.bundle() .on('error', function(err) { console.log('ERROR OCCURED ON js:compile'.red); console.error(err); notifier.notify({ title: 'build failed', message: err }); }) .pipe(source('application.js')) .pipe(buffer()) .pipe(size()) .pipe(rev()) .pipe(gulp.dest('public/js')) .pipe(rev.manifest('config/assets.json', { base: 'config', merge: true })) .pipe(revDel({ dest: 'public/js', oldManifest: 'config/assets.json' })) .pipe(gulp.dest('config')); }); gulp.task('scss:vendor', () => { gulp.src([ 'node_modules/bootstrap/dist/css/bootstrap.min.css' ]).pipe(concat('vendor.css')) .pipe(size()) .pipe(rev()) .pipe(gulp.dest('public/css')) .pipe(rev.manifest('config/assets.json', { base: 'config', merge: true })) .pipe(revDel({ dest: 'public/css', oldManifest: 'config/assets.json' })) .pipe(gulp.dest('config')); }); gulp.task('scss:application', () => { return gulp.src('frontend/scss/application.scss') .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'compressed' })) .pipe(concat({ path: 'application.css', cwd: '' })) .pipe(size()) .pipe(rev()) .pipe(sourcemaps.write()) .pipe(gulp.dest('public/css')) .pipe(rev.manifest('config/assets.json', { base: 'config', merge: true })) .pipe(revDel({ dest: 'public/css', oldManifest: 'config/assets.json' })) .pipe(gulp.dest('config')); }); gulp.task('default', ['scss:vendor', 'scss:application', 'js:vendor', 'js:application'], () => { gulp.watch('frontend/scss/**/*.scss', ['scss:vendor', 'scss:application']); gulp.watch('frontend/js/**/*.js', ['js:vendor', 'js:application']); nodemon(); });
{ "content_hash": "d3b888a404694093164c411df6ecf3db", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 96, "avg_line_length": 28.39090909090909, "alnum_prop": 0.5686839577329491, "repo_name": "elakorkmaz/new-personal-website", "id": "d39dce91f9f3be4e66852f6c0547a228450b3a22", "size": "3123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9502" }, { "name": "HTML", "bytes": "18220" }, { "name": "JavaScript", "bytes": "6802" } ], "symlink_target": "" }
package org.docksidestage.hanger.dbflute.cbean.bs; import org.dbflute.cbean.AbstractConditionBean; import org.dbflute.cbean.ConditionBean; import org.dbflute.cbean.ConditionQuery; import org.dbflute.cbean.chelper.*; import org.dbflute.cbean.coption.*; import org.dbflute.cbean.dream.*; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.cbean.sqlclause.SqlClauseCreator; import org.dbflute.cbean.scoping.*; import org.dbflute.dbmeta.DBMetaProvider; import org.dbflute.twowaysql.factory.SqlAnalyzerFactory; import org.dbflute.twowaysql.style.BoundDateDisplayTimeZoneProvider; import org.docksidestage.hanger.dbflute.allcommon.CDef; import org.docksidestage.hanger.dbflute.allcommon.DBFluteConfig; import org.docksidestage.hanger.dbflute.allcommon.DBMetaInstanceHandler; import org.docksidestage.hanger.dbflute.allcommon.ImplementedInvokerAssistant; import org.docksidestage.hanger.dbflute.allcommon.ImplementedSqlClauseCreator; import org.docksidestage.hanger.dbflute.cbean.*; import org.docksidestage.hanger.dbflute.cbean.cq.*; /** * The base condition-bean of MEMBER_STATUS. * @author DBFlute(AutoGenerator) */ public class BsMemberStatusCB extends AbstractConditionBean { // =================================================================================== // Attribute // ========= protected MemberStatusCQ _conditionQuery; // =================================================================================== // Constructor // =========== public BsMemberStatusCB() { if (DBFluteConfig.getInstance().isPagingCountLater()) { enablePagingCountLater(); } if (DBFluteConfig.getInstance().isPagingCountLeastJoin()) { enablePagingCountLeastJoin(); } if (DBFluteConfig.getInstance().isNonSpecifiedColumnAccessAllowed()) { enableNonSpecifiedColumnAccess(); } if (DBFluteConfig.getInstance().isQueryUpdateCountPreCheck()) { enableQueryUpdateCountPreCheck(); } } // =================================================================================== // SqlClause // ========= @Override protected SqlClause createSqlClause() { SqlClauseCreator creator = DBFluteConfig.getInstance().getSqlClauseCreator(); if (creator != null) { return creator.createSqlClause(this); } return new ImplementedSqlClauseCreator().createSqlClause(this); // as default } // =================================================================================== // DB Meta // ======= @Override protected DBMetaProvider getDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); // as default } public String asTableDbName() { return "MEMBER_STATUS"; } // =================================================================================== // PrimaryKey Handling // =================== /** * Accept the query condition of primary key as equal. * @param memberStatusCode (会員ステータスコード): PK, NotNull, CHAR(3), classification=MemberStatus. (NotNull) * @return this. (NotNull) */ public MemberStatusCB acceptPK(CDef.MemberStatus memberStatusCode) { assertObjectNotNull("memberStatusCode", memberStatusCode); BsMemberStatusCB cb = this; cb.query().setMemberStatusCode_Equal_AsMemberStatus(memberStatusCode); return (MemberStatusCB)this; } /** * Accept the query condition of unique key as equal. * @param displayOrder (表示順): UQ, NotNull, INTEGER(10). (NotNull) * @return this. (NotNull) */ public MemberStatusCB acceptUniqueOf(Integer displayOrder) { assertObjectNotNull("displayOrder", displayOrder); BsMemberStatusCB cb = this; cb.query().setDisplayOrder_Equal(displayOrder); return (MemberStatusCB)this; } public ConditionBean addOrderBy_PK_Asc() { query().addOrderBy_MemberStatusCode_Asc(); return this; } public ConditionBean addOrderBy_PK_Desc() { query().addOrderBy_MemberStatusCode_Desc(); return this; } // =================================================================================== // Query // ===== /** * Prepare for various queries. <br> * Examples of main functions are following: * <pre> * <span style="color: #3F7E5E">// Basic Queries</span> * cb.query().setMemberId_Equal(value); <span style="color: #3F7E5E">// =</span> * cb.query().setMemberId_NotEqual(value); <span style="color: #3F7E5E">// !=</span> * cb.query().setMemberId_GreaterThan(value); <span style="color: #3F7E5E">// &gt;</span> * cb.query().setMemberId_LessThan(value); <span style="color: #3F7E5E">// &lt;</span> * cb.query().setMemberId_GreaterEqual(value); <span style="color: #3F7E5E">// &gt;=</span> * cb.query().setMemberId_LessEqual(value); <span style="color: #3F7E5E">// &lt;=</span> * cb.query().setMemberName_InScope(valueList); <span style="color: #3F7E5E">// in ('a', 'b')</span> * cb.query().setMemberName_NotInScope(valueList); <span style="color: #3F7E5E">// not in ('a', 'b')</span> * <span style="color: #3F7E5E">// LikeSearch with various options: (versatile)</span> * <span style="color: #3F7E5E">// {like ... [options]}</span> * cb.query().setMemberName_LikeSearch(value, option); * cb.query().setMemberName_NotLikeSearch(value, option); <span style="color: #3F7E5E">// not like ...</span> * <span style="color: #3F7E5E">// FromTo with various options: (versatile)</span> * <span style="color: #3F7E5E">// {(default) fromDatetime &lt;= BIRTHDATE &lt;= toDatetime}</span> * cb.query().setBirthdate_FromTo(fromDatetime, toDatetime, option); * <span style="color: #3F7E5E">// DateFromTo: (Date means yyyy/MM/dd)</span> * <span style="color: #3F7E5E">// {fromDate &lt;= BIRTHDATE &lt; toDate + 1 day}</span> * cb.query().setBirthdate_IsNull(); <span style="color: #3F7E5E">// is null</span> * cb.query().setBirthdate_IsNotNull(); <span style="color: #3F7E5E">// is not null</span> * * <span style="color: #3F7E5E">// ExistsReferrer: (correlated sub-query)</span> * <span style="color: #3F7E5E">// {where exists (select PURCHASE_ID from PURCHASE where ...)}</span> * cb.query().existsPurchase(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }); * cb.query().notExistsPurchase... * * <span style="color: #3F7E5E">// (Query)DerivedReferrer: (correlated sub-query)</span> * cb.query().derivedPurchaseList().max(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.specify().columnPurchasePrice(); <span style="color: #3F7E5E">// derived column for function</span> * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }).greaterEqual(value); * * <span style="color: #3F7E5E">// ScalarCondition: (self-table sub-query)</span> * cb.query().scalar_Equal().max(scalarCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * scalarCB.specify().columnBirthdate(); <span style="color: #3F7E5E">// derived column for function</span> * scalarCB.query().set... <span style="color: #3F7E5E">// scalar sub-query condition</span> * }); * * <span style="color: #3F7E5E">// OrderBy</span> * cb.query().addOrderBy_MemberName_Asc(); * cb.query().addOrderBy_MemberName_Desc().withManualOrder(option); * cb.query().addOrderBy_MemberName_Desc().withNullsFirst(); * cb.query().addOrderBy_MemberName_Desc().withNullsLast(); * cb.query().addSpecifiedDerivedOrderBy_Desc(aliasName); * * <span style="color: #3F7E5E">// Query(Relation)</span> * cb.query().queryMemberStatus()...; * cb.query().queryMemberAddressAsValid(targetDate)...; * </pre> * @return The instance of condition-query for base-point table to set up query. (NotNull) */ public MemberStatusCQ query() { assertQueryPurpose(); // assert only when user-public query return doGetConditionQuery(); } public MemberStatusCQ xdfgetConditionQuery() { // public for parameter comment and internal return doGetConditionQuery(); } protected MemberStatusCQ doGetConditionQuery() { if (_conditionQuery == null) { _conditionQuery = createLocalCQ(); } return _conditionQuery; } protected MemberStatusCQ createLocalCQ() { return xcreateCQ(null, getSqlClause(), getSqlClause().getBasePointAliasName(), 0); } protected MemberStatusCQ xcreateCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { MemberStatusCQ cq = xnewCQ(childQuery, sqlClause, aliasName, nestLevel); cq.xsetBaseCB(this); return cq; } protected MemberStatusCQ xnewCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { return new MemberStatusCQ(childQuery, sqlClause, aliasName, nestLevel); } /** * {@inheritDoc} */ public ConditionQuery localCQ() { return doGetConditionQuery(); } // =================================================================================== // Union // ===== /** * Set up 'union' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">union</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union'. (NotNull) */ public void union(UnionQuery<MemberStatusCB> unionCBLambda) { final MemberStatusCB cb = new MemberStatusCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final MemberStatusCQ cq = cb.query(); query().xsetUnionQuery(cq); } /** * Set up 'union all' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">unionAll</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union all'. (NotNull) */ public void unionAll(UnionQuery<MemberStatusCB> unionCBLambda) { final MemberStatusCB cb = new MemberStatusCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final MemberStatusCQ cq = cb.query(); query().xsetUnionAllQuery(cq); } // =================================================================================== // SetupSelect // =========== // [DBFlute-0.7.4] // =================================================================================== // Specify // ======= protected HpSpecification _specification; /** * Prepare for SpecifyColumn, (Specify)DerivedReferrer. <br> * This method should be called after SetupSelect. * <pre> * <span style="color: #0000C0">memberBhv</span>.selectEntity(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.setupSelect_MemberStatus(); <span style="color: #3F7E5E">// should be called before specify()</span> * <span style="color: #553000">cb</span>.specify().columnMemberName(); * <span style="color: #553000">cb</span>.specify().specifyMemberStatus().columnMemberStatusName(); * <span style="color: #553000">cb</span>.specify().derivedPurchaseList().max(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().columnPurchaseDatetime(); * <span style="color: #553000">purchaseCB</span>.query().set... * }, aliasName); * }).alwaysPresent(<span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... * }); * </pre> * @return The instance of specification. (NotNull) */ public HpSpecification specify() { assertSpecifyPurpose(); if (_specification == null) { _specification = new HpSpecification(this , xcreateSpQyCall(() -> true, () -> xdfgetConditionQuery()) , _purpose, getDBMetaProvider(), xcSDRFnFc()); } return _specification; } public HpColumnSpHandler localSp() { return specify(); } public boolean hasSpecifiedColumn() { return _specification != null && _specification.isAlreadySpecifiedRequiredColumn(); } public static class HpSpecification extends HpAbstractSpecification<MemberStatusCQ> { public HpSpecification(ConditionBean baseCB, HpSpQyCall<MemberStatusCQ> qyCall , HpCBPurpose purpose, DBMetaProvider dbmetaProvider , HpSDRFunctionFactory sdrFuncFactory) { super(baseCB, qyCall, purpose, dbmetaProvider, sdrFuncFactory); } /** * (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnMemberStatusCode() { return doColumn("MEMBER_STATUS_CODE"); } /** * (会員ステータス名称)MEMBER_STATUS_NAME: {NotNull, VARCHAR(50)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnMemberStatusName() { return doColumn("MEMBER_STATUS_NAME"); } /** * (説明)DESCRIPTION: {NotNull, VARCHAR(200)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnDescription() { return doColumn("DESCRIPTION"); } /** * (表示順)DISPLAY_ORDER: {UQ, NotNull, INTEGER(10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnDisplayOrder() { return doColumn("DISPLAY_ORDER"); } public void everyColumn() { doEveryColumn(); } public void exceptRecordMetaColumn() { doExceptRecordMetaColumn(); } @Override protected void doSpecifyRequiredColumn() { columnMemberStatusCode(); // PK } @Override protected String getTableDbName() { return "MEMBER_STATUS"; } /** * Prepare for (Specify)DerivedReferrer (correlated sub-query). <br> * {select max(FOO) from MEMBER where ...) as FOO_MAX} <br> * (会員)MEMBER by MEMBER_STATUS_CODE, named 'memberList'. * <pre> * cb.specify().<span style="color: #CC4747">derived${relationMethodIdentityName}()</span>.<span style="color: #CC4747">max</span>(memberCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * memberCB.specify().<span style="color: #CC4747">column...</span> <span style="color: #3F7E5E">// derived column by function</span> * memberCB.query().set... <span style="color: #3F7E5E">// referrer condition</span> * }, Member.<span style="color: #CC4747">ALIAS_foo...</span>); * </pre> * @return The object to set up a function for referrer table. (NotNull) */ public HpSDRFunction<MemberCB, MemberStatusCQ> derivedMember() { assertDerived("memberList"); if (xhasSyncQyCall()) { xsyncQyCall().qy(); } // for sync (for example, this in ColumnQuery) return cHSDRF(_baseCB, _qyCall.qy(), (String fn, SubQuery<MemberCB> sq, MemberStatusCQ cq, String al, DerivedReferrerOption op) -> cq.xsderiveMemberList(fn, sq, al, op), _dbmetaProvider); } /** * Prepare for (Specify)DerivedReferrer (correlated sub-query). <br> * {select max(FOO) from MEMBER_LOGIN where ...) as FOO_MAX} <br> * (会員ログイン)MEMBER_LOGIN by LOGIN_MEMBER_STATUS_CODE, named 'memberLoginList'. * <pre> * cb.specify().<span style="color: #CC4747">derived${relationMethodIdentityName}()</span>.<span style="color: #CC4747">max</span>(loginCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * loginCB.specify().<span style="color: #CC4747">column...</span> <span style="color: #3F7E5E">// derived column by function</span> * loginCB.query().set... <span style="color: #3F7E5E">// referrer condition</span> * }, MemberLogin.<span style="color: #CC4747">ALIAS_foo...</span>); * </pre> * @return The object to set up a function for referrer table. (NotNull) */ public HpSDRFunction<MemberLoginCB, MemberStatusCQ> derivedMemberLogin() { assertDerived("memberLoginList"); if (xhasSyncQyCall()) { xsyncQyCall().qy(); } // for sync (for example, this in ColumnQuery) return cHSDRF(_baseCB, _qyCall.qy(), (String fn, SubQuery<MemberLoginCB> sq, MemberStatusCQ cq, String al, DerivedReferrerOption op) -> cq.xsderiveMemberLoginList(fn, sq, al, op), _dbmetaProvider); } } // =================================================================================== // Dream Cruise // ============ /** * Welcome to the Dream Cruise for condition-bean deep world. <br> * This is very specialty so you can get the frontier spirit. Bon voyage! * @return The condition-bean for dream cruise, which is linked to main condition-bean. */ public MemberStatusCB dreamCruiseCB() { MemberStatusCB cb = new MemberStatusCB(); cb.xsetupForDreamCruise((MemberStatusCB) this); return cb; } protected ConditionBean xdoCreateDreamCruiseCB() { return dreamCruiseCB(); } // [DBFlute-0.9.5.3] // =================================================================================== // Column Query // ============ /** * Set up column-query. {column1 = column2} * <pre> * <span style="color: #3F7E5E">// where FOO &lt; BAR</span> * cb.<span style="color: #CC4747">columnQuery</span>(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFoo()</span>; <span style="color: #3F7E5E">// left column</span> * }).lessThan(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnBar()</span>; <span style="color: #3F7E5E">// right column</span> * }); <span style="color: #3F7E5E">// you can calculate for right column like '}).plus(3);'</span> * </pre> * @param colCBLambda The callback for specify-query of left column. (NotNull) * @return The object for setting up operand and right column. (NotNull) */ public HpColQyOperand<MemberStatusCB> columnQuery(final SpecifyQuery<MemberStatusCB> colCBLambda) { return xcreateColQyOperand((rightSp, operand) -> { return xcolqy(xcreateColumnQueryCB(), xcreateColumnQueryCB(), colCBLambda, rightSp, operand); }); } protected MemberStatusCB xcreateColumnQueryCB() { MemberStatusCB cb = new MemberStatusCB(); cb.xsetupForColumnQuery((MemberStatusCB)this); return cb; } // [DBFlute-0.9.6.3] // =================================================================================== // OrScope Query // ============= /** * Set up the query for or-scope. <br> * (Same-column-and-same-condition-key conditions are allowed in or-scope) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or BAR = '...')</span> * cb.<span style="color: #CC4747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.query().setBar... * }); * </pre> * @param orCBLambda The callback for query of or-condition. (NotNull) */ public void orScopeQuery(OrQuery<MemberStatusCB> orCBLambda) { xorSQ((MemberStatusCB)this, orCBLambda); } /** * Set up the and-part of or-scope. <br> * (However nested or-scope query and as-or-split of like-search in and-part are unsupported) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or (BAR = '...' and QUX = '...'))</span> * cb.<span style="color: #994747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.<span style="color: #CC4747">orScopeQueryAndPart</span>(<span style="color: #553000">andCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">andCB</span>.query().setBar... * <span style="color: #553000">andCB</span>.query().setQux... * }); * }); * </pre> * @param andCBLambda The callback for query of and-condition. (NotNull) */ public void orScopeQueryAndPart(AndQuery<MemberStatusCB> andCBLambda) { xorSQAP((MemberStatusCB)this, andCBLambda); } // =================================================================================== // DisplaySQL // ========== @Override protected SqlAnalyzerFactory getSqlAnalyzerFactory() { return new ImplementedInvokerAssistant().assistSqlAnalyzerFactory(); } @Override protected String getConfiguredLogDatePattern() { return DBFluteConfig.getInstance().getLogDatePattern(); } @Override protected String getConfiguredLogTimestampPattern() { return DBFluteConfig.getInstance().getLogTimestampPattern(); } @Override protected String getConfiguredLogTimePattern() { return DBFluteConfig.getInstance().getLogTimePattern(); } @Override protected BoundDateDisplayTimeZoneProvider getConfiguredLogTimeZoneProvider() { return DBFluteConfig.getInstance().getLogTimeZoneProvider(); } // =================================================================================== // Meta Handling // ============= public boolean hasUnionQueryOrUnionAllQuery() { return query().hasUnionQueryOrUnionAllQuery(); } // =================================================================================== // Purpose Type // ============ @Override protected void xprepareSyncQyCall(ConditionBean mainCB) { final MemberStatusCB cb; if (mainCB != null) { cb = (MemberStatusCB)mainCB; } else { cb = new MemberStatusCB(); } specify().xsetSyncQyCall(xcreateSpQyCall(() -> true, () -> cb.query())); } // =================================================================================== // Internal // ======== // very internal (for suppressing warn about 'Not Use Import') protected String xgetConditionBeanClassNameInternally() { return MemberStatusCB.class.getName(); } protected String xgetConditionQueryClassNameInternally() { return MemberStatusCQ.class.getName(); } protected String xgetSubQueryClassNameInternally() { return SubQuery.class.getName(); } protected String xgetConditionOptionClassNameInternally() { return ConditionOption.class.getName(); } }
{ "content_hash": "5a91a5b599dfd6e5100480aec76f63f3", "timestamp": "", "source": "github", "line_count": 489, "max_line_length": 249, "avg_line_length": 55.80163599182004, "alnum_prop": 0.5509216843185399, "repo_name": "dbflute-test/dbflute-test-active-hanger", "id": "a772e750639a8fae4142330b612c6d2467b51827", "size": "27377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/docksidestage/hanger/dbflute/cbean/bs/BsMemberStatusCB.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "42770" }, { "name": "Java", "bytes": "7082587" }, { "name": "PLSQL", "bytes": "1951" }, { "name": "PLpgSQL", "bytes": "2498" }, { "name": "Perl", "bytes": "9821" }, { "name": "Python", "bytes": "3285" }, { "name": "SQLPL", "bytes": "5634" }, { "name": "Shell", "bytes": "69473" }, { "name": "XSLT", "bytes": "218435" } ], "symlink_target": "" }
FROM golang #RUN go get github.com/aonx/axone RUN CGO_ENABLED=0 go get -a -ldflags '-s' github.com/aonx/axone/... RUN ls -lR /go/bin ENTRYPOINT /go/bin/cmd start -c /go/src/github.com/aonx/axone/config.toml EXPOSE 1883 7780
{ "content_hash": "fd403d30551405f728655d680b9363d3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 73, "avg_line_length": 37.333333333333336, "alnum_prop": 0.7366071428571429, "repo_name": "elarasu/todoserver", "id": "f6293ad4b7bcd0c5c662276f5aef431dedb4c7ca", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "message/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1346" }, { "name": "HTML", "bytes": "4836" }, { "name": "JavaScript", "bytes": "2786" }, { "name": "Python", "bytes": "26543" } ], "symlink_target": "" }
import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class DT_ID3_Reduce extends Reducer<Text, Text, Text, Text>{ public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException{ HashMap<String,Integer> counts=new HashMap<String,Integer>(); String maxKey=""; int maxValue=-1; for(Text value:values){ if(counts.containsKey(value.toString())) counts.put(value.toString(), counts.get(value.toString())+1); else counts.put(value.toString(), 1); } for(Entry<String,Integer> e:counts.entrySet()){ if(e.getValue()>maxValue){ maxKey=e.getKey(); maxValue=e.getValue(); } } context.write(null, new Text(maxKey)); } }
{ "content_hash": "063c8611d2ed3565b908c3c76ea5ff25", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 111, "avg_line_length": 31.307692307692307, "alnum_prop": 0.7162162162162162, "repo_name": "punit-naik/MLHadoop", "id": "60652275be830828d9ee8a29cac449ad128050c7", "size": "814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Decision_Tree_ID3_MapReduce/src/DT_ID3_Reduce.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "115775" } ], "symlink_target": "" }
@interface PodsDummy_Pods_BYBStore : NSObject @end @implementation PodsDummy_Pods_BYBStore @end
{ "content_hash": "04315b8d395db109e260bbb197a69fc7", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 45, "avg_line_length": 24, "alnum_prop": 0.8229166666666666, "repo_name": "HJXIcon/BYBStore", "id": "d24f542d3af14cf50f23058dbdfd21a58a73462f", "size": "130", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BYBStore/Pods/Target Support Files/Pods-BYBStore/Pods-BYBStore-dummy.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1010" }, { "name": "Objective-C", "bytes": "473662" }, { "name": "Ruby", "bytes": "919" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `has_dtor` fn in crate `rustc_lint`."> <meta name="keywords" content="rust, rustlang, rust-lang, has_dtor"> <title>rustc_lint::middle::ty::has_dtor - Rust</title> <link rel="stylesheet" type="text/css" href="../../../main.css"> <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <a href='../../../rustc_lint/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../index.html'>rustc_lint</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a></p><script>window.sidebarCurrent = {name: 'has_dtor', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press 'S' to search, '?' for more options..." type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>rustc_lint</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a>::<wbr><a class='fn' href=''>has_dtor</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'> <a id="collapse-all" href="#">[-]</a>&nbsp;<a id="expand-all" href="#">[+]</a> </span><a id='src-229240' href='../../../rustc/middle/ty/fn.has_dtor.html?gotosrc=229240'>[src]</a></span></h1> <pre class='rust fn'>pub fn has_dtor(cx: &amp;<a class='struct' href='../../../rustc_lint/middle/ty/struct.ctxt.html' title='rustc_lint::middle::ty::ctxt'>ctxt</a>, struct_id: <a class='struct' href='../../../syntax/ast/struct.DefId.html' title='syntax::ast::DefId'>DefId</a>) -&gt; <a href='../../../std/primitive.bool.html'>bool</a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div class="shortcuts"> <h1>Keyboard shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>typedef</code> (or <code>tdef</code>). </p> </div> </div> <script> window.rootPath = "../../../"; window.currentCrate = "rustc_lint"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script async src="../../../search-index.js"></script> </body> </html>
{ "content_hash": "1e882c3b69827c21aaeeb92654c3094d", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 350, "avg_line_length": 42.83157894736842, "alnum_prop": 0.5362496927992135, "repo_name": "ArcherSys/ArcherSys", "id": "fdd09230c28f862c4f382f5a9557a2d1e89652db", "size": "4069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Rust/share/doc/rust/html/rustc_lint/middle/ty/fn.has_dtor.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.mediatek.settings.ext; import android.preference.PreferenceScreen; public interface IAppsExt { /** * @param prefScreen * customized prefScreen * @internal */ void launchApp(PreferenceScreen prefScreen, String packageName); }
{ "content_hash": "ce098c20d2f03dafc3782dd466a6454e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 21.46153846153846, "alnum_prop": 0.6810035842293907, "repo_name": "miswenwen/My_bird_work", "id": "53a97eb7aad3817b2b245e796cc45c4ede2e3164", "size": "279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Bird_work/我的项目/Settings/ext/src/com/mediatek/settings/ext/IAppsExt.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2387" }, { "name": "C++", "bytes": "6784" }, { "name": "HTML", "bytes": "250647" }, { "name": "Java", "bytes": "14786345" }, { "name": "Makefile", "bytes": "26457" }, { "name": "Protocol Buffer", "bytes": "1071" }, { "name": "Python", "bytes": "1310" }, { "name": "Shell", "bytes": "133" } ], "symlink_target": "" }
When configuration problems are detectable in a module, it is a good idea to write an assertion or warning. Doing so provides clear feedback to the user and prevents errors after the build. Although Nix has the `abort` and `builtins.trace` [functions](https://nixos.org/nix/manual/#ssec-builtins) to perform such tasks, they are not ideally suited for NixOS modules. Instead of these functions, you can declare your warnings and assertions using the NixOS module system. ## Warnings {#sec-assertions-warnings} This is an example of using `warnings`. ```nix { config, lib, ... }: { config = lib.mkIf config.services.foo.enable { warnings = if config.services.foo.bar then [ ''You have enabled the bar feature of the foo service. This is known to cause some specific problems in certain situations. '' ] else []; } } ``` ## Assertions {#sec-assertions-assetions} This example, extracted from the [`syslogd` module](https://github.com/NixOS/nixpkgs/blob/release-17.09/nixos/modules/services/logging/syslogd.nix) shows how to use `assertions`. Since there can only be one active syslog daemon at a time, an assertion is useful to prevent such a broken system from being built. ```nix { config, lib, ... }: { config = lib.mkIf config.services.syslogd.enable { assertions = [ { assertion = !config.services.rsyslogd.enable; message = "rsyslogd conflicts with syslogd"; } ]; } } ```
{ "content_hash": "6e34fd69d6f45d506b5841409f65df92", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 311, "avg_line_length": 38.86842105263158, "alnum_prop": 0.7000677048070413, "repo_name": "NixOS/nixpkgs", "id": "cc6d81e56990b7e9f054eb326ce1b55fd900e5a3", "size": "1522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nixos/doc/manual/development/assertions.section.md", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "2836" }, { "name": "C", "bytes": "152018" }, { "name": "C#", "bytes": "1462" }, { "name": "C++", "bytes": "25094" }, { "name": "CMake", "bytes": "1245" }, { "name": "CSS", "bytes": "749" }, { "name": "Common Lisp", "bytes": "63628" }, { "name": "D", "bytes": "5281" }, { "name": "Emacs Lisp", "bytes": "23735" }, { "name": "Erlang", "bytes": "1437" }, { "name": "Go", "bytes": "345" }, { "name": "HCL", "bytes": "210" }, { "name": "Haskell", "bytes": "24243" }, { "name": "Jasmin", "bytes": "656" }, { "name": "Java", "bytes": "1387" }, { "name": "JavaScript", "bytes": "19128" }, { "name": "Lua", "bytes": "548" }, { "name": "M4", "bytes": "9030" }, { "name": "Makefile", "bytes": "1878" }, { "name": "Meson", "bytes": "134" }, { "name": "Nim", "bytes": "5730" }, { "name": "Nix", "bytes": "60599214" }, { "name": "PHP", "bytes": "224" }, { "name": "Perl", "bytes": "200361" }, { "name": "Prolog", "bytes": "9914" }, { "name": "PureScript", "bytes": "170" }, { "name": "Python", "bytes": "494938" }, { "name": "QMake", "bytes": "729" }, { "name": "R", "bytes": "5075" }, { "name": "Reason", "bytes": "182" }, { "name": "Roff", "bytes": "2202" }, { "name": "Ruby", "bytes": "62965" }, { "name": "Rust", "bytes": "28196" }, { "name": "Scheme", "bytes": "181" }, { "name": "Shell", "bytes": "1150670" }, { "name": "SmPL", "bytes": "2780" }, { "name": "Smarty", "bytes": "178" }, { "name": "TypeScript", "bytes": "7559" }, { "name": "VHDL", "bytes": "2420" }, { "name": "Vim Script", "bytes": "21353" }, { "name": "XSLT", "bytes": "20355" }, { "name": "sed", "bytes": "1073" } ], "symlink_target": "" }
package org.apache.spark.util.collection import scala.reflect.ClassTag import org.apache.spark.annotation.DeveloperApi /** * :: DeveloperApi :: * A fast hash map implementation for nullable keys. This hash map supports insertions and updates, * but not deletions. This map is about 5X faster than java.util.HashMap, while using much less * space overhead. * * Under the hood, it uses our OpenHashSet implementation. */ @DeveloperApi private[spark] class OpenHashMap[K : ClassTag, @specialized(Long, Int, Double) V: ClassTag]( initialCapacity: Int) extends Iterable[(K, V)] with Serializable { def this() = this(64) protected var _keySet = new OpenHashSet[K](initialCapacity) // Init in constructor (instead of in declaration) to work around a Scala compiler specialization // bug that would generate two arrays (one for Object and one for specialized T). private var _values: Array[V] = _ _values = new Array[V](_keySet.capacity) @transient private var _oldValues: Array[V] = null // Treat the null key differently so we can use nulls in "data" to represent empty items. private var haveNullValue = false private var nullValue: V = null.asInstanceOf[V] override def size: Int = if (haveNullValue) _keySet.size + 1 else _keySet.size /** Get the value for a given key */ def apply(k: K): V = { if (k == null) { nullValue } else { val pos = _keySet.getPos(k) if (pos < 0) { null.asInstanceOf[V] } else { _values(pos) } } } /** Set the value for a key */ def update(k: K, v: V) { if (k == null) { haveNullValue = true nullValue = v } else { val pos = _keySet.addWithoutResize(k) & OpenHashSet.POSITION_MASK _values(pos) = v _keySet.rehashIfNeeded(k, grow, move) _oldValues = null } } /** * If the key doesn't exist yet in the hash map, set its value to defaultValue; otherwise, * set its value to mergeValue(oldValue). * * @return the newly updated value. */ def changeValue(k: K, defaultValue: => V, mergeValue: (V) => V): V = { if (k == null) { if (haveNullValue) { nullValue = mergeValue(nullValue) } else { haveNullValue = true nullValue = defaultValue } nullValue } else { val pos = _keySet.addWithoutResize(k) if ((pos & OpenHashSet.NONEXISTENCE_MASK) != 0) { val newValue = defaultValue _values(pos & OpenHashSet.POSITION_MASK) = newValue _keySet.rehashIfNeeded(k, grow, move) newValue } else { _values(pos) = mergeValue(_values(pos)) _values(pos) } } } override def iterator = new Iterator[(K, V)] { var pos = -1 var nextPair: (K, V) = computeNextPair() /** Get the next value we should return from next(), or null if we're finished iterating */ def computeNextPair(): (K, V) = { if (pos == -1) { // Treat position -1 as looking at the null value if (haveNullValue) { pos += 1 return (null.asInstanceOf[K], nullValue) } pos += 1 } pos = _keySet.nextPos(pos) if (pos >= 0) { val ret = (_keySet.getValue(pos), _values(pos)) pos += 1 ret } else { null } } def hasNext = nextPair != null def next() = { val pair = nextPair nextPair = computeNextPair() pair } } // The following member variables are declared as protected instead of private for the // specialization to work (specialized class extends the non-specialized one and needs access // to the "private" variables). // They also should have been val's. We use var's because there is a Scala compiler bug that // would throw illegal access error at runtime if they are declared as val's. protected var grow = (newCapacity: Int) => { _oldValues = _values _values = new Array[V](newCapacity) } protected var move = (oldPos: Int, newPos: Int) => { _values(newPos) = _oldValues(oldPos) } }
{ "content_hash": "0a7bea1bed2af350fe7686012d084fac", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 99, "avg_line_length": 28.661971830985916, "alnum_prop": 0.6203931203931204, "repo_name": "hengyicai/OnlineAggregationUCAS", "id": "b8de4ff9aa494f3efbf5f910793633005b740d5c", "size": "4870", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/src/main/scala/org/apache/spark/util/collection/OpenHashMap.scala", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "35774" }, { "name": "CSS", "bytes": "4512" }, { "name": "Java", "bytes": "605689" }, { "name": "JavaScript", "bytes": "21537" }, { "name": "Makefile", "bytes": "6840" }, { "name": "Python", "bytes": "924210" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "3603" }, { "name": "Scala", "bytes": "6747601" }, { "name": "Shell", "bytes": "141008" } ], "symlink_target": "" }
class WorklogsController < ApplicationController def index @user = current_user @clients = @user.clients_and_shared_clients.order("name ASC") if params[:updated_since] @worklogs = Worklog.updated_since(params[:updated_since]).where(user_id: current_user.id).includes({client: :user}, :timeframes).joins(:timeframes).order("timeframes.started DESC") else @worklogs = current_user.worklogs.includes({client: :user}, :timeframes).joins(:timeframes).order("timeframes.started DESC") scope_for_subquery = current_user.worklogs.reorder('') params[:client] ? @worklogs = @worklogs.where(client_id: params[:client]) : @worklogs params[:paid] == "true" ? @worklogs = @worklogs.paid : @worklogs params[:paid] == "false" ? @worklogs = @worklogs.unpaid : @worklogs params[:time] == "today" ? @worklogs = @worklogs.today(scope_for_subquery) : @worklogs params[:time] == "this_week" ? @worklogs = @worklogs.this_week(scope_for_subquery) : @worklogs params[:time] == "this_month" ? @worklogs = @worklogs.this_month(scope_for_subquery) : @worklogs params[:time] == "older_than_this_month" ? @worklogs = @worklogs.older_than_this_month(scope_for_subquery) : @worklogs params[:time] == "last_month" ? @worklogs = @worklogs.last_month(scope_for_subquery) : @worklogs end @worklogs = @worklogs.paginate(:page => params[:page]) respond_to do |format| format.html # index.html.erb format.json format.csv { render text: @worklogs.to_csv(@worklogs) } end end def new if params[:client] gon.client_id = params[:client].to_i end end def edit @worklog = current_user.worklogs.find(params[:id]) gon.worklog_id = @worklog.id end def show @worklog = current_user.worklogs.find(params[:id]) render json: @worklog, status: 200 end def create if (params[:worklog] && params[:worklog][:team_id].present?) @team = Team.find(params[:worklog][:team_id]) end form = WorklogForm.new_from_params(params[:worklog], user: current_user, team: @team) if form.save render json: form.worklog, status: 200, root: "worklog" else render json: form.errors.full_messages.to_json, status: 422 end end def update @worklog = current_user.worklogs.find(params[:id]) if (params[:worklog] && params[:worklog][:team_id].present?) @team = Team.find(params[:worklog][:team_id]) end form = WorklogForm.new_from_params(params[:worklog], user: current_user, worklog: @worklog, team: @team) if form.save render json: form.worklog, status: 200, root: "worklog" else render json: form.errors.full_messages, status: 422 end end def destroy @worklog = current_user.worklogs.find(params[:id]) @worklog.destroy! redirect_to worklogs_path, notice: "Worklog successfully deleted." end end
{ "content_hash": "a8a0277d2eac7248cafdaabd42da3850", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 186, "avg_line_length": 38.1578947368421, "alnum_prop": 0.6620689655172414, "repo_name": "ZEITIO/zeitkit", "id": "8be1872e48729bf2e9d4ac129e69aa705349f9a7", "size": "2900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/worklogs_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16410" }, { "name": "HTML", "bytes": "61959" }, { "name": "JavaScript", "bytes": "29826" }, { "name": "Ruby", "bytes": "197838" } ], "symlink_target": "" }
<?php /* TwigBundle:Exception:trace.txt.twig */ class __TwigTemplate_96e87de5c168b5f17adb76cf07a0f151301c035b8481a58541ff88b080c882c2 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $__internal_24297bcc61acbd796810a0e90ba1f845b14b83db0332b5aeed445e961183b207 = $this->env->getExtension("native_profiler"); $__internal_24297bcc61acbd796810a0e90ba1f845b14b83db0332b5aeed445e961183b207->enter($__internal_24297bcc61acbd796810a0e90ba1f845b14b83db0332b5aeed445e961183b207_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:trace.txt.twig")); // line 1 if ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) { // line 2 echo " at "; echo (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "class", array()) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "type", array())) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())); echo "("; echo $this->env->getExtension('code')->formatArgsAsText($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "args", array())); echo ") "; } else { // line 4 echo " at n/a "; } // line 6 if (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "file", array(), "any", true, true) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "line", array(), "any", true, true))) { // line 7 echo " in "; echo $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()); echo " line "; echo $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()); echo " "; } $__internal_24297bcc61acbd796810a0e90ba1f845b14b83db0332b5aeed445e961183b207->leave($__internal_24297bcc61acbd796810a0e90ba1f845b14b83db0332b5aeed445e961183b207_prof); } public function getTemplateName() { return "TwigBundle:Exception:trace.txt.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 38 => 7, 36 => 6, 32 => 4, 24 => 2, 22 => 1,); } }
{ "content_hash": "7254bdf4fa08d33ae240fc0433ed1383", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 402, "avg_line_length": 45.515625, "alnum_prop": 0.6031582560933745, "repo_name": "nfouka/Symfony2_MongoDB", "id": "7f5c7c4c0180aa140d7d8237f85024ecf3b3f124", "size": "2913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/dev/twig/9/6/96e87de5c168b5f17adb76cf07a0f151301c035b8481a58541ff88b080c882c2.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2907" }, { "name": "CSS", "bytes": "80352" }, { "name": "HTML", "bytes": "34220" }, { "name": "JavaScript", "bytes": "67546" }, { "name": "PHP", "bytes": "116125" } ], "symlink_target": "" }
namespace browser { // Shows or closes the logout dialog for Kiosk Mode. void ShowIdleLogoutDialog(); void CloseIdleLogoutDialog(); } // namespace browser namespace chromeos { class KioskModeIdleLogout : public PowerManagerClient::Observer, public content::NotificationObserver { public: KioskModeIdleLogout(); // Really initialize idle logout when KioskModeHelper is initialized. void Setup(); // NotificationObserver overrides: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // PowerManagerClient::Observer overrides: virtual void IdleNotify(int64 threshold) OVERRIDE; virtual void ActiveNotify() OVERRIDE; private: friend class KioskModeIdleLogoutTest; content::NotificationRegistrar registrar_; void SetupIdleNotifications(); void RequestNextActiveNotification(); void RequestNextIdleNotification(); DISALLOW_COPY_AND_ASSIGN(KioskModeIdleLogout); }; void InitializeKioskModeIdleLogout(); } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_KIOSK_MODE_KIOSK_MODE_IDLE_LOGOUT_H_
{ "content_hash": "b42a1c113d67714b645fb7178e2dbe6b", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 77, "avg_line_length": 27.651162790697676, "alnum_prop": 0.7375946173254836, "repo_name": "gavinp/chromium", "id": "109dba1e2c3e098eb5bf8803e2cfeab7d239dafe", "size": "1721", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1178292" }, { "name": "C", "bytes": "72353788" }, { "name": "C++", "bytes": "117593783" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "10440" }, { "name": "Java", "bytes": "24087" }, { "name": "JavaScript", "bytes": "8781314" }, { "name": "Objective-C", "bytes": "5340290" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "918286" }, { "name": "Python", "bytes": "5942009" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4149832" }, { "name": "Tcl", "bytes": "255109" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function, unicode_literals from amaascore.core.amaas_model import AMaaSModel class Reference(AMaaSModel): def __init__(self, reference_value, reference_primary=False, *args, **kwargs): self.reference_value = reference_value self.reference_primary = reference_primary super(Reference, self).__init__(*args, **kwargs) @property def reference_primary(self): if hasattr(self, '_reference_primary'): return self._reference_primary @reference_primary.setter def reference_primary(self, value): """ Always convert to bool if the service/database returns 0 or 1 """ if value is not None: self._reference_primary = True if value else False
{ "content_hash": "4ace5ff3b2a714086b8ec9350ab36eaa", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 82, "avg_line_length": 33.333333333333336, "alnum_prop": 0.66375, "repo_name": "amaas-fintech/amaas-core-sdk-python", "id": "f34efe6aecbc3f1613edb3fce4c434b317c8d8a0", "size": "800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "amaascore/core/reference.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "618" }, { "name": "Python", "bytes": "529460" }, { "name": "Shell", "bytes": "42" } ], "symlink_target": "" }
<?php namespace DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialFractionDescription; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialOrganism; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialPartDescription; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString; use DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource; use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants; use DCarbone\PHPFHIRGenerated\R4\PHPFHIRContainedTypeInterface; use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface; /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * If the element is present, it must have either a \@value, an \@id, or extensions * * Class FHIRSubstanceSourceMaterial * @package \DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource */ class FHIRSubstanceSourceMaterial extends FHIRDomainResource implements PHPFHIRContainedTypeInterface { // name of FHIR type this class describes const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL; const FIELD_COUNTRY_OF_ORIGIN = 'countryOfOrigin'; const FIELD_DEVELOPMENT_STAGE = 'developmentStage'; const FIELD_FRACTION_DESCRIPTION = 'fractionDescription'; const FIELD_GEOGRAPHICAL_LOCATION = 'geographicalLocation'; const FIELD_GEOGRAPHICAL_LOCATION_EXT = '_geographicalLocation'; const FIELD_ORGANISM = 'organism'; const FIELD_ORGANISM_ID = 'organismId'; const FIELD_ORGANISM_NAME = 'organismName'; const FIELD_ORGANISM_NAME_EXT = '_organismName'; const FIELD_PARENT_SUBSTANCE_ID = 'parentSubstanceId'; const FIELD_PARENT_SUBSTANCE_NAME = 'parentSubstanceName'; const FIELD_PARENT_SUBSTANCE_NAME_EXT = '_parentSubstanceName'; const FIELD_PART_DESCRIPTION = 'partDescription'; const FIELD_SOURCE_MATERIAL_CLASS = 'sourceMaterialClass'; const FIELD_SOURCE_MATERIAL_STATE = 'sourceMaterialState'; const FIELD_SOURCE_MATERIAL_TYPE = 'sourceMaterialType'; /** @var string */ private $_xmlns = 'http://hl7.org/fhir'; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The country where the plant material is harvested or the countries where the * plasma is sourced from as laid down in accordance with the Plasma Master File. * For “Plasma-derived substances” the attribute country of origin provides * information about the countries used for the manufacturing of the Cryopoor plama * or Crioprecipitate. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept[] */ protected $countryOfOrigin = []; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Stage of life for animals, plants, insects and microorganisms. This information * shall be provided only when the substance is significantly different in these * stages (e.g. foetal bovine serum). * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ protected $developmentStage = null; /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * Many complex materials are fractions of parts of plants, animals, or minerals. * Fraction elements are often necessary to define both Substances and Specified * Group 1 Substances. For substances derived from Plants, fraction information * will be captured at the Substance information level ( . Oils, Juices and * Exudates). Additional information for Extracts, such as extraction solvent * composition, will be captured at the Specified Substance Group 1 information * level. For plasma-derived products fraction information will be captured at the * Substance and the Specified Substance Group 1 levels. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialFractionDescription[] */ protected $fractionDescription = []; /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The place/region where the plant is harvested or the places/regions where the * animal source material has its habitat. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] */ protected $geographicalLocation = []; /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * This subclause describes the organism which the substance is derived from. For * vaccines, the parent organism shall be specified based on these subclause * elements. As an example, full taxonomy will be described for the Substance Name: * ., Leaf. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialOrganism */ protected $organism = null; /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The unique identifier associated with the source material parent organism shall * be specified. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier */ protected $organismId = null; /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The organism accepted Scientific name shall be provided based on the organism * taxonomy. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString */ protected $organismName = null; /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The parent of the herbal drug Ginkgo biloba, Leaf is the substance ID of the * substance (fresh) of Ginkgo biloba L. or Ginkgo biloba L. (Whole plant). * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier[] */ protected $parentSubstanceId = []; /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The parent substance of the Herbal Drug, or Herbal preparation. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] */ protected $parentSubstanceName = []; /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * To do. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialPartDescription[] */ protected $partDescription = []; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * General high level classification of the source material specific to the origin * of the material. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ protected $sourceMaterialClass = null; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The state of the source material when extracted. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ protected $sourceMaterialState = null; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The type of the source material shall be specified based on a controlled * vocabulary. For vaccines, this subclause refers to the class of infectious * agent. * * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ protected $sourceMaterialType = null; /** * Validation map for fields in type SubstanceSourceMaterial * @var array */ private static $_validationRules = [ ]; /** * FHIRSubstanceSourceMaterial Constructor * @param null|array $data */ public function __construct($data = null) { if (null === $data || [] === $data) { return; } if (!is_array($data)) { throw new \InvalidArgumentException(sprintf( 'FHIRSubstanceSourceMaterial::_construct - $data expected to be null or array, %s seen', gettype($data) )); } parent::__construct($data); if (isset($data[self::FIELD_COUNTRY_OF_ORIGIN])) { if (is_array($data[self::FIELD_COUNTRY_OF_ORIGIN])) { foreach($data[self::FIELD_COUNTRY_OF_ORIGIN] as $v) { if (null === $v) { continue; } if ($v instanceof FHIRCodeableConcept) { $this->addCountryOfOrigin($v); } else { $this->addCountryOfOrigin(new FHIRCodeableConcept($v)); } } } else if ($data[self::FIELD_COUNTRY_OF_ORIGIN] instanceof FHIRCodeableConcept) { $this->addCountryOfOrigin($data[self::FIELD_COUNTRY_OF_ORIGIN]); } else { $this->addCountryOfOrigin(new FHIRCodeableConcept($data[self::FIELD_COUNTRY_OF_ORIGIN])); } } if (isset($data[self::FIELD_DEVELOPMENT_STAGE])) { if ($data[self::FIELD_DEVELOPMENT_STAGE] instanceof FHIRCodeableConcept) { $this->setDevelopmentStage($data[self::FIELD_DEVELOPMENT_STAGE]); } else { $this->setDevelopmentStage(new FHIRCodeableConcept($data[self::FIELD_DEVELOPMENT_STAGE])); } } if (isset($data[self::FIELD_FRACTION_DESCRIPTION])) { if (is_array($data[self::FIELD_FRACTION_DESCRIPTION])) { foreach($data[self::FIELD_FRACTION_DESCRIPTION] as $v) { if (null === $v) { continue; } if ($v instanceof FHIRSubstanceSourceMaterialFractionDescription) { $this->addFractionDescription($v); } else { $this->addFractionDescription(new FHIRSubstanceSourceMaterialFractionDescription($v)); } } } else if ($data[self::FIELD_FRACTION_DESCRIPTION] instanceof FHIRSubstanceSourceMaterialFractionDescription) { $this->addFractionDescription($data[self::FIELD_FRACTION_DESCRIPTION]); } else { $this->addFractionDescription(new FHIRSubstanceSourceMaterialFractionDescription($data[self::FIELD_FRACTION_DESCRIPTION])); } } if (isset($data[self::FIELD_GEOGRAPHICAL_LOCATION]) || isset($data[self::FIELD_GEOGRAPHICAL_LOCATION_EXT])) { if (isset($data[self::FIELD_GEOGRAPHICAL_LOCATION])) { $value = $data[self::FIELD_GEOGRAPHICAL_LOCATION]; } else { $value = null; } if (isset($data[self::FIELD_GEOGRAPHICAL_LOCATION_EXT]) && is_array($data[self::FIELD_GEOGRAPHICAL_LOCATION_EXT])) { $ext = $data[self::FIELD_GEOGRAPHICAL_LOCATION_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRString) { $this->addGeographicalLocation($value); } else if (is_array($value)) { foreach($value as $i => $v) { if ($v instanceof FHIRString) { $this->addGeographicalLocation($v); } else { $iext = (isset($ext[$i]) && is_array($ext[$i])) ? $ext[$i] : []; if (is_array($v)) { $this->addGeographicalLocation(new FHIRString(array_merge($v, $iext))); } else { $this->addGeographicalLocation(new FHIRString([FHIRString::FIELD_VALUE => $v] + $iext)); } } } } elseif (is_array($value)) { $this->addGeographicalLocation(new FHIRString(array_merge($ext, $value))); } else { $this->addGeographicalLocation(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { foreach($ext as $iext) { $this->addGeographicalLocation(new FHIRString($iext)); } } } if (isset($data[self::FIELD_ORGANISM])) { if ($data[self::FIELD_ORGANISM] instanceof FHIRSubstanceSourceMaterialOrganism) { $this->setOrganism($data[self::FIELD_ORGANISM]); } else { $this->setOrganism(new FHIRSubstanceSourceMaterialOrganism($data[self::FIELD_ORGANISM])); } } if (isset($data[self::FIELD_ORGANISM_ID])) { if ($data[self::FIELD_ORGANISM_ID] instanceof FHIRIdentifier) { $this->setOrganismId($data[self::FIELD_ORGANISM_ID]); } else { $this->setOrganismId(new FHIRIdentifier($data[self::FIELD_ORGANISM_ID])); } } if (isset($data[self::FIELD_ORGANISM_NAME]) || isset($data[self::FIELD_ORGANISM_NAME_EXT])) { if (isset($data[self::FIELD_ORGANISM_NAME])) { $value = $data[self::FIELD_ORGANISM_NAME]; } else { $value = null; } if (isset($data[self::FIELD_ORGANISM_NAME_EXT]) && is_array($data[self::FIELD_ORGANISM_NAME_EXT])) { $ext = $data[self::FIELD_ORGANISM_NAME_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRString) { $this->setOrganismName($value); } else if (is_array($value)) { $this->setOrganismName(new FHIRString(array_merge($ext, $value))); } else { $this->setOrganismName(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { $this->setOrganismName(new FHIRString($ext)); } } if (isset($data[self::FIELD_PARENT_SUBSTANCE_ID])) { if (is_array($data[self::FIELD_PARENT_SUBSTANCE_ID])) { foreach($data[self::FIELD_PARENT_SUBSTANCE_ID] as $v) { if (null === $v) { continue; } if ($v instanceof FHIRIdentifier) { $this->addParentSubstanceId($v); } else { $this->addParentSubstanceId(new FHIRIdentifier($v)); } } } else if ($data[self::FIELD_PARENT_SUBSTANCE_ID] instanceof FHIRIdentifier) { $this->addParentSubstanceId($data[self::FIELD_PARENT_SUBSTANCE_ID]); } else { $this->addParentSubstanceId(new FHIRIdentifier($data[self::FIELD_PARENT_SUBSTANCE_ID])); } } if (isset($data[self::FIELD_PARENT_SUBSTANCE_NAME]) || isset($data[self::FIELD_PARENT_SUBSTANCE_NAME_EXT])) { if (isset($data[self::FIELD_PARENT_SUBSTANCE_NAME])) { $value = $data[self::FIELD_PARENT_SUBSTANCE_NAME]; } else { $value = null; } if (isset($data[self::FIELD_PARENT_SUBSTANCE_NAME_EXT]) && is_array($data[self::FIELD_PARENT_SUBSTANCE_NAME_EXT])) { $ext = $data[self::FIELD_PARENT_SUBSTANCE_NAME_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRString) { $this->addParentSubstanceName($value); } else if (is_array($value)) { foreach($value as $i => $v) { if ($v instanceof FHIRString) { $this->addParentSubstanceName($v); } else { $iext = (isset($ext[$i]) && is_array($ext[$i])) ? $ext[$i] : []; if (is_array($v)) { $this->addParentSubstanceName(new FHIRString(array_merge($v, $iext))); } else { $this->addParentSubstanceName(new FHIRString([FHIRString::FIELD_VALUE => $v] + $iext)); } } } } elseif (is_array($value)) { $this->addParentSubstanceName(new FHIRString(array_merge($ext, $value))); } else { $this->addParentSubstanceName(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { foreach($ext as $iext) { $this->addParentSubstanceName(new FHIRString($iext)); } } } if (isset($data[self::FIELD_PART_DESCRIPTION])) { if (is_array($data[self::FIELD_PART_DESCRIPTION])) { foreach($data[self::FIELD_PART_DESCRIPTION] as $v) { if (null === $v) { continue; } if ($v instanceof FHIRSubstanceSourceMaterialPartDescription) { $this->addPartDescription($v); } else { $this->addPartDescription(new FHIRSubstanceSourceMaterialPartDescription($v)); } } } else if ($data[self::FIELD_PART_DESCRIPTION] instanceof FHIRSubstanceSourceMaterialPartDescription) { $this->addPartDescription($data[self::FIELD_PART_DESCRIPTION]); } else { $this->addPartDescription(new FHIRSubstanceSourceMaterialPartDescription($data[self::FIELD_PART_DESCRIPTION])); } } if (isset($data[self::FIELD_SOURCE_MATERIAL_CLASS])) { if ($data[self::FIELD_SOURCE_MATERIAL_CLASS] instanceof FHIRCodeableConcept) { $this->setSourceMaterialClass($data[self::FIELD_SOURCE_MATERIAL_CLASS]); } else { $this->setSourceMaterialClass(new FHIRCodeableConcept($data[self::FIELD_SOURCE_MATERIAL_CLASS])); } } if (isset($data[self::FIELD_SOURCE_MATERIAL_STATE])) { if ($data[self::FIELD_SOURCE_MATERIAL_STATE] instanceof FHIRCodeableConcept) { $this->setSourceMaterialState($data[self::FIELD_SOURCE_MATERIAL_STATE]); } else { $this->setSourceMaterialState(new FHIRCodeableConcept($data[self::FIELD_SOURCE_MATERIAL_STATE])); } } if (isset($data[self::FIELD_SOURCE_MATERIAL_TYPE])) { if ($data[self::FIELD_SOURCE_MATERIAL_TYPE] instanceof FHIRCodeableConcept) { $this->setSourceMaterialType($data[self::FIELD_SOURCE_MATERIAL_TYPE]); } else { $this->setSourceMaterialType(new FHIRCodeableConcept($data[self::FIELD_SOURCE_MATERIAL_TYPE])); } } } /** * @return string */ public function _getFHIRTypeName() { return self::FHIR_TYPE_NAME; } /** * @return string */ public function _getFHIRXMLElementDefinition() { $xmlns = $this->_getFHIRXMLNamespace(); if (null !== $xmlns) { $xmlns = " xmlns=\"{$xmlns}\""; } return "<SubstanceSourceMaterial{$xmlns}></SubstanceSourceMaterial>"; } /** * @return string */ public function _getResourceType() { return static::FHIR_TYPE_NAME; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The country where the plant material is harvested or the countries where the * plasma is sourced from as laid down in accordance with the Plasma Master File. * For “Plasma-derived substances” the attribute country of origin provides * information about the countries used for the manufacturing of the Cryopoor plama * or Crioprecipitate. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept[] */ public function getCountryOfOrigin() { return $this->countryOfOrigin; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The country where the plant material is harvested or the countries where the * plasma is sourced from as laid down in accordance with the Plasma Master File. * For “Plasma-derived substances” the attribute country of origin provides * information about the countries used for the manufacturing of the Cryopoor plama * or Crioprecipitate. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $countryOfOrigin * @return static */ public function addCountryOfOrigin(FHIRCodeableConcept $countryOfOrigin = null) { $this->countryOfOrigin[] = $countryOfOrigin; return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The country where the plant material is harvested or the countries where the * plasma is sourced from as laid down in accordance with the Plasma Master File. * For “Plasma-derived substances” the attribute country of origin provides * information about the countries used for the manufacturing of the Cryopoor plama * or Crioprecipitate. * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept[] $countryOfOrigin * @return static */ public function setCountryOfOrigin(array $countryOfOrigin = []) { $this->countryOfOrigin = []; if ([] === $countryOfOrigin) { return $this; } foreach($countryOfOrigin as $v) { if ($v instanceof FHIRCodeableConcept) { $this->addCountryOfOrigin($v); } else { $this->addCountryOfOrigin(new FHIRCodeableConcept($v)); } } return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Stage of life for animals, plants, insects and microorganisms. This information * shall be provided only when the substance is significantly different in these * stages (e.g. foetal bovine serum). * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ public function getDevelopmentStage() { return $this->developmentStage; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Stage of life for animals, plants, insects and microorganisms. This information * shall be provided only when the substance is significantly different in these * stages (e.g. foetal bovine serum). * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $developmentStage * @return static */ public function setDevelopmentStage(FHIRCodeableConcept $developmentStage = null) { $this->developmentStage = $developmentStage; return $this; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * Many complex materials are fractions of parts of plants, animals, or minerals. * Fraction elements are often necessary to define both Substances and Specified * Group 1 Substances. For substances derived from Plants, fraction information * will be captured at the Substance information level ( . Oils, Juices and * Exudates). Additional information for Extracts, such as extraction solvent * composition, will be captured at the Specified Substance Group 1 information * level. For plasma-derived products fraction information will be captured at the * Substance and the Specified Substance Group 1 levels. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialFractionDescription[] */ public function getFractionDescription() { return $this->fractionDescription; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * Many complex materials are fractions of parts of plants, animals, or minerals. * Fraction elements are often necessary to define both Substances and Specified * Group 1 Substances. For substances derived from Plants, fraction information * will be captured at the Substance information level ( . Oils, Juices and * Exudates). Additional information for Extracts, such as extraction solvent * composition, will be captured at the Specified Substance Group 1 information * level. For plasma-derived products fraction information will be captured at the * Substance and the Specified Substance Group 1 levels. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialFractionDescription $fractionDescription * @return static */ public function addFractionDescription(FHIRSubstanceSourceMaterialFractionDescription $fractionDescription = null) { $this->fractionDescription[] = $fractionDescription; return $this; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * Many complex materials are fractions of parts of plants, animals, or minerals. * Fraction elements are often necessary to define both Substances and Specified * Group 1 Substances. For substances derived from Plants, fraction information * will be captured at the Substance information level ( . Oils, Juices and * Exudates). Additional information for Extracts, such as extraction solvent * composition, will be captured at the Specified Substance Group 1 information * level. For plasma-derived products fraction information will be captured at the * Substance and the Specified Substance Group 1 levels. * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialFractionDescription[] $fractionDescription * @return static */ public function setFractionDescription(array $fractionDescription = []) { $this->fractionDescription = []; if ([] === $fractionDescription) { return $this; } foreach($fractionDescription as $v) { if ($v instanceof FHIRSubstanceSourceMaterialFractionDescription) { $this->addFractionDescription($v); } else { $this->addFractionDescription(new FHIRSubstanceSourceMaterialFractionDescription($v)); } } return $this; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The place/region where the plant is harvested or the places/regions where the * animal source material has its habitat. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] */ public function getGeographicalLocation() { return $this->geographicalLocation; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The place/region where the plant is harvested or the places/regions where the * animal source material has its habitat. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString $geographicalLocation * @return static */ public function addGeographicalLocation($geographicalLocation = null) { if (null === $geographicalLocation) { $this->geographicalLocation = []; return $this; } if ($geographicalLocation instanceof FHIRString) { $this->geographicalLocation[] = $geographicalLocation; return $this; } $this->geographicalLocation[] = new FHIRString($geographicalLocation); return $this; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The place/region where the plant is harvested or the places/regions where the * animal source material has its habitat. * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] $geographicalLocation * @return static */ public function setGeographicalLocation(array $geographicalLocation = []) { $this->geographicalLocation = []; if ([] === $geographicalLocation) { return $this; } foreach($geographicalLocation as $v) { if ($v instanceof FHIRString) { $this->addGeographicalLocation($v); } else { $this->addGeographicalLocation(new FHIRString($v)); } } return $this; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * This subclause describes the organism which the substance is derived from. For * vaccines, the parent organism shall be specified based on these subclause * elements. As an example, full taxonomy will be described for the Substance Name: * ., Leaf. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialOrganism */ public function getOrganism() { return $this->organism; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * This subclause describes the organism which the substance is derived from. For * vaccines, the parent organism shall be specified based on these subclause * elements. As an example, full taxonomy will be described for the Substance Name: * ., Leaf. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialOrganism $organism * @return static */ public function setOrganism(FHIRSubstanceSourceMaterialOrganism $organism = null) { $this->organism = $organism; return $this; } /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The unique identifier associated with the source material parent organism shall * be specified. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier */ public function getOrganismId() { return $this->organismId; } /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The unique identifier associated with the source material parent organism shall * be specified. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier $organismId * @return static */ public function setOrganismId(FHIRIdentifier $organismId = null) { $this->organismId = $organismId; return $this; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The organism accepted Scientific name shall be provided based on the organism * taxonomy. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString */ public function getOrganismName() { return $this->organismName; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The organism accepted Scientific name shall be provided based on the organism * taxonomy. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString $organismName * @return static */ public function setOrganismName($organismName = null) { if (null === $organismName) { $this->organismName = null; return $this; } if ($organismName instanceof FHIRString) { $this->organismName = $organismName; return $this; } $this->organismName = new FHIRString($organismName); return $this; } /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The parent of the herbal drug Ginkgo biloba, Leaf is the substance ID of the * substance (fresh) of Ginkgo biloba L. or Ginkgo biloba L. (Whole plant). * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier[] */ public function getParentSubstanceId() { return $this->parentSubstanceId; } /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The parent of the herbal drug Ginkgo biloba, Leaf is the substance ID of the * substance (fresh) of Ginkgo biloba L. or Ginkgo biloba L. (Whole plant). * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier $parentSubstanceId * @return static */ public function addParentSubstanceId(FHIRIdentifier $parentSubstanceId = null) { $this->parentSubstanceId[] = $parentSubstanceId; return $this; } /** * An identifier - identifies some entity uniquely and unambiguously. Typically * this is used for business identifiers. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The parent of the herbal drug Ginkgo biloba, Leaf is the substance ID of the * substance (fresh) of Ginkgo biloba L. or Ginkgo biloba L. (Whole plant). * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentifier[] $parentSubstanceId * @return static */ public function setParentSubstanceId(array $parentSubstanceId = []) { $this->parentSubstanceId = []; if ([] === $parentSubstanceId) { return $this; } foreach($parentSubstanceId as $v) { if ($v instanceof FHIRIdentifier) { $this->addParentSubstanceId($v); } else { $this->addParentSubstanceId(new FHIRIdentifier($v)); } } return $this; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The parent substance of the Herbal Drug, or Herbal preparation. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] */ public function getParentSubstanceName() { return $this->parentSubstanceName; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The parent substance of the Herbal Drug, or Herbal preparation. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString $parentSubstanceName * @return static */ public function addParentSubstanceName($parentSubstanceName = null) { if (null === $parentSubstanceName) { $this->parentSubstanceName = []; return $this; } if ($parentSubstanceName instanceof FHIRString) { $this->parentSubstanceName[] = $parentSubstanceName; return $this; } $this->parentSubstanceName[] = new FHIRString($parentSubstanceName); return $this; } /** * A sequence of Unicode characters * Note that FHIR strings SHALL NOT exceed 1MB in size * If the element is present, it must have either a \@value, an \@id, or extensions * * The parent substance of the Herbal Drug, or Herbal preparation. * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString[] $parentSubstanceName * @return static */ public function setParentSubstanceName(array $parentSubstanceName = []) { $this->parentSubstanceName = []; if ([] === $parentSubstanceName) { return $this; } foreach($parentSubstanceName as $v) { if ($v instanceof FHIRString) { $this->addParentSubstanceName($v); } else { $this->addParentSubstanceName(new FHIRString($v)); } } return $this; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * To do. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialPartDescription[] */ public function getPartDescription() { return $this->partDescription; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * To do. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialPartDescription $partDescription * @return static */ public function addPartDescription(FHIRSubstanceSourceMaterialPartDescription $partDescription = null) { $this->partDescription[] = $partDescription; return $this; } /** * Source material shall capture information on the taxonomic and anatomical * origins as well as the fraction of a material that can result in or can be * modified to form a substance. This set of data elements shall be used to define * polymer substances isolated from biological matrices. Taxonomic and anatomical * origins shall be described using a controlled vocabulary as required. This * information is captured for naturally derived polymers ( . starch) and * structurally diverse substances. For Organisms belonging to the Kingdom Plantae * the Substance level defines the fresh material of a single species or * infraspecies, the Herbal Drug and the Herbal preparation. For Herbal * preparations, the fraction information will be captured at the Substance * information level and additional information for herbal extracts will be * captured at the Specified Substance Group 1 information level. See for further * explanation the Substance Class: Structurally Diverse and the herbal annex. * * To do. * * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSourceMaterial\FHIRSubstanceSourceMaterialPartDescription[] $partDescription * @return static */ public function setPartDescription(array $partDescription = []) { $this->partDescription = []; if ([] === $partDescription) { return $this; } foreach($partDescription as $v) { if ($v instanceof FHIRSubstanceSourceMaterialPartDescription) { $this->addPartDescription($v); } else { $this->addPartDescription(new FHIRSubstanceSourceMaterialPartDescription($v)); } } return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * General high level classification of the source material specific to the origin * of the material. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ public function getSourceMaterialClass() { return $this->sourceMaterialClass; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * General high level classification of the source material specific to the origin * of the material. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $sourceMaterialClass * @return static */ public function setSourceMaterialClass(FHIRCodeableConcept $sourceMaterialClass = null) { $this->sourceMaterialClass = $sourceMaterialClass; return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The state of the source material when extracted. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ public function getSourceMaterialState() { return $this->sourceMaterialState; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The state of the source material when extracted. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $sourceMaterialState * @return static */ public function setSourceMaterialState(FHIRCodeableConcept $sourceMaterialState = null) { $this->sourceMaterialState = $sourceMaterialState; return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The type of the source material shall be specified based on a controlled * vocabulary. For vaccines, this subclause refers to the class of infectious * agent. * * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept */ public function getSourceMaterialType() { return $this->sourceMaterialType; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The type of the source material shall be specified based on a controlled * vocabulary. For vaccines, this subclause refers to the class of infectious * agent. * * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $sourceMaterialType * @return static */ public function setSourceMaterialType(FHIRCodeableConcept $sourceMaterialType = null) { $this->sourceMaterialType = $sourceMaterialType; return $this; } /** * Returns the validation rules that this type's fields must comply with to be considered "valid" * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]] * * @return array */ public function _getValidationRules() { return self::$_validationRules; } /** * Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as * passing. * * @return array */ public function _getValidationErrors() { $errs = parent::_getValidationErrors(); $validationRules = $this->_getValidationRules(); if ([] !== ($vs = $this->getCountryOfOrigin())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_COUNTRY_OF_ORIGIN, $i)] = $fieldErrs; } } } if (null !== ($v = $this->getDevelopmentStage())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_DEVELOPMENT_STAGE] = $fieldErrs; } } if ([] !== ($vs = $this->getFractionDescription())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_FRACTION_DESCRIPTION, $i)] = $fieldErrs; } } } if ([] !== ($vs = $this->getGeographicalLocation())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_GEOGRAPHICAL_LOCATION, $i)] = $fieldErrs; } } } if (null !== ($v = $this->getOrganism())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_ORGANISM] = $fieldErrs; } } if (null !== ($v = $this->getOrganismId())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_ORGANISM_ID] = $fieldErrs; } } if (null !== ($v = $this->getOrganismName())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_ORGANISM_NAME] = $fieldErrs; } } if ([] !== ($vs = $this->getParentSubstanceId())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_PARENT_SUBSTANCE_ID, $i)] = $fieldErrs; } } } if ([] !== ($vs = $this->getParentSubstanceName())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_PARENT_SUBSTANCE_NAME, $i)] = $fieldErrs; } } } if ([] !== ($vs = $this->getPartDescription())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_PART_DESCRIPTION, $i)] = $fieldErrs; } } } if (null !== ($v = $this->getSourceMaterialClass())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_SOURCE_MATERIAL_CLASS] = $fieldErrs; } } if (null !== ($v = $this->getSourceMaterialState())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_SOURCE_MATERIAL_STATE] = $fieldErrs; } } if (null !== ($v = $this->getSourceMaterialType())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_SOURCE_MATERIAL_TYPE] = $fieldErrs; } } if (isset($validationRules[self::FIELD_COUNTRY_OF_ORIGIN])) { $v = $this->getCountryOfOrigin(); foreach($validationRules[self::FIELD_COUNTRY_OF_ORIGIN] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_COUNTRY_OF_ORIGIN, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_COUNTRY_OF_ORIGIN])) { $errs[self::FIELD_COUNTRY_OF_ORIGIN] = []; } $errs[self::FIELD_COUNTRY_OF_ORIGIN][$rule] = $err; } } } if (isset($validationRules[self::FIELD_DEVELOPMENT_STAGE])) { $v = $this->getDevelopmentStage(); foreach($validationRules[self::FIELD_DEVELOPMENT_STAGE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_DEVELOPMENT_STAGE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_DEVELOPMENT_STAGE])) { $errs[self::FIELD_DEVELOPMENT_STAGE] = []; } $errs[self::FIELD_DEVELOPMENT_STAGE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_FRACTION_DESCRIPTION])) { $v = $this->getFractionDescription(); foreach($validationRules[self::FIELD_FRACTION_DESCRIPTION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_FRACTION_DESCRIPTION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_FRACTION_DESCRIPTION])) { $errs[self::FIELD_FRACTION_DESCRIPTION] = []; } $errs[self::FIELD_FRACTION_DESCRIPTION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_GEOGRAPHICAL_LOCATION])) { $v = $this->getGeographicalLocation(); foreach($validationRules[self::FIELD_GEOGRAPHICAL_LOCATION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_GEOGRAPHICAL_LOCATION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_GEOGRAPHICAL_LOCATION])) { $errs[self::FIELD_GEOGRAPHICAL_LOCATION] = []; } $errs[self::FIELD_GEOGRAPHICAL_LOCATION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ORGANISM])) { $v = $this->getOrganism(); foreach($validationRules[self::FIELD_ORGANISM] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_ORGANISM, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ORGANISM])) { $errs[self::FIELD_ORGANISM] = []; } $errs[self::FIELD_ORGANISM][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ORGANISM_ID])) { $v = $this->getOrganismId(); foreach($validationRules[self::FIELD_ORGANISM_ID] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_ORGANISM_ID, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ORGANISM_ID])) { $errs[self::FIELD_ORGANISM_ID] = []; } $errs[self::FIELD_ORGANISM_ID][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ORGANISM_NAME])) { $v = $this->getOrganismName(); foreach($validationRules[self::FIELD_ORGANISM_NAME] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_ORGANISM_NAME, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ORGANISM_NAME])) { $errs[self::FIELD_ORGANISM_NAME] = []; } $errs[self::FIELD_ORGANISM_NAME][$rule] = $err; } } } if (isset($validationRules[self::FIELD_PARENT_SUBSTANCE_ID])) { $v = $this->getParentSubstanceId(); foreach($validationRules[self::FIELD_PARENT_SUBSTANCE_ID] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_PARENT_SUBSTANCE_ID, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_PARENT_SUBSTANCE_ID])) { $errs[self::FIELD_PARENT_SUBSTANCE_ID] = []; } $errs[self::FIELD_PARENT_SUBSTANCE_ID][$rule] = $err; } } } if (isset($validationRules[self::FIELD_PARENT_SUBSTANCE_NAME])) { $v = $this->getParentSubstanceName(); foreach($validationRules[self::FIELD_PARENT_SUBSTANCE_NAME] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_PARENT_SUBSTANCE_NAME, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_PARENT_SUBSTANCE_NAME])) { $errs[self::FIELD_PARENT_SUBSTANCE_NAME] = []; } $errs[self::FIELD_PARENT_SUBSTANCE_NAME][$rule] = $err; } } } if (isset($validationRules[self::FIELD_PART_DESCRIPTION])) { $v = $this->getPartDescription(); foreach($validationRules[self::FIELD_PART_DESCRIPTION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_PART_DESCRIPTION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_PART_DESCRIPTION])) { $errs[self::FIELD_PART_DESCRIPTION] = []; } $errs[self::FIELD_PART_DESCRIPTION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_SOURCE_MATERIAL_CLASS])) { $v = $this->getSourceMaterialClass(); foreach($validationRules[self::FIELD_SOURCE_MATERIAL_CLASS] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_SOURCE_MATERIAL_CLASS, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_SOURCE_MATERIAL_CLASS])) { $errs[self::FIELD_SOURCE_MATERIAL_CLASS] = []; } $errs[self::FIELD_SOURCE_MATERIAL_CLASS][$rule] = $err; } } } if (isset($validationRules[self::FIELD_SOURCE_MATERIAL_STATE])) { $v = $this->getSourceMaterialState(); foreach($validationRules[self::FIELD_SOURCE_MATERIAL_STATE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_SOURCE_MATERIAL_STATE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_SOURCE_MATERIAL_STATE])) { $errs[self::FIELD_SOURCE_MATERIAL_STATE] = []; } $errs[self::FIELD_SOURCE_MATERIAL_STATE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_SOURCE_MATERIAL_TYPE])) { $v = $this->getSourceMaterialType(); foreach($validationRules[self::FIELD_SOURCE_MATERIAL_TYPE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_SOURCE_MATERIAL, self::FIELD_SOURCE_MATERIAL_TYPE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_SOURCE_MATERIAL_TYPE])) { $errs[self::FIELD_SOURCE_MATERIAL_TYPE] = []; } $errs[self::FIELD_SOURCE_MATERIAL_TYPE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_CONTAINED])) { $v = $this->getContained(); foreach($validationRules[self::FIELD_CONTAINED] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_CONTAINED, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_CONTAINED])) { $errs[self::FIELD_CONTAINED] = []; } $errs[self::FIELD_CONTAINED][$rule] = $err; } } } if (isset($validationRules[self::FIELD_EXTENSION])) { $v = $this->getExtension(); foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_EXTENSION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_EXTENSION])) { $errs[self::FIELD_EXTENSION] = []; } $errs[self::FIELD_EXTENSION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) { $v = $this->getModifierExtension(); foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) { $errs[self::FIELD_MODIFIER_EXTENSION] = []; } $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_TEXT])) { $v = $this->getText(); foreach($validationRules[self::FIELD_TEXT] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_TEXT, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_TEXT])) { $errs[self::FIELD_TEXT] = []; } $errs[self::FIELD_TEXT][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ID])) { $v = $this->getId(); foreach($validationRules[self::FIELD_ID] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_ID, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ID])) { $errs[self::FIELD_ID] = []; } $errs[self::FIELD_ID][$rule] = $err; } } } if (isset($validationRules[self::FIELD_IMPLICIT_RULES])) { $v = $this->getImplicitRules(); foreach($validationRules[self::FIELD_IMPLICIT_RULES] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_IMPLICIT_RULES, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_IMPLICIT_RULES])) { $errs[self::FIELD_IMPLICIT_RULES] = []; } $errs[self::FIELD_IMPLICIT_RULES][$rule] = $err; } } } if (isset($validationRules[self::FIELD_LANGUAGE])) { $v = $this->getLanguage(); foreach($validationRules[self::FIELD_LANGUAGE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_LANGUAGE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_LANGUAGE])) { $errs[self::FIELD_LANGUAGE] = []; } $errs[self::FIELD_LANGUAGE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_META])) { $v = $this->getMeta(); foreach($validationRules[self::FIELD_META] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_META, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_META])) { $errs[self::FIELD_META] = []; } $errs[self::FIELD_META][$rule] = $err; } } } return $errs; } /** * @param \SimpleXMLElement|string|null $sxe * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource\FHIRSubstanceSourceMaterial $type * @param null|int $libxmlOpts * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource\FHIRSubstanceSourceMaterial */ public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872) { if (null === $sxe) { return null; } if (is_string($sxe)) { libxml_use_internal_errors(true); $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false); if ($sxe === false) { throw new \DomainException(sprintf('FHIRSubstanceSourceMaterial::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors())))); } libxml_use_internal_errors(false); } if (!($sxe instanceof \SimpleXMLElement)) { throw new \InvalidArgumentException(sprintf('FHIRSubstanceSourceMaterial::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe))); } if (null === $type) { $type = new FHIRSubstanceSourceMaterial; } elseif (!is_object($type) || !($type instanceof FHIRSubstanceSourceMaterial)) { throw new \RuntimeException(sprintf( 'FHIRSubstanceSourceMaterial::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRResource\FHIRDomainResource\FHIRSubstanceSourceMaterial or null, %s seen.', is_object($type) ? get_class($type) : gettype($type) )); } FHIRDomainResource::xmlUnserialize($sxe, $type); $xmlNamespaces = $sxe->getDocNamespaces(false, false); if ([] !== $xmlNamespaces) { $ns = reset($xmlNamespaces); if (false !== $ns && '' !== $ns) { $type->_xmlns = $ns; } } $attributes = $sxe->attributes(); $children = $sxe->children(); if (isset($children->countryOfOrigin)) { foreach($children->countryOfOrigin as $child) { $type->addCountryOfOrigin(FHIRCodeableConcept::xmlUnserialize($child)); } } if (isset($children->developmentStage)) { $type->setDevelopmentStage(FHIRCodeableConcept::xmlUnserialize($children->developmentStage)); } if (isset($children->fractionDescription)) { foreach($children->fractionDescription as $child) { $type->addFractionDescription(FHIRSubstanceSourceMaterialFractionDescription::xmlUnserialize($child)); } } if (isset($children->geographicalLocation)) { foreach($children->geographicalLocation as $child) { $type->addGeographicalLocation(FHIRString::xmlUnserialize($child)); } } if (isset($children->organism)) { $type->setOrganism(FHIRSubstanceSourceMaterialOrganism::xmlUnserialize($children->organism)); } if (isset($children->organismId)) { $type->setOrganismId(FHIRIdentifier::xmlUnserialize($children->organismId)); } if (isset($children->organismName)) { $type->setOrganismName(FHIRString::xmlUnserialize($children->organismName)); } if (isset($attributes->organismName)) { $pt = $type->getOrganismName(); if (null !== $pt) { $pt->setValue((string)$attributes->organismName); } else { $type->setOrganismName((string)$attributes->organismName); } } if (isset($children->parentSubstanceId)) { foreach($children->parentSubstanceId as $child) { $type->addParentSubstanceId(FHIRIdentifier::xmlUnserialize($child)); } } if (isset($children->parentSubstanceName)) { foreach($children->parentSubstanceName as $child) { $type->addParentSubstanceName(FHIRString::xmlUnserialize($child)); } } if (isset($children->partDescription)) { foreach($children->partDescription as $child) { $type->addPartDescription(FHIRSubstanceSourceMaterialPartDescription::xmlUnserialize($child)); } } if (isset($children->sourceMaterialClass)) { $type->setSourceMaterialClass(FHIRCodeableConcept::xmlUnserialize($children->sourceMaterialClass)); } if (isset($children->sourceMaterialState)) { $type->setSourceMaterialState(FHIRCodeableConcept::xmlUnserialize($children->sourceMaterialState)); } if (isset($children->sourceMaterialType)) { $type->setSourceMaterialType(FHIRCodeableConcept::xmlUnserialize($children->sourceMaterialType)); } return $type; } /** * @param null|\SimpleXMLElement $sxe * @param null|int $libxmlOpts * @return \SimpleXMLElement */ public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872) { if (null === $sxe) { $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false); } parent::xmlSerialize($sxe); if ([] !== ($vs = $this->getCountryOfOrigin())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_COUNTRY_OF_ORIGIN, null, $v->_getFHIRXMLNamespace())); } } if (null !== ($v = $this->getDevelopmentStage())) { $v->xmlSerialize($sxe->addChild(self::FIELD_DEVELOPMENT_STAGE, null, $v->_getFHIRXMLNamespace())); } if ([] !== ($vs = $this->getFractionDescription())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_FRACTION_DESCRIPTION, null, $v->_getFHIRXMLNamespace())); } } if ([] !== ($vs = $this->getGeographicalLocation())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_GEOGRAPHICAL_LOCATION, null, $v->_getFHIRXMLNamespace())); } } if (null !== ($v = $this->getOrganism())) { $v->xmlSerialize($sxe->addChild(self::FIELD_ORGANISM, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getOrganismId())) { $v->xmlSerialize($sxe->addChild(self::FIELD_ORGANISM_ID, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getOrganismName())) { $v->xmlSerialize($sxe->addChild(self::FIELD_ORGANISM_NAME, null, $v->_getFHIRXMLNamespace())); } if ([] !== ($vs = $this->getParentSubstanceId())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_PARENT_SUBSTANCE_ID, null, $v->_getFHIRXMLNamespace())); } } if ([] !== ($vs = $this->getParentSubstanceName())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_PARENT_SUBSTANCE_NAME, null, $v->_getFHIRXMLNamespace())); } } if ([] !== ($vs = $this->getPartDescription())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_PART_DESCRIPTION, null, $v->_getFHIRXMLNamespace())); } } if (null !== ($v = $this->getSourceMaterialClass())) { $v->xmlSerialize($sxe->addChild(self::FIELD_SOURCE_MATERIAL_CLASS, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getSourceMaterialState())) { $v->xmlSerialize($sxe->addChild(self::FIELD_SOURCE_MATERIAL_STATE, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getSourceMaterialType())) { $v->xmlSerialize($sxe->addChild(self::FIELD_SOURCE_MATERIAL_TYPE, null, $v->_getFHIRXMLNamespace())); } return $sxe; } /** * @return array */ public function jsonSerialize() { $a = parent::jsonSerialize(); if ([] !== ($vs = $this->getCountryOfOrigin())) { $a[self::FIELD_COUNTRY_OF_ORIGIN] = []; foreach($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_COUNTRY_OF_ORIGIN][] = $v; } } if (null !== ($v = $this->getDevelopmentStage())) { $a[self::FIELD_DEVELOPMENT_STAGE] = $v; } if ([] !== ($vs = $this->getFractionDescription())) { $a[self::FIELD_FRACTION_DESCRIPTION] = []; foreach($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_FRACTION_DESCRIPTION][] = $v; } } if ([] !== ($vs = $this->getGeographicalLocation())) { $a[self::FIELD_GEOGRAPHICAL_LOCATION] = []; $encs = []; $encValued = false; foreach ($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_GEOGRAPHICAL_LOCATION][] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 === $cnt || (1 === $cnt && (isset($enc[FHIRString::FIELD_VALUE]) || array_key_exists(FHIRString::FIELD_VALUE, $enc)))) { $encs[] = null; } else { unset($enc[FHIRString::FIELD_VALUE]); $encs[] = $enc; $encValued = true; } } if ($encValued) { $a[self::FIELD_GEOGRAPHICAL_LOCATION_EXT] = $encs; } } if (null !== ($v = $this->getOrganism())) { $a[self::FIELD_ORGANISM] = $v; } if (null !== ($v = $this->getOrganismId())) { $a[self::FIELD_ORGANISM_ID] = $v; } if (null !== ($v = $this->getOrganismName())) { $a[self::FIELD_ORGANISM_NAME] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRString::FIELD_VALUE, $enc)))) { unset($enc[FHIRString::FIELD_VALUE]); $a[self::FIELD_ORGANISM_NAME_EXT] = $enc; } } if ([] !== ($vs = $this->getParentSubstanceId())) { $a[self::FIELD_PARENT_SUBSTANCE_ID] = []; foreach($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_PARENT_SUBSTANCE_ID][] = $v; } } if ([] !== ($vs = $this->getParentSubstanceName())) { $a[self::FIELD_PARENT_SUBSTANCE_NAME] = []; $encs = []; $encValued = false; foreach ($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_PARENT_SUBSTANCE_NAME][] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 === $cnt || (1 === $cnt && (isset($enc[FHIRString::FIELD_VALUE]) || array_key_exists(FHIRString::FIELD_VALUE, $enc)))) { $encs[] = null; } else { unset($enc[FHIRString::FIELD_VALUE]); $encs[] = $enc; $encValued = true; } } if ($encValued) { $a[self::FIELD_PARENT_SUBSTANCE_NAME_EXT] = $encs; } } if ([] !== ($vs = $this->getPartDescription())) { $a[self::FIELD_PART_DESCRIPTION] = []; foreach($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_PART_DESCRIPTION][] = $v; } } if (null !== ($v = $this->getSourceMaterialClass())) { $a[self::FIELD_SOURCE_MATERIAL_CLASS] = $v; } if (null !== ($v = $this->getSourceMaterialState())) { $a[self::FIELD_SOURCE_MATERIAL_STATE] = $v; } if (null !== ($v = $this->getSourceMaterialType())) { $a[self::FIELD_SOURCE_MATERIAL_TYPE] = $v; } if ([] !== ($vs = $this->_getFHIRComments())) { $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs; } return [PHPFHIRConstants::JSON_FIELD_RESOURCE_TYPE => $this->_getResourceType()] + $a; } /** * @return string */ public function __toString() { return self::FHIR_TYPE_NAME; } }
{ "content_hash": "f195652bb21784b16e6b403c73de07c0", "timestamp": "", "source": "github", "line_count": 1921, "max_line_length": 247, "avg_line_length": 46.86985944820406, "alnum_prop": 0.6037295778402212, "repo_name": "dcarbone/php-fhir-generated", "id": "c7fe50081c5610c4cc24e160913e3f5394c33cd0", "size": "92942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DCarbone/PHPFHIRGenerated/R4/FHIRResource/FHIRDomainResource/FHIRSubstanceSourceMaterial.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "113066525" } ], "symlink_target": "" }
export MALLOC_CONF="tcache_max:1024"
{ "content_hash": "db17cf90022ed1129c381e2a8eb97c89", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 36, "avg_line_length": 37, "alnum_prop": 0.7837837837837838, "repo_name": "graetzer/arangodb", "id": "4480d733cb694035040813e9162773927aaaf242", "size": "48", "binary": false, "copies": "10", "ref": "refs/heads/devel", "path": "3rdParty/jemalloc/v5.2.1/test/unit/tcache_max.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "391227" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "63025" }, { "name": "C", "bytes": "7952921" }, { "name": "C#", "bytes": "96431" }, { "name": "C++", "bytes": "274543069" }, { "name": "CMake", "bytes": "646773" }, { "name": "CSS", "bytes": "1054160" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "259402" }, { "name": "Emacs Lisp", "bytes": "14637" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groovy", "bytes": "131" }, { "name": "HTML", "bytes": "2215528" }, { "name": "Java", "bytes": "922156" }, { "name": "JavaScript", "bytes": "53300241" }, { "name": "LLVM", "bytes": "24129" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "17899" }, { "name": "M4", "bytes": "575204" }, { "name": "Makefile", "bytes": "492694" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "28404" }, { "name": "Objective-C", "bytes": "18435" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "107274" }, { "name": "Pascal", "bytes": "150599" }, { "name": "Perl", "bytes": "564374" }, { "name": "Perl6", "bytes": "9918" }, { "name": "Python", "bytes": "4527647" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "1007604" }, { "name": "Ruby", "bytes": "929950" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "424800" }, { "name": "Swift", "bytes": "116" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XSLT", "bytes": "551977" }, { "name": "Yacc", "bytes": "53072" } ], "symlink_target": "" }
namespace ouro { class tbb_context { public: static tbb_context& singleton(); tbb_context() { Observer = new observer(); Init = new ::tbb::task_scheduler_init(); } ~tbb_context() { // This was causing a hang/deadlock so disable the check for now - this only // gets called when the process exits anyway so nothing should be affected. //delete Init; //delete Observer; } inline void dispatch(const std::function<void()>& _Task) { // Use task::enqueue for tasks with no dependency to ensure the main thread // never has to participate in TBB threading and prioritizes tasks that are // issued without dependency as these tend to be tasks that are longer running // and behave more like raw threads. // // task::enqueue vs task::spawn // http://software.intel.com/en-us/blogs/2010/05/04/tbb-30-new-today-version-of-intel-threading-building-blocks/ // The TBB 3.0 schedule supports task::enqueue, which is effectively a “run me // after the other things already pending” request. Although similar to // spawning a task, an enqueued task is scheduled in a different manner. // Enqueued tasks are valuable when approximately first-in first-out behavior // is important, such as in situations where latency of response is more // important than efficient throughput. ::tbb::task& taskToSpawn = *new(::tbb::task::allocate_root()) task_adapter(_Task); ::tbb::task::enqueue(taskToSpawn); } private: class observer : public ::tbb::task_scheduler_observer { public: observer() { observe(); } void on_scheduler_entry(bool is_worker) override { if (is_worker) core_thread_traits::begin_thread("TBB Worker"); } void on_scheduler_exit(bool is_worker) override { if (is_worker) core_thread_traits::end_thread(); } }; class task_adapter : public ::tbb::task { public: task_adapter(const std::function<void()>& _task_adapter) : Task(_task_adapter) {} task_adapter(std::function<void()>&& _task_adapter) { operator=(std::move(_task_adapter)); } task_adapter& operator=(task_adapter&& _That) { if (this != &_That) Task = std::move(_That.Task); return *this; } task* execute() { Task(); return nullptr; } private: std::function<void()> Task; task_adapter(const task_adapter&); const task_adapter& operator=(const task_adapter&); }; ::tbb::task_scheduler_init* Init; observer* Observer; }; template<typename T> T& get_singleton(T*& _pInstance, process_heap::scope _Scope = process_heap::per_process, process_heap::tracking _Tracking = process_heap::garbage_collected) { if (!_pInstance) { process_heap::find_or_allocate( typeid(T).name() , process_heap::per_process , process_heap::garbage_collected , [=](void* _pMemory) { new (_pMemory) T(); } , [=](void* _pMemory) { ((T*)_pMemory)->~T(); } , &_pInstance); } return *_pInstance; } #define oSINGLETON(_ClassName) _ClassName& _ClassName::singleton() { static _ClassName* sInstance = nullptr; return get_singleton(sInstance); } oSINGLETON(tbb_context); class task_group_tbb : public task_group { ::tbb::task_group g; public: ~task_group_tbb() { wait(); } void run(const std::function<void()>& _Task) override { g.run(_Task); } void wait() override { g.wait(); } void cancel() override { g.cancel(); } bool is_canceling() override { return g.is_canceling(); } }; ouro::task_group* new_task_group() { void* p = default_allocate(sizeof(task_group_tbb), memory_alignment::cacheline, scheduler_name()); return p ? new (p) task_group_tbb() : nullptr; } void delete_task_group(ouro::task_group* g) { default_deallocate(g); } void* commitment_allocate(size_t bytes) { return default_allocate(bytes, memory_alignment::cacheline, scheduler_name()); } void commitment_deallocate(void* ptr) { default_deallocate(ptr); } const char* scheduler_name() { return "tbb"; } void ensure_scheduler_initialized() { tbb_context::singleton(); } void dispatch(const std::function<void()>& _Task) { tbb_context::singleton().dispatch(_Task); } void parallel_for(size_t _Begin, size_t _End, const std::function<void(size_t _Index)>& _Task) { ::tbb::parallel_for(_Begin, _End, _Task); } void at_thread_exit(const std::function<void()>& _Task) { oTHROW0(operation_not_supported); } }
{ "content_hash": "90f51e4a3d3d7c281a3ca830adfeb6b8", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 177, "avg_line_length": 30.20689655172414, "alnum_prop": 0.6657534246575343, "repo_name": "dismalion/oooii", "id": "73ce6652f371b70b279c755d96e6dbc9c2ee95b0", "size": "4674", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Ouroboros/Source/oCore/concurrency_tbb.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1183169" }, { "name": "AutoIt", "bytes": "2656" }, { "name": "Batchfile", "bytes": "55732" }, { "name": "C", "bytes": "19203089" }, { "name": "C#", "bytes": "5483" }, { "name": "C++", "bytes": "6329982" }, { "name": "CMake", "bytes": "43005" }, { "name": "CSS", "bytes": "20006" }, { "name": "DIGITAL Command Language", "bytes": "307233" }, { "name": "Emacs Lisp", "bytes": "1684" }, { "name": "Groff", "bytes": "40632" }, { "name": "HTML", "bytes": "502585" }, { "name": "Java", "bytes": "121265" }, { "name": "JavaScript", "bytes": "21232" }, { "name": "Makefile", "bytes": "730389" }, { "name": "Objective-C", "bytes": "268973" }, { "name": "Perl", "bytes": "2635172" }, { "name": "Perl 6", "bytes": "28115" }, { "name": "Prolog", "bytes": "30361" }, { "name": "Protocol Buffer", "bytes": "2825" }, { "name": "Scheme", "bytes": "8727" }, { "name": "Shell", "bytes": "685585" }, { "name": "Visual Basic", "bytes": "7995" }, { "name": "XS", "bytes": "4587" }, { "name": "eC", "bytes": "5223" } ], "symlink_target": "" }
package org.cinchapi.concourse.server.concurrent; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.cinchapi.concourse.ConcourseBaseTest; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.TestData; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.Lists; /** * Unit tests for {@link ReardWriteSharedLock} objects * * @author Jeff Nelson */ public class ReadWriteSharedLockTest extends ConcourseBaseTest { private ReadWriteSharedLock lock; @Override public void beforeEachTest() { lock = new ReadWriteSharedLock(); } @Test public void testMultipleConcurrentWriters() { List<Thread> threads = Lists.newArrayList(); final AtomicBoolean success = new AtomicBoolean(true); Runnable runnable = new Runnable() { @Override public void run() { if(!lock.writeLock().tryLock()) { success.set(false); } } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } Assert.assertTrue(success.get()); } @Test public void testMultipleConcurrentReaders() { List<Thread> threads = Lists.newArrayList(); final AtomicBoolean success = new AtomicBoolean(true); Runnable runnable = new Runnable() { @Override public void run() { if(!lock.readLock().tryLock()) { success.set(false); } } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } Assert.assertTrue(success.get()); } @Test public void testNoReadersWithMultipleConcurrentWriters() { List<Thread> threads = Lists.newArrayList(); Runnable runnable = new Runnable() { @Override public void run() { lock.writeLock().lock(); } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } new Thread(new Runnable() { @Override public void run() { Assert.assertFalse(lock.readLock().tryLock()); } }).start(); } @Test public void testNoWritersWithMultipleConcurrentReaders() { List<Thread> threads = Lists.newArrayList(); Runnable runnable = new Runnable() { @Override public void run() { lock.readLock().lock(); } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } new Thread(new Runnable() { @Override public void run() { Assert.assertFalse(lock.writeLock().tryLock()); } }).start(); } @Test public void testNotifyWhenReadNoLongerBlocked() { List<Thread> threads = Lists.newArrayList(); final AtomicBoolean unlock = new AtomicBoolean(false); Runnable runnable = new Runnable() { @Override public void run() { lock.writeLock().lock(); while (!unlock.get()) { continue; } lock.writeLock().unlock(); } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } new Thread(new Runnable() { @Override public void run() { long t1 = Time.now(); lock.readLock().lock(); try { long elapsed = TimeUnit.MILLISECONDS.convert(Time.now() - t1, TimeUnit.MICROSECONDS); Assert.assertTrue(elapsed >= (.80 * 100)); // sleep time is // imprecise, so // accept 80% // accuracy } finally { lock.readLock().unlock(); } } }).start(); Threads.sleep(100); unlock.set(true); } @Test public void testNotifyWhenWriteNoLongerBlocked() { List<Thread> threads = Lists.newArrayList(); final AtomicBoolean unlock = new AtomicBoolean(false); Runnable runnable = new Runnable() { @Override public void run() { lock.readLock().lock(); while (!unlock.get()) { continue; } lock.readLock().unlock(); } }; for (int i = 0; i < TestData.getScaleCount(); i++) { threads.add(new Thread(runnable)); } for (Thread thread : threads) { thread.start(); } new Thread(new Runnable() { @Override public void run() { long t1 = Time.now(); lock.writeLock().lock(); try { long elapsed = TimeUnit.MILLISECONDS.convert(Time.now() - t1, TimeUnit.MICROSECONDS); Assert.assertTrue(elapsed >= (.80 * 100)); // sleep time is // imprecise, so // accept 80% // accuracy } finally { lock.writeLock().unlock(); } } }).start(); Threads.sleep(100); unlock.set(true); } @Test public void testGetWriteLockCount() { int count = TestData.getScaleCount(); final AtomicInteger finished = new AtomicInteger(0); Runnable runnable = new Runnable() { @Override public void run() { lock.writeLock().lock(); finished.incrementAndGet(); } }; for (int i = 0; i < count; i++) { new Thread(runnable).start(); } while (finished.get() < count) { continue; } Assert.assertEquals(lock.getWriteLockCount(), count); } @Test public void testGetWriteHoldCount() { int count = TestData.getScaleCount(); for (int i = 0; i < count; i++) { lock.writeLock().lock(); } Assert.assertEquals(lock.getWriteHoldCount(), count); } @Test public void testGetReadLockCount() { int count = TestData.getScaleCount(); final AtomicInteger finished = new AtomicInteger(0); Runnable runnable = new Runnable() { @Override public void run() { lock.readLock().lock(); finished.incrementAndGet(); } }; for (int i = 0; i < count; i++) { new Thread(runnable).start(); } while (finished.get() < count) { continue; } Assert.assertEquals(lock.getReadLockCount(), count); } @Test public void testGetReadHoldCount() { int count = TestData.getScaleCount(); for (int i = 0; i < count; i++) { lock.readLock().lock(); } Assert.assertEquals(lock.getReadHoldCount(), count); } @Test public void testIsWriteLockedByCurrentThread() { Runnable a = new Runnable() { @Override public void run() { Assert.assertFalse(lock.isWriteLockedByCurrentThread()); } }; Runnable b = new Runnable() { @Override public void run() { lock.writeLock().lock(); Assert.assertTrue(lock.isWriteLockedByCurrentThread()); } }; for(int i = 0; i < TestData.getScaleCount(); i++){ Thread t = i %3 == 0 ? new Thread(a) : new Thread(b); t.start(); } } }
{ "content_hash": "c3aaa139bb3c04ba384284072d5b806a", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 79, "avg_line_length": 28.0828025477707, "alnum_prop": 0.48094806078475844, "repo_name": "Qunzer/concourse", "id": "de1cfeea31709765f5bc15c7512a8e757be854e8", "size": "9421", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "concourse-server/src/test/java/org/cinchapi/concourse/server/concurrent/ReadWriteSharedLockTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6985" }, { "name": "Groff", "bytes": "39953" }, { "name": "Groovy", "bytes": "84616" }, { "name": "HTML", "bytes": "36688" }, { "name": "Java", "bytes": "3359879" }, { "name": "PHP", "bytes": "2172481" }, { "name": "Python", "bytes": "205360" }, { "name": "Ruby", "bytes": "257335" }, { "name": "Shell", "bytes": "87413" }, { "name": "Thrift", "bytes": "55791" } ], "symlink_target": "" }
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "ifcpp/model/GlobalDefines.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingObject.h" #include "IfcConstructionResource.h" namespace IFC4X3 { class IFCQUERY_EXPORT IfcCrewResourceTypeEnum; //ENTITY class IFCQUERY_EXPORT IfcCrewResource : public IfcConstructionResource { public: IfcCrewResource() = default; IfcCrewResource( int id ); virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepArguments( const std::vector<std::string>& args, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream ); virtual void setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self ); virtual uint8_t getNumAttributes() const { return 11; } virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const; virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const; virtual void unlinkFromInverseCounterparts(); virtual uint32_t classID() const { return 3295246426; } // IfcRoot ----------------------------------------------------------- // attributes: // shared_ptr<IfcGloballyUniqueId> m_GlobalId; // shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcText> m_Description; //optional // IfcObjectDefinition ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse; // std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse; // std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse; // std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse; // std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse; // IfcObject ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_ObjectType; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse; // std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse; // IfcResource ----------------------------------------------------------- // attributes: // shared_ptr<IfcIdentifier> m_Identification; //optional // shared_ptr<IfcText> m_LongDescription; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelAssignsToResource> > m_ResourceOf_inverse; // IfcConstructionResource ----------------------------------------------------------- // attributes: // shared_ptr<IfcResourceTime> m_Usage; //optional // std::vector<shared_ptr<IfcAppliedValue> > m_BaseCosts; //optional // shared_ptr<IfcPhysicalQuantity> m_BaseQuantity; //optional // IfcCrewResource ----------------------------------------------------------- // attributes: shared_ptr<IfcCrewResourceTypeEnum> m_PredefinedType; //optional }; }
{ "content_hash": "eda81e49af3cdabe827484d92c66ad7b", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 159, "avg_line_length": 49.026666666666664, "alnum_prop": 0.6423714985042154, "repo_name": "ifcquery/ifcplusplus", "id": "88da6ad07573c3ac06cb8f7fa45591f261b27e67", "size": "3677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IfcPlusPlus/src/ifcpp/IFC4X3/include/IfcCrewResource.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1270" }, { "name": "C++", "bytes": "10988148" }, { "name": "CMake", "bytes": "6507" }, { "name": "Dockerfile", "bytes": "951" } ], "symlink_target": "" }
using System; using System.Collections; using Server; using Server.Items; using Server.Network; using Server.Accounting; using Server.Commands; namespace Server.RemoteAdmin { public enum LoginResponse : byte { NoUser = 0, BadIP, BadPass, NoAccess, OK } public sealed class AdminCompressedPacket : Packet { public AdminCompressedPacket(byte[] CompData, int CDLen, int unCompSize) : base(0x01) { EnsureCapacity(1 + 2 + 2 + CDLen); m_Stream.Write((ushort)unCompSize); m_Stream.Write(CompData, 0, CDLen); } } public sealed class Login : Packet { public Login(LoginResponse resp) : base(0x02, 2) { m_Stream.Write((byte)resp); } } public sealed class ConsoleData : Packet { public ConsoleData(string str) : base(0x03) { EnsureCapacity(1 + 2 + 1 + str.Length + 1); m_Stream.Write((byte)2); m_Stream.WriteAsciiNull(str); } public ConsoleData(char ch) : base(0x03) { EnsureCapacity(1 + 2 + 1 + 1); m_Stream.Write((byte)3); m_Stream.Write((byte)ch); } } public sealed class ServerInfo : Packet { public ServerInfo() : base(0x04) { string netVer = Environment.Version.ToString(); string os = Environment.OSVersion.ToString(); EnsureCapacity(1 + 2 + (10 * 4) + netVer.Length + 1 + os.Length + 1); int banned = 0; int active = 0; foreach (Account acct in Accounts.GetAccounts()) { if (acct.Banned) ++banned; else ++active; } m_Stream.Write((int)active); m_Stream.Write((int)banned); m_Stream.Write((int)Firewall.List.Count); m_Stream.Write((int)NetState.Instances.Count); m_Stream.Write((int)World.Mobiles.Count); m_Stream.Write((int)Core.ScriptMobiles); m_Stream.Write((int)World.Items.Count); m_Stream.Write((int)Core.ScriptItems); m_Stream.Write((uint)(DateTime.Now - Clock.ServerStart).TotalSeconds); m_Stream.Write((uint)GC.GetTotalMemory(false)); // TODO: uint not sufficient for TotalMemory (long). Fix protocol. m_Stream.WriteAsciiNull(netVer); m_Stream.WriteAsciiNull(os); } } public sealed class AccountSearchResults : Packet { public AccountSearchResults(ArrayList results) : base(0x05) { EnsureCapacity(1 + 2 + 2); m_Stream.Write((byte)results.Count); foreach (Account a in results) { m_Stream.WriteAsciiNull(a.Username); string pwToSend = a.PlainPassword; if (pwToSend == null) pwToSend = "(hidden)"; m_Stream.WriteAsciiNull(pwToSend); m_Stream.Write((byte)a.AccessLevel); m_Stream.Write(a.Banned); unchecked { m_Stream.Write((uint)a.LastLogin.Ticks); } // TODO: This doesn't work, uint.MaxValue is only 7 minutes of ticks. Fix protocol. m_Stream.Write((ushort)a.LoginIPs.Length); for (int i = 0; i < a.LoginIPs.Length; i++) m_Stream.WriteAsciiNull(a.LoginIPs[i].ToString()); m_Stream.Write((ushort)a.IPRestrictions.Length); for (int i = 0; i < a.IPRestrictions.Length; i++) m_Stream.WriteAsciiNull(a.IPRestrictions[i]); } } } public sealed class CompactServerInfo : Packet { public CompactServerInfo() : base(0x51) { EnsureCapacity(1 + 2 + (4 * 4) + 8); m_Stream.Write((int)NetState.Instances.Count - 1); // Clients m_Stream.Write((int)World.Items.Count); // Items m_Stream.Write((int)World.Mobiles.Count); // Mobiles m_Stream.Write((uint)(DateTime.Now - Clock.ServerStart).TotalSeconds); // Age (seconds) long memory = GC.GetTotalMemory(false); m_Stream.Write((uint)(memory >> 32)); // Memory high bytes m_Stream.Write((uint)memory); // Memory low bytes } } public sealed class UOGInfo : Packet { public UOGInfo(string str) : base(0x52, str.Length + 6) // 'R' { m_Stream.WriteAsciiFixed("unUO", 4); m_Stream.WriteAsciiNull(str); } } public sealed class MessageBoxMessage : Packet { public MessageBoxMessage(string msg, string caption) : base(0x08) { EnsureCapacity(1 + 2 + msg.Length + 1 + caption.Length + 1); m_Stream.WriteAsciiNull(msg); m_Stream.WriteAsciiNull(caption); } } }
{ "content_hash": "2d84e951ebedc19068587408e3369b13", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 154, "avg_line_length": 30.690058479532162, "alnum_prop": 0.5137195121951219, "repo_name": "ggobbe/vivre-uo", "id": "15ec02de3f03099303d2fdcd52a3708e9acd8949", "size": "5248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Scripts/Engines/RemoteAdmin/Packets.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "19852349" }, { "name": "CSS", "bytes": "699" }, { "name": "HTML", "bytes": "3008" } ], "symlink_target": "" }
<?php /** * Implements the OpenID attribute exchange specification, version 1.0 * as of svn revision 370 from openid.net svn. * * @package OpenID */ /** * Require utility classes and functions for the consumer. */ require_once "Auth/OpenID/Extension.php"; require_once "Auth/OpenID/Message.php"; require_once "Auth/OpenID/TrustRoot.php"; define('Auth_OpenID_AX_NS_URI', 'http://openid.net/srv/ax/1.0'); // Use this as the 'count' value for an attribute in a FetchRequest to // ask for as many values as the OP can provide. define('Auth_OpenID_AX_UNLIMITED_VALUES', 'unlimited'); // Minimum supported alias length in characters. Here for // completeness. define('Auth_OpenID_AX_MINIMUM_SUPPORTED_ALIAS_LENGTH', 32); /** * AX utility class. * * @package OpenID */ class Auth_OpenID_AX { /** * @param mixed $thing Any object which may be an * Auth_OpenID_AX_Error object. * * @return bool true if $thing is an Auth_OpenID_AX_Error; false * if not. */ static function isError($thing) { return is_a($thing, 'Auth_OpenID_AX_Error'); } } /** * Check an alias for invalid characters; raise AXError if any are * found. Return None if the alias is valid. * * @param string $alias * @return Auth_OpenID_AX_Error|bool */ function Auth_OpenID_AX_checkAlias($alias) { if (strpos($alias, ',') !== false) { return new Auth_OpenID_AX_Error(sprintf( "Alias %s must not contain comma", $alias)); } if (strpos($alias, '.') !== false) { return new Auth_OpenID_AX_Error(sprintf( "Alias %s must not contain period", $alias)); } return true; } /** * Results from data that does not meet the attribute exchange 1.0 * specification * * @package OpenID */ class Auth_OpenID_AX_Error { function __construct($message=null) { $this->message = $message; } } /** * Abstract class containing common code for attribute exchange * messages. * * @package OpenID */ class Auth_OpenID_AX_Message extends Auth_OpenID_Extension { /** * ns_alias: The preferred namespace alias for attribute exchange * messages */ public $ns_alias = 'ax'; /** * mode: The type of this attribute exchange message. This must be * overridden in subclasses. */ public $mode = null; public $ns_uri = Auth_OpenID_AX_NS_URI; /** * Return Auth_OpenID_AX_Error if the mode in the attribute * exchange arguments does not match what is expected for this * class; true otherwise. * * @access private * @param array $ax_args * @return Auth_OpenID_AX_Error|bool */ function _checkMode($ax_args) { $mode = Auth_OpenID::arrayGet($ax_args, 'mode'); if ($mode != $this->mode) { return new Auth_OpenID_AX_Error( sprintf( "Expected mode '%s'; got '%s'", $this->mode, $mode)); } return true; } /** * Return a set of attribute exchange arguments containing the * basic information that must be in every attribute exchange * message. * * @access private */ function _newArgs() { return ['mode' => $this->mode]; } } /** * Represents a single attribute in an attribute exchange * request. This should be added to an AXRequest object in order to * request the attribute. * * @package OpenID */ class Auth_OpenID_AX_AttrInfo { /** * Construct an attribute information object. Do not call this * directly; call make(...) instead. * * @param string $type_uri The type URI for this attribute. * * @param int $count The number of values of this type to request. * * @param bool $required Whether the attribute will be marked as * required in the request. * * @param string $alias The name that should be given to this * attribute in the request. */ function __construct($type_uri, $count, $required, $alias) { /** * required: Whether the attribute will be marked as required * when presented to the subject of the attribute exchange * request. */ $this->required = $required; /** * count: How many values of this type to request from the * subject. Defaults to one. */ $this->count = $count; /** * type_uri: The identifier that determines what the attribute * represents and how it is serialized. For example, one type * URI representing dates could represent a Unix timestamp in * base 10 and another could represent a human-readable * string. */ $this->type_uri = $type_uri; /** * alias: The name that should be given to this attribute in * the request. If it is not supplied, a generic name will be * assigned. For example, if you want to call a Unix timestamp * value 'tstamp', set its alias to that value. If two * attributes in the same message request to use the same * alias, the request will fail to be generated. */ $this->alias = $alias; } /** * Construct an attribute information object. For parameter * details, see the constructor. * * @param string $type_uri * @param int $count * @param bool $required * @param string|null $alias * @return Auth_OpenID_AX_AttrInfo|Auth_OpenID_AX_Error|bool */ static function make($type_uri, $count=1, $required=false, $alias=null) { if ($alias !== null) { $result = Auth_OpenID_AX_checkAlias($alias); if (Auth_OpenID_AX::isError($result)) { return $result; } } return new Auth_OpenID_AX_AttrInfo($type_uri, $count, $required, $alias); } /** * When processing a request for this attribute, the OP should * call this method to determine whether all available attribute * values were requested. If self.count == UNLIMITED_VALUES, this * returns True. Otherwise this returns False, in which case * self.count is an integer. */ function wantsUnlimitedValues() { return $this->count === Auth_OpenID_AX_UNLIMITED_VALUES; } } /** * Given a namespace mapping and a string containing a comma-separated * list of namespace aliases, return a list of type URIs that * correspond to those aliases. * * @param Auth_OpenID_NamespaceMap $namespace_map The mapping from namespace URI to alias * @param string $alias_list_s The string containing the comma-separated * list of aliases. May also be None for convenience. * * @return string[]|Auth_OpenID_AX_Error The list of namespace URIs that corresponds to the * supplied list of aliases. If the string was zero-length or None, an * empty list will be returned. * * return null If an alias is present in the list of aliases but * is not present in the namespace map. */ function Auth_OpenID_AX_toTypeURIs($namespace_map, $alias_list_s) { $uris = []; if ($alias_list_s) { foreach (explode(',', $alias_list_s) as $alias) { $type_uri = $namespace_map->getNamespaceURI($alias); if ($type_uri === null) { // raise KeyError( // 'No type is defined for attribute name %r' % (alias,)) return new Auth_OpenID_AX_Error( sprintf('No type is defined for attribute name %s', $alias) ); } else { $uris[] = $type_uri; } } } return $uris; } /** * An attribute exchange 'fetch_request' message. This message is sent * by a relying party when it wishes to obtain attributes about the * subject of an OpenID authentication request. * * @package OpenID */ class Auth_OpenID_AX_FetchRequest extends Auth_OpenID_AX_Message { public $mode = 'fetch_request'; /** * update_url: A URL that will accept responses for this * attribute exchange request, even in the absence of the user * who made this request. * * @var string */ public $update_url = ''; /** * requested_attributes: The attributes that have been * requested thus far, indexed by the type URI. * * @var array */ private $requested_attributes = []; function __construct($update_url=null) { $this->update_url = $update_url; } /** * Add an attribute to this attribute exchange request. * * @param attribute: The attribute that is being requested * @return bool|Auth_OpenID_AX_Error */ function add($attribute) { if ($this->contains($attribute->type_uri)) { return new Auth_OpenID_AX_Error( sprintf("The attribute %s has already been requested", $attribute->type_uri)); } $this->requested_attributes[$attribute->type_uri] = $attribute; return true; } /** * Get the serialized form of this attribute fetch request. * * @param Auth_OpenID_Request|null $request * @return Auth_OpenID_AX_Error|Auth_OpenID_AX_FetchRequest The fetch request message parameters */ function getExtensionArgs($request = null) { $aliases = new Auth_OpenID_NamespaceMap(); $required = []; $if_available = []; $ax_args = $this->_newArgs(); foreach ($this->requested_attributes as $type_uri => $attribute) { if ($attribute->alias === null) { $alias = $aliases->add($type_uri); } else { $alias = $aliases->addAlias($type_uri, $attribute->alias); if ($alias === null) { return new Auth_OpenID_AX_Error( sprintf("Could not add alias %s for URI %s", $attribute->alias, $type_uri )); } } if ($attribute->required) { $required[] = $alias; } else { $if_available[] = $alias; } if ($attribute->count != 1) { $ax_args['count.' . $alias] = strval($attribute->count); } $ax_args['type.' . $alias] = $type_uri; } if ($required) { $ax_args['required'] = implode(',', $required); } if ($if_available) { $ax_args['if_available'] = implode(',', $if_available); } return $ax_args; } /** * Get the type URIs for all attributes that have been marked as * required. * * @return array A list of the type URIs for attributes that have been * marked as required. */ function getRequiredAttrs() { $required = []; foreach ($this->requested_attributes as $type_uri => $attribute) { if ($attribute->required) { $required[] = $type_uri; } } return $required; } /** * Extract a FetchRequest from an OpenID message * * @param Auth_OpenID_Request $request The OpenID request containing the attribute fetch request * * @return Auth_OpenID_AX_FetchRequest|Auth_OpenID_AX_Error */ static function fromOpenIDRequest($request) { $m = $request->message; $obj = new Auth_OpenID_AX_FetchRequest(); $ax_args = $m->getArgs($obj->ns_uri); $result = $obj->parseExtensionArgs($ax_args); if (Auth_OpenID_AX::isError($result)) { return $result; } if ($obj->update_url) { // Update URL must match the openid.realm of the // underlying OpenID 2 message. $realm = $m->getArg(Auth_OpenID_OPENID_NS, 'realm', $m->getArg( Auth_OpenID_OPENID_NS, 'return_to')); if (!$realm) { $obj = new Auth_OpenID_AX_Error( sprintf("Cannot validate update_url %s " . "against absent realm", $obj->update_url)); } else if (!Auth_OpenID_TrustRoot::match($realm, $obj->update_url)) { $obj = new Auth_OpenID_AX_Error( sprintf("Update URL %s failed validation against realm %s", $obj->update_url, $realm)); } } return $obj; } /** * Given attribute exchange arguments, populate this FetchRequest. * * @param array $ax_args * @return Auth_OpenID_AX_Error|bool if the data to be parsed * does not follow the attribute exchange specification. At least * when 'if_available' or 'required' is not specified for a * particular attribute type. Returns true otherwise. */ function parseExtensionArgs($ax_args) { $result = $this->_checkMode($ax_args); if (Auth_OpenID_AX::isError($result)) { return $result; } $aliases = new Auth_OpenID_NamespaceMap(); foreach ($ax_args as $key => $value) { if (strpos($key, 'type.') === 0) { $alias = substr($key, 5); $type_uri = $value; $alias = $aliases->addAlias($type_uri, $alias); if ($alias === null) { return new Auth_OpenID_AX_Error( sprintf("Could not add alias %s for URI %s", $alias, $type_uri) ); } $count_s = Auth_OpenID::arrayGet($ax_args, 'count.' . $alias); if ($count_s) { $count = Auth_OpenID::intval($count_s); if (($count === false) && ($count_s === Auth_OpenID_AX_UNLIMITED_VALUES)) { $count = $count_s; } } else { $count = 1; } if ($count === false) { return new Auth_OpenID_AX_Error( sprintf("Integer value expected for %s, got %s", 'count.' . $alias, $count_s)); } $attrinfo = Auth_OpenID_AX_AttrInfo::make($type_uri, $count, false, $alias); if (Auth_OpenID_AX::isError($attrinfo)) { return $attrinfo; } $this->add($attrinfo); } } $required = Auth_OpenID_AX_toTypeURIs($aliases, Auth_OpenID::arrayGet($ax_args, 'required')); foreach ($required as $type_uri) { $attrib = $this->requested_attributes[$type_uri]; $attrib->required = true; } $if_available = Auth_OpenID_AX_toTypeURIs($aliases, Auth_OpenID::arrayGet($ax_args, 'if_available')); $all_type_uris = array_merge($required, $if_available); foreach ($aliases->iterNamespaceURIs() as $type_uri) { if (!in_array($type_uri, $all_type_uris)) { return new Auth_OpenID_AX_Error( sprintf('Type URI %s was in the request but not ' . 'present in "required" or "if_available"', $type_uri)); } } $this->update_url = Auth_OpenID::arrayGet($ax_args, 'update_url'); return true; } /** * Iterate over the AttrInfo objects that are contained in this * fetch_request. */ function iterAttrs() { return array_values($this->requested_attributes); } function iterTypes() { return array_keys($this->requested_attributes); } /** * Is the given type URI present in this fetch_request? * * @param string $type_uri * @return bool */ function contains($type_uri) { return in_array($type_uri, $this->iterTypes()); } } /** * An abstract class that implements a message that has attribute keys * and values. It contains the common code between fetch_response and * store_request. * * @package OpenID */ class Auth_OpenID_AX_KeyValueMessage extends Auth_OpenID_AX_Message { /** @var array */ protected $data = []; /** * Add a single value for the given attribute type to the * message. If there are already values specified for this type, * this value will be sent in addition to the values already * specified. * * @param type_uri: The URI for the attribute * @param value: The value to add to the response to the relying * party for this attribute */ function addValue($type_uri, $value) { if (!array_key_exists($type_uri, $this->data)) { $this->data[$type_uri] = []; } $values =& $this->data[$type_uri]; $values[] = $value; } /** * Set the values for the given attribute type. This replaces any * values that have already been set for this attribute. * * @param type_uri: The URI for the attribute * @param values: A list of values to send for this attribute. */ function setValues($type_uri, &$values) { $this->data[$type_uri] =& $values; } /** * Get the extension arguments for the key/value pairs contained * in this message. * * @param Auth_OpenID_NamespaceMap $aliases An alias mapping. Set to None if you don't care * about the aliases for this request. * * @access private * @return array */ function _getExtensionKpublicgs($aliases) { if ($aliases === null) { $aliases = new Auth_OpenID_NamespaceMap(); } $ax_args = []; foreach ($this->data as $type_uri => $values) { $alias = $aliases->add($type_uri); $ax_args['type.' . $alias] = $type_uri; $ax_args['count.' . $alias] = strval(count($values)); foreach ($values as $i => $value) { $key = sprintf('value.%s.%d', $alias, $i + 1); $ax_args[$key] = $value; } } return $ax_args; } /** * Parse attribute exchange key/value arguments into this object. * * @param array $ax_args The attribute exchange fetch_response * arguments, with namespacing removed. * * @return Auth_OpenID_AX_Error|bool */ function parseExtensionArgs($ax_args) { $result = $this->_checkMode($ax_args); if (Auth_OpenID_AX::isError($result)) { return $result; } $aliases = new Auth_OpenID_NamespaceMap(); foreach ($ax_args as $key => $value) { if (strpos($key, 'type.') === 0) { $type_uri = $value; $alias = substr($key, 5); $result = Auth_OpenID_AX_checkAlias($alias); if (Auth_OpenID_AX::isError($result)) { return $result; } $alias = $aliases->addAlias($type_uri, $alias); if ($alias === null) { return new Auth_OpenID_AX_Error( sprintf("Could not add alias %s for URI %s", $alias, $type_uri) ); } } } foreach ($aliases->iteritems() as $pair) { list($type_uri, $alias) = $pair; if (array_key_exists('count.' . $alias, $ax_args) && ($ax_args['count.' . $alias] !== Auth_OpenID_AX_UNLIMITED_VALUES)) { $count_key = 'count.' . $alias; $count_s = $ax_args[$count_key]; $count = Auth_OpenID::intval($count_s); if ($count === false) { return new Auth_OpenID_AX_Error( sprintf("Integer value expected for %s, got %s", 'count. %s' . $alias, $count_s, Auth_OpenID_AX_UNLIMITED_VALUES) ); } $values = []; for ($i = 1; $i < $count + 1; $i++) { $value_key = sprintf('value.%s.%d', $alias, $i); if (!array_key_exists($value_key, $ax_args)) { return new Auth_OpenID_AX_Error( sprintf( "No value found for key %s", $value_key)); } $value = $ax_args[$value_key]; $values[] = $value; } } else { $key = 'value.' . $alias; if (!array_key_exists($key, $ax_args)) { return new Auth_OpenID_AX_Error( sprintf( "No value found for key %s", $key)); } $value = $ax_args['value.' . $alias]; if ($value == '') { $values = []; } else { $values = [$value]; } } $this->data[$type_uri] = $values; } return true; } /** * Get a single value for an attribute. If no value was sent for * this attribute, use the supplied default. If there is more than * one value for this attribute, this method will fail. * * @param string $type_uri The URI for the attribute * @param mixed $default The value to return if the attribute was not * sent in the fetch_response. * * @return Auth_OpenID_AX_Error|mixed */ function getSingle($type_uri, $default=null) { $values = Auth_OpenID::arrayGet($this->data, $type_uri); if (!$values) { return $default; } else if (count($values) == 1) { return $values[0]; } else { return new Auth_OpenID_AX_Error( sprintf('More than one value present for %s', $type_uri) ); } } /** * Get the list of values for this attribute in the * fetch_response. * * XXX: what to do if the values are not present? default * parameter? this is funny because it's always supposed to return * a list, so the default may break that, though it's provided by * the user's code, so it might be okay. If no default is * supplied, should the return be None or []? * * @param string $type_uri The URI of the attribute * * @return Auth_OpenID_AX_Error|array The list of values for this attribute in the * response. May be an empty list. If the attribute was not sent * in the response, returns Auth_OpenID_AX_Error. */ function get($type_uri) { if (array_key_exists($type_uri, $this->data)) { return $this->data[$type_uri]; } else { return new Auth_OpenID_AX_Error( sprintf("Type URI %s not found in response", $type_uri) ); } } /** * Get the number of responses for a particular attribute in this * fetch_response message. * * @param string $type_uri The URI of the attribute * * @returns int|Auth_OpenID_AX_Error The number of values sent for this attribute. If * the attribute was not sent in the response, returns * Auth_OpenID_AX_Error. */ function count($type_uri) { if (array_key_exists($type_uri, $this->data)) { return count($this->get($type_uri)); } else { return new Auth_OpenID_AX_Error( sprintf("Type URI %s not found in response", $type_uri) ); } } } /** * A fetch_response attribute exchange message. * * @package OpenID */ class Auth_OpenID_AX_FetchResponse extends Auth_OpenID_AX_KeyValueMessage { public $mode = 'fetch_response'; /** @var string */ private $update_url = ''; function __construct($update_url=null) { $this->update_url = $update_url; } /** * Serialize this object into arguments in the attribute exchange * namespace * * @param Auth_OpenID_AX_FetchRequest|null $request * @return Auth_OpenID_AX_Error|array|null $args The dictionary of unqualified attribute exchange * arguments that represent this fetch_response, or * Auth_OpenID_AX_Error on error. */ function getExtensionArgs($request=null) { $aliases = new Auth_OpenID_NamespaceMap(); $zero_value_types = []; if ($request !== null) { // Validate the data in the context of the request (the // same attributes should be present in each, and the // counts in the response must be no more than the counts // in the request) foreach ($this->data as $type_uri => $unused) { if (!$request->contains($type_uri)) { return new Auth_OpenID_AX_Error( sprintf("Response attribute not present in request: %s", $type_uri) ); } } foreach ($request->iterAttrs() as $attr_info) { // Copy the aliases from the request so that reading // the response in light of the request is easier if ($attr_info->alias === null) { $aliases->add($attr_info->type_uri); } else { $alias = $aliases->addAlias($attr_info->type_uri, $attr_info->alias); if ($alias === null) { return new Auth_OpenID_AX_Error( sprintf("Could not add alias %s for URI %s", $attr_info->alias, $attr_info->type_uri) ); } } if (array_key_exists($attr_info->type_uri, $this->data)) { $values = $this->data[$attr_info->type_uri]; } else { $values = []; $zero_value_types[] = $attr_info; } if (($attr_info->count != Auth_OpenID_AX_UNLIMITED_VALUES) && ($attr_info->count < count($values))) { return new Auth_OpenID_AX_Error( sprintf("More than the number of requested values " . "were specified for %s", $attr_info->type_uri) ); } } } $kv_args = $this->_getExtensionKpublicgs($aliases); // Add the KV args into the response with the args that are // unique to the fetch_response $ax_args = $this->_newArgs(); // For each requested attribute, put its type/alias and count // into the response even if no data were returned. foreach ($zero_value_types as $attr_info) { $alias = $aliases->getAlias($attr_info->type_uri); $kv_args['type.' . $alias] = $attr_info->type_uri; $kv_args['count.' . $alias] = '0'; } $update_url = null; if ($request) { $update_url = $request->update_url; } else { $update_url = $this->update_url; } if ($update_url) { $ax_args['update_url'] = $update_url; } Auth_OpenID::update($ax_args, $kv_args); return $ax_args; } /** * @param array $ax_args * @return Auth_OpenID_AX_Error|bool Auth_OpenID_AX_Error on failure or true on * success. */ function parseExtensionArgs($ax_args) { $result = parent::parseExtensionArgs($ax_args); if (Auth_OpenID_AX::isError($result)) { return $result; } $this->update_url = Auth_OpenID::arrayGet($ax_args, 'update_url'); return true; } /** * Construct a FetchResponse object from an OpenID library * SuccessResponse object. * * @param Auth_OpenID_SuccessResponse $success_response A successful id_res response object * * @param bool $signed Whether non-signed args should be processsed. If * True (the default), only signed arguments will be processsed. * * @return Auth_OpenID_AX_FetchResponse|null A FetchResponse containing the data from the * OpenID message */ static function fromSuccessResponse($success_response, $signed=true) { $obj = new Auth_OpenID_AX_FetchResponse(); if ($signed) { $ax_args = $success_response->getSignedNS($obj->ns_uri); } else { $ax_args = $success_response->message->getArgs($obj->ns_uri); } if ($ax_args === null || Auth_OpenID::isFailure($ax_args) || sizeof($ax_args) == 0) { return null; } $result = $obj->parseExtensionArgs($ax_args); if (Auth_OpenID_AX::isError($result)) { #XXX log me return null; } return $obj; } } /** * A store request attribute exchange message representation. * * @package OpenID */ class Auth_OpenID_AX_StoreRequest extends Auth_OpenID_AX_KeyValueMessage { public $mode = 'store_request'; /** * @param Auth_OpenID_NamespaceMap $aliases The namespace aliases to use when making * this store response. Leave as None to use defaults. * @return array|null */ function getExtensionArgs($aliases=null) { $ax_args = $this->_newArgs(); $kv_args = $this->_getExtensionKpublicgs($aliases); Auth_OpenID::update($ax_args, $kv_args); return $ax_args; } } /** * An indication that the store request was processed along with this * OpenID transaction. Use make(), NOT the constructor, to create * response objects. * * @package OpenID */ class Auth_OpenID_AX_StoreResponse extends Auth_OpenID_AX_Message { public $SUCCESS_MODE = 'store_response_success'; public $FAILURE_MODE = 'store_response_failure'; /** * @var string */ private $error_message = ''; /** * @param bool $succeeded * @param string $error_message * @return Auth_OpenID_AX_Error|Auth_OpenID_AX_StoreResponse */ function make($succeeded=true, $error_message=null) { if (($succeeded) && ($error_message !== null)) { return new Auth_OpenID_AX_Error('An error message may only be '. 'included in a failing fetch response'); } return new Auth_OpenID_AX_StoreResponse($succeeded, $error_message); } function __construct($succeeded=true, $error_message=null) { if ($succeeded) { $this->mode = $this->SUCCESS_MODE; } else { $this->mode = $this->FAILURE_MODE; } $this->error_message = $error_message; } /** * Was this response a success response? */ function succeeded() { return $this->mode == $this->SUCCESS_MODE; } /** * Get the string arguments that should be added to an OpenID * message for this extension. * * @param Auth_OpenID_Request|null $request * @return null */ function getExtensionArgs($request = null) { $ax_args = $this->_newArgs(); if ((!$this->succeeded()) && $this->error_message) { $ax_args['error'] = $this->error_message; } return $ax_args; } }
{ "content_hash": "0852938d6e017690ceeeb66b7193fa37", "timestamp": "", "source": "github", "line_count": 1054, "max_line_length": 133, "avg_line_length": 30.540796963946867, "alnum_prop": 0.5281453867660765, "repo_name": "openid/php-openid", "id": "82b354d1cb70204d070b2787708692eec32da0f0", "size": "32190", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Auth/OpenID/AX.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2300" }, { "name": "PHP", "bytes": "1050637" }, { "name": "Perl", "bytes": "3794" }, { "name": "Python", "bytes": "16292" }, { "name": "Shell", "bytes": "4106" } ], "symlink_target": "" }
<?php namespace skeeks\cms\components\urlRules; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsSite; use skeeks\cms\models\Tree; use \yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\web\Application; /** * Class UrlRuleContentElement * @package skeeks\cms\components\urlRules */ class UrlRuleContentElement extends \yii\web\UrlRule { public function init() { if ($this->name === null) { $this->name = __CLASS__; } } /** * //Это можно использовать только в коротких сценариях, иначе произойдет переполнение памяти * @var array */ static public $models = []; /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { if ($route == 'cms/content-element/view') { $contentElement = $this->_getElement($params); if (!$contentElement) { return false; } $url = ''; $cmsTree = ArrayHelper::getValue($params, 'cmsTree'); ArrayHelper::remove($params, 'cmsTree'); $cmsSite = ArrayHelper::getValue($params, 'cmsSite', null); ArrayHelper::remove($params, 'cmsSite'); //We need to build on what that particular section of the settings /*if (!$cmsTree) { $cmsTree = $contentElement->cmsTree; }*/ if ($cmsTree) { $url = $cmsTree->dir . "/"; } //$url .= $contentElement->id . "-" . $contentElement->code; $url .= $contentElement->code . '-' . $contentElement->id; if (strpos($url, '//') !== false) { $url = preg_replace('#/+#', '/', $url); } /** * @see parent::createUrl() */ if ($url !== '') { $url .= ($this->suffix === null ? $manager->suffix : $this->suffix); } /** * @see parent::createUrl() */ if (!empty($params) && ($query = http_build_query($params)) !== '') { $url .= '?' . $query; } //Раздел привязан к сайту, сайт может отличаться от того на котором мы сейчас находимся if (!$cmsSite) { $siteClass = \Yii::$app->skeeks->siteClass; $cmsSite = $siteClass::getById($contentElement->cms_site_id); //$cmsSite = $contentElement->cmsSite; } if ($cmsSite) { if ($cmsSite->cmsSiteMainDomain) { return $cmsSite->url . '/' . $url; } } return $url; } return false; } /** * * @param $params * @return bool|CmsContentElement */ protected function _getElement(&$params) { $id = (int)ArrayHelper::getValue($params, 'id'); $contentElement = ArrayHelper::getValue($params, 'model'); if (!$id && !$contentElement) { return false; } if ($contentElement && $contentElement instanceof CmsContentElement) { if (\Yii::$app instanceof Application) { self::$models[$contentElement->id] = $contentElement; } } else { /** * @var $contentElement CmsContentElement */ if (!$contentElement = ArrayHelper::getValue(self::$models, $id)) { $contentElement = CmsContentElement::findOne(['id' => $id]); if (\Yii::$app instanceof Application) { self::$models[$id] = $contentElement; } } } ArrayHelper::remove($params, 'id'); ArrayHelper::remove($params, 'code'); ArrayHelper::remove($params, 'model'); return $contentElement; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { if ($this->mode === self::CREATION_ONLY) { return false; } if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) { return false; } $pathInfo = $request->getPathInfo(); if ($this->host !== null) { $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo); } $params = $request->getQueryParams(); $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); $treeNode = null; if (!$pathInfo) { return false; } if ($suffix) { $pathInfo = substr($pathInfo, 0, strlen($pathInfo) - strlen($suffix)); } if (preg_match('/\/(?<code>\S+)\-(?<id>\d+)$/i', "/" . $pathInfo, $matches)) { return [ 'cms/content-element/view', [ 'id' => $matches['id'], 'code' => $matches['code'] ] ]; } /** * @deprecated */ if (preg_match('/\/(?<id>\d+)\-(?<code>\S+)$/i', "/" . $pathInfo, $matches)) { return [ 'cms/content-element/view', [ 'id' => $matches['id'], 'code' => $matches['code'] ] ]; } return false; /*if (!preg_match('/\/(?<id>\d+)\-(?<code>\S+)$/i', "/" . $pathInfo, $matches)) { return false; }*/ } }
{ "content_hash": "8d4fa044f44f9508fded281fe7272435", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 104, "avg_line_length": 27.66346153846154, "alnum_prop": 0.47149808828640943, "repo_name": "skeeks-cms/cms", "id": "732850d7eff9886799c401e886237c9754ccf71a", "size": "6046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/urlRules/UrlRuleContentElement.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "10030" }, { "name": "Hack", "bytes": "7" }, { "name": "JavaScript", "bytes": "45956" }, { "name": "PHP", "bytes": "2469965" } ], "symlink_target": "" }
import { TestBed, inject } from '@angular/core/testing'; import { Service867Service } from './service-867.service'; describe('Service867Service', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [Service867Service] }); }); it('should ...', inject([Service867Service], (service: Service867Service) => { expect(service).toBeTruthy(); })); });
{ "content_hash": "178c4f2ee558c927138aa272e75fff4c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 80, "avg_line_length": 23.176470588235293, "alnum_prop": 0.6421319796954315, "repo_name": "angular/angular-cli-stress-test", "id": "ca0fdd2e0a0c48b8d9fe81e3154918a6da829e47", "size": "596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/services/service-867.service.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1040888" }, { "name": "HTML", "bytes": "300322" }, { "name": "JavaScript", "bytes": "2404" }, { "name": "TypeScript", "bytes": "8535506" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> <Catalog uuid="2131ff1e-77b0-48d2-81e6-f2703f27a16e"> <InternalInfo> <xr:GeneratedType name="CatalogObject.Users" category="Object"> <xr:TypeId>b6b93851-6330-4542-8dc8-a5b17c9c2692</xr:TypeId> <xr:ValueId>7fd907eb-175e-475a-89f2-9f164f0c3f55</xr:ValueId> </xr:GeneratedType> <xr:GeneratedType name="CatalogRef.Users" category="Ref"> <xr:TypeId>53cbe5af-5a50-4540-a501-e59e39dcf4bc</xr:TypeId> <xr:ValueId>f38a9bc7-869f-4112-91d2-b99a15e098f3</xr:ValueId> </xr:GeneratedType> <xr:GeneratedType name="CatalogSelection.Users" category="Selection"> <xr:TypeId>91691412-eb64-42c4-93b5-3cfe757dc927</xr:TypeId> <xr:ValueId>fdb6ccdd-f1cc-472c-87f1-b918e6f2acb3</xr:ValueId> </xr:GeneratedType> <xr:GeneratedType name="CatalogList.Users" category="List"> <xr:TypeId>2d1ad634-289e-45c5-81cf-8fae6b0aee7a</xr:TypeId> <xr:ValueId>633ce26a-d03e-49ed-ab92-c34a508da0df</xr:ValueId> </xr:GeneratedType> <xr:GeneratedType name="CatalogManager.Users" category="Manager"> <xr:TypeId>ab36a136-d761-498f-909d-fc9c0c2e2117</xr:TypeId> <xr:ValueId>2b77c46b-47b7-4155-aa56-f88c2cad150a</xr:ValueId> </xr:GeneratedType> </InternalInfo> <Properties> <Name>Users</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Users</v8:content> </v8:item> </Synonym> <Comment/> <Hierarchical>false</Hierarchical> <HierarchyType>HierarchyFoldersAndItems</HierarchyType> <LimitLevelCount>false</LimitLevelCount> <LevelCount>2</LevelCount> <FoldersOnTop>false</FoldersOnTop> <UseStandardCommands>true</UseStandardCommands> <Owners/> <SubordinationUse>ToItems</SubordinationUse> <CodeLength>0</CodeLength> <DescriptionLength>100</DescriptionLength> <CodeType>String</CodeType> <CodeAllowedLength>Variable</CodeAllowedLength> <CodeSeries>WholeCatalog</CodeSeries> <CheckUnique>false</CheckUnique> <Autonumbering>false</Autonumbering> <DefaultPresentation>AsDescription</DefaultPresentation> <StandardAttributes> <xr:StandardAttribute name="PredefinedDataName"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Predefined"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Ref"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="DeletionMark"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:type="xs:boolean">false</xr:FillValue> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="IsFolder"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Owner"> <xr:LinkByType/> <xr:FillChecking>ShowError</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>true</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Parent"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>true</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Group where user belongs</v8:content> </v8:item> </xr:ToolTip> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>In group</v8:content> </v8:item> </xr:Synonym> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:type="xr:DesignTimeRef">Catalog.Users.EmptyRef</xr:FillValue> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Description"> <xr:LinkByType/> <xr:FillChecking>ShowError</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>User presentation in the interface, usually it is first and second name.</v8:content> </v8:item> </xr:ToolTip> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Full name</v8:content> </v8:item> </xr:Synonym> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:type="xs:string"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> <xr:StandardAttribute name="Code"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Infobase account user name</v8:content> </v8:item> </xr:ToolTip> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>User</v8:content> </v8:item> </xr:Synonym> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:type="xs:string"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> </StandardAttributes> <Characteristics/> <PredefinedDataUpdate>Auto</PredefinedDataUpdate> <EditType>InDialog</EditType> <QuickChoice>false</QuickChoice> <ChoiceMode>BothWays</ChoiceMode> <InputByString> <xr:Field>Catalog.Users.StandardAttribute.Description</xr:Field> </InputByString> <SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString> <FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString> <ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString> <DefaultObjectForm>Catalog.Users.Form.ItemForm</DefaultObjectForm> <DefaultFolderForm/> <DefaultListForm>Catalog.Users.Form.ListForm</DefaultListForm> <DefaultChoiceForm>Catalog.Users.Form.ListForm</DefaultChoiceForm> <DefaultFolderChoiceForm/> <AuxiliaryObjectForm/> <AuxiliaryFolderForm/> <AuxiliaryListForm/> <AuxiliaryChoiceForm/> <AuxiliaryFolderChoiceForm/> <IncludeHelpInContents>true</IncludeHelpInContents> <BasedOn/> <DataLockFields/> <DataLockControlMode>Managed</DataLockControlMode> <FullTextSearch>Use</FullTextSearch> <ObjectPresentation> <v8:item> <v8:lang>en</v8:lang> <v8:content>User</v8:content> </v8:item> </ObjectPresentation> <ExtendedObjectPresentation/> <ListPresentation/> <ExtendedListPresentation/> <Explanation/> <CreateOnInput>Use</CreateOnInput> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> </Properties> <ChildObjects> <Attribute uuid="ae6d0e12-8857-476c-b4b2-f03295cbed3e"> <Properties> <Name>NotValid</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Not valid</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:boolean</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>The user no longer operates the application but user's details are stored. Such users are hidden from all lists used for selecting or picking users in documents and other application parts.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>Index</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="7ee1e0d0-9735-45da-bd24-c0dbabfd5b1e"> <Properties> <Name>Comment</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Comment</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>0</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>ru</v8:lang> <v8:content>Arbitrary string</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>true</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:type="xs:string"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="bd0e3bd4-1207-41ea-8dfc-afa8f7d08cc2"> <Properties> <Name>Internal</Name> <Synonym> <v8:item> <v8:lang>ru</v8:lang> <v8:content>Internal</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:boolean</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Shared or separated internal user whose rights are specified directly and programmatically.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="51d83895-5692-4479-9612-07c790d19dff"> <Properties> <Name>Prepared</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Prepared</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:boolean</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>ru</v8:lang> <v8:content>The user has been prepared by a person responsible for the user list.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="8db2a971-47d5-4186-ac05-730b25ca7222"> <Properties> <Name>InfobaseUserID</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Infobase user ID</v8:content> </v8:item> </Synonym> <Comment>It is required for mapping Users catalog item to infobase user.</Comment> <Type> <v8:Type>v8:UUID</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Unique infobase user ID which is used to link the catalog item with infobase user.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>Index</Indexing> <FullTextSearch>DontUse</FullTextSearch> </Properties> </Attribute> <Attribute uuid="dface15c-cd65-4fb1-b4dd-b513086d3f8e"> <Properties> <Name>ServiceUserID</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Service user ID</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>v8:UUID</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>UUID of a service user that is mapped with the current catalog item.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>Index</Indexing> <FullTextSearch>DontUse</FullTextSearch> </Properties> </Attribute> <Attribute uuid="d854b528-8456-4453-9c2d-4f96caf10481"> <Properties> <Name>InfobaseUserProperties</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Infobase user properties</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>v8:ValueStorage</v8:Type> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Internal storage with some infobase user properties</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillFromFillingValue>false</FillFromFillingValue> <FillValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Use>ForItem</Use> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <TabularSection uuid="d6969c1e-e13c-4542-abb7-9cf6bb50b8e2"> <InternalInfo> <xr:GeneratedType name="CatalogTabularSection.Users.ContactInformation" category="TabularSection"> <xr:TypeId>c0a04c76-07c3-4c54-b386-2d1dde72458c</xr:TypeId> <xr:ValueId>6d96b0e9-f453-4eb4-95c2-2e6732438dea</xr:ValueId> </xr:GeneratedType> <xr:GeneratedType name="CatalogTabularSectionRow.Users.ContactInformation" category="TabularSectionRow"> <xr:TypeId>6a940803-b679-4a70-9544-7eb0e0d9b611</xr:TypeId> <xr:ValueId>dfa411ce-5b74-4587-b057-a84369421f44</xr:ValueId> </xr:GeneratedType> </InternalInfo> <Properties> <Name>ContactInformation</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Contact information</v8:content> </v8:item> </Synonym> <Comment/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Contact information storage (addresses, web pages, phone numbers, and so on)</v8:content> </v8:item> </ToolTip> <FillChecking>DontCheck</FillChecking> <StandardAttributes> <xr:StandardAttribute name="LineNumber"> <xr:LinkByType/> <xr:FillChecking>DontCheck</xr:FillChecking> <xr:MultiLine>false</xr:MultiLine> <xr:FillFromFillingValue>false</xr:FillFromFillingValue> <xr:CreateOnInput>Auto</xr:CreateOnInput> <xr:MaxValue xsi:nil="true"/> <xr:ToolTip/> <xr:ExtendedEdit>false</xr:ExtendedEdit> <xr:Format/> <xr:ChoiceForm/> <xr:QuickChoice>Auto</xr:QuickChoice> <xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput> <xr:EditFormat/> <xr:PasswordMode>false</xr:PasswordMode> <xr:MarkNegatives>false</xr:MarkNegatives> <xr:MinValue xsi:nil="true"/> <xr:Synonym/> <xr:Comment/> <xr:FullTextSearch>Use</xr:FullTextSearch> <xr:ChoiceParameterLinks/> <xr:FillValue xsi:nil="true"/> <xr:Mask/> <xr:ChoiceParameters/> </xr:StandardAttribute> </StandardAttributes> <Use>ForItem</Use> </Properties> <ChildObjects> <Attribute uuid="ccd91f94-d3f1-4aa3-90cf-081d72c4cab1"> <Properties> <Name>Type</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Type</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>10</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Contact information type (address, phone, and so on)</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="aa7d5ca4-3c02-4ca1-a790-2435ee9f9f02"> <Properties> <Name>Kind</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Kind</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>10</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Contact information kind</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="b7e85f5c-4312-44c6-895a-3f636a8c78d8"> <Properties> <Name>Presentation</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Presentation</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>500</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Contact information presentation for forms.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="3b6e7ee6-0ef5-464a-a01a-6143479c7a61"> <Properties> <Name>FieldValues</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Field values</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>0</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Auxiliary attribute for storing contact information.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="1969e8d1-0a82-44cb-a0d4-e5badb1d28d4"> <Properties> <Name>Country</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Country</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>100</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Country (is filled for address)</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="a1afacc5-f49a-4df2-a44d-479594d50179"> <Properties> <Name>State</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>State</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>50</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>State (is filled for address)</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="fe70eba3-7477-4a38-a511-d69960abb928"> <Properties> <Name>City</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>City</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>50</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>City (is filled for address)</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="6534ea96-2145-49e6-9739-f59459dc7f6b"> <Properties> <Name>EmailAddress</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Email address</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>100</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Email address</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="f49bffa0-cad6-4801-b82e-21aa580e72e6"> <Properties> <Name>ServerDomainName</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Server domain name</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>100</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>The domain of an email server or a web page.</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="bbbfb817-8db3-4415-86c3-af028276d6e9"> <Properties> <Name>PhoneNumber</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Phone number</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>20</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Full phone number</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> <Attribute uuid="6a91112c-f6cc-47a0-9d26-a36c7702af7d"> <Properties> <Name>PhoneNumberWithoutCodes</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Phone number without codes</v8:content> </v8:item> </Synonym> <Comment/> <Type> <v8:Type>xs:string</v8:Type> <v8:StringQualifiers> <v8:Length>20</v8:Length> <v8:AllowedLength>Variable</v8:AllowedLength> </v8:StringQualifiers> </Type> <PasswordMode>false</PasswordMode> <Format/> <EditFormat/> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Phone number without codes and extension</v8:content> </v8:item> </ToolTip> <MarkNegatives>false</MarkNegatives> <Mask/> <MultiLine>false</MultiLine> <ExtendedEdit>false</ExtendedEdit> <MinValue xsi:nil="true"/> <MaxValue xsi:nil="true"/> <FillChecking>DontCheck</FillChecking> <ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems> <ChoiceParameterLinks/> <ChoiceParameters/> <QuickChoice>Auto</QuickChoice> <CreateOnInput>Auto</CreateOnInput> <ChoiceForm/> <LinkByType/> <ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput> <Indexing>DontIndex</Indexing> <FullTextSearch>Use</FullTextSearch> </Properties> </Attribute> </ChildObjects> </TabularSection> <Form>ItemForm</Form> <Form>ListForm</Form> <Form>InfobaseUsers</Form> <Form>OSUserSelectionForm</Form> <Form>EmailAddressChange</Form> <Command uuid="bed3f0b2-40c6-4323-9bca-cb8864e38ec0"> <Properties> <Name>InfobaseUsers</Name> <Synonym> <v8:item> <v8:lang>en</v8:lang> <v8:content>Infobase users</v8:content> </v8:item> </Synonym> <Comment/> <Group>FormCommandBarImportant</Group> <CommandParameterType/> <ParameterUseMode>Single</ParameterUseMode> <ModifiesData>false</ModifiesData> <Representation>Auto</Representation> <ToolTip> <v8:item> <v8:lang>en</v8:lang> <v8:content>Infobase users</v8:content> </v8:item> </ToolTip> <Picture/> <Shortcut/> </Properties> </Command> </ChildObjects> </Catalog> </MetaDataObject>
{ "content_hash": "04e7953cbe81ca44ccaa31deb0b66c0a", "timestamp": "", "source": "github", "line_count": 1246, "max_line_length": 867, "avg_line_length": 33.3892455858748, "alnum_prop": 0.6356272384203062, "repo_name": "alexkmbk/1CI", "id": "c1dc09baf17eae1b12e67187d935199c69a40ee0", "size": "41605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Catalogs/Users.xml", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "3123796" }, { "name": "CSS", "bytes": "8912" }, { "name": "HTML", "bytes": "195844" }, { "name": "Python", "bytes": "6949" } ], "symlink_target": "" }
/** * @fileoverview Unit tests for the UI prompt. */ /** @suppress {extraProvide} */ goog.provide('e2e.ext.ui.PromptTest'); goog.require('e2e.ext.Launcher'); goog.require('e2e.ext.actions.DecryptVerify'); goog.require('e2e.ext.actions.EncryptSign'); goog.require('e2e.ext.actions.GetKeyDescription'); goog.require('e2e.ext.constants'); goog.require('e2e.ext.constants.Actions'); goog.require('e2e.ext.constants.CssClass'); goog.require('e2e.ext.constants.ElementId'); goog.require('e2e.ext.testingstubs'); goog.require('e2e.ext.ui.Prompt'); goog.require('e2e.ext.ui.draftmanager'); goog.require('e2e.ext.ui.preferences'); goog.require('e2e.ext.utils'); goog.require('e2e.ext.utils.text'); /** @suppress {extraRequire} intentionally importing all signer functions */ goog.require('e2e.signer.all'); goog.require('goog.Timer'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.mockmatchers'); goog.require('goog.testing.mockmatchers.ArgumentMatcher'); goog.require('goog.testing.mockmatchers.SaveArgument'); goog.setTestOnly(); var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(document.title); asyncTestCase.stepTimeout = 2000; var constants = e2e.ext.constants; var drafts = e2e.ext.ui.draftmanager; var mockControl = null; var preferences = e2e.ext.ui.preferences; var prompt = null; var stubs = new goog.testing.PropertyReplacer(); var utils = e2e.ext.utils; function setUp() { window.localStorage.clear(); mockControl = new goog.testing.MockControl(); e2e.ext.testingstubs.initStubs(stubs); stubs.replace(goog.Timer.prototype, 'start', goog.nullFunction); prompt = new e2e.ext.ui.Prompt(); prompt.pgpLauncher_ = new e2e.ext.Launcher(); prompt.pgpLauncher_.start(); stubs.setPath('chrome.runtime.getBackgroundPage', function(callback) { callback({launcher: prompt.pgpLauncher_}); }); stubs.replace(e2e.ext.Launcher.prototype, 'hasPassphrase', function() { return true; }); } function tearDown() { stubs.reset(); mockControl.$tearDown(); prompt.dispose(); goog.dispose(prompt); } /* function testGetSelectedContent() { stubs.replace(e2e.ext.Launcher.prototype, 'hasPassphrase', function() { return true; }); var queriedForSelectedContent = false; stubs.replace( e2e.ext.Launcher.prototype, 'getSelectedContent', function() { queriedForSelectedContent = true; }); stubs.replace(chrome.runtime, 'getBackgroundPage', function(callback) { callback({launcher: new e2e.ext.Launcher()}); }); prompt.decorate(document.documentElement); assertTrue('Failed to query for selected content', queriedForSelectedContent); } */ function testRendering() { stubs.replace(chrome.i18n, 'getMessage', function() { return 'PGP Encrypt/Sign'; }); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: 'irrelevant', recipients: ['example@example.com'] }); var elem = document.body; assertTrue(elem.textContent.indexOf('PGP Encrypt/Sign') > -1); } function testMenuRendering() { prompt.decorate(document.documentElement); prompt.processSelectedContent_(); var elem = document.body; assertContains('actionUserSpecified', elem.textContent); } function testDisposeOnClose() { prompt.close(); assertTrue('Failed to dispose prompt', prompt.isDisposed()); } function testGetTitle() { stubs.replace(chrome.i18n, 'getMessage', function(msgId) { return msgId; }); assertEquals('actionUserSpecified', prompt.getTitle_(e2e.ext.constants.Actions.USER_SPECIFIED)); assertEquals('actionUnlockKeyring', prompt.getTitle_(e2e.ext.constants.Actions.GET_PASSPHRASE)); } var PRIVATE_KEY_ASCII = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: GnuPG v1.4.11 (GNU/Linux)\n' + '\n' + 'lQIGBFHMug4BBACW9E+4EJXykFpkdHS1K7nkTFcvFHpnJsbHSB99Px6ib6jusVNJ\n' + 'SjWhbWlcQXXpwDKRKKItRHE4v2zin89+hWPxQEU4l79S17i8xSXT8o02I4e7cPrj\n' + 'j1JSyQk2YpIK5zNO7cU1IlVRHrTmvrp8ip9exF9D5UqQGxmXncjtJxsF8wARAQAB\n' + '/gkDAgxGSvTcN/9nYDs6DJVcH5zs/RiEw8xwMhVxHepb0D0jHDxWpPxHoT6enWSS\n' + 'expqlvP6Oclgp0AgUBZNLr1G8i6cFTbH8VP1f+be3isyt/DzBYUE3GEBj/6pg2ft\n' + 'tRgUs/yWT731BkvK6o3kMBm5OJtOSi6rBwvNgfgA3KLlv4QknOHAFoEZL+CpsjWn\n' + 'SPE7SdAPIcIiT4aIrIe4RWm0iP1HcCfhoGgvbMlrB9r5uQdlenRxWwhP+Tlik5A9\n' + 'uYqrAT4Rxb7ce+IDuWPHGOZVIQr4trXegGpCHqfi0DgZ0MOolaSnfcrRDZMy0zAd\n' + 'HASBijOSPTZiF1aSg/p6ghqBvDwRvRgLv1HNdaObH+LRpr/AI/t0o6AmqWdeuLIG\n' + 'TctvYIIEZNvThDvYzjcpoxz03qRD3I+b8nuyweKH/2bUSobHc6EacHYSUML8SxRC\n' + 'TcM/iyDcplK5g1Rul73fhAjw3A9Y6elGiitzmO/oeAi2+Oh7XrUdnaG0BnRlc3Qg\n' + 'NIi4BBMBAgAiBQJRzLoOAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAG\n' + '/5ysCS2oCL2SA/9EV9j3T/TM3VRD0NvNySHodcxCP1BF0zm/M84I/WHQsGKmHStf\n' + 'CqqEGruB8E6NHQMJwNp1TzcswuxE0wiTJiXKe3w3+GZhPHdW5zcgiMKKYLn80Tk6\n' + 'fUMx1zVZtXlSBYCN5Op/axjQRyb+fGnXOhmboqQodYaWS7qhJWQJilH6ip0CBgRR\n' + 'zLoOAQQAw0zLIR7cmIS5lgu+/dxZThZebZHBH3RSiUZt9JP/cpMuHLs//13uLlzO\n' + '9kmkyNQ34ulCM+WbhU8cN25wF2r/kleEOHWaNIW+I1PGGkHwy+E7Eae7juoqsXfJ\n' + '5bIfSZwShOhZPwluRaDGWd/8hJt6avduFL9gGZTunWn4F3nMqjUAEQEAAf4JAwIM\n' + 'Rkr03Df/Z2BQOTPSVVkZoaZ2FC7fly+54YG9jWBCAwR6P8Os8Cp1BM8BG+E6jL3b\n' + 'X7djq70YwF9t1NMas2sXviGfAZEpZZnjQYfcl6EsvBciDspzYQKiSdndCehuoA4g\n' + 'QYJ0M9XzBtCaCJ7ti2azTNAYYtw0vWkvGfgzWxw6IbLttHRIWEdvBMul+u2NzPhy\n' + 'x8MpulrIyAER0SgaE0oJlHm8LfjV/qJd4Gpb9NG9QmdFrpPrIvDFh/mJC6CyqdVU\n' + 'ZfahmuzfFANMEZehsrFHZmpIAzfrv5BBppVV4/vVVuoR74ohcur36sqiSZPI4pkg\n' + 'LE7BR0A4PGdSRroZZFB4djV+6dIM0LKwqb+d50UUsJy7JIyIFHZAR70tEIfyyF0I\n' + '7ZzlmO9ebwy/XiJnxYuVKh3M1q97b7lGlVGD4hvi37jv+YYqLe4Rd4T9Ho+qM33T\n' + 'OfVHAfr6v5YhlnaMYfKC7407kWA9bRnItdjy/m5br05bncH7iJ8EGAECAAkFAlHM\n' + 'ug4CGwwACgkQBv+crAktqAhENwQAkMY/nds36KgzwfMPpxtBaq8GbrUqY1r8lBl6\n' + 'a/bi8qeOuEgQmIxM2OpVPtL04c1c1hLflPCi1SQUlCIh3DkEGQIcy0/wxUZdCvZK\n' + '0mF5nZSq6tez3CwqbeOA4nBOLwbxho50VqxBpR4qypYrB2ipykxlwiqudEe0sE2b\n' + '1KwNtVw=\n' + '=wHzz\n' + '-----END PGP PRIVATE KEY BLOCK-----'; var USER_ID = 'test 4'; var PUBLIC_KEY_ASCII = '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' + 'Version: GnuPG v1.4.11 (GNU/Linux)\n' + '\n' + 'mI0EUcy6DgEEAJb0T7gQlfKQWmR0dLUrueRMVy8UemcmxsdIH30/HqJvqO6xU0lK\n' + 'NaFtaVxBdenAMpEooi1EcTi/bOKfz36FY/FARTiXv1LXuLzFJdPyjTYjh7tw+uOP\n' + 'UlLJCTZikgrnM07txTUiVVEetOa+unyKn17EX0PlSpAbGZedyO0nGwXzABEBAAG0\n' + 'BnRlc3QgNIi4BBMBAgAiBQJRzLoOAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIX\n' + 'gAAKCRAG/5ysCS2oCL2SA/9EV9j3T/TM3VRD0NvNySHodcxCP1BF0zm/M84I/WHQ\n' + 'sGKmHStfCqqEGruB8E6NHQMJwNp1TzcswuxE0wiTJiXKe3w3+GZhPHdW5zcgiMKK\n' + 'YLn80Tk6fUMx1zVZtXlSBYCN5Op/axjQRyb+fGnXOhmboqQodYaWS7qhJWQJilH6\n' + 'iriNBFHMug4BBADDTMshHtyYhLmWC7793FlOFl5tkcEfdFKJRm30k/9yky4cuz//\n' + 'Xe4uXM72SaTI1Dfi6UIz5ZuFTxw3bnAXav+SV4Q4dZo0hb4jU8YaQfDL4TsRp7uO\n' + '6iqxd8nlsh9JnBKE6Fk/CW5FoMZZ3/yEm3pq924Uv2AZlO6dafgXecyqNQARAQAB\n' + 'iJ8EGAECAAkFAlHMug4CGwwACgkQBv+crAktqAhENwQAkMY/nds36KgzwfMPpxtB\n' + 'aq8GbrUqY1r8lBl6a/bi8qeOuEgQmIxM2OpVPtL04c1c1hLflPCi1SQUlCIh3DkE\n' + 'GQIcy0/wxUZdCvZK0mF5nZSq6tez3CwqbeOA4nBOLwbxho50VqxBpR4qypYrB2ip\n' + 'ykxlwiqudEe0sE2b1KwNtVw=\n' + '=nHBL\n' + '-----END PGP PUBLIC KEY BLOCK-----'; var USER_ID_2 = 'Drew Hintz <adhintz@google.com>'; var PUBLIC_KEY_ASCII_2 = // user ID of 'Drew Hintz <adhintz@google.com>' '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' + 'Charset: UTF-8\n' + '\n' + 'xv8AAABSBFP3bHYTCCqGSM49AwEHAgMECt6MVqa43Ab248CosK/cy664pkL/9XvC\n' + '0O2K0O1Jh2qau7ll3Q9vssdObSwX0EaiMm4Dvegxr1z+SblWSFV4x83/AAAAH0Ry\n' + 'ZXcgSGludHogPGFkaGludHpAZ29vZ2xlLmNvbT7C/wAAAGYEEBMIABj/AAAABYJT\n' + '92x2/wAAAAmQ8eznwfj7hkMAADA9AQCWE4jmpmA5XRN1tZduuz8QwtxGZOFurpAK\n' + '6RCzKDqS8wEAx9eBxXLhKB4xm9xwPdh0+W6rbsvf58FzKjlxrkUfuxTO/wAAAFYE\n' + 'U/dsdhIIKoZIzj0DAQcCAwQ0M6kFa7VaVmt2PRdOUdZWrHp6CZZglTVQi1eyiXB/\n' + 'nnUUbH+qrreWTD7W9RxRtr0IqAYssLG5ZoWsXa5jQC3DAwEIB8L/AAAAZgQYEwgA\n' + 'GP8AAAAFglP3bHf/AAAACZDx7OfB+PuGQwAAkO4BALMuXsta+bCOvzSn7InOs7wA\n' + '+OmDN5cv1cR/SsN5+FkLAQCmmBa/Fe76gmDd0RjvpQW7pWK2zXj3il6HYQ2NsWlI\n' + 'bQ==\n' + '=LlKd\n' + '-----END PGP PUBLIC KEY BLOCK-----'; var PUBLIC_KEY_ASCII_2_EVIL = // Evil Drew Hintz <adhintz@google.com.evil.com> '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' + 'Version: GnuPG v1.4.11 (GNU/Linux)\n' + '\n' + 'mI0EU7FngwEEALi4HSlK9DJuYUS7zEuJpi2RVdTE0zDQwyX7xLCERZLrPVWUHH0x\n' + 'XO9X7X6ngA2qNQVUirMsGK/OOwTwzN0ywmETmHJCjx7cPqruSxD+BsnceiHRWc7m\n' + 'FCJSP7Vl7BQUp16sbryT8dOpXmc+72ftxPahDJ0WWKSebXYVvvcJM8cLABEBAAG0\n' + 'MkxpbnVzIFRvcndhbGRzIDxMaW51cy5Ub3J3YWxkczFAY2FyYW1haWwuY29tLmV2\n' + 'aWw+iLgEEwECACIFAlOxZ4MCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ\n' + 'EMBeGa5IppzDSFoD/0KGrjnLynrzOD7ZZRCL6jcv/YXR0PCgmyko94njmozfupmp\n' + 'his/9Nw6EChGC1WigwmgOYXzy/fynnts1YlPSQQJpbDt1XIOkm0dmSKSI+/zNxGm\n' + 'BZqstDLEdUPLt7HZecz5iTbEh3NDpz8nhiHiiIq0rMN0f67+vFpsfLQLtvw7tDVM\n' + 'aW51cy5Ub3J3YWxkczFAY2FyYW1haWwuY29tLmV2aWwyIDxhbm90aGVyQGV2aWwu\n' + 'Y29tPoi4BBMBAgAiBQJTsWmqAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAK\n' + 'CRDAXhmuSKacw7C+A/988WuUl7PzBjIDiCEjffe/fC4gNP7viRRQhwvh8QSgNpXl\n' + '9TQ4PcKQRZvfNJk+OQvHMoPa+qXAB91GQg/nzYcFwKrsiy+wddAc/SbL0ClT5EEG\n' + 'hy2DzvuOHoTK51O+RwaHP08jciQIeLC0BRJEMsuxK86j9vlUEWAEP9uPEiUvobiN\n' + 'BFOxZ4MBBADDAzzpcIhOslSqULxjSdhQH0y8DK8GgbsCeIxf8iGIFNHEbOzUUZKV\n' + 'IITTBjQVZS/2enkE+UOpVZUp2SgJogEbxstjeE7NofWNqeDGye01dfGDOyjc1Se/\n' + 'WwHbxendlFpjZ8iHAjza4Bws2SsgCYYx0vfB8yruDnj9B299xXevLQARAQABiJ8E\n' + 'GAECAAkFAlOxZ4MCGwwACgkQwF4ZrkimnMMPnwP+J/cbZK5eR0v6Y9VI2uA6GW7T\n' + 'vILwfV3mUki9a5ag0XhL1xQWJSEBSLvNJac8/Cpc80yUpXvmvBhoefZSzzcR00pN\n' + 'RyfyHLU6nEU7LDvQlN3TPpuctRhrLEnn4pMhgvIxDRLKcR1JtZ9ikcYI9pC9ywx7\n' + 'YjNmsSc84KVYhDqIn6eZAaIEU7GElxEEAIbLqIgY+O3NLfNYp5da8c5hnPdMprOP\n' + '2dzL7d0ay6LsuaAcXSq4yaOa/WOAL64kFdX+I40sV21nQZ/gYB6OFT/qk3WtKepE\n' + 'L6lc9iZULbVL9H14UOFAetYrmO53YetFpJZVCnsVBw7GRhOLV31oXldouh2a2NjC\n' + 'r+5By/EaP2ADAKDxqlytOJwCJ+sWP0PGnjONb4zOdQP/X15UGQbmsDIm/iY3yPQe\n' + 'FJjqMX0dKUJxB5cpVhBg2R4JZLCuDiN+3xC7/bcyZzUlaU7axt1/KvwighAnZrBD\n' + 'Z6RbbPdCOf+KtSifQvNSrAOk8AhRrUN+sGc/fLSotsBPXcXYSR6bm/fzRKtcmV7U\n' + '95dkYanPy2rGG/HfB+opWrED/ic1Ib28DNReZ/xvbJicm2YDda8SyemX8g4/Qrir\n' + 'oqtXeOIyHyOeZQoFk+W5sIXy1t8lM8isYNctKdvuSPjaZbTD//bI2r2T1Sc/nwoy\n' + 'LupRcNH2oSfZ/4idPzCNdyHEDhzzNw1m8LQO1x5a2FJGJgaF8JCiNeNT8m65b/Uq\n' + 'myw7tC1FdmlsIERyZXcgSGludHogPGFkaGludHpAZ29vZ2xlLmNvbS5ldmlsLmNv\n' + 'bT6IYgQTEQIAIgUCU7GElwIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ\n' + 'qFdA2mzeclR1qwCg0a+61ZBPYdopFg8cwUjsDnFVvUAAoNun2cB7omK05P3URbVf\n' + 'HEWI4RSPuQENBFOxhJcQBAC/SptM2I3+1ktGrhVHTkSU0C7/hiKWqKKg4lrQe0VR\n' + 'GPi4SBc2stjS5HhBhDb+fBl3K+IiqDh8yCHxtXJeenrOutklMSfl89hDWLQefgrU\n' + 'zZ3VX3llAs4DDjxF7ppEAraHM6GpPm+oEXeOuThBAqOkstT53IehTspiqnoouKgu\n' + 'PwAECwQAmBGvx+TYOhEajpexobauc8yTACFwhYiwx7XK4+LGRenRJMY9/oGMb4/r\n' + 'L4DLA4kosrzvblbGFLOsj/MtN2HZZIjekVqEpLqNULX8WfwO4ku+ahRCT+qOQe5x\n' + '9dHXUgr+ZRFtAkhxdMIF6Yh3eH7aSYZYkbUUaxtRSPsNfDe1Xh2ISQQYEQIACQUC\n' + 'U7GElwIbDAAKCRCoV0DabN5yVIa4AKCwMqovxeUL8m2D7aWMZBLYG5Bb2wCfVpwq\n' + 'x4imzBK+e4+YnAiNVhYYEJY=\n' + '=lo5W\n' + '-----END PGP PUBLIC KEY BLOCK-----'; function testEncrypt() { var plaintext = 'plaintext message'; var encrypted = 'encrypted message'; var encryptCb = new goog.testing.mockmatchers.SaveArgument(goog.isFunction); stubs.setPath('e2e.ext.actions.EncryptSign.prototype.execute', mockControl.createFunctionMock('encryptSign')); e2e.ext.actions.EncryptSign.prototype.execute( goog.testing.mockmatchers.ignoreArgument, new goog.testing.mockmatchers.ArgumentMatcher(function(arg) { assertEquals(plaintext, arg.content); return true; }), goog.testing.mockmatchers.ignoreArgument, encryptCb, new goog.testing.mockmatchers.ArgumentMatcher(goog.isFunction)); stubs.replace(e2e.ext.utils.text, 'extractValidEmail', function(recipient) { if (recipient == USER_ID) { return recipient; } return null; }); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: plaintext, recipients: [USER_ID] }, constants.Actions.ENCRYPT_SIGN); goog.dom.getElement(constants.ElementId.SIGN_MESSAGE_CHECK).checked = true; var protectBtn = document.querySelector('button.action'); protectBtn.click(); asyncTestCase.waitForAsync('Waiting for message to be encrypted.'); window.setTimeout(function() { encryptCb.arg(encrypted); var textArea = document.querySelector('textarea'); assertEquals(encrypted, textArea.value); assertTrue(textArea.disabled); mockControl.$verifyAll(); asyncTestCase.continueTesting(); }, 100); } function testDecrypt() { var plaintext = 'plaintext message'; var encrypted = 'encrypted message'; var decryptCb = new goog.testing.mockmatchers.SaveArgument(goog.isFunction); stubs.setPath('e2e.ext.actions.DecryptVerify.prototype.execute', mockControl.createFunctionMock('decryptVerify')); e2e.ext.actions.DecryptVerify.prototype.execute( goog.testing.mockmatchers.ignoreArgument, new goog.testing.mockmatchers.ArgumentMatcher(function(arg) { assertEquals(encrypted, arg.content); return true; }), goog.testing.mockmatchers.ignoreArgument, decryptCb, new goog.testing.mockmatchers.ArgumentMatcher(goog.isFunction)); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: encrypted }, constants.Actions.DECRYPT_VERIFY); var decryptBtn = document.querySelector('button.action'); decryptBtn.click(); asyncTestCase.waitForAsync('Waiting for text to be decrypted.'); window.setTimeout(function() { decryptCb.arg(plaintext); assertEquals( '', goog.dom.getElement(constants.ElementId.ERROR_DIV).textContent); assertEquals(plaintext, document.querySelector('textarea').value); mockControl.$verifyAll(); asyncTestCase.continueTesting(); }, 100); } function testContentInsertedOnEncrypt() { var plaintext = 'irrelevant'; var origin = 'http://www.example.com'; var subject = 'encrypted message'; stubs.replace(e2e.ext.utils.text, 'extractValidEmail', function(recipient) { if (recipient == USER_ID) { return recipient; } return null; }); stubs.set(prompt.pgpLauncher_, 'updateSelectedContent', mockControl.createFunctionMock('updateSelectedContent')); var encryptedMsg = new goog.testing.mockmatchers.SaveArgument(goog.isString); var subjectMsg = new goog.testing.mockmatchers.SaveArgument(function(a) { return (!goog.isDef(a) || goog.isString(a)); }); prompt.pgpLauncher_.updateSelectedContent(encryptedMsg, [USER_ID], origin, false, goog.testing.mockmatchers.ignoreArgument, subjectMsg); mockControl.$replayAll(); populatePgpKeys(); asyncTestCase.waitForAsync('Waiting for keys to be populated.'); window.setTimeout(function() { prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: plaintext, recipients: [USER_ID], origin: origin, canInject: true, subject: subject }, constants.Actions.ENCRYPT_SIGN); var protectBtn = document.querySelector('button.action'); protectBtn.click(); asyncTestCase.waitForAsync('Waiting for message to be encrypted.'); window.setTimeout(function() { var insertBtn = document.querySelector('button.insert'); insertBtn.click(); assertContains('-----BEGIN PGP MESSAGE-----', encryptedMsg.arg); assertEquals(subject, subjectMsg.arg); mockControl.$verifyAll(); asyncTestCase.continueTesting(); }, 500); }, 500); } function testImportKey() { stubs.setPath('chrome.runtime.getBackgroundPage', function(callback) { callback({launcher: prompt.pgpLauncher_}); }); stubs.setPath('e2e.ext.actions.GetKeyDescription.prototype.execute', mockControl.createFunctionMock('execute')); var keyDescriptionArg = new goog.testing.mockmatchers.SaveArgument(goog.isFunction); e2e.ext.actions.GetKeyDescription.prototype.execute( goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, keyDescriptionArg, goog.testing.mockmatchers.ignoreArgument); stubs.replace(chrome.notifications, 'create', mockControl.createFunctionMock('create')); var notificationArg = new goog.testing.mockmatchers.SaveArgument(goog.isFunction); chrome.notifications.create( goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, notificationArg); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: PUBLIC_KEY_ASCII }, constants.Actions.IMPORT_KEY); var importBtn = document.querySelector('button.action'); importBtn.click(); keyDescriptionArg.arg(''); asyncTestCase.waitForAsync('waiting for keyring to be imported'); window.setTimeout(function() { notificationArg.arg(); mockControl.$verifyAll(); asyncTestCase.continueTesting(); }, 500); } function testDisplayFailure() { prompt.decorate(document.documentElement); var errorDiv = document.getElementById(constants.ElementId.ERROR_DIV); prompt.displayFailure_(new Error('test failure')); assertEquals('test failure', errorDiv.textContent); } function testSelectAction() { var processedContent = false; stubs.replace( e2e.ext.ui.Prompt.prototype, 'processSelectedContent_', function(blob, action) { assertEquals('Failed to select action', 'test_action', action); processedContent = true; }); prompt.selectAction_(null, { target: { getValue: function() { return 'test_action'} } }); assertTrue('Failed to process content', processedContent); } function testIfNoPassphrase() { prompt.pgpLauncher_ = new e2e.ext.Launcher(); stubs.replace(e2e.ext.Launcher.prototype, 'hasPassphrase', function() { return false; }); prompt.decorate(document.documentElement); prompt.processSelectedContent_( null, e2e.ext.constants.Actions.ENCRYPT_SIGN); assertContains('actionEnterPassphrase', document.body.textContent); } function testSetKeyringPassphrase() { var passphrase = 'test'; stubs.set(prompt.pgpLauncher_, 'start', mockControl.createFunctionMock('start')); prompt.pgpLauncher_.start(passphrase); stubs.set(prompt, 'close', mockControl.createFunctionMock('close')); prompt.close(); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_(null, constants.Actions.GET_PASSPHRASE); assertFalse(goog.dom.classlist.contains( goog.dom.getElement(e2e.ext.constants.ElementId.BODY), e2e.ext.constants.CssClass.TRANSPARENT)); var dialog = prompt.getChildAt(1); dialog.dialogCallback_(passphrase); mockControl.$verifyAll(); } function testSetKeyringPassphraseRedirect() { var passphrase = 'test'; stubs.set(prompt.pgpLauncher_, 'start', mockControl.createFunctionMock('start')); prompt.pgpLauncher_.start(passphrase); stubs.set(prompt, 'close', mockControl.createFunctionMock('close')); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ request: true, selection: 'irrelevant', recipients: [USER_ID], action: constants.Actions.ENCRYPT_SIGN }, constants.Actions.GET_PASSPHRASE); var dialog = prompt.getChildAt(1); dialog.dialogCallback_(passphrase); assertContains('promptEncryptSignActionLabel', document.body.textContent); mockControl.$verifyAll(); } function testSetKeyringPassphraseRedirectDefault() { var passphrase = 'test'; stubs.set(prompt.pgpLauncher_, 'start', mockControl.createFunctionMock('start')); prompt.pgpLauncher_.start(passphrase); stubs.set(prompt, 'close', mockControl.createFunctionMock('close')); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ action: constants.Actions.GET_PASSPHRASE }, constants.Actions.GET_PASSPHRASE); var dialog = prompt.getChildAt(1); dialog.dialogCallback_(passphrase); assertContains('promptEncryptSignTitle', document.body.textContent); mockControl.$verifyAll(); } function testSetKeyringPassphraseError() { var passphrase = 'test'; stubs.set(prompt.pgpLauncher_, 'start', mockControl.createFunctionMock('start')); prompt.pgpLauncher_.start(passphrase).$throws(new Error('irrlevant')); stubs.set(prompt, 'close', mockControl.createFunctionMock('close')); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_({ action: constants.Actions.GET_PASSPHRASE }, constants.Actions.GET_PASSPHRASE); var dialog = prompt.getChildAt(1); dialog.dialogCallback_(passphrase); assertEquals(3, prompt.getChildCount()); mockControl.$verifyAll(); } function testClose() { var closedWindow = false; stubs.replace(window, 'close', function() { closedWindow = true; }); prompt.decorate(document.body); prompt.close(); assertTrue(prompt.isDisposed()); assertTrue(closedWindow); goog.array.forEach( document.querySelectorAll('textarea,input'), function(elem) { assertEquals('', elem.value); }); } function testConfigureExtension() { stubs.setPath('chrome.tabs.create', mockControl.createFunctionMock()); chrome.tabs.create( new goog.testing.mockmatchers.ArgumentMatcher(function(arg) { assertEquals('settings.html', arg.url); assertFalse(arg.active); return true; }), goog.nullFunction); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_(null, constants.Actions.CONFIGURE_EXTENSION); mockControl.$verifyAll(); } function testNoOp() { stubs.set(prompt, 'close', mockControl.createFunctionMock()); prompt.close(); mockControl.$replayAll(); prompt.decorate(document.documentElement); prompt.processSelectedContent_(null, constants.Actions.NO_OP); mockControl.$verifyAll(); } function testShareKey() { var subject = 'irrelevant'; stubs.setPath('chrome.i18n.getMessage', function() { if (arguments[0] === 'shareKeySubject') { return subject; } else { return [].join.call(arguments); } }); prompt.processSelectedContent_(null, constants.Actions.SHARE_KEY); assertEquals(subject, goog.dom.getElement(constants.ElementId.SUBJECT_HOLDER).value); } function populatePgpKeys() { var ctx = prompt.pgpLauncher_.getContext(); ctx.importKey(function(uid, callback) { callback('test'); }, PRIVATE_KEY_ASCII); ctx.importKey(function() {}, PUBLIC_KEY_ASCII); }
{ "content_hash": "6411f466e1123d4c451bbd6383772d3b", "timestamp": "", "source": "github", "line_count": 675, "max_line_length": 80, "avg_line_length": 34.77185185185185, "alnum_prop": 0.7476886370414554, "repo_name": "diracdeltas/end-to-end-1", "id": "15e629367d860ecd008aa214ad4ad154d90f5930", "size": "24094", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/javascript/crypto/e2e/extension/ui/prompt/prompt_test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21102" }, { "name": "HTML", "bytes": "602624" }, { "name": "JavaScript", "bytes": "3082082" }, { "name": "Python", "bytes": "3136" }, { "name": "Shell", "bytes": "12925" } ], "symlink_target": "" }
module CloudFormer module EC2 class VPCEndpoint < Resource aws_property :policy_document, type: Hash aws_property :route_table_ids, type: String, list: true aws_property :service_name, type: String, required: true aws_property :vpc_id, type: String, required: true end end end
{ "content_hash": "79b9e2858234d1f08c4d2de15fc74fff", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 62, "avg_line_length": 28.545454545454547, "alnum_prop": 0.6878980891719745, "repo_name": "custora/cloud_former", "id": "3ce32d4ba1119ddb1cc09a6cc0f86784b40fe912", "size": "412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cloud_former/resources/ec2/vpc_endpoint.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "723" }, { "name": "Ruby", "bytes": "332207" } ], "symlink_target": "" }
Compute all the 4-pi (geodesy) normalized associated Legendre functions and first derivatives. # Usage call PlmBar_d1 (`p`, `dp`, `lmax`, `z`, `csphase`, `cnorm`, `exitstatus`) # Parameters `p` : output, real\*8, dimension ((`lmax`+1)\*(`lmax`+2)/2) : An array of 4-pi (geodesy) normalized associated Legendre functions up to degree `lmax`. The index corresponds to `l*(l+1)/2+m+1`, which can be calculated by a call to `PlmIndex`. `dp` : output, real\*8, dimension ((`lmax`+1)\*(`lmax`+2)/2) : An array of the first derivatives of the 4-pi (geodesy) normalized associated Legendre functions up to degree `lmax`. The index corresponds to `l*(l+1)/2+m+1`, which can be calculated by a call to `PlmIndex`. `lmax` : input, integer : The maximum degree of the associated Legendre functions to be computed. If `lmax` is -1, allocated memory will be deallocated. `z` : input, real\*8 : The argument of the associated Legendre functions. `csphase` : input, optional, integer, default = 1 : If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. `cnorm` : input, optional, integer, default = 0 : If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. `exitstatus` : output, optional, integer : If present, instead of executing a STOP when an error is encountered, the variable exitstatus will be returned describing the error. 0 = No errors; 1 = Improper dimensions of input array; 2 = Improper bounds for input variable; 3 = Error allocating memory; 4 = File IO error. # Description `PlmBar_d1` will calculate all of the 4-pi (geodesy) normalized associated Legendre functions and first derivatives up to degree `lmax` for a given argument. These are calculated using a standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. These functions are accurate to about degree 2800. The index of the array corresponding to a given degree `l` and angular order `m` corresponds to `l*(l+1)/2+m+1`, which can be computed by a call to `PlmIndex`. The integral of the squared Legendre functions over the interval [-1, 1] is `2*(2-delta(0,m))`, where delta is the Kronecker delta function. If the optional parameter `cnorm` is set equal to 1, the complex normalization will be used where the integral of the squared Legendre functions over the interval [-1, 1] is 2. The default is to exclude the Condon-Shortley phase, but this can be modified by setting the optional argument `csphase` to -1. Note that the derivative of the Legendre functions is calculated with respect to its arguement `z`, and not latitude or colatitude. If `z=cos(theta)`, where `theta` is the colatitude, then it is only necessary to multiply `dp` by `-sin(theta)` to obtain the derivative with respect to `theta`. This routine saves the three-term recursion factors and square roots of the integers the first time being called. If subsequent calls possess the same value of `lmax`, these will not be recomputed. If you wish to deallocate this memory, which is an array of length `(lmax+1)*(lmax+2)`, recall this routine with `lmax`=-1. # References Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279- 299, 2002. # See also [plbar](plbar.html), [plbar_d1](plbar_d1.html), [plmbar](plmbar.html), [plon](plon.html), [plon_d1](plon_d1.html), [plmon](plmon.html), [plmon_d1](plmon_d1.html), [plschmidt](plschmidt.html), [plschmidt_d1](plschmidt_d1.html), [plmschmidt](plmschmidt.html), [plmschmidt_d1](plmschmidt_d1.html), [plegendre](plegendre.html), [plegendre_d1](plegendre_d1.html), [plegendrea](plegendrea.html), [plegendrea_d1](plegendrea_d1.html), [plmindex](plmindex.html)
{ "content_hash": "9d43f4ee2aca309a195353fcf0f60173", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 739, "avg_line_length": 84.76595744680851, "alnum_prop": 0.7457329317269076, "repo_name": "MMesch/SHTOOLS", "id": "c96537fc4b6741d2e5b4ef200abdeb440221b278", "size": "3997", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/fdoc/plmbar_d1.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Fortran", "bytes": "1209672" }, { "name": "Makefile", "bytes": "26802" }, { "name": "Python", "bytes": "244699" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <!-- To enable XML intellisense, use package manager console command: Install-SolidEdgeAddInRibbonSchema This command adds\updates Ribbon.xsd in your project. https://github.com/SolidEdgeCommunity/SolidEdge.Community/wiki/Package-Manager-Console-Powershell-Reference#install-solidedgeaddinribbonschema --> <ribbon xmlns="http://github.com/SolidEdgeCommunity/SolidEdge/Ribbon"> <tab name="SolidEdgeCommunity"> <group name="Group1"> <!-- Note: imageId is defined in AssemblyInfo.[cs|vb] --> <button id="0" size="normal" label="Save" screentip="Save Screentip" supertip="Save Supertip" imageId="114" /> <button id="1" size="normal" label="Folder" screentip="Folder Screentip" supertip="Folder Supertip" imageId="106" /> <button id="2" size="normal" label="Monitor" screentip="Monitor Screentip" supertip="Monitor Supertip" imageId="109" /> <button id="3" size="large" label="Box" screentip="Box Screentip" supertip="Box Supertip" imageId="101" /> </group> <group name="Group2"> <button id="4" size="large" label="Camera" screentip="Camera Screentip" supertip="Camera Supertip" imageId="103" /> <button id="5" size="large" label="Photograph" screentip="Photograph Screentip" supertip="Photograph Supertip" imageId="111" enabled="false" /> <button id="6" size="large" label="Favorites" screentip="Favorites Screentip" supertip="Favorites Supertip" imageId="105" enabled="false" /> <button id="7" size="large" label="Printer" screentip="Printer Screentip" supertip="Printer Supertip" imageId="112" /> </group> <group name="Group3"> <button id="8" size="large" label="Tools" screentip="Tools Screentip" supertip="Tools Supertip" imageId="116" /> <button id="9" size="large" label="Command Prompt" screentip="CommandPrompt Screentip" supertip="CommandPrompt Supertip" imageId="104" macro="cmd.exe"/> <button id="10" size="large" label="Notepad" screentip="Notepad Screentip" supertip="Notepad Supertip" imageId="110" macro="notepad.exe"/> </group> <group name="Group4"> <button id="11" size="large" label="Help" screentip="Help Screentip" supertip="Help Supertip" imageId="108" /> <button id="12" size="large" label="Search" screentip="Search Screentip" supertip="Search Supertip" imageId="115" /> </group> <group name="Group5"> <button id="13" size="large" label="Question" screentip="Question Screentip" supertip="Question Supertip" imageId="113" /> </group> <group name="Group6"> <checkBox id="14" label="Checkbox1" screentip="Checkbox1 Screentip" supertip="Checkbox1 Supertip" /> <checkBox id="15" label="Checkbox2" screentip="Checkbox2 Screentip" supertip="Checkbox2 Supertip" /> <checkBox id="16" label="Checkbox3" screentip="Checkbox3 Screentip" supertip="Checkbox3 Supertip" /> <radioButton id="17" label="Radiobutton1" screentip="Radiobutton1 Screentip" supertip="Radiobutton1 Supertip" /> <radioButton id="18" label="Radiobutton2" screentip="Radiobutton2 Screentip" supertip="Radiobutton2 Supertip" /> <radioButton id="19" label="Radiobutton3" screentip="Radiobutton3 Screentip" supertip="Radiobutton3 Supertip" /> </group> </tab> </ribbon>
{ "content_hash": "9ab723be1e47001dc8b23dba016ef702", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 158, "avg_line_length": 75.95348837209302, "alnum_prop": 0.7088181261481935, "repo_name": "SolidEdgeCommunity/Samples", "id": "4a7767506c051ea8fc124e1751c760f1127f68e7", "size": "3268", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "AddIn/DemoAddIn/cs/DemoAddIn/Ribbon2d.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "929" }, { "name": "C", "bytes": "19081" }, { "name": "C#", "bytes": "935866" }, { "name": "C++", "bytes": "80242" }, { "name": "Makefile", "bytes": "420" }, { "name": "Objective-C", "bytes": "4246" }, { "name": "PowerShell", "bytes": "2316" }, { "name": "Visual Basic", "bytes": "1027183" } ], "symlink_target": "" }
package com.dailystudio.factory; import android.content.Context; import com.dailystudio.factory.Factory; import com.dailystudio.test.ActivityTestCase; public class ClassNameFactoryTest extends ActivityTestCase { static class TestObject extends Object { } static class TestContextObject extends TestObject { protected Context mContext; public TestContextObject(Context context) { mContext = context; } public Context getContext() { return mContext; } } @Override protected void setUp() throws Exception { super.setUp(); Factory.bindContext(mContext); } @Override protected void tearDown() throws Exception { super.tearDown(); Factory.unbindContext(mContext); } public void testParseClassName() { ClassNameFactory<TestObject> factory = new ClassNameFactory<TestObject>(); assertNotNull(factory); String klassName = null; assertNull(factory.parseClassName(null)); klassName = factory.parseClassName(".factory.ClassFactoryTest.TestObject"); assertEquals("com.dailystudio.test.factory.ClassFactoryTest.TestObject", klassName); klassName = factory.parseClassName("com.dailystudio.test.factory.ClassFactoryTest.TestObject"); assertEquals("com.dailystudio.test.factory.ClassFactoryTest.TestObject", klassName); } public void testNewObject() { ClassNameFactory<TestObject> factory = new ClassNameFactory<TestObject>(); assertNotNull(factory); TestObject object = null; object = factory.newObject( "com.dailystudio.factory.ClassNameFactoryTest$TestObject"); assertNotNull(object); assertTrue(object instanceof TestObject); object = factory.newObject( "com.dailystudio.factory.ClassNameFactoryTest$TestContextObject"); assertNotNull(object); assertTrue(object instanceof TestContextObject); assertEquals(mContext.getApplicationContext(), ((TestContextObject)object).getContext()); } }
{ "content_hash": "f76bd845b873650f543c2f6abe893060", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 97, "avg_line_length": 25.756756756756758, "alnum_prop": 0.7649527806925498, "repo_name": "dailystudio/devbricks", "id": "b279913f457672b28bb1bf929ccb7d1429785d13", "size": "1906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/androidTest/java/com/dailystudio/factory/ClassNameFactoryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1089574" }, { "name": "Shell", "bytes": "887" } ], "symlink_target": "" }
title: Simplifying Dev for the rest of the world date: 10/01/2021 published: true --- I've had a few instances where people have asked as to what I do and what my role means, and writing a post just for that one thing will short and useless so we're going to go around a few things that are common among the dev / engineers and I'll try to explain them for you in the simplest language that I can. I'll give you an overview of what I do and I'll get to the remaining details. As of writing this post I'm a Principal Developer at a startup called [Fountane](https://fountane.com/), I take care of deciding architechture, tech stack (No we don't have the same stack for every project), toolchains and process pipelines, automations, CI/CD that are then used by the devs to write/build apps based on the client requirements. ## Software and Software Engineers Now these are really common terms and most people understand the gist, I won't really go into the depth of everything that a software engineer does. **Software** : Packaged set of digital instructions that run on various platforms a.k.a , it's just an App, the platforms might vary from desktop(PC, Mac), embedded (Chipsets, Microwave, fridge, etc), mobile (Android, iOS) so on. I say `packaged` since it is a combination of a lot of instructions that are given to the underlying platform and sometimes on a layer that's talking to the underlying platform. **Software Engineers** : These are the amazing humans that take the responsibility of writing these instructions and often also work on ways to find optimal ways to make those set of instructions make the best use of the hardware. Software Engineers can be divided into a lot of roles based on a lot of variables, the most common one that you can find almost always is the classification based on the platform the engineer works for. So examples would be - Embedded Systems Software Engineer - iOS Developer - Android Developer - Web Developer - IOT Developer (Sometimes, comes in Embedded development) After this, there's another variable that makes these role a little more specific, where people start adding details of what they really want. A general start or add-on to the above would be the language that the person works with. For Example the iOS Developer and Android Developer can be split into - iOS Swift Developer - iOS ObjectiveC Developer - Android Java Devloper - Android Kotlin Developer A lot of times the same person might have both languages in his/her skillset but these are specified by the hiring company when the codebase already exists and they are looking for a language specific role, the actual engineer on the other hand might just mention "iOS Developer" in his resume/profile. ### Languages As I pointed out language in the previous point. I'll explain what languages are. These are basically how the instructions are written for the software to be created. Developers specialise in these languages and take pride in it. Technical term for this is `Programming Languages` and Python, Javascript, GoLang, Rust, C, C++, Objective C, Fortran, LISP, Crystal, D lang, are all a few examples, there's over 300 (maybe more) such programming languages (and still none were built specifically for Desktop UI development...) Going further we can classify some of these into even smaller parts where we start adding which side of the work do they do, a general classification would be whether the developer works on "Business Logic" or BLOC , or on User Interface or UI. A **BLOC** developer works on Server Sided Code, Shared Logical code between various systems and similar things. These are the guys who work and use the algorithms a lot, also called the backend/back-office developer A **UI Developer** is works on making sure what the user sees is functional and in certain cases uses the shared code developed by the BLOC Dev into the interface to make sure the app follows the requirement generally called the UI Developer or in certain cases Frontend Developer. In a very ideal case these 2 should be enough to handle or get an App out in the market (this can vary a lot based on a lot of things) Oh, and examples of these will be of the fashion - Platform - BLOC(Backend/Back-office) | UI(Frontend) - Framework / Language - Web Developer - Frontend - React / Javascript - Web Developer - Frontend - Angular / Javascript - Web Developer - Frontend - Vue / Javascript - Web Developer - Backend - Express / Node - Web Developer - Backend - Buffalo / Golang - iOS Developer - Frontend - SwiftUI / Swift - iOS Developer - Frontend Now obviously there's people who enjoy doing both BLOC and UI and these people are called Full Stack Developers, though a full stack developer is never limited to just those 2 things. More often than not he/she is to have knowledge of how the architecture of the app works and how he can improve it. While today a Full Stack Dev is limited to a single language and people are proud of that , I remember mentioning in the previous post, don't limit your skillset! , so if I were to be a full stack dev I'd be learning every language there is and work on projects handling both frontend and backend and understanding architecture for dev. Since we're done with the classification part, let's get to the general roles that are assigned to someone in a company. - Junior Dev / The Trainee - Senior Dev / The Guide - Lead Dev / The Mentor - Principal Dev / The Overlord - CTO / The Elder The name beside the role are just something that I've come up with, I'll try explaining why and what they are. #### Junior Dev This guy is here to learn, you can have junior devs who've been in the industry for over 10 years and prefer having mentors and keep learning (a very good thing to do!) but yeah, these are the trainee, they keeps learning ,These people like having a mentor on top of them almost always, they enjoy the part where they keep learning new things and growing. A developer should always keep this mentality no matter what role they actually get in a company. I've made quite a few attempts to stay at this role but i don't know , get pushed up always.... #### Senior Dev This guy has made enough fuck ups in his dev life to understand what and where to look for solutions and can guide you on how to approach a problem, again these can be people who just started development and also people that have been doing it for 10+ years, there's no limit to good you get at a skill, it's different for everyone. ### Lead Dev This person's role is to make sure the other two are able to find resources, docs around well enough and acts as the person who gets rid of the road blocks. His/her work is to manage your work, review your work and 90% of the time acts as an indirect quality check engineer and the person both junior and senior go to when trying to understand the architectural decisions that were made and how the code should/could be structured to perform better , 8/10 this is where the Full Stack Developer ends up being after he's learned how to handle both people and code fuck ups. ### Principal Dev He/she are there to be with the development from start to finish, they take care of architecture, development toolchain, dev processes, automations, programming standard / principles and overlooks and plans stuff. An interested Developer grows towards this mentality everyday without even knowing but at this point you are the person who researches a lot more than he implements, unless you are in a startup then you might have more than one role anyway but this guy has plans for plans that act as backup for the backup of a backup while being a backup. Tagged him as _The Overlord_ , because he's just that, plan everything, has people acting on those plans and doesn't get into the field unless it's absolutely necessary. I'm no where close to a Good Principal Dev yet but we're getting there. ### CTO - Chief Technology Officer The Elder, aka _the know it all_ , That's all I'm going to put here, there's nothing more you can talk about the CTO. This is one huge post.... I've probably missed a few specifications in terms of roles and thus it's not to be considered a hard limit on what you can/cannot do and a passionate developer can never be limited to a single role anyway. You can be a junior working towards becoming a senior, you can be a junior who has moments where you help out a principal developer make decisions, it's always possible, not everyone knows everything, even if I just said that the CTO is supposed to be the know it all. That's it for now, Adios!
{ "content_hash": "c923ddedf6ff0fec70e55e8bade034bb", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 572, "avg_line_length": 65.11278195488721, "alnum_prop": 0.7748267898383372, "repo_name": "alienblogger/alienblogger.github.io", "id": "45a3159d3ed29f910a8d6fa75e012d9e49916688", "size": "8664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "posts/10012021-dev-in-simple-terms.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1772" }, { "name": "HTML", "bytes": "2450" }, { "name": "JavaScript", "bytes": "568" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "27f0f837153491470adc90891813e9ed", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "77e0a92316cc05a86ec209e3427ae976d2a4341f", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Pyrrosia/Cyclophorus giesenhagenii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.jetbrains.python; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.jetbrains.python.psi.PyElementType; public class PyTokenTypes { private PyTokenTypes() { } public static final PyElementType IDENTIFIER = new PyElementType("IDENTIFIER"); public static final PyElementType LINE_BREAK = new PyElementType("LINE_BREAK"); public static final PyElementType STATEMENT_BREAK = new PyElementType("STATEMENT_BREAK"); public static final PyElementType SPACE = new PyElementType("SPACE"); public static final PyElementType TAB = new PyElementType("TAB"); public static final PyElementType FORMFEED = new PyElementType("FORMFEED"); public static final IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER; public static final PyElementType INCONSISTENT_DEDENT = new PyElementType("INCONSISTENT_DEDENT"); public static final PyElementType END_OF_LINE_COMMENT = new PyElementType("END_OF_LINE_COMMENT"); public static final PyElementType AND_KEYWORD = new PyElementType("AND_KEYWORD"); public static final PyElementType AS_KEYWORD = new PyElementType("AS_KEYWORD"); public static final PyElementType ASSERT_KEYWORD = new PyElementType("ASSERT_KEYWORD"); public static final PyElementType BREAK_KEYWORD = new PyElementType("BREAK_KEYWORD"); public static final PyElementType CLASS_KEYWORD = new PyElementType("CLASS_KEYWORD"); public static final PyElementType CONTINUE_KEYWORD = new PyElementType("CONTINUE_KEYWORD"); public static final PyElementType DEF_KEYWORD = new PyElementType("DEF_KEYWORD"); public static final PyElementType DEL_KEYWORD = new PyElementType("DEL_KEYWORD"); public static final PyElementType ELIF_KEYWORD = new PyElementType("ELIF_KEYWORD"); public static final PyElementType ELSE_KEYWORD = new PyElementType("ELSE_KEYWORD"); public static final PyElementType EXCEPT_KEYWORD = new PyElementType("EXCEPT_KEYWORD"); public static final PyElementType EXEC_KEYWORD = new PyElementType("EXEC_KEYWORD"); public static final PyElementType FINALLY_KEYWORD = new PyElementType("FINALLY_KEYWORD"); public static final PyElementType FOR_KEYWORD = new PyElementType("FOR_KEYWORD"); public static final PyElementType FROM_KEYWORD = new PyElementType("FROM_KEYWORD"); public static final PyElementType GLOBAL_KEYWORD = new PyElementType("GLOBAL_KEYWORD"); public static final PyElementType IF_KEYWORD = new PyElementType("IF_KEYWORD"); public static final PyElementType IMPORT_KEYWORD = new PyElementType("IMPORT_KEYWORD"); public static final PyElementType IN_KEYWORD = new PyElementType("IN_KEYWORD", "__contains__"); public static final PyElementType IS_KEYWORD = new PyElementType("IS_KEYWORD"); public static final PyElementType LAMBDA_KEYWORD = new PyElementType("LAMBDA_KEYWORD"); public static final PyElementType NOT_KEYWORD = new PyElementType("NOT_KEYWORD"); public static final PyElementType OR_KEYWORD = new PyElementType("OR_KEYWORD"); public static final PyElementType PASS_KEYWORD = new PyElementType("PASS_KEYWORD"); public static final PyElementType PRINT_KEYWORD = new PyElementType("PRINT_KEYWORD"); public static final PyElementType RAISE_KEYWORD = new PyElementType("RAISE_KEYWORD"); public static final PyElementType RETURN_KEYWORD = new PyElementType("RETURN_KEYWORD"); public static final PyElementType TRY_KEYWORD = new PyElementType("TRY_KEYWORD"); public static final PyElementType WITH_KEYWORD = new PyElementType("WITH_KEYWORD"); public static final PyElementType WHILE_KEYWORD = new PyElementType("WHILE_KEYWORD"); public static final PyElementType YIELD_KEYWORD = new PyElementType("YIELD_KEYWORD"); // new keywords in Python 3 public static final PyElementType NONE_KEYWORD = new PyElementType("NONE_KEYWORD"); public static final PyElementType TRUE_KEYWORD = new PyElementType("TRUE_KEYWORD"); public static final PyElementType FALSE_KEYWORD = new PyElementType("FALSE_KEYWORD"); public static final PyElementType NONLOCAL_KEYWORD = new PyElementType("NONLOCAL_KEYWORD"); public static final PyElementType DEBUG_KEYWORD = new PyElementType("DEBUG_KEYWORD"); public static final PyElementType ASYNC_KEYWORD = new PyElementType("ASYNC_KEYWORD"); public static final PyElementType AWAIT_KEYWORD = new PyElementType("AWAIT_KEYWORD", "__await__"); public static final PyElementType INTEGER_LITERAL = new PyElementType("INTEGER_LITERAL"); public static final PyElementType FLOAT_LITERAL = new PyElementType("FLOAT_LITERAL"); public static final PyElementType IMAGINARY_LITERAL = new PyElementType("IMAGINARY_LITERAL"); public static final PyElementType SINGLE_QUOTED_STRING = new PyElementType("SINGLE_QUOTED_STRING"); public static final PyElementType TRIPLE_QUOTED_STRING = new PyElementType("TRIPLE_QUOTED_STRING"); public static final PyElementType SINGLE_QUOTED_UNICODE = new PyElementType("SINGLE_QUOTED_UNICODE"); public static final PyElementType TRIPLE_QUOTED_UNICODE = new PyElementType("TRIPLE_QUOTED_UNICODE"); public static final PyElementType DOCSTRING = new PyElementType("DOCSTRING"); public static final TokenSet UNICODE_NODES = TokenSet.create(TRIPLE_QUOTED_UNICODE, SINGLE_QUOTED_UNICODE); public static final TokenSet TRIPLE_NODES = TokenSet.create(TRIPLE_QUOTED_UNICODE, TRIPLE_QUOTED_STRING); public static final TokenSet STRING_NODES = TokenSet.orSet(UNICODE_NODES, TokenSet.create(SINGLE_QUOTED_STRING, TRIPLE_QUOTED_STRING, DOCSTRING)); // Operators public static final PyElementType PLUS = new PyElementType("PLUS", "__add__");// + public static final PyElementType MINUS = new PyElementType("MINUS", "__sub__");// - public static final PyElementType MULT = new PyElementType("MULT", "__mul__");// * public static final PyElementType EXP = new PyElementType("EXP", "__pow__");// ** public static final PyElementType DIV = new PyElementType("DIV", "__div__"); // / public static final PyElementType FLOORDIV = new PyElementType("FLOORDIV", "__floordiv__"); // // public static final PyElementType PERC = new PyElementType("PERC", "__mod__");// % public static final PyElementType LTLT = new PyElementType("LTLT", "__lshift__");// << public static final PyElementType GTGT = new PyElementType("GTGT", "__rshift__");// >> public static final PyElementType AND = new PyElementType("AND", "__and__");// & public static final PyElementType OR = new PyElementType("OR", "__or__");// | public static final PyElementType XOR = new PyElementType("XOR", "__xor__");// ^ public static final PyElementType TILDE = new PyElementType("TILDE", "__invert__");// ~ public static final PyElementType LT = new PyElementType("LT", "__lt__");// < public static final PyElementType GT = new PyElementType("GT", "__gt__");// > public static final PyElementType LE = new PyElementType("LE", "__le__");// <= public static final PyElementType GE = new PyElementType("GE", "__ge__");// >= public static final PyElementType EQEQ = new PyElementType("EQEQ", "__eq__");// == public static final PyElementType NE = new PyElementType("NE", "__ne__");// != public static final PyElementType NE_OLD = new PyElementType("NE_OLD", "__ne__");// <> // Delimiters public static final PyElementType LPAR = new PyElementType("LPAR");// ( public static final PyElementType RPAR = new PyElementType("RPAR");// ) public static final PyElementType LBRACKET = new PyElementType("LBRACKET");// [ public static final PyElementType RBRACKET = new PyElementType("RBRACKET");// ] public static final PyElementType LBRACE = new PyElementType("LBRACE");// { public static final PyElementType RBRACE = new PyElementType("RBRACE");// } public static final PyElementType AT = new PyElementType("AT", "__matmul__");// @ public static final PyElementType COMMA = new PyElementType("COMMA");// , public static final PyElementType COLON = new PyElementType("COLON");// : public static final PyElementType DOT = new PyElementType("DOT");// . public static final PyElementType TICK = new PyElementType("TICK");// ` public static final PyElementType EQ = new PyElementType("EQ");// = public static final PyElementType SEMICOLON = new PyElementType("SEMICOLON");// ; public static final PyElementType PLUSEQ = new PyElementType("PLUSEQ");// += public static final PyElementType MINUSEQ = new PyElementType("MINUSEQ");// -= public static final PyElementType MULTEQ = new PyElementType("MULTEQ");// *= public static final PyElementType ATEQ = new PyElementType("ATEQ"); // @= public static final PyElementType DIVEQ = new PyElementType("DIVEQ"); // /= public static final PyElementType FLOORDIVEQ = new PyElementType("FLOORDIVEQ"); // //= public static final PyElementType PERCEQ = new PyElementType("PERCEQ");// %= public static final PyElementType ANDEQ = new PyElementType("ANDEQ");// &= public static final PyElementType OREQ = new PyElementType("OREQ");// |= public static final PyElementType XOREQ = new PyElementType("XOREQ");// ^= public static final PyElementType LTLTEQ = new PyElementType("LTLTEQ");// <<= public static final PyElementType GTGTEQ = new PyElementType("GTGTEQ");// >>= public static final PyElementType EXPEQ = new PyElementType("EXPEQ");// **= public static final PyElementType RARROW = new PyElementType("RARROW");// -> public static final TokenSet OPERATIONS = TokenSet.create( PLUS, MINUS, MULT, AT, EXP, DIV, FLOORDIV, PERC, LTLT, GTGT, AND, OR, XOR, TILDE, LT, GT, LE, GE, EQEQ, NE, NE_OLD, AT, COLON, TICK, EQ, PLUSEQ, MINUSEQ, MULTEQ, ATEQ, DIVEQ, FLOORDIVEQ, PERCEQ, ANDEQ, OREQ, XOREQ, LTLTEQ, GTGTEQ, EXPEQ); public static final TokenSet COMPARISON_OPERATIONS = TokenSet.create( LT, GT, EQEQ, GE, LE, NE, NE_OLD, IN_KEYWORD, IS_KEYWORD, NOT_KEYWORD); public static final TokenSet SHIFT_OPERATIONS = TokenSet.create(LTLT, GTGT); public static final TokenSet ADDITIVE_OPERATIONS = TokenSet.create(PLUS, MINUS); public static final TokenSet MULTIPLICATIVE_OPERATIONS = TokenSet.create(MULT, AT, FLOORDIV, DIV, PERC); public static final TokenSet STAR_OPERATORS = TokenSet.create(MULT, EXP); public static final TokenSet UNARY_OPERATIONS = TokenSet.create(PLUS, MINUS, TILDE); public static final TokenSet BITWISE_OPERATIONS = TokenSet.create(AND, OR, XOR); public static final TokenSet EQUALITY_OPERATIONS = TokenSet.create(EQEQ, NE, NE_OLD); public static final TokenSet RELATIONAL_OPERATIONS = TokenSet.create(LT, GT, LE, GE); public static final TokenSet END_OF_STATEMENT = TokenSet.create(STATEMENT_BREAK, SEMICOLON); public static final TokenSet WHITESPACE = TokenSet.create(SPACE, TAB, FORMFEED); public static final TokenSet WHITESPACE_OR_LINEBREAK = TokenSet.create(SPACE, TAB, FORMFEED, LINE_BREAK); public static final TokenSet OPEN_BRACES = TokenSet.create(LBRACKET, LBRACE, LPAR); public static final TokenSet CLOSE_BRACES = TokenSet.create(RBRACKET, RBRACE, RPAR); public static final TokenSet NUMERIC_LITERALS = TokenSet.create(FLOAT_LITERAL, INTEGER_LITERAL, IMAGINARY_LITERAL); public static final TokenSet BOOL_LITERALS = TokenSet.create(TRUE_KEYWORD, FALSE_KEYWORD); public static final TokenSet SCALAR_LITERALS = TokenSet.orSet(BOOL_LITERALS, NUMERIC_LITERALS, TokenSet.create(NONE_KEYWORD)); public static final TokenSet EXPRESSION_KEYWORDS = TokenSet.create(TRUE_KEYWORD, FALSE_KEYWORD, NONE_KEYWORD); public static final TokenSet AUG_ASSIGN_OPERATIONS = TokenSet.create(PLUSEQ, MINUSEQ, MULTEQ, ATEQ, DIVEQ, PERCEQ, EXPEQ, GTGTEQ, LTLTEQ, ANDEQ, OREQ, XOREQ, FLOORDIVEQ); public static final PyElementType BACKSLASH = new PyElementType("BACKSLASH"); public static final PyElementType INDENT = new PyElementType("INDENT"); public static final PyElementType DEDENT = new PyElementType("DEDENT"); }
{ "content_hash": "eafb341847d6f9a2490241a3ee4a795a", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 128, "avg_line_length": 71.35928143712574, "alnum_prop": 0.750776202064278, "repo_name": "ThiagoGarciaAlves/intellij-community", "id": "63b80160a75ba5e2a2349873cbabb0cb8f3cc1c2", "size": "12517", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "python/psi-api/src/com/jetbrains/python/PyTokenTypes.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "63518" }, { "name": "C", "bytes": "214180" }, { "name": "C#", "bytes": "1538" }, { "name": "C++", "bytes": "190028" }, { "name": "CSS", "bytes": "111474" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "2194261" }, { "name": "HTML", "bytes": "1726130" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "148273590" }, { "name": "JavaScript", "bytes": "125292" }, { "name": "Kotlin", "bytes": "454154" }, { "name": "Lex", "bytes": "166177" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "85969" }, { "name": "Objective-C", "bytes": "28634" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6570" }, { "name": "Python", "bytes": "21460459" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "63190" }, { "name": "Smalltalk", "bytes": "64" }, { "name": "TeX", "bytes": "60798" }, { "name": "TypeScript", "bytes": "6152" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
package com.hsjawanda.gaeobjectify.tests; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.common.base.Optional; import com.hsjawanda.gaeobjectify.util.KeyValueUriInfo; import com.hsjawanda.gaeobjectify.util.PositionalUriInfo; import com.hsjawanda.gaeobjectify.util.PositionalUriParser; import com.hsjawanda.gaeobjectify.util.UriParser; /** * @author Harshdeep S Jawanda (hsjawanda@gmail.com) * */ public class UriParserTests { UriParser actionParser = UriParser.instance("/", true); @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testParseNullUri() { KeyValueUriInfo info = this.actionParser.parse((String) null, false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); } @Test public void testParseEmptyUri() { KeyValueUriInfo info = this.actionParser.parse(EMPTY, false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); } @Test public void testParseEmptyAction() { KeyValueUriInfo info = this.actionParser.parse("", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertEquals(EMPTY, info.action); } @Test public void testParseWithTrailingSlash() { KeyValueUriInfo info = this.actionParser.parse("/action/", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertEquals("action", info.action); } @Test public void testParseWithoutTrailingSlash() { KeyValueUriInfo info = this.actionParser.parse("/action", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertEquals("action", info.action); } @Test public void testParseMixedCaseAction() { KeyValueUriInfo info = this.actionParser.parse("/ACTion", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertEquals("ACTion", info.action); } @Test public void testParseMixedCaseOneKeyValue() { KeyValueUriInfo info = this.actionParser.parse("/ACTion/Key1/ValuE1", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertTrue(info.containsParam("key1")); assertEquals("ValuE1", info.getParam("key1").orNull()); } @Test public void testParseMixedCaseTwoKeyValue() { KeyValueUriInfo info = this.actionParser.parse("/ACTion/Key1/ValuE1/kEY2/VALUE2", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertTrue(info.containsParam("key1")); assertTrue(info.containsParam("key2")); assertFalse(info.containsParam(null)); assertEquals("VALUE2", info.getParam("key2").orNull()); } @Test public void testParseMissingLastValue() { KeyValueUriInfo info = this.actionParser.parse("/ACTion/Key1/ValuE1/kEY2", false); assertNotNull("The KeyValueUriInfo object was unexpectedly null.", info); assertTrue(info.containsParam("key1")); assertTrue(info.containsParam("key2")); assertEquals(EMPTY, info.getParam("key2").orNull()); } @Test public void testParsePositionalUri() { PositionalUriParser positionalParser = PositionalUriParser .instance("/photos/{profile}/{photoId}"); Optional<PositionalUriInfo> info = positionalParser.parse("/photos/hsjawanda/lfauouekllfl", false); assertTrue(info.isPresent()); assertEquals("hsjawanda", info.get().getParam("profile").get()); assertEquals("lfauouekllfl", info.get().getParam("photoId").get()); } @Test public void testParsePositionalUriFixedPartsOnly() { PositionalUriParser positionalParser = PositionalUriParser .instance("/photos/user/{profile}/{photoId}"); Optional<PositionalUriInfo> info = positionalParser.parse("/photos/user/", true); assertTrue(info.isPresent()); assertNull(info.get().getParam("profile").orNull()); assertNull(info.get().getParam("photoId").orNull()); } @Test public void testParsePositionalUriMismatch() { PositionalUriParser positionalParser = PositionalUriParser .instance("/photos/{profile}/{photoId}"); Optional<PositionalUriInfo> info = positionalParser.parse("/photosa/hsjawanda/lfauouekllfl", false); assertFalse(info.isPresent()); } }
{ "content_hash": "3e73f2aca8380c25c55cf5e12de9cdfe", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 94, "avg_line_length": 33.27407407407407, "alnum_prop": 0.7593499554764025, "repo_name": "hsjawanda/gae-objectify-utils", "id": "df0c8eb8a349c3691c3bf9aaf102e4fbb205ef66", "size": "4492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/hsjawanda/gaeobjectify/tests/UriParserTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2199988" } ], "symlink_target": "" }
package org.apache.http.HC4.protocol; import java.io.IOException; import org.apache.http.HC4.HttpException; import org.apache.http.HC4.HttpResponse; import org.apache.http.HC4.HttpResponseInterceptor; import org.apache.http.HC4.annotation.Immutable; import org.apache.http.HC4.util.Args; import org.apache.http.HC4.protocol.HTTP; import org.apache.http.HC4.protocol.HttpContext; /** * ResponseServer is responsible for adding {@code Server} header. This * interceptor is recommended for server side protocol processors. * * @since 4.0 */ @Immutable public class ResponseServer implements HttpResponseInterceptor { private final String originServer; /** * @since 4.3 */ public ResponseServer(final String originServer) { super(); this.originServer = originServer; } public ResponseServer() { this(null); } @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP response"); if (!response.containsHeader(HTTP.SERVER_HEADER)) { if (this.originServer != null) { response.addHeader(HTTP.SERVER_HEADER, this.originServer); } } } }
{ "content_hash": "874356a37b023e08afe027799e304ba8", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 79, "avg_line_length": 26.142857142857142, "alnum_prop": 0.6908665105386417, "repo_name": "garymabin/YGOMobile", "id": "f29577bdb85dec92cba610a38aa3e4256e48ad60", "size": "2464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apache-async-http-HC4/src/org/apache/http/HC4/protocol/ResponseServer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "404947" }, { "name": "Awk", "bytes": "38419" }, { "name": "Batchfile", "bytes": "6024" }, { "name": "C", "bytes": "28105829" }, { "name": "C++", "bytes": "9794211" }, { "name": "CMake", "bytes": "21541" }, { "name": "CSS", "bytes": "1746" }, { "name": "DIGITAL Command Language", "bytes": "124189" }, { "name": "GLSL", "bytes": "3574" }, { "name": "Groff", "bytes": "381234" }, { "name": "HTML", "bytes": "32922" }, { "name": "Java", "bytes": "4675551" }, { "name": "Lua", "bytes": "7905" }, { "name": "M4", "bytes": "71797" }, { "name": "Makefile", "bytes": "418307" }, { "name": "Module Management System", "bytes": "15805" }, { "name": "Objective-C", "bytes": "11724" }, { "name": "Objective-C++", "bytes": "85956" }, { "name": "Perl", "bytes": "912548" }, { "name": "Python", "bytes": "76605" }, { "name": "SAS", "bytes": "14183" }, { "name": "Shell", "bytes": "379187" }, { "name": "Smalltalk", "bytes": "1252" }, { "name": "XS", "bytes": "4319" }, { "name": "XSLT", "bytes": "12288" }, { "name": "eC", "bytes": "3710" } ], "symlink_target": "" }
package org.optaplanner.examples.nurserostering.app; import org.optaplanner.examples.common.app.CommonBenchmarkApp; public class NurseRosteringBenchmarkApp extends CommonBenchmarkApp { public static final String SPRINT_BENCHMARK_CONFIG = "/org/optaplanner/examples/nurserostering/benchmark/nurseRosteringSprintBenchmarkConfig.xml"; public static final String MEDIUM_BENCHMARK_CONFIG = "/org/optaplanner/examples/nurserostering/benchmark/nurseRosteringMediumBenchmarkConfig.xml"; public static final String LONG_BENCHMARK_CONFIG = "/org/optaplanner/examples/nurserostering/benchmark/nurseRosteringLongBenchmarkConfig.xml"; public static final String STEP_LIMIT_BENCHMARK_CONFIG = "/org/optaplanner/examples/nurserostering/benchmark/nurseRosteringStepLimitBenchmarkConfig.xml"; public static void main(String[] args) { String benchmarkConfig; if (args.length > 0) { if (args[0].equals("sprint")) { benchmarkConfig = SPRINT_BENCHMARK_CONFIG; } else if (args[0].equals("medium")) { benchmarkConfig = MEDIUM_BENCHMARK_CONFIG; } else if (args[0].equals("long")) { benchmarkConfig = LONG_BENCHMARK_CONFIG; } else if (args[0].equals("stepLimit")) { benchmarkConfig = STEP_LIMIT_BENCHMARK_CONFIG; } else { throw new IllegalArgumentException("The program argument (" + args[0] + ") is not supported."); } } else { benchmarkConfig = MEDIUM_BENCHMARK_CONFIG; } new NurseRosteringBenchmarkApp().buildAndBenchmark(benchmarkConfig); } }
{ "content_hash": "4d5474dfa9f33a6c8924368ed8f40d10", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 111, "avg_line_length": 44.86842105263158, "alnum_prop": 0.6715542521994134, "repo_name": "kiereleaseuser/optaplanner", "id": "a7a1151fe6c419d25014789e098f1577c6ed3b57", "size": "2298", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/app/NurseRosteringBenchmarkApp.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* $OpenBSD: enc.c,v 1.3 2014/10/22 13:54:03 jsing Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include <openssl/bio.h> #include <openssl/comp.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/pem.h> #include <openssl/x509.h> int set_hex(char *in, unsigned char *out, int size); #define SIZE (512) #define BSIZE (8*1024) static struct { int base64; char *bufsize; const EVP_CIPHER *cipher; int debug; #ifdef ZLIB int do_zlib; #endif int enc; #ifndef OPENSSL_NO_ENGINE char *engine; #endif char *hiv; char *hkey; char *hsalt; char *inf; char *keyfile; char *keystr; char *md; int nopad; int nosalt; int olb64; char *outf; char *passarg; int printkey; int verbose; } enc_config; static int enc_opt_cipher(int argc, char **argv, int *argsused) { char *name = argv[0]; if (*name++ != '-') return (1); if (strcmp(name, "none") == 0) { enc_config.cipher = NULL; *argsused = 1; return (0); } if ((enc_config.cipher = EVP_get_cipherbyname(name)) != NULL) { *argsused = 1; return (0); } return (1); } static struct option enc_options[] = { { .name = "A", .desc = "Process base64 data on one line (requires -a)", .type = OPTION_FLAG, .opt.flag = &enc_config.olb64, }, { .name = "a", .desc = "Perform base64 encoding/decoding (alias -base64)", .type = OPTION_FLAG, .opt.flag = &enc_config.base64, }, { .name = "base64", .type = OPTION_FLAG, .opt.flag = &enc_config.base64, }, { .name = "bufsize", .argname = "size", .desc = "Specify the buffer size to use for I/O", .type = OPTION_ARG, .opt.arg = &enc_config.bufsize, }, { .name = "d", .desc = "Decrypt the input data", .type = OPTION_VALUE, .opt.value = &enc_config.enc, .value = 0, }, { .name = "debug", .desc = "Print debugging information", .type = OPTION_FLAG, .opt.flag = &enc_config.debug, }, { .name = "e", .desc = "Encrypt the input data (default)", .type = OPTION_VALUE, .opt.value = &enc_config.enc, .value = 1, }, #ifndef OPENSSL_NO_ENGINE { .name = "engine", .argname = "id", .desc = "Use the engine specified by the given identifier", .type = OPTION_ARG, .opt.arg = &enc_config.engine, }, #endif { .name = "in", .argname = "file", .desc = "Input file to read from (default stdin)", .type = OPTION_ARG, .opt.arg = &enc_config.inf, }, { .name = "iv", .argname = "IV", .desc = "IV to use, specified as a hexidecimal string", .type = OPTION_ARG, .opt.arg = &enc_config.hiv, }, { .name = "K", .argname = "key", .desc = "Key to use, specified as a hexidecimal string", .type = OPTION_ARG, .opt.arg = &enc_config.hkey, }, { .name = "k", /* Superseded by -pass. */ .type = OPTION_ARG, .opt.arg = &enc_config.keystr, }, { .name = "kfile", /* Superseded by -pass. */ .type = OPTION_ARG, .opt.arg = &enc_config.keyfile, }, { .name = "md", .argname = "digest", .desc = "Digest to use to create a key from the passphrase", .type = OPTION_ARG, .opt.arg = &enc_config.md, }, { .name = "none", .desc = "Use NULL cipher (no encryption or decryption)", .type = OPTION_ARGV_FUNC, .opt.argvfunc = enc_opt_cipher, }, { .name = "nopad", .desc = "Disable standard block padding", .type = OPTION_FLAG, .opt.flag = &enc_config.nopad, }, { .name = "nosalt", .type = OPTION_VALUE, .opt.value = &enc_config.nosalt, .value = 1, }, { .name = "out", .argname = "file", .desc = "Output file to write to (default stdout)", .type = OPTION_ARG, .opt.arg = &enc_config.outf, }, { .name = "P", .desc = "Print out the salt, key and IV used, then exit\n" " (no encryption or decryption is performed)", .type = OPTION_VALUE, .opt.value = &enc_config.printkey, .value = 2, }, { .name = "p", .desc = "Print out the salt, key and IV used", .type = OPTION_VALUE, .opt.value = &enc_config.printkey, .value = 1, }, { .name = "pass", .argname = "source", .desc = "Password source", .type = OPTION_ARG, .opt.arg = &enc_config.passarg, }, { .name = "S", .argname = "salt", .desc = "Salt to use, specified as a hexidecimal string", .type = OPTION_ARG, .opt.arg = &enc_config.hsalt, }, { .name = "salt", .desc = "Use a salt in the key derivation routines (default)", .type = OPTION_VALUE, .opt.value = &enc_config.nosalt, .value = 0, }, { .name = "v", .desc = "Verbose", .type = OPTION_FLAG, .opt.flag = &enc_config.verbose, }, #ifdef ZLIB { .name = "z", .desc = "Perform zlib compression/decompression", .type = OPTION_FLAG, .opt.flag = &enc_config.do_zlib, }, #endif { .name = NULL, .type = OPTION_ARGV_FUNC, .opt.argvfunc = enc_opt_cipher, }, { NULL }, }; static void show_ciphers(const OBJ_NAME *name, void *arg) { static int n; if (!islower((unsigned char)*name->name)) return; fprintf(stderr, " -%-24s%s", name->name, (++n % 3 ? "" : "\n")); } static void enc_usage(void) { fprintf(stderr, "usage: enc -ciphername [-AadePp] [-base64] " "[-bufsize number] [-debug]\n" " [-engine id] [-in file] [-iv IV] [-K key] [-k password]\n" " [-kfile file] [-md digest] [-none] [-nopad] [-nosalt]\n" " [-out file] [-pass arg] [-S salt] [-salt]\n\n"); options_usage(enc_options); fprintf(stderr, "\n"); fprintf(stderr, "Valid ciphername values:\n\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, NULL); fprintf(stderr, "\n"); } int enc_main(int, char **); int enc_main(int argc, char **argv) { static const char magic[] = "Salted__"; char mbuf[sizeof magic - 1]; char *strbuf = NULL, *pass = NULL; unsigned char *buff = NULL; int bsize = BSIZE; int ret = 1, inl; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; #ifdef ZLIB BIO *bzl = NULL; #endif EVP_CIPHER_CTX *ctx = NULL; const EVP_MD *dgst = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL; BIO *rbio = NULL, *wbio = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; int i; memset(&enc_config, 0, sizeof(enc_config)); enc_config.enc = 1; /* first check the program name */ program_name(argv[0], pname, sizeof(pname)); if (strcmp(pname, "base64") == 0) enc_config.base64 = 1; #ifdef ZLIB if (strcmp(pname, "zlib") == 0) enc_config.do_zlib = 1; #endif enc_config.cipher = EVP_get_cipherbyname(pname); #ifdef ZLIB if (!enc_config.do_zlib && !enc_config.base64 && enc_config.cipher == NULL && strcmp(pname, "enc") != 0) #else if (!enc_config.base64 && enc_config.cipher == NULL && strcmp(pname, "enc") != 0) #endif { BIO_printf(bio_err, "%s is an unknown cipher\n", pname); goto end; } if (options_parse(argc, argv, enc_options, NULL, NULL) != 0) { enc_usage(); goto end; } if (enc_config.keyfile != NULL) { static char buf[128]; FILE *infile; infile = fopen(enc_config.keyfile, "r"); if (infile == NULL) { BIO_printf(bio_err, "unable to read key from '%s'\n", enc_config.keyfile); goto end; } buf[0] = '\0'; if (!fgets(buf, sizeof buf, infile)) { BIO_printf(bio_err, "unable to read key from '%s'\n", enc_config.keyfile); fclose(infile); goto end; } fclose(infile); i = strlen(buf); if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if (i < 1) { BIO_printf(bio_err, "zero length password\n"); goto end; } enc_config.keystr = buf; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, enc_config.engine, 0); #endif if (enc_config.md != NULL && (dgst = EVP_get_digestbyname(enc_config.md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", enc_config.md); goto end; } if (dgst == NULL) { dgst = EVP_md5(); /* XXX */ } if (enc_config.bufsize != NULL) { char *p = enc_config.bufsize; unsigned long n; /* XXX - provide an OPTION_ARG_DISKUNIT. */ for (n = 0; *p != '\0'; p++) { i = *p; if ((i <= '9') && (i >= '0')) n = n * 10 + i - '0'; else if (i == 'k') { n *= 1024; p++; break; } } if (*p != '\0') { BIO_printf(bio_err, "invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line. */ if (enc_config.base64 && n < 80) n = 80; bsize = (int)n; if (enc_config.verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); } strbuf = malloc(SIZE); buff = malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err, "malloc failure %ld\n", (long) EVP_ENCODE_LENGTH(bsize)); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (enc_config.debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *) bio_err); BIO_set_callback_arg(out, (char *) bio_err); } if (enc_config.inf == NULL) { if (enc_config.bufsize != NULL) setvbuf(stdin, (char *) NULL, _IONBF, 0); BIO_set_fp(in, stdin, BIO_NOCLOSE); } else { if (BIO_read_filename(in, enc_config.inf) <= 0) { perror(enc_config.inf); goto end; } } if (!enc_config.keystr && enc_config.passarg) { if (!app_passwd(bio_err, enc_config.passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } enc_config.keystr = pass; } if (enc_config.keystr == NULL && enc_config.cipher != NULL && enc_config.hkey == NULL) { for (;;) { char buf[200]; int retval; retval = snprintf(buf, sizeof buf, "enter %s %s password:", OBJ_nid2ln(EVP_CIPHER_nid(enc_config.cipher)), enc_config.enc ? "encryption" : "decryption"); if ((size_t)retval >= sizeof buf) { BIO_printf(bio_err, "Password prompt too long\n"); goto end; } strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc_config.enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } enc_config.keystr = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } if (enc_config.outf == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); if (enc_config.bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); } else { if (BIO_write_filename(out, enc_config.outf) <= 0) { perror(enc_config.outf); goto end; } } rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (enc_config.base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (enc_config.debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *) bio_err); } if (enc_config.olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc_config.enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (enc_config.cipher != NULL) { /* * Note that keystr is NULL if a key was passed on the command * line, so we get no salt in that case. Is this a bug? */ if (enc_config.keystr != NULL) { /* * Salt handling: if encrypting generate a salt and * write to output BIO. If decrypting read salt from * input BIO. */ unsigned char *sptr; if (enc_config.nosalt) sptr = NULL; else { if (enc_config.enc) { if (enc_config.hsalt) { if (!set_hex(enc_config.hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else arc4random_buf(salt, sizeof(salt)); /* * If -P option then don't bother * writing */ if ((enc_config.printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *) salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *) salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(enc_config.cipher, dgst, sptr, (unsigned char *)enc_config.keystr, strlen(enc_config.keystr), 1, key, iv); /* * zero the complete buffer or the string passed from * the command line bug picked up by Larry J. Hughes * Jr. <hughes@indiana.edu> */ if (enc_config.keystr == strbuf) OPENSSL_cleanse(enc_config.keystr, SIZE); else OPENSSL_cleanse(enc_config.keystr, strlen(enc_config.keystr)); } if (enc_config.hiv != NULL && !set_hex(enc_config.hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } if (enc_config.hiv == NULL && enc_config.keystr == NULL && EVP_CIPHER_iv_length(enc_config.cipher) != 0) { /* * No IV was explicitly set and no IV was generated * during EVP_BytesToKey. Hence the IV is undefined, * making correct decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if (enc_config.hkey != NULL && !set_hex(enc_config.hkey, key, sizeof key)) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption * context rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (!EVP_CipherInit_ex(ctx, enc_config.cipher, NULL, NULL, NULL, enc_config.enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(enc_config.cipher)); ERR_print_errors(bio_err); goto end; } if (enc_config.nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc_config.enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(enc_config.cipher)); ERR_print_errors(bio_err); goto end; } if (enc_config.debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *) bio_err); } if (enc_config.printkey) { if (!enc_config.nosalt) { printf("salt="); for (i = 0; i < (int) sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (enc_config.cipher->key_len > 0) { printf("key="); for (i = 0; i < enc_config.cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (enc_config.cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < enc_config.cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (enc_config.printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *) buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *) buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (enc_config.verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); free(strbuf); free(buff); BIO_free(in); if (out != NULL) BIO_free_all(out); BIO_free(benc); BIO_free(b64); #ifdef ZLIB BIO_free(bzl); #endif free(pass); return (ret); } int set_hex(char *in, unsigned char *out, int size) { int i, n; unsigned char j; n = strlen(in); if (n > (size * 2)) { BIO_printf(bio_err, "hex string is too long\n"); return (0); } memset(out, 0, size); for (i = 0; i < n; i++) { j = (unsigned char) *in; *(in++) = '\0'; if (j == 0) break; if ((j >= '0') && (j <= '9')) j -= '0'; else if ((j >= 'A') && (j <= 'F')) j = j - 'A' + 10; else if ((j >= 'a') && (j <= 'f')) j = j - 'a' + 10; else { BIO_printf(bio_err, "non-hex digit\n"); return (0); } if (i & 1) out[i / 2] |= j; else out[i / 2] = (j << 4); } return (1); }
{ "content_hash": "aaf3e1dc0b9fe436af93e77b2de41b98", "timestamp": "", "source": "github", "line_count": 781, "max_line_length": 80, "avg_line_length": 25.29449423815621, "alnum_prop": 0.6061756517337383, "repo_name": "GaloisInc/hacrypto", "id": "ec3c663d4da11c4a6a874c48973ed2a414ca2dfe", "size": "19755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/C/libressl/libressl-2.1.6/apps/enc.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "62991" }, { "name": "Ada", "bytes": "443" }, { "name": "AppleScript", "bytes": "4518" }, { "name": "Assembly", "bytes": "25398957" }, { "name": "Awk", "bytes": "36188" }, { "name": "Batchfile", "bytes": "530568" }, { "name": "C", "bytes": "344517599" }, { "name": "C#", "bytes": "7553169" }, { "name": "C++", "bytes": "36635617" }, { "name": "CMake", "bytes": "213895" }, { "name": "CSS", "bytes": "139462" }, { "name": "Coq", "bytes": "320964" }, { "name": "Cuda", "bytes": "103316" }, { "name": "DIGITAL Command Language", "bytes": "1545539" }, { "name": "DTrace", "bytes": "33228" }, { "name": "Emacs Lisp", "bytes": "22827" }, { "name": "GDB", "bytes": "93449" }, { "name": "Gnuplot", "bytes": "7195" }, { "name": "Go", "bytes": "393057" }, { "name": "HTML", "bytes": "41466430" }, { "name": "Hack", "bytes": "22842" }, { "name": "Haskell", "bytes": "64053" }, { "name": "IDL", "bytes": "3205" }, { "name": "Java", "bytes": "49060925" }, { "name": "JavaScript", "bytes": "3476841" }, { "name": "Jolie", "bytes": "412" }, { "name": "Lex", "bytes": "26290" }, { "name": "Logos", "bytes": "108920" }, { "name": "Lua", "bytes": "427" }, { "name": "M4", "bytes": "2508986" }, { "name": "Makefile", "bytes": "29393197" }, { "name": "Mathematica", "bytes": "48978" }, { "name": "Mercury", "bytes": "2053" }, { "name": "Module Management System", "bytes": "1313" }, { "name": "NSIS", "bytes": "19051" }, { "name": "OCaml", "bytes": "981255" }, { "name": "Objective-C", "bytes": "4099236" }, { "name": "Objective-C++", "bytes": "243505" }, { "name": "PHP", "bytes": "22677635" }, { "name": "Pascal", "bytes": "99565" }, { "name": "Perl", "bytes": "35079773" }, { "name": "Prolog", "bytes": "350124" }, { "name": "Python", "bytes": "1242241" }, { "name": "Rebol", "bytes": "106436" }, { "name": "Roff", "bytes": "16457446" }, { "name": "Ruby", "bytes": "49694" }, { "name": "Scheme", "bytes": "138999" }, { "name": "Shell", "bytes": "10192290" }, { "name": "Smalltalk", "bytes": "22630" }, { "name": "Smarty", "bytes": "51246" }, { "name": "SourcePawn", "bytes": "542790" }, { "name": "SystemVerilog", "bytes": "95379" }, { "name": "Tcl", "bytes": "35696" }, { "name": "TeX", "bytes": "2351627" }, { "name": "Verilog", "bytes": "91541" }, { "name": "Visual Basic", "bytes": "88541" }, { "name": "XS", "bytes": "38300" }, { "name": "Yacc", "bytes": "132970" }, { "name": "eC", "bytes": "33673" }, { "name": "q", "bytes": "145272" }, { "name": "sed", "bytes": "1196" } ], "symlink_target": "" }
**Notable Changes** - Support typescript 2.x
{ "content_hash": "a9b835bc10d96018d35bb518ea3f7e55", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 24, "avg_line_length": 15.333333333333334, "alnum_prop": 0.717391304347826, "repo_name": "agentframework/agentframework", "id": "474c0a2c230894664b6a27c3b115a9d87601db32", "size": "119", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "doc/changelogs/CHANGELOG_0.4.x.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "TypeScript", "bytes": "564590" } ], "symlink_target": "" }
package com.intellij.codeInsight.completion; import com.intellij.codeWithMe.ClientId; import com.intellij.lang.LanguageExtension; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class NextPrevParameterHandler extends EditorWriteActionHandler.ForEachCaret { private static final LanguageExtension<TemplateParameterTraversalPolicy> EP = new LanguageExtension<>("com.intellij.templateParameterTraversalPolicy"); protected final EditorActionHandler originalHandler; protected final boolean next; public NextPrevParameterHandler(EditorActionHandler originalHandler, boolean next) { this.originalHandler = originalHandler; this.next = next; } public static boolean hasSuitablePolicy(Editor editor, PsiFile file) { return findSuitableTraversalPolicy(editor, file) != null; } public static boolean isEnabledForContext(DataContext context, Boolean next) { Editor editor = CommonDataKeys.EDITOR.getData(context); if (editor == null) return false; return handleTab(editor, context, false, next); } public static boolean hasSuitablePolicy(PsiFile file) { return findPolicyForFile(file) != null; } @Nullable static TemplateParameterTraversalPolicy findSuitableTraversalPolicy(Editor editor, PsiFile file) { TemplateParameterTraversalPolicy policy = findPolicyForFile(file); return policy != null && policy.isValidForFile(editor, file) ? policy : null; } private static TemplateParameterTraversalPolicy findPolicyForFile(PsiFile file) { return EP.forLanguage(file.getLanguage()); } @Override public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { if (originalHandler == null) return false; return originalHandler.isEnabled(editor, caret, dataContext); } @Override public void executeWriteAction(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { if (!handleTab(editor, dataContext, true, next)) { originalHandler.execute(editor, caret, dataContext); } } private static boolean handleTab(@NotNull Editor editor, DataContext dataContext, boolean invoke, boolean next) { if (editor.getCaretModel().getCaretCount() > 1) return false; KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager != null && ClientId.isCurrentlyUnderLocalId()) { Shortcut @NotNull [] shortcuts = keymapManager.getActiveKeymap().getShortcuts(next ? "NextTemplateParameter" : "PrevTemplateParameter"); if (shortcuts.length > 0) { return false; } } Project project = dataContext.getData(CommonDataKeys.PROJECT); PsiFile psiFile = dataContext.getData(CommonDataKeys.PSI_FILE); if (project == null || psiFile == null) return false; TemplateParameterTraversalPolicy policy = findSuitableTraversalPolicy(editor, psiFile); if (policy != null) { if (invoke) { policy.invoke(editor, psiFile, next); } return true; } else { return false; } } } class NextParameterHandler extends NextPrevParameterHandler { NextParameterHandler(EditorActionHandler originalHandler) { super(originalHandler, true); } } class PrevParameterHandler extends NextPrevParameterHandler { PrevParameterHandler(EditorActionHandler originalHandler) { super(originalHandler, false); } }
{ "content_hash": "2f6fc60f29d6c3e316c794b0fa97cb2a", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 123, "avg_line_length": 36.907407407407405, "alnum_prop": 0.7541394882087306, "repo_name": "Maccimo/intellij-community", "id": "a699a5de0e436bdf49d761ab15a029808a57eca3", "size": "4145", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "platform/lang-api/src/com/intellij/codeInsight/completion/NextPrevParameterHandler.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import argparse import json import os import re import urllib.request _REPO_URL = 'https://repo.maven.apache.org/maven2' _GROUP_NAME = 'io/grpc' _MODULE_NAME = 'grpc-core' _FILE_EXT = 'jar' _OVERRIDE_LATEST = None _PATCH_VERSION = 'cr1' def do_latest(): if _OVERRIDE_LATEST is not None: print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') return maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( _REPO_URL, _GROUP_NAME, _MODULE_NAME) metadata = urllib.request.urlopen(maven_metadata_url).read().decode( 'utf-8') # Do not parse xml with the python included parser since it is susceptible # to maliciously crafted xmls. Only use regular expression parsing to be # safe. RE should be enough to handle what we need to extract. match = re.search('<latest>([^<]+)</latest>', metadata) if match: latest = match.group(1) else: # if no latest info was found just hope the versions are sorted and the # last one is the latest (as is commonly the case). latest = re.findall('<version>([^<]+)</version>', metadata)[-1] print(latest + f'.{_PATCH_VERSION}') def get_download_url(version): # Remove the patch version when getting the download url version_no_patch, patch = version.rsplit('.', 1) if patch.startswith('cr'): version = version_no_patch file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, _MODULE_NAME, version, _FILE_EXT) file_name = file_url.rsplit('/', 1)[-1] partial_manifest = { 'url': [file_url], 'name': [file_name], 'ext': '.' + _FILE_EXT, } print(json.dumps(partial_manifest)) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers() latest = sub.add_parser('latest') latest.set_defaults(func=lambda _opts: do_latest()) download = sub.add_parser('get_url') download.set_defaults( func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) opts = ap.parse_args() opts.func(opts) if __name__ == '__main__': main()
{ "content_hash": "036263d1b02d446af0d86c44705143e7", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 79, "avg_line_length": 31.285714285714285, "alnum_prop": 0.5917808219178082, "repo_name": "chromium/chromium", "id": "132cdd2b52bc56ef6598638b8d00f47236b49620", "size": "2457", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "third_party/android_deps/libs/io_grpc_grpc_core/3pp/fetch.py", "mode": "33261", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>How do I reset a tool?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="" name="description"> <meta content="refresh" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">How do I reset a tool?</h1> </div> <div id="article-description"> <p>Resetting a tool returns you to the starting point of the tool you're using, as if you had entered the tool in a new session.</p> </div> <div id="steps-container"> <div id="step-13270" class="step-container"> <h2 class="step-title">Click on the tool name.</h2> <div class="step-image-container step-image-fullsize"> <img src="/library/image/help/en/How-do-I-reset-a-tool-/Click-on-the-tool-name-sm.png" width="640" height="373" class="step-image" alt="Click on the tool name."><div class="step-image-caption"> <a href="/library/image/help/en/How-do-I-reset-a-tool-/Click-on-the-tool-name.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"> <p>When you're using a tool, clicking on the tool's name in either the Tool Menu or the Breadcrumbs, takes you back to the first page of that tool and resets the tool. </p> <p><em>Note: If you return to the starting point of the tool before saving (e.g., before choosing to add, post, save as draft, etc.), you will lose any information you have entered.</em></p> </div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
{ "content_hash": "f91839949d7a1d4185b01e6ee0fb6123", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 274, "avg_line_length": 59.111111111111114, "alnum_prop": 0.6466165413533834, "repo_name": "frasese/sakai", "id": "6d970565a6660cb26697053f9305588e37ed5a88", "size": "2660", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "help/help/src/sakai_screensteps_courseandProjectSitesUserGuide/How-do-I-reset-a-tool-.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "59098" }, { "name": "Batchfile", "bytes": "5172" }, { "name": "CSS", "bytes": "2078969" }, { "name": "ColdFusion", "bytes": "146057" }, { "name": "HTML", "bytes": "6036923" }, { "name": "Java", "bytes": "47615196" }, { "name": "JavaScript", "bytes": "8931735" }, { "name": "Lasso", "bytes": "26436" }, { "name": "PHP", "bytes": "606568" }, { "name": "PLSQL", "bytes": "2325610" }, { "name": "Perl", "bytes": "61738" }, { "name": "Python", "bytes": "44698" }, { "name": "Ruby", "bytes": "1276" }, { "name": "Shell", "bytes": "19259" }, { "name": "SourcePawn", "bytes": "2247" }, { "name": "XSLT", "bytes": "280557" } ], "symlink_target": "" }
/** * @author Bart van Vliet - bart@dobots.nl */ var NAVIGATION2D = NAVIGATION2D || { REVISION : '1' }; /** * @author Bart van Vliet - bart@dobots.nl */ /** * Send and draw a goal pose * * @constructor * @param options - object with following keys: * * ros - the ROSLIB.Ros connection handle * * rootObject (optional) - the root object to render to * * actionTopic (optional) - the action server topic to use for navigation, like '/move_base' * * actionMsgType (optional) - the navigation action message type, like 'move_base_msgs/MoveBaseAction' * * mapFrame (optional) - the frame of the map to use when sending a goal, like '/map' */ NAVIGATION2D.NavGoal = function(options) { var that = this; options = options || {}; var ros = options.ros; this.rootObject = options.rootObject || new createjs.Container(); var actionTopic = options.actionTopic || '/move_base'; var actionMsgType = options.actionMsgType || 'move_base_msgs/MoveBaseAction'; this.mapFrame = options.mapFrame || '/map'; // setup the actionlib client this.actionClient = new ROSLIB.ActionClient({ ros : ros, actionName : actionMsgType, serverName : actionTopic }); // get a handle to the stage if (this.rootObject instanceof createjs.Stage) { this.stage = this.rootObject; } else { this.stage = this.rootObject.getStage(); } this.container = new createjs.Container(); this.rootObject.addChild(this.container); // marker for goal orientation this.goalOrientationMarker = new ROS2D.ArrowShape({ size : 30, strokeSize : 1, fillColor : createjs.Graphics.getRGB(0, 255, 0, 0.66), pulse : false }); this.goalOrientationMarker.visible = false; this.container.addChild(this.goalOrientationMarker); // Used to set the goal marker this.goalStartPos = null; this.initScaleSet = false; }; /** * Initialize scale, current scale will be used for the goal markers */ NAVIGATION2D.NavGoal.prototype.initScale = function() { if (this.initScaleSet) { console.log('Warning: scale has already been initialized!'); // TODO: reinit } this.initScaleSet = true; this.initScaleX = 1.0 / this.stage.scaleX; this.initScaleY = 1.0 / this.stage.scaleY; }; /** * Start goal selection, given position will be the goal position, draw the orientation marker * * @param pos - current selection position on the map in meters (ROSLIB.Vector3) */ NAVIGATION2D.NavGoal.prototype.startGoalSelection = function(pos) { this.goalStartPos = pos; this.goalOrientationMarker.visible = true; this.goalOrientationMarker.scaleX = 1.0 / this.stage.scaleX; this.goalOrientationMarker.scaleY = 1.0 / this.stage.scaleY; this.goalOrientationMarker.x = pos.x; this.goalOrientationMarker.y = -pos.y; }; /** * Orient goal, after starting the goal, this function updates the orientation of the goal orientation marker * * @param pos - current selection position on the map in meters (ROSLIB.Vector3) */ NAVIGATION2D.NavGoal.prototype.orientGoalSelection = function(pos) { this.goalOrientationMarker.scaleX = 1.0 / this.stage.scaleX; this.goalOrientationMarker.scaleY = 1.0 / this.stage.scaleY; var dx = pos.x - this.goalStartPos.x; var dy = pos.y - this.goalStartPos.y; this.goalOrientationMarker.rotation = -Math.atan2(dy, dx) * 180.0 / Math.PI; }; /** * End of selecting a goal, removes the orientation marker * * @param pos - current selection position on the map in meters (ROSLIB.Vector3) * * @returns the goal pose (ROSLIB.Pose) */ NAVIGATION2D.NavGoal.prototype.endGoalSelection = function() { this.goalOrientationMarker.visible = false; // Get angle from orientation marker, so that the goal always matches with the marker // convert to radians and counter clock wise var theta = -this.goalOrientationMarker.rotation * Math.PI / 180.0; var qz = Math.sin(theta/2.0); var qw = Math.cos(theta/2.0); var quat = new ROSLIB.Quaternion({ x : 0, y : 0, z : qz, w : qw }); return new ROSLIB.Pose({ position : this.goalStartPos, orientation : quat }); }; /** * Send a goal to the navigation stack with the given pose. * Draw the goal * * @param pose - the goal pose (ROSLIB.Pose) */ NAVIGATION2D.NavGoal.prototype.sendGoal = function(pose) { // create a goal var goal = new ROSLIB.Goal({ actionClient : this.actionClient, goalMessage : { target_pose : { header : { frame_id : this.mapFrame }, pose : pose } } }); goal.send(); // create a marker for the goal var goalMarker = new ROS2D.ArrowShape({ size : 10, strokeSize : 1, fillColor : createjs.Graphics.getRGB(255, 64, 128, 0.66), pulse : true }); goalMarker.x = pose.position.x; goalMarker.y = -pose.position.y; goalMarker.rotation = this.stage.rosQuaternionToGlobalTheta(pose.orientation); goalMarker.scaleX = this.initScaleX; goalMarker.scaleY = this.initScaleY; this.container.addChild(goalMarker); var that = this; goal.on('result', function() { that.container.removeChild(goalMarker); }); }; /** * @author Bart van Vliet - bart@dobots.nl */ /** * Listens for path msgs and draws the path * * @constructor * @param options - object with following keys: * * ros - the ROSLIB.Ros connection handle * * rootObject (optional) - the root object to render to * * pathTopic (optional) - the path topic to subscribe to, like '/plan', must be of type: 'nav_msgs/Path' * * color (optional) - color of the marker * * size (optional) - size of the marker */ NAVIGATION2D.NavPath = function(options) { var that = this; options = options || {}; var ros = options.ros; this.rootObject = options.rootObject || new createjs.Container(); var pathTopic = options.pathTopic || '/plan'; var color = options.color || createjs.Graphics.getRGB(0, 255, 0, 1); var size = options.size || 1; // get a handle to the stage if (this.rootObject instanceof createjs.Stage) { this.stage = this.rootObject; } else { this.stage = this.rootObject.getStage(); } // shape for the path this.path = new ROS2D.PathShape({ strokeSize : size, strokeColor : color }); this.path.visible = false; this.rootObject.addChild(this.path); this.initScaleSet = false; // Set up a listener for the planned path var pathListener = new ROSLIB.Topic({ ros : ros, name : pathTopic, messageType : 'nav_msgs/Path', throttle_rate : 100 }); pathListener.subscribe(this.updatePath.bind(this)); }; /** * Initialize scale, current scale will be used for the goal markers */ NAVIGATION2D.NavPath.prototype.initScale = function() { if (this.initScaleSet) { console.log('Warning: scale has already been initialized!'); // TODO: reinit } this.initScaleSet = true; this.path.scaleX = 1.0 / this.stage.scaleX; this.path.scaleY = 1.0 / this.stage.scaleY; }; /** * Update the robot's path drawing * * @param path - the path (nav_msgs/Path) */ NAVIGATION2D.NavPath.prototype.updatePath = function(path) { if (this.initScaleSet) { this.path.visible = true; } this.path.setPath(path); }; /** * @author Bart van Vliet - bart@dobots.nl */ /** * Listens for pose msgs and draws the robot pose and a trace * * @constructor * @param options - object with following keys: * * ros - the ROSLIB.Ros connection handle * * rootObject (optional) - the root object to render to * * poseTopic (optional) - the pose topic to subscribe to, like '/robot_pose', must be of type: 'geometry_msgs/Pose' * * withTrace (optional) - whether to draw the robot's trace (default: true) * * maxTraceLength (optional) - maximum length of the trace in number of poses (0 for infinite) * * traceColor (optional) - color of the trace shape * * traceSize (optional) - size of the trace shape * * robotColor (optional) - color of the robot shape * * robotSize (optional) - size of the robot shape * * robotShape (optional) - shape of your robot, front should point to the east at 0 rotation */ NAVIGATION2D.PoseAndTrace = function(options) { var that = this; options = options || {}; var ros = options.ros; this.rootObject = options.rootObject || new createjs.Container(); var poseTopic = options.poseTopic || '/robot_pose'; this.withTrace = options.withTrace || true; this.maxTraceLength = options.maxTraceLength || 100; var traceColor = options.traceColor || createjs.Graphics.getRGB(0, 150, 0, 0.66); var traceSize = options.traceSize || 1.5; var robotColor = options.robotColor || createjs.Graphics.getRGB(255, 0, 0, 0.66); var robotSize = options.robotSize || 15; this.robotMarker = options.robotShape || null; // get a handle to the stage if (this.rootObject instanceof createjs.Stage) { this.stage = this.rootObject; } else { this.stage = this.rootObject.getStage(); } // shape for the trace this.trace = new ROS2D.TraceShape({ strokeSize : traceSize, strokeColor : traceColor, maxPoses : this.maxTraceLength }); this.trace.visible = false; this.rootObject.addChild(this.trace); // marker for the robot if (!this.robotMarker) { this.robotMarker = new ROS2D.ArrowShape({ size : robotSize, strokeSize : 1, strokeColor : robotColor, fillColor : robotColor, pulse : true }); } this.robotMarker.visible = false; this.rootObject.addChild(this.robotMarker); this.initScaleSet = false; // setup a listener for the robot pose var poseListener = new ROSLIB.Topic({ ros : ros, name : poseTopic, messageType : 'geometry_msgs/Pose', throttle_rate : 100 }); poseListener.subscribe(this.updatePose.bind(this)); }; /** * Initialize scale, current scale will be used for the goal markers */ NAVIGATION2D.PoseAndTrace.prototype.initScale = function() { if (this.initScaleSet) { console.log('Warning: scale has already been initialized!'); // TODO: reinit } this.initScaleSet = true; this.robotMarker.scaleX = 1.0 / this.stage.scaleX; this.robotMarker.scaleY = 1.0 / this.stage.scaleY; this.trace.scaleX = 1.0 / this.stage.scaleX; this.trace.scaleY = 1.0 / this.stage.scaleY; }; /** * Update the robot's pose: move the robot marker and add to trace * * @param pose - the robot's pose (geometry_msgs/Pose) */ NAVIGATION2D.PoseAndTrace.prototype.updatePose = function(pose) { // update the robot's position and rotation on the map this.robotMarker.x = pose.position.x; this.robotMarker.y = -pose.position.y; this.robotMarker.rotation = this.stage.rosQuaternionToGlobalTheta(pose.orientation); if (this.initScaleSet) { this.robotMarker.visible = true; } // Draw trace if (this.withTrace === true && this.initScaleSet === true) { this.trace.addPose(pose); this.trace.visible = true; } };
{ "content_hash": "3e37e477b1da0af938a72964d950c2b5", "timestamp": "", "source": "github", "line_count": 362, "max_line_length": 119, "avg_line_length": 29.248618784530386, "alnum_prop": 0.6997544389875331, "repo_name": "dobots/navigation_2d_js", "id": "fdf3d70e59a944dddadeaf0f906edd9813ad8f43", "size": "10588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/navigation_2d.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7755" }, { "name": "JavaScript", "bytes": "549982" } ], "symlink_target": "" }
#include "testhlp.h" #include <libcpphaggle/Thread.h> #include "utils.h" #include <haggleutils.h> #include "Interface.h" using namespace haggle; /* This program tests refcounting */ static long pass_cppreference(const InterfaceRef &iface) { return iface.refcount(); } #if defined(OS_WINDOWS) int haggle_test_refcount(void) #else int main(int argc, char *argv[]) #endif { // Disable tracing trace_disable(true); print_over_test_str_nl(0, "Refcount test: "); try { bool success = true; bool tmp_succ; unsigned char mac[6] = { (unsigned char) RANDOM_INT(255), (unsigned char) RANDOM_INT(255), (unsigned char) RANDOM_INT(255), (unsigned char) RANDOM_INT(255), (unsigned char) RANDOM_INT(255), (unsigned char) RANDOM_INT(255) }; Interface *iface = new EthernetInterface(mac); try { { print_over_test_str(1, "Create and check refcount==0: "); InterfaceRef nullRef; tmp_succ = (!nullRef && nullRef.refcount() == 0); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Create and check refcount==1: "); InterfaceRef ifaceRef(iface); tmp_succ = (ifaceRef && ifaceRef.refcount() == 1); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Increase refcount with operator \'=\': "); { InterfaceRef ifaceRef2 = ifaceRef; tmp_succ = (ifaceRef2 && ifaceRef2.refcount() == 2 && ifaceRef.refcount() == 2); success &= tmp_succ; print_pass(tmp_succ); } print_over_test_str(1, "No refcount increase on passing C++ reference: "); long count = ifaceRef.refcount(); tmp_succ = (pass_cppreference(ifaceRef) == count); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Decrease refcount due to context: "); tmp_succ = (ifaceRef.refcount() == 1); success &= tmp_succ; print_pass(tmp_succ); } InterfaceRef ifaceRef = new EthernetInterface(mac); print_over_test_str(1, "Refcount==0 when NULL: "); tmp_succ &= (ifaceRef && ifaceRef.refcount() == 1); success &= tmp_succ; ifaceRef = NULL; tmp_succ &= (!ifaceRef && ifaceRef.refcount() == 0); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "No exception when refcounting object twice: "); iface = new EthernetInterface(mac); Interface *iface2 = iface; ifaceRef = InterfaceRef(iface); try { InterfaceRef ifaceRef = iface2; tmp_succ = true; } catch (Exception &) { tmp_succ = false; } success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Decrease/increase refcount on reassignment: "); InterfaceRef ifaceRef3 = new EthernetInterface(mac); InterfaceRef ifaceRef2 = ifaceRef; tmp_succ = (ifaceRef.refcount() == 2 && ifaceRef2.refcount() == 2 && ifaceRef3.refcount() == 1); ifaceRef2 = ifaceRef3; tmp_succ &= (ifaceRef.refcount() == 1 && ifaceRef2.refcount() == 2 && ifaceRef3.refcount() == 2); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Refcount on reassignment with derived reference: "); EthernetInterfaceRef ifaceRef4 = new EthernetInterface(mac); InterfaceRef ifaceRef5 = ifaceRef4; WiFiInterfaceRef ifaceRef6 = ifaceRef5; tmp_succ &= (ifaceRef4.refcount() == 3 && ifaceRef5.refcount() == 3 && ifaceRef6.refcount() == 3); ifaceRef6 = NULL; tmp_succ &= (ifaceRef4.refcount() == 2 && ifaceRef5.refcount() == 2); success &= tmp_succ; print_pass(tmp_succ); print_over_test_str(1, "Total: "); } catch(Exception &) { return 2; } return success ? 0 : 1; } catch(Exception &) { printf("**CRASH** "); return 1; } }
{ "content_hash": "fde4dbe95144a2d12a4b00e21c3a61f6", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 79, "avg_line_length": 23.77639751552795, "alnum_prop": 0.6115464994775339, "repo_name": "dmonakhov/haggle", "id": "3637a089b1294c1a5cf6671038835265380a7122", "size": "4439", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testsuite/test_libcpphaggle/refcount.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "293764" }, { "name": "C", "bytes": "24785933" }, { "name": "C#", "bytes": "273912" }, { "name": "C++", "bytes": "2045853" }, { "name": "Emacs Lisp", "bytes": "6023" }, { "name": "Java", "bytes": "120953" }, { "name": "JavaScript", "bytes": "30528" }, { "name": "Objective-C", "bytes": "45086" }, { "name": "Perl", "bytes": "1755512" }, { "name": "Prolog", "bytes": "29150" }, { "name": "Python", "bytes": "100993" }, { "name": "R", "bytes": "106436" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "474103" } ], "symlink_target": "" }
import datetime import decimal import uuid from functools import lru_cache from itertools import chain from django.conf import settings from django.core.exceptions import FieldError from django.db import DatabaseError, NotSupportedError, models from django.db.backends.base.operations import BaseDatabaseOperations from django.db.models.constants import OnConflict from django.db.models.expressions import Col from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.functional import cached_property class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "text" cast_data_types = { "DateField": "TEXT", "DateTimeField": "TEXT", } explain_prefix = "EXPLAIN QUERY PLAN" # List of datatypes to that cannot be extracted with JSON_EXTRACT() on # SQLite. Use JSON_TYPE() instead. jsonfield_datatype_values = frozenset(["null", "false", "true"]) def bulk_batch_size(self, fields, objs): """ SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of 999 variables per query. If there's only a single field to insert, the limit is 500 (SQLITE_MAX_COMPOUND_SELECT). """ if len(fields) == 1: return 500 elif len(fields) > 1: return self.connection.features.max_query_params // len(fields) else: return len(objs) def check_expression_support(self, expression): bad_fields = (models.DateField, models.DateTimeField, models.TimeField) bad_aggregates = (models.Sum, models.Avg, models.Variance, models.StdDev) if isinstance(expression, bad_aggregates): for expr in expression.get_source_expressions(): try: output_field = expr.output_field except (AttributeError, FieldError): # Not every subexpression has an output_field which is fine # to ignore. pass else: if isinstance(output_field, bad_fields): raise NotSupportedError( "You cannot use Sum, Avg, StdDev, and Variance " "aggregations on date/time fields in sqlite3 " "since date/time is saved as text." ) if ( isinstance(expression, models.Aggregate) and expression.distinct and len(expression.source_expressions) > 1 ): raise NotSupportedError( "SQLite doesn't support DISTINCT on aggregate functions " "accepting multiple arguments." ) def date_extract_sql(self, lookup_type, field_name): """ Support EXTRACT with a user-defined function django_date_extract() that's registered in connect(). Use single quotes because this is a string and could otherwise cause a collision with a field name. """ return "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name) def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the list of returned data. """ return cursor.fetchall() def format_for_duration_arithmetic(self, sql): """Do nothing since formatting is handled in the custom function.""" return sql def date_trunc_sql(self, lookup_type, field_name, tzname=None): return "django_date_trunc('%s', %s, %s, %s)" % ( lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname), ) def time_trunc_sql(self, lookup_type, field_name, tzname=None): return "django_time_trunc('%s', %s, %s, %s)" % ( lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname), ) def _convert_tznames_to_sql(self, tzname): if tzname and settings.USE_TZ: return "'%s'" % tzname, "'%s'" % self.connection.timezone_name return "NULL", "NULL" def datetime_cast_date_sql(self, field_name, tzname): return "django_datetime_cast_date(%s, %s, %s)" % ( field_name, *self._convert_tznames_to_sql(tzname), ) def datetime_cast_time_sql(self, field_name, tzname): return "django_datetime_cast_time(%s, %s, %s)" % ( field_name, *self._convert_tznames_to_sql(tzname), ) def datetime_extract_sql(self, lookup_type, field_name, tzname): return "django_datetime_extract('%s', %s, %s, %s)" % ( lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname), ) def datetime_trunc_sql(self, lookup_type, field_name, tzname): return "django_datetime_trunc('%s', %s, %s, %s)" % ( lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname), ) def time_extract_sql(self, lookup_type, field_name): return "django_time_extract('%s', %s)" % (lookup_type.lower(), field_name) def pk_default_value(self): return "NULL" def _quote_params_for_last_executed_query(self, params): """ Only for last_executed_query! Don't use this to execute SQL queries! """ # This function is limited both by SQLITE_LIMIT_VARIABLE_NUMBER (the # number of parameters, default = 999) and SQLITE_MAX_COLUMN (the # number of return values, default = 2000). Since Python's sqlite3 # module doesn't expose the get_limit() C API, assume the default # limits are in effect and split the work in batches if needed. BATCH_SIZE = 999 if len(params) > BATCH_SIZE: results = () for index in range(0, len(params), BATCH_SIZE): chunk = params[index : index + BATCH_SIZE] results += self._quote_params_for_last_executed_query(chunk) return results sql = "SELECT " + ", ".join(["QUOTE(?)"] * len(params)) # Bypass Django's wrappers and use the underlying sqlite3 connection # to avoid logging this query - it would trigger infinite recursion. cursor = self.connection.connection.cursor() # Native sqlite3 cursors cannot be used as context managers. try: return cursor.execute(sql, params).fetchone() finally: cursor.close() def last_executed_query(self, cursor, sql, params): # Python substitutes parameters in Modules/_sqlite/cursor.c with: # pysqlite_statement_bind_parameters( # self->statement, parameters, allow_8bit_chars # ); # Unfortunately there is no way to reach self->statement from Python, # so we quote and substitute parameters manually. if params: if isinstance(params, (list, tuple)): params = self._quote_params_for_last_executed_query(params) else: values = tuple(params.values()) values = self._quote_params_for_last_executed_query(values) params = dict(zip(params, values)) return sql % params # For consistency with SQLiteCursorWrapper.execute(), just return sql # when there are no parameters. See #13648 and #17158. else: return sql def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def no_limit_value(self): return -1 def __references_graph(self, table_name): query = """ WITH tables AS ( SELECT %s name UNION SELECT sqlite_master.name FROM sqlite_master JOIN tables ON (sql REGEXP %s || tables.name || %s) ) SELECT name FROM tables; """ params = ( table_name, r'(?i)\s+references\s+("|\')?', r'("|\')?\s*\(', ) with self.connection.cursor() as cursor: results = cursor.execute(query, params) return [row[0] for row in results.fetchall()] @cached_property def _references_graph(self): # 512 is large enough to fit the ~330 tables (as of this writing) in # Django's test suite. return lru_cache(maxsize=512)(self.__references_graph) def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if tables and allow_cascade: # Simulate TRUNCATE CASCADE by recursively collecting the tables # referencing the tables to be flushed. tables = set( chain.from_iterable(self._references_graph(table) for table in tables) ) sql = [ "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table)), ) for table in tables ] if reset_sequences: sequences = [{"table": table} for table in tables] sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql def sequence_reset_by_name_sql(self, style, sequences): if not sequences: return [] return [ "%s %s %s %s = 0 %s %s %s (%s);" % ( style.SQL_KEYWORD("UPDATE"), style.SQL_TABLE(self.quote_name("sqlite_sequence")), style.SQL_KEYWORD("SET"), style.SQL_FIELD(self.quote_name("seq")), style.SQL_KEYWORD("WHERE"), style.SQL_FIELD(self.quote_name("name")), style.SQL_KEYWORD("IN"), ", ".join( ["'%s'" % sequence_info["table"] for sequence_info in sequences] ), ), ] def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "SQLite backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): raise ValueError("SQLite backend does not support timezone-aware times.") return str(value) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "DateTimeField": converters.append(self.convert_datetimefield_value) elif internal_type == "DateField": converters.append(self.convert_datefield_value) elif internal_type == "TimeField": converters.append(self.convert_timefield_value) elif internal_type == "DecimalField": converters.append(self.get_decimalfield_converter(expression)) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) elif internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) return converters def convert_datetimefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.datetime): value = parse_datetime(value) if settings.USE_TZ and not timezone.is_aware(value): value = timezone.make_aware(value, self.connection.timezone) return value def convert_datefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.date): value = parse_date(value) return value def convert_timefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.time): value = parse_time(value) return value def get_decimalfield_converter(self, expression): # SQLite stores only 15 significant digits. Digits coming from # float inaccuracy must be removed. create_decimal = decimal.Context(prec=15).create_decimal_from_float if isinstance(expression, Col): quantize_value = decimal.Decimal(1).scaleb( -expression.output_field.decimal_places ) def converter(value, expression, connection): if value is not None: return create_decimal(value).quantize( quantize_value, context=expression.output_field.context ) else: def converter(value, expression, connection): if value is not None: return create_decimal(value) return converter def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def convert_booleanfield_value(self, value, expression, connection): return bool(value) if value in (1, 0) else value def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join(f"({sql})" for sql in placeholder_rows_sql) return f"VALUES {values_sql}" def combine_expression(self, connector, sub_expressions): # SQLite doesn't have a ^ operator, so use the user-defined POWER # function that's registered in connect(). if connector == "^": return "POWER(%s)" % ",".join(sub_expressions) elif connector == "#": return "BITXOR(%s)" % ",".join(sub_expressions) return super().combine_expression(connector, sub_expressions) def combine_duration_expression(self, connector, sub_expressions): if connector not in ["+", "-", "*", "/"]: raise DatabaseError("Invalid connector for timedelta: %s." % connector) fn_params = ["'%s'" % connector] + sub_expressions if len(fn_params) > 3: raise ValueError("Too many params for timedelta operations.") return "django_format_dtdelta(%s)" % ", ".join(fn_params) def integer_field_range(self, internal_type): # SQLite doesn't enforce any integer constraints return (None, None) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) if internal_type == "TimeField": return "django_time_diff(%s, %s)" % (lhs_sql, rhs_sql), params return "django_timestamp_diff(%s, %s)" % (lhs_sql, rhs_sql), params def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT OR IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def return_insert_columns(self, fields): # SQLite < 3.35 doesn't support an INSERT...RETURNING statement. if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if ( on_conflict == OnConflict.UPDATE and self.connection.features.supports_update_conflicts_with_target ): return "ON CONFLICT(%s) DO UPDATE SET %s" % ( ", ".join(map(self.quote_name, unique_fields)), ", ".join( [ f"{field} = EXCLUDED.{field}" for field in map(self.quote_name, update_fields) ] ), ) return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
{ "content_hash": "1f88bdf59f612f53c123b9945245e625", "timestamp": "", "source": "github", "line_count": 436, "max_line_length": 88, "avg_line_length": 39.0848623853211, "alnum_prop": 0.5788979519981222, "repo_name": "auvipy/django", "id": "7c7cfce1ba045408aeb698f040928a0fc8b46e84", "size": "17041", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "django/db/backends/sqlite3/operations.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "87610" }, { "name": "HTML", "bytes": "236871" }, { "name": "JavaScript", "bytes": "146241" }, { "name": "Makefile", "bytes": "125" }, { "name": "Procfile", "bytes": "47" }, { "name": "Python", "bytes": "16014747" }, { "name": "Shell", "bytes": "809" }, { "name": "Smarty", "bytes": "392" } ], "symlink_target": "" }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.displayvideo.v1.model; /** * Creatives related settings of an advertiser. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Display & Video 360 API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class AdvertiserCreativeConfig extends com.google.api.client.json.GenericJson { /** * Whether or not the advertiser is enabled for dynamic creatives. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean dynamicCreativeEnabled; /** * An ID for configuring campaign monitoring provided by Integral Ad Service (IAS). The DV360 * system will append an IAS "Campaign Monitor" tag containing this ID to the creative tag. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long iasClientId; /** * Whether or not to use DV360's Online Behavioral Advertising (OBA) compliance. Warning: Changing * OBA settings may cause the audit status of your creatives to be reset by some ad exchanges, * making them ineligible to serve until they are re-approved. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean obaComplianceDisabled; /** * By setting this field to `true`, you, on behalf of your company, authorize Google to use video * creatives associated with this Display & Video 360 advertiser to provide reporting and features * related to the advertiser's television campaigns. Applicable only when the advertiser has a * CM360 hybrid ad server configuration. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean videoCreativeDataSharingAuthorized; /** * Whether or not the advertiser is enabled for dynamic creatives. * @return value or {@code null} for none */ public java.lang.Boolean getDynamicCreativeEnabled() { return dynamicCreativeEnabled; } /** * Whether or not the advertiser is enabled for dynamic creatives. * @param dynamicCreativeEnabled dynamicCreativeEnabled or {@code null} for none */ public AdvertiserCreativeConfig setDynamicCreativeEnabled(java.lang.Boolean dynamicCreativeEnabled) { this.dynamicCreativeEnabled = dynamicCreativeEnabled; return this; } /** * An ID for configuring campaign monitoring provided by Integral Ad Service (IAS). The DV360 * system will append an IAS "Campaign Monitor" tag containing this ID to the creative tag. * @return value or {@code null} for none */ public java.lang.Long getIasClientId() { return iasClientId; } /** * An ID for configuring campaign monitoring provided by Integral Ad Service (IAS). The DV360 * system will append an IAS "Campaign Monitor" tag containing this ID to the creative tag. * @param iasClientId iasClientId or {@code null} for none */ public AdvertiserCreativeConfig setIasClientId(java.lang.Long iasClientId) { this.iasClientId = iasClientId; return this; } /** * Whether or not to use DV360's Online Behavioral Advertising (OBA) compliance. Warning: Changing * OBA settings may cause the audit status of your creatives to be reset by some ad exchanges, * making them ineligible to serve until they are re-approved. * @return value or {@code null} for none */ public java.lang.Boolean getObaComplianceDisabled() { return obaComplianceDisabled; } /** * Whether or not to use DV360's Online Behavioral Advertising (OBA) compliance. Warning: Changing * OBA settings may cause the audit status of your creatives to be reset by some ad exchanges, * making them ineligible to serve until they are re-approved. * @param obaComplianceDisabled obaComplianceDisabled or {@code null} for none */ public AdvertiserCreativeConfig setObaComplianceDisabled(java.lang.Boolean obaComplianceDisabled) { this.obaComplianceDisabled = obaComplianceDisabled; return this; } /** * By setting this field to `true`, you, on behalf of your company, authorize Google to use video * creatives associated with this Display & Video 360 advertiser to provide reporting and features * related to the advertiser's television campaigns. Applicable only when the advertiser has a * CM360 hybrid ad server configuration. * @return value or {@code null} for none */ public java.lang.Boolean getVideoCreativeDataSharingAuthorized() { return videoCreativeDataSharingAuthorized; } /** * By setting this field to `true`, you, on behalf of your company, authorize Google to use video * creatives associated with this Display & Video 360 advertiser to provide reporting and features * related to the advertiser's television campaigns. Applicable only when the advertiser has a * CM360 hybrid ad server configuration. * @param videoCreativeDataSharingAuthorized videoCreativeDataSharingAuthorized or {@code null} for none */ public AdvertiserCreativeConfig setVideoCreativeDataSharingAuthorized(java.lang.Boolean videoCreativeDataSharingAuthorized) { this.videoCreativeDataSharingAuthorized = videoCreativeDataSharingAuthorized; return this; } @Override public AdvertiserCreativeConfig set(String fieldName, Object value) { return (AdvertiserCreativeConfig) super.set(fieldName, value); } @Override public AdvertiserCreativeConfig clone() { return (AdvertiserCreativeConfig) super.clone(); } }
{ "content_hash": "f5d9466152775e4487d3133a943f42b4", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 182, "avg_line_length": 41.42675159235669, "alnum_prop": 0.746309963099631, "repo_name": "googleapis/google-api-java-client-services", "id": "d47ad01a971fa6aa72df9ce08427b8f2b0fa6c06", "size": "6504", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "clients/google-api-services-displayvideo/v1/1.31.0/com/google/api/services/displayvideo/v1/model/AdvertiserCreativeConfig.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>area</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry"> <link rel="up" href="../algorithms.html" title="Algorithms"> <link rel="prev" href="../algorithms.html" title="Algorithms"> <link rel="next" href="area/area_1.html" title="area"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../algorithms.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../algorithms.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="area/area_1.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.algorithms.area"></a><a class="link" href="area.html" title="area">area</a> </h4></div></div></div> <div class="toc"><dl> <dt><span class="section"><a href="area/area_1.html">area</a></span></dt> <dt><span class="section"><a href="area/area_2_with_strategy.html">area (with strategy)</a></span></dt> </dl></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2012 Barend Gehrels, Bruno Lalande, Mateusz Loskot<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../algorithms.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../algorithms.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="area/area_1.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "507be1c2d3f15d56f2e56e8be7c747eb", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 451, "avg_line_length": 63.734693877551024, "alnum_prop": 0.5994236311239193, "repo_name": "hand-iemura/lightpng", "id": "5b21395548b1938c593b45df78ac1d3e26fa3878", "size": "3123", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "boost_1_53_0/libs/geometry/doc/html/geometry/reference/algorithms/area.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "139512" }, { "name": "Batchfile", "bytes": "43970" }, { "name": "C", "bytes": "2306793" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "139009726" }, { "name": "CMake", "bytes": "1741" }, { "name": "CSS", "bytes": "309758" }, { "name": "Cuda", "bytes": "26749" }, { "name": "FORTRAN", "bytes": "1387" }, { "name": "Groff", "bytes": "8039" }, { "name": "HTML", "bytes": "139153356" }, { "name": "IDL", "bytes": "14" }, { "name": "JavaScript", "bytes": "132031" }, { "name": "Lex", "bytes": "1255" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1074346" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "3745" }, { "name": "PHP", "bytes": "59030" }, { "name": "Perl", "bytes": "29502" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1710815" }, { "name": "QML", "bytes": "593" }, { "name": "Rebol", "bytes": "354" }, { "name": "Shell", "bytes": "376263" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "13404" }, { "name": "XSLT", "bytes": "761090" }, { "name": "Yacc", "bytes": "18910" } ], "symlink_target": "" }